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 cominber 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 cominber 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::getAllOnesValue(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::getAllOnesValue(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); 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 519 SDValue visitFADDForFMACombine(SDNode *N); 520 SDValue visitFSUBForFMACombine(SDNode *N); 521 SDValue visitFMULForFMADistributiveCombine(SDNode *N); 522 523 SDValue XformToShuffleWithZero(SDNode *N); 524 bool reassociationCanBreakAddressingModePattern(unsigned Opc, 525 const SDLoc &DL, SDValue N0, 526 SDValue N1); 527 SDValue reassociateOpsCommutative(unsigned Opc, const SDLoc &DL, SDValue N0, 528 SDValue N1); 529 SDValue reassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, 530 SDValue N1, SDNodeFlags Flags); 531 532 SDValue visitShiftByConstant(SDNode *N); 533 534 SDValue foldSelectOfConstants(SDNode *N); 535 SDValue foldVSelectOfConstants(SDNode *N); 536 SDValue foldBinOpIntoSelect(SDNode *BO); 537 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 538 SDValue hoistLogicOpWithSameOpcodeHands(SDNode *N); 539 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2); 540 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 541 SDValue N2, SDValue N3, ISD::CondCode CC, 542 bool NotExtCompare = false); 543 SDValue convertSelectOfFPConstantsToLoadOffset( 544 const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2, SDValue N3, 545 ISD::CondCode CC); 546 SDValue foldSignChangeInBitcast(SDNode *N); 547 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1, 548 SDValue N2, SDValue N3, ISD::CondCode CC); 549 SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, 550 const SDLoc &DL); 551 SDValue foldSubToUSubSat(EVT DstVT, SDNode *N); 552 SDValue unfoldMaskedMerge(SDNode *N); 553 SDValue unfoldExtremeBitClearingToShifts(SDNode *N); 554 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 555 const SDLoc &DL, bool foldBooleans); 556 SDValue rebuildSetCC(SDValue N); 557 558 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 559 SDValue &CC, bool MatchStrict = false) const; 560 bool isOneUseSetCC(SDValue N) const; 561 562 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 563 unsigned HiOp); 564 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 565 SDValue CombineExtLoad(SDNode *N); 566 SDValue CombineZExtLogicopShiftLoad(SDNode *N); 567 SDValue combineRepeatedFPDivisors(SDNode *N); 568 SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex); 569 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 570 SDValue BuildSDIV(SDNode *N); 571 SDValue BuildSDIVPow2(SDNode *N); 572 SDValue BuildUDIV(SDNode *N); 573 SDValue BuildLogBase2(SDValue V, const SDLoc &DL); 574 SDValue BuildDivEstimate(SDValue N, SDValue Op, SDNodeFlags Flags); 575 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags); 576 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags); 577 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip); 578 SDValue buildSqrtNROneConst(SDValue Arg, SDValue Est, unsigned Iterations, 579 SDNodeFlags Flags, bool Reciprocal); 580 SDValue buildSqrtNRTwoConst(SDValue Arg, SDValue Est, unsigned Iterations, 581 SDNodeFlags Flags, bool Reciprocal); 582 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 583 bool DemandHighBits = true); 584 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 585 SDValue MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 586 SDValue InnerPos, SDValue InnerNeg, 587 unsigned PosOpcode, unsigned NegOpcode, 588 const SDLoc &DL); 589 SDValue MatchFunnelPosNeg(SDValue N0, SDValue N1, SDValue Pos, SDValue Neg, 590 SDValue InnerPos, SDValue InnerNeg, 591 unsigned PosOpcode, unsigned NegOpcode, 592 const SDLoc &DL); 593 SDValue MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL); 594 SDValue MatchLoadCombine(SDNode *N); 595 SDValue mergeTruncStores(StoreSDNode *N); 596 SDValue ReduceLoadWidth(SDNode *N); 597 SDValue ReduceLoadOpStoreWidth(SDNode *N); 598 SDValue splitMergedValStore(StoreSDNode *ST); 599 SDValue TransformFPLoadStorePair(SDNode *N); 600 SDValue convertBuildVecZextToZext(SDNode *N); 601 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 602 SDValue reduceBuildVecTruncToBitCast(SDNode *N); 603 SDValue reduceBuildVecToShuffle(SDNode *N); 604 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N, 605 ArrayRef<int> VectorMask, SDValue VecIn1, 606 SDValue VecIn2, unsigned LeftIdx, 607 bool DidSplitVec); 608 SDValue matchVSelectOpSizesWithSetCC(SDNode *Cast); 609 610 /// Walk up chain skipping non-aliasing memory nodes, 611 /// looking for aliasing nodes and adding them to the Aliases vector. 612 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 613 SmallVectorImpl<SDValue> &Aliases); 614 615 /// Return true if there is any possibility that the two addresses overlap. 616 bool isAlias(SDNode *Op0, SDNode *Op1) const; 617 618 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 619 /// chain (aliasing node.) 620 SDValue FindBetterChain(SDNode *N, SDValue Chain); 621 622 /// Try to replace a store and any possibly adjacent stores on 623 /// consecutive chains with better chains. Return true only if St is 624 /// replaced. 625 /// 626 /// Notice that other chains may still be replaced even if the function 627 /// returns false. 628 bool findBetterNeighborChains(StoreSDNode *St); 629 630 // Helper for findBetterNeighborChains. Walk up store chain add additional 631 // chained stores that do not overlap and can be parallelized. 632 bool parallelizeChainedStores(StoreSDNode *St); 633 634 /// Holds a pointer to an LSBaseSDNode as well as information on where it 635 /// is located in a sequence of memory operations connected by a chain. 636 struct MemOpLink { 637 // Ptr to the mem node. 638 LSBaseSDNode *MemNode; 639 640 // Offset from the base ptr. 641 int64_t OffsetFromBase; 642 643 MemOpLink(LSBaseSDNode *N, int64_t Offset) 644 : MemNode(N), OffsetFromBase(Offset) {} 645 }; 646 647 // Classify the origin of a stored value. 648 enum class StoreSource { Unknown, Constant, Extract, Load }; 649 StoreSource getStoreSource(SDValue StoreVal) { 650 switch (StoreVal.getOpcode()) { 651 case ISD::Constant: 652 case ISD::ConstantFP: 653 return StoreSource::Constant; 654 case ISD::EXTRACT_VECTOR_ELT: 655 case ISD::EXTRACT_SUBVECTOR: 656 return StoreSource::Extract; 657 case ISD::LOAD: 658 return StoreSource::Load; 659 default: 660 return StoreSource::Unknown; 661 } 662 } 663 664 /// This is a helper function for visitMUL to check the profitability 665 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 666 /// MulNode is the original multiply, AddNode is (add x, c1), 667 /// and ConstNode is c2. 668 bool isMulAddWithConstProfitable(SDNode *MulNode, 669 SDValue &AddNode, 670 SDValue &ConstNode); 671 672 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns 673 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns 674 /// the type of the loaded value to be extended. 675 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 676 EVT LoadResultTy, EVT &ExtVT); 677 678 /// Helper function to calculate whether the given Load/Store can have its 679 /// width reduced to ExtVT. 680 bool isLegalNarrowLdSt(LSBaseSDNode *LDSTN, ISD::LoadExtType ExtType, 681 EVT &MemVT, unsigned ShAmt = 0); 682 683 /// Used by BackwardsPropagateMask to find suitable loads. 684 bool SearchForAndLoads(SDNode *N, SmallVectorImpl<LoadSDNode*> &Loads, 685 SmallPtrSetImpl<SDNode*> &NodesWithConsts, 686 ConstantSDNode *Mask, SDNode *&NodeToMask); 687 /// Attempt to propagate a given AND node back to load leaves so that they 688 /// can be combined into narrow loads. 689 bool BackwardsPropagateMask(SDNode *N); 690 691 /// Helper function for mergeConsecutiveStores which merges the component 692 /// store chains. 693 SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 694 unsigned NumStores); 695 696 /// This is a helper function for mergeConsecutiveStores. When the source 697 /// elements of the consecutive stores are all constants or all extracted 698 /// vector elements, try to merge them into one larger store introducing 699 /// bitcasts if necessary. \return True if a merged store was created. 700 bool mergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 701 EVT MemVT, unsigned NumStores, 702 bool IsConstantSrc, bool UseVector, 703 bool UseTrunc); 704 705 /// This is a helper function for mergeConsecutiveStores. Stores that 706 /// potentially may be merged with St are placed in StoreNodes. RootNode is 707 /// a chain predecessor to all store candidates. 708 void getStoreMergeCandidates(StoreSDNode *St, 709 SmallVectorImpl<MemOpLink> &StoreNodes, 710 SDNode *&Root); 711 712 /// Helper function for mergeConsecutiveStores. Checks if candidate stores 713 /// have indirect dependency through their operands. RootNode is the 714 /// predecessor to all stores calculated by getStoreMergeCandidates and is 715 /// used to prune the dependency check. \return True if safe to merge. 716 bool checkMergeStoreCandidatesForDependencies( 717 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores, 718 SDNode *RootNode); 719 720 /// This is a helper function for mergeConsecutiveStores. Given a list of 721 /// store candidates, find the first N that are consecutive in memory. 722 /// Returns 0 if there are not at least 2 consecutive stores to try merging. 723 unsigned getConsecutiveStores(SmallVectorImpl<MemOpLink> &StoreNodes, 724 int64_t ElementSizeBytes) const; 725 726 /// This is a helper function for mergeConsecutiveStores. It is used for 727 /// store chains that are composed entirely of constant values. 728 bool tryStoreMergeOfConstants(SmallVectorImpl<MemOpLink> &StoreNodes, 729 unsigned NumConsecutiveStores, 730 EVT MemVT, SDNode *Root, bool AllowVectors); 731 732 /// This is a helper function for mergeConsecutiveStores. It is used for 733 /// store chains that are composed entirely of extracted vector elements. 734 /// When extracting multiple vector elements, try to store them in one 735 /// vector store rather than a sequence of scalar stores. 736 bool tryStoreMergeOfExtracts(SmallVectorImpl<MemOpLink> &StoreNodes, 737 unsigned NumConsecutiveStores, EVT MemVT, 738 SDNode *Root); 739 740 /// This is a helper function for mergeConsecutiveStores. It is used for 741 /// store chains that are composed entirely of loaded values. 742 bool tryStoreMergeOfLoads(SmallVectorImpl<MemOpLink> &StoreNodes, 743 unsigned NumConsecutiveStores, EVT MemVT, 744 SDNode *Root, bool AllowVectors, 745 bool IsNonTemporalStore, bool IsNonTemporalLoad); 746 747 /// Merge consecutive store operations into a wide store. 748 /// This optimization uses wide integers or vectors when possible. 749 /// \return true if stores were merged. 750 bool mergeConsecutiveStores(StoreSDNode *St); 751 752 /// Try to transform a truncation where C is a constant: 753 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 754 /// 755 /// \p N needs to be a truncation and its first operand an AND. Other 756 /// requirements are checked by the function (e.g. that trunc is 757 /// single-use) and if missed an empty SDValue is returned. 758 SDValue distributeTruncateThroughAnd(SDNode *N); 759 760 /// Helper function to determine whether the target supports operation 761 /// given by \p Opcode for type \p VT, that is, whether the operation 762 /// is legal or custom before legalizing operations, and whether is 763 /// legal (but not custom) after legalization. 764 bool hasOperation(unsigned Opcode, EVT VT) { 765 return TLI.isOperationLegalOrCustom(Opcode, VT, LegalOperations); 766 } 767 768 public: 769 /// Runs the dag combiner on all nodes in the work list 770 void Run(CombineLevel AtLevel); 771 772 SelectionDAG &getDAG() const { return DAG; } 773 774 /// Returns a type large enough to hold any valid shift amount - before type 775 /// legalization these can be huge. 776 EVT getShiftAmountTy(EVT LHSTy) { 777 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 778 return TLI.getShiftAmountTy(LHSTy, DAG.getDataLayout(), LegalTypes); 779 } 780 781 /// This method returns true if we are running before type legalization or 782 /// if the specified VT is legal. 783 bool isTypeLegal(const EVT &VT) { 784 if (!LegalTypes) return true; 785 return TLI.isTypeLegal(VT); 786 } 787 788 /// Convenience wrapper around TargetLowering::getSetCCResultType 789 EVT getSetCCResultType(EVT VT) const { 790 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 791 } 792 793 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 794 SDValue OrigLoad, SDValue ExtLoad, 795 ISD::NodeType ExtType); 796 }; 797 798 /// This class is a DAGUpdateListener that removes any deleted 799 /// nodes from the worklist. 800 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 801 DAGCombiner &DC; 802 803 public: 804 explicit WorklistRemover(DAGCombiner &dc) 805 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 806 807 void NodeDeleted(SDNode *N, SDNode *E) override { 808 DC.removeFromWorklist(N); 809 } 810 }; 811 812 class WorklistInserter : public SelectionDAG::DAGUpdateListener { 813 DAGCombiner &DC; 814 815 public: 816 explicit WorklistInserter(DAGCombiner &dc) 817 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 818 819 // FIXME: Ideally we could add N to the worklist, but this causes exponential 820 // compile time costs in large DAGs, e.g. Halide. 821 void NodeInserted(SDNode *N) override { DC.ConsiderForPruning(N); } 822 }; 823 824 } // end anonymous namespace 825 826 //===----------------------------------------------------------------------===// 827 // TargetLowering::DAGCombinerInfo implementation 828 //===----------------------------------------------------------------------===// 829 830 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 831 ((DAGCombiner*)DC)->AddToWorklist(N); 832 } 833 834 SDValue TargetLowering::DAGCombinerInfo:: 835 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 836 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 837 } 838 839 SDValue TargetLowering::DAGCombinerInfo:: 840 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 841 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 842 } 843 844 SDValue TargetLowering::DAGCombinerInfo:: 845 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 846 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 847 } 848 849 bool TargetLowering::DAGCombinerInfo:: 850 recursivelyDeleteUnusedNodes(SDNode *N) { 851 return ((DAGCombiner*)DC)->recursivelyDeleteUnusedNodes(N); 852 } 853 854 void TargetLowering::DAGCombinerInfo:: 855 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 856 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 857 } 858 859 //===----------------------------------------------------------------------===// 860 // Helper Functions 861 //===----------------------------------------------------------------------===// 862 863 void DAGCombiner::deleteAndRecombine(SDNode *N) { 864 removeFromWorklist(N); 865 866 // If the operands of this node are only used by the node, they will now be 867 // dead. Make sure to re-visit them and recursively delete dead nodes. 868 for (const SDValue &Op : N->ops()) 869 // For an operand generating multiple values, one of the values may 870 // become dead allowing further simplification (e.g. split index 871 // arithmetic from an indexed load). 872 if (Op->hasOneUse() || Op->getNumValues() > 1) 873 AddToWorklist(Op.getNode()); 874 875 DAG.DeleteNode(N); 876 } 877 878 // APInts must be the same size for most operations, this helper 879 // function zero extends the shorter of the pair so that they match. 880 // We provide an Offset so that we can create bitwidths that won't overflow. 881 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) { 882 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth()); 883 LHS = LHS.zextOrSelf(Bits); 884 RHS = RHS.zextOrSelf(Bits); 885 } 886 887 // Return true if this node is a setcc, or is a select_cc 888 // that selects between the target values used for true and false, making it 889 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 890 // the appropriate nodes based on the type of node we are checking. This 891 // simplifies life a bit for the callers. 892 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 893 SDValue &CC, bool MatchStrict) const { 894 if (N.getOpcode() == ISD::SETCC) { 895 LHS = N.getOperand(0); 896 RHS = N.getOperand(1); 897 CC = N.getOperand(2); 898 return true; 899 } 900 901 if (MatchStrict && 902 (N.getOpcode() == ISD::STRICT_FSETCC || 903 N.getOpcode() == ISD::STRICT_FSETCCS)) { 904 LHS = N.getOperand(1); 905 RHS = N.getOperand(2); 906 CC = N.getOperand(3); 907 return true; 908 } 909 910 if (N.getOpcode() != ISD::SELECT_CC || 911 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 912 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 913 return false; 914 915 if (TLI.getBooleanContents(N.getValueType()) == 916 TargetLowering::UndefinedBooleanContent) 917 return false; 918 919 LHS = N.getOperand(0); 920 RHS = N.getOperand(1); 921 CC = N.getOperand(4); 922 return true; 923 } 924 925 /// Return true if this is a SetCC-equivalent operation with only one use. 926 /// If this is true, it allows the users to invert the operation for free when 927 /// it is profitable to do so. 928 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 929 SDValue N0, N1, N2; 930 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 931 return true; 932 return false; 933 } 934 935 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT ScalarTy) { 936 if (!ScalarTy.isSimple()) 937 return false; 938 939 uint64_t MaskForTy = 0ULL; 940 switch (ScalarTy.getSimpleVT().SimpleTy) { 941 case MVT::i8: 942 MaskForTy = 0xFFULL; 943 break; 944 case MVT::i16: 945 MaskForTy = 0xFFFFULL; 946 break; 947 case MVT::i32: 948 MaskForTy = 0xFFFFFFFFULL; 949 break; 950 default: 951 return false; 952 break; 953 } 954 955 APInt Val; 956 if (ISD::isConstantSplatVector(N, Val)) 957 return Val.getLimitedValue() == MaskForTy; 958 959 return false; 960 } 961 962 // Determines if it is a constant integer or a splat/build vector of constant 963 // integers (and undefs). 964 // Do not permit build vector implicit truncation. 965 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) { 966 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N)) 967 return !(Const->isOpaque() && NoOpaques); 968 if (N.getOpcode() != ISD::BUILD_VECTOR && N.getOpcode() != ISD::SPLAT_VECTOR) 969 return false; 970 unsigned BitWidth = N.getScalarValueSizeInBits(); 971 for (const SDValue &Op : N->op_values()) { 972 if (Op.isUndef()) 973 continue; 974 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op); 975 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth || 976 (Const->isOpaque() && NoOpaques)) 977 return false; 978 } 979 return true; 980 } 981 982 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with 983 // undef's. 984 static bool isAnyConstantBuildVector(SDValue V, bool NoOpaques = false) { 985 if (V.getOpcode() != ISD::BUILD_VECTOR) 986 return false; 987 return isConstantOrConstantVector(V, NoOpaques) || 988 ISD::isBuildVectorOfConstantFPSDNodes(V.getNode()); 989 } 990 991 // Determine if this an indexed load with an opaque target constant index. 992 static bool canSplitIdx(LoadSDNode *LD) { 993 return MaySplitLoadIndex && 994 (LD->getOperand(2).getOpcode() != ISD::TargetConstant || 995 !cast<ConstantSDNode>(LD->getOperand(2))->isOpaque()); 996 } 997 998 bool DAGCombiner::reassociationCanBreakAddressingModePattern(unsigned Opc, 999 const SDLoc &DL, 1000 SDValue N0, 1001 SDValue N1) { 1002 // Currently this only tries to ensure we don't undo the GEP splits done by 1003 // CodeGenPrepare when shouldConsiderGEPOffsetSplit is true. To ensure this, 1004 // we check if the following transformation would be problematic: 1005 // (load/store (add, (add, x, offset1), offset2)) -> 1006 // (load/store (add, x, offset1+offset2)). 1007 1008 if (Opc != ISD::ADD || N0.getOpcode() != ISD::ADD) 1009 return false; 1010 1011 if (N0.hasOneUse()) 1012 return false; 1013 1014 auto *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 1015 auto *C2 = dyn_cast<ConstantSDNode>(N1); 1016 if (!C1 || !C2) 1017 return false; 1018 1019 const APInt &C1APIntVal = C1->getAPIntValue(); 1020 const APInt &C2APIntVal = C2->getAPIntValue(); 1021 if (C1APIntVal.getBitWidth() > 64 || C2APIntVal.getBitWidth() > 64) 1022 return false; 1023 1024 const APInt CombinedValueIntVal = C1APIntVal + C2APIntVal; 1025 if (CombinedValueIntVal.getBitWidth() > 64) 1026 return false; 1027 const int64_t CombinedValue = CombinedValueIntVal.getSExtValue(); 1028 1029 for (SDNode *Node : N0->uses()) { 1030 auto LoadStore = dyn_cast<MemSDNode>(Node); 1031 if (LoadStore) { 1032 // Is x[offset2] already not a legal addressing mode? If so then 1033 // reassociating the constants breaks nothing (we test offset2 because 1034 // that's the one we hope to fold into the load or store). 1035 TargetLoweringBase::AddrMode AM; 1036 AM.HasBaseReg = true; 1037 AM.BaseOffs = C2APIntVal.getSExtValue(); 1038 EVT VT = LoadStore->getMemoryVT(); 1039 unsigned AS = LoadStore->getAddressSpace(); 1040 Type *AccessTy = VT.getTypeForEVT(*DAG.getContext()); 1041 if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS)) 1042 continue; 1043 1044 // Would x[offset1+offset2] still be a legal addressing mode? 1045 AM.BaseOffs = CombinedValue; 1046 if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS)) 1047 return true; 1048 } 1049 } 1050 1051 return false; 1052 } 1053 1054 // Helper for DAGCombiner::reassociateOps. Try to reassociate an expression 1055 // such as (Opc N0, N1), if \p N0 is the same kind of operation as \p Opc. 1056 SDValue DAGCombiner::reassociateOpsCommutative(unsigned Opc, const SDLoc &DL, 1057 SDValue N0, SDValue N1) { 1058 EVT VT = N0.getValueType(); 1059 1060 if (N0.getOpcode() != Opc) 1061 return SDValue(); 1062 1063 if (DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 1064 if (DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 1065 // Reassociate: (op (op x, c1), c2) -> (op x, (op c1, c2)) 1066 if (SDValue OpNode = 1067 DAG.FoldConstantArithmetic(Opc, DL, VT, {N0.getOperand(1), N1})) 1068 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 1069 return SDValue(); 1070 } 1071 if (N0.hasOneUse()) { 1072 // Reassociate: (op (op x, c1), y) -> (op (op x, y), c1) 1073 // iff (op x, c1) has one use 1074 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 1075 if (!OpNode.getNode()) 1076 return SDValue(); 1077 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 1078 } 1079 } 1080 return SDValue(); 1081 } 1082 1083 // Try to reassociate commutative binops. 1084 SDValue DAGCombiner::reassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, 1085 SDValue N1, SDNodeFlags Flags) { 1086 assert(TLI.isCommutativeBinOp(Opc) && "Operation not commutative."); 1087 1088 // Floating-point reassociation is not allowed without loose FP math. 1089 if (N0.getValueType().isFloatingPoint() || 1090 N1.getValueType().isFloatingPoint()) 1091 if (!Flags.hasAllowReassociation() || !Flags.hasNoSignedZeros()) 1092 return SDValue(); 1093 1094 if (SDValue Combined = reassociateOpsCommutative(Opc, DL, N0, N1)) 1095 return Combined; 1096 if (SDValue Combined = reassociateOpsCommutative(Opc, DL, N1, N0)) 1097 return Combined; 1098 return SDValue(); 1099 } 1100 1101 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 1102 bool AddTo) { 1103 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 1104 ++NodesCombined; 1105 LLVM_DEBUG(dbgs() << "\nReplacing.1 "; N->dump(&DAG); dbgs() << "\nWith: "; 1106 To[0].getNode()->dump(&DAG); 1107 dbgs() << " and " << NumTo - 1 << " other values\n"); 1108 for (unsigned i = 0, e = NumTo; i != e; ++i) 1109 assert((!To[i].getNode() || 1110 N->getValueType(i) == To[i].getValueType()) && 1111 "Cannot combine value to value of different type!"); 1112 1113 WorklistRemover DeadNodes(*this); 1114 DAG.ReplaceAllUsesWith(N, To); 1115 if (AddTo) { 1116 // Push the new nodes and any users onto the worklist 1117 for (unsigned i = 0, e = NumTo; i != e; ++i) { 1118 if (To[i].getNode()) { 1119 AddToWorklist(To[i].getNode()); 1120 AddUsersToWorklist(To[i].getNode()); 1121 } 1122 } 1123 } 1124 1125 // Finally, if the node is now dead, remove it from the graph. The node 1126 // may not be dead if the replacement process recursively simplified to 1127 // something else needing this node. 1128 if (N->use_empty()) 1129 deleteAndRecombine(N); 1130 return SDValue(N, 0); 1131 } 1132 1133 void DAGCombiner:: 1134 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 1135 // Replace the old value with the new one. 1136 ++NodesCombined; 1137 LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG); 1138 dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG); 1139 dbgs() << '\n'); 1140 1141 // Replace all uses. If any nodes become isomorphic to other nodes and 1142 // are deleted, make sure to remove them from our worklist. 1143 WorklistRemover DeadNodes(*this); 1144 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 1145 1146 // Push the new node and any (possibly new) users onto the worklist. 1147 AddToWorklistWithUsers(TLO.New.getNode()); 1148 1149 // Finally, if the node is now dead, remove it from the graph. The node 1150 // may not be dead if the replacement process recursively simplified to 1151 // something else needing this node. 1152 if (TLO.Old.getNode()->use_empty()) 1153 deleteAndRecombine(TLO.Old.getNode()); 1154 } 1155 1156 /// Check the specified integer node value to see if it can be simplified or if 1157 /// things it uses can be simplified by bit propagation. If so, return true. 1158 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 1159 const APInt &DemandedElts, 1160 bool AssumeSingleUse) { 1161 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 1162 KnownBits Known; 1163 if (!TLI.SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, 0, 1164 AssumeSingleUse)) 1165 return false; 1166 1167 // Revisit the node. 1168 AddToWorklist(Op.getNode()); 1169 1170 CommitTargetLoweringOpt(TLO); 1171 return true; 1172 } 1173 1174 /// Check the specified vector node value to see if it can be simplified or 1175 /// if things it uses can be simplified as it only uses some of the elements. 1176 /// If so, return true. 1177 bool DAGCombiner::SimplifyDemandedVectorElts(SDValue Op, 1178 const APInt &DemandedElts, 1179 bool AssumeSingleUse) { 1180 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 1181 APInt KnownUndef, KnownZero; 1182 if (!TLI.SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, 1183 TLO, 0, AssumeSingleUse)) 1184 return false; 1185 1186 // Revisit the node. 1187 AddToWorklist(Op.getNode()); 1188 1189 CommitTargetLoweringOpt(TLO); 1190 return true; 1191 } 1192 1193 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 1194 SDLoc DL(Load); 1195 EVT VT = Load->getValueType(0); 1196 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0)); 1197 1198 LLVM_DEBUG(dbgs() << "\nReplacing.9 "; Load->dump(&DAG); dbgs() << "\nWith: "; 1199 Trunc.getNode()->dump(&DAG); dbgs() << '\n'); 1200 WorklistRemover DeadNodes(*this); 1201 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 1202 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 1203 deleteAndRecombine(Load); 1204 AddToWorklist(Trunc.getNode()); 1205 } 1206 1207 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 1208 Replace = false; 1209 SDLoc DL(Op); 1210 if (ISD::isUNINDEXEDLoad(Op.getNode())) { 1211 LoadSDNode *LD = cast<LoadSDNode>(Op); 1212 EVT MemVT = LD->getMemoryVT(); 1213 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD 1214 : LD->getExtensionType(); 1215 Replace = true; 1216 return DAG.getExtLoad(ExtType, DL, PVT, 1217 LD->getChain(), LD->getBasePtr(), 1218 MemVT, LD->getMemOperand()); 1219 } 1220 1221 unsigned Opc = Op.getOpcode(); 1222 switch (Opc) { 1223 default: break; 1224 case ISD::AssertSext: 1225 if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT)) 1226 return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1)); 1227 break; 1228 case ISD::AssertZext: 1229 if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT)) 1230 return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1)); 1231 break; 1232 case ISD::Constant: { 1233 unsigned ExtOpc = 1234 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 1235 return DAG.getNode(ExtOpc, DL, PVT, Op); 1236 } 1237 } 1238 1239 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 1240 return SDValue(); 1241 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op); 1242 } 1243 1244 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 1245 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 1246 return SDValue(); 1247 EVT OldVT = Op.getValueType(); 1248 SDLoc DL(Op); 1249 bool Replace = false; 1250 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1251 if (!NewOp.getNode()) 1252 return SDValue(); 1253 AddToWorklist(NewOp.getNode()); 1254 1255 if (Replace) 1256 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1257 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp, 1258 DAG.getValueType(OldVT)); 1259 } 1260 1261 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1262 EVT OldVT = Op.getValueType(); 1263 SDLoc DL(Op); 1264 bool Replace = false; 1265 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1266 if (!NewOp.getNode()) 1267 return SDValue(); 1268 AddToWorklist(NewOp.getNode()); 1269 1270 if (Replace) 1271 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1272 return DAG.getZeroExtendInReg(NewOp, DL, OldVT); 1273 } 1274 1275 /// Promote the specified integer binary operation if the target indicates it is 1276 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1277 /// i32 since i16 instructions are longer. 1278 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1279 if (!LegalOperations) 1280 return SDValue(); 1281 1282 EVT VT = Op.getValueType(); 1283 if (VT.isVector() || !VT.isInteger()) 1284 return SDValue(); 1285 1286 // If operation type is 'undesirable', e.g. i16 on x86, consider 1287 // promoting it. 1288 unsigned Opc = Op.getOpcode(); 1289 if (TLI.isTypeDesirableForOp(Opc, VT)) 1290 return SDValue(); 1291 1292 EVT PVT = VT; 1293 // Consult target whether it is a good idea to promote this operation and 1294 // what's the right type to promote it to. 1295 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1296 assert(PVT != VT && "Don't know what type to promote to!"); 1297 1298 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1299 1300 bool Replace0 = false; 1301 SDValue N0 = Op.getOperand(0); 1302 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1303 1304 bool Replace1 = false; 1305 SDValue N1 = Op.getOperand(1); 1306 SDValue NN1 = PromoteOperand(N1, PVT, Replace1); 1307 SDLoc DL(Op); 1308 1309 SDValue RV = 1310 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1)); 1311 1312 // We are always replacing N0/N1's use in N and only need additional 1313 // replacements if there are additional uses. 1314 // Note: We are checking uses of the *nodes* (SDNode) rather than values 1315 // (SDValue) here because the node may reference multiple values 1316 // (for example, the chain value of a load node). 1317 Replace0 &= !N0->hasOneUse(); 1318 Replace1 &= (N0 != N1) && !N1->hasOneUse(); 1319 1320 // Combine Op here so it is preserved past replacements. 1321 CombineTo(Op.getNode(), RV); 1322 1323 // If operands have a use ordering, make sure we deal with 1324 // predecessor first. 1325 if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) { 1326 std::swap(N0, N1); 1327 std::swap(NN0, NN1); 1328 } 1329 1330 if (Replace0) { 1331 AddToWorklist(NN0.getNode()); 1332 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1333 } 1334 if (Replace1) { 1335 AddToWorklist(NN1.getNode()); 1336 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1337 } 1338 return Op; 1339 } 1340 return SDValue(); 1341 } 1342 1343 /// Promote the specified integer shift operation if the target indicates it is 1344 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1345 /// i32 since i16 instructions are longer. 1346 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1347 if (!LegalOperations) 1348 return SDValue(); 1349 1350 EVT VT = Op.getValueType(); 1351 if (VT.isVector() || !VT.isInteger()) 1352 return SDValue(); 1353 1354 // If operation type is 'undesirable', e.g. i16 on x86, consider 1355 // promoting it. 1356 unsigned Opc = Op.getOpcode(); 1357 if (TLI.isTypeDesirableForOp(Opc, VT)) 1358 return SDValue(); 1359 1360 EVT PVT = VT; 1361 // Consult target whether it is a good idea to promote this operation and 1362 // what's the right type to promote it to. 1363 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1364 assert(PVT != VT && "Don't know what type to promote to!"); 1365 1366 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1367 1368 bool Replace = false; 1369 SDValue N0 = Op.getOperand(0); 1370 SDValue N1 = Op.getOperand(1); 1371 if (Opc == ISD::SRA) 1372 N0 = SExtPromoteOperand(N0, PVT); 1373 else if (Opc == ISD::SRL) 1374 N0 = ZExtPromoteOperand(N0, PVT); 1375 else 1376 N0 = PromoteOperand(N0, PVT, Replace); 1377 1378 if (!N0.getNode()) 1379 return SDValue(); 1380 1381 SDLoc DL(Op); 1382 SDValue RV = 1383 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1)); 1384 1385 if (Replace) 1386 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1387 1388 // Deal with Op being deleted. 1389 if (Op && Op.getOpcode() != ISD::DELETED_NODE) 1390 return RV; 1391 } 1392 return SDValue(); 1393 } 1394 1395 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1396 if (!LegalOperations) 1397 return SDValue(); 1398 1399 EVT VT = Op.getValueType(); 1400 if (VT.isVector() || !VT.isInteger()) 1401 return SDValue(); 1402 1403 // If operation type is 'undesirable', e.g. i16 on x86, consider 1404 // promoting it. 1405 unsigned Opc = Op.getOpcode(); 1406 if (TLI.isTypeDesirableForOp(Opc, VT)) 1407 return SDValue(); 1408 1409 EVT PVT = VT; 1410 // Consult target whether it is a good idea to promote this operation and 1411 // what's the right type to promote it to. 1412 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1413 assert(PVT != VT && "Don't know what type to promote to!"); 1414 // fold (aext (aext x)) -> (aext x) 1415 // fold (aext (zext x)) -> (zext x) 1416 // fold (aext (sext x)) -> (sext x) 1417 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1418 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1419 } 1420 return SDValue(); 1421 } 1422 1423 bool DAGCombiner::PromoteLoad(SDValue Op) { 1424 if (!LegalOperations) 1425 return false; 1426 1427 if (!ISD::isUNINDEXEDLoad(Op.getNode())) 1428 return false; 1429 1430 EVT VT = Op.getValueType(); 1431 if (VT.isVector() || !VT.isInteger()) 1432 return false; 1433 1434 // If operation type is 'undesirable', e.g. i16 on x86, consider 1435 // promoting it. 1436 unsigned Opc = Op.getOpcode(); 1437 if (TLI.isTypeDesirableForOp(Opc, VT)) 1438 return false; 1439 1440 EVT PVT = VT; 1441 // Consult target whether it is a good idea to promote this operation and 1442 // what's the right type to promote it to. 1443 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1444 assert(PVT != VT && "Don't know what type to promote to!"); 1445 1446 SDLoc DL(Op); 1447 SDNode *N = Op.getNode(); 1448 LoadSDNode *LD = cast<LoadSDNode>(N); 1449 EVT MemVT = LD->getMemoryVT(); 1450 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD 1451 : LD->getExtensionType(); 1452 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT, 1453 LD->getChain(), LD->getBasePtr(), 1454 MemVT, LD->getMemOperand()); 1455 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD); 1456 1457 LLVM_DEBUG(dbgs() << "\nPromoting "; N->dump(&DAG); dbgs() << "\nTo: "; 1458 Result.getNode()->dump(&DAG); dbgs() << '\n'); 1459 WorklistRemover DeadNodes(*this); 1460 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1461 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1462 deleteAndRecombine(N); 1463 AddToWorklist(Result.getNode()); 1464 return true; 1465 } 1466 return false; 1467 } 1468 1469 /// Recursively delete a node which has no uses and any operands for 1470 /// which it is the only use. 1471 /// 1472 /// Note that this both deletes the nodes and removes them from the worklist. 1473 /// It also adds any nodes who have had a user deleted to the worklist as they 1474 /// may now have only one use and subject to other combines. 1475 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1476 if (!N->use_empty()) 1477 return false; 1478 1479 SmallSetVector<SDNode *, 16> Nodes; 1480 Nodes.insert(N); 1481 do { 1482 N = Nodes.pop_back_val(); 1483 if (!N) 1484 continue; 1485 1486 if (N->use_empty()) { 1487 for (const SDValue &ChildN : N->op_values()) 1488 Nodes.insert(ChildN.getNode()); 1489 1490 removeFromWorklist(N); 1491 DAG.DeleteNode(N); 1492 } else { 1493 AddToWorklist(N); 1494 } 1495 } while (!Nodes.empty()); 1496 return true; 1497 } 1498 1499 //===----------------------------------------------------------------------===// 1500 // Main DAG Combiner implementation 1501 //===----------------------------------------------------------------------===// 1502 1503 void DAGCombiner::Run(CombineLevel AtLevel) { 1504 // set the instance variables, so that the various visit routines may use it. 1505 Level = AtLevel; 1506 LegalDAG = Level >= AfterLegalizeDAG; 1507 LegalOperations = Level >= AfterLegalizeVectorOps; 1508 LegalTypes = Level >= AfterLegalizeTypes; 1509 1510 WorklistInserter AddNodes(*this); 1511 1512 // Add all the dag nodes to the worklist. 1513 for (SDNode &Node : DAG.allnodes()) 1514 AddToWorklist(&Node); 1515 1516 // Create a dummy node (which is not added to allnodes), that adds a reference 1517 // to the root node, preventing it from being deleted, and tracking any 1518 // changes of the root. 1519 HandleSDNode Dummy(DAG.getRoot()); 1520 1521 // While we have a valid worklist entry node, try to combine it. 1522 while (SDNode *N = getNextWorklistEntry()) { 1523 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1524 // N is deleted from the DAG, since they too may now be dead or may have a 1525 // reduced number of uses, allowing other xforms. 1526 if (recursivelyDeleteUnusedNodes(N)) 1527 continue; 1528 1529 WorklistRemover DeadNodes(*this); 1530 1531 // If this combine is running after legalizing the DAG, re-legalize any 1532 // nodes pulled off the worklist. 1533 if (LegalDAG) { 1534 SmallSetVector<SDNode *, 16> UpdatedNodes; 1535 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1536 1537 for (SDNode *LN : UpdatedNodes) 1538 AddToWorklistWithUsers(LN); 1539 1540 if (!NIsValid) 1541 continue; 1542 } 1543 1544 LLVM_DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1545 1546 // Add any operands of the new node which have not yet been combined to the 1547 // worklist as well. Because the worklist uniques things already, this 1548 // won't repeatedly process the same operand. 1549 CombinedNodes.insert(N); 1550 for (const SDValue &ChildN : N->op_values()) 1551 if (!CombinedNodes.count(ChildN.getNode())) 1552 AddToWorklist(ChildN.getNode()); 1553 1554 SDValue RV = combine(N); 1555 1556 if (!RV.getNode()) 1557 continue; 1558 1559 ++NodesCombined; 1560 1561 // If we get back the same node we passed in, rather than a new node or 1562 // zero, we know that the node must have defined multiple values and 1563 // CombineTo was used. Since CombineTo takes care of the worklist 1564 // mechanics for us, we have no work to do in this case. 1565 if (RV.getNode() == N) 1566 continue; 1567 1568 assert(N->getOpcode() != ISD::DELETED_NODE && 1569 RV.getOpcode() != ISD::DELETED_NODE && 1570 "Node was deleted but visit returned new node!"); 1571 1572 LLVM_DEBUG(dbgs() << " ... into: "; RV.getNode()->dump(&DAG)); 1573 1574 if (N->getNumValues() == RV.getNode()->getNumValues()) 1575 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1576 else { 1577 assert(N->getValueType(0) == RV.getValueType() && 1578 N->getNumValues() == 1 && "Type mismatch"); 1579 DAG.ReplaceAllUsesWith(N, &RV); 1580 } 1581 1582 // Push the new node and any users onto the worklist. Omit this if the 1583 // new node is the EntryToken (e.g. if a store managed to get optimized 1584 // out), because re-visiting the EntryToken and its users will not uncover 1585 // any additional opportunities, but there may be a large number of such 1586 // users, potentially causing compile time explosion. 1587 if (RV.getOpcode() != ISD::EntryToken) { 1588 AddToWorklist(RV.getNode()); 1589 AddUsersToWorklist(RV.getNode()); 1590 } 1591 1592 // Finally, if the node is now dead, remove it from the graph. The node 1593 // may not be dead if the replacement process recursively simplified to 1594 // something else needing this node. This will also take care of adding any 1595 // operands which have lost a user to the worklist. 1596 recursivelyDeleteUnusedNodes(N); 1597 } 1598 1599 // If the root changed (e.g. it was a dead load, update the root). 1600 DAG.setRoot(Dummy.getValue()); 1601 DAG.RemoveDeadNodes(); 1602 } 1603 1604 SDValue DAGCombiner::visit(SDNode *N) { 1605 switch (N->getOpcode()) { 1606 default: break; 1607 case ISD::TokenFactor: return visitTokenFactor(N); 1608 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1609 case ISD::ADD: return visitADD(N); 1610 case ISD::SUB: return visitSUB(N); 1611 case ISD::SADDSAT: 1612 case ISD::UADDSAT: return visitADDSAT(N); 1613 case ISD::SSUBSAT: 1614 case ISD::USUBSAT: return visitSUBSAT(N); 1615 case ISD::ADDC: return visitADDC(N); 1616 case ISD::SADDO: 1617 case ISD::UADDO: return visitADDO(N); 1618 case ISD::SUBC: return visitSUBC(N); 1619 case ISD::SSUBO: 1620 case ISD::USUBO: return visitSUBO(N); 1621 case ISD::ADDE: return visitADDE(N); 1622 case ISD::ADDCARRY: return visitADDCARRY(N); 1623 case ISD::SADDO_CARRY: return visitSADDO_CARRY(N); 1624 case ISD::SUBE: return visitSUBE(N); 1625 case ISD::SUBCARRY: return visitSUBCARRY(N); 1626 case ISD::SSUBO_CARRY: return visitSSUBO_CARRY(N); 1627 case ISD::SMULFIX: 1628 case ISD::SMULFIXSAT: 1629 case ISD::UMULFIX: 1630 case ISD::UMULFIXSAT: return visitMULFIX(N); 1631 case ISD::MUL: return visitMUL(N); 1632 case ISD::SDIV: return visitSDIV(N); 1633 case ISD::UDIV: return visitUDIV(N); 1634 case ISD::SREM: 1635 case ISD::UREM: return visitREM(N); 1636 case ISD::MULHU: return visitMULHU(N); 1637 case ISD::MULHS: return visitMULHS(N); 1638 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1639 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1640 case ISD::SMULO: 1641 case ISD::UMULO: return visitMULO(N); 1642 case ISD::SMIN: 1643 case ISD::SMAX: 1644 case ISD::UMIN: 1645 case ISD::UMAX: return visitIMINMAX(N); 1646 case ISD::AND: return visitAND(N); 1647 case ISD::OR: return visitOR(N); 1648 case ISD::XOR: return visitXOR(N); 1649 case ISD::SHL: return visitSHL(N); 1650 case ISD::SRA: return visitSRA(N); 1651 case ISD::SRL: return visitSRL(N); 1652 case ISD::ROTR: 1653 case ISD::ROTL: return visitRotate(N); 1654 case ISD::FSHL: 1655 case ISD::FSHR: return visitFunnelShift(N); 1656 case ISD::ABS: return visitABS(N); 1657 case ISD::BSWAP: return visitBSWAP(N); 1658 case ISD::BITREVERSE: return visitBITREVERSE(N); 1659 case ISD::CTLZ: return visitCTLZ(N); 1660 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1661 case ISD::CTTZ: return visitCTTZ(N); 1662 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1663 case ISD::CTPOP: return visitCTPOP(N); 1664 case ISD::SELECT: return visitSELECT(N); 1665 case ISD::VSELECT: return visitVSELECT(N); 1666 case ISD::SELECT_CC: return visitSELECT_CC(N); 1667 case ISD::SETCC: return visitSETCC(N); 1668 case ISD::SETCCCARRY: return visitSETCCCARRY(N); 1669 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1670 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1671 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1672 case ISD::AssertSext: 1673 case ISD::AssertZext: return visitAssertExt(N); 1674 case ISD::AssertAlign: return visitAssertAlign(N); 1675 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1676 case ISD::SIGN_EXTEND_VECTOR_INREG: 1677 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitEXTEND_VECTOR_INREG(N); 1678 case ISD::TRUNCATE: return visitTRUNCATE(N); 1679 case ISD::BITCAST: return visitBITCAST(N); 1680 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1681 case ISD::FADD: return visitFADD(N); 1682 case ISD::STRICT_FADD: return visitSTRICT_FADD(N); 1683 case ISD::FSUB: return visitFSUB(N); 1684 case ISD::FMUL: return visitFMUL(N); 1685 case ISD::FMA: return visitFMA(N); 1686 case ISD::FDIV: return visitFDIV(N); 1687 case ISD::FREM: return visitFREM(N); 1688 case ISD::FSQRT: return visitFSQRT(N); 1689 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1690 case ISD::FPOW: return visitFPOW(N); 1691 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1692 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1693 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1694 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1695 case ISD::FP_ROUND: return visitFP_ROUND(N); 1696 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1697 case ISD::FNEG: return visitFNEG(N); 1698 case ISD::FABS: return visitFABS(N); 1699 case ISD::FFLOOR: return visitFFLOOR(N); 1700 case ISD::FMINNUM: return visitFMINNUM(N); 1701 case ISD::FMAXNUM: return visitFMAXNUM(N); 1702 case ISD::FMINIMUM: return visitFMINIMUM(N); 1703 case ISD::FMAXIMUM: return visitFMAXIMUM(N); 1704 case ISD::FCEIL: return visitFCEIL(N); 1705 case ISD::FTRUNC: return visitFTRUNC(N); 1706 case ISD::BRCOND: return visitBRCOND(N); 1707 case ISD::BR_CC: return visitBR_CC(N); 1708 case ISD::LOAD: return visitLOAD(N); 1709 case ISD::STORE: return visitSTORE(N); 1710 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1711 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1712 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1713 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1714 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1715 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1716 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1717 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1718 case ISD::MGATHER: return visitMGATHER(N); 1719 case ISD::MLOAD: return visitMLOAD(N); 1720 case ISD::MSCATTER: return visitMSCATTER(N); 1721 case ISD::MSTORE: return visitMSTORE(N); 1722 case ISD::LIFETIME_END: return visitLIFETIME_END(N); 1723 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1724 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1725 case ISD::FREEZE: return visitFREEZE(N); 1726 case ISD::VECREDUCE_FADD: 1727 case ISD::VECREDUCE_FMUL: 1728 case ISD::VECREDUCE_ADD: 1729 case ISD::VECREDUCE_MUL: 1730 case ISD::VECREDUCE_AND: 1731 case ISD::VECREDUCE_OR: 1732 case ISD::VECREDUCE_XOR: 1733 case ISD::VECREDUCE_SMAX: 1734 case ISD::VECREDUCE_SMIN: 1735 case ISD::VECREDUCE_UMAX: 1736 case ISD::VECREDUCE_UMIN: 1737 case ISD::VECREDUCE_FMAX: 1738 case ISD::VECREDUCE_FMIN: return visitVECREDUCE(N); 1739 } 1740 return SDValue(); 1741 } 1742 1743 SDValue DAGCombiner::combine(SDNode *N) { 1744 SDValue RV; 1745 if (!DisableGenericCombines) 1746 RV = visit(N); 1747 1748 // If nothing happened, try a target-specific DAG combine. 1749 if (!RV.getNode()) { 1750 assert(N->getOpcode() != ISD::DELETED_NODE && 1751 "Node was deleted but visit returned NULL!"); 1752 1753 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1754 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1755 1756 // Expose the DAG combiner to the target combiner impls. 1757 TargetLowering::DAGCombinerInfo 1758 DagCombineInfo(DAG, Level, false, this); 1759 1760 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1761 } 1762 } 1763 1764 // If nothing happened still, try promoting the operation. 1765 if (!RV.getNode()) { 1766 switch (N->getOpcode()) { 1767 default: break; 1768 case ISD::ADD: 1769 case ISD::SUB: 1770 case ISD::MUL: 1771 case ISD::AND: 1772 case ISD::OR: 1773 case ISD::XOR: 1774 RV = PromoteIntBinOp(SDValue(N, 0)); 1775 break; 1776 case ISD::SHL: 1777 case ISD::SRA: 1778 case ISD::SRL: 1779 RV = PromoteIntShiftOp(SDValue(N, 0)); 1780 break; 1781 case ISD::SIGN_EXTEND: 1782 case ISD::ZERO_EXTEND: 1783 case ISD::ANY_EXTEND: 1784 RV = PromoteExtend(SDValue(N, 0)); 1785 break; 1786 case ISD::LOAD: 1787 if (PromoteLoad(SDValue(N, 0))) 1788 RV = SDValue(N, 0); 1789 break; 1790 } 1791 } 1792 1793 // If N is a commutative binary node, try to eliminate it if the commuted 1794 // version is already present in the DAG. 1795 if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) && 1796 N->getNumValues() == 1) { 1797 SDValue N0 = N->getOperand(0); 1798 SDValue N1 = N->getOperand(1); 1799 1800 // Constant operands are canonicalized to RHS. 1801 if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) { 1802 SDValue Ops[] = {N1, N0}; 1803 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1804 N->getFlags()); 1805 if (CSENode) 1806 return SDValue(CSENode, 0); 1807 } 1808 } 1809 1810 return RV; 1811 } 1812 1813 /// Given a node, return its input chain if it has one, otherwise return a null 1814 /// sd operand. 1815 static SDValue getInputChainForNode(SDNode *N) { 1816 if (unsigned NumOps = N->getNumOperands()) { 1817 if (N->getOperand(0).getValueType() == MVT::Other) 1818 return N->getOperand(0); 1819 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1820 return N->getOperand(NumOps-1); 1821 for (unsigned i = 1; i < NumOps-1; ++i) 1822 if (N->getOperand(i).getValueType() == MVT::Other) 1823 return N->getOperand(i); 1824 } 1825 return SDValue(); 1826 } 1827 1828 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1829 // If N has two operands, where one has an input chain equal to the other, 1830 // the 'other' chain is redundant. 1831 if (N->getNumOperands() == 2) { 1832 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1833 return N->getOperand(0); 1834 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1835 return N->getOperand(1); 1836 } 1837 1838 // Don't simplify token factors if optnone. 1839 if (OptLevel == CodeGenOpt::None) 1840 return SDValue(); 1841 1842 // Don't simplify the token factor if the node itself has too many operands. 1843 if (N->getNumOperands() > TokenFactorInlineLimit) 1844 return SDValue(); 1845 1846 // If the sole user is a token factor, we should make sure we have a 1847 // chance to merge them together. This prevents TF chains from inhibiting 1848 // optimizations. 1849 if (N->hasOneUse() && N->use_begin()->getOpcode() == ISD::TokenFactor) 1850 AddToWorklist(*(N->use_begin())); 1851 1852 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1853 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1854 SmallPtrSet<SDNode*, 16> SeenOps; 1855 bool Changed = false; // If we should replace this token factor. 1856 1857 // Start out with this token factor. 1858 TFs.push_back(N); 1859 1860 // Iterate through token factors. The TFs grows when new token factors are 1861 // encountered. 1862 for (unsigned i = 0; i < TFs.size(); ++i) { 1863 // Limit number of nodes to inline, to avoid quadratic compile times. 1864 // We have to add the outstanding Token Factors to Ops, otherwise we might 1865 // drop Ops from the resulting Token Factors. 1866 if (Ops.size() > TokenFactorInlineLimit) { 1867 for (unsigned j = i; j < TFs.size(); j++) 1868 Ops.emplace_back(TFs[j], 0); 1869 // Drop unprocessed Token Factors from TFs, so we do not add them to the 1870 // combiner worklist later. 1871 TFs.resize(i); 1872 break; 1873 } 1874 1875 SDNode *TF = TFs[i]; 1876 // Check each of the operands. 1877 for (const SDValue &Op : TF->op_values()) { 1878 switch (Op.getOpcode()) { 1879 case ISD::EntryToken: 1880 // Entry tokens don't need to be added to the list. They are 1881 // redundant. 1882 Changed = true; 1883 break; 1884 1885 case ISD::TokenFactor: 1886 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) { 1887 // Queue up for processing. 1888 TFs.push_back(Op.getNode()); 1889 Changed = true; 1890 break; 1891 } 1892 LLVM_FALLTHROUGH; 1893 1894 default: 1895 // Only add if it isn't already in the list. 1896 if (SeenOps.insert(Op.getNode()).second) 1897 Ops.push_back(Op); 1898 else 1899 Changed = true; 1900 break; 1901 } 1902 } 1903 } 1904 1905 // Re-visit inlined Token Factors, to clean them up in case they have been 1906 // removed. Skip the first Token Factor, as this is the current node. 1907 for (unsigned i = 1, e = TFs.size(); i < e; i++) 1908 AddToWorklist(TFs[i]); 1909 1910 // Remove Nodes that are chained to another node in the list. Do so 1911 // by walking up chains breath-first stopping when we've seen 1912 // another operand. In general we must climb to the EntryNode, but we can exit 1913 // early if we find all remaining work is associated with just one operand as 1914 // no further pruning is possible. 1915 1916 // List of nodes to search through and original Ops from which they originate. 1917 SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist; 1918 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op. 1919 SmallPtrSet<SDNode *, 16> SeenChains; 1920 bool DidPruneOps = false; 1921 1922 unsigned NumLeftToConsider = 0; 1923 for (const SDValue &Op : Ops) { 1924 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++)); 1925 OpWorkCount.push_back(1); 1926 } 1927 1928 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) { 1929 // If this is an Op, we can remove the op from the list. Remark any 1930 // search associated with it as from the current OpNumber. 1931 if (SeenOps.contains(Op)) { 1932 Changed = true; 1933 DidPruneOps = true; 1934 unsigned OrigOpNumber = 0; 1935 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op) 1936 OrigOpNumber++; 1937 assert((OrigOpNumber != Ops.size()) && 1938 "expected to find TokenFactor Operand"); 1939 // Re-mark worklist from OrigOpNumber to OpNumber 1940 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) { 1941 if (Worklist[i].second == OrigOpNumber) { 1942 Worklist[i].second = OpNumber; 1943 } 1944 } 1945 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber]; 1946 OpWorkCount[OrigOpNumber] = 0; 1947 NumLeftToConsider--; 1948 } 1949 // Add if it's a new chain 1950 if (SeenChains.insert(Op).second) { 1951 OpWorkCount[OpNumber]++; 1952 Worklist.push_back(std::make_pair(Op, OpNumber)); 1953 } 1954 }; 1955 1956 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) { 1957 // We need at least be consider at least 2 Ops to prune. 1958 if (NumLeftToConsider <= 1) 1959 break; 1960 auto CurNode = Worklist[i].first; 1961 auto CurOpNumber = Worklist[i].second; 1962 assert((OpWorkCount[CurOpNumber] > 0) && 1963 "Node should not appear in worklist"); 1964 switch (CurNode->getOpcode()) { 1965 case ISD::EntryToken: 1966 // Hitting EntryToken is the only way for the search to terminate without 1967 // hitting 1968 // another operand's search. Prevent us from marking this operand 1969 // considered. 1970 NumLeftToConsider++; 1971 break; 1972 case ISD::TokenFactor: 1973 for (const SDValue &Op : CurNode->op_values()) 1974 AddToWorklist(i, Op.getNode(), CurOpNumber); 1975 break; 1976 case ISD::LIFETIME_START: 1977 case ISD::LIFETIME_END: 1978 case ISD::CopyFromReg: 1979 case ISD::CopyToReg: 1980 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber); 1981 break; 1982 default: 1983 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode)) 1984 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber); 1985 break; 1986 } 1987 OpWorkCount[CurOpNumber]--; 1988 if (OpWorkCount[CurOpNumber] == 0) 1989 NumLeftToConsider--; 1990 } 1991 1992 // If we've changed things around then replace token factor. 1993 if (Changed) { 1994 SDValue Result; 1995 if (Ops.empty()) { 1996 // The entry token is the only possible outcome. 1997 Result = DAG.getEntryNode(); 1998 } else { 1999 if (DidPruneOps) { 2000 SmallVector<SDValue, 8> PrunedOps; 2001 // 2002 for (const SDValue &Op : Ops) { 2003 if (SeenChains.count(Op.getNode()) == 0) 2004 PrunedOps.push_back(Op); 2005 } 2006 Result = DAG.getTokenFactor(SDLoc(N), PrunedOps); 2007 } else { 2008 Result = DAG.getTokenFactor(SDLoc(N), Ops); 2009 } 2010 } 2011 return Result; 2012 } 2013 return SDValue(); 2014 } 2015 2016 /// MERGE_VALUES can always be eliminated. 2017 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 2018 WorklistRemover DeadNodes(*this); 2019 // Replacing results may cause a different MERGE_VALUES to suddenly 2020 // be CSE'd with N, and carry its uses with it. Iterate until no 2021 // uses remain, to ensure that the node can be safely deleted. 2022 // First add the users of this node to the work list so that they 2023 // can be tried again once they have new operands. 2024 AddUsersToWorklist(N); 2025 do { 2026 // Do as a single replacement to avoid rewalking use lists. 2027 SmallVector<SDValue, 8> Ops; 2028 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 2029 Ops.push_back(N->getOperand(i)); 2030 DAG.ReplaceAllUsesWith(N, Ops.data()); 2031 } while (!N->use_empty()); 2032 deleteAndRecombine(N); 2033 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2034 } 2035 2036 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a 2037 /// ConstantSDNode pointer else nullptr. 2038 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 2039 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 2040 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 2041 } 2042 2043 /// Return true if 'Use' is a load or a store that uses N as its base pointer 2044 /// and that N may be folded in the load / store addressing mode. 2045 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, SelectionDAG &DAG, 2046 const TargetLowering &TLI) { 2047 EVT VT; 2048 unsigned AS; 2049 2050 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 2051 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 2052 return false; 2053 VT = LD->getMemoryVT(); 2054 AS = LD->getAddressSpace(); 2055 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 2056 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 2057 return false; 2058 VT = ST->getMemoryVT(); 2059 AS = ST->getAddressSpace(); 2060 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(Use)) { 2061 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 2062 return false; 2063 VT = LD->getMemoryVT(); 2064 AS = LD->getAddressSpace(); 2065 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(Use)) { 2066 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 2067 return false; 2068 VT = ST->getMemoryVT(); 2069 AS = ST->getAddressSpace(); 2070 } else 2071 return false; 2072 2073 TargetLowering::AddrMode AM; 2074 if (N->getOpcode() == ISD::ADD) { 2075 AM.HasBaseReg = true; 2076 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 2077 if (Offset) 2078 // [reg +/- imm] 2079 AM.BaseOffs = Offset->getSExtValue(); 2080 else 2081 // [reg +/- reg] 2082 AM.Scale = 1; 2083 } else if (N->getOpcode() == ISD::SUB) { 2084 AM.HasBaseReg = true; 2085 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 2086 if (Offset) 2087 // [reg +/- imm] 2088 AM.BaseOffs = -Offset->getSExtValue(); 2089 else 2090 // [reg +/- reg] 2091 AM.Scale = 1; 2092 } else 2093 return false; 2094 2095 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 2096 VT.getTypeForEVT(*DAG.getContext()), AS); 2097 } 2098 2099 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) { 2100 assert(TLI.isBinOp(BO->getOpcode()) && BO->getNumValues() == 1 && 2101 "Unexpected binary operator"); 2102 2103 // Don't do this unless the old select is going away. We want to eliminate the 2104 // binary operator, not replace a binop with a select. 2105 // TODO: Handle ISD::SELECT_CC. 2106 unsigned SelOpNo = 0; 2107 SDValue Sel = BO->getOperand(0); 2108 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) { 2109 SelOpNo = 1; 2110 Sel = BO->getOperand(1); 2111 } 2112 2113 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) 2114 return SDValue(); 2115 2116 SDValue CT = Sel.getOperand(1); 2117 if (!isConstantOrConstantVector(CT, true) && 2118 !DAG.isConstantFPBuildVectorOrConstantFP(CT)) 2119 return SDValue(); 2120 2121 SDValue CF = Sel.getOperand(2); 2122 if (!isConstantOrConstantVector(CF, true) && 2123 !DAG.isConstantFPBuildVectorOrConstantFP(CF)) 2124 return SDValue(); 2125 2126 // Bail out if any constants are opaque because we can't constant fold those. 2127 // The exception is "and" and "or" with either 0 or -1 in which case we can 2128 // propagate non constant operands into select. I.e.: 2129 // and (select Cond, 0, -1), X --> select Cond, 0, X 2130 // or X, (select Cond, -1, 0) --> select Cond, -1, X 2131 auto BinOpcode = BO->getOpcode(); 2132 bool CanFoldNonConst = 2133 (BinOpcode == ISD::AND || BinOpcode == ISD::OR) && 2134 (isNullOrNullSplat(CT) || isAllOnesOrAllOnesSplat(CT)) && 2135 (isNullOrNullSplat(CF) || isAllOnesOrAllOnesSplat(CF)); 2136 2137 SDValue CBO = BO->getOperand(SelOpNo ^ 1); 2138 if (!CanFoldNonConst && 2139 !isConstantOrConstantVector(CBO, true) && 2140 !DAG.isConstantFPBuildVectorOrConstantFP(CBO)) 2141 return SDValue(); 2142 2143 EVT VT = BO->getValueType(0); 2144 2145 // We have a select-of-constants followed by a binary operator with a 2146 // constant. Eliminate the binop by pulling the constant math into the select. 2147 // Example: add (select Cond, CT, CF), CBO --> select Cond, CT + CBO, CF + CBO 2148 SDLoc DL(Sel); 2149 SDValue NewCT = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CT) 2150 : DAG.getNode(BinOpcode, DL, VT, CT, CBO); 2151 if (!CanFoldNonConst && !NewCT.isUndef() && 2152 !isConstantOrConstantVector(NewCT, true) && 2153 !DAG.isConstantFPBuildVectorOrConstantFP(NewCT)) 2154 return SDValue(); 2155 2156 SDValue NewCF = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CF) 2157 : DAG.getNode(BinOpcode, DL, VT, CF, CBO); 2158 if (!CanFoldNonConst && !NewCF.isUndef() && 2159 !isConstantOrConstantVector(NewCF, true) && 2160 !DAG.isConstantFPBuildVectorOrConstantFP(NewCF)) 2161 return SDValue(); 2162 2163 SDValue SelectOp = DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF); 2164 SelectOp->setFlags(BO->getFlags()); 2165 return SelectOp; 2166 } 2167 2168 static SDValue foldAddSubBoolOfMaskedVal(SDNode *N, SelectionDAG &DAG) { 2169 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && 2170 "Expecting add or sub"); 2171 2172 // Match a constant operand and a zext operand for the math instruction: 2173 // add Z, C 2174 // sub C, Z 2175 bool IsAdd = N->getOpcode() == ISD::ADD; 2176 SDValue C = IsAdd ? N->getOperand(1) : N->getOperand(0); 2177 SDValue Z = IsAdd ? N->getOperand(0) : N->getOperand(1); 2178 auto *CN = dyn_cast<ConstantSDNode>(C); 2179 if (!CN || Z.getOpcode() != ISD::ZERO_EXTEND) 2180 return SDValue(); 2181 2182 // Match the zext operand as a setcc of a boolean. 2183 if (Z.getOperand(0).getOpcode() != ISD::SETCC || 2184 Z.getOperand(0).getValueType() != MVT::i1) 2185 return SDValue(); 2186 2187 // Match the compare as: setcc (X & 1), 0, eq. 2188 SDValue SetCC = Z.getOperand(0); 2189 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get(); 2190 if (CC != ISD::SETEQ || !isNullConstant(SetCC.getOperand(1)) || 2191 SetCC.getOperand(0).getOpcode() != ISD::AND || 2192 !isOneConstant(SetCC.getOperand(0).getOperand(1))) 2193 return SDValue(); 2194 2195 // We are adding/subtracting a constant and an inverted low bit. Turn that 2196 // into a subtract/add of the low bit with incremented/decremented constant: 2197 // add (zext i1 (seteq (X & 1), 0)), C --> sub C+1, (zext (X & 1)) 2198 // sub C, (zext i1 (seteq (X & 1), 0)) --> add C-1, (zext (X & 1)) 2199 EVT VT = C.getValueType(); 2200 SDLoc DL(N); 2201 SDValue LowBit = DAG.getZExtOrTrunc(SetCC.getOperand(0), DL, VT); 2202 SDValue C1 = IsAdd ? DAG.getConstant(CN->getAPIntValue() + 1, DL, VT) : 2203 DAG.getConstant(CN->getAPIntValue() - 1, DL, VT); 2204 return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, C1, LowBit); 2205 } 2206 2207 /// Try to fold a 'not' shifted sign-bit with add/sub with constant operand into 2208 /// a shift and add with a different constant. 2209 static SDValue foldAddSubOfSignBit(SDNode *N, SelectionDAG &DAG) { 2210 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && 2211 "Expecting add or sub"); 2212 2213 // We need a constant operand for the add/sub, and the other operand is a 2214 // logical shift right: add (srl), C or sub C, (srl). 2215 bool IsAdd = N->getOpcode() == ISD::ADD; 2216 SDValue ConstantOp = IsAdd ? N->getOperand(1) : N->getOperand(0); 2217 SDValue ShiftOp = IsAdd ? N->getOperand(0) : N->getOperand(1); 2218 if (!DAG.isConstantIntBuildVectorOrConstantInt(ConstantOp) || 2219 ShiftOp.getOpcode() != ISD::SRL) 2220 return SDValue(); 2221 2222 // The shift must be of a 'not' value. 2223 SDValue Not = ShiftOp.getOperand(0); 2224 if (!Not.hasOneUse() || !isBitwiseNot(Not)) 2225 return SDValue(); 2226 2227 // The shift must be moving the sign bit to the least-significant-bit. 2228 EVT VT = ShiftOp.getValueType(); 2229 SDValue ShAmt = ShiftOp.getOperand(1); 2230 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt); 2231 if (!ShAmtC || ShAmtC->getAPIntValue() != (VT.getScalarSizeInBits() - 1)) 2232 return SDValue(); 2233 2234 // Eliminate the 'not' by adjusting the shift and add/sub constant: 2235 // add (srl (not X), 31), C --> add (sra X, 31), (C + 1) 2236 // sub C, (srl (not X), 31) --> add (srl X, 31), (C - 1) 2237 SDLoc DL(N); 2238 auto ShOpcode = IsAdd ? ISD::SRA : ISD::SRL; 2239 SDValue NewShift = DAG.getNode(ShOpcode, DL, VT, Not.getOperand(0), ShAmt); 2240 if (SDValue NewC = 2241 DAG.FoldConstantArithmetic(IsAdd ? ISD::ADD : ISD::SUB, DL, VT, 2242 {ConstantOp, DAG.getConstant(1, DL, VT)})) 2243 return DAG.getNode(ISD::ADD, DL, VT, NewShift, NewC); 2244 return SDValue(); 2245 } 2246 2247 /// Try to fold a node that behaves like an ADD (note that N isn't necessarily 2248 /// an ISD::ADD here, it could for example be an ISD::OR if we know that there 2249 /// are no common bits set in the operands). 2250 SDValue DAGCombiner::visitADDLike(SDNode *N) { 2251 SDValue N0 = N->getOperand(0); 2252 SDValue N1 = N->getOperand(1); 2253 EVT VT = N0.getValueType(); 2254 SDLoc DL(N); 2255 2256 // fold vector ops 2257 if (VT.isVector()) { 2258 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2259 return FoldedVOp; 2260 2261 // fold (add x, 0) -> x, vector edition 2262 if (ISD::isConstantSplatVectorAllZeros(N1.getNode())) 2263 return N0; 2264 if (ISD::isConstantSplatVectorAllZeros(N0.getNode())) 2265 return N1; 2266 } 2267 2268 // fold (add x, undef) -> undef 2269 if (N0.isUndef()) 2270 return N0; 2271 2272 if (N1.isUndef()) 2273 return N1; 2274 2275 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 2276 // canonicalize constant to RHS 2277 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2278 return DAG.getNode(ISD::ADD, DL, VT, N1, N0); 2279 // fold (add c1, c2) -> c1+c2 2280 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N0, N1}); 2281 } 2282 2283 // fold (add x, 0) -> x 2284 if (isNullConstant(N1)) 2285 return N0; 2286 2287 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) { 2288 // fold ((A-c1)+c2) -> (A+(c2-c1)) 2289 if (N0.getOpcode() == ISD::SUB && 2290 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaque */ true)) { 2291 SDValue Sub = 2292 DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N1, N0.getOperand(1)}); 2293 assert(Sub && "Constant folding failed"); 2294 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Sub); 2295 } 2296 2297 // fold ((c1-A)+c2) -> (c1+c2)-A 2298 if (N0.getOpcode() == ISD::SUB && 2299 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) { 2300 SDValue Add = 2301 DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N1, N0.getOperand(0)}); 2302 assert(Add && "Constant folding failed"); 2303 return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1)); 2304 } 2305 2306 // add (sext i1 X), 1 -> zext (not i1 X) 2307 // We don't transform this pattern: 2308 // add (zext i1 X), -1 -> sext (not i1 X) 2309 // because most (?) targets generate better code for the zext form. 2310 if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() && 2311 isOneOrOneSplat(N1)) { 2312 SDValue X = N0.getOperand(0); 2313 if ((!LegalOperations || 2314 (TLI.isOperationLegal(ISD::XOR, X.getValueType()) && 2315 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) && 2316 X.getScalarValueSizeInBits() == 1) { 2317 SDValue Not = DAG.getNOT(DL, X, X.getValueType()); 2318 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not); 2319 } 2320 } 2321 2322 // Fold (add (or x, c0), c1) -> (add x, (c0 + c1)) if (or x, c0) is 2323 // equivalent to (add x, c0). 2324 if (N0.getOpcode() == ISD::OR && 2325 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaque */ true) && 2326 DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) { 2327 if (SDValue Add0 = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, 2328 {N1, N0.getOperand(1)})) 2329 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0); 2330 } 2331 } 2332 2333 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2334 return NewSel; 2335 2336 // reassociate add 2337 if (!reassociationCanBreakAddressingModePattern(ISD::ADD, DL, N0, N1)) { 2338 if (SDValue RADD = reassociateOps(ISD::ADD, DL, N0, N1, N->getFlags())) 2339 return RADD; 2340 } 2341 // fold ((0-A) + B) -> B-A 2342 if (N0.getOpcode() == ISD::SUB && isNullOrNullSplat(N0.getOperand(0))) 2343 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1)); 2344 2345 // fold (A + (0-B)) -> A-B 2346 if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0))) 2347 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1)); 2348 2349 // fold (A+(B-A)) -> B 2350 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 2351 return N1.getOperand(0); 2352 2353 // fold ((B-A)+A) -> B 2354 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 2355 return N0.getOperand(0); 2356 2357 // fold ((A-B)+(C-A)) -> (C-B) 2358 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB && 2359 N0.getOperand(0) == N1.getOperand(1)) 2360 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 2361 N0.getOperand(1)); 2362 2363 // fold ((A-B)+(B-C)) -> (A-C) 2364 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB && 2365 N0.getOperand(1) == N1.getOperand(0)) 2366 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), 2367 N1.getOperand(1)); 2368 2369 // fold (A+(B-(A+C))) to (B-C) 2370 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 2371 N0 == N1.getOperand(1).getOperand(0)) 2372 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 2373 N1.getOperand(1).getOperand(1)); 2374 2375 // fold (A+(B-(C+A))) to (B-C) 2376 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 2377 N0 == N1.getOperand(1).getOperand(1)) 2378 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 2379 N1.getOperand(1).getOperand(0)); 2380 2381 // fold (A+((B-A)+or-C)) to (B+or-C) 2382 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 2383 N1.getOperand(0).getOpcode() == ISD::SUB && 2384 N0 == N1.getOperand(0).getOperand(1)) 2385 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0), 2386 N1.getOperand(1)); 2387 2388 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 2389 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 2390 SDValue N00 = N0.getOperand(0); 2391 SDValue N01 = N0.getOperand(1); 2392 SDValue N10 = N1.getOperand(0); 2393 SDValue N11 = N1.getOperand(1); 2394 2395 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10)) 2396 return DAG.getNode(ISD::SUB, DL, VT, 2397 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 2398 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 2399 } 2400 2401 // fold (add (umax X, C), -C) --> (usubsat X, C) 2402 if (N0.getOpcode() == ISD::UMAX && hasOperation(ISD::USUBSAT, VT)) { 2403 auto MatchUSUBSAT = [](ConstantSDNode *Max, ConstantSDNode *Op) { 2404 return (!Max && !Op) || 2405 (Max && Op && Max->getAPIntValue() == (-Op->getAPIntValue())); 2406 }; 2407 if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchUSUBSAT, 2408 /*AllowUndefs*/ true)) 2409 return DAG.getNode(ISD::USUBSAT, DL, VT, N0.getOperand(0), 2410 N0.getOperand(1)); 2411 } 2412 2413 if (SimplifyDemandedBits(SDValue(N, 0))) 2414 return SDValue(N, 0); 2415 2416 if (isOneOrOneSplat(N1)) { 2417 // fold (add (xor a, -1), 1) -> (sub 0, a) 2418 if (isBitwiseNot(N0)) 2419 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), 2420 N0.getOperand(0)); 2421 2422 // fold (add (add (xor a, -1), b), 1) -> (sub b, a) 2423 if (N0.getOpcode() == ISD::ADD || 2424 N0.getOpcode() == ISD::UADDO || 2425 N0.getOpcode() == ISD::SADDO) { 2426 SDValue A, Xor; 2427 2428 if (isBitwiseNot(N0.getOperand(0))) { 2429 A = N0.getOperand(1); 2430 Xor = N0.getOperand(0); 2431 } else if (isBitwiseNot(N0.getOperand(1))) { 2432 A = N0.getOperand(0); 2433 Xor = N0.getOperand(1); 2434 } 2435 2436 if (Xor) 2437 return DAG.getNode(ISD::SUB, DL, VT, A, Xor.getOperand(0)); 2438 } 2439 2440 // Look for: 2441 // add (add x, y), 1 2442 // And if the target does not like this form then turn into: 2443 // sub y, (xor x, -1) 2444 if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.hasOneUse() && 2445 N0.getOpcode() == ISD::ADD) { 2446 SDValue Not = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 2447 DAG.getAllOnesConstant(DL, VT)); 2448 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(1), Not); 2449 } 2450 } 2451 2452 // (x - y) + -1 -> add (xor y, -1), x 2453 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB && 2454 isAllOnesOrAllOnesSplat(N1)) { 2455 SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), N1); 2456 return DAG.getNode(ISD::ADD, DL, VT, Xor, N0.getOperand(0)); 2457 } 2458 2459 if (SDValue Combined = visitADDLikeCommutative(N0, N1, N)) 2460 return Combined; 2461 2462 if (SDValue Combined = visitADDLikeCommutative(N1, N0, N)) 2463 return Combined; 2464 2465 return SDValue(); 2466 } 2467 2468 SDValue DAGCombiner::visitADD(SDNode *N) { 2469 SDValue N0 = N->getOperand(0); 2470 SDValue N1 = N->getOperand(1); 2471 EVT VT = N0.getValueType(); 2472 SDLoc DL(N); 2473 2474 if (SDValue Combined = visitADDLike(N)) 2475 return Combined; 2476 2477 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG)) 2478 return V; 2479 2480 if (SDValue V = foldAddSubOfSignBit(N, DAG)) 2481 return V; 2482 2483 // fold (a+b) -> (a|b) iff a and b share no bits. 2484 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) && 2485 DAG.haveNoCommonBitsSet(N0, N1)) 2486 return DAG.getNode(ISD::OR, DL, VT, N0, N1); 2487 2488 // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)). 2489 if (N0.getOpcode() == ISD::VSCALE && N1.getOpcode() == ISD::VSCALE) { 2490 const APInt &C0 = N0->getConstantOperandAPInt(0); 2491 const APInt &C1 = N1->getConstantOperandAPInt(0); 2492 return DAG.getVScale(DL, VT, C0 + C1); 2493 } 2494 2495 // fold a+vscale(c1)+vscale(c2) -> a+vscale(c1+c2) 2496 if ((N0.getOpcode() == ISD::ADD) && 2497 (N0.getOperand(1).getOpcode() == ISD::VSCALE) && 2498 (N1.getOpcode() == ISD::VSCALE)) { 2499 const APInt &VS0 = N0.getOperand(1)->getConstantOperandAPInt(0); 2500 const APInt &VS1 = N1->getConstantOperandAPInt(0); 2501 SDValue VS = DAG.getVScale(DL, VT, VS0 + VS1); 2502 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), VS); 2503 } 2504 2505 // Fold (add step_vector(c1), step_vector(c2) to step_vector(c1+c2)) 2506 if (N0.getOpcode() == ISD::STEP_VECTOR && 2507 N1.getOpcode() == ISD::STEP_VECTOR) { 2508 const APInt &C0 = N0->getConstantOperandAPInt(0); 2509 const APInt &C1 = N1->getConstantOperandAPInt(0); 2510 EVT SVT = N0.getOperand(0).getValueType(); 2511 SDValue NewStep = DAG.getConstant(C0 + C1, DL, SVT); 2512 return DAG.getStepVector(DL, VT, NewStep); 2513 } 2514 2515 // Fold a + step_vector(c1) + step_vector(c2) to a + step_vector(c1+c2) 2516 if ((N0.getOpcode() == ISD::ADD) && 2517 (N0.getOperand(1).getOpcode() == ISD::STEP_VECTOR) && 2518 (N1.getOpcode() == ISD::STEP_VECTOR)) { 2519 const APInt &SV0 = N0.getOperand(1)->getConstantOperandAPInt(0); 2520 const APInt &SV1 = N1->getConstantOperandAPInt(0); 2521 EVT SVT = N1.getOperand(0).getValueType(); 2522 assert(N1.getOperand(0).getValueType() == 2523 N0.getOperand(1)->getOperand(0).getValueType() && 2524 "Different operand types of STEP_VECTOR."); 2525 SDValue NewStep = DAG.getConstant(SV0 + SV1, DL, SVT); 2526 SDValue SV = DAG.getStepVector(DL, VT, NewStep); 2527 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), SV); 2528 } 2529 2530 return SDValue(); 2531 } 2532 2533 SDValue DAGCombiner::visitADDSAT(SDNode *N) { 2534 unsigned Opcode = N->getOpcode(); 2535 SDValue N0 = N->getOperand(0); 2536 SDValue N1 = N->getOperand(1); 2537 EVT VT = N0.getValueType(); 2538 SDLoc DL(N); 2539 2540 // fold vector ops 2541 if (VT.isVector()) { 2542 // TODO SimplifyVBinOp 2543 2544 // fold (add_sat x, 0) -> x, vector edition 2545 if (ISD::isConstantSplatVectorAllZeros(N1.getNode())) 2546 return N0; 2547 if (ISD::isConstantSplatVectorAllZeros(N0.getNode())) 2548 return N1; 2549 } 2550 2551 // fold (add_sat x, undef) -> -1 2552 if (N0.isUndef() || N1.isUndef()) 2553 return DAG.getAllOnesConstant(DL, VT); 2554 2555 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 2556 // canonicalize constant to RHS 2557 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2558 return DAG.getNode(Opcode, DL, VT, N1, N0); 2559 // fold (add_sat c1, c2) -> c3 2560 return DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}); 2561 } 2562 2563 // fold (add_sat x, 0) -> x 2564 if (isNullConstant(N1)) 2565 return N0; 2566 2567 // If it cannot overflow, transform into an add. 2568 if (Opcode == ISD::UADDSAT) 2569 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2570 return DAG.getNode(ISD::ADD, DL, VT, N0, N1); 2571 2572 return SDValue(); 2573 } 2574 2575 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) { 2576 bool Masked = false; 2577 2578 // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization. 2579 while (true) { 2580 if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) { 2581 V = V.getOperand(0); 2582 continue; 2583 } 2584 2585 if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) { 2586 Masked = true; 2587 V = V.getOperand(0); 2588 continue; 2589 } 2590 2591 break; 2592 } 2593 2594 // If this is not a carry, return. 2595 if (V.getResNo() != 1) 2596 return SDValue(); 2597 2598 if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY && 2599 V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO) 2600 return SDValue(); 2601 2602 EVT VT = V.getNode()->getValueType(0); 2603 if (!TLI.isOperationLegalOrCustom(V.getOpcode(), VT)) 2604 return SDValue(); 2605 2606 // If the result is masked, then no matter what kind of bool it is we can 2607 // return. If it isn't, then we need to make sure the bool type is either 0 or 2608 // 1 and not other values. 2609 if (Masked || 2610 TLI.getBooleanContents(V.getValueType()) == 2611 TargetLoweringBase::ZeroOrOneBooleanContent) 2612 return V; 2613 2614 return SDValue(); 2615 } 2616 2617 /// Given the operands of an add/sub operation, see if the 2nd operand is a 2618 /// masked 0/1 whose source operand is actually known to be 0/-1. If so, invert 2619 /// the opcode and bypass the mask operation. 2620 static SDValue foldAddSubMasked1(bool IsAdd, SDValue N0, SDValue N1, 2621 SelectionDAG &DAG, const SDLoc &DL) { 2622 if (N1.getOpcode() != ISD::AND || !isOneOrOneSplat(N1->getOperand(1))) 2623 return SDValue(); 2624 2625 EVT VT = N0.getValueType(); 2626 if (DAG.ComputeNumSignBits(N1.getOperand(0)) != VT.getScalarSizeInBits()) 2627 return SDValue(); 2628 2629 // add N0, (and (AssertSext X, i1), 1) --> sub N0, X 2630 // sub N0, (and (AssertSext X, i1), 1) --> add N0, X 2631 return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, N0, N1.getOperand(0)); 2632 } 2633 2634 /// Helper for doing combines based on N0 and N1 being added to each other. 2635 SDValue DAGCombiner::visitADDLikeCommutative(SDValue N0, SDValue N1, 2636 SDNode *LocReference) { 2637 EVT VT = N0.getValueType(); 2638 SDLoc DL(LocReference); 2639 2640 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 2641 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 2642 isNullOrNullSplat(N1.getOperand(0).getOperand(0))) 2643 return DAG.getNode(ISD::SUB, DL, VT, N0, 2644 DAG.getNode(ISD::SHL, DL, VT, 2645 N1.getOperand(0).getOperand(1), 2646 N1.getOperand(1))); 2647 2648 if (SDValue V = foldAddSubMasked1(true, N0, N1, DAG, DL)) 2649 return V; 2650 2651 // Look for: 2652 // add (add x, 1), y 2653 // And if the target does not like this form then turn into: 2654 // sub y, (xor x, -1) 2655 if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.hasOneUse() && 2656 N0.getOpcode() == ISD::ADD && isOneOrOneSplat(N0.getOperand(1))) { 2657 SDValue Not = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 2658 DAG.getAllOnesConstant(DL, VT)); 2659 return DAG.getNode(ISD::SUB, DL, VT, N1, Not); 2660 } 2661 2662 // Hoist one-use subtraction by non-opaque constant: 2663 // (x - C) + y -> (x + y) - C 2664 // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors. 2665 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB && 2666 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) { 2667 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), N1); 2668 return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1)); 2669 } 2670 // Hoist one-use subtraction from non-opaque constant: 2671 // (C - x) + y -> (y - x) + C 2672 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB && 2673 isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) { 2674 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1)); 2675 return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(0)); 2676 } 2677 2678 // If the target's bool is represented as 0/1, prefer to make this 'sub 0/1' 2679 // rather than 'add 0/-1' (the zext should get folded). 2680 // add (sext i1 Y), X --> sub X, (zext i1 Y) 2681 if (N0.getOpcode() == ISD::SIGN_EXTEND && 2682 N0.getOperand(0).getScalarValueSizeInBits() == 1 && 2683 TLI.getBooleanContents(VT) == TargetLowering::ZeroOrOneBooleanContent) { 2684 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 2685 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 2686 } 2687 2688 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 2689 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2690 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2691 if (TN->getVT() == MVT::i1) { 2692 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2693 DAG.getConstant(1, DL, VT)); 2694 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 2695 } 2696 } 2697 2698 // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2699 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)) && 2700 N1.getResNo() == 0) 2701 return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(), 2702 N0, N1.getOperand(0), N1.getOperand(2)); 2703 2704 // (add X, Carry) -> (addcarry X, 0, Carry) 2705 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) 2706 if (SDValue Carry = getAsCarry(TLI, N1)) 2707 return DAG.getNode(ISD::ADDCARRY, DL, 2708 DAG.getVTList(VT, Carry.getValueType()), N0, 2709 DAG.getConstant(0, DL, VT), Carry); 2710 2711 return SDValue(); 2712 } 2713 2714 SDValue DAGCombiner::visitADDC(SDNode *N) { 2715 SDValue N0 = N->getOperand(0); 2716 SDValue N1 = N->getOperand(1); 2717 EVT VT = N0.getValueType(); 2718 SDLoc DL(N); 2719 2720 // If the flag result is dead, turn this into an ADD. 2721 if (!N->hasAnyUseOfValue(1)) 2722 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2723 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2724 2725 // canonicalize constant to RHS. 2726 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2727 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2728 if (N0C && !N1C) 2729 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0); 2730 2731 // fold (addc x, 0) -> x + no carry out 2732 if (isNullConstant(N1)) 2733 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 2734 DL, MVT::Glue)); 2735 2736 // If it cannot overflow, transform into an add. 2737 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2738 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2739 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2740 2741 return SDValue(); 2742 } 2743 2744 /** 2745 * Flips a boolean if it is cheaper to compute. If the Force parameters is set, 2746 * then the flip also occurs if computing the inverse is the same cost. 2747 * This function returns an empty SDValue in case it cannot flip the boolean 2748 * without increasing the cost of the computation. If you want to flip a boolean 2749 * no matter what, use DAG.getLogicalNOT. 2750 */ 2751 static SDValue extractBooleanFlip(SDValue V, SelectionDAG &DAG, 2752 const TargetLowering &TLI, 2753 bool Force) { 2754 if (Force && isa<ConstantSDNode>(V)) 2755 return DAG.getLogicalNOT(SDLoc(V), V, V.getValueType()); 2756 2757 if (V.getOpcode() != ISD::XOR) 2758 return SDValue(); 2759 2760 ConstantSDNode *Const = isConstOrConstSplat(V.getOperand(1), false); 2761 if (!Const) 2762 return SDValue(); 2763 2764 EVT VT = V.getValueType(); 2765 2766 bool IsFlip = false; 2767 switch(TLI.getBooleanContents(VT)) { 2768 case TargetLowering::ZeroOrOneBooleanContent: 2769 IsFlip = Const->isOne(); 2770 break; 2771 case TargetLowering::ZeroOrNegativeOneBooleanContent: 2772 IsFlip = Const->isAllOnesValue(); 2773 break; 2774 case TargetLowering::UndefinedBooleanContent: 2775 IsFlip = (Const->getAPIntValue() & 0x01) == 1; 2776 break; 2777 } 2778 2779 if (IsFlip) 2780 return V.getOperand(0); 2781 if (Force) 2782 return DAG.getLogicalNOT(SDLoc(V), V, V.getValueType()); 2783 return SDValue(); 2784 } 2785 2786 SDValue DAGCombiner::visitADDO(SDNode *N) { 2787 SDValue N0 = N->getOperand(0); 2788 SDValue N1 = N->getOperand(1); 2789 EVT VT = N0.getValueType(); 2790 bool IsSigned = (ISD::SADDO == N->getOpcode()); 2791 2792 EVT CarryVT = N->getValueType(1); 2793 SDLoc DL(N); 2794 2795 // If the flag result is dead, turn this into an ADD. 2796 if (!N->hasAnyUseOfValue(1)) 2797 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2798 DAG.getUNDEF(CarryVT)); 2799 2800 // canonicalize constant to RHS. 2801 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2802 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2803 return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0); 2804 2805 // fold (addo x, 0) -> x + no carry out 2806 if (isNullOrNullSplat(N1)) 2807 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 2808 2809 if (!IsSigned) { 2810 // If it cannot overflow, transform into an add. 2811 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2812 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2813 DAG.getConstant(0, DL, CarryVT)); 2814 2815 // fold (uaddo (xor a, -1), 1) -> (usub 0, a) and flip carry. 2816 if (isBitwiseNot(N0) && isOneOrOneSplat(N1)) { 2817 SDValue Sub = DAG.getNode(ISD::USUBO, DL, N->getVTList(), 2818 DAG.getConstant(0, DL, VT), N0.getOperand(0)); 2819 return CombineTo( 2820 N, Sub, DAG.getLogicalNOT(DL, Sub.getValue(1), Sub->getValueType(1))); 2821 } 2822 2823 if (SDValue Combined = visitUADDOLike(N0, N1, N)) 2824 return Combined; 2825 2826 if (SDValue Combined = visitUADDOLike(N1, N0, N)) 2827 return Combined; 2828 } 2829 2830 return SDValue(); 2831 } 2832 2833 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) { 2834 EVT VT = N0.getValueType(); 2835 if (VT.isVector()) 2836 return SDValue(); 2837 2838 // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2839 // If Y + 1 cannot overflow. 2840 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) { 2841 SDValue Y = N1.getOperand(0); 2842 SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType()); 2843 if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never) 2844 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y, 2845 N1.getOperand(2)); 2846 } 2847 2848 // (uaddo X, Carry) -> (addcarry X, 0, Carry) 2849 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) 2850 if (SDValue Carry = getAsCarry(TLI, N1)) 2851 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, 2852 DAG.getConstant(0, SDLoc(N), VT), Carry); 2853 2854 return SDValue(); 2855 } 2856 2857 SDValue DAGCombiner::visitADDE(SDNode *N) { 2858 SDValue N0 = N->getOperand(0); 2859 SDValue N1 = N->getOperand(1); 2860 SDValue CarryIn = N->getOperand(2); 2861 2862 // canonicalize constant to RHS 2863 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2864 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2865 if (N0C && !N1C) 2866 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 2867 N1, N0, CarryIn); 2868 2869 // fold (adde x, y, false) -> (addc x, y) 2870 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2871 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 2872 2873 return SDValue(); 2874 } 2875 2876 SDValue DAGCombiner::visitADDCARRY(SDNode *N) { 2877 SDValue N0 = N->getOperand(0); 2878 SDValue N1 = N->getOperand(1); 2879 SDValue CarryIn = N->getOperand(2); 2880 SDLoc DL(N); 2881 2882 // canonicalize constant to RHS 2883 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2884 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2885 if (N0C && !N1C) 2886 return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn); 2887 2888 // fold (addcarry x, y, false) -> (uaddo x, y) 2889 if (isNullConstant(CarryIn)) { 2890 if (!LegalOperations || 2891 TLI.isOperationLegalOrCustom(ISD::UADDO, N->getValueType(0))) 2892 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1); 2893 } 2894 2895 // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry. 2896 if (isNullConstant(N0) && isNullConstant(N1)) { 2897 EVT VT = N0.getValueType(); 2898 EVT CarryVT = CarryIn.getValueType(); 2899 SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT); 2900 AddToWorklist(CarryExt.getNode()); 2901 return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt, 2902 DAG.getConstant(1, DL, VT)), 2903 DAG.getConstant(0, DL, CarryVT)); 2904 } 2905 2906 if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N)) 2907 return Combined; 2908 2909 if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N)) 2910 return Combined; 2911 2912 return SDValue(); 2913 } 2914 2915 SDValue DAGCombiner::visitSADDO_CARRY(SDNode *N) { 2916 SDValue N0 = N->getOperand(0); 2917 SDValue N1 = N->getOperand(1); 2918 SDValue CarryIn = N->getOperand(2); 2919 SDLoc DL(N); 2920 2921 // canonicalize constant to RHS 2922 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2923 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2924 if (N0C && !N1C) 2925 return DAG.getNode(ISD::SADDO_CARRY, DL, N->getVTList(), N1, N0, CarryIn); 2926 2927 // fold (saddo_carry x, y, false) -> (saddo x, y) 2928 if (isNullConstant(CarryIn)) { 2929 if (!LegalOperations || 2930 TLI.isOperationLegalOrCustom(ISD::SADDO, N->getValueType(0))) 2931 return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0, N1); 2932 } 2933 2934 return SDValue(); 2935 } 2936 2937 /** 2938 * If we are facing some sort of diamond carry propapagtion pattern try to 2939 * break it up to generate something like: 2940 * (addcarry X, 0, (addcarry A, B, Z):Carry) 2941 * 2942 * The end result is usually an increase in operation required, but because the 2943 * carry is now linearized, other tranforms can kick in and optimize the DAG. 2944 * 2945 * Patterns typically look something like 2946 * (uaddo A, B) 2947 * / \ 2948 * Carry Sum 2949 * | \ 2950 * | (addcarry *, 0, Z) 2951 * | / 2952 * \ Carry 2953 * | / 2954 * (addcarry X, *, *) 2955 * 2956 * But numerous variation exist. Our goal is to identify A, B, X and Z and 2957 * produce a combine with a single path for carry propagation. 2958 */ 2959 static SDValue combineADDCARRYDiamond(DAGCombiner &Combiner, SelectionDAG &DAG, 2960 SDValue X, SDValue Carry0, SDValue Carry1, 2961 SDNode *N) { 2962 if (Carry1.getResNo() != 1 || Carry0.getResNo() != 1) 2963 return SDValue(); 2964 if (Carry1.getOpcode() != ISD::UADDO) 2965 return SDValue(); 2966 2967 SDValue Z; 2968 2969 /** 2970 * First look for a suitable Z. It will present itself in the form of 2971 * (addcarry Y, 0, Z) or its equivalent (uaddo Y, 1) for Z=true 2972 */ 2973 if (Carry0.getOpcode() == ISD::ADDCARRY && 2974 isNullConstant(Carry0.getOperand(1))) { 2975 Z = Carry0.getOperand(2); 2976 } else if (Carry0.getOpcode() == ISD::UADDO && 2977 isOneConstant(Carry0.getOperand(1))) { 2978 EVT VT = Combiner.getSetCCResultType(Carry0.getValueType()); 2979 Z = DAG.getConstant(1, SDLoc(Carry0.getOperand(1)), VT); 2980 } else { 2981 // We couldn't find a suitable Z. 2982 return SDValue(); 2983 } 2984 2985 2986 auto cancelDiamond = [&](SDValue A,SDValue B) { 2987 SDLoc DL(N); 2988 SDValue NewY = DAG.getNode(ISD::ADDCARRY, DL, Carry0->getVTList(), A, B, Z); 2989 Combiner.AddToWorklist(NewY.getNode()); 2990 return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), X, 2991 DAG.getConstant(0, DL, X.getValueType()), 2992 NewY.getValue(1)); 2993 }; 2994 2995 /** 2996 * (uaddo A, B) 2997 * | 2998 * Sum 2999 * | 3000 * (addcarry *, 0, Z) 3001 */ 3002 if (Carry0.getOperand(0) == Carry1.getValue(0)) { 3003 return cancelDiamond(Carry1.getOperand(0), Carry1.getOperand(1)); 3004 } 3005 3006 /** 3007 * (addcarry A, 0, Z) 3008 * | 3009 * Sum 3010 * | 3011 * (uaddo *, B) 3012 */ 3013 if (Carry1.getOperand(0) == Carry0.getValue(0)) { 3014 return cancelDiamond(Carry0.getOperand(0), Carry1.getOperand(1)); 3015 } 3016 3017 if (Carry1.getOperand(1) == Carry0.getValue(0)) { 3018 return cancelDiamond(Carry1.getOperand(0), Carry0.getOperand(0)); 3019 } 3020 3021 return SDValue(); 3022 } 3023 3024 // If we are facing some sort of diamond carry/borrow in/out pattern try to 3025 // match patterns like: 3026 // 3027 // (uaddo A, B) CarryIn 3028 // | \ | 3029 // | \ | 3030 // PartialSum PartialCarryOutX / 3031 // | | / 3032 // | ____|____________/ 3033 // | / | 3034 // (uaddo *, *) \________ 3035 // | \ \ 3036 // | \ | 3037 // | PartialCarryOutY | 3038 // | \ | 3039 // | \ / 3040 // AddCarrySum | ______/ 3041 // | / 3042 // CarryOut = (or *, *) 3043 // 3044 // And generate ADDCARRY (or SUBCARRY) with two result values: 3045 // 3046 // {AddCarrySum, CarryOut} = (addcarry A, B, CarryIn) 3047 // 3048 // Our goal is to identify A, B, and CarryIn and produce ADDCARRY/SUBCARRY with 3049 // a single path for carry/borrow out propagation: 3050 static SDValue combineCarryDiamond(DAGCombiner &Combiner, SelectionDAG &DAG, 3051 const TargetLowering &TLI, SDValue Carry0, 3052 SDValue Carry1, SDNode *N) { 3053 if (Carry0.getResNo() != 1 || Carry1.getResNo() != 1) 3054 return SDValue(); 3055 unsigned Opcode = Carry0.getOpcode(); 3056 if (Opcode != Carry1.getOpcode()) 3057 return SDValue(); 3058 if (Opcode != ISD::UADDO && Opcode != ISD::USUBO) 3059 return SDValue(); 3060 3061 // Canonicalize the add/sub of A and B as Carry0 and the add/sub of the 3062 // carry/borrow in as Carry1. (The top and middle uaddo nodes respectively in 3063 // the above ASCII art.) 3064 if (Carry1.getOperand(0) != Carry0.getValue(0) && 3065 Carry1.getOperand(1) != Carry0.getValue(0)) 3066 std::swap(Carry0, Carry1); 3067 if (Carry1.getOperand(0) != Carry0.getValue(0) && 3068 Carry1.getOperand(1) != Carry0.getValue(0)) 3069 return SDValue(); 3070 3071 // The carry in value must be on the righthand side for subtraction. 3072 unsigned CarryInOperandNum = 3073 Carry1.getOperand(0) == Carry0.getValue(0) ? 1 : 0; 3074 if (Opcode == ISD::USUBO && CarryInOperandNum != 1) 3075 return SDValue(); 3076 SDValue CarryIn = Carry1.getOperand(CarryInOperandNum); 3077 3078 unsigned NewOp = Opcode == ISD::UADDO ? ISD::ADDCARRY : ISD::SUBCARRY; 3079 if (!TLI.isOperationLegalOrCustom(NewOp, Carry0.getValue(0).getValueType())) 3080 return SDValue(); 3081 3082 // Verify that the carry/borrow in is plausibly a carry/borrow bit. 3083 // TODO: make getAsCarry() aware of how partial carries are merged. 3084 if (CarryIn.getOpcode() != ISD::ZERO_EXTEND) 3085 return SDValue(); 3086 CarryIn = CarryIn.getOperand(0); 3087 if (CarryIn.getValueType() != MVT::i1) 3088 return SDValue(); 3089 3090 SDLoc DL(N); 3091 SDValue Merged = 3092 DAG.getNode(NewOp, DL, Carry1->getVTList(), Carry0.getOperand(0), 3093 Carry0.getOperand(1), CarryIn); 3094 3095 // Please note that because we have proven that the result of the UADDO/USUBO 3096 // of A and B feeds into the UADDO/USUBO that does the carry/borrow in, we can 3097 // therefore prove that if the first UADDO/USUBO overflows, the second 3098 // UADDO/USUBO cannot. For example consider 8-bit numbers where 0xFF is the 3099 // maximum value. 3100 // 3101 // 0xFF + 0xFF == 0xFE with carry but 0xFE + 1 does not carry 3102 // 0x00 - 0xFF == 1 with a carry/borrow but 1 - 1 == 0 (no carry/borrow) 3103 // 3104 // This is important because it means that OR and XOR can be used to merge 3105 // carry flags; and that AND can return a constant zero. 3106 // 3107 // TODO: match other operations that can merge flags (ADD, etc) 3108 DAG.ReplaceAllUsesOfValueWith(Carry1.getValue(0), Merged.getValue(0)); 3109 if (N->getOpcode() == ISD::AND) 3110 return DAG.getConstant(0, DL, MVT::i1); 3111 return Merged.getValue(1); 3112 } 3113 3114 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, 3115 SDNode *N) { 3116 // fold (addcarry (xor a, -1), b, c) -> (subcarry b, a, !c) and flip carry. 3117 if (isBitwiseNot(N0)) 3118 if (SDValue NotC = extractBooleanFlip(CarryIn, DAG, TLI, true)) { 3119 SDLoc DL(N); 3120 SDValue Sub = DAG.getNode(ISD::SUBCARRY, DL, N->getVTList(), N1, 3121 N0.getOperand(0), NotC); 3122 return CombineTo( 3123 N, Sub, DAG.getLogicalNOT(DL, Sub.getValue(1), Sub->getValueType(1))); 3124 } 3125 3126 // Iff the flag result is dead: 3127 // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry) 3128 // Don't do this if the Carry comes from the uaddo. It won't remove the uaddo 3129 // or the dependency between the instructions. 3130 if ((N0.getOpcode() == ISD::ADD || 3131 (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0 && 3132 N0.getValue(1) != CarryIn)) && 3133 isNullConstant(N1) && !N->hasAnyUseOfValue(1)) 3134 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), 3135 N0.getOperand(0), N0.getOperand(1), CarryIn); 3136 3137 /** 3138 * When one of the addcarry argument is itself a carry, we may be facing 3139 * a diamond carry propagation. In which case we try to transform the DAG 3140 * to ensure linear carry propagation if that is possible. 3141 */ 3142 if (auto Y = getAsCarry(TLI, N1)) { 3143 // Because both are carries, Y and Z can be swapped. 3144 if (auto R = combineADDCARRYDiamond(*this, DAG, N0, Y, CarryIn, N)) 3145 return R; 3146 if (auto R = combineADDCARRYDiamond(*this, DAG, N0, CarryIn, Y, N)) 3147 return R; 3148 } 3149 3150 return SDValue(); 3151 } 3152 3153 // Attempt to create a USUBSAT(LHS, RHS) node with DstVT, performing a 3154 // clamp/truncation if necessary. 3155 static SDValue getTruncatedUSUBSAT(EVT DstVT, EVT SrcVT, SDValue LHS, 3156 SDValue RHS, SelectionDAG &DAG, 3157 const SDLoc &DL) { 3158 assert(DstVT.getScalarSizeInBits() <= SrcVT.getScalarSizeInBits() && 3159 "Illegal truncation"); 3160 3161 if (DstVT == SrcVT) 3162 return DAG.getNode(ISD::USUBSAT, DL, DstVT, LHS, RHS); 3163 3164 // If the LHS is zero-extended then we can perform the USUBSAT as DstVT by 3165 // clamping RHS. 3166 APInt UpperBits = APInt::getBitsSetFrom(SrcVT.getScalarSizeInBits(), 3167 DstVT.getScalarSizeInBits()); 3168 if (!DAG.MaskedValueIsZero(LHS, UpperBits)) 3169 return SDValue(); 3170 3171 SDValue SatLimit = 3172 DAG.getConstant(APInt::getLowBitsSet(SrcVT.getScalarSizeInBits(), 3173 DstVT.getScalarSizeInBits()), 3174 DL, SrcVT); 3175 RHS = DAG.getNode(ISD::UMIN, DL, SrcVT, RHS, SatLimit); 3176 RHS = DAG.getNode(ISD::TRUNCATE, DL, DstVT, RHS); 3177 LHS = DAG.getNode(ISD::TRUNCATE, DL, DstVT, LHS); 3178 return DAG.getNode(ISD::USUBSAT, DL, DstVT, LHS, RHS); 3179 } 3180 3181 // Try to find umax(a,b) - b or a - umin(a,b) patterns that may be converted to 3182 // usubsat(a,b), optionally as a truncated type. 3183 SDValue DAGCombiner::foldSubToUSubSat(EVT DstVT, SDNode *N) { 3184 if (N->getOpcode() != ISD::SUB || 3185 !(!LegalOperations || hasOperation(ISD::USUBSAT, DstVT))) 3186 return SDValue(); 3187 3188 EVT SubVT = N->getValueType(0); 3189 SDValue Op0 = N->getOperand(0); 3190 SDValue Op1 = N->getOperand(1); 3191 3192 // Try to find umax(a,b) - b or a - umin(a,b) patterns 3193 // they may be converted to usubsat(a,b). 3194 if (Op0.getOpcode() == ISD::UMAX) { 3195 SDValue MaxLHS = Op0.getOperand(0); 3196 SDValue MaxRHS = Op0.getOperand(1); 3197 if (MaxLHS == Op1) 3198 return getTruncatedUSUBSAT(DstVT, SubVT, MaxRHS, Op1, DAG, SDLoc(N)); 3199 if (MaxRHS == Op1) 3200 return getTruncatedUSUBSAT(DstVT, SubVT, MaxLHS, Op1, DAG, SDLoc(N)); 3201 } 3202 3203 if (Op1.getOpcode() == ISD::UMIN) { 3204 SDValue MinLHS = Op1.getOperand(0); 3205 SDValue MinRHS = Op1.getOperand(1); 3206 if (MinLHS == Op0) 3207 return getTruncatedUSUBSAT(DstVT, SubVT, Op0, MinRHS, DAG, SDLoc(N)); 3208 if (MinRHS == Op0) 3209 return getTruncatedUSUBSAT(DstVT, SubVT, Op0, MinLHS, DAG, SDLoc(N)); 3210 } 3211 3212 // sub(a,trunc(umin(zext(a),b))) -> usubsat(a,trunc(umin(b,SatLimit))) 3213 if (Op1.getOpcode() == ISD::TRUNCATE && 3214 Op1.getOperand(0).getOpcode() == ISD::UMIN) { 3215 SDValue MinLHS = Op1.getOperand(0).getOperand(0); 3216 SDValue MinRHS = Op1.getOperand(0).getOperand(1); 3217 if (MinLHS.getOpcode() == ISD::ZERO_EXTEND && MinLHS.getOperand(0) == Op0) 3218 return getTruncatedUSUBSAT(DstVT, MinLHS.getValueType(), MinLHS, MinRHS, 3219 DAG, SDLoc(N)); 3220 if (MinRHS.getOpcode() == ISD::ZERO_EXTEND && MinRHS.getOperand(0) == Op0) 3221 return getTruncatedUSUBSAT(DstVT, MinLHS.getValueType(), MinRHS, MinLHS, 3222 DAG, SDLoc(N)); 3223 } 3224 3225 return SDValue(); 3226 } 3227 3228 // Since it may not be valid to emit a fold to zero for vector initializers 3229 // check if we can before folding. 3230 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT, 3231 SelectionDAG &DAG, bool LegalOperations) { 3232 if (!VT.isVector()) 3233 return DAG.getConstant(0, DL, VT); 3234 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 3235 return DAG.getConstant(0, DL, VT); 3236 return SDValue(); 3237 } 3238 3239 SDValue DAGCombiner::visitSUB(SDNode *N) { 3240 SDValue N0 = N->getOperand(0); 3241 SDValue N1 = N->getOperand(1); 3242 EVT VT = N0.getValueType(); 3243 SDLoc DL(N); 3244 3245 // fold vector ops 3246 if (VT.isVector()) { 3247 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3248 return FoldedVOp; 3249 3250 // fold (sub x, 0) -> x, vector edition 3251 if (ISD::isConstantSplatVectorAllZeros(N1.getNode())) 3252 return N0; 3253 } 3254 3255 // fold (sub x, x) -> 0 3256 // FIXME: Refactor this and xor and other similar operations together. 3257 if (N0 == N1) 3258 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations); 3259 3260 // fold (sub c1, c2) -> c3 3261 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0, N1})) 3262 return C; 3263 3264 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3265 return NewSel; 3266 3267 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 3268 3269 // fold (sub x, c) -> (add x, -c) 3270 if (N1C) { 3271 return DAG.getNode(ISD::ADD, DL, VT, N0, 3272 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 3273 } 3274 3275 if (isNullOrNullSplat(N0)) { 3276 unsigned BitWidth = VT.getScalarSizeInBits(); 3277 // Right-shifting everything out but the sign bit followed by negation is 3278 // the same as flipping arithmetic/logical shift type without the negation: 3279 // -(X >>u 31) -> (X >>s 31) 3280 // -(X >>s 31) -> (X >>u 31) 3281 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) { 3282 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1)); 3283 if (ShiftAmt && ShiftAmt->getAPIntValue() == (BitWidth - 1)) { 3284 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA; 3285 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT)) 3286 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1)); 3287 } 3288 } 3289 3290 // 0 - X --> 0 if the sub is NUW. 3291 if (N->getFlags().hasNoUnsignedWrap()) 3292 return N0; 3293 3294 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) { 3295 // N1 is either 0 or the minimum signed value. If the sub is NSW, then 3296 // N1 must be 0 because negating the minimum signed value is undefined. 3297 if (N->getFlags().hasNoSignedWrap()) 3298 return N0; 3299 3300 // 0 - X --> X if X is 0 or the minimum signed value. 3301 return N1; 3302 } 3303 3304 // Convert 0 - abs(x). 3305 SDValue Result; 3306 if (N1->getOpcode() == ISD::ABS && 3307 !TLI.isOperationLegalOrCustom(ISD::ABS, VT) && 3308 TLI.expandABS(N1.getNode(), Result, DAG, true)) 3309 return Result; 3310 } 3311 3312 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 3313 if (isAllOnesOrAllOnesSplat(N0)) 3314 return DAG.getNode(ISD::XOR, DL, VT, N1, N0); 3315 3316 // fold (A - (0-B)) -> A+B 3317 if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0))) 3318 return DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(1)); 3319 3320 // fold A-(A-B) -> B 3321 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 3322 return N1.getOperand(1); 3323 3324 // fold (A+B)-A -> B 3325 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 3326 return N0.getOperand(1); 3327 3328 // fold (A+B)-B -> A 3329 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 3330 return N0.getOperand(0); 3331 3332 // fold (A+C1)-C2 -> A+(C1-C2) 3333 if (N0.getOpcode() == ISD::ADD && 3334 isConstantOrConstantVector(N1, /* NoOpaques */ true) && 3335 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) { 3336 SDValue NewC = 3337 DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0.getOperand(1), N1}); 3338 assert(NewC && "Constant folding failed"); 3339 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), NewC); 3340 } 3341 3342 // fold C2-(A+C1) -> (C2-C1)-A 3343 if (N1.getOpcode() == ISD::ADD) { 3344 SDValue N11 = N1.getOperand(1); 3345 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) && 3346 isConstantOrConstantVector(N11, /* NoOpaques */ true)) { 3347 SDValue NewC = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0, N11}); 3348 assert(NewC && "Constant folding failed"); 3349 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0)); 3350 } 3351 } 3352 3353 // fold (A-C1)-C2 -> A-(C1+C2) 3354 if (N0.getOpcode() == ISD::SUB && 3355 isConstantOrConstantVector(N1, /* NoOpaques */ true) && 3356 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) { 3357 SDValue NewC = 3358 DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N0.getOperand(1), N1}); 3359 assert(NewC && "Constant folding failed"); 3360 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), NewC); 3361 } 3362 3363 // fold (c1-A)-c2 -> (c1-c2)-A 3364 if (N0.getOpcode() == ISD::SUB && 3365 isConstantOrConstantVector(N1, /* NoOpaques */ true) && 3366 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaques */ true)) { 3367 SDValue NewC = 3368 DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0.getOperand(0), N1}); 3369 assert(NewC && "Constant folding failed"); 3370 return DAG.getNode(ISD::SUB, DL, VT, NewC, N0.getOperand(1)); 3371 } 3372 3373 // fold ((A+(B+or-C))-B) -> A+or-C 3374 if (N0.getOpcode() == ISD::ADD && 3375 (N0.getOperand(1).getOpcode() == ISD::SUB || 3376 N0.getOperand(1).getOpcode() == ISD::ADD) && 3377 N0.getOperand(1).getOperand(0) == N1) 3378 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0), 3379 N0.getOperand(1).getOperand(1)); 3380 3381 // fold ((A+(C+B))-B) -> A+C 3382 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD && 3383 N0.getOperand(1).getOperand(1) == N1) 3384 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), 3385 N0.getOperand(1).getOperand(0)); 3386 3387 // fold ((A-(B-C))-C) -> A-B 3388 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB && 3389 N0.getOperand(1).getOperand(1) == N1) 3390 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), 3391 N0.getOperand(1).getOperand(0)); 3392 3393 // fold (A-(B-C)) -> A+(C-B) 3394 if (N1.getOpcode() == ISD::SUB && N1.hasOneUse()) 3395 return DAG.getNode(ISD::ADD, DL, VT, N0, 3396 DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(1), 3397 N1.getOperand(0))); 3398 3399 // A - (A & B) -> A & (~B) 3400 if (N1.getOpcode() == ISD::AND) { 3401 SDValue A = N1.getOperand(0); 3402 SDValue B = N1.getOperand(1); 3403 if (A != N0) 3404 std::swap(A, B); 3405 if (A == N0 && 3406 (N1.hasOneUse() || isConstantOrConstantVector(B, /*NoOpaques=*/true))) { 3407 SDValue InvB = 3408 DAG.getNode(ISD::XOR, DL, VT, B, DAG.getAllOnesConstant(DL, VT)); 3409 return DAG.getNode(ISD::AND, DL, VT, A, InvB); 3410 } 3411 } 3412 3413 // fold (X - (-Y * Z)) -> (X + (Y * Z)) 3414 if (N1.getOpcode() == ISD::MUL && N1.hasOneUse()) { 3415 if (N1.getOperand(0).getOpcode() == ISD::SUB && 3416 isNullOrNullSplat(N1.getOperand(0).getOperand(0))) { 3417 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, 3418 N1.getOperand(0).getOperand(1), 3419 N1.getOperand(1)); 3420 return DAG.getNode(ISD::ADD, DL, VT, N0, Mul); 3421 } 3422 if (N1.getOperand(1).getOpcode() == ISD::SUB && 3423 isNullOrNullSplat(N1.getOperand(1).getOperand(0))) { 3424 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, 3425 N1.getOperand(0), 3426 N1.getOperand(1).getOperand(1)); 3427 return DAG.getNode(ISD::ADD, DL, VT, N0, Mul); 3428 } 3429 } 3430 3431 // If either operand of a sub is undef, the result is undef 3432 if (N0.isUndef()) 3433 return N0; 3434 if (N1.isUndef()) 3435 return N1; 3436 3437 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG)) 3438 return V; 3439 3440 if (SDValue V = foldAddSubOfSignBit(N, DAG)) 3441 return V; 3442 3443 if (SDValue V = foldAddSubMasked1(false, N0, N1, DAG, SDLoc(N))) 3444 return V; 3445 3446 if (SDValue V = foldSubToUSubSat(VT, N)) 3447 return V; 3448 3449 // (x - y) - 1 -> add (xor y, -1), x 3450 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB && isOneOrOneSplat(N1)) { 3451 SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 3452 DAG.getAllOnesConstant(DL, VT)); 3453 return DAG.getNode(ISD::ADD, DL, VT, Xor, N0.getOperand(0)); 3454 } 3455 3456 // Look for: 3457 // sub y, (xor x, -1) 3458 // And if the target does not like this form then turn into: 3459 // add (add x, y), 1 3460 if (TLI.preferIncOfAddToSubOfNot(VT) && N1.hasOneUse() && isBitwiseNot(N1)) { 3461 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(0)); 3462 return DAG.getNode(ISD::ADD, DL, VT, Add, DAG.getConstant(1, DL, VT)); 3463 } 3464 3465 // Hoist one-use addition by non-opaque constant: 3466 // (x + C) - y -> (x - y) + C 3467 if (N0.hasOneUse() && N0.getOpcode() == ISD::ADD && 3468 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) { 3469 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1); 3470 return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(1)); 3471 } 3472 // y - (x + C) -> (y - x) - C 3473 if (N1.hasOneUse() && N1.getOpcode() == ISD::ADD && 3474 isConstantOrConstantVector(N1.getOperand(1), /*NoOpaques=*/true)) { 3475 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(0)); 3476 return DAG.getNode(ISD::SUB, DL, VT, Sub, N1.getOperand(1)); 3477 } 3478 // (x - C) - y -> (x - y) - C 3479 // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors. 3480 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB && 3481 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) { 3482 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1); 3483 return DAG.getNode(ISD::SUB, DL, VT, Sub, N0.getOperand(1)); 3484 } 3485 // (C - x) - y -> C - (x + y) 3486 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB && 3487 isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) { 3488 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1), N1); 3489 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), Add); 3490 } 3491 3492 // If the target's bool is represented as 0/-1, prefer to make this 'add 0/-1' 3493 // rather than 'sub 0/1' (the sext should get folded). 3494 // sub X, (zext i1 Y) --> add X, (sext i1 Y) 3495 if (N1.getOpcode() == ISD::ZERO_EXTEND && 3496 N1.getOperand(0).getScalarValueSizeInBits() == 1 && 3497 TLI.getBooleanContents(VT) == 3498 TargetLowering::ZeroOrNegativeOneBooleanContent) { 3499 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N1.getOperand(0)); 3500 return DAG.getNode(ISD::ADD, DL, VT, N0, SExt); 3501 } 3502 3503 // fold Y = sra (X, size(X)-1); sub (xor (X, Y), Y) -> (abs X) 3504 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) { 3505 if (N0.getOpcode() == ISD::XOR && N1.getOpcode() == ISD::SRA) { 3506 SDValue X0 = N0.getOperand(0), X1 = N0.getOperand(1); 3507 SDValue S0 = N1.getOperand(0); 3508 if ((X0 == S0 && X1 == N1) || (X0 == N1 && X1 == S0)) 3509 if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1))) 3510 if (C->getAPIntValue() == (VT.getScalarSizeInBits() - 1)) 3511 return DAG.getNode(ISD::ABS, SDLoc(N), VT, S0); 3512 } 3513 } 3514 3515 // If the relocation model supports it, consider symbol offsets. 3516 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 3517 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 3518 // fold (sub Sym, c) -> Sym-c 3519 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 3520 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 3521 GA->getOffset() - 3522 (uint64_t)N1C->getSExtValue()); 3523 // fold (sub Sym+c1, Sym+c2) -> c1-c2 3524 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 3525 if (GA->getGlobal() == GB->getGlobal()) 3526 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 3527 DL, VT); 3528 } 3529 3530 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 3531 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 3532 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 3533 if (TN->getVT() == MVT::i1) { 3534 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 3535 DAG.getConstant(1, DL, VT)); 3536 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 3537 } 3538 } 3539 3540 // canonicalize (sub X, (vscale * C)) to (add X, (vscale * -C)) 3541 if (N1.getOpcode() == ISD::VSCALE) { 3542 const APInt &IntVal = N1.getConstantOperandAPInt(0); 3543 return DAG.getNode(ISD::ADD, DL, VT, N0, DAG.getVScale(DL, VT, -IntVal)); 3544 } 3545 3546 // canonicalize (sub X, step_vector(C)) to (add X, step_vector(-C)) 3547 if (N1.getOpcode() == ISD::STEP_VECTOR && N1.hasOneUse()) { 3548 SDValue NewStep = DAG.getConstant(-N1.getConstantOperandAPInt(0), DL, 3549 N1.getOperand(0).getValueType()); 3550 return DAG.getNode(ISD::ADD, DL, VT, N0, 3551 DAG.getStepVector(DL, VT, NewStep)); 3552 } 3553 3554 // Prefer an add for more folding potential and possibly better codegen: 3555 // sub N0, (lshr N10, width-1) --> add N0, (ashr N10, width-1) 3556 if (!LegalOperations && N1.getOpcode() == ISD::SRL && N1.hasOneUse()) { 3557 SDValue ShAmt = N1.getOperand(1); 3558 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt); 3559 if (ShAmtC && 3560 ShAmtC->getAPIntValue() == (N1.getScalarValueSizeInBits() - 1)) { 3561 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, N1.getOperand(0), ShAmt); 3562 return DAG.getNode(ISD::ADD, DL, VT, N0, SRA); 3563 } 3564 } 3565 3566 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) { 3567 // (sub Carry, X) -> (addcarry (sub 0, X), 0, Carry) 3568 if (SDValue Carry = getAsCarry(TLI, N0)) { 3569 SDValue X = N1; 3570 SDValue Zero = DAG.getConstant(0, DL, VT); 3571 SDValue NegX = DAG.getNode(ISD::SUB, DL, VT, Zero, X); 3572 return DAG.getNode(ISD::ADDCARRY, DL, 3573 DAG.getVTList(VT, Carry.getValueType()), NegX, Zero, 3574 Carry); 3575 } 3576 } 3577 3578 return SDValue(); 3579 } 3580 3581 SDValue DAGCombiner::visitSUBSAT(SDNode *N) { 3582 SDValue N0 = N->getOperand(0); 3583 SDValue N1 = N->getOperand(1); 3584 EVT VT = N0.getValueType(); 3585 SDLoc DL(N); 3586 3587 // fold vector ops 3588 if (VT.isVector()) { 3589 // TODO SimplifyVBinOp 3590 3591 // fold (sub_sat x, 0) -> x, vector edition 3592 if (ISD::isConstantSplatVectorAllZeros(N1.getNode())) 3593 return N0; 3594 } 3595 3596 // fold (sub_sat x, undef) -> 0 3597 if (N0.isUndef() || N1.isUndef()) 3598 return DAG.getConstant(0, DL, VT); 3599 3600 // fold (sub_sat x, x) -> 0 3601 if (N0 == N1) 3602 return DAG.getConstant(0, DL, VT); 3603 3604 // fold (sub_sat c1, c2) -> c3 3605 if (SDValue C = DAG.FoldConstantArithmetic(N->getOpcode(), DL, VT, {N0, N1})) 3606 return C; 3607 3608 // fold (sub_sat x, 0) -> x 3609 if (isNullConstant(N1)) 3610 return N0; 3611 3612 return SDValue(); 3613 } 3614 3615 SDValue DAGCombiner::visitSUBC(SDNode *N) { 3616 SDValue N0 = N->getOperand(0); 3617 SDValue N1 = N->getOperand(1); 3618 EVT VT = N0.getValueType(); 3619 SDLoc DL(N); 3620 3621 // If the flag result is dead, turn this into an SUB. 3622 if (!N->hasAnyUseOfValue(1)) 3623 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 3624 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 3625 3626 // fold (subc x, x) -> 0 + no borrow 3627 if (N0 == N1) 3628 return CombineTo(N, DAG.getConstant(0, DL, VT), 3629 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 3630 3631 // fold (subc x, 0) -> x + no borrow 3632 if (isNullConstant(N1)) 3633 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 3634 3635 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 3636 if (isAllOnesConstant(N0)) 3637 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 3638 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 3639 3640 return SDValue(); 3641 } 3642 3643 SDValue DAGCombiner::visitSUBO(SDNode *N) { 3644 SDValue N0 = N->getOperand(0); 3645 SDValue N1 = N->getOperand(1); 3646 EVT VT = N0.getValueType(); 3647 bool IsSigned = (ISD::SSUBO == N->getOpcode()); 3648 3649 EVT CarryVT = N->getValueType(1); 3650 SDLoc DL(N); 3651 3652 // If the flag result is dead, turn this into an SUB. 3653 if (!N->hasAnyUseOfValue(1)) 3654 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 3655 DAG.getUNDEF(CarryVT)); 3656 3657 // fold (subo x, x) -> 0 + no borrow 3658 if (N0 == N1) 3659 return CombineTo(N, DAG.getConstant(0, DL, VT), 3660 DAG.getConstant(0, DL, CarryVT)); 3661 3662 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 3663 3664 // fold (subox, c) -> (addo x, -c) 3665 if (IsSigned && N1C && !N1C->getAPIntValue().isMinSignedValue()) { 3666 return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0, 3667 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 3668 } 3669 3670 // fold (subo x, 0) -> x + no borrow 3671 if (isNullOrNullSplat(N1)) 3672 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 3673 3674 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow 3675 if (!IsSigned && isAllOnesOrAllOnesSplat(N0)) 3676 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 3677 DAG.getConstant(0, DL, CarryVT)); 3678 3679 return SDValue(); 3680 } 3681 3682 SDValue DAGCombiner::visitSUBE(SDNode *N) { 3683 SDValue N0 = N->getOperand(0); 3684 SDValue N1 = N->getOperand(1); 3685 SDValue CarryIn = N->getOperand(2); 3686 3687 // fold (sube x, y, false) -> (subc x, y) 3688 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 3689 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 3690 3691 return SDValue(); 3692 } 3693 3694 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) { 3695 SDValue N0 = N->getOperand(0); 3696 SDValue N1 = N->getOperand(1); 3697 SDValue CarryIn = N->getOperand(2); 3698 3699 // fold (subcarry x, y, false) -> (usubo x, y) 3700 if (isNullConstant(CarryIn)) { 3701 if (!LegalOperations || 3702 TLI.isOperationLegalOrCustom(ISD::USUBO, N->getValueType(0))) 3703 return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1); 3704 } 3705 3706 return SDValue(); 3707 } 3708 3709 SDValue DAGCombiner::visitSSUBO_CARRY(SDNode *N) { 3710 SDValue N0 = N->getOperand(0); 3711 SDValue N1 = N->getOperand(1); 3712 SDValue CarryIn = N->getOperand(2); 3713 3714 // fold (ssubo_carry x, y, false) -> (ssubo x, y) 3715 if (isNullConstant(CarryIn)) { 3716 if (!LegalOperations || 3717 TLI.isOperationLegalOrCustom(ISD::SSUBO, N->getValueType(0))) 3718 return DAG.getNode(ISD::SSUBO, SDLoc(N), N->getVTList(), N0, N1); 3719 } 3720 3721 return SDValue(); 3722 } 3723 3724 // Notice that "mulfix" can be any of SMULFIX, SMULFIXSAT, UMULFIX and 3725 // UMULFIXSAT here. 3726 SDValue DAGCombiner::visitMULFIX(SDNode *N) { 3727 SDValue N0 = N->getOperand(0); 3728 SDValue N1 = N->getOperand(1); 3729 SDValue Scale = N->getOperand(2); 3730 EVT VT = N0.getValueType(); 3731 3732 // fold (mulfix x, undef, scale) -> 0 3733 if (N0.isUndef() || N1.isUndef()) 3734 return DAG.getConstant(0, SDLoc(N), VT); 3735 3736 // Canonicalize constant to RHS (vector doesn't have to splat) 3737 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3738 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3739 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0, Scale); 3740 3741 // fold (mulfix x, 0, scale) -> 0 3742 if (isNullConstant(N1)) 3743 return DAG.getConstant(0, SDLoc(N), VT); 3744 3745 return SDValue(); 3746 } 3747 3748 SDValue DAGCombiner::visitMUL(SDNode *N) { 3749 SDValue N0 = N->getOperand(0); 3750 SDValue N1 = N->getOperand(1); 3751 EVT VT = N0.getValueType(); 3752 3753 // fold (mul x, undef) -> 0 3754 if (N0.isUndef() || N1.isUndef()) 3755 return DAG.getConstant(0, SDLoc(N), VT); 3756 3757 bool N1IsConst = false; 3758 bool N1IsOpaqueConst = false; 3759 APInt ConstValue1; 3760 3761 // fold vector ops 3762 if (VT.isVector()) { 3763 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3764 return FoldedVOp; 3765 3766 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1); 3767 assert((!N1IsConst || 3768 ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) && 3769 "Splat APInt should be element width"); 3770 } else { 3771 N1IsConst = isa<ConstantSDNode>(N1); 3772 if (N1IsConst) { 3773 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 3774 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 3775 } 3776 } 3777 3778 // fold (mul c1, c2) -> c1*c2 3779 if (SDValue C = DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, {N0, N1})) 3780 return C; 3781 3782 // canonicalize constant to RHS (vector doesn't have to splat) 3783 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3784 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3785 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 3786 3787 // fold (mul x, 0) -> 0 3788 if (N1IsConst && ConstValue1.isNullValue()) 3789 return N1; 3790 3791 // fold (mul x, 1) -> x 3792 if (N1IsConst && ConstValue1.isOneValue()) 3793 return N0; 3794 3795 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3796 return NewSel; 3797 3798 // fold (mul x, -1) -> 0-x 3799 if (N1IsConst && ConstValue1.isAllOnesValue()) { 3800 SDLoc DL(N); 3801 return DAG.getNode(ISD::SUB, DL, VT, 3802 DAG.getConstant(0, DL, VT), N0); 3803 } 3804 3805 // fold (mul x, (1 << c)) -> x << c 3806 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 3807 DAG.isKnownToBeAPowerOfTwo(N1) && 3808 (!VT.isVector() || Level <= AfterLegalizeVectorOps)) { 3809 SDLoc DL(N); 3810 SDValue LogBase2 = BuildLogBase2(N1, DL); 3811 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 3812 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 3813 return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc); 3814 } 3815 3816 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 3817 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2()) { 3818 unsigned Log2Val = (-ConstValue1).logBase2(); 3819 SDLoc DL(N); 3820 // FIXME: If the input is something that is easily negated (e.g. a 3821 // single-use add), we should put the negate there. 3822 return DAG.getNode(ISD::SUB, DL, VT, 3823 DAG.getConstant(0, DL, VT), 3824 DAG.getNode(ISD::SHL, DL, VT, N0, 3825 DAG.getConstant(Log2Val, DL, 3826 getShiftAmountTy(N0.getValueType())))); 3827 } 3828 3829 // Try to transform: 3830 // (1) multiply-by-(power-of-2 +/- 1) into shift and add/sub. 3831 // mul x, (2^N + 1) --> add (shl x, N), x 3832 // mul x, (2^N - 1) --> sub (shl x, N), x 3833 // Examples: x * 33 --> (x << 5) + x 3834 // x * 15 --> (x << 4) - x 3835 // x * -33 --> -((x << 5) + x) 3836 // x * -15 --> -((x << 4) - x) ; this reduces --> x - (x << 4) 3837 // (2) multiply-by-(power-of-2 +/- power-of-2) into shifts and add/sub. 3838 // mul x, (2^N + 2^M) --> (add (shl x, N), (shl x, M)) 3839 // mul x, (2^N - 2^M) --> (sub (shl x, N), (shl x, M)) 3840 // Examples: x * 0x8800 --> (x << 15) + (x << 11) 3841 // x * 0xf800 --> (x << 16) - (x << 11) 3842 // x * -0x8800 --> -((x << 15) + (x << 11)) 3843 // x * -0xf800 --> -((x << 16) - (x << 11)) ; (x << 11) - (x << 16) 3844 if (N1IsConst && TLI.decomposeMulByConstant(*DAG.getContext(), VT, N1)) { 3845 // TODO: We could handle more general decomposition of any constant by 3846 // having the target set a limit on number of ops and making a 3847 // callback to determine that sequence (similar to sqrt expansion). 3848 unsigned MathOp = ISD::DELETED_NODE; 3849 APInt MulC = ConstValue1.abs(); 3850 // The constant `2` should be treated as (2^0 + 1). 3851 unsigned TZeros = MulC == 2 ? 0 : MulC.countTrailingZeros(); 3852 MulC.lshrInPlace(TZeros); 3853 if ((MulC - 1).isPowerOf2()) 3854 MathOp = ISD::ADD; 3855 else if ((MulC + 1).isPowerOf2()) 3856 MathOp = ISD::SUB; 3857 3858 if (MathOp != ISD::DELETED_NODE) { 3859 unsigned ShAmt = 3860 MathOp == ISD::ADD ? (MulC - 1).logBase2() : (MulC + 1).logBase2(); 3861 ShAmt += TZeros; 3862 assert(ShAmt < VT.getScalarSizeInBits() && 3863 "multiply-by-constant generated out of bounds shift"); 3864 SDLoc DL(N); 3865 SDValue Shl = 3866 DAG.getNode(ISD::SHL, DL, VT, N0, DAG.getConstant(ShAmt, DL, VT)); 3867 SDValue R = 3868 TZeros ? DAG.getNode(MathOp, DL, VT, Shl, 3869 DAG.getNode(ISD::SHL, DL, VT, N0, 3870 DAG.getConstant(TZeros, DL, VT))) 3871 : DAG.getNode(MathOp, DL, VT, Shl, N0); 3872 if (ConstValue1.isNegative()) 3873 R = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), R); 3874 return R; 3875 } 3876 } 3877 3878 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 3879 if (N0.getOpcode() == ISD::SHL && 3880 isConstantOrConstantVector(N1, /* NoOpaques */ true) && 3881 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) { 3882 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1)); 3883 if (isConstantOrConstantVector(C3)) 3884 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3); 3885 } 3886 3887 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 3888 // use. 3889 { 3890 SDValue Sh(nullptr, 0), Y(nullptr, 0); 3891 3892 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 3893 if (N0.getOpcode() == ISD::SHL && 3894 isConstantOrConstantVector(N0.getOperand(1)) && 3895 N0.getNode()->hasOneUse()) { 3896 Sh = N0; Y = N1; 3897 } else if (N1.getOpcode() == ISD::SHL && 3898 isConstantOrConstantVector(N1.getOperand(1)) && 3899 N1.getNode()->hasOneUse()) { 3900 Sh = N1; Y = N0; 3901 } 3902 3903 if (Sh.getNode()) { 3904 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y); 3905 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1)); 3906 } 3907 } 3908 3909 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 3910 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 3911 N0.getOpcode() == ISD::ADD && 3912 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 3913 isMulAddWithConstProfitable(N, N0, N1)) 3914 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 3915 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 3916 N0.getOperand(0), N1), 3917 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 3918 N0.getOperand(1), N1)); 3919 3920 // Fold (mul (vscale * C0), C1) to (vscale * (C0 * C1)). 3921 if (N0.getOpcode() == ISD::VSCALE) 3922 if (ConstantSDNode *NC1 = isConstOrConstSplat(N1)) { 3923 const APInt &C0 = N0.getConstantOperandAPInt(0); 3924 const APInt &C1 = NC1->getAPIntValue(); 3925 return DAG.getVScale(SDLoc(N), VT, C0 * C1); 3926 } 3927 3928 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)). 3929 APInt MulVal; 3930 if (N0.getOpcode() == ISD::STEP_VECTOR) 3931 if (ISD::isConstantSplatVector(N1.getNode(), MulVal)) { 3932 const APInt &C0 = N0.getConstantOperandAPInt(0); 3933 EVT SVT = N0.getOperand(0).getValueType(); 3934 SDValue NewStep = DAG.getConstant( 3935 C0 * MulVal.sextOrTrunc(SVT.getSizeInBits()), SDLoc(N), SVT); 3936 return DAG.getStepVector(SDLoc(N), VT, NewStep); 3937 } 3938 3939 // Fold ((mul x, 0/undef) -> 0, 3940 // (mul x, 1) -> x) -> x) 3941 // -> and(x, mask) 3942 // We can replace vectors with '0' and '1' factors with a clearing mask. 3943 if (VT.isFixedLengthVector()) { 3944 unsigned NumElts = VT.getVectorNumElements(); 3945 SmallBitVector ClearMask; 3946 ClearMask.reserve(NumElts); 3947 auto IsClearMask = [&ClearMask](ConstantSDNode *V) { 3948 if (!V || V->isNullValue()) { 3949 ClearMask.push_back(true); 3950 return true; 3951 } 3952 ClearMask.push_back(false); 3953 return V->isOne(); 3954 }; 3955 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::AND, VT)) && 3956 ISD::matchUnaryPredicate(N1, IsClearMask, /*AllowUndefs*/ true)) { 3957 assert(N1.getOpcode() == ISD::BUILD_VECTOR && "Unknown constant vector"); 3958 SDLoc DL(N); 3959 EVT LegalSVT = N1.getOperand(0).getValueType(); 3960 SDValue Zero = DAG.getConstant(0, DL, LegalSVT); 3961 SDValue AllOnes = DAG.getAllOnesConstant(DL, LegalSVT); 3962 SmallVector<SDValue, 16> Mask(NumElts, AllOnes); 3963 for (unsigned I = 0; I != NumElts; ++I) 3964 if (ClearMask[I]) 3965 Mask[I] = Zero; 3966 return DAG.getNode(ISD::AND, DL, VT, N0, DAG.getBuildVector(VT, DL, Mask)); 3967 } 3968 } 3969 3970 // reassociate mul 3971 if (SDValue RMUL = reassociateOps(ISD::MUL, SDLoc(N), N0, N1, N->getFlags())) 3972 return RMUL; 3973 3974 return SDValue(); 3975 } 3976 3977 /// Return true if divmod libcall is available. 3978 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 3979 const TargetLowering &TLI) { 3980 RTLIB::Libcall LC; 3981 EVT NodeType = Node->getValueType(0); 3982 if (!NodeType.isSimple()) 3983 return false; 3984 switch (NodeType.getSimpleVT().SimpleTy) { 3985 default: return false; // No libcall for vector types. 3986 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 3987 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 3988 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 3989 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 3990 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 3991 } 3992 3993 return TLI.getLibcallName(LC) != nullptr; 3994 } 3995 3996 /// Issue divrem if both quotient and remainder are needed. 3997 SDValue DAGCombiner::useDivRem(SDNode *Node) { 3998 if (Node->use_empty()) 3999 return SDValue(); // This is a dead node, leave it alone. 4000 4001 unsigned Opcode = Node->getOpcode(); 4002 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 4003 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 4004 4005 // DivMod lib calls can still work on non-legal types if using lib-calls. 4006 EVT VT = Node->getValueType(0); 4007 if (VT.isVector() || !VT.isInteger()) 4008 return SDValue(); 4009 4010 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) 4011 return SDValue(); 4012 4013 // If DIVREM is going to get expanded into a libcall, 4014 // but there is no libcall available, then don't combine. 4015 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 4016 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 4017 return SDValue(); 4018 4019 // If div is legal, it's better to do the normal expansion 4020 unsigned OtherOpcode = 0; 4021 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 4022 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 4023 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 4024 return SDValue(); 4025 } else { 4026 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 4027 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 4028 return SDValue(); 4029 } 4030 4031 SDValue Op0 = Node->getOperand(0); 4032 SDValue Op1 = Node->getOperand(1); 4033 SDValue combined; 4034 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 4035 UE = Op0.getNode()->use_end(); UI != UE; ++UI) { 4036 SDNode *User = *UI; 4037 if (User == Node || User->getOpcode() == ISD::DELETED_NODE || 4038 User->use_empty()) 4039 continue; 4040 // Convert the other matching node(s), too; 4041 // otherwise, the DIVREM may get target-legalized into something 4042 // target-specific that we won't be able to recognize. 4043 unsigned UserOpc = User->getOpcode(); 4044 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 4045 User->getOperand(0) == Op0 && 4046 User->getOperand(1) == Op1) { 4047 if (!combined) { 4048 if (UserOpc == OtherOpcode) { 4049 SDVTList VTs = DAG.getVTList(VT, VT); 4050 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 4051 } else if (UserOpc == DivRemOpc) { 4052 combined = SDValue(User, 0); 4053 } else { 4054 assert(UserOpc == Opcode); 4055 continue; 4056 } 4057 } 4058 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 4059 CombineTo(User, combined); 4060 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 4061 CombineTo(User, combined.getValue(1)); 4062 } 4063 } 4064 return combined; 4065 } 4066 4067 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) { 4068 SDValue N0 = N->getOperand(0); 4069 SDValue N1 = N->getOperand(1); 4070 EVT VT = N->getValueType(0); 4071 SDLoc DL(N); 4072 4073 unsigned Opc = N->getOpcode(); 4074 bool IsDiv = (ISD::SDIV == Opc) || (ISD::UDIV == Opc); 4075 ConstantSDNode *N1C = isConstOrConstSplat(N1); 4076 4077 // X / undef -> undef 4078 // X % undef -> undef 4079 // X / 0 -> undef 4080 // X % 0 -> undef 4081 // NOTE: This includes vectors where any divisor element is zero/undef. 4082 if (DAG.isUndef(Opc, {N0, N1})) 4083 return DAG.getUNDEF(VT); 4084 4085 // undef / X -> 0 4086 // undef % X -> 0 4087 if (N0.isUndef()) 4088 return DAG.getConstant(0, DL, VT); 4089 4090 // 0 / X -> 0 4091 // 0 % X -> 0 4092 ConstantSDNode *N0C = isConstOrConstSplat(N0); 4093 if (N0C && N0C->isNullValue()) 4094 return N0; 4095 4096 // X / X -> 1 4097 // X % X -> 0 4098 if (N0 == N1) 4099 return DAG.getConstant(IsDiv ? 1 : 0, DL, VT); 4100 4101 // X / 1 -> X 4102 // X % 1 -> 0 4103 // If this is a boolean op (single-bit element type), we can't have 4104 // division-by-zero or remainder-by-zero, so assume the divisor is 1. 4105 // TODO: Similarly, if we're zero-extending a boolean divisor, then assume 4106 // it's a 1. 4107 if ((N1C && N1C->isOne()) || (VT.getScalarType() == MVT::i1)) 4108 return IsDiv ? N0 : DAG.getConstant(0, DL, VT); 4109 4110 return SDValue(); 4111 } 4112 4113 SDValue DAGCombiner::visitSDIV(SDNode *N) { 4114 SDValue N0 = N->getOperand(0); 4115 SDValue N1 = N->getOperand(1); 4116 EVT VT = N->getValueType(0); 4117 EVT CCVT = getSetCCResultType(VT); 4118 4119 // fold vector ops 4120 if (VT.isVector()) 4121 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4122 return FoldedVOp; 4123 4124 SDLoc DL(N); 4125 4126 // fold (sdiv c1, c2) -> c1/c2 4127 ConstantSDNode *N1C = isConstOrConstSplat(N1); 4128 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, {N0, N1})) 4129 return C; 4130 4131 // fold (sdiv X, -1) -> 0-X 4132 if (N1C && N1C->isAllOnesValue()) 4133 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0); 4134 4135 // fold (sdiv X, MIN_SIGNED) -> select(X == MIN_SIGNED, 1, 0) 4136 if (N1C && N1C->getAPIntValue().isMinSignedValue()) 4137 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ), 4138 DAG.getConstant(1, DL, VT), 4139 DAG.getConstant(0, DL, VT)); 4140 4141 if (SDValue V = simplifyDivRem(N, DAG)) 4142 return V; 4143 4144 if (SDValue NewSel = foldBinOpIntoSelect(N)) 4145 return NewSel; 4146 4147 // If we know the sign bits of both operands are zero, strength reduce to a 4148 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 4149 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 4150 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 4151 4152 if (SDValue V = visitSDIVLike(N0, N1, N)) { 4153 // If the corresponding remainder node exists, update its users with 4154 // (Dividend - (Quotient * Divisor). 4155 if (SDNode *RemNode = DAG.getNodeIfExists(ISD::SREM, N->getVTList(), 4156 { N0, N1 })) { 4157 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1); 4158 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 4159 AddToWorklist(Mul.getNode()); 4160 AddToWorklist(Sub.getNode()); 4161 CombineTo(RemNode, Sub); 4162 } 4163 return V; 4164 } 4165 4166 // sdiv, srem -> sdivrem 4167 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 4168 // true. Otherwise, we break the simplification logic in visitREM(). 4169 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4170 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 4171 if (SDValue DivRem = useDivRem(N)) 4172 return DivRem; 4173 4174 return SDValue(); 4175 } 4176 4177 SDValue DAGCombiner::visitSDIVLike(SDValue N0, SDValue N1, SDNode *N) { 4178 SDLoc DL(N); 4179 EVT VT = N->getValueType(0); 4180 EVT CCVT = getSetCCResultType(VT); 4181 unsigned BitWidth = VT.getScalarSizeInBits(); 4182 4183 // Helper for determining whether a value is a power-2 constant scalar or a 4184 // vector of such elements. 4185 auto IsPowerOfTwo = [](ConstantSDNode *C) { 4186 if (C->isNullValue() || C->isOpaque()) 4187 return false; 4188 if (C->getAPIntValue().isPowerOf2()) 4189 return true; 4190 if ((-C->getAPIntValue()).isPowerOf2()) 4191 return true; 4192 return false; 4193 }; 4194 4195 // fold (sdiv X, pow2) -> simple ops after legalize 4196 // FIXME: We check for the exact bit here because the generic lowering gives 4197 // better results in that case. The target-specific lowering should learn how 4198 // to handle exact sdivs efficiently. 4199 if (!N->getFlags().hasExact() && ISD::matchUnaryPredicate(N1, IsPowerOfTwo)) { 4200 // Target-specific implementation of sdiv x, pow2. 4201 if (SDValue Res = BuildSDIVPow2(N)) 4202 return Res; 4203 4204 // Create constants that are functions of the shift amount value. 4205 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); 4206 SDValue Bits = DAG.getConstant(BitWidth, DL, ShiftAmtTy); 4207 SDValue C1 = DAG.getNode(ISD::CTTZ, DL, VT, N1); 4208 C1 = DAG.getZExtOrTrunc(C1, DL, ShiftAmtTy); 4209 SDValue Inexact = DAG.getNode(ISD::SUB, DL, ShiftAmtTy, Bits, C1); 4210 if (!isConstantOrConstantVector(Inexact)) 4211 return SDValue(); 4212 4213 // Splat the sign bit into the register 4214 SDValue Sign = DAG.getNode(ISD::SRA, DL, VT, N0, 4215 DAG.getConstant(BitWidth - 1, DL, ShiftAmtTy)); 4216 AddToWorklist(Sign.getNode()); 4217 4218 // Add (N0 < 0) ? abs2 - 1 : 0; 4219 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, Sign, Inexact); 4220 AddToWorklist(Srl.getNode()); 4221 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Srl); 4222 AddToWorklist(Add.getNode()); 4223 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Add, C1); 4224 AddToWorklist(Sra.getNode()); 4225 4226 // Special case: (sdiv X, 1) -> X 4227 // Special Case: (sdiv X, -1) -> 0-X 4228 SDValue One = DAG.getConstant(1, DL, VT); 4229 SDValue AllOnes = DAG.getAllOnesConstant(DL, VT); 4230 SDValue IsOne = DAG.getSetCC(DL, CCVT, N1, One, ISD::SETEQ); 4231 SDValue IsAllOnes = DAG.getSetCC(DL, CCVT, N1, AllOnes, ISD::SETEQ); 4232 SDValue IsOneOrAllOnes = DAG.getNode(ISD::OR, DL, CCVT, IsOne, IsAllOnes); 4233 Sra = DAG.getSelect(DL, VT, IsOneOrAllOnes, N0, Sra); 4234 4235 // If dividing by a positive value, we're done. Otherwise, the result must 4236 // be negated. 4237 SDValue Zero = DAG.getConstant(0, DL, VT); 4238 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, Zero, Sra); 4239 4240 // FIXME: Use SELECT_CC once we improve SELECT_CC constant-folding. 4241 SDValue IsNeg = DAG.getSetCC(DL, CCVT, N1, Zero, ISD::SETLT); 4242 SDValue Res = DAG.getSelect(DL, VT, IsNeg, Sub, Sra); 4243 return Res; 4244 } 4245 4246 // If integer divide is expensive and we satisfy the requirements, emit an 4247 // alternate sequence. Targets may check function attributes for size/speed 4248 // trade-offs. 4249 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4250 if (isConstantOrConstantVector(N1) && 4251 !TLI.isIntDivCheap(N->getValueType(0), Attr)) 4252 if (SDValue Op = BuildSDIV(N)) 4253 return Op; 4254 4255 return SDValue(); 4256 } 4257 4258 SDValue DAGCombiner::visitUDIV(SDNode *N) { 4259 SDValue N0 = N->getOperand(0); 4260 SDValue N1 = N->getOperand(1); 4261 EVT VT = N->getValueType(0); 4262 EVT CCVT = getSetCCResultType(VT); 4263 4264 // fold vector ops 4265 if (VT.isVector()) 4266 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4267 return FoldedVOp; 4268 4269 SDLoc DL(N); 4270 4271 // fold (udiv c1, c2) -> c1/c2 4272 ConstantSDNode *N1C = isConstOrConstSplat(N1); 4273 if (SDValue C = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, {N0, N1})) 4274 return C; 4275 4276 // fold (udiv X, -1) -> select(X == -1, 1, 0) 4277 if (N1C && N1C->getAPIntValue().isAllOnesValue()) 4278 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ), 4279 DAG.getConstant(1, DL, VT), 4280 DAG.getConstant(0, DL, VT)); 4281 4282 if (SDValue V = simplifyDivRem(N, DAG)) 4283 return V; 4284 4285 if (SDValue NewSel = foldBinOpIntoSelect(N)) 4286 return NewSel; 4287 4288 if (SDValue V = visitUDIVLike(N0, N1, N)) { 4289 // If the corresponding remainder node exists, update its users with 4290 // (Dividend - (Quotient * Divisor). 4291 if (SDNode *RemNode = DAG.getNodeIfExists(ISD::UREM, N->getVTList(), 4292 { N0, N1 })) { 4293 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1); 4294 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 4295 AddToWorklist(Mul.getNode()); 4296 AddToWorklist(Sub.getNode()); 4297 CombineTo(RemNode, Sub); 4298 } 4299 return V; 4300 } 4301 4302 // sdiv, srem -> sdivrem 4303 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 4304 // true. Otherwise, we break the simplification logic in visitREM(). 4305 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4306 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 4307 if (SDValue DivRem = useDivRem(N)) 4308 return DivRem; 4309 4310 return SDValue(); 4311 } 4312 4313 SDValue DAGCombiner::visitUDIVLike(SDValue N0, SDValue N1, SDNode *N) { 4314 SDLoc DL(N); 4315 EVT VT = N->getValueType(0); 4316 4317 // fold (udiv x, (1 << c)) -> x >>u c 4318 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 4319 DAG.isKnownToBeAPowerOfTwo(N1)) { 4320 SDValue LogBase2 = BuildLogBase2(N1, DL); 4321 AddToWorklist(LogBase2.getNode()); 4322 4323 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 4324 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 4325 AddToWorklist(Trunc.getNode()); 4326 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc); 4327 } 4328 4329 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 4330 if (N1.getOpcode() == ISD::SHL) { 4331 SDValue N10 = N1.getOperand(0); 4332 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) && 4333 DAG.isKnownToBeAPowerOfTwo(N10)) { 4334 SDValue LogBase2 = BuildLogBase2(N10, DL); 4335 AddToWorklist(LogBase2.getNode()); 4336 4337 EVT ADDVT = N1.getOperand(1).getValueType(); 4338 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT); 4339 AddToWorklist(Trunc.getNode()); 4340 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc); 4341 AddToWorklist(Add.getNode()); 4342 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 4343 } 4344 } 4345 4346 // fold (udiv x, c) -> alternate 4347 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4348 if (isConstantOrConstantVector(N1) && 4349 !TLI.isIntDivCheap(N->getValueType(0), Attr)) 4350 if (SDValue Op = BuildUDIV(N)) 4351 return Op; 4352 4353 return SDValue(); 4354 } 4355 4356 // handles ISD::SREM and ISD::UREM 4357 SDValue DAGCombiner::visitREM(SDNode *N) { 4358 unsigned Opcode = N->getOpcode(); 4359 SDValue N0 = N->getOperand(0); 4360 SDValue N1 = N->getOperand(1); 4361 EVT VT = N->getValueType(0); 4362 EVT CCVT = getSetCCResultType(VT); 4363 4364 bool isSigned = (Opcode == ISD::SREM); 4365 SDLoc DL(N); 4366 4367 // fold (rem c1, c2) -> c1%c2 4368 ConstantSDNode *N1C = isConstOrConstSplat(N1); 4369 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1})) 4370 return C; 4371 4372 // fold (urem X, -1) -> select(X == -1, 0, x) 4373 if (!isSigned && N1C && N1C->getAPIntValue().isAllOnesValue()) 4374 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ), 4375 DAG.getConstant(0, DL, VT), N0); 4376 4377 if (SDValue V = simplifyDivRem(N, DAG)) 4378 return V; 4379 4380 if (SDValue NewSel = foldBinOpIntoSelect(N)) 4381 return NewSel; 4382 4383 if (isSigned) { 4384 // If we know the sign bits of both operands are zero, strength reduce to a 4385 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 4386 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 4387 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 4388 } else { 4389 if (DAG.isKnownToBeAPowerOfTwo(N1)) { 4390 // fold (urem x, pow2) -> (and x, pow2-1) 4391 SDValue NegOne = DAG.getAllOnesConstant(DL, VT); 4392 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 4393 AddToWorklist(Add.getNode()); 4394 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 4395 } 4396 if (N1.getOpcode() == ISD::SHL && 4397 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) { 4398 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 4399 SDValue NegOne = DAG.getAllOnesConstant(DL, VT); 4400 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 4401 AddToWorklist(Add.getNode()); 4402 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 4403 } 4404 } 4405 4406 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4407 4408 // If X/C can be simplified by the division-by-constant logic, lower 4409 // X%C to the equivalent of X-X/C*C. 4410 // Reuse the SDIVLike/UDIVLike combines - to avoid mangling nodes, the 4411 // speculative DIV must not cause a DIVREM conversion. We guard against this 4412 // by skipping the simplification if isIntDivCheap(). When div is not cheap, 4413 // combine will not return a DIVREM. Regardless, checking cheapness here 4414 // makes sense since the simplification results in fatter code. 4415 if (DAG.isKnownNeverZero(N1) && !TLI.isIntDivCheap(VT, Attr)) { 4416 SDValue OptimizedDiv = 4417 isSigned ? visitSDIVLike(N0, N1, N) : visitUDIVLike(N0, N1, N); 4418 if (OptimizedDiv.getNode()) { 4419 // If the equivalent Div node also exists, update its users. 4420 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 4421 if (SDNode *DivNode = DAG.getNodeIfExists(DivOpcode, N->getVTList(), 4422 { N0, N1 })) 4423 CombineTo(DivNode, OptimizedDiv); 4424 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 4425 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 4426 AddToWorklist(OptimizedDiv.getNode()); 4427 AddToWorklist(Mul.getNode()); 4428 return Sub; 4429 } 4430 } 4431 4432 // sdiv, srem -> sdivrem 4433 if (SDValue DivRem = useDivRem(N)) 4434 return DivRem.getValue(1); 4435 4436 return SDValue(); 4437 } 4438 4439 SDValue DAGCombiner::visitMULHS(SDNode *N) { 4440 SDValue N0 = N->getOperand(0); 4441 SDValue N1 = N->getOperand(1); 4442 EVT VT = N->getValueType(0); 4443 SDLoc DL(N); 4444 4445 if (VT.isVector()) { 4446 // fold (mulhs x, 0) -> 0 4447 // do not return N0/N1, because undef node may exist. 4448 if (ISD::isConstantSplatVectorAllZeros(N0.getNode()) || 4449 ISD::isConstantSplatVectorAllZeros(N1.getNode())) 4450 return DAG.getConstant(0, DL, VT); 4451 } 4452 4453 // fold (mulhs x, 0) -> 0 4454 if (isNullConstant(N1)) 4455 return N1; 4456 // fold (mulhs x, 1) -> (sra x, size(x)-1) 4457 if (isOneConstant(N1)) 4458 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 4459 DAG.getConstant(N0.getScalarValueSizeInBits() - 1, DL, 4460 getShiftAmountTy(N0.getValueType()))); 4461 4462 // fold (mulhs x, undef) -> 0 4463 if (N0.isUndef() || N1.isUndef()) 4464 return DAG.getConstant(0, DL, VT); 4465 4466 // If the type twice as wide is legal, transform the mulhs to a wider multiply 4467 // plus a shift. 4468 if (!TLI.isOperationLegalOrCustom(ISD::MULHS, VT) && VT.isSimple() && 4469 !VT.isVector()) { 4470 MVT Simple = VT.getSimpleVT(); 4471 unsigned SimpleSize = Simple.getSizeInBits(); 4472 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 4473 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 4474 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 4475 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 4476 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 4477 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 4478 DAG.getConstant(SimpleSize, DL, 4479 getShiftAmountTy(N1.getValueType()))); 4480 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 4481 } 4482 } 4483 4484 return SDValue(); 4485 } 4486 4487 SDValue DAGCombiner::visitMULHU(SDNode *N) { 4488 SDValue N0 = N->getOperand(0); 4489 SDValue N1 = N->getOperand(1); 4490 EVT VT = N->getValueType(0); 4491 SDLoc DL(N); 4492 4493 if (VT.isVector()) { 4494 // fold (mulhu x, 0) -> 0 4495 // do not return N0/N1, because undef node may exist. 4496 if (ISD::isConstantSplatVectorAllZeros(N0.getNode()) || 4497 ISD::isConstantSplatVectorAllZeros(N1.getNode())) 4498 return DAG.getConstant(0, DL, VT); 4499 } 4500 4501 // fold (mulhu x, 0) -> 0 4502 if (isNullConstant(N1)) 4503 return N1; 4504 // fold (mulhu x, 1) -> 0 4505 if (isOneConstant(N1)) 4506 return DAG.getConstant(0, DL, N0.getValueType()); 4507 // fold (mulhu x, undef) -> 0 4508 if (N0.isUndef() || N1.isUndef()) 4509 return DAG.getConstant(0, DL, VT); 4510 4511 // fold (mulhu x, (1 << c)) -> x >> (bitwidth - c) 4512 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 4513 DAG.isKnownToBeAPowerOfTwo(N1) && hasOperation(ISD::SRL, VT)) { 4514 unsigned NumEltBits = VT.getScalarSizeInBits(); 4515 SDValue LogBase2 = BuildLogBase2(N1, DL); 4516 SDValue SRLAmt = DAG.getNode( 4517 ISD::SUB, DL, VT, DAG.getConstant(NumEltBits, DL, VT), LogBase2); 4518 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 4519 SDValue Trunc = DAG.getZExtOrTrunc(SRLAmt, DL, ShiftVT); 4520 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc); 4521 } 4522 4523 // If the type twice as wide is legal, transform the mulhu to a wider multiply 4524 // plus a shift. 4525 if (!TLI.isOperationLegalOrCustom(ISD::MULHU, VT) && VT.isSimple() && 4526 !VT.isVector()) { 4527 MVT Simple = VT.getSimpleVT(); 4528 unsigned SimpleSize = Simple.getSizeInBits(); 4529 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 4530 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 4531 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 4532 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 4533 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 4534 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 4535 DAG.getConstant(SimpleSize, DL, 4536 getShiftAmountTy(N1.getValueType()))); 4537 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 4538 } 4539 } 4540 4541 return SDValue(); 4542 } 4543 4544 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 4545 /// give the opcodes for the two computations that are being performed. Return 4546 /// true if a simplification was made. 4547 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 4548 unsigned HiOp) { 4549 // If the high half is not needed, just compute the low half. 4550 bool HiExists = N->hasAnyUseOfValue(1); 4551 if (!HiExists && (!LegalOperations || 4552 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 4553 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 4554 return CombineTo(N, Res, Res); 4555 } 4556 4557 // If the low half is not needed, just compute the high half. 4558 bool LoExists = N->hasAnyUseOfValue(0); 4559 if (!LoExists && (!LegalOperations || 4560 TLI.isOperationLegalOrCustom(HiOp, N->getValueType(1)))) { 4561 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 4562 return CombineTo(N, Res, Res); 4563 } 4564 4565 // If both halves are used, return as it is. 4566 if (LoExists && HiExists) 4567 return SDValue(); 4568 4569 // If the two computed results can be simplified separately, separate them. 4570 if (LoExists) { 4571 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 4572 AddToWorklist(Lo.getNode()); 4573 SDValue LoOpt = combine(Lo.getNode()); 4574 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 4575 (!LegalOperations || 4576 TLI.isOperationLegalOrCustom(LoOpt.getOpcode(), LoOpt.getValueType()))) 4577 return CombineTo(N, LoOpt, LoOpt); 4578 } 4579 4580 if (HiExists) { 4581 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 4582 AddToWorklist(Hi.getNode()); 4583 SDValue HiOpt = combine(Hi.getNode()); 4584 if (HiOpt.getNode() && HiOpt != Hi && 4585 (!LegalOperations || 4586 TLI.isOperationLegalOrCustom(HiOpt.getOpcode(), HiOpt.getValueType()))) 4587 return CombineTo(N, HiOpt, HiOpt); 4588 } 4589 4590 return SDValue(); 4591 } 4592 4593 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 4594 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 4595 return Res; 4596 4597 EVT VT = N->getValueType(0); 4598 SDLoc DL(N); 4599 4600 // If the type is twice as wide is legal, transform the mulhu to a wider 4601 // multiply plus a shift. 4602 if (VT.isSimple() && !VT.isVector()) { 4603 MVT Simple = VT.getSimpleVT(); 4604 unsigned SimpleSize = Simple.getSizeInBits(); 4605 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 4606 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 4607 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 4608 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 4609 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 4610 // Compute the high part as N1. 4611 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 4612 DAG.getConstant(SimpleSize, DL, 4613 getShiftAmountTy(Lo.getValueType()))); 4614 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 4615 // Compute the low part as N0. 4616 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 4617 return CombineTo(N, Lo, Hi); 4618 } 4619 } 4620 4621 return SDValue(); 4622 } 4623 4624 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 4625 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 4626 return Res; 4627 4628 EVT VT = N->getValueType(0); 4629 SDLoc DL(N); 4630 4631 // (umul_lohi N0, 0) -> (0, 0) 4632 if (isNullConstant(N->getOperand(1))) { 4633 SDValue Zero = DAG.getConstant(0, DL, VT); 4634 return CombineTo(N, Zero, Zero); 4635 } 4636 4637 // (umul_lohi N0, 1) -> (N0, 0) 4638 if (isOneConstant(N->getOperand(1))) { 4639 SDValue Zero = DAG.getConstant(0, DL, VT); 4640 return CombineTo(N, N->getOperand(0), Zero); 4641 } 4642 4643 // If the type is twice as wide is legal, transform the mulhu to a wider 4644 // multiply plus a shift. 4645 if (VT.isSimple() && !VT.isVector()) { 4646 MVT Simple = VT.getSimpleVT(); 4647 unsigned SimpleSize = Simple.getSizeInBits(); 4648 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 4649 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 4650 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 4651 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 4652 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 4653 // Compute the high part as N1. 4654 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 4655 DAG.getConstant(SimpleSize, DL, 4656 getShiftAmountTy(Lo.getValueType()))); 4657 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 4658 // Compute the low part as N0. 4659 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 4660 return CombineTo(N, Lo, Hi); 4661 } 4662 } 4663 4664 return SDValue(); 4665 } 4666 4667 SDValue DAGCombiner::visitMULO(SDNode *N) { 4668 SDValue N0 = N->getOperand(0); 4669 SDValue N1 = N->getOperand(1); 4670 EVT VT = N0.getValueType(); 4671 bool IsSigned = (ISD::SMULO == N->getOpcode()); 4672 4673 EVT CarryVT = N->getValueType(1); 4674 SDLoc DL(N); 4675 4676 ConstantSDNode *N0C = isConstOrConstSplat(N0); 4677 ConstantSDNode *N1C = isConstOrConstSplat(N1); 4678 4679 // fold operation with constant operands. 4680 // TODO: Move this to FoldConstantArithmetic when it supports nodes with 4681 // multiple results. 4682 if (N0C && N1C) { 4683 bool Overflow; 4684 APInt Result = 4685 IsSigned ? N0C->getAPIntValue().smul_ov(N1C->getAPIntValue(), Overflow) 4686 : N0C->getAPIntValue().umul_ov(N1C->getAPIntValue(), Overflow); 4687 return CombineTo(N, DAG.getConstant(Result, DL, VT), 4688 DAG.getBoolConstant(Overflow, DL, CarryVT, CarryVT)); 4689 } 4690 4691 // canonicalize constant to RHS. 4692 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4693 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4694 return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0); 4695 4696 // fold (mulo x, 0) -> 0 + no carry out 4697 if (isNullOrNullSplat(N1)) 4698 return CombineTo(N, DAG.getConstant(0, DL, VT), 4699 DAG.getConstant(0, DL, CarryVT)); 4700 4701 // (mulo x, 2) -> (addo x, x) 4702 if (N1C && N1C->getAPIntValue() == 2) 4703 return DAG.getNode(IsSigned ? ISD::SADDO : ISD::UADDO, DL, 4704 N->getVTList(), N0, N0); 4705 4706 if (IsSigned) { 4707 // A 1 bit SMULO overflows if both inputs are 1. 4708 if (VT.getScalarSizeInBits() == 1) { 4709 SDValue And = DAG.getNode(ISD::AND, DL, VT, N0, N1); 4710 return CombineTo(N, And, 4711 DAG.getSetCC(DL, CarryVT, And, 4712 DAG.getConstant(0, DL, VT), ISD::SETNE)); 4713 } 4714 4715 // Multiplying n * m significant bits yields a result of n + m significant 4716 // bits. If the total number of significant bits does not exceed the 4717 // result bit width (minus 1), there is no overflow. 4718 unsigned SignBits = DAG.ComputeNumSignBits(N0); 4719 if (SignBits > 1) 4720 SignBits += DAG.ComputeNumSignBits(N1); 4721 if (SignBits > VT.getScalarSizeInBits() + 1) 4722 return CombineTo(N, DAG.getNode(ISD::MUL, DL, VT, N0, N1), 4723 DAG.getConstant(0, DL, CarryVT)); 4724 } else { 4725 KnownBits N1Known = DAG.computeKnownBits(N1); 4726 KnownBits N0Known = DAG.computeKnownBits(N0); 4727 bool Overflow; 4728 (void)N0Known.getMaxValue().umul_ov(N1Known.getMaxValue(), Overflow); 4729 if (!Overflow) 4730 return CombineTo(N, DAG.getNode(ISD::MUL, DL, VT, N0, N1), 4731 DAG.getConstant(0, DL, CarryVT)); 4732 } 4733 4734 return SDValue(); 4735 } 4736 4737 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 4738 SDValue N0 = N->getOperand(0); 4739 SDValue N1 = N->getOperand(1); 4740 EVT VT = N0.getValueType(); 4741 unsigned Opcode = N->getOpcode(); 4742 4743 // fold vector ops 4744 if (VT.isVector()) 4745 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4746 return FoldedVOp; 4747 4748 // fold operation with constant operands. 4749 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, SDLoc(N), VT, {N0, N1})) 4750 return C; 4751 4752 // canonicalize constant to RHS 4753 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4754 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4755 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 4756 4757 // Is sign bits are zero, flip between UMIN/UMAX and SMIN/SMAX. 4758 // Only do this if the current op isn't legal and the flipped is. 4759 if (!TLI.isOperationLegal(Opcode, VT) && 4760 (N0.isUndef() || DAG.SignBitIsZero(N0)) && 4761 (N1.isUndef() || DAG.SignBitIsZero(N1))) { 4762 unsigned AltOpcode; 4763 switch (Opcode) { 4764 case ISD::SMIN: AltOpcode = ISD::UMIN; break; 4765 case ISD::SMAX: AltOpcode = ISD::UMAX; break; 4766 case ISD::UMIN: AltOpcode = ISD::SMIN; break; 4767 case ISD::UMAX: AltOpcode = ISD::SMAX; break; 4768 default: llvm_unreachable("Unknown MINMAX opcode"); 4769 } 4770 if (TLI.isOperationLegal(AltOpcode, VT)) 4771 return DAG.getNode(AltOpcode, SDLoc(N), VT, N0, N1); 4772 } 4773 4774 // Simplify the operands using demanded-bits information. 4775 if (SimplifyDemandedBits(SDValue(N, 0))) 4776 return SDValue(N, 0); 4777 4778 return SDValue(); 4779 } 4780 4781 /// If this is a bitwise logic instruction and both operands have the same 4782 /// opcode, try to sink the other opcode after the logic instruction. 4783 SDValue DAGCombiner::hoistLogicOpWithSameOpcodeHands(SDNode *N) { 4784 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 4785 EVT VT = N0.getValueType(); 4786 unsigned LogicOpcode = N->getOpcode(); 4787 unsigned HandOpcode = N0.getOpcode(); 4788 assert((LogicOpcode == ISD::AND || LogicOpcode == ISD::OR || 4789 LogicOpcode == ISD::XOR) && "Expected logic opcode"); 4790 assert(HandOpcode == N1.getOpcode() && "Bad input!"); 4791 4792 // Bail early if none of these transforms apply. 4793 if (N0.getNumOperands() == 0) 4794 return SDValue(); 4795 4796 // FIXME: We should check number of uses of the operands to not increase 4797 // the instruction count for all transforms. 4798 4799 // Handle size-changing casts. 4800 SDValue X = N0.getOperand(0); 4801 SDValue Y = N1.getOperand(0); 4802 EVT XVT = X.getValueType(); 4803 SDLoc DL(N); 4804 if (HandOpcode == ISD::ANY_EXTEND || HandOpcode == ISD::ZERO_EXTEND || 4805 HandOpcode == ISD::SIGN_EXTEND) { 4806 // If both operands have other uses, this transform would create extra 4807 // instructions without eliminating anything. 4808 if (!N0.hasOneUse() && !N1.hasOneUse()) 4809 return SDValue(); 4810 // We need matching integer source types. 4811 if (XVT != Y.getValueType()) 4812 return SDValue(); 4813 // Don't create an illegal op during or after legalization. Don't ever 4814 // create an unsupported vector op. 4815 if ((VT.isVector() || LegalOperations) && 4816 !TLI.isOperationLegalOrCustom(LogicOpcode, XVT)) 4817 return SDValue(); 4818 // Avoid infinite looping with PromoteIntBinOp. 4819 // TODO: Should we apply desirable/legal constraints to all opcodes? 4820 if (HandOpcode == ISD::ANY_EXTEND && LegalTypes && 4821 !TLI.isTypeDesirableForOp(LogicOpcode, XVT)) 4822 return SDValue(); 4823 // logic_op (hand_op X), (hand_op Y) --> hand_op (logic_op X, Y) 4824 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y); 4825 return DAG.getNode(HandOpcode, DL, VT, Logic); 4826 } 4827 4828 // logic_op (truncate x), (truncate y) --> truncate (logic_op x, y) 4829 if (HandOpcode == ISD::TRUNCATE) { 4830 // If both operands have other uses, this transform would create extra 4831 // instructions without eliminating anything. 4832 if (!N0.hasOneUse() && !N1.hasOneUse()) 4833 return SDValue(); 4834 // We need matching source types. 4835 if (XVT != Y.getValueType()) 4836 return SDValue(); 4837 // Don't create an illegal op during or after legalization. 4838 if (LegalOperations && !TLI.isOperationLegal(LogicOpcode, XVT)) 4839 return SDValue(); 4840 // Be extra careful sinking truncate. If it's free, there's no benefit in 4841 // widening a binop. Also, don't create a logic op on an illegal type. 4842 if (TLI.isZExtFree(VT, XVT) && TLI.isTruncateFree(XVT, VT)) 4843 return SDValue(); 4844 if (!TLI.isTypeLegal(XVT)) 4845 return SDValue(); 4846 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y); 4847 return DAG.getNode(HandOpcode, DL, VT, Logic); 4848 } 4849 4850 // For binops SHL/SRL/SRA/AND: 4851 // logic_op (OP x, z), (OP y, z) --> OP (logic_op x, y), z 4852 if ((HandOpcode == ISD::SHL || HandOpcode == ISD::SRL || 4853 HandOpcode == ISD::SRA || HandOpcode == ISD::AND) && 4854 N0.getOperand(1) == N1.getOperand(1)) { 4855 // If either operand has other uses, this transform is not an improvement. 4856 if (!N0.hasOneUse() || !N1.hasOneUse()) 4857 return SDValue(); 4858 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y); 4859 return DAG.getNode(HandOpcode, DL, VT, Logic, N0.getOperand(1)); 4860 } 4861 4862 // Unary ops: logic_op (bswap x), (bswap y) --> bswap (logic_op x, y) 4863 if (HandOpcode == ISD::BSWAP) { 4864 // If either operand has other uses, this transform is not an improvement. 4865 if (!N0.hasOneUse() || !N1.hasOneUse()) 4866 return SDValue(); 4867 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y); 4868 return DAG.getNode(HandOpcode, DL, VT, Logic); 4869 } 4870 4871 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 4872 // Only perform this optimization up until type legalization, before 4873 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 4874 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 4875 // we don't want to undo this promotion. 4876 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 4877 // on scalars. 4878 if ((HandOpcode == ISD::BITCAST || HandOpcode == ISD::SCALAR_TO_VECTOR) && 4879 Level <= AfterLegalizeTypes) { 4880 // Input types must be integer and the same. 4881 if (XVT.isInteger() && XVT == Y.getValueType() && 4882 !(VT.isVector() && TLI.isTypeLegal(VT) && 4883 !XVT.isVector() && !TLI.isTypeLegal(XVT))) { 4884 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y); 4885 return DAG.getNode(HandOpcode, DL, VT, Logic); 4886 } 4887 } 4888 4889 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 4890 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 4891 // If both shuffles use the same mask, and both shuffle within a single 4892 // vector, then it is worthwhile to move the swizzle after the operation. 4893 // The type-legalizer generates this pattern when loading illegal 4894 // vector types from memory. In many cases this allows additional shuffle 4895 // optimizations. 4896 // There are other cases where moving the shuffle after the xor/and/or 4897 // is profitable even if shuffles don't perform a swizzle. 4898 // If both shuffles use the same mask, and both shuffles have the same first 4899 // or second operand, then it might still be profitable to move the shuffle 4900 // after the xor/and/or operation. 4901 if (HandOpcode == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 4902 auto *SVN0 = cast<ShuffleVectorSDNode>(N0); 4903 auto *SVN1 = cast<ShuffleVectorSDNode>(N1); 4904 assert(X.getValueType() == Y.getValueType() && 4905 "Inputs to shuffles are not the same type"); 4906 4907 // Check that both shuffles use the same mask. The masks are known to be of 4908 // the same length because the result vector type is the same. 4909 // Check also that shuffles have only one use to avoid introducing extra 4910 // instructions. 4911 if (!SVN0->hasOneUse() || !SVN1->hasOneUse() || 4912 !SVN0->getMask().equals(SVN1->getMask())) 4913 return SDValue(); 4914 4915 // Don't try to fold this node if it requires introducing a 4916 // build vector of all zeros that might be illegal at this stage. 4917 SDValue ShOp = N0.getOperand(1); 4918 if (LogicOpcode == ISD::XOR && !ShOp.isUndef()) 4919 ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations); 4920 4921 // (logic_op (shuf (A, C), shuf (B, C))) --> shuf (logic_op (A, B), C) 4922 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 4923 SDValue Logic = DAG.getNode(LogicOpcode, DL, VT, 4924 N0.getOperand(0), N1.getOperand(0)); 4925 return DAG.getVectorShuffle(VT, DL, Logic, ShOp, SVN0->getMask()); 4926 } 4927 4928 // Don't try to fold this node if it requires introducing a 4929 // build vector of all zeros that might be illegal at this stage. 4930 ShOp = N0.getOperand(0); 4931 if (LogicOpcode == ISD::XOR && !ShOp.isUndef()) 4932 ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations); 4933 4934 // (logic_op (shuf (C, A), shuf (C, B))) --> shuf (C, logic_op (A, B)) 4935 if (N0.getOperand(0) == N1.getOperand(0) && ShOp.getNode()) { 4936 SDValue Logic = DAG.getNode(LogicOpcode, DL, VT, N0.getOperand(1), 4937 N1.getOperand(1)); 4938 return DAG.getVectorShuffle(VT, DL, ShOp, Logic, SVN0->getMask()); 4939 } 4940 } 4941 4942 return SDValue(); 4943 } 4944 4945 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient. 4946 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, 4947 const SDLoc &DL) { 4948 SDValue LL, LR, RL, RR, N0CC, N1CC; 4949 if (!isSetCCEquivalent(N0, LL, LR, N0CC) || 4950 !isSetCCEquivalent(N1, RL, RR, N1CC)) 4951 return SDValue(); 4952 4953 assert(N0.getValueType() == N1.getValueType() && 4954 "Unexpected operand types for bitwise logic op"); 4955 assert(LL.getValueType() == LR.getValueType() && 4956 RL.getValueType() == RR.getValueType() && 4957 "Unexpected operand types for setcc"); 4958 4959 // If we're here post-legalization or the logic op type is not i1, the logic 4960 // op type must match a setcc result type. Also, all folds require new 4961 // operations on the left and right operands, so those types must match. 4962 EVT VT = N0.getValueType(); 4963 EVT OpVT = LL.getValueType(); 4964 if (LegalOperations || VT.getScalarType() != MVT::i1) 4965 if (VT != getSetCCResultType(OpVT)) 4966 return SDValue(); 4967 if (OpVT != RL.getValueType()) 4968 return SDValue(); 4969 4970 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get(); 4971 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get(); 4972 bool IsInteger = OpVT.isInteger(); 4973 if (LR == RR && CC0 == CC1 && IsInteger) { 4974 bool IsZero = isNullOrNullSplat(LR); 4975 bool IsNeg1 = isAllOnesOrAllOnesSplat(LR); 4976 4977 // All bits clear? 4978 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero; 4979 // All sign bits clear? 4980 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1; 4981 // Any bits set? 4982 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero; 4983 // Any sign bits set? 4984 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero; 4985 4986 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0) 4987 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1) 4988 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0) 4989 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0) 4990 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) { 4991 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL); 4992 AddToWorklist(Or.getNode()); 4993 return DAG.getSetCC(DL, VT, Or, LR, CC1); 4994 } 4995 4996 // All bits set? 4997 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1; 4998 // All sign bits set? 4999 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero; 5000 // Any bits clear? 5001 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1; 5002 // Any sign bits clear? 5003 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1; 5004 5005 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1) 5006 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0) 5007 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1) 5008 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1) 5009 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) { 5010 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL); 5011 AddToWorklist(And.getNode()); 5012 return DAG.getSetCC(DL, VT, And, LR, CC1); 5013 } 5014 } 5015 5016 // TODO: What is the 'or' equivalent of this fold? 5017 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2) 5018 if (IsAnd && LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 && 5019 IsInteger && CC0 == ISD::SETNE && 5020 ((isNullConstant(LR) && isAllOnesConstant(RR)) || 5021 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 5022 SDValue One = DAG.getConstant(1, DL, OpVT); 5023 SDValue Two = DAG.getConstant(2, DL, OpVT); 5024 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One); 5025 AddToWorklist(Add.getNode()); 5026 return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE); 5027 } 5028 5029 // Try more general transforms if the predicates match and the only user of 5030 // the compares is the 'and' or 'or'. 5031 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 && 5032 N0.hasOneUse() && N1.hasOneUse()) { 5033 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0 5034 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0 5035 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) { 5036 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR); 5037 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR); 5038 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR); 5039 SDValue Zero = DAG.getConstant(0, DL, OpVT); 5040 return DAG.getSetCC(DL, VT, Or, Zero, CC1); 5041 } 5042 5043 // Turn compare of constants whose difference is 1 bit into add+and+setcc. 5044 // TODO - support non-uniform vector amounts. 5045 if ((IsAnd && CC1 == ISD::SETNE) || (!IsAnd && CC1 == ISD::SETEQ)) { 5046 // Match a shared variable operand and 2 non-opaque constant operands. 5047 ConstantSDNode *C0 = isConstOrConstSplat(LR); 5048 ConstantSDNode *C1 = isConstOrConstSplat(RR); 5049 if (LL == RL && C0 && C1 && !C0->isOpaque() && !C1->isOpaque()) { 5050 const APInt &CMax = 5051 APIntOps::umax(C0->getAPIntValue(), C1->getAPIntValue()); 5052 const APInt &CMin = 5053 APIntOps::umin(C0->getAPIntValue(), C1->getAPIntValue()); 5054 // The difference of the constants must be a single bit. 5055 if ((CMax - CMin).isPowerOf2()) { 5056 // and/or (setcc X, CMax, ne), (setcc X, CMin, ne/eq) --> 5057 // setcc ((sub X, CMin), ~(CMax - CMin)), 0, ne/eq 5058 SDValue Max = DAG.getNode(ISD::UMAX, DL, OpVT, LR, RR); 5059 SDValue Min = DAG.getNode(ISD::UMIN, DL, OpVT, LR, RR); 5060 SDValue Offset = DAG.getNode(ISD::SUB, DL, OpVT, LL, Min); 5061 SDValue Diff = DAG.getNode(ISD::SUB, DL, OpVT, Max, Min); 5062 SDValue Mask = DAG.getNOT(DL, Diff, OpVT); 5063 SDValue And = DAG.getNode(ISD::AND, DL, OpVT, Offset, Mask); 5064 SDValue Zero = DAG.getConstant(0, DL, OpVT); 5065 return DAG.getSetCC(DL, VT, And, Zero, CC0); 5066 } 5067 } 5068 } 5069 } 5070 5071 // Canonicalize equivalent operands to LL == RL. 5072 if (LL == RR && LR == RL) { 5073 CC1 = ISD::getSetCCSwappedOperands(CC1); 5074 std::swap(RL, RR); 5075 } 5076 5077 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 5078 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 5079 if (LL == RL && LR == RR) { 5080 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, OpVT) 5081 : ISD::getSetCCOrOperation(CC0, CC1, OpVT); 5082 if (NewCC != ISD::SETCC_INVALID && 5083 (!LegalOperations || 5084 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) && 5085 TLI.isOperationLegal(ISD::SETCC, OpVT)))) 5086 return DAG.getSetCC(DL, VT, LL, LR, NewCC); 5087 } 5088 5089 return SDValue(); 5090 } 5091 5092 /// This contains all DAGCombine rules which reduce two values combined by 5093 /// an And operation to a single value. This makes them reusable in the context 5094 /// of visitSELECT(). Rules involving constants are not included as 5095 /// visitSELECT() already handles those cases. 5096 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) { 5097 EVT VT = N1.getValueType(); 5098 SDLoc DL(N); 5099 5100 // fold (and x, undef) -> 0 5101 if (N0.isUndef() || N1.isUndef()) 5102 return DAG.getConstant(0, DL, VT); 5103 5104 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL)) 5105 return V; 5106 5107 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 5108 VT.getSizeInBits() <= 64) { 5109 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5110 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 5111 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 5112 // immediate for an add, but it is legal if its top c2 bits are set, 5113 // transform the ADD so the immediate doesn't need to be materialized 5114 // in a register. 5115 APInt ADDC = ADDI->getAPIntValue(); 5116 APInt SRLC = SRLI->getAPIntValue(); 5117 if (ADDC.getMinSignedBits() <= 64 && 5118 SRLC.ult(VT.getSizeInBits()) && 5119 !TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 5120 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 5121 SRLC.getZExtValue()); 5122 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 5123 ADDC |= Mask; 5124 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 5125 SDLoc DL0(N0); 5126 SDValue NewAdd = 5127 DAG.getNode(ISD::ADD, DL0, VT, 5128 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 5129 CombineTo(N0.getNode(), NewAdd); 5130 // Return N so it doesn't get rechecked! 5131 return SDValue(N, 0); 5132 } 5133 } 5134 } 5135 } 5136 } 5137 } 5138 5139 // Reduce bit extract of low half of an integer to the narrower type. 5140 // (and (srl i64:x, K), KMask) -> 5141 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask) 5142 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 5143 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) { 5144 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5145 unsigned Size = VT.getSizeInBits(); 5146 const APInt &AndMask = CAnd->getAPIntValue(); 5147 unsigned ShiftBits = CShift->getZExtValue(); 5148 5149 // Bail out, this node will probably disappear anyway. 5150 if (ShiftBits == 0) 5151 return SDValue(); 5152 5153 unsigned MaskBits = AndMask.countTrailingOnes(); 5154 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2); 5155 5156 if (AndMask.isMask() && 5157 // Required bits must not span the two halves of the integer and 5158 // must fit in the half size type. 5159 (ShiftBits + MaskBits <= Size / 2) && 5160 TLI.isNarrowingProfitable(VT, HalfVT) && 5161 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) && 5162 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) && 5163 TLI.isTruncateFree(VT, HalfVT) && 5164 TLI.isZExtFree(HalfVT, VT)) { 5165 // The isNarrowingProfitable is to avoid regressions on PPC and 5166 // AArch64 which match a few 64-bit bit insert / bit extract patterns 5167 // on downstream users of this. Those patterns could probably be 5168 // extended to handle extensions mixed in. 5169 5170 SDValue SL(N0); 5171 assert(MaskBits <= Size); 5172 5173 // Extracting the highest bit of the low half. 5174 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout()); 5175 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT, 5176 N0.getOperand(0)); 5177 5178 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT); 5179 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT); 5180 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK); 5181 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask); 5182 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And); 5183 } 5184 } 5185 } 5186 } 5187 5188 return SDValue(); 5189 } 5190 5191 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 5192 EVT LoadResultTy, EVT &ExtVT) { 5193 if (!AndC->getAPIntValue().isMask()) 5194 return false; 5195 5196 unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes(); 5197 5198 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 5199 EVT LoadedVT = LoadN->getMemoryVT(); 5200 5201 if (ExtVT == LoadedVT && 5202 (!LegalOperations || 5203 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 5204 // ZEXTLOAD will match without needing to change the size of the value being 5205 // loaded. 5206 return true; 5207 } 5208 5209 // Do not change the width of a volatile or atomic loads. 5210 if (!LoadN->isSimple()) 5211 return false; 5212 5213 // Do not generate loads of non-round integer types since these can 5214 // be expensive (and would be wrong if the type is not byte sized). 5215 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 5216 return false; 5217 5218 if (LegalOperations && 5219 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 5220 return false; 5221 5222 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 5223 return false; 5224 5225 return true; 5226 } 5227 5228 bool DAGCombiner::isLegalNarrowLdSt(LSBaseSDNode *LDST, 5229 ISD::LoadExtType ExtType, EVT &MemVT, 5230 unsigned ShAmt) { 5231 if (!LDST) 5232 return false; 5233 // Only allow byte offsets. 5234 if (ShAmt % 8) 5235 return false; 5236 5237 // Do not generate loads of non-round integer types since these can 5238 // be expensive (and would be wrong if the type is not byte sized). 5239 if (!MemVT.isRound()) 5240 return false; 5241 5242 // Don't change the width of a volatile or atomic loads. 5243 if (!LDST->isSimple()) 5244 return false; 5245 5246 EVT LdStMemVT = LDST->getMemoryVT(); 5247 5248 // Bail out when changing the scalable property, since we can't be sure that 5249 // we're actually narrowing here. 5250 if (LdStMemVT.isScalableVector() != MemVT.isScalableVector()) 5251 return false; 5252 5253 // Verify that we are actually reducing a load width here. 5254 if (LdStMemVT.bitsLT(MemVT)) 5255 return false; 5256 5257 // Ensure that this isn't going to produce an unsupported memory access. 5258 if (ShAmt) { 5259 assert(ShAmt % 8 == 0 && "ShAmt is byte offset"); 5260 const unsigned ByteShAmt = ShAmt / 8; 5261 const Align LDSTAlign = LDST->getAlign(); 5262 const Align NarrowAlign = commonAlignment(LDSTAlign, ByteShAmt); 5263 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 5264 LDST->getAddressSpace(), NarrowAlign, 5265 LDST->getMemOperand()->getFlags())) 5266 return false; 5267 } 5268 5269 // It's not possible to generate a constant of extended or untyped type. 5270 EVT PtrType = LDST->getBasePtr().getValueType(); 5271 if (PtrType == MVT::Untyped || PtrType.isExtended()) 5272 return false; 5273 5274 if (isa<LoadSDNode>(LDST)) { 5275 LoadSDNode *Load = cast<LoadSDNode>(LDST); 5276 // Don't transform one with multiple uses, this would require adding a new 5277 // load. 5278 if (!SDValue(Load, 0).hasOneUse()) 5279 return false; 5280 5281 if (LegalOperations && 5282 !TLI.isLoadExtLegal(ExtType, Load->getValueType(0), MemVT)) 5283 return false; 5284 5285 // For the transform to be legal, the load must produce only two values 5286 // (the value loaded and the chain). Don't transform a pre-increment 5287 // load, for example, which produces an extra value. Otherwise the 5288 // transformation is not equivalent, and the downstream logic to replace 5289 // uses gets things wrong. 5290 if (Load->getNumValues() > 2) 5291 return false; 5292 5293 // If the load that we're shrinking is an extload and we're not just 5294 // discarding the extension we can't simply shrink the load. Bail. 5295 // TODO: It would be possible to merge the extensions in some cases. 5296 if (Load->getExtensionType() != ISD::NON_EXTLOAD && 5297 Load->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt) 5298 return false; 5299 5300 if (!TLI.shouldReduceLoadWidth(Load, ExtType, MemVT)) 5301 return false; 5302 } else { 5303 assert(isa<StoreSDNode>(LDST) && "It is not a Load nor a Store SDNode"); 5304 StoreSDNode *Store = cast<StoreSDNode>(LDST); 5305 // Can't write outside the original store 5306 if (Store->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt) 5307 return false; 5308 5309 if (LegalOperations && 5310 !TLI.isTruncStoreLegal(Store->getValue().getValueType(), MemVT)) 5311 return false; 5312 } 5313 return true; 5314 } 5315 5316 bool DAGCombiner::SearchForAndLoads(SDNode *N, 5317 SmallVectorImpl<LoadSDNode*> &Loads, 5318 SmallPtrSetImpl<SDNode*> &NodesWithConsts, 5319 ConstantSDNode *Mask, 5320 SDNode *&NodeToMask) { 5321 // Recursively search for the operands, looking for loads which can be 5322 // narrowed. 5323 for (SDValue Op : N->op_values()) { 5324 if (Op.getValueType().isVector()) 5325 return false; 5326 5327 // Some constants may need fixing up later if they are too large. 5328 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 5329 if ((N->getOpcode() == ISD::OR || N->getOpcode() == ISD::XOR) && 5330 (Mask->getAPIntValue() & C->getAPIntValue()) != C->getAPIntValue()) 5331 NodesWithConsts.insert(N); 5332 continue; 5333 } 5334 5335 if (!Op.hasOneUse()) 5336 return false; 5337 5338 switch(Op.getOpcode()) { 5339 case ISD::LOAD: { 5340 auto *Load = cast<LoadSDNode>(Op); 5341 EVT ExtVT; 5342 if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) && 5343 isLegalNarrowLdSt(Load, ISD::ZEXTLOAD, ExtVT)) { 5344 5345 // ZEXTLOAD is already small enough. 5346 if (Load->getExtensionType() == ISD::ZEXTLOAD && 5347 ExtVT.bitsGE(Load->getMemoryVT())) 5348 continue; 5349 5350 // Use LE to convert equal sized loads to zext. 5351 if (ExtVT.bitsLE(Load->getMemoryVT())) 5352 Loads.push_back(Load); 5353 5354 continue; 5355 } 5356 return false; 5357 } 5358 case ISD::ZERO_EXTEND: 5359 case ISD::AssertZext: { 5360 unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes(); 5361 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 5362 EVT VT = Op.getOpcode() == ISD::AssertZext ? 5363 cast<VTSDNode>(Op.getOperand(1))->getVT() : 5364 Op.getOperand(0).getValueType(); 5365 5366 // We can accept extending nodes if the mask is wider or an equal 5367 // width to the original type. 5368 if (ExtVT.bitsGE(VT)) 5369 continue; 5370 break; 5371 } 5372 case ISD::OR: 5373 case ISD::XOR: 5374 case ISD::AND: 5375 if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask, 5376 NodeToMask)) 5377 return false; 5378 continue; 5379 } 5380 5381 // Allow one node which will masked along with any loads found. 5382 if (NodeToMask) 5383 return false; 5384 5385 // Also ensure that the node to be masked only produces one data result. 5386 NodeToMask = Op.getNode(); 5387 if (NodeToMask->getNumValues() > 1) { 5388 bool HasValue = false; 5389 for (unsigned i = 0, e = NodeToMask->getNumValues(); i < e; ++i) { 5390 MVT VT = SDValue(NodeToMask, i).getSimpleValueType(); 5391 if (VT != MVT::Glue && VT != MVT::Other) { 5392 if (HasValue) { 5393 NodeToMask = nullptr; 5394 return false; 5395 } 5396 HasValue = true; 5397 } 5398 } 5399 assert(HasValue && "Node to be masked has no data result?"); 5400 } 5401 } 5402 return true; 5403 } 5404 5405 bool DAGCombiner::BackwardsPropagateMask(SDNode *N) { 5406 auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1)); 5407 if (!Mask) 5408 return false; 5409 5410 if (!Mask->getAPIntValue().isMask()) 5411 return false; 5412 5413 // No need to do anything if the and directly uses a load. 5414 if (isa<LoadSDNode>(N->getOperand(0))) 5415 return false; 5416 5417 SmallVector<LoadSDNode*, 8> Loads; 5418 SmallPtrSet<SDNode*, 2> NodesWithConsts; 5419 SDNode *FixupNode = nullptr; 5420 if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) { 5421 if (Loads.size() == 0) 5422 return false; 5423 5424 LLVM_DEBUG(dbgs() << "Backwards propagate AND: "; N->dump()); 5425 SDValue MaskOp = N->getOperand(1); 5426 5427 // If it exists, fixup the single node we allow in the tree that needs 5428 // masking. 5429 if (FixupNode) { 5430 LLVM_DEBUG(dbgs() << "First, need to fix up: "; FixupNode->dump()); 5431 SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode), 5432 FixupNode->getValueType(0), 5433 SDValue(FixupNode, 0), MaskOp); 5434 DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And); 5435 if (And.getOpcode() == ISD ::AND) 5436 DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0), MaskOp); 5437 } 5438 5439 // Narrow any constants that need it. 5440 for (auto *LogicN : NodesWithConsts) { 5441 SDValue Op0 = LogicN->getOperand(0); 5442 SDValue Op1 = LogicN->getOperand(1); 5443 5444 if (isa<ConstantSDNode>(Op0)) 5445 std::swap(Op0, Op1); 5446 5447 SDValue And = DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(), 5448 Op1, MaskOp); 5449 5450 DAG.UpdateNodeOperands(LogicN, Op0, And); 5451 } 5452 5453 // Create narrow loads. 5454 for (auto *Load : Loads) { 5455 LLVM_DEBUG(dbgs() << "Propagate AND back to: "; Load->dump()); 5456 SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0), 5457 SDValue(Load, 0), MaskOp); 5458 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And); 5459 if (And.getOpcode() == ISD ::AND) 5460 And = SDValue( 5461 DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp), 0); 5462 SDValue NewLoad = ReduceLoadWidth(And.getNode()); 5463 assert(NewLoad && 5464 "Shouldn't be masking the load if it can't be narrowed"); 5465 CombineTo(Load, NewLoad, NewLoad.getValue(1)); 5466 } 5467 DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode()); 5468 return true; 5469 } 5470 return false; 5471 } 5472 5473 // Unfold 5474 // x & (-1 'logical shift' y) 5475 // To 5476 // (x 'opposite logical shift' y) 'logical shift' y 5477 // if it is better for performance. 5478 SDValue DAGCombiner::unfoldExtremeBitClearingToShifts(SDNode *N) { 5479 assert(N->getOpcode() == ISD::AND); 5480 5481 SDValue N0 = N->getOperand(0); 5482 SDValue N1 = N->getOperand(1); 5483 5484 // Do we actually prefer shifts over mask? 5485 if (!TLI.shouldFoldMaskToVariableShiftPair(N0)) 5486 return SDValue(); 5487 5488 // Try to match (-1 '[outer] logical shift' y) 5489 unsigned OuterShift; 5490 unsigned InnerShift; // The opposite direction to the OuterShift. 5491 SDValue Y; // Shift amount. 5492 auto matchMask = [&OuterShift, &InnerShift, &Y](SDValue M) -> bool { 5493 if (!M.hasOneUse()) 5494 return false; 5495 OuterShift = M->getOpcode(); 5496 if (OuterShift == ISD::SHL) 5497 InnerShift = ISD::SRL; 5498 else if (OuterShift == ISD::SRL) 5499 InnerShift = ISD::SHL; 5500 else 5501 return false; 5502 if (!isAllOnesConstant(M->getOperand(0))) 5503 return false; 5504 Y = M->getOperand(1); 5505 return true; 5506 }; 5507 5508 SDValue X; 5509 if (matchMask(N1)) 5510 X = N0; 5511 else if (matchMask(N0)) 5512 X = N1; 5513 else 5514 return SDValue(); 5515 5516 SDLoc DL(N); 5517 EVT VT = N->getValueType(0); 5518 5519 // tmp = x 'opposite logical shift' y 5520 SDValue T0 = DAG.getNode(InnerShift, DL, VT, X, Y); 5521 // ret = tmp 'logical shift' y 5522 SDValue T1 = DAG.getNode(OuterShift, DL, VT, T0, Y); 5523 5524 return T1; 5525 } 5526 5527 /// Try to replace shift/logic that tests if a bit is clear with mask + setcc. 5528 /// For a target with a bit test, this is expected to become test + set and save 5529 /// at least 1 instruction. 5530 static SDValue combineShiftAnd1ToBitTest(SDNode *And, SelectionDAG &DAG) { 5531 assert(And->getOpcode() == ISD::AND && "Expected an 'and' op"); 5532 5533 // This is probably not worthwhile without a supported type. 5534 EVT VT = And->getValueType(0); 5535 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5536 if (!TLI.isTypeLegal(VT)) 5537 return SDValue(); 5538 5539 // Look through an optional extension and find a 'not'. 5540 // TODO: Should we favor test+set even without the 'not' op? 5541 SDValue Not = And->getOperand(0), And1 = And->getOperand(1); 5542 if (Not.getOpcode() == ISD::ANY_EXTEND) 5543 Not = Not.getOperand(0); 5544 if (!isBitwiseNot(Not) || !Not.hasOneUse() || !isOneConstant(And1)) 5545 return SDValue(); 5546 5547 // Look though an optional truncation. The source operand may not be the same 5548 // type as the original 'and', but that is ok because we are masking off 5549 // everything but the low bit. 5550 SDValue Srl = Not.getOperand(0); 5551 if (Srl.getOpcode() == ISD::TRUNCATE) 5552 Srl = Srl.getOperand(0); 5553 5554 // Match a shift-right by constant. 5555 if (Srl.getOpcode() != ISD::SRL || !Srl.hasOneUse() || 5556 !isa<ConstantSDNode>(Srl.getOperand(1))) 5557 return SDValue(); 5558 5559 // We might have looked through casts that make this transform invalid. 5560 // TODO: If the source type is wider than the result type, do the mask and 5561 // compare in the source type. 5562 const APInt &ShiftAmt = Srl.getConstantOperandAPInt(1); 5563 unsigned VTBitWidth = VT.getSizeInBits(); 5564 if (ShiftAmt.uge(VTBitWidth)) 5565 return SDValue(); 5566 5567 // Turn this into a bit-test pattern using mask op + setcc: 5568 // and (not (srl X, C)), 1 --> (and X, 1<<C) == 0 5569 SDLoc DL(And); 5570 SDValue X = DAG.getZExtOrTrunc(Srl.getOperand(0), DL, VT); 5571 EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 5572 SDValue Mask = DAG.getConstant( 5573 APInt::getOneBitSet(VTBitWidth, ShiftAmt.getZExtValue()), DL, VT); 5574 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, Mask); 5575 SDValue Zero = DAG.getConstant(0, DL, VT); 5576 SDValue Setcc = DAG.getSetCC(DL, CCVT, NewAnd, Zero, ISD::SETEQ); 5577 return DAG.getZExtOrTrunc(Setcc, DL, VT); 5578 } 5579 5580 SDValue DAGCombiner::visitAND(SDNode *N) { 5581 SDValue N0 = N->getOperand(0); 5582 SDValue N1 = N->getOperand(1); 5583 EVT VT = N1.getValueType(); 5584 5585 // x & x --> x 5586 if (N0 == N1) 5587 return N0; 5588 5589 // fold vector ops 5590 if (VT.isVector()) { 5591 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5592 return FoldedVOp; 5593 5594 // fold (and x, 0) -> 0, vector edition 5595 if (ISD::isConstantSplatVectorAllZeros(N0.getNode())) 5596 // do not return N0, because undef node may exist in N0 5597 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()), 5598 SDLoc(N), N0.getValueType()); 5599 if (ISD::isConstantSplatVectorAllZeros(N1.getNode())) 5600 // do not return N1, because undef node may exist in N1 5601 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()), 5602 SDLoc(N), N1.getValueType()); 5603 5604 // fold (and x, -1) -> x, vector edition 5605 if (ISD::isConstantSplatVectorAllOnes(N0.getNode())) 5606 return N1; 5607 if (ISD::isConstantSplatVectorAllOnes(N1.getNode())) 5608 return N0; 5609 5610 // fold (and (masked_load) (build_vec (x, ...))) to zext_masked_load 5611 auto *MLoad = dyn_cast<MaskedLoadSDNode>(N0); 5612 auto *BVec = dyn_cast<BuildVectorSDNode>(N1); 5613 if (MLoad && BVec && MLoad->getExtensionType() == ISD::EXTLOAD && 5614 N0.hasOneUse() && N1.hasOneUse()) { 5615 EVT LoadVT = MLoad->getMemoryVT(); 5616 EVT ExtVT = VT; 5617 if (TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT, LoadVT)) { 5618 // For this AND to be a zero extension of the masked load the elements 5619 // of the BuildVec must mask the bottom bits of the extended element 5620 // type 5621 if (ConstantSDNode *Splat = BVec->getConstantSplatNode()) { 5622 uint64_t ElementSize = 5623 LoadVT.getVectorElementType().getScalarSizeInBits(); 5624 if (Splat->getAPIntValue().isMask(ElementSize)) { 5625 return DAG.getMaskedLoad( 5626 ExtVT, SDLoc(N), MLoad->getChain(), MLoad->getBasePtr(), 5627 MLoad->getOffset(), MLoad->getMask(), MLoad->getPassThru(), 5628 LoadVT, MLoad->getMemOperand(), MLoad->getAddressingMode(), 5629 ISD::ZEXTLOAD, MLoad->isExpandingLoad()); 5630 } 5631 } 5632 } 5633 } 5634 } 5635 5636 // fold (and c1, c2) -> c1&c2 5637 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5638 if (SDValue C = DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, {N0, N1})) 5639 return C; 5640 5641 // canonicalize constant to RHS 5642 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 5643 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 5644 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 5645 5646 // fold (and x, -1) -> x 5647 if (isAllOnesConstant(N1)) 5648 return N0; 5649 5650 // if (and x, c) is known to be zero, return 0 5651 unsigned BitWidth = VT.getScalarSizeInBits(); 5652 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 5653 APInt::getAllOnesValue(BitWidth))) 5654 return DAG.getConstant(0, SDLoc(N), VT); 5655 5656 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5657 return NewSel; 5658 5659 // reassociate and 5660 if (SDValue RAND = reassociateOps(ISD::AND, SDLoc(N), N0, N1, N->getFlags())) 5661 return RAND; 5662 5663 // Try to convert a constant mask AND into a shuffle clear mask. 5664 if (VT.isVector()) 5665 if (SDValue Shuffle = XformToShuffleWithZero(N)) 5666 return Shuffle; 5667 5668 if (SDValue Combined = combineCarryDiamond(*this, DAG, TLI, N0, N1, N)) 5669 return Combined; 5670 5671 // fold (and (or x, C), D) -> D if (C & D) == D 5672 auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) { 5673 return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue()); 5674 }; 5675 if (N0.getOpcode() == ISD::OR && 5676 ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset)) 5677 return N1; 5678 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 5679 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 5680 SDValue N0Op0 = N0.getOperand(0); 5681 APInt Mask = ~N1C->getAPIntValue(); 5682 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits()); 5683 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 5684 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 5685 N0.getValueType(), N0Op0); 5686 5687 // Replace uses of the AND with uses of the Zero extend node. 5688 CombineTo(N, Zext); 5689 5690 // We actually want to replace all uses of the any_extend with the 5691 // zero_extend, to avoid duplicating things. This will later cause this 5692 // AND to be folded. 5693 CombineTo(N0.getNode(), Zext); 5694 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5695 } 5696 } 5697 5698 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 5699 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 5700 // already be zero by virtue of the width of the base type of the load. 5701 // 5702 // the 'X' node here can either be nothing or an extract_vector_elt to catch 5703 // more cases. 5704 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5705 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 5706 N0.getOperand(0).getOpcode() == ISD::LOAD && 5707 N0.getOperand(0).getResNo() == 0) || 5708 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { 5709 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 5710 N0 : N0.getOperand(0) ); 5711 5712 // Get the constant (if applicable) the zero'th operand is being ANDed with. 5713 // This can be a pure constant or a vector splat, in which case we treat the 5714 // vector as a scalar and use the splat value. 5715 APInt Constant = APInt::getNullValue(1); 5716 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 5717 Constant = C->getAPIntValue(); 5718 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 5719 APInt SplatValue, SplatUndef; 5720 unsigned SplatBitSize; 5721 bool HasAnyUndefs; 5722 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 5723 SplatBitSize, HasAnyUndefs); 5724 if (IsSplat) { 5725 // Undef bits can contribute to a possible optimisation if set, so 5726 // set them. 5727 SplatValue |= SplatUndef; 5728 5729 // The splat value may be something like "0x00FFFFFF", which means 0 for 5730 // the first vector value and FF for the rest, repeating. We need a mask 5731 // that will apply equally to all members of the vector, so AND all the 5732 // lanes of the constant together. 5733 unsigned EltBitWidth = Vector->getValueType(0).getScalarSizeInBits(); 5734 5735 // If the splat value has been compressed to a bitlength lower 5736 // than the size of the vector lane, we need to re-expand it to 5737 // the lane size. 5738 if (EltBitWidth > SplatBitSize) 5739 for (SplatValue = SplatValue.zextOrTrunc(EltBitWidth); 5740 SplatBitSize < EltBitWidth; SplatBitSize = SplatBitSize * 2) 5741 SplatValue |= SplatValue.shl(SplatBitSize); 5742 5743 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 5744 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 5745 if ((SplatBitSize % EltBitWidth) == 0) { 5746 Constant = APInt::getAllOnesValue(EltBitWidth); 5747 for (unsigned i = 0, n = (SplatBitSize / EltBitWidth); i < n; ++i) 5748 Constant &= SplatValue.extractBits(EltBitWidth, i * EltBitWidth); 5749 } 5750 } 5751 } 5752 5753 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 5754 // actually legal and isn't going to get expanded, else this is a false 5755 // optimisation. 5756 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 5757 Load->getValueType(0), 5758 Load->getMemoryVT()); 5759 5760 // Resize the constant to the same size as the original memory access before 5761 // extension. If it is still the AllOnesValue then this AND is completely 5762 // unneeded. 5763 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits()); 5764 5765 bool B; 5766 switch (Load->getExtensionType()) { 5767 default: B = false; break; 5768 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 5769 case ISD::ZEXTLOAD: 5770 case ISD::NON_EXTLOAD: B = true; break; 5771 } 5772 5773 if (B && Constant.isAllOnesValue()) { 5774 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 5775 // preserve semantics once we get rid of the AND. 5776 SDValue NewLoad(Load, 0); 5777 5778 // Fold the AND away. NewLoad may get replaced immediately. 5779 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 5780 5781 if (Load->getExtensionType() == ISD::EXTLOAD) { 5782 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 5783 Load->getValueType(0), SDLoc(Load), 5784 Load->getChain(), Load->getBasePtr(), 5785 Load->getOffset(), Load->getMemoryVT(), 5786 Load->getMemOperand()); 5787 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 5788 if (Load->getNumValues() == 3) { 5789 // PRE/POST_INC loads have 3 values. 5790 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 5791 NewLoad.getValue(2) }; 5792 CombineTo(Load, To, 3, true); 5793 } else { 5794 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 5795 } 5796 } 5797 5798 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5799 } 5800 } 5801 5802 // fold (and (masked_gather x)) -> (zext_masked_gather x) 5803 if (auto *GN0 = dyn_cast<MaskedGatherSDNode>(N0)) { 5804 EVT MemVT = GN0->getMemoryVT(); 5805 EVT ScalarVT = MemVT.getScalarType(); 5806 5807 if (SDValue(GN0, 0).hasOneUse() && 5808 isConstantSplatVectorMaskForType(N1.getNode(), ScalarVT) && 5809 TLI.isVectorLoadExtDesirable(SDValue(SDValue(GN0, 0)))) { 5810 SDValue Ops[] = {GN0->getChain(), GN0->getPassThru(), GN0->getMask(), 5811 GN0->getBasePtr(), GN0->getIndex(), GN0->getScale()}; 5812 5813 SDValue ZExtLoad = DAG.getMaskedGather( 5814 DAG.getVTList(VT, MVT::Other), MemVT, SDLoc(N), Ops, 5815 GN0->getMemOperand(), GN0->getIndexType(), ISD::ZEXTLOAD); 5816 5817 CombineTo(N, ZExtLoad); 5818 AddToWorklist(ZExtLoad.getNode()); 5819 // Avoid recheck of N. 5820 return SDValue(N, 0); 5821 } 5822 } 5823 5824 // fold (and (load x), 255) -> (zextload x, i8) 5825 // fold (and (extload x, i16), 255) -> (zextload x, i8) 5826 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 5827 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD || 5828 (N0.getOpcode() == ISD::ANY_EXTEND && 5829 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 5830 if (SDValue Res = ReduceLoadWidth(N)) { 5831 LoadSDNode *LN0 = N0->getOpcode() == ISD::ANY_EXTEND 5832 ? cast<LoadSDNode>(N0.getOperand(0)) : cast<LoadSDNode>(N0); 5833 AddToWorklist(N); 5834 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 0), Res); 5835 return SDValue(N, 0); 5836 } 5837 } 5838 5839 if (LegalTypes) { 5840 // Attempt to propagate the AND back up to the leaves which, if they're 5841 // loads, can be combined to narrow loads and the AND node can be removed. 5842 // Perform after legalization so that extend nodes will already be 5843 // combined into the loads. 5844 if (BackwardsPropagateMask(N)) 5845 return SDValue(N, 0); 5846 } 5847 5848 if (SDValue Combined = visitANDLike(N0, N1, N)) 5849 return Combined; 5850 5851 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 5852 if (N0.getOpcode() == N1.getOpcode()) 5853 if (SDValue V = hoistLogicOpWithSameOpcodeHands(N)) 5854 return V; 5855 5856 // Masking the negated extension of a boolean is just the zero-extended 5857 // boolean: 5858 // and (sub 0, zext(bool X)), 1 --> zext(bool X) 5859 // and (sub 0, sext(bool X)), 1 --> zext(bool X) 5860 // 5861 // Note: the SimplifyDemandedBits fold below can make an information-losing 5862 // transform, and then we have no way to find this better fold. 5863 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) { 5864 if (isNullOrNullSplat(N0.getOperand(0))) { 5865 SDValue SubRHS = N0.getOperand(1); 5866 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND && 5867 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 5868 return SubRHS; 5869 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND && 5870 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 5871 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0)); 5872 } 5873 } 5874 5875 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 5876 // fold (and (sra)) -> (and (srl)) when possible. 5877 if (SimplifyDemandedBits(SDValue(N, 0))) 5878 return SDValue(N, 0); 5879 5880 // fold (zext_inreg (extload x)) -> (zextload x) 5881 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 5882 if (ISD::isUNINDEXEDLoad(N0.getNode()) && 5883 (ISD::isEXTLoad(N0.getNode()) || 5884 (ISD::isSEXTLoad(N0.getNode()) && N0.hasOneUse()))) { 5885 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5886 EVT MemVT = LN0->getMemoryVT(); 5887 // If we zero all the possible extended bits, then we can turn this into 5888 // a zextload if we are running before legalize or the operation is legal. 5889 unsigned ExtBitSize = N1.getScalarValueSizeInBits(); 5890 unsigned MemBitSize = MemVT.getScalarSizeInBits(); 5891 APInt ExtBits = APInt::getHighBitsSet(ExtBitSize, ExtBitSize - MemBitSize); 5892 if (DAG.MaskedValueIsZero(N1, ExtBits) && 5893 ((!LegalOperations && LN0->isSimple()) || 5894 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 5895 SDValue ExtLoad = 5896 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, LN0->getChain(), 5897 LN0->getBasePtr(), MemVT, LN0->getMemOperand()); 5898 AddToWorklist(N); 5899 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 5900 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5901 } 5902 } 5903 5904 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 5905 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 5906 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 5907 N0.getOperand(1), false)) 5908 return BSwap; 5909 } 5910 5911 if (SDValue Shifts = unfoldExtremeBitClearingToShifts(N)) 5912 return Shifts; 5913 5914 if (TLI.hasBitTest(N0, N1)) 5915 if (SDValue V = combineShiftAnd1ToBitTest(N, DAG)) 5916 return V; 5917 5918 // Recognize the following pattern: 5919 // 5920 // AndVT = (and (sign_extend NarrowVT to AndVT) #bitmask) 5921 // 5922 // where bitmask is a mask that clears the upper bits of AndVT. The 5923 // number of bits in bitmask must be a power of two. 5924 auto IsAndZeroExtMask = [](SDValue LHS, SDValue RHS) { 5925 if (LHS->getOpcode() != ISD::SIGN_EXTEND) 5926 return false; 5927 5928 auto *C = dyn_cast<ConstantSDNode>(RHS); 5929 if (!C) 5930 return false; 5931 5932 if (!C->getAPIntValue().isMask( 5933 LHS.getOperand(0).getValueType().getFixedSizeInBits())) 5934 return false; 5935 5936 return true; 5937 }; 5938 5939 // Replace (and (sign_extend ...) #bitmask) with (zero_extend ...). 5940 if (IsAndZeroExtMask(N0, N1)) 5941 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0.getOperand(0)); 5942 5943 return SDValue(); 5944 } 5945 5946 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 5947 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 5948 bool DemandHighBits) { 5949 if (!LegalOperations) 5950 return SDValue(); 5951 5952 EVT VT = N->getValueType(0); 5953 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 5954 return SDValue(); 5955 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 5956 return SDValue(); 5957 5958 // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff) 5959 bool LookPassAnd0 = false; 5960 bool LookPassAnd1 = false; 5961 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 5962 std::swap(N0, N1); 5963 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 5964 std::swap(N0, N1); 5965 if (N0.getOpcode() == ISD::AND) { 5966 if (!N0.getNode()->hasOneUse()) 5967 return SDValue(); 5968 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5969 // Also handle 0xffff since the LHS is guaranteed to have zeros there. 5970 // This is needed for X86. 5971 if (!N01C || (N01C->getZExtValue() != 0xFF00 && 5972 N01C->getZExtValue() != 0xFFFF)) 5973 return SDValue(); 5974 N0 = N0.getOperand(0); 5975 LookPassAnd0 = true; 5976 } 5977 5978 if (N1.getOpcode() == ISD::AND) { 5979 if (!N1.getNode()->hasOneUse()) 5980 return SDValue(); 5981 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 5982 if (!N11C || N11C->getZExtValue() != 0xFF) 5983 return SDValue(); 5984 N1 = N1.getOperand(0); 5985 LookPassAnd1 = true; 5986 } 5987 5988 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 5989 std::swap(N0, N1); 5990 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 5991 return SDValue(); 5992 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse()) 5993 return SDValue(); 5994 5995 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5996 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 5997 if (!N01C || !N11C) 5998 return SDValue(); 5999 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 6000 return SDValue(); 6001 6002 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 6003 SDValue N00 = N0->getOperand(0); 6004 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 6005 if (!N00.getNode()->hasOneUse()) 6006 return SDValue(); 6007 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 6008 if (!N001C || N001C->getZExtValue() != 0xFF) 6009 return SDValue(); 6010 N00 = N00.getOperand(0); 6011 LookPassAnd0 = true; 6012 } 6013 6014 SDValue N10 = N1->getOperand(0); 6015 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 6016 if (!N10.getNode()->hasOneUse()) 6017 return SDValue(); 6018 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 6019 // Also allow 0xFFFF since the bits will be shifted out. This is needed 6020 // for X86. 6021 if (!N101C || (N101C->getZExtValue() != 0xFF00 && 6022 N101C->getZExtValue() != 0xFFFF)) 6023 return SDValue(); 6024 N10 = N10.getOperand(0); 6025 LookPassAnd1 = true; 6026 } 6027 6028 if (N00 != N10) 6029 return SDValue(); 6030 6031 // Make sure everything beyond the low halfword gets set to zero since the SRL 6032 // 16 will clear the top bits. 6033 unsigned OpSizeInBits = VT.getSizeInBits(); 6034 if (DemandHighBits && OpSizeInBits > 16) { 6035 // If the left-shift isn't masked out then the only way this is a bswap is 6036 // if all bits beyond the low 8 are 0. In that case the entire pattern 6037 // reduces to a left shift anyway: leave it for other parts of the combiner. 6038 if (!LookPassAnd0) 6039 return SDValue(); 6040 6041 // However, if the right shift isn't masked out then it might be because 6042 // it's not needed. See if we can spot that too. 6043 if (!LookPassAnd1 && 6044 !DAG.MaskedValueIsZero( 6045 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 6046 return SDValue(); 6047 } 6048 6049 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 6050 if (OpSizeInBits > 16) { 6051 SDLoc DL(N); 6052 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 6053 DAG.getConstant(OpSizeInBits - 16, DL, 6054 getShiftAmountTy(VT))); 6055 } 6056 return Res; 6057 } 6058 6059 /// Return true if the specified node is an element that makes up a 32-bit 6060 /// packed halfword byteswap. 6061 /// ((x & 0x000000ff) << 8) | 6062 /// ((x & 0x0000ff00) >> 8) | 6063 /// ((x & 0x00ff0000) << 8) | 6064 /// ((x & 0xff000000) >> 8) 6065 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 6066 if (!N.getNode()->hasOneUse()) 6067 return false; 6068 6069 unsigned Opc = N.getOpcode(); 6070 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 6071 return false; 6072 6073 SDValue N0 = N.getOperand(0); 6074 unsigned Opc0 = N0.getOpcode(); 6075 if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL) 6076 return false; 6077 6078 ConstantSDNode *N1C = nullptr; 6079 // SHL or SRL: look upstream for AND mask operand 6080 if (Opc == ISD::AND) 6081 N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 6082 else if (Opc0 == ISD::AND) 6083 N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6084 if (!N1C) 6085 return false; 6086 6087 unsigned MaskByteOffset; 6088 switch (N1C->getZExtValue()) { 6089 default: 6090 return false; 6091 case 0xFF: MaskByteOffset = 0; break; 6092 case 0xFF00: MaskByteOffset = 1; break; 6093 case 0xFFFF: 6094 // In case demanded bits didn't clear the bits that will be shifted out. 6095 // This is needed for X86. 6096 if (Opc == ISD::SRL || (Opc == ISD::AND && Opc0 == ISD::SHL)) { 6097 MaskByteOffset = 1; 6098 break; 6099 } 6100 return false; 6101 case 0xFF0000: MaskByteOffset = 2; break; 6102 case 0xFF000000: MaskByteOffset = 3; break; 6103 } 6104 6105 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 6106 if (Opc == ISD::AND) { 6107 if (MaskByteOffset == 0 || MaskByteOffset == 2) { 6108 // (x >> 8) & 0xff 6109 // (x >> 8) & 0xff0000 6110 if (Opc0 != ISD::SRL) 6111 return false; 6112 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6113 if (!C || C->getZExtValue() != 8) 6114 return false; 6115 } else { 6116 // (x << 8) & 0xff00 6117 // (x << 8) & 0xff000000 6118 if (Opc0 != ISD::SHL) 6119 return false; 6120 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6121 if (!C || C->getZExtValue() != 8) 6122 return false; 6123 } 6124 } else if (Opc == ISD::SHL) { 6125 // (x & 0xff) << 8 6126 // (x & 0xff0000) << 8 6127 if (MaskByteOffset != 0 && MaskByteOffset != 2) 6128 return false; 6129 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 6130 if (!C || C->getZExtValue() != 8) 6131 return false; 6132 } else { // Opc == ISD::SRL 6133 // (x & 0xff00) >> 8 6134 // (x & 0xff000000) >> 8 6135 if (MaskByteOffset != 1 && MaskByteOffset != 3) 6136 return false; 6137 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 6138 if (!C || C->getZExtValue() != 8) 6139 return false; 6140 } 6141 6142 if (Parts[MaskByteOffset]) 6143 return false; 6144 6145 Parts[MaskByteOffset] = N0.getOperand(0).getNode(); 6146 return true; 6147 } 6148 6149 // Match 2 elements of a packed halfword bswap. 6150 static bool isBSwapHWordPair(SDValue N, MutableArrayRef<SDNode *> Parts) { 6151 if (N.getOpcode() == ISD::OR) 6152 return isBSwapHWordElement(N.getOperand(0), Parts) && 6153 isBSwapHWordElement(N.getOperand(1), Parts); 6154 6155 if (N.getOpcode() == ISD::SRL && N.getOperand(0).getOpcode() == ISD::BSWAP) { 6156 ConstantSDNode *C = isConstOrConstSplat(N.getOperand(1)); 6157 if (!C || C->getAPIntValue() != 16) 6158 return false; 6159 Parts[0] = Parts[1] = N.getOperand(0).getOperand(0).getNode(); 6160 return true; 6161 } 6162 6163 return false; 6164 } 6165 6166 // Match this pattern: 6167 // (or (and (shl (A, 8)), 0xff00ff00), (and (srl (A, 8)), 0x00ff00ff)) 6168 // And rewrite this to: 6169 // (rotr (bswap A), 16) 6170 static SDValue matchBSwapHWordOrAndAnd(const TargetLowering &TLI, 6171 SelectionDAG &DAG, SDNode *N, SDValue N0, 6172 SDValue N1, EVT VT, EVT ShiftAmountTy) { 6173 assert(N->getOpcode() == ISD::OR && VT == MVT::i32 && 6174 "MatchBSwapHWordOrAndAnd: expecting i32"); 6175 if (!TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 6176 return SDValue(); 6177 if (N0.getOpcode() != ISD::AND || N1.getOpcode() != ISD::AND) 6178 return SDValue(); 6179 // TODO: this is too restrictive; lifting this restriction requires more tests 6180 if (!N0->hasOneUse() || !N1->hasOneUse()) 6181 return SDValue(); 6182 ConstantSDNode *Mask0 = isConstOrConstSplat(N0.getOperand(1)); 6183 ConstantSDNode *Mask1 = isConstOrConstSplat(N1.getOperand(1)); 6184 if (!Mask0 || !Mask1) 6185 return SDValue(); 6186 if (Mask0->getAPIntValue() != 0xff00ff00 || 6187 Mask1->getAPIntValue() != 0x00ff00ff) 6188 return SDValue(); 6189 SDValue Shift0 = N0.getOperand(0); 6190 SDValue Shift1 = N1.getOperand(0); 6191 if (Shift0.getOpcode() != ISD::SHL || Shift1.getOpcode() != ISD::SRL) 6192 return SDValue(); 6193 ConstantSDNode *ShiftAmt0 = isConstOrConstSplat(Shift0.getOperand(1)); 6194 ConstantSDNode *ShiftAmt1 = isConstOrConstSplat(Shift1.getOperand(1)); 6195 if (!ShiftAmt0 || !ShiftAmt1) 6196 return SDValue(); 6197 if (ShiftAmt0->getAPIntValue() != 8 || ShiftAmt1->getAPIntValue() != 8) 6198 return SDValue(); 6199 if (Shift0.getOperand(0) != Shift1.getOperand(0)) 6200 return SDValue(); 6201 6202 SDLoc DL(N); 6203 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Shift0.getOperand(0)); 6204 SDValue ShAmt = DAG.getConstant(16, DL, ShiftAmountTy); 6205 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 6206 } 6207 6208 /// Match a 32-bit packed halfword bswap. That is 6209 /// ((x & 0x000000ff) << 8) | 6210 /// ((x & 0x0000ff00) >> 8) | 6211 /// ((x & 0x00ff0000) << 8) | 6212 /// ((x & 0xff000000) >> 8) 6213 /// => (rotl (bswap x), 16) 6214 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 6215 if (!LegalOperations) 6216 return SDValue(); 6217 6218 EVT VT = N->getValueType(0); 6219 if (VT != MVT::i32) 6220 return SDValue(); 6221 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 6222 return SDValue(); 6223 6224 if (SDValue BSwap = matchBSwapHWordOrAndAnd(TLI, DAG, N, N0, N1, VT, 6225 getShiftAmountTy(VT))) 6226 return BSwap; 6227 6228 // Try again with commuted operands. 6229 if (SDValue BSwap = matchBSwapHWordOrAndAnd(TLI, DAG, N, N1, N0, VT, 6230 getShiftAmountTy(VT))) 6231 return BSwap; 6232 6233 6234 // Look for either 6235 // (or (bswaphpair), (bswaphpair)) 6236 // (or (or (bswaphpair), (and)), (and)) 6237 // (or (or (and), (bswaphpair)), (and)) 6238 SDNode *Parts[4] = {}; 6239 6240 if (isBSwapHWordPair(N0, Parts)) { 6241 // (or (or (and), (and)), (or (and), (and))) 6242 if (!isBSwapHWordPair(N1, Parts)) 6243 return SDValue(); 6244 } else if (N0.getOpcode() == ISD::OR) { 6245 // (or (or (or (and), (and)), (and)), (and)) 6246 if (!isBSwapHWordElement(N1, Parts)) 6247 return SDValue(); 6248 SDValue N00 = N0.getOperand(0); 6249 SDValue N01 = N0.getOperand(1); 6250 if (!(isBSwapHWordElement(N01, Parts) && isBSwapHWordPair(N00, Parts)) && 6251 !(isBSwapHWordElement(N00, Parts) && isBSwapHWordPair(N01, Parts))) 6252 return SDValue(); 6253 } else 6254 return SDValue(); 6255 6256 // Make sure the parts are all coming from the same node. 6257 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 6258 return SDValue(); 6259 6260 SDLoc DL(N); 6261 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 6262 SDValue(Parts[0], 0)); 6263 6264 // Result of the bswap should be rotated by 16. If it's not legal, then 6265 // do (x << 16) | (x >> 16). 6266 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 6267 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 6268 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 6269 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 6270 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 6271 return DAG.getNode(ISD::OR, DL, VT, 6272 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 6273 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 6274 } 6275 6276 /// This contains all DAGCombine rules which reduce two values combined by 6277 /// an Or operation to a single value \see visitANDLike(). 6278 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) { 6279 EVT VT = N1.getValueType(); 6280 SDLoc DL(N); 6281 6282 // fold (or x, undef) -> -1 6283 if (!LegalOperations && (N0.isUndef() || N1.isUndef())) 6284 return DAG.getAllOnesConstant(DL, VT); 6285 6286 if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL)) 6287 return V; 6288 6289 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 6290 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 6291 // Don't increase # computations. 6292 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 6293 // We can only do this xform if we know that bits from X that are set in C2 6294 // but not in C1 are already zero. Likewise for Y. 6295 if (const ConstantSDNode *N0O1C = 6296 getAsNonOpaqueConstant(N0.getOperand(1))) { 6297 if (const ConstantSDNode *N1O1C = 6298 getAsNonOpaqueConstant(N1.getOperand(1))) { 6299 // We can only do this xform if we know that bits from X that are set in 6300 // C2 but not in C1 are already zero. Likewise for Y. 6301 const APInt &LHSMask = N0O1C->getAPIntValue(); 6302 const APInt &RHSMask = N1O1C->getAPIntValue(); 6303 6304 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 6305 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 6306 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 6307 N0.getOperand(0), N1.getOperand(0)); 6308 return DAG.getNode(ISD::AND, DL, VT, X, 6309 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 6310 } 6311 } 6312 } 6313 } 6314 6315 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 6316 if (N0.getOpcode() == ISD::AND && 6317 N1.getOpcode() == ISD::AND && 6318 N0.getOperand(0) == N1.getOperand(0) && 6319 // Don't increase # computations. 6320 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 6321 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 6322 N0.getOperand(1), N1.getOperand(1)); 6323 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X); 6324 } 6325 6326 return SDValue(); 6327 } 6328 6329 /// OR combines for which the commuted variant will be tried as well. 6330 static SDValue visitORCommutative( 6331 SelectionDAG &DAG, SDValue N0, SDValue N1, SDNode *N) { 6332 EVT VT = N0.getValueType(); 6333 if (N0.getOpcode() == ISD::AND) { 6334 // fold (or (and X, (xor Y, -1)), Y) -> (or X, Y) 6335 if (isBitwiseNot(N0.getOperand(1)) && N0.getOperand(1).getOperand(0) == N1) 6336 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0.getOperand(0), N1); 6337 6338 // fold (or (and (xor Y, -1), X), Y) -> (or X, Y) 6339 if (isBitwiseNot(N0.getOperand(0)) && N0.getOperand(0).getOperand(0) == N1) 6340 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0.getOperand(1), N1); 6341 } 6342 6343 return SDValue(); 6344 } 6345 6346 SDValue DAGCombiner::visitOR(SDNode *N) { 6347 SDValue N0 = N->getOperand(0); 6348 SDValue N1 = N->getOperand(1); 6349 EVT VT = N1.getValueType(); 6350 6351 // x | x --> x 6352 if (N0 == N1) 6353 return N0; 6354 6355 // fold vector ops 6356 if (VT.isVector()) { 6357 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 6358 return FoldedVOp; 6359 6360 // fold (or x, 0) -> x, vector edition 6361 if (ISD::isConstantSplatVectorAllZeros(N0.getNode())) 6362 return N1; 6363 if (ISD::isConstantSplatVectorAllZeros(N1.getNode())) 6364 return N0; 6365 6366 // fold (or x, -1) -> -1, vector edition 6367 if (ISD::isConstantSplatVectorAllOnes(N0.getNode())) 6368 // do not return N0, because undef node may exist in N0 6369 return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType()); 6370 if (ISD::isConstantSplatVectorAllOnes(N1.getNode())) 6371 // do not return N1, because undef node may exist in N1 6372 return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType()); 6373 6374 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask) 6375 // Do this only if the resulting shuffle is legal. 6376 if (isa<ShuffleVectorSDNode>(N0) && 6377 isa<ShuffleVectorSDNode>(N1) && 6378 // Avoid folding a node with illegal type. 6379 TLI.isTypeLegal(VT)) { 6380 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode()); 6381 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()); 6382 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 6383 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode()); 6384 // Ensure both shuffles have a zero input. 6385 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) { 6386 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!"); 6387 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!"); 6388 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 6389 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 6390 bool CanFold = true; 6391 int NumElts = VT.getVectorNumElements(); 6392 SmallVector<int, 4> Mask(NumElts); 6393 6394 for (int i = 0; i != NumElts; ++i) { 6395 int M0 = SV0->getMaskElt(i); 6396 int M1 = SV1->getMaskElt(i); 6397 6398 // Determine if either index is pointing to a zero vector. 6399 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts)); 6400 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts)); 6401 6402 // If one element is zero and the otherside is undef, keep undef. 6403 // This also handles the case that both are undef. 6404 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) { 6405 Mask[i] = -1; 6406 continue; 6407 } 6408 6409 // Make sure only one of the elements is zero. 6410 if (M0Zero == M1Zero) { 6411 CanFold = false; 6412 break; 6413 } 6414 6415 assert((M0 >= 0 || M1 >= 0) && "Undef index!"); 6416 6417 // We have a zero and non-zero element. If the non-zero came from 6418 // SV0 make the index a LHS index. If it came from SV1, make it 6419 // a RHS index. We need to mod by NumElts because we don't care 6420 // which operand it came from in the original shuffles. 6421 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts; 6422 } 6423 6424 if (CanFold) { 6425 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0); 6426 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0); 6427 6428 SDValue LegalShuffle = 6429 TLI.buildLegalVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, 6430 Mask, DAG); 6431 if (LegalShuffle) 6432 return LegalShuffle; 6433 } 6434 } 6435 } 6436 } 6437 6438 // fold (or c1, c2) -> c1|c2 6439 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 6440 if (SDValue C = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, {N0, N1})) 6441 return C; 6442 6443 // canonicalize constant to RHS 6444 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 6445 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 6446 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 6447 6448 // fold (or x, 0) -> x 6449 if (isNullConstant(N1)) 6450 return N0; 6451 6452 // fold (or x, -1) -> -1 6453 if (isAllOnesConstant(N1)) 6454 return N1; 6455 6456 if (SDValue NewSel = foldBinOpIntoSelect(N)) 6457 return NewSel; 6458 6459 // fold (or x, c) -> c iff (x & ~c) == 0 6460 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 6461 return N1; 6462 6463 if (SDValue Combined = visitORLike(N0, N1, N)) 6464 return Combined; 6465 6466 if (SDValue Combined = combineCarryDiamond(*this, DAG, TLI, N0, N1, N)) 6467 return Combined; 6468 6469 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 6470 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 6471 return BSwap; 6472 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 6473 return BSwap; 6474 6475 // reassociate or 6476 if (SDValue ROR = reassociateOps(ISD::OR, SDLoc(N), N0, N1, N->getFlags())) 6477 return ROR; 6478 6479 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 6480 // iff (c1 & c2) != 0 or c1/c2 are undef. 6481 auto MatchIntersect = [](ConstantSDNode *C1, ConstantSDNode *C2) { 6482 return !C1 || !C2 || C1->getAPIntValue().intersects(C2->getAPIntValue()); 6483 }; 6484 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 6485 ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchIntersect, true)) { 6486 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, 6487 {N1, N0.getOperand(1)})) { 6488 SDValue IOR = DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1); 6489 AddToWorklist(IOR.getNode()); 6490 return DAG.getNode(ISD::AND, SDLoc(N), VT, COR, IOR); 6491 } 6492 } 6493 6494 if (SDValue Combined = visitORCommutative(DAG, N0, N1, N)) 6495 return Combined; 6496 if (SDValue Combined = visitORCommutative(DAG, N1, N0, N)) 6497 return Combined; 6498 6499 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 6500 if (N0.getOpcode() == N1.getOpcode()) 6501 if (SDValue V = hoistLogicOpWithSameOpcodeHands(N)) 6502 return V; 6503 6504 // See if this is some rotate idiom. 6505 if (SDValue Rot = MatchRotate(N0, N1, SDLoc(N))) 6506 return Rot; 6507 6508 if (SDValue Load = MatchLoadCombine(N)) 6509 return Load; 6510 6511 // Simplify the operands using demanded-bits information. 6512 if (SimplifyDemandedBits(SDValue(N, 0))) 6513 return SDValue(N, 0); 6514 6515 // If OR can be rewritten into ADD, try combines based on ADD. 6516 if ((!LegalOperations || TLI.isOperationLegal(ISD::ADD, VT)) && 6517 DAG.haveNoCommonBitsSet(N0, N1)) 6518 if (SDValue Combined = visitADDLike(N)) 6519 return Combined; 6520 6521 return SDValue(); 6522 } 6523 6524 static SDValue stripConstantMask(SelectionDAG &DAG, SDValue Op, SDValue &Mask) { 6525 if (Op.getOpcode() == ISD::AND && 6526 DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 6527 Mask = Op.getOperand(1); 6528 return Op.getOperand(0); 6529 } 6530 return Op; 6531 } 6532 6533 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 6534 static bool matchRotateHalf(SelectionDAG &DAG, SDValue Op, SDValue &Shift, 6535 SDValue &Mask) { 6536 Op = stripConstantMask(DAG, Op, Mask); 6537 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 6538 Shift = Op; 6539 return true; 6540 } 6541 return false; 6542 } 6543 6544 /// Helper function for visitOR to extract the needed side of a rotate idiom 6545 /// from a shl/srl/mul/udiv. This is meant to handle cases where 6546 /// InstCombine merged some outside op with one of the shifts from 6547 /// the rotate pattern. 6548 /// \returns An empty \c SDValue if the needed shift couldn't be extracted. 6549 /// Otherwise, returns an expansion of \p ExtractFrom based on the following 6550 /// patterns: 6551 /// 6552 /// (or (add v v) (shrl v bitwidth-1)): 6553 /// expands (add v v) -> (shl v 1) 6554 /// 6555 /// (or (mul v c0) (shrl (mul v c1) c2)): 6556 /// expands (mul v c0) -> (shl (mul v c1) c3) 6557 /// 6558 /// (or (udiv v c0) (shl (udiv v c1) c2)): 6559 /// expands (udiv v c0) -> (shrl (udiv v c1) c3) 6560 /// 6561 /// (or (shl v c0) (shrl (shl v c1) c2)): 6562 /// expands (shl v c0) -> (shl (shl v c1) c3) 6563 /// 6564 /// (or (shrl v c0) (shl (shrl v c1) c2)): 6565 /// expands (shrl v c0) -> (shrl (shrl v c1) c3) 6566 /// 6567 /// Such that in all cases, c3+c2==bitwidth(op v c1). 6568 static SDValue extractShiftForRotate(SelectionDAG &DAG, SDValue OppShift, 6569 SDValue ExtractFrom, SDValue &Mask, 6570 const SDLoc &DL) { 6571 assert(OppShift && ExtractFrom && "Empty SDValue"); 6572 assert( 6573 (OppShift.getOpcode() == ISD::SHL || OppShift.getOpcode() == ISD::SRL) && 6574 "Existing shift must be valid as a rotate half"); 6575 6576 ExtractFrom = stripConstantMask(DAG, ExtractFrom, Mask); 6577 6578 // Value and Type of the shift. 6579 SDValue OppShiftLHS = OppShift.getOperand(0); 6580 EVT ShiftedVT = OppShiftLHS.getValueType(); 6581 6582 // Amount of the existing shift. 6583 ConstantSDNode *OppShiftCst = isConstOrConstSplat(OppShift.getOperand(1)); 6584 6585 // (add v v) -> (shl v 1) 6586 // TODO: Should this be a general DAG canonicalization? 6587 if (OppShift.getOpcode() == ISD::SRL && OppShiftCst && 6588 ExtractFrom.getOpcode() == ISD::ADD && 6589 ExtractFrom.getOperand(0) == ExtractFrom.getOperand(1) && 6590 ExtractFrom.getOperand(0) == OppShiftLHS && 6591 OppShiftCst->getAPIntValue() == ShiftedVT.getScalarSizeInBits() - 1) 6592 return DAG.getNode(ISD::SHL, DL, ShiftedVT, OppShiftLHS, 6593 DAG.getShiftAmountConstant(1, ShiftedVT, DL)); 6594 6595 // Preconditions: 6596 // (or (op0 v c0) (shiftl/r (op0 v c1) c2)) 6597 // 6598 // Find opcode of the needed shift to be extracted from (op0 v c0). 6599 unsigned Opcode = ISD::DELETED_NODE; 6600 bool IsMulOrDiv = false; 6601 // Set Opcode and IsMulOrDiv if the extract opcode matches the needed shift 6602 // opcode or its arithmetic (mul or udiv) variant. 6603 auto SelectOpcode = [&](unsigned NeededShift, unsigned MulOrDivVariant) { 6604 IsMulOrDiv = ExtractFrom.getOpcode() == MulOrDivVariant; 6605 if (!IsMulOrDiv && ExtractFrom.getOpcode() != NeededShift) 6606 return false; 6607 Opcode = NeededShift; 6608 return true; 6609 }; 6610 // op0 must be either the needed shift opcode or the mul/udiv equivalent 6611 // that the needed shift can be extracted from. 6612 if ((OppShift.getOpcode() != ISD::SRL || !SelectOpcode(ISD::SHL, ISD::MUL)) && 6613 (OppShift.getOpcode() != ISD::SHL || !SelectOpcode(ISD::SRL, ISD::UDIV))) 6614 return SDValue(); 6615 6616 // op0 must be the same opcode on both sides, have the same LHS argument, 6617 // and produce the same value type. 6618 if (OppShiftLHS.getOpcode() != ExtractFrom.getOpcode() || 6619 OppShiftLHS.getOperand(0) != ExtractFrom.getOperand(0) || 6620 ShiftedVT != ExtractFrom.getValueType()) 6621 return SDValue(); 6622 6623 // Constant mul/udiv/shift amount from the RHS of the shift's LHS op. 6624 ConstantSDNode *OppLHSCst = isConstOrConstSplat(OppShiftLHS.getOperand(1)); 6625 // Constant mul/udiv/shift amount from the RHS of the ExtractFrom op. 6626 ConstantSDNode *ExtractFromCst = 6627 isConstOrConstSplat(ExtractFrom.getOperand(1)); 6628 // TODO: We should be able to handle non-uniform constant vectors for these values 6629 // Check that we have constant values. 6630 if (!OppShiftCst || !OppShiftCst->getAPIntValue() || 6631 !OppLHSCst || !OppLHSCst->getAPIntValue() || 6632 !ExtractFromCst || !ExtractFromCst->getAPIntValue()) 6633 return SDValue(); 6634 6635 // Compute the shift amount we need to extract to complete the rotate. 6636 const unsigned VTWidth = ShiftedVT.getScalarSizeInBits(); 6637 if (OppShiftCst->getAPIntValue().ugt(VTWidth)) 6638 return SDValue(); 6639 APInt NeededShiftAmt = VTWidth - OppShiftCst->getAPIntValue(); 6640 // Normalize the bitwidth of the two mul/udiv/shift constant operands. 6641 APInt ExtractFromAmt = ExtractFromCst->getAPIntValue(); 6642 APInt OppLHSAmt = OppLHSCst->getAPIntValue(); 6643 zeroExtendToMatch(ExtractFromAmt, OppLHSAmt); 6644 6645 // Now try extract the needed shift from the ExtractFrom op and see if the 6646 // result matches up with the existing shift's LHS op. 6647 if (IsMulOrDiv) { 6648 // Op to extract from is a mul or udiv by a constant. 6649 // Check: 6650 // c2 / (1 << (bitwidth(op0 v c0) - c1)) == c0 6651 // c2 % (1 << (bitwidth(op0 v c0) - c1)) == 0 6652 const APInt ExtractDiv = APInt::getOneBitSet(ExtractFromAmt.getBitWidth(), 6653 NeededShiftAmt.getZExtValue()); 6654 APInt ResultAmt; 6655 APInt Rem; 6656 APInt::udivrem(ExtractFromAmt, ExtractDiv, ResultAmt, Rem); 6657 if (Rem != 0 || ResultAmt != OppLHSAmt) 6658 return SDValue(); 6659 } else { 6660 // Op to extract from is a shift by a constant. 6661 // Check: 6662 // c2 - (bitwidth(op0 v c0) - c1) == c0 6663 if (OppLHSAmt != ExtractFromAmt - NeededShiftAmt.zextOrTrunc( 6664 ExtractFromAmt.getBitWidth())) 6665 return SDValue(); 6666 } 6667 6668 // Return the expanded shift op that should allow a rotate to be formed. 6669 EVT ShiftVT = OppShift.getOperand(1).getValueType(); 6670 EVT ResVT = ExtractFrom.getValueType(); 6671 SDValue NewShiftNode = DAG.getConstant(NeededShiftAmt, DL, ShiftVT); 6672 return DAG.getNode(Opcode, DL, ResVT, OppShiftLHS, NewShiftNode); 6673 } 6674 6675 // Return true if we can prove that, whenever Neg and Pos are both in the 6676 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 6677 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 6678 // 6679 // (or (shift1 X, Neg), (shift2 X, Pos)) 6680 // 6681 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 6682 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 6683 // to consider shift amounts with defined behavior. 6684 // 6685 // The IsRotate flag should be set when the LHS of both shifts is the same. 6686 // Otherwise if matching a general funnel shift, it should be clear. 6687 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize, 6688 SelectionDAG &DAG, bool IsRotate) { 6689 // If EltSize is a power of 2 then: 6690 // 6691 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 6692 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 6693 // 6694 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 6695 // for the stronger condition: 6696 // 6697 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 6698 // 6699 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 6700 // we can just replace Neg with Neg' for the rest of the function. 6701 // 6702 // In other cases we check for the even stronger condition: 6703 // 6704 // Neg == EltSize - Pos [B] 6705 // 6706 // for all Neg and Pos. Note that the (or ...) then invokes undefined 6707 // behavior if Pos == 0 (and consequently Neg == EltSize). 6708 // 6709 // We could actually use [A] whenever EltSize is a power of 2, but the 6710 // only extra cases that it would match are those uninteresting ones 6711 // where Neg and Pos are never in range at the same time. E.g. for 6712 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 6713 // as well as (sub 32, Pos), but: 6714 // 6715 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 6716 // 6717 // always invokes undefined behavior for 32-bit X. 6718 // 6719 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 6720 // 6721 // NOTE: We can only do this when matching an AND and not a general 6722 // funnel shift. 6723 unsigned MaskLoBits = 0; 6724 if (IsRotate && Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 6725 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 6726 KnownBits Known = DAG.computeKnownBits(Neg.getOperand(0)); 6727 unsigned Bits = Log2_64(EltSize); 6728 if (NegC->getAPIntValue().getActiveBits() <= Bits && 6729 ((NegC->getAPIntValue() | Known.Zero).countTrailingOnes() >= Bits)) { 6730 Neg = Neg.getOperand(0); 6731 MaskLoBits = Bits; 6732 } 6733 } 6734 } 6735 6736 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 6737 if (Neg.getOpcode() != ISD::SUB) 6738 return false; 6739 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 6740 if (!NegC) 6741 return false; 6742 SDValue NegOp1 = Neg.getOperand(1); 6743 6744 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 6745 // Pos'. The truncation is redundant for the purpose of the equality. 6746 if (MaskLoBits && Pos.getOpcode() == ISD::AND) { 6747 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) { 6748 KnownBits Known = DAG.computeKnownBits(Pos.getOperand(0)); 6749 if (PosC->getAPIntValue().getActiveBits() <= MaskLoBits && 6750 ((PosC->getAPIntValue() | Known.Zero).countTrailingOnes() >= 6751 MaskLoBits)) 6752 Pos = Pos.getOperand(0); 6753 } 6754 } 6755 6756 // The condition we need is now: 6757 // 6758 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 6759 // 6760 // If NegOp1 == Pos then we need: 6761 // 6762 // EltSize & Mask == NegC & Mask 6763 // 6764 // (because "x & Mask" is a truncation and distributes through subtraction). 6765 // 6766 // We also need to account for a potential truncation of NegOp1 if the amount 6767 // has already been legalized to a shift amount type. 6768 APInt Width; 6769 if ((Pos == NegOp1) || 6770 (NegOp1.getOpcode() == ISD::TRUNCATE && Pos == NegOp1.getOperand(0))) 6771 Width = NegC->getAPIntValue(); 6772 6773 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 6774 // Then the condition we want to prove becomes: 6775 // 6776 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 6777 // 6778 // which, again because "x & Mask" is a truncation, becomes: 6779 // 6780 // NegC & Mask == (EltSize - PosC) & Mask 6781 // EltSize & Mask == (NegC + PosC) & Mask 6782 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 6783 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 6784 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 6785 else 6786 return false; 6787 } else 6788 return false; 6789 6790 // Now we just need to check that EltSize & Mask == Width & Mask. 6791 if (MaskLoBits) 6792 // EltSize & Mask is 0 since Mask is EltSize - 1. 6793 return Width.getLoBits(MaskLoBits) == 0; 6794 return Width == EltSize; 6795 } 6796 6797 // A subroutine of MatchRotate used once we have found an OR of two opposite 6798 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 6799 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 6800 // former being preferred if supported. InnerPos and InnerNeg are Pos and 6801 // Neg with outer conversions stripped away. 6802 SDValue DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 6803 SDValue Neg, SDValue InnerPos, 6804 SDValue InnerNeg, unsigned PosOpcode, 6805 unsigned NegOpcode, const SDLoc &DL) { 6806 // fold (or (shl x, (*ext y)), 6807 // (srl x, (*ext (sub 32, y)))) -> 6808 // (rotl x, y) or (rotr x, (sub 32, y)) 6809 // 6810 // fold (or (shl x, (*ext (sub 32, y))), 6811 // (srl x, (*ext y))) -> 6812 // (rotr x, y) or (rotl x, (sub 32, y)) 6813 EVT VT = Shifted.getValueType(); 6814 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits(), DAG, 6815 /*IsRotate*/ true)) { 6816 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 6817 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 6818 HasPos ? Pos : Neg); 6819 } 6820 6821 return SDValue(); 6822 } 6823 6824 // A subroutine of MatchRotate used once we have found an OR of two opposite 6825 // shifts of N0 + N1. If Neg == <operand size> - Pos then the OR reduces 6826 // to both (PosOpcode N0, N1, Pos) and (NegOpcode N0, N1, Neg), with the 6827 // former being preferred if supported. InnerPos and InnerNeg are Pos and 6828 // Neg with outer conversions stripped away. 6829 // TODO: Merge with MatchRotatePosNeg. 6830 SDValue DAGCombiner::MatchFunnelPosNeg(SDValue N0, SDValue N1, SDValue Pos, 6831 SDValue Neg, SDValue InnerPos, 6832 SDValue InnerNeg, unsigned PosOpcode, 6833 unsigned NegOpcode, const SDLoc &DL) { 6834 EVT VT = N0.getValueType(); 6835 unsigned EltBits = VT.getScalarSizeInBits(); 6836 6837 // fold (or (shl x0, (*ext y)), 6838 // (srl x1, (*ext (sub 32, y)))) -> 6839 // (fshl x0, x1, y) or (fshr x0, x1, (sub 32, y)) 6840 // 6841 // fold (or (shl x0, (*ext (sub 32, y))), 6842 // (srl x1, (*ext y))) -> 6843 // (fshr x0, x1, y) or (fshl x0, x1, (sub 32, y)) 6844 if (matchRotateSub(InnerPos, InnerNeg, EltBits, DAG, /*IsRotate*/ N0 == N1)) { 6845 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 6846 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, N0, N1, 6847 HasPos ? Pos : Neg); 6848 } 6849 6850 // Matching the shift+xor cases, we can't easily use the xor'd shift amount 6851 // so for now just use the PosOpcode case if its legal. 6852 // TODO: When can we use the NegOpcode case? 6853 if (PosOpcode == ISD::FSHL && isPowerOf2_32(EltBits)) { 6854 auto IsBinOpImm = [](SDValue Op, unsigned BinOpc, unsigned Imm) { 6855 if (Op.getOpcode() != BinOpc) 6856 return false; 6857 ConstantSDNode *Cst = isConstOrConstSplat(Op.getOperand(1)); 6858 return Cst && (Cst->getAPIntValue() == Imm); 6859 }; 6860 6861 // fold (or (shl x0, y), (srl (srl x1, 1), (xor y, 31))) 6862 // -> (fshl x0, x1, y) 6863 if (IsBinOpImm(N1, ISD::SRL, 1) && 6864 IsBinOpImm(InnerNeg, ISD::XOR, EltBits - 1) && 6865 InnerPos == InnerNeg.getOperand(0) && 6866 TLI.isOperationLegalOrCustom(ISD::FSHL, VT)) { 6867 return DAG.getNode(ISD::FSHL, DL, VT, N0, N1.getOperand(0), Pos); 6868 } 6869 6870 // fold (or (shl (shl x0, 1), (xor y, 31)), (srl x1, y)) 6871 // -> (fshr x0, x1, y) 6872 if (IsBinOpImm(N0, ISD::SHL, 1) && 6873 IsBinOpImm(InnerPos, ISD::XOR, EltBits - 1) && 6874 InnerNeg == InnerPos.getOperand(0) && 6875 TLI.isOperationLegalOrCustom(ISD::FSHR, VT)) { 6876 return DAG.getNode(ISD::FSHR, DL, VT, N0.getOperand(0), N1, Neg); 6877 } 6878 6879 // fold (or (shl (add x0, x0), (xor y, 31)), (srl x1, y)) 6880 // -> (fshr x0, x1, y) 6881 // TODO: Should add(x,x) -> shl(x,1) be a general DAG canonicalization? 6882 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N0.getOperand(1) && 6883 IsBinOpImm(InnerPos, ISD::XOR, EltBits - 1) && 6884 InnerNeg == InnerPos.getOperand(0) && 6885 TLI.isOperationLegalOrCustom(ISD::FSHR, VT)) { 6886 return DAG.getNode(ISD::FSHR, DL, VT, N0.getOperand(0), N1, Neg); 6887 } 6888 } 6889 6890 return SDValue(); 6891 } 6892 6893 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 6894 // idioms for rotate, and if the target supports rotation instructions, generate 6895 // a rot[lr]. This also matches funnel shift patterns, similar to rotation but 6896 // with different shifted sources. 6897 SDValue DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) { 6898 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 6899 EVT VT = LHS.getValueType(); 6900 if (!TLI.isTypeLegal(VT)) 6901 return SDValue(); 6902 6903 // The target must have at least one rotate/funnel flavor. 6904 bool HasROTL = hasOperation(ISD::ROTL, VT); 6905 bool HasROTR = hasOperation(ISD::ROTR, VT); 6906 bool HasFSHL = hasOperation(ISD::FSHL, VT); 6907 bool HasFSHR = hasOperation(ISD::FSHR, VT); 6908 if (!HasROTL && !HasROTR && !HasFSHL && !HasFSHR) 6909 return SDValue(); 6910 6911 // Check for truncated rotate. 6912 if (LHS.getOpcode() == ISD::TRUNCATE && RHS.getOpcode() == ISD::TRUNCATE && 6913 LHS.getOperand(0).getValueType() == RHS.getOperand(0).getValueType()) { 6914 assert(LHS.getValueType() == RHS.getValueType()); 6915 if (SDValue Rot = MatchRotate(LHS.getOperand(0), RHS.getOperand(0), DL)) { 6916 return DAG.getNode(ISD::TRUNCATE, SDLoc(LHS), LHS.getValueType(), Rot); 6917 } 6918 } 6919 6920 // Match "(X shl/srl V1) & V2" where V2 may not be present. 6921 SDValue LHSShift; // The shift. 6922 SDValue LHSMask; // AND value if any. 6923 matchRotateHalf(DAG, LHS, LHSShift, LHSMask); 6924 6925 SDValue RHSShift; // The shift. 6926 SDValue RHSMask; // AND value if any. 6927 matchRotateHalf(DAG, RHS, RHSShift, RHSMask); 6928 6929 // If neither side matched a rotate half, bail 6930 if (!LHSShift && !RHSShift) 6931 return SDValue(); 6932 6933 // InstCombine may have combined a constant shl, srl, mul, or udiv with one 6934 // side of the rotate, so try to handle that here. In all cases we need to 6935 // pass the matched shift from the opposite side to compute the opcode and 6936 // needed shift amount to extract. We still want to do this if both sides 6937 // matched a rotate half because one half may be a potential overshift that 6938 // can be broken down (ie if InstCombine merged two shl or srl ops into a 6939 // single one). 6940 6941 // Have LHS side of the rotate, try to extract the needed shift from the RHS. 6942 if (LHSShift) 6943 if (SDValue NewRHSShift = 6944 extractShiftForRotate(DAG, LHSShift, RHS, RHSMask, DL)) 6945 RHSShift = NewRHSShift; 6946 // Have RHS side of the rotate, try to extract the needed shift from the LHS. 6947 if (RHSShift) 6948 if (SDValue NewLHSShift = 6949 extractShiftForRotate(DAG, RHSShift, LHS, LHSMask, DL)) 6950 LHSShift = NewLHSShift; 6951 6952 // If a side is still missing, nothing else we can do. 6953 if (!RHSShift || !LHSShift) 6954 return SDValue(); 6955 6956 // At this point we've matched or extracted a shift op on each side. 6957 6958 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 6959 return SDValue(); // Shifts must disagree. 6960 6961 bool IsRotate = LHSShift.getOperand(0) == RHSShift.getOperand(0); 6962 if (!IsRotate && !(HasFSHL || HasFSHR)) 6963 return SDValue(); // Requires funnel shift support. 6964 6965 // Canonicalize shl to left side in a shl/srl pair. 6966 if (RHSShift.getOpcode() == ISD::SHL) { 6967 std::swap(LHS, RHS); 6968 std::swap(LHSShift, RHSShift); 6969 std::swap(LHSMask, RHSMask); 6970 } 6971 6972 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 6973 SDValue LHSShiftArg = LHSShift.getOperand(0); 6974 SDValue LHSShiftAmt = LHSShift.getOperand(1); 6975 SDValue RHSShiftArg = RHSShift.getOperand(0); 6976 SDValue RHSShiftAmt = RHSShift.getOperand(1); 6977 6978 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 6979 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 6980 // fold (or (shl x, C1), (srl y, C2)) -> (fshl x, y, C1) 6981 // fold (or (shl x, C1), (srl y, C2)) -> (fshr x, y, C2) 6982 // iff C1+C2 == EltSizeInBits 6983 auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS, 6984 ConstantSDNode *RHS) { 6985 return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits; 6986 }; 6987 if (ISD::matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) { 6988 SDValue Res; 6989 if (IsRotate && (HasROTL || HasROTR)) 6990 Res = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg, 6991 HasROTL ? LHSShiftAmt : RHSShiftAmt); 6992 else 6993 Res = DAG.getNode(HasFSHL ? ISD::FSHL : ISD::FSHR, DL, VT, LHSShiftArg, 6994 RHSShiftArg, HasFSHL ? LHSShiftAmt : RHSShiftAmt); 6995 6996 // If there is an AND of either shifted operand, apply it to the result. 6997 if (LHSMask.getNode() || RHSMask.getNode()) { 6998 SDValue AllOnes = DAG.getAllOnesConstant(DL, VT); 6999 SDValue Mask = AllOnes; 7000 7001 if (LHSMask.getNode()) { 7002 SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt); 7003 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 7004 DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits)); 7005 } 7006 if (RHSMask.getNode()) { 7007 SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt); 7008 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 7009 DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits)); 7010 } 7011 7012 Res = DAG.getNode(ISD::AND, DL, VT, Res, Mask); 7013 } 7014 7015 return Res; 7016 } 7017 7018 // If there is a mask here, and we have a variable shift, we can't be sure 7019 // that we're masking out the right stuff. 7020 if (LHSMask.getNode() || RHSMask.getNode()) 7021 return SDValue(); 7022 7023 // If the shift amount is sign/zext/any-extended just peel it off. 7024 SDValue LExtOp0 = LHSShiftAmt; 7025 SDValue RExtOp0 = RHSShiftAmt; 7026 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 7027 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 7028 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 7029 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 7030 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 7031 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 7032 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 7033 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 7034 LExtOp0 = LHSShiftAmt.getOperand(0); 7035 RExtOp0 = RHSShiftAmt.getOperand(0); 7036 } 7037 7038 if (IsRotate && (HasROTL || HasROTR)) { 7039 SDValue TryL = 7040 MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, LExtOp0, 7041 RExtOp0, ISD::ROTL, ISD::ROTR, DL); 7042 if (TryL) 7043 return TryL; 7044 7045 SDValue TryR = 7046 MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, RExtOp0, 7047 LExtOp0, ISD::ROTR, ISD::ROTL, DL); 7048 if (TryR) 7049 return TryR; 7050 } 7051 7052 SDValue TryL = 7053 MatchFunnelPosNeg(LHSShiftArg, RHSShiftArg, LHSShiftAmt, RHSShiftAmt, 7054 LExtOp0, RExtOp0, ISD::FSHL, ISD::FSHR, DL); 7055 if (TryL) 7056 return TryL; 7057 7058 SDValue TryR = 7059 MatchFunnelPosNeg(LHSShiftArg, RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 7060 RExtOp0, LExtOp0, ISD::FSHR, ISD::FSHL, DL); 7061 if (TryR) 7062 return TryR; 7063 7064 return SDValue(); 7065 } 7066 7067 namespace { 7068 7069 /// Represents known origin of an individual byte in load combine pattern. The 7070 /// value of the byte is either constant zero or comes from memory. 7071 struct ByteProvider { 7072 // For constant zero providers Load is set to nullptr. For memory providers 7073 // Load represents the node which loads the byte from memory. 7074 // ByteOffset is the offset of the byte in the value produced by the load. 7075 LoadSDNode *Load = nullptr; 7076 unsigned ByteOffset = 0; 7077 7078 ByteProvider() = default; 7079 7080 static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) { 7081 return ByteProvider(Load, ByteOffset); 7082 } 7083 7084 static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); } 7085 7086 bool isConstantZero() const { return !Load; } 7087 bool isMemory() const { return Load; } 7088 7089 bool operator==(const ByteProvider &Other) const { 7090 return Other.Load == Load && Other.ByteOffset == ByteOffset; 7091 } 7092 7093 private: 7094 ByteProvider(LoadSDNode *Load, unsigned ByteOffset) 7095 : Load(Load), ByteOffset(ByteOffset) {} 7096 }; 7097 7098 } // end anonymous namespace 7099 7100 /// Recursively traverses the expression calculating the origin of the requested 7101 /// byte of the given value. Returns None if the provider can't be calculated. 7102 /// 7103 /// For all the values except the root of the expression verifies that the value 7104 /// has exactly one use and if it's not true return None. This way if the origin 7105 /// of the byte is returned it's guaranteed that the values which contribute to 7106 /// the byte are not used outside of this expression. 7107 /// 7108 /// Because the parts of the expression are not allowed to have more than one 7109 /// use this function iterates over trees, not DAGs. So it never visits the same 7110 /// node more than once. 7111 static const Optional<ByteProvider> 7112 calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth, 7113 bool Root = false) { 7114 // Typical i64 by i8 pattern requires recursion up to 8 calls depth 7115 if (Depth == 10) 7116 return None; 7117 7118 if (!Root && !Op.hasOneUse()) 7119 return None; 7120 7121 assert(Op.getValueType().isScalarInteger() && "can't handle other types"); 7122 unsigned BitWidth = Op.getValueSizeInBits(); 7123 if (BitWidth % 8 != 0) 7124 return None; 7125 unsigned ByteWidth = BitWidth / 8; 7126 assert(Index < ByteWidth && "invalid index requested"); 7127 (void) ByteWidth; 7128 7129 switch (Op.getOpcode()) { 7130 case ISD::OR: { 7131 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1); 7132 if (!LHS) 7133 return None; 7134 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1); 7135 if (!RHS) 7136 return None; 7137 7138 if (LHS->isConstantZero()) 7139 return RHS; 7140 if (RHS->isConstantZero()) 7141 return LHS; 7142 return None; 7143 } 7144 case ISD::SHL: { 7145 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 7146 if (!ShiftOp) 7147 return None; 7148 7149 uint64_t BitShift = ShiftOp->getZExtValue(); 7150 if (BitShift % 8 != 0) 7151 return None; 7152 uint64_t ByteShift = BitShift / 8; 7153 7154 return Index < ByteShift 7155 ? ByteProvider::getConstantZero() 7156 : calculateByteProvider(Op->getOperand(0), Index - ByteShift, 7157 Depth + 1); 7158 } 7159 case ISD::ANY_EXTEND: 7160 case ISD::SIGN_EXTEND: 7161 case ISD::ZERO_EXTEND: { 7162 SDValue NarrowOp = Op->getOperand(0); 7163 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits(); 7164 if (NarrowBitWidth % 8 != 0) 7165 return None; 7166 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 7167 7168 if (Index >= NarrowByteWidth) 7169 return Op.getOpcode() == ISD::ZERO_EXTEND 7170 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 7171 : None; 7172 return calculateByteProvider(NarrowOp, Index, Depth + 1); 7173 } 7174 case ISD::BSWAP: 7175 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1, 7176 Depth + 1); 7177 case ISD::LOAD: { 7178 auto L = cast<LoadSDNode>(Op.getNode()); 7179 if (!L->isSimple() || L->isIndexed()) 7180 return None; 7181 7182 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits(); 7183 if (NarrowBitWidth % 8 != 0) 7184 return None; 7185 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 7186 7187 if (Index >= NarrowByteWidth) 7188 return L->getExtensionType() == ISD::ZEXTLOAD 7189 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 7190 : None; 7191 return ByteProvider::getMemory(L, Index); 7192 } 7193 } 7194 7195 return None; 7196 } 7197 7198 static unsigned littleEndianByteAt(unsigned BW, unsigned i) { 7199 return i; 7200 } 7201 7202 static unsigned bigEndianByteAt(unsigned BW, unsigned i) { 7203 return BW - i - 1; 7204 } 7205 7206 // Check if the bytes offsets we are looking at match with either big or 7207 // little endian value loaded. Return true for big endian, false for little 7208 // endian, and None if match failed. 7209 static Optional<bool> isBigEndian(const ArrayRef<int64_t> ByteOffsets, 7210 int64_t FirstOffset) { 7211 // The endian can be decided only when it is 2 bytes at least. 7212 unsigned Width = ByteOffsets.size(); 7213 if (Width < 2) 7214 return None; 7215 7216 bool BigEndian = true, LittleEndian = true; 7217 for (unsigned i = 0; i < Width; i++) { 7218 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset; 7219 LittleEndian &= CurrentByteOffset == littleEndianByteAt(Width, i); 7220 BigEndian &= CurrentByteOffset == bigEndianByteAt(Width, i); 7221 if (!BigEndian && !LittleEndian) 7222 return None; 7223 } 7224 7225 assert((BigEndian != LittleEndian) && "It should be either big endian or" 7226 "little endian"); 7227 return BigEndian; 7228 } 7229 7230 static SDValue stripTruncAndExt(SDValue Value) { 7231 switch (Value.getOpcode()) { 7232 case ISD::TRUNCATE: 7233 case ISD::ZERO_EXTEND: 7234 case ISD::SIGN_EXTEND: 7235 case ISD::ANY_EXTEND: 7236 return stripTruncAndExt(Value.getOperand(0)); 7237 } 7238 return Value; 7239 } 7240 7241 /// Match a pattern where a wide type scalar value is stored by several narrow 7242 /// stores. Fold it into a single store or a BSWAP and a store if the targets 7243 /// supports it. 7244 /// 7245 /// Assuming little endian target: 7246 /// i8 *p = ... 7247 /// i32 val = ... 7248 /// p[0] = (val >> 0) & 0xFF; 7249 /// p[1] = (val >> 8) & 0xFF; 7250 /// p[2] = (val >> 16) & 0xFF; 7251 /// p[3] = (val >> 24) & 0xFF; 7252 /// => 7253 /// *((i32)p) = val; 7254 /// 7255 /// i8 *p = ... 7256 /// i32 val = ... 7257 /// p[0] = (val >> 24) & 0xFF; 7258 /// p[1] = (val >> 16) & 0xFF; 7259 /// p[2] = (val >> 8) & 0xFF; 7260 /// p[3] = (val >> 0) & 0xFF; 7261 /// => 7262 /// *((i32)p) = BSWAP(val); 7263 SDValue DAGCombiner::mergeTruncStores(StoreSDNode *N) { 7264 // The matching looks for "store (trunc x)" patterns that appear early but are 7265 // likely to be replaced by truncating store nodes during combining. 7266 // TODO: If there is evidence that running this later would help, this 7267 // limitation could be removed. Legality checks may need to be added 7268 // for the created store and optional bswap/rotate. 7269 if (LegalOperations) 7270 return SDValue(); 7271 7272 // Collect all the stores in the chain. 7273 SDValue Chain; 7274 SmallVector<StoreSDNode *, 8> Stores; 7275 for (StoreSDNode *Store = N; Store; Store = dyn_cast<StoreSDNode>(Chain)) { 7276 // TODO: Allow unordered atomics when wider type is legal (see D66309) 7277 EVT MemVT = Store->getMemoryVT(); 7278 if (!(MemVT == MVT::i8 || MemVT == MVT::i16 || MemVT == MVT::i32) || 7279 !Store->isSimple() || Store->isIndexed()) 7280 return SDValue(); 7281 Stores.push_back(Store); 7282 Chain = Store->getChain(); 7283 } 7284 // There is no reason to continue if we do not have at least a pair of stores. 7285 if (Stores.size() < 2) 7286 return SDValue(); 7287 7288 // Handle simple types only. 7289 LLVMContext &Context = *DAG.getContext(); 7290 unsigned NumStores = Stores.size(); 7291 unsigned NarrowNumBits = N->getMemoryVT().getScalarSizeInBits(); 7292 unsigned WideNumBits = NumStores * NarrowNumBits; 7293 EVT WideVT = EVT::getIntegerVT(Context, WideNumBits); 7294 if (WideVT != MVT::i16 && WideVT != MVT::i32 && WideVT != MVT::i64) 7295 return SDValue(); 7296 7297 // Check if all bytes of the source value that we are looking at are stored 7298 // to the same base address. Collect offsets from Base address into OffsetMap. 7299 SDValue SourceValue; 7300 SmallVector<int64_t, 8> OffsetMap(NumStores, INT64_MAX); 7301 int64_t FirstOffset = INT64_MAX; 7302 StoreSDNode *FirstStore = nullptr; 7303 Optional<BaseIndexOffset> Base; 7304 for (auto Store : Stores) { 7305 // All the stores store different parts of the CombinedValue. A truncate is 7306 // required to get the partial value. 7307 SDValue Trunc = Store->getValue(); 7308 if (Trunc.getOpcode() != ISD::TRUNCATE) 7309 return SDValue(); 7310 // Other than the first/last part, a shift operation is required to get the 7311 // offset. 7312 int64_t Offset = 0; 7313 SDValue WideVal = Trunc.getOperand(0); 7314 if ((WideVal.getOpcode() == ISD::SRL || WideVal.getOpcode() == ISD::SRA) && 7315 isa<ConstantSDNode>(WideVal.getOperand(1))) { 7316 // The shift amount must be a constant multiple of the narrow type. 7317 // It is translated to the offset address in the wide source value "y". 7318 // 7319 // x = srl y, ShiftAmtC 7320 // i8 z = trunc x 7321 // store z, ... 7322 uint64_t ShiftAmtC = WideVal.getConstantOperandVal(1); 7323 if (ShiftAmtC % NarrowNumBits != 0) 7324 return SDValue(); 7325 7326 Offset = ShiftAmtC / NarrowNumBits; 7327 WideVal = WideVal.getOperand(0); 7328 } 7329 7330 // Stores must share the same source value with different offsets. 7331 // Truncate and extends should be stripped to get the single source value. 7332 if (!SourceValue) 7333 SourceValue = WideVal; 7334 else if (stripTruncAndExt(SourceValue) != stripTruncAndExt(WideVal)) 7335 return SDValue(); 7336 else if (SourceValue.getValueType() != WideVT) { 7337 if (WideVal.getValueType() == WideVT || 7338 WideVal.getScalarValueSizeInBits() > 7339 SourceValue.getScalarValueSizeInBits()) 7340 SourceValue = WideVal; 7341 // Give up if the source value type is smaller than the store size. 7342 if (SourceValue.getScalarValueSizeInBits() < WideVT.getScalarSizeInBits()) 7343 return SDValue(); 7344 } 7345 7346 // Stores must share the same base address. 7347 BaseIndexOffset Ptr = BaseIndexOffset::match(Store, DAG); 7348 int64_t ByteOffsetFromBase = 0; 7349 if (!Base) 7350 Base = Ptr; 7351 else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase)) 7352 return SDValue(); 7353 7354 // Remember the first store. 7355 if (ByteOffsetFromBase < FirstOffset) { 7356 FirstStore = Store; 7357 FirstOffset = ByteOffsetFromBase; 7358 } 7359 // Map the offset in the store and the offset in the combined value, and 7360 // early return if it has been set before. 7361 if (Offset < 0 || Offset >= NumStores || OffsetMap[Offset] != INT64_MAX) 7362 return SDValue(); 7363 OffsetMap[Offset] = ByteOffsetFromBase; 7364 } 7365 7366 assert(FirstOffset != INT64_MAX && "First byte offset must be set"); 7367 assert(FirstStore && "First store must be set"); 7368 7369 // Check that a store of the wide type is both allowed and fast on the target 7370 const DataLayout &Layout = DAG.getDataLayout(); 7371 bool Fast = false; 7372 bool Allowed = TLI.allowsMemoryAccess(Context, Layout, WideVT, 7373 *FirstStore->getMemOperand(), &Fast); 7374 if (!Allowed || !Fast) 7375 return SDValue(); 7376 7377 // Check if the pieces of the value are going to the expected places in memory 7378 // to merge the stores. 7379 auto checkOffsets = [&](bool MatchLittleEndian) { 7380 if (MatchLittleEndian) { 7381 for (unsigned i = 0; i != NumStores; ++i) 7382 if (OffsetMap[i] != i * (NarrowNumBits / 8) + FirstOffset) 7383 return false; 7384 } else { // MatchBigEndian by reversing loop counter. 7385 for (unsigned i = 0, j = NumStores - 1; i != NumStores; ++i, --j) 7386 if (OffsetMap[j] != i * (NarrowNumBits / 8) + FirstOffset) 7387 return false; 7388 } 7389 return true; 7390 }; 7391 7392 // Check if the offsets line up for the native data layout of this target. 7393 bool NeedBswap = false; 7394 bool NeedRotate = false; 7395 if (!checkOffsets(Layout.isLittleEndian())) { 7396 // Special-case: check if byte offsets line up for the opposite endian. 7397 if (NarrowNumBits == 8 && checkOffsets(Layout.isBigEndian())) 7398 NeedBswap = true; 7399 else if (NumStores == 2 && checkOffsets(Layout.isBigEndian())) 7400 NeedRotate = true; 7401 else 7402 return SDValue(); 7403 } 7404 7405 SDLoc DL(N); 7406 if (WideVT != SourceValue.getValueType()) { 7407 assert(SourceValue.getValueType().getScalarSizeInBits() > WideNumBits && 7408 "Unexpected store value to merge"); 7409 SourceValue = DAG.getNode(ISD::TRUNCATE, DL, WideVT, SourceValue); 7410 } 7411 7412 // Before legalize we can introduce illegal bswaps/rotates which will be later 7413 // converted to an explicit bswap sequence. This way we end up with a single 7414 // store and byte shuffling instead of several stores and byte shuffling. 7415 if (NeedBswap) { 7416 SourceValue = DAG.getNode(ISD::BSWAP, DL, WideVT, SourceValue); 7417 } else if (NeedRotate) { 7418 assert(WideNumBits % 2 == 0 && "Unexpected type for rotate"); 7419 SDValue RotAmt = DAG.getConstant(WideNumBits / 2, DL, WideVT); 7420 SourceValue = DAG.getNode(ISD::ROTR, DL, WideVT, SourceValue, RotAmt); 7421 } 7422 7423 SDValue NewStore = 7424 DAG.getStore(Chain, DL, SourceValue, FirstStore->getBasePtr(), 7425 FirstStore->getPointerInfo(), FirstStore->getAlign()); 7426 7427 // Rely on other DAG combine rules to remove the other individual stores. 7428 DAG.ReplaceAllUsesWith(N, NewStore.getNode()); 7429 return NewStore; 7430 } 7431 7432 /// Match a pattern where a wide type scalar value is loaded by several narrow 7433 /// loads and combined by shifts and ors. Fold it into a single load or a load 7434 /// and a BSWAP if the targets supports it. 7435 /// 7436 /// Assuming little endian target: 7437 /// i8 *a = ... 7438 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24) 7439 /// => 7440 /// i32 val = *((i32)a) 7441 /// 7442 /// i8 *a = ... 7443 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3] 7444 /// => 7445 /// i32 val = BSWAP(*((i32)a)) 7446 /// 7447 /// TODO: This rule matches complex patterns with OR node roots and doesn't 7448 /// interact well with the worklist mechanism. When a part of the pattern is 7449 /// updated (e.g. one of the loads) its direct users are put into the worklist, 7450 /// but the root node of the pattern which triggers the load combine is not 7451 /// necessarily a direct user of the changed node. For example, once the address 7452 /// of t28 load is reassociated load combine won't be triggered: 7453 /// t25: i32 = add t4, Constant:i32<2> 7454 /// t26: i64 = sign_extend t25 7455 /// t27: i64 = add t2, t26 7456 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64 7457 /// t29: i32 = zero_extend t28 7458 /// t32: i32 = shl t29, Constant:i8<8> 7459 /// t33: i32 = or t23, t32 7460 /// As a possible fix visitLoad can check if the load can be a part of a load 7461 /// combine pattern and add corresponding OR roots to the worklist. 7462 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) { 7463 assert(N->getOpcode() == ISD::OR && 7464 "Can only match load combining against OR nodes"); 7465 7466 // Handles simple types only 7467 EVT VT = N->getValueType(0); 7468 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64) 7469 return SDValue(); 7470 unsigned ByteWidth = VT.getSizeInBits() / 8; 7471 7472 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian(); 7473 auto MemoryByteOffset = [&] (ByteProvider P) { 7474 assert(P.isMemory() && "Must be a memory byte provider"); 7475 unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits(); 7476 assert(LoadBitWidth % 8 == 0 && 7477 "can only analyze providers for individual bytes not bit"); 7478 unsigned LoadByteWidth = LoadBitWidth / 8; 7479 return IsBigEndianTarget 7480 ? bigEndianByteAt(LoadByteWidth, P.ByteOffset) 7481 : littleEndianByteAt(LoadByteWidth, P.ByteOffset); 7482 }; 7483 7484 Optional<BaseIndexOffset> Base; 7485 SDValue Chain; 7486 7487 SmallPtrSet<LoadSDNode *, 8> Loads; 7488 Optional<ByteProvider> FirstByteProvider; 7489 int64_t FirstOffset = INT64_MAX; 7490 7491 // Check if all the bytes of the OR we are looking at are loaded from the same 7492 // base address. Collect bytes offsets from Base address in ByteOffsets. 7493 SmallVector<int64_t, 8> ByteOffsets(ByteWidth); 7494 unsigned ZeroExtendedBytes = 0; 7495 for (int i = ByteWidth - 1; i >= 0; --i) { 7496 auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true); 7497 if (!P) 7498 return SDValue(); 7499 7500 if (P->isConstantZero()) { 7501 // It's OK for the N most significant bytes to be 0, we can just 7502 // zero-extend the load. 7503 if (++ZeroExtendedBytes != (ByteWidth - static_cast<unsigned>(i))) 7504 return SDValue(); 7505 continue; 7506 } 7507 assert(P->isMemory() && "provenance should either be memory or zero"); 7508 7509 LoadSDNode *L = P->Load; 7510 assert(L->hasNUsesOfValue(1, 0) && L->isSimple() && 7511 !L->isIndexed() && 7512 "Must be enforced by calculateByteProvider"); 7513 assert(L->getOffset().isUndef() && "Unindexed load must have undef offset"); 7514 7515 // All loads must share the same chain 7516 SDValue LChain = L->getChain(); 7517 if (!Chain) 7518 Chain = LChain; 7519 else if (Chain != LChain) 7520 return SDValue(); 7521 7522 // Loads must share the same base address 7523 BaseIndexOffset Ptr = BaseIndexOffset::match(L, DAG); 7524 int64_t ByteOffsetFromBase = 0; 7525 if (!Base) 7526 Base = Ptr; 7527 else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase)) 7528 return SDValue(); 7529 7530 // Calculate the offset of the current byte from the base address 7531 ByteOffsetFromBase += MemoryByteOffset(*P); 7532 ByteOffsets[i] = ByteOffsetFromBase; 7533 7534 // Remember the first byte load 7535 if (ByteOffsetFromBase < FirstOffset) { 7536 FirstByteProvider = P; 7537 FirstOffset = ByteOffsetFromBase; 7538 } 7539 7540 Loads.insert(L); 7541 } 7542 assert(!Loads.empty() && "All the bytes of the value must be loaded from " 7543 "memory, so there must be at least one load which produces the value"); 7544 assert(Base && "Base address of the accessed memory location must be set"); 7545 assert(FirstOffset != INT64_MAX && "First byte offset must be set"); 7546 7547 bool NeedsZext = ZeroExtendedBytes > 0; 7548 7549 EVT MemVT = 7550 EVT::getIntegerVT(*DAG.getContext(), (ByteWidth - ZeroExtendedBytes) * 8); 7551 7552 if (!MemVT.isSimple()) 7553 return SDValue(); 7554 7555 // Before legalize we can introduce too wide illegal loads which will be later 7556 // split into legal sized loads. This enables us to combine i64 load by i8 7557 // patterns to a couple of i32 loads on 32 bit targets. 7558 if (LegalOperations && 7559 !TLI.isOperationLegal(NeedsZext ? ISD::ZEXTLOAD : ISD::NON_EXTLOAD, 7560 MemVT)) 7561 return SDValue(); 7562 7563 // Check if the bytes of the OR we are looking at match with either big or 7564 // little endian value load 7565 Optional<bool> IsBigEndian = isBigEndian( 7566 makeArrayRef(ByteOffsets).drop_back(ZeroExtendedBytes), FirstOffset); 7567 if (!IsBigEndian.hasValue()) 7568 return SDValue(); 7569 7570 assert(FirstByteProvider && "must be set"); 7571 7572 // Ensure that the first byte is loaded from zero offset of the first load. 7573 // So the combined value can be loaded from the first load address. 7574 if (MemoryByteOffset(*FirstByteProvider) != 0) 7575 return SDValue(); 7576 LoadSDNode *FirstLoad = FirstByteProvider->Load; 7577 7578 // The node we are looking at matches with the pattern, check if we can 7579 // replace it with a single (possibly zero-extended) load and bswap + shift if 7580 // needed. 7581 7582 // If the load needs byte swap check if the target supports it 7583 bool NeedsBswap = IsBigEndianTarget != *IsBigEndian; 7584 7585 // Before legalize we can introduce illegal bswaps which will be later 7586 // converted to an explicit bswap sequence. This way we end up with a single 7587 // load and byte shuffling instead of several loads and byte shuffling. 7588 // We do not introduce illegal bswaps when zero-extending as this tends to 7589 // introduce too many arithmetic instructions. 7590 if (NeedsBswap && (LegalOperations || NeedsZext) && 7591 !TLI.isOperationLegal(ISD::BSWAP, VT)) 7592 return SDValue(); 7593 7594 // If we need to bswap and zero extend, we have to insert a shift. Check that 7595 // it is legal. 7596 if (NeedsBswap && NeedsZext && LegalOperations && 7597 !TLI.isOperationLegal(ISD::SHL, VT)) 7598 return SDValue(); 7599 7600 // Check that a load of the wide type is both allowed and fast on the target 7601 bool Fast = false; 7602 bool Allowed = 7603 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 7604 *FirstLoad->getMemOperand(), &Fast); 7605 if (!Allowed || !Fast) 7606 return SDValue(); 7607 7608 SDValue NewLoad = 7609 DAG.getExtLoad(NeedsZext ? ISD::ZEXTLOAD : ISD::NON_EXTLOAD, SDLoc(N), VT, 7610 Chain, FirstLoad->getBasePtr(), 7611 FirstLoad->getPointerInfo(), MemVT, FirstLoad->getAlign()); 7612 7613 // Transfer chain users from old loads to the new load. 7614 for (LoadSDNode *L : Loads) 7615 DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1)); 7616 7617 if (!NeedsBswap) 7618 return NewLoad; 7619 7620 SDValue ShiftedLoad = 7621 NeedsZext 7622 ? DAG.getNode(ISD::SHL, SDLoc(N), VT, NewLoad, 7623 DAG.getShiftAmountConstant(ZeroExtendedBytes * 8, VT, 7624 SDLoc(N), LegalOperations)) 7625 : NewLoad; 7626 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, ShiftedLoad); 7627 } 7628 7629 // If the target has andn, bsl, or a similar bit-select instruction, 7630 // we want to unfold masked merge, with canonical pattern of: 7631 // | A | |B| 7632 // ((x ^ y) & m) ^ y 7633 // | D | 7634 // Into: 7635 // (x & m) | (y & ~m) 7636 // If y is a constant, and the 'andn' does not work with immediates, 7637 // we unfold into a different pattern: 7638 // ~(~x & m) & (m | y) 7639 // NOTE: we don't unfold the pattern if 'xor' is actually a 'not', because at 7640 // the very least that breaks andnpd / andnps patterns, and because those 7641 // patterns are simplified in IR and shouldn't be created in the DAG 7642 SDValue DAGCombiner::unfoldMaskedMerge(SDNode *N) { 7643 assert(N->getOpcode() == ISD::XOR); 7644 7645 // Don't touch 'not' (i.e. where y = -1). 7646 if (isAllOnesOrAllOnesSplat(N->getOperand(1))) 7647 return SDValue(); 7648 7649 EVT VT = N->getValueType(0); 7650 7651 // There are 3 commutable operators in the pattern, 7652 // so we have to deal with 8 possible variants of the basic pattern. 7653 SDValue X, Y, M; 7654 auto matchAndXor = [&X, &Y, &M](SDValue And, unsigned XorIdx, SDValue Other) { 7655 if (And.getOpcode() != ISD::AND || !And.hasOneUse()) 7656 return false; 7657 SDValue Xor = And.getOperand(XorIdx); 7658 if (Xor.getOpcode() != ISD::XOR || !Xor.hasOneUse()) 7659 return false; 7660 SDValue Xor0 = Xor.getOperand(0); 7661 SDValue Xor1 = Xor.getOperand(1); 7662 // Don't touch 'not' (i.e. where y = -1). 7663 if (isAllOnesOrAllOnesSplat(Xor1)) 7664 return false; 7665 if (Other == Xor0) 7666 std::swap(Xor0, Xor1); 7667 if (Other != Xor1) 7668 return false; 7669 X = Xor0; 7670 Y = Xor1; 7671 M = And.getOperand(XorIdx ? 0 : 1); 7672 return true; 7673 }; 7674 7675 SDValue N0 = N->getOperand(0); 7676 SDValue N1 = N->getOperand(1); 7677 if (!matchAndXor(N0, 0, N1) && !matchAndXor(N0, 1, N1) && 7678 !matchAndXor(N1, 0, N0) && !matchAndXor(N1, 1, N0)) 7679 return SDValue(); 7680 7681 // Don't do anything if the mask is constant. This should not be reachable. 7682 // InstCombine should have already unfolded this pattern, and DAGCombiner 7683 // probably shouldn't produce it, too. 7684 if (isa<ConstantSDNode>(M.getNode())) 7685 return SDValue(); 7686 7687 // We can transform if the target has AndNot 7688 if (!TLI.hasAndNot(M)) 7689 return SDValue(); 7690 7691 SDLoc DL(N); 7692 7693 // If Y is a constant, check that 'andn' works with immediates. 7694 if (!TLI.hasAndNot(Y)) { 7695 assert(TLI.hasAndNot(X) && "Only mask is a variable? Unreachable."); 7696 // If not, we need to do a bit more work to make sure andn is still used. 7697 SDValue NotX = DAG.getNOT(DL, X, VT); 7698 SDValue LHS = DAG.getNode(ISD::AND, DL, VT, NotX, M); 7699 SDValue NotLHS = DAG.getNOT(DL, LHS, VT); 7700 SDValue RHS = DAG.getNode(ISD::OR, DL, VT, M, Y); 7701 return DAG.getNode(ISD::AND, DL, VT, NotLHS, RHS); 7702 } 7703 7704 SDValue LHS = DAG.getNode(ISD::AND, DL, VT, X, M); 7705 SDValue NotM = DAG.getNOT(DL, M, VT); 7706 SDValue RHS = DAG.getNode(ISD::AND, DL, VT, Y, NotM); 7707 7708 return DAG.getNode(ISD::OR, DL, VT, LHS, RHS); 7709 } 7710 7711 SDValue DAGCombiner::visitXOR(SDNode *N) { 7712 SDValue N0 = N->getOperand(0); 7713 SDValue N1 = N->getOperand(1); 7714 EVT VT = N0.getValueType(); 7715 7716 // fold vector ops 7717 if (VT.isVector()) { 7718 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 7719 return FoldedVOp; 7720 7721 // fold (xor x, 0) -> x, vector edition 7722 if (ISD::isConstantSplatVectorAllZeros(N0.getNode())) 7723 return N1; 7724 if (ISD::isConstantSplatVectorAllZeros(N1.getNode())) 7725 return N0; 7726 } 7727 7728 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 7729 SDLoc DL(N); 7730 if (N0.isUndef() && N1.isUndef()) 7731 return DAG.getConstant(0, DL, VT); 7732 7733 // fold (xor x, undef) -> undef 7734 if (N0.isUndef()) 7735 return N0; 7736 if (N1.isUndef()) 7737 return N1; 7738 7739 // fold (xor c1, c2) -> c1^c2 7740 if (SDValue C = DAG.FoldConstantArithmetic(ISD::XOR, DL, VT, {N0, N1})) 7741 return C; 7742 7743 // canonicalize constant to RHS 7744 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 7745 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 7746 return DAG.getNode(ISD::XOR, DL, VT, N1, N0); 7747 7748 // fold (xor x, 0) -> x 7749 if (isNullConstant(N1)) 7750 return N0; 7751 7752 if (SDValue NewSel = foldBinOpIntoSelect(N)) 7753 return NewSel; 7754 7755 // reassociate xor 7756 if (SDValue RXOR = reassociateOps(ISD::XOR, DL, N0, N1, N->getFlags())) 7757 return RXOR; 7758 7759 // fold !(x cc y) -> (x !cc y) 7760 unsigned N0Opcode = N0.getOpcode(); 7761 SDValue LHS, RHS, CC; 7762 if (TLI.isConstTrueVal(N1.getNode()) && 7763 isSetCCEquivalent(N0, LHS, RHS, CC, /*MatchStrict*/true)) { 7764 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 7765 LHS.getValueType()); 7766 if (!LegalOperations || 7767 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 7768 switch (N0Opcode) { 7769 default: 7770 llvm_unreachable("Unhandled SetCC Equivalent!"); 7771 case ISD::SETCC: 7772 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC); 7773 case ISD::SELECT_CC: 7774 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2), 7775 N0.getOperand(3), NotCC); 7776 case ISD::STRICT_FSETCC: 7777 case ISD::STRICT_FSETCCS: { 7778 if (N0.hasOneUse()) { 7779 // FIXME Can we handle multiple uses? Could we token factor the chain 7780 // results from the new/old setcc? 7781 SDValue SetCC = 7782 DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC, 7783 N0.getOperand(0), N0Opcode == ISD::STRICT_FSETCCS); 7784 CombineTo(N, SetCC); 7785 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), SetCC.getValue(1)); 7786 recursivelyDeleteUnusedNodes(N0.getNode()); 7787 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7788 } 7789 break; 7790 } 7791 } 7792 } 7793 } 7794 7795 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 7796 if (isOneConstant(N1) && N0Opcode == ISD::ZERO_EXTEND && N0.hasOneUse() && 7797 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 7798 SDValue V = N0.getOperand(0); 7799 SDLoc DL0(N0); 7800 V = DAG.getNode(ISD::XOR, DL0, V.getValueType(), V, 7801 DAG.getConstant(1, DL0, V.getValueType())); 7802 AddToWorklist(V.getNode()); 7803 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, V); 7804 } 7805 7806 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 7807 if (isOneConstant(N1) && VT == MVT::i1 && N0.hasOneUse() && 7808 (N0Opcode == ISD::OR || N0Opcode == ISD::AND)) { 7809 SDValue N00 = N0.getOperand(0), N01 = N0.getOperand(1); 7810 if (isOneUseSetCC(N01) || isOneUseSetCC(N00)) { 7811 unsigned NewOpcode = N0Opcode == ISD::AND ? ISD::OR : ISD::AND; 7812 N00 = DAG.getNode(ISD::XOR, SDLoc(N00), VT, N00, N1); // N00 = ~N00 7813 N01 = DAG.getNode(ISD::XOR, SDLoc(N01), VT, N01, N1); // N01 = ~N01 7814 AddToWorklist(N00.getNode()); AddToWorklist(N01.getNode()); 7815 return DAG.getNode(NewOpcode, DL, VT, N00, N01); 7816 } 7817 } 7818 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 7819 if (isAllOnesConstant(N1) && N0.hasOneUse() && 7820 (N0Opcode == ISD::OR || N0Opcode == ISD::AND)) { 7821 SDValue N00 = N0.getOperand(0), N01 = N0.getOperand(1); 7822 if (isa<ConstantSDNode>(N01) || isa<ConstantSDNode>(N00)) { 7823 unsigned NewOpcode = N0Opcode == ISD::AND ? ISD::OR : ISD::AND; 7824 N00 = DAG.getNode(ISD::XOR, SDLoc(N00), VT, N00, N1); // N00 = ~N00 7825 N01 = DAG.getNode(ISD::XOR, SDLoc(N01), VT, N01, N1); // N01 = ~N01 7826 AddToWorklist(N00.getNode()); AddToWorklist(N01.getNode()); 7827 return DAG.getNode(NewOpcode, DL, VT, N00, N01); 7828 } 7829 } 7830 7831 // fold (not (neg x)) -> (add X, -1) 7832 // FIXME: This can be generalized to (not (sub Y, X)) -> (add X, ~Y) if 7833 // Y is a constant or the subtract has a single use. 7834 if (isAllOnesConstant(N1) && N0.getOpcode() == ISD::SUB && 7835 isNullConstant(N0.getOperand(0))) { 7836 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1), 7837 DAG.getAllOnesConstant(DL, VT)); 7838 } 7839 7840 // fold (not (add X, -1)) -> (neg X) 7841 if (isAllOnesConstant(N1) && N0.getOpcode() == ISD::ADD && 7842 isAllOnesOrAllOnesSplat(N0.getOperand(1))) { 7843 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), 7844 N0.getOperand(0)); 7845 } 7846 7847 // fold (xor (and x, y), y) -> (and (not x), y) 7848 if (N0Opcode == ISD::AND && N0.hasOneUse() && N0->getOperand(1) == N1) { 7849 SDValue X = N0.getOperand(0); 7850 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 7851 AddToWorklist(NotX.getNode()); 7852 return DAG.getNode(ISD::AND, DL, VT, NotX, N1); 7853 } 7854 7855 if ((N0Opcode == ISD::SRL || N0Opcode == ISD::SHL) && N0.hasOneUse()) { 7856 ConstantSDNode *XorC = isConstOrConstSplat(N1); 7857 ConstantSDNode *ShiftC = isConstOrConstSplat(N0.getOperand(1)); 7858 unsigned BitWidth = VT.getScalarSizeInBits(); 7859 if (XorC && ShiftC) { 7860 // Don't crash on an oversized shift. We can not guarantee that a bogus 7861 // shift has been simplified to undef. 7862 uint64_t ShiftAmt = ShiftC->getLimitedValue(); 7863 if (ShiftAmt < BitWidth) { 7864 APInt Ones = APInt::getAllOnesValue(BitWidth); 7865 Ones = N0Opcode == ISD::SHL ? Ones.shl(ShiftAmt) : Ones.lshr(ShiftAmt); 7866 if (XorC->getAPIntValue() == Ones) { 7867 // If the xor constant is a shifted -1, do a 'not' before the shift: 7868 // xor (X << ShiftC), XorC --> (not X) << ShiftC 7869 // xor (X >> ShiftC), XorC --> (not X) >> ShiftC 7870 SDValue Not = DAG.getNOT(DL, N0.getOperand(0), VT); 7871 return DAG.getNode(N0Opcode, DL, VT, Not, N0.getOperand(1)); 7872 } 7873 } 7874 } 7875 } 7876 7877 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X) 7878 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) { 7879 SDValue A = N0Opcode == ISD::ADD ? N0 : N1; 7880 SDValue S = N0Opcode == ISD::SRA ? N0 : N1; 7881 if (A.getOpcode() == ISD::ADD && S.getOpcode() == ISD::SRA) { 7882 SDValue A0 = A.getOperand(0), A1 = A.getOperand(1); 7883 SDValue S0 = S.getOperand(0); 7884 if ((A0 == S && A1 == S0) || (A1 == S && A0 == S0)) 7885 if (ConstantSDNode *C = isConstOrConstSplat(S.getOperand(1))) 7886 if (C->getAPIntValue() == (VT.getScalarSizeInBits() - 1)) 7887 return DAG.getNode(ISD::ABS, DL, VT, S0); 7888 } 7889 } 7890 7891 // fold (xor x, x) -> 0 7892 if (N0 == N1) 7893 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations); 7894 7895 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 7896 // Here is a concrete example of this equivalence: 7897 // i16 x == 14 7898 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 7899 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 7900 // 7901 // => 7902 // 7903 // i16 ~1 == 0b1111111111111110 7904 // i16 rol(~1, 14) == 0b1011111111111111 7905 // 7906 // Some additional tips to help conceptualize this transform: 7907 // - Try to see the operation as placing a single zero in a value of all ones. 7908 // - There exists no value for x which would allow the result to contain zero. 7909 // - Values of x larger than the bitwidth are undefined and do not require a 7910 // consistent result. 7911 // - Pushing the zero left requires shifting one bits in from the right. 7912 // A rotate left of ~1 is a nice way of achieving the desired result. 7913 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0Opcode == ISD::SHL && 7914 isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 7915 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 7916 N0.getOperand(1)); 7917 } 7918 7919 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 7920 if (N0Opcode == N1.getOpcode()) 7921 if (SDValue V = hoistLogicOpWithSameOpcodeHands(N)) 7922 return V; 7923 7924 // Unfold ((x ^ y) & m) ^ y into (x & m) | (y & ~m) if profitable 7925 if (SDValue MM = unfoldMaskedMerge(N)) 7926 return MM; 7927 7928 // Simplify the expression using non-local knowledge. 7929 if (SimplifyDemandedBits(SDValue(N, 0))) 7930 return SDValue(N, 0); 7931 7932 if (SDValue Combined = combineCarryDiamond(*this, DAG, TLI, N0, N1, N)) 7933 return Combined; 7934 7935 return SDValue(); 7936 } 7937 7938 /// If we have a shift-by-constant of a bitwise logic op that itself has a 7939 /// shift-by-constant operand with identical opcode, we may be able to convert 7940 /// that into 2 independent shifts followed by the logic op. This is a 7941 /// throughput improvement. 7942 static SDValue combineShiftOfShiftedLogic(SDNode *Shift, SelectionDAG &DAG) { 7943 // Match a one-use bitwise logic op. 7944 SDValue LogicOp = Shift->getOperand(0); 7945 if (!LogicOp.hasOneUse()) 7946 return SDValue(); 7947 7948 unsigned LogicOpcode = LogicOp.getOpcode(); 7949 if (LogicOpcode != ISD::AND && LogicOpcode != ISD::OR && 7950 LogicOpcode != ISD::XOR) 7951 return SDValue(); 7952 7953 // Find a matching one-use shift by constant. 7954 unsigned ShiftOpcode = Shift->getOpcode(); 7955 SDValue C1 = Shift->getOperand(1); 7956 ConstantSDNode *C1Node = isConstOrConstSplat(C1); 7957 assert(C1Node && "Expected a shift with constant operand"); 7958 const APInt &C1Val = C1Node->getAPIntValue(); 7959 auto matchFirstShift = [&](SDValue V, SDValue &ShiftOp, 7960 const APInt *&ShiftAmtVal) { 7961 if (V.getOpcode() != ShiftOpcode || !V.hasOneUse()) 7962 return false; 7963 7964 ConstantSDNode *ShiftCNode = isConstOrConstSplat(V.getOperand(1)); 7965 if (!ShiftCNode) 7966 return false; 7967 7968 // Capture the shifted operand and shift amount value. 7969 ShiftOp = V.getOperand(0); 7970 ShiftAmtVal = &ShiftCNode->getAPIntValue(); 7971 7972 // Shift amount types do not have to match their operand type, so check that 7973 // the constants are the same width. 7974 if (ShiftAmtVal->getBitWidth() != C1Val.getBitWidth()) 7975 return false; 7976 7977 // The fold is not valid if the sum of the shift values exceeds bitwidth. 7978 if ((*ShiftAmtVal + C1Val).uge(V.getScalarValueSizeInBits())) 7979 return false; 7980 7981 return true; 7982 }; 7983 7984 // Logic ops are commutative, so check each operand for a match. 7985 SDValue X, Y; 7986 const APInt *C0Val; 7987 if (matchFirstShift(LogicOp.getOperand(0), X, C0Val)) 7988 Y = LogicOp.getOperand(1); 7989 else if (matchFirstShift(LogicOp.getOperand(1), X, C0Val)) 7990 Y = LogicOp.getOperand(0); 7991 else 7992 return SDValue(); 7993 7994 // shift (logic (shift X, C0), Y), C1 -> logic (shift X, C0+C1), (shift Y, C1) 7995 SDLoc DL(Shift); 7996 EVT VT = Shift->getValueType(0); 7997 EVT ShiftAmtVT = Shift->getOperand(1).getValueType(); 7998 SDValue ShiftSumC = DAG.getConstant(*C0Val + C1Val, DL, ShiftAmtVT); 7999 SDValue NewShift1 = DAG.getNode(ShiftOpcode, DL, VT, X, ShiftSumC); 8000 SDValue NewShift2 = DAG.getNode(ShiftOpcode, DL, VT, Y, C1); 8001 return DAG.getNode(LogicOpcode, DL, VT, NewShift1, NewShift2); 8002 } 8003 8004 /// Handle transforms common to the three shifts, when the shift amount is a 8005 /// constant. 8006 /// We are looking for: (shift being one of shl/sra/srl) 8007 /// shift (binop X, C0), C1 8008 /// And want to transform into: 8009 /// binop (shift X, C1), (shift C0, C1) 8010 SDValue DAGCombiner::visitShiftByConstant(SDNode *N) { 8011 assert(isConstOrConstSplat(N->getOperand(1)) && "Expected constant operand"); 8012 8013 // Do not turn a 'not' into a regular xor. 8014 if (isBitwiseNot(N->getOperand(0))) 8015 return SDValue(); 8016 8017 // The inner binop must be one-use, since we want to replace it. 8018 SDValue LHS = N->getOperand(0); 8019 if (!LHS.hasOneUse() || !TLI.isDesirableToCommuteWithShift(N, Level)) 8020 return SDValue(); 8021 8022 // TODO: This is limited to early combining because it may reveal regressions 8023 // otherwise. But since we just checked a target hook to see if this is 8024 // desirable, that should have filtered out cases where this interferes 8025 // with some other pattern matching. 8026 if (!LegalTypes) 8027 if (SDValue R = combineShiftOfShiftedLogic(N, DAG)) 8028 return R; 8029 8030 // We want to pull some binops through shifts, so that we have (and (shift)) 8031 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 8032 // thing happens with address calculations, so it's important to canonicalize 8033 // it. 8034 switch (LHS.getOpcode()) { 8035 default: 8036 return SDValue(); 8037 case ISD::OR: 8038 case ISD::XOR: 8039 case ISD::AND: 8040 break; 8041 case ISD::ADD: 8042 if (N->getOpcode() != ISD::SHL) 8043 return SDValue(); // only shl(add) not sr[al](add). 8044 break; 8045 } 8046 8047 // We require the RHS of the binop to be a constant and not opaque as well. 8048 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS.getOperand(1)); 8049 if (!BinOpCst) 8050 return SDValue(); 8051 8052 // FIXME: disable this unless the input to the binop is a shift by a constant 8053 // or is copy/select. Enable this in other cases when figure out it's exactly 8054 // profitable. 8055 SDValue BinOpLHSVal = LHS.getOperand(0); 8056 bool IsShiftByConstant = (BinOpLHSVal.getOpcode() == ISD::SHL || 8057 BinOpLHSVal.getOpcode() == ISD::SRA || 8058 BinOpLHSVal.getOpcode() == ISD::SRL) && 8059 isa<ConstantSDNode>(BinOpLHSVal.getOperand(1)); 8060 bool IsCopyOrSelect = BinOpLHSVal.getOpcode() == ISD::CopyFromReg || 8061 BinOpLHSVal.getOpcode() == ISD::SELECT; 8062 8063 if (!IsShiftByConstant && !IsCopyOrSelect) 8064 return SDValue(); 8065 8066 if (IsCopyOrSelect && N->hasOneUse()) 8067 return SDValue(); 8068 8069 // Fold the constants, shifting the binop RHS by the shift amount. 8070 SDLoc DL(N); 8071 EVT VT = N->getValueType(0); 8072 SDValue NewRHS = DAG.getNode(N->getOpcode(), DL, VT, LHS.getOperand(1), 8073 N->getOperand(1)); 8074 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 8075 8076 SDValue NewShift = DAG.getNode(N->getOpcode(), DL, VT, LHS.getOperand(0), 8077 N->getOperand(1)); 8078 return DAG.getNode(LHS.getOpcode(), DL, VT, NewShift, NewRHS); 8079 } 8080 8081 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 8082 assert(N->getOpcode() == ISD::TRUNCATE); 8083 assert(N->getOperand(0).getOpcode() == ISD::AND); 8084 8085 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 8086 EVT TruncVT = N->getValueType(0); 8087 if (N->hasOneUse() && N->getOperand(0).hasOneUse() && 8088 TLI.isTypeDesirableForOp(ISD::AND, TruncVT)) { 8089 SDValue N01 = N->getOperand(0).getOperand(1); 8090 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) { 8091 SDLoc DL(N); 8092 SDValue N00 = N->getOperand(0).getOperand(0); 8093 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00); 8094 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01); 8095 AddToWorklist(Trunc00.getNode()); 8096 AddToWorklist(Trunc01.getNode()); 8097 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01); 8098 } 8099 } 8100 8101 return SDValue(); 8102 } 8103 8104 SDValue DAGCombiner::visitRotate(SDNode *N) { 8105 SDLoc dl(N); 8106 SDValue N0 = N->getOperand(0); 8107 SDValue N1 = N->getOperand(1); 8108 EVT VT = N->getValueType(0); 8109 unsigned Bitsize = VT.getScalarSizeInBits(); 8110 8111 // fold (rot x, 0) -> x 8112 if (isNullOrNullSplat(N1)) 8113 return N0; 8114 8115 // fold (rot x, c) -> x iff (c % BitSize) == 0 8116 if (isPowerOf2_32(Bitsize) && Bitsize > 1) { 8117 APInt ModuloMask(N1.getScalarValueSizeInBits(), Bitsize - 1); 8118 if (DAG.MaskedValueIsZero(N1, ModuloMask)) 8119 return N0; 8120 } 8121 8122 // fold (rot x, c) -> (rot x, c % BitSize) 8123 bool OutOfRange = false; 8124 auto MatchOutOfRange = [Bitsize, &OutOfRange](ConstantSDNode *C) { 8125 OutOfRange |= C->getAPIntValue().uge(Bitsize); 8126 return true; 8127 }; 8128 if (ISD::matchUnaryPredicate(N1, MatchOutOfRange) && OutOfRange) { 8129 EVT AmtVT = N1.getValueType(); 8130 SDValue Bits = DAG.getConstant(Bitsize, dl, AmtVT); 8131 if (SDValue Amt = 8132 DAG.FoldConstantArithmetic(ISD::UREM, dl, AmtVT, {N1, Bits})) 8133 return DAG.getNode(N->getOpcode(), dl, VT, N0, Amt); 8134 } 8135 8136 // rot i16 X, 8 --> bswap X 8137 auto *RotAmtC = isConstOrConstSplat(N1); 8138 if (RotAmtC && RotAmtC->getAPIntValue() == 8 && 8139 VT.getScalarSizeInBits() == 16 && hasOperation(ISD::BSWAP, VT)) 8140 return DAG.getNode(ISD::BSWAP, dl, VT, N0); 8141 8142 // Simplify the operands using demanded-bits information. 8143 if (SimplifyDemandedBits(SDValue(N, 0))) 8144 return SDValue(N, 0); 8145 8146 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 8147 if (N1.getOpcode() == ISD::TRUNCATE && 8148 N1.getOperand(0).getOpcode() == ISD::AND) { 8149 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 8150 return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1); 8151 } 8152 8153 unsigned NextOp = N0.getOpcode(); 8154 // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize) 8155 if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) { 8156 SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1); 8157 SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)); 8158 if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) { 8159 EVT ShiftVT = C1->getValueType(0); 8160 bool SameSide = (N->getOpcode() == NextOp); 8161 unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB; 8162 if (SDValue CombinedShift = DAG.FoldConstantArithmetic( 8163 CombineOp, dl, ShiftVT, {N1, N0.getOperand(1)})) { 8164 SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT); 8165 SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic( 8166 ISD::SREM, dl, ShiftVT, {CombinedShift, BitsizeC}); 8167 return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0), 8168 CombinedShiftNorm); 8169 } 8170 } 8171 } 8172 return SDValue(); 8173 } 8174 8175 SDValue DAGCombiner::visitSHL(SDNode *N) { 8176 SDValue N0 = N->getOperand(0); 8177 SDValue N1 = N->getOperand(1); 8178 if (SDValue V = DAG.simplifyShift(N0, N1)) 8179 return V; 8180 8181 EVT VT = N0.getValueType(); 8182 EVT ShiftVT = N1.getValueType(); 8183 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 8184 8185 // fold vector ops 8186 if (VT.isVector()) { 8187 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8188 return FoldedVOp; 8189 8190 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 8191 // If setcc produces all-one true value then: 8192 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 8193 if (N1CV && N1CV->isConstant()) { 8194 if (N0.getOpcode() == ISD::AND) { 8195 SDValue N00 = N0->getOperand(0); 8196 SDValue N01 = N0->getOperand(1); 8197 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 8198 8199 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 8200 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 8201 TargetLowering::ZeroOrNegativeOneBooleanContent) { 8202 if (SDValue C = 8203 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, {N01, N1})) 8204 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 8205 } 8206 } 8207 } 8208 } 8209 8210 ConstantSDNode *N1C = isConstOrConstSplat(N1); 8211 8212 // fold (shl c1, c2) -> c1<<c2 8213 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, {N0, N1})) 8214 return C; 8215 8216 if (SDValue NewSel = foldBinOpIntoSelect(N)) 8217 return NewSel; 8218 8219 // if (shl x, c) is known to be zero, return 0 8220 if (DAG.MaskedValueIsZero(SDValue(N, 0), 8221 APInt::getAllOnesValue(OpSizeInBits))) 8222 return DAG.getConstant(0, SDLoc(N), VT); 8223 8224 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 8225 if (N1.getOpcode() == ISD::TRUNCATE && 8226 N1.getOperand(0).getOpcode() == ISD::AND) { 8227 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 8228 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 8229 } 8230 8231 if (SimplifyDemandedBits(SDValue(N, 0))) 8232 return SDValue(N, 0); 8233 8234 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 8235 if (N0.getOpcode() == ISD::SHL) { 8236 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 8237 ConstantSDNode *RHS) { 8238 APInt c1 = LHS->getAPIntValue(); 8239 APInt c2 = RHS->getAPIntValue(); 8240 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 8241 return (c1 + c2).uge(OpSizeInBits); 8242 }; 8243 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 8244 return DAG.getConstant(0, SDLoc(N), VT); 8245 8246 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 8247 ConstantSDNode *RHS) { 8248 APInt c1 = LHS->getAPIntValue(); 8249 APInt c2 = RHS->getAPIntValue(); 8250 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 8251 return (c1 + c2).ult(OpSizeInBits); 8252 }; 8253 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 8254 SDLoc DL(N); 8255 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 8256 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum); 8257 } 8258 } 8259 8260 // fold (shl (ext (shl x, c1)), c2) -> (shl (ext x), (add c1, c2)) 8261 // For this to be valid, the second form must not preserve any of the bits 8262 // that are shifted out by the inner shift in the first form. This means 8263 // the outer shift size must be >= the number of bits added by the ext. 8264 // As a corollary, we don't care what kind of ext it is. 8265 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 8266 N0.getOpcode() == ISD::ANY_EXTEND || 8267 N0.getOpcode() == ISD::SIGN_EXTEND) && 8268 N0.getOperand(0).getOpcode() == ISD::SHL) { 8269 SDValue N0Op0 = N0.getOperand(0); 8270 SDValue InnerShiftAmt = N0Op0.getOperand(1); 8271 EVT InnerVT = N0Op0.getValueType(); 8272 uint64_t InnerBitwidth = InnerVT.getScalarSizeInBits(); 8273 8274 auto MatchOutOfRange = [OpSizeInBits, InnerBitwidth](ConstantSDNode *LHS, 8275 ConstantSDNode *RHS) { 8276 APInt c1 = LHS->getAPIntValue(); 8277 APInt c2 = RHS->getAPIntValue(); 8278 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 8279 return c2.uge(OpSizeInBits - InnerBitwidth) && 8280 (c1 + c2).uge(OpSizeInBits); 8281 }; 8282 if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchOutOfRange, 8283 /*AllowUndefs*/ false, 8284 /*AllowTypeMismatch*/ true)) 8285 return DAG.getConstant(0, SDLoc(N), VT); 8286 8287 auto MatchInRange = [OpSizeInBits, InnerBitwidth](ConstantSDNode *LHS, 8288 ConstantSDNode *RHS) { 8289 APInt c1 = LHS->getAPIntValue(); 8290 APInt c2 = RHS->getAPIntValue(); 8291 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 8292 return c2.uge(OpSizeInBits - InnerBitwidth) && 8293 (c1 + c2).ult(OpSizeInBits); 8294 }; 8295 if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchInRange, 8296 /*AllowUndefs*/ false, 8297 /*AllowTypeMismatch*/ true)) { 8298 SDLoc DL(N); 8299 SDValue Ext = DAG.getNode(N0.getOpcode(), DL, VT, N0Op0.getOperand(0)); 8300 SDValue Sum = DAG.getZExtOrTrunc(InnerShiftAmt, DL, ShiftVT); 8301 Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, Sum, N1); 8302 return DAG.getNode(ISD::SHL, DL, VT, Ext, Sum); 8303 } 8304 } 8305 8306 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 8307 // Only fold this if the inner zext has no other uses to avoid increasing 8308 // the total number of instructions. 8309 if (N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 8310 N0.getOperand(0).getOpcode() == ISD::SRL) { 8311 SDValue N0Op0 = N0.getOperand(0); 8312 SDValue InnerShiftAmt = N0Op0.getOperand(1); 8313 8314 auto MatchEqual = [VT](ConstantSDNode *LHS, ConstantSDNode *RHS) { 8315 APInt c1 = LHS->getAPIntValue(); 8316 APInt c2 = RHS->getAPIntValue(); 8317 zeroExtendToMatch(c1, c2); 8318 return c1.ult(VT.getScalarSizeInBits()) && (c1 == c2); 8319 }; 8320 if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchEqual, 8321 /*AllowUndefs*/ false, 8322 /*AllowTypeMismatch*/ true)) { 8323 SDLoc DL(N); 8324 EVT InnerShiftAmtVT = N0Op0.getOperand(1).getValueType(); 8325 SDValue NewSHL = DAG.getZExtOrTrunc(N1, DL, InnerShiftAmtVT); 8326 NewSHL = DAG.getNode(ISD::SHL, DL, N0Op0.getValueType(), N0Op0, NewSHL); 8327 AddToWorklist(NewSHL.getNode()); 8328 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 8329 } 8330 } 8331 8332 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 8333 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 8334 // TODO - support non-uniform vector shift amounts. 8335 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 8336 N0->getFlags().hasExact()) { 8337 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 8338 uint64_t C1 = N0C1->getZExtValue(); 8339 uint64_t C2 = N1C->getZExtValue(); 8340 SDLoc DL(N); 8341 if (C1 <= C2) 8342 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 8343 DAG.getConstant(C2 - C1, DL, ShiftVT)); 8344 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 8345 DAG.getConstant(C1 - C2, DL, ShiftVT)); 8346 } 8347 } 8348 8349 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 8350 // (and (srl x, (sub c1, c2), MASK) 8351 // Only fold this if the inner shift has no other uses -- if it does, folding 8352 // this will increase the total number of instructions. 8353 // TODO - drop hasOneUse requirement if c1 == c2? 8354 // TODO - support non-uniform vector shift amounts. 8355 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() && 8356 TLI.shouldFoldConstantShiftPairToMask(N, Level)) { 8357 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 8358 if (N0C1->getAPIntValue().ult(OpSizeInBits)) { 8359 uint64_t c1 = N0C1->getZExtValue(); 8360 uint64_t c2 = N1C->getZExtValue(); 8361 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 8362 SDValue Shift; 8363 if (c2 > c1) { 8364 Mask <<= c2 - c1; 8365 SDLoc DL(N); 8366 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 8367 DAG.getConstant(c2 - c1, DL, ShiftVT)); 8368 } else { 8369 Mask.lshrInPlace(c1 - c2); 8370 SDLoc DL(N); 8371 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 8372 DAG.getConstant(c1 - c2, DL, ShiftVT)); 8373 } 8374 SDLoc DL(N0); 8375 return DAG.getNode(ISD::AND, DL, VT, Shift, 8376 DAG.getConstant(Mask, DL, VT)); 8377 } 8378 } 8379 } 8380 8381 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 8382 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) && 8383 isConstantOrConstantVector(N1, /* No Opaques */ true)) { 8384 SDLoc DL(N); 8385 SDValue AllBits = DAG.getAllOnesConstant(DL, VT); 8386 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1); 8387 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask); 8388 } 8389 8390 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 8391 // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 8392 // Variant of version done on multiply, except mul by a power of 2 is turned 8393 // into a shift. 8394 if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) && 8395 N0.getNode()->hasOneUse() && 8396 isConstantOrConstantVector(N1, /* No Opaques */ true) && 8397 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true) && 8398 TLI.isDesirableToCommuteWithShift(N, Level)) { 8399 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 8400 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 8401 AddToWorklist(Shl0.getNode()); 8402 AddToWorklist(Shl1.getNode()); 8403 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, Shl0, Shl1); 8404 } 8405 8406 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 8407 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() && 8408 isConstantOrConstantVector(N1, /* No Opaques */ true) && 8409 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 8410 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 8411 if (isConstantOrConstantVector(Shl)) 8412 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl); 8413 } 8414 8415 if (N1C && !N1C->isOpaque()) 8416 if (SDValue NewSHL = visitShiftByConstant(N)) 8417 return NewSHL; 8418 8419 // Fold (shl (vscale * C0), C1) to (vscale * (C0 << C1)). 8420 if (N0.getOpcode() == ISD::VSCALE) 8421 if (ConstantSDNode *NC1 = isConstOrConstSplat(N->getOperand(1))) { 8422 const APInt &C0 = N0.getConstantOperandAPInt(0); 8423 const APInt &C1 = NC1->getAPIntValue(); 8424 return DAG.getVScale(SDLoc(N), VT, C0 << C1); 8425 } 8426 8427 // Fold (shl step_vector(C0), C1) to (step_vector(C0 << C1)). 8428 APInt ShlVal; 8429 if (N0.getOpcode() == ISD::STEP_VECTOR) 8430 if (ISD::isConstantSplatVector(N1.getNode(), ShlVal)) { 8431 const APInt &C0 = N0.getConstantOperandAPInt(0); 8432 EVT SVT = N0.getOperand(0).getValueType(); 8433 SDValue NewStep = DAG.getConstant( 8434 C0 << ShlVal.sextOrTrunc(SVT.getSizeInBits()), SDLoc(N), SVT); 8435 return DAG.getStepVector(SDLoc(N), VT, NewStep); 8436 } 8437 8438 return SDValue(); 8439 } 8440 8441 // Transform a right shift of a multiply into a multiply-high. 8442 // Examples: 8443 // (srl (mul (zext i32:$a to i64), (zext i32:$a to i64)), 32) -> (mulhu $a, $b) 8444 // (sra (mul (sext i32:$a to i64), (sext i32:$a to i64)), 32) -> (mulhs $a, $b) 8445 static SDValue combineShiftToMULH(SDNode *N, SelectionDAG &DAG, 8446 const TargetLowering &TLI) { 8447 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 8448 "SRL or SRA node is required here!"); 8449 8450 // Check the shift amount. Proceed with the transformation if the shift 8451 // amount is constant. 8452 ConstantSDNode *ShiftAmtSrc = isConstOrConstSplat(N->getOperand(1)); 8453 if (!ShiftAmtSrc) 8454 return SDValue(); 8455 8456 SDLoc DL(N); 8457 8458 // The operation feeding into the shift must be a multiply. 8459 SDValue ShiftOperand = N->getOperand(0); 8460 if (ShiftOperand.getOpcode() != ISD::MUL) 8461 return SDValue(); 8462 8463 // Both operands must be equivalent extend nodes. 8464 SDValue LeftOp = ShiftOperand.getOperand(0); 8465 SDValue RightOp = ShiftOperand.getOperand(1); 8466 bool IsSignExt = LeftOp.getOpcode() == ISD::SIGN_EXTEND; 8467 bool IsZeroExt = LeftOp.getOpcode() == ISD::ZERO_EXTEND; 8468 8469 if ((!(IsSignExt || IsZeroExt)) || LeftOp.getOpcode() != RightOp.getOpcode()) 8470 return SDValue(); 8471 8472 EVT WideVT1 = LeftOp.getValueType(); 8473 EVT WideVT2 = RightOp.getValueType(); 8474 (void)WideVT2; 8475 // Proceed with the transformation if the wide types match. 8476 assert((WideVT1 == WideVT2) && 8477 "Cannot have a multiply node with two different operand types."); 8478 8479 EVT NarrowVT = LeftOp.getOperand(0).getValueType(); 8480 // Check that the two extend nodes are the same type. 8481 if (NarrowVT != RightOp.getOperand(0).getValueType()) 8482 return SDValue(); 8483 8484 // Proceed with the transformation if the wide type is twice as large 8485 // as the narrow type. 8486 unsigned NarrowVTSize = NarrowVT.getScalarSizeInBits(); 8487 if (WideVT1.getScalarSizeInBits() != 2 * NarrowVTSize) 8488 return SDValue(); 8489 8490 // Check the shift amount with the narrow type size. 8491 // Proceed with the transformation if the shift amount is the width 8492 // of the narrow type. 8493 unsigned ShiftAmt = ShiftAmtSrc->getZExtValue(); 8494 if (ShiftAmt != NarrowVTSize) 8495 return SDValue(); 8496 8497 // If the operation feeding into the MUL is a sign extend (sext), 8498 // we use mulhs. Othewise, zero extends (zext) use mulhu. 8499 unsigned MulhOpcode = IsSignExt ? ISD::MULHS : ISD::MULHU; 8500 8501 // Combine to mulh if mulh is legal/custom for the narrow type on the target. 8502 if (!TLI.isOperationLegalOrCustom(MulhOpcode, NarrowVT)) 8503 return SDValue(); 8504 8505 SDValue Result = DAG.getNode(MulhOpcode, DL, NarrowVT, LeftOp.getOperand(0), 8506 RightOp.getOperand(0)); 8507 return (N->getOpcode() == ISD::SRA ? DAG.getSExtOrTrunc(Result, DL, WideVT1) 8508 : DAG.getZExtOrTrunc(Result, DL, WideVT1)); 8509 } 8510 8511 SDValue DAGCombiner::visitSRA(SDNode *N) { 8512 SDValue N0 = N->getOperand(0); 8513 SDValue N1 = N->getOperand(1); 8514 if (SDValue V = DAG.simplifyShift(N0, N1)) 8515 return V; 8516 8517 EVT VT = N0.getValueType(); 8518 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 8519 8520 // Arithmetic shifting an all-sign-bit value is a no-op. 8521 // fold (sra 0, x) -> 0 8522 // fold (sra -1, x) -> -1 8523 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits) 8524 return N0; 8525 8526 // fold vector ops 8527 if (VT.isVector()) 8528 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8529 return FoldedVOp; 8530 8531 ConstantSDNode *N1C = isConstOrConstSplat(N1); 8532 8533 // fold (sra c1, c2) -> (sra c1, c2) 8534 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, {N0, N1})) 8535 return C; 8536 8537 if (SDValue NewSel = foldBinOpIntoSelect(N)) 8538 return NewSel; 8539 8540 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 8541 // sext_inreg. 8542 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 8543 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 8544 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 8545 if (VT.isVector()) 8546 ExtVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, 8547 VT.getVectorElementCount()); 8548 if (!LegalOperations || 8549 TLI.getOperationAction(ISD::SIGN_EXTEND_INREG, ExtVT) == 8550 TargetLowering::Legal) 8551 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 8552 N0.getOperand(0), DAG.getValueType(ExtVT)); 8553 // Even if we can't convert to sext_inreg, we might be able to remove 8554 // this shift pair if the input is already sign extended. 8555 if (DAG.ComputeNumSignBits(N0.getOperand(0)) > N1C->getZExtValue()) 8556 return N0.getOperand(0); 8557 } 8558 8559 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 8560 // clamp (add c1, c2) to max shift. 8561 if (N0.getOpcode() == ISD::SRA) { 8562 SDLoc DL(N); 8563 EVT ShiftVT = N1.getValueType(); 8564 EVT ShiftSVT = ShiftVT.getScalarType(); 8565 SmallVector<SDValue, 16> ShiftValues; 8566 8567 auto SumOfShifts = [&](ConstantSDNode *LHS, ConstantSDNode *RHS) { 8568 APInt c1 = LHS->getAPIntValue(); 8569 APInt c2 = RHS->getAPIntValue(); 8570 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 8571 APInt Sum = c1 + c2; 8572 unsigned ShiftSum = 8573 Sum.uge(OpSizeInBits) ? (OpSizeInBits - 1) : Sum.getZExtValue(); 8574 ShiftValues.push_back(DAG.getConstant(ShiftSum, DL, ShiftSVT)); 8575 return true; 8576 }; 8577 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), SumOfShifts)) { 8578 SDValue ShiftValue; 8579 if (VT.isVector()) 8580 ShiftValue = DAG.getBuildVector(ShiftVT, DL, ShiftValues); 8581 else 8582 ShiftValue = ShiftValues[0]; 8583 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), ShiftValue); 8584 } 8585 } 8586 8587 // fold (sra (shl X, m), (sub result_size, n)) 8588 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 8589 // result_size - n != m. 8590 // If truncate is free for the target sext(shl) is likely to result in better 8591 // code. 8592 if (N0.getOpcode() == ISD::SHL && N1C) { 8593 // Get the two constanst of the shifts, CN0 = m, CN = n. 8594 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 8595 if (N01C) { 8596 LLVMContext &Ctx = *DAG.getContext(); 8597 // Determine what the truncate's result bitsize and type would be. 8598 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 8599 8600 if (VT.isVector()) 8601 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorElementCount()); 8602 8603 // Determine the residual right-shift amount. 8604 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 8605 8606 // If the shift is not a no-op (in which case this should be just a sign 8607 // extend already), the truncated to type is legal, sign_extend is legal 8608 // on that type, and the truncate to that type is both legal and free, 8609 // perform the transform. 8610 if ((ShiftAmt > 0) && 8611 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 8612 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 8613 TLI.isTruncateFree(VT, TruncVT)) { 8614 SDLoc DL(N); 8615 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 8616 getShiftAmountTy(N0.getOperand(0).getValueType())); 8617 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 8618 N0.getOperand(0), Amt); 8619 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 8620 Shift); 8621 return DAG.getNode(ISD::SIGN_EXTEND, DL, 8622 N->getValueType(0), Trunc); 8623 } 8624 } 8625 } 8626 8627 // We convert trunc/ext to opposing shifts in IR, but casts may be cheaper. 8628 // sra (add (shl X, N1C), AddC), N1C --> 8629 // sext (add (trunc X to (width - N1C)), AddC') 8630 if (N0.getOpcode() == ISD::ADD && N0.hasOneUse() && N1C && 8631 N0.getOperand(0).getOpcode() == ISD::SHL && 8632 N0.getOperand(0).getOperand(1) == N1 && N0.getOperand(0).hasOneUse()) { 8633 if (ConstantSDNode *AddC = isConstOrConstSplat(N0.getOperand(1))) { 8634 SDValue Shl = N0.getOperand(0); 8635 // Determine what the truncate's type would be and ask the target if that 8636 // is a free operation. 8637 LLVMContext &Ctx = *DAG.getContext(); 8638 unsigned ShiftAmt = N1C->getZExtValue(); 8639 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - ShiftAmt); 8640 if (VT.isVector()) 8641 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorElementCount()); 8642 8643 // TODO: The simple type check probably belongs in the default hook 8644 // implementation and/or target-specific overrides (because 8645 // non-simple types likely require masking when legalized), but that 8646 // restriction may conflict with other transforms. 8647 if (TruncVT.isSimple() && isTypeLegal(TruncVT) && 8648 TLI.isTruncateFree(VT, TruncVT)) { 8649 SDLoc DL(N); 8650 SDValue Trunc = DAG.getZExtOrTrunc(Shl.getOperand(0), DL, TruncVT); 8651 SDValue ShiftC = DAG.getConstant(AddC->getAPIntValue().lshr(ShiftAmt). 8652 trunc(TruncVT.getScalarSizeInBits()), DL, TruncVT); 8653 SDValue Add = DAG.getNode(ISD::ADD, DL, TruncVT, Trunc, ShiftC); 8654 return DAG.getSExtOrTrunc(Add, DL, VT); 8655 } 8656 } 8657 } 8658 8659 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 8660 if (N1.getOpcode() == ISD::TRUNCATE && 8661 N1.getOperand(0).getOpcode() == ISD::AND) { 8662 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 8663 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 8664 } 8665 8666 // fold (sra (trunc (sra x, c1)), c2) -> (trunc (sra x, c1 + c2)) 8667 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 8668 // if c1 is equal to the number of bits the trunc removes 8669 // TODO - support non-uniform vector shift amounts. 8670 if (N0.getOpcode() == ISD::TRUNCATE && 8671 (N0.getOperand(0).getOpcode() == ISD::SRL || 8672 N0.getOperand(0).getOpcode() == ISD::SRA) && 8673 N0.getOperand(0).hasOneUse() && 8674 N0.getOperand(0).getOperand(1).hasOneUse() && N1C) { 8675 SDValue N0Op0 = N0.getOperand(0); 8676 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 8677 EVT LargeVT = N0Op0.getValueType(); 8678 unsigned TruncBits = LargeVT.getScalarSizeInBits() - OpSizeInBits; 8679 if (LargeShift->getAPIntValue() == TruncBits) { 8680 SDLoc DL(N); 8681 SDValue Amt = DAG.getConstant(N1C->getZExtValue() + TruncBits, DL, 8682 getShiftAmountTy(LargeVT)); 8683 SDValue SRA = 8684 DAG.getNode(ISD::SRA, DL, LargeVT, N0Op0.getOperand(0), Amt); 8685 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 8686 } 8687 } 8688 } 8689 8690 // Simplify, based on bits shifted out of the LHS. 8691 if (SimplifyDemandedBits(SDValue(N, 0))) 8692 return SDValue(N, 0); 8693 8694 // If the sign bit is known to be zero, switch this to a SRL. 8695 if (DAG.SignBitIsZero(N0)) 8696 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 8697 8698 if (N1C && !N1C->isOpaque()) 8699 if (SDValue NewSRA = visitShiftByConstant(N)) 8700 return NewSRA; 8701 8702 // Try to transform this shift into a multiply-high if 8703 // it matches the appropriate pattern detected in combineShiftToMULH. 8704 if (SDValue MULH = combineShiftToMULH(N, DAG, TLI)) 8705 return MULH; 8706 8707 return SDValue(); 8708 } 8709 8710 SDValue DAGCombiner::visitSRL(SDNode *N) { 8711 SDValue N0 = N->getOperand(0); 8712 SDValue N1 = N->getOperand(1); 8713 if (SDValue V = DAG.simplifyShift(N0, N1)) 8714 return V; 8715 8716 EVT VT = N0.getValueType(); 8717 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 8718 8719 // fold vector ops 8720 if (VT.isVector()) 8721 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8722 return FoldedVOp; 8723 8724 ConstantSDNode *N1C = isConstOrConstSplat(N1); 8725 8726 // fold (srl c1, c2) -> c1 >>u c2 8727 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, {N0, N1})) 8728 return C; 8729 8730 if (SDValue NewSel = foldBinOpIntoSelect(N)) 8731 return NewSel; 8732 8733 // if (srl x, c) is known to be zero, return 0 8734 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 8735 APInt::getAllOnesValue(OpSizeInBits))) 8736 return DAG.getConstant(0, SDLoc(N), VT); 8737 8738 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 8739 if (N0.getOpcode() == ISD::SRL) { 8740 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 8741 ConstantSDNode *RHS) { 8742 APInt c1 = LHS->getAPIntValue(); 8743 APInt c2 = RHS->getAPIntValue(); 8744 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 8745 return (c1 + c2).uge(OpSizeInBits); 8746 }; 8747 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 8748 return DAG.getConstant(0, SDLoc(N), VT); 8749 8750 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 8751 ConstantSDNode *RHS) { 8752 APInt c1 = LHS->getAPIntValue(); 8753 APInt c2 = RHS->getAPIntValue(); 8754 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 8755 return (c1 + c2).ult(OpSizeInBits); 8756 }; 8757 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 8758 SDLoc DL(N); 8759 EVT ShiftVT = N1.getValueType(); 8760 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 8761 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum); 8762 } 8763 } 8764 8765 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 8766 N0.getOperand(0).getOpcode() == ISD::SRL) { 8767 SDValue InnerShift = N0.getOperand(0); 8768 // TODO - support non-uniform vector shift amounts. 8769 if (auto *N001C = isConstOrConstSplat(InnerShift.getOperand(1))) { 8770 uint64_t c1 = N001C->getZExtValue(); 8771 uint64_t c2 = N1C->getZExtValue(); 8772 EVT InnerShiftVT = InnerShift.getValueType(); 8773 EVT ShiftAmtVT = InnerShift.getOperand(1).getValueType(); 8774 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 8775 // srl (trunc (srl x, c1)), c2 --> 0 or (trunc (srl x, (add c1, c2))) 8776 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 8777 if (c1 + OpSizeInBits == InnerShiftSize) { 8778 SDLoc DL(N); 8779 if (c1 + c2 >= InnerShiftSize) 8780 return DAG.getConstant(0, DL, VT); 8781 SDValue NewShiftAmt = DAG.getConstant(c1 + c2, DL, ShiftAmtVT); 8782 SDValue NewShift = DAG.getNode(ISD::SRL, DL, InnerShiftVT, 8783 InnerShift.getOperand(0), NewShiftAmt); 8784 return DAG.getNode(ISD::TRUNCATE, DL, VT, NewShift); 8785 } 8786 // In the more general case, we can clear the high bits after the shift: 8787 // srl (trunc (srl x, c1)), c2 --> trunc (and (srl x, (c1+c2)), Mask) 8788 if (N0.hasOneUse() && InnerShift.hasOneUse() && 8789 c1 + c2 < InnerShiftSize) { 8790 SDLoc DL(N); 8791 SDValue NewShiftAmt = DAG.getConstant(c1 + c2, DL, ShiftAmtVT); 8792 SDValue NewShift = DAG.getNode(ISD::SRL, DL, InnerShiftVT, 8793 InnerShift.getOperand(0), NewShiftAmt); 8794 SDValue Mask = DAG.getConstant(APInt::getLowBitsSet(InnerShiftSize, 8795 OpSizeInBits - c2), 8796 DL, InnerShiftVT); 8797 SDValue And = DAG.getNode(ISD::AND, DL, InnerShiftVT, NewShift, Mask); 8798 return DAG.getNode(ISD::TRUNCATE, DL, VT, And); 8799 } 8800 } 8801 } 8802 8803 // fold (srl (shl x, c), c) -> (and x, cst2) 8804 // TODO - (srl (shl x, c1), c2). 8805 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 8806 isConstantOrConstantVector(N1, /* NoOpaques */ true)) { 8807 SDLoc DL(N); 8808 SDValue Mask = 8809 DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1); 8810 AddToWorklist(Mask.getNode()); 8811 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask); 8812 } 8813 8814 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 8815 // TODO - support non-uniform vector shift amounts. 8816 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 8817 // Shifting in all undef bits? 8818 EVT SmallVT = N0.getOperand(0).getValueType(); 8819 unsigned BitSize = SmallVT.getScalarSizeInBits(); 8820 if (N1C->getAPIntValue().uge(BitSize)) 8821 return DAG.getUNDEF(VT); 8822 8823 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 8824 uint64_t ShiftAmt = N1C->getZExtValue(); 8825 SDLoc DL0(N0); 8826 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 8827 N0.getOperand(0), 8828 DAG.getConstant(ShiftAmt, DL0, 8829 getShiftAmountTy(SmallVT))); 8830 AddToWorklist(SmallShift.getNode()); 8831 APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt); 8832 SDLoc DL(N); 8833 return DAG.getNode(ISD::AND, DL, VT, 8834 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 8835 DAG.getConstant(Mask, DL, VT)); 8836 } 8837 } 8838 8839 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 8840 // bit, which is unmodified by sra. 8841 if (N1C && N1C->getAPIntValue() == (OpSizeInBits - 1)) { 8842 if (N0.getOpcode() == ISD::SRA) 8843 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 8844 } 8845 8846 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 8847 if (N1C && N0.getOpcode() == ISD::CTLZ && 8848 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 8849 KnownBits Known = DAG.computeKnownBits(N0.getOperand(0)); 8850 8851 // If any of the input bits are KnownOne, then the input couldn't be all 8852 // zeros, thus the result of the srl will always be zero. 8853 if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 8854 8855 // If all of the bits input the to ctlz node are known to be zero, then 8856 // the result of the ctlz is "32" and the result of the shift is one. 8857 APInt UnknownBits = ~Known.Zero; 8858 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 8859 8860 // Otherwise, check to see if there is exactly one bit input to the ctlz. 8861 if (UnknownBits.isPowerOf2()) { 8862 // Okay, we know that only that the single bit specified by UnknownBits 8863 // could be set on input to the CTLZ node. If this bit is set, the SRL 8864 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 8865 // to an SRL/XOR pair, which is likely to simplify more. 8866 unsigned ShAmt = UnknownBits.countTrailingZeros(); 8867 SDValue Op = N0.getOperand(0); 8868 8869 if (ShAmt) { 8870 SDLoc DL(N0); 8871 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 8872 DAG.getConstant(ShAmt, DL, 8873 getShiftAmountTy(Op.getValueType()))); 8874 AddToWorklist(Op.getNode()); 8875 } 8876 8877 SDLoc DL(N); 8878 return DAG.getNode(ISD::XOR, DL, VT, 8879 Op, DAG.getConstant(1, DL, VT)); 8880 } 8881 } 8882 8883 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 8884 if (N1.getOpcode() == ISD::TRUNCATE && 8885 N1.getOperand(0).getOpcode() == ISD::AND) { 8886 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 8887 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 8888 } 8889 8890 // fold operands of srl based on knowledge that the low bits are not 8891 // demanded. 8892 if (SimplifyDemandedBits(SDValue(N, 0))) 8893 return SDValue(N, 0); 8894 8895 if (N1C && !N1C->isOpaque()) 8896 if (SDValue NewSRL = visitShiftByConstant(N)) 8897 return NewSRL; 8898 8899 // Attempt to convert a srl of a load into a narrower zero-extending load. 8900 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 8901 return NarrowLoad; 8902 8903 // Here is a common situation. We want to optimize: 8904 // 8905 // %a = ... 8906 // %b = and i32 %a, 2 8907 // %c = srl i32 %b, 1 8908 // brcond i32 %c ... 8909 // 8910 // into 8911 // 8912 // %a = ... 8913 // %b = and %a, 2 8914 // %c = setcc eq %b, 0 8915 // brcond %c ... 8916 // 8917 // However when after the source operand of SRL is optimized into AND, the SRL 8918 // itself may not be optimized further. Look for it and add the BRCOND into 8919 // the worklist. 8920 if (N->hasOneUse()) { 8921 SDNode *Use = *N->use_begin(); 8922 if (Use->getOpcode() == ISD::BRCOND) 8923 AddToWorklist(Use); 8924 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 8925 // Also look pass the truncate. 8926 Use = *Use->use_begin(); 8927 if (Use->getOpcode() == ISD::BRCOND) 8928 AddToWorklist(Use); 8929 } 8930 } 8931 8932 // Try to transform this shift into a multiply-high if 8933 // it matches the appropriate pattern detected in combineShiftToMULH. 8934 if (SDValue MULH = combineShiftToMULH(N, DAG, TLI)) 8935 return MULH; 8936 8937 return SDValue(); 8938 } 8939 8940 SDValue DAGCombiner::visitFunnelShift(SDNode *N) { 8941 EVT VT = N->getValueType(0); 8942 SDValue N0 = N->getOperand(0); 8943 SDValue N1 = N->getOperand(1); 8944 SDValue N2 = N->getOperand(2); 8945 bool IsFSHL = N->getOpcode() == ISD::FSHL; 8946 unsigned BitWidth = VT.getScalarSizeInBits(); 8947 8948 // fold (fshl N0, N1, 0) -> N0 8949 // fold (fshr N0, N1, 0) -> N1 8950 if (isPowerOf2_32(BitWidth)) 8951 if (DAG.MaskedValueIsZero( 8952 N2, APInt(N2.getScalarValueSizeInBits(), BitWidth - 1))) 8953 return IsFSHL ? N0 : N1; 8954 8955 auto IsUndefOrZero = [](SDValue V) { 8956 return V.isUndef() || isNullOrNullSplat(V, /*AllowUndefs*/ true); 8957 }; 8958 8959 // TODO - support non-uniform vector shift amounts. 8960 if (ConstantSDNode *Cst = isConstOrConstSplat(N2)) { 8961 EVT ShAmtTy = N2.getValueType(); 8962 8963 // fold (fsh* N0, N1, c) -> (fsh* N0, N1, c % BitWidth) 8964 if (Cst->getAPIntValue().uge(BitWidth)) { 8965 uint64_t RotAmt = Cst->getAPIntValue().urem(BitWidth); 8966 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N0, N1, 8967 DAG.getConstant(RotAmt, SDLoc(N), ShAmtTy)); 8968 } 8969 8970 unsigned ShAmt = Cst->getZExtValue(); 8971 if (ShAmt == 0) 8972 return IsFSHL ? N0 : N1; 8973 8974 // fold fshl(undef_or_zero, N1, C) -> lshr(N1, BW-C) 8975 // fold fshr(undef_or_zero, N1, C) -> lshr(N1, C) 8976 // fold fshl(N0, undef_or_zero, C) -> shl(N0, C) 8977 // fold fshr(N0, undef_or_zero, C) -> shl(N0, BW-C) 8978 if (IsUndefOrZero(N0)) 8979 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N1, 8980 DAG.getConstant(IsFSHL ? BitWidth - ShAmt : ShAmt, 8981 SDLoc(N), ShAmtTy)); 8982 if (IsUndefOrZero(N1)) 8983 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 8984 DAG.getConstant(IsFSHL ? ShAmt : BitWidth - ShAmt, 8985 SDLoc(N), ShAmtTy)); 8986 8987 // fold (fshl ld1, ld0, c) -> (ld0[ofs]) iff ld0 and ld1 are consecutive. 8988 // fold (fshr ld1, ld0, c) -> (ld0[ofs]) iff ld0 and ld1 are consecutive. 8989 // TODO - bigendian support once we have test coverage. 8990 // TODO - can we merge this with CombineConseutiveLoads/MatchLoadCombine? 8991 // TODO - permit LHS EXTLOAD if extensions are shifted out. 8992 if ((BitWidth % 8) == 0 && (ShAmt % 8) == 0 && !VT.isVector() && 8993 !DAG.getDataLayout().isBigEndian()) { 8994 auto *LHS = dyn_cast<LoadSDNode>(N0); 8995 auto *RHS = dyn_cast<LoadSDNode>(N1); 8996 if (LHS && RHS && LHS->isSimple() && RHS->isSimple() && 8997 LHS->getAddressSpace() == RHS->getAddressSpace() && 8998 (LHS->hasOneUse() || RHS->hasOneUse()) && ISD::isNON_EXTLoad(RHS) && 8999 ISD::isNON_EXTLoad(LHS)) { 9000 if (DAG.areNonVolatileConsecutiveLoads(LHS, RHS, BitWidth / 8, 1)) { 9001 SDLoc DL(RHS); 9002 uint64_t PtrOff = 9003 IsFSHL ? (((BitWidth - ShAmt) % BitWidth) / 8) : (ShAmt / 8); 9004 Align NewAlign = commonAlignment(RHS->getAlign(), PtrOff); 9005 bool Fast = false; 9006 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 9007 RHS->getAddressSpace(), NewAlign, 9008 RHS->getMemOperand()->getFlags(), &Fast) && 9009 Fast) { 9010 SDValue NewPtr = DAG.getMemBasePlusOffset( 9011 RHS->getBasePtr(), TypeSize::Fixed(PtrOff), DL); 9012 AddToWorklist(NewPtr.getNode()); 9013 SDValue Load = DAG.getLoad( 9014 VT, DL, RHS->getChain(), NewPtr, 9015 RHS->getPointerInfo().getWithOffset(PtrOff), NewAlign, 9016 RHS->getMemOperand()->getFlags(), RHS->getAAInfo()); 9017 // Replace the old load's chain with the new load's chain. 9018 WorklistRemover DeadNodes(*this); 9019 DAG.ReplaceAllUsesOfValueWith(N1.getValue(1), Load.getValue(1)); 9020 return Load; 9021 } 9022 } 9023 } 9024 } 9025 } 9026 9027 // fold fshr(undef_or_zero, N1, N2) -> lshr(N1, N2) 9028 // fold fshl(N0, undef_or_zero, N2) -> shl(N0, N2) 9029 // iff We know the shift amount is in range. 9030 // TODO: when is it worth doing SUB(BW, N2) as well? 9031 if (isPowerOf2_32(BitWidth)) { 9032 APInt ModuloBits(N2.getScalarValueSizeInBits(), BitWidth - 1); 9033 if (IsUndefOrZero(N0) && !IsFSHL && DAG.MaskedValueIsZero(N2, ~ModuloBits)) 9034 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N1, N2); 9035 if (IsUndefOrZero(N1) && IsFSHL && DAG.MaskedValueIsZero(N2, ~ModuloBits)) 9036 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, N2); 9037 } 9038 9039 // fold (fshl N0, N0, N2) -> (rotl N0, N2) 9040 // fold (fshr N0, N0, N2) -> (rotr N0, N2) 9041 // TODO: Investigate flipping this rotate if only one is legal, if funnel shift 9042 // is legal as well we might be better off avoiding non-constant (BW - N2). 9043 unsigned RotOpc = IsFSHL ? ISD::ROTL : ISD::ROTR; 9044 if (N0 == N1 && hasOperation(RotOpc, VT)) 9045 return DAG.getNode(RotOpc, SDLoc(N), VT, N0, N2); 9046 9047 // Simplify, based on bits shifted out of N0/N1. 9048 if (SimplifyDemandedBits(SDValue(N, 0))) 9049 return SDValue(N, 0); 9050 9051 return SDValue(); 9052 } 9053 9054 SDValue DAGCombiner::visitABS(SDNode *N) { 9055 SDValue N0 = N->getOperand(0); 9056 EVT VT = N->getValueType(0); 9057 9058 // fold (abs c1) -> c2 9059 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 9060 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0); 9061 // fold (abs (abs x)) -> (abs x) 9062 if (N0.getOpcode() == ISD::ABS) 9063 return N0; 9064 // fold (abs x) -> x iff not-negative 9065 if (DAG.SignBitIsZero(N0)) 9066 return N0; 9067 return SDValue(); 9068 } 9069 9070 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 9071 SDValue N0 = N->getOperand(0); 9072 EVT VT = N->getValueType(0); 9073 9074 // fold (bswap c1) -> c2 9075 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 9076 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 9077 // fold (bswap (bswap x)) -> x 9078 if (N0.getOpcode() == ISD::BSWAP) 9079 return N0->getOperand(0); 9080 return SDValue(); 9081 } 9082 9083 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) { 9084 SDValue N0 = N->getOperand(0); 9085 EVT VT = N->getValueType(0); 9086 9087 // fold (bitreverse c1) -> c2 9088 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 9089 return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0); 9090 // fold (bitreverse (bitreverse x)) -> x 9091 if (N0.getOpcode() == ISD::BITREVERSE) 9092 return N0.getOperand(0); 9093 return SDValue(); 9094 } 9095 9096 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 9097 SDValue N0 = N->getOperand(0); 9098 EVT VT = N->getValueType(0); 9099 9100 // fold (ctlz c1) -> c2 9101 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 9102 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 9103 9104 // If the value is known never to be zero, switch to the undef version. 9105 if (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ_ZERO_UNDEF, VT)) { 9106 if (DAG.isKnownNeverZero(N0)) 9107 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 9108 } 9109 9110 return SDValue(); 9111 } 9112 9113 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 9114 SDValue N0 = N->getOperand(0); 9115 EVT VT = N->getValueType(0); 9116 9117 // fold (ctlz_zero_undef c1) -> c2 9118 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 9119 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 9120 return SDValue(); 9121 } 9122 9123 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 9124 SDValue N0 = N->getOperand(0); 9125 EVT VT = N->getValueType(0); 9126 9127 // fold (cttz c1) -> c2 9128 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 9129 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 9130 9131 // If the value is known never to be zero, switch to the undef version. 9132 if (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ_ZERO_UNDEF, VT)) { 9133 if (DAG.isKnownNeverZero(N0)) 9134 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 9135 } 9136 9137 return SDValue(); 9138 } 9139 9140 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 9141 SDValue N0 = N->getOperand(0); 9142 EVT VT = N->getValueType(0); 9143 9144 // fold (cttz_zero_undef c1) -> c2 9145 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 9146 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 9147 return SDValue(); 9148 } 9149 9150 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 9151 SDValue N0 = N->getOperand(0); 9152 EVT VT = N->getValueType(0); 9153 9154 // fold (ctpop c1) -> c2 9155 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 9156 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 9157 return SDValue(); 9158 } 9159 9160 // FIXME: This should be checking for no signed zeros on individual operands, as 9161 // well as no nans. 9162 static bool isLegalToCombineMinNumMaxNum(SelectionDAG &DAG, SDValue LHS, 9163 SDValue RHS, 9164 const TargetLowering &TLI) { 9165 const TargetOptions &Options = DAG.getTarget().Options; 9166 EVT VT = LHS.getValueType(); 9167 9168 return Options.NoSignedZerosFPMath && VT.isFloatingPoint() && 9169 TLI.isProfitableToCombineMinNumMaxNum(VT) && 9170 DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS); 9171 } 9172 9173 /// Generate Min/Max node 9174 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS, 9175 SDValue RHS, SDValue True, SDValue False, 9176 ISD::CondCode CC, const TargetLowering &TLI, 9177 SelectionDAG &DAG) { 9178 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 9179 return SDValue(); 9180 9181 EVT TransformVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT); 9182 switch (CC) { 9183 case ISD::SETOLT: 9184 case ISD::SETOLE: 9185 case ISD::SETLT: 9186 case ISD::SETLE: 9187 case ISD::SETULT: 9188 case ISD::SETULE: { 9189 // Since it's known never nan to get here already, either fminnum or 9190 // fminnum_ieee are OK. Try the ieee version first, since it's fminnum is 9191 // expanded in terms of it. 9192 unsigned IEEEOpcode = (LHS == True) ? ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE; 9193 if (TLI.isOperationLegalOrCustom(IEEEOpcode, VT)) 9194 return DAG.getNode(IEEEOpcode, DL, VT, LHS, RHS); 9195 9196 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 9197 if (TLI.isOperationLegalOrCustom(Opcode, TransformVT)) 9198 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 9199 return SDValue(); 9200 } 9201 case ISD::SETOGT: 9202 case ISD::SETOGE: 9203 case ISD::SETGT: 9204 case ISD::SETGE: 9205 case ISD::SETUGT: 9206 case ISD::SETUGE: { 9207 unsigned IEEEOpcode = (LHS == True) ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE; 9208 if (TLI.isOperationLegalOrCustom(IEEEOpcode, VT)) 9209 return DAG.getNode(IEEEOpcode, DL, VT, LHS, RHS); 9210 9211 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 9212 if (TLI.isOperationLegalOrCustom(Opcode, TransformVT)) 9213 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 9214 return SDValue(); 9215 } 9216 default: 9217 return SDValue(); 9218 } 9219 } 9220 9221 /// If a (v)select has a condition value that is a sign-bit test, try to smear 9222 /// the condition operand sign-bit across the value width and use it as a mask. 9223 static SDValue foldSelectOfConstantsUsingSra(SDNode *N, SelectionDAG &DAG) { 9224 SDValue Cond = N->getOperand(0); 9225 SDValue C1 = N->getOperand(1); 9226 SDValue C2 = N->getOperand(2); 9227 if (!isConstantOrConstantVector(C1) || !isConstantOrConstantVector(C2)) 9228 return SDValue(); 9229 9230 EVT VT = N->getValueType(0); 9231 if (Cond.getOpcode() != ISD::SETCC || !Cond.hasOneUse() || 9232 VT != Cond.getOperand(0).getValueType()) 9233 return SDValue(); 9234 9235 // The inverted-condition + commuted-select variants of these patterns are 9236 // canonicalized to these forms in IR. 9237 SDValue X = Cond.getOperand(0); 9238 SDValue CondC = Cond.getOperand(1); 9239 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 9240 if (CC == ISD::SETGT && isAllOnesOrAllOnesSplat(CondC) && 9241 isAllOnesOrAllOnesSplat(C2)) { 9242 // i32 X > -1 ? C1 : -1 --> (X >>s 31) | C1 9243 SDLoc DL(N); 9244 SDValue ShAmtC = DAG.getConstant(X.getScalarValueSizeInBits() - 1, DL, VT); 9245 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, X, ShAmtC); 9246 return DAG.getNode(ISD::OR, DL, VT, Sra, C1); 9247 } 9248 if (CC == ISD::SETLT && isNullOrNullSplat(CondC) && isNullOrNullSplat(C2)) { 9249 // i8 X < 0 ? C1 : 0 --> (X >>s 7) & C1 9250 SDLoc DL(N); 9251 SDValue ShAmtC = DAG.getConstant(X.getScalarValueSizeInBits() - 1, DL, VT); 9252 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, X, ShAmtC); 9253 return DAG.getNode(ISD::AND, DL, VT, Sra, C1); 9254 } 9255 return SDValue(); 9256 } 9257 9258 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) { 9259 SDValue Cond = N->getOperand(0); 9260 SDValue N1 = N->getOperand(1); 9261 SDValue N2 = N->getOperand(2); 9262 EVT VT = N->getValueType(0); 9263 EVT CondVT = Cond.getValueType(); 9264 SDLoc DL(N); 9265 9266 if (!VT.isInteger()) 9267 return SDValue(); 9268 9269 auto *C1 = dyn_cast<ConstantSDNode>(N1); 9270 auto *C2 = dyn_cast<ConstantSDNode>(N2); 9271 if (!C1 || !C2) 9272 return SDValue(); 9273 9274 // Only do this before legalization to avoid conflicting with target-specific 9275 // transforms in the other direction (create a select from a zext/sext). There 9276 // is also a target-independent combine here in DAGCombiner in the other 9277 // direction for (select Cond, -1, 0) when the condition is not i1. 9278 if (CondVT == MVT::i1 && !LegalOperations) { 9279 if (C1->isNullValue() && C2->isOne()) { 9280 // select Cond, 0, 1 --> zext (!Cond) 9281 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 9282 if (VT != MVT::i1) 9283 NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond); 9284 return NotCond; 9285 } 9286 if (C1->isNullValue() && C2->isAllOnesValue()) { 9287 // select Cond, 0, -1 --> sext (!Cond) 9288 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 9289 if (VT != MVT::i1) 9290 NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond); 9291 return NotCond; 9292 } 9293 if (C1->isOne() && C2->isNullValue()) { 9294 // select Cond, 1, 0 --> zext (Cond) 9295 if (VT != MVT::i1) 9296 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 9297 return Cond; 9298 } 9299 if (C1->isAllOnesValue() && C2->isNullValue()) { 9300 // select Cond, -1, 0 --> sext (Cond) 9301 if (VT != MVT::i1) 9302 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 9303 return Cond; 9304 } 9305 9306 // Use a target hook because some targets may prefer to transform in the 9307 // other direction. 9308 if (TLI.convertSelectOfConstantsToMath(VT)) { 9309 // For any constants that differ by 1, we can transform the select into an 9310 // extend and add. 9311 const APInt &C1Val = C1->getAPIntValue(); 9312 const APInt &C2Val = C2->getAPIntValue(); 9313 if (C1Val - 1 == C2Val) { 9314 // select Cond, C1, C1-1 --> add (zext Cond), C1-1 9315 if (VT != MVT::i1) 9316 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 9317 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 9318 } 9319 if (C1Val + 1 == C2Val) { 9320 // select Cond, C1, C1+1 --> add (sext Cond), C1+1 9321 if (VT != MVT::i1) 9322 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 9323 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 9324 } 9325 9326 // select Cond, Pow2, 0 --> (zext Cond) << log2(Pow2) 9327 if (C1Val.isPowerOf2() && C2Val.isNullValue()) { 9328 if (VT != MVT::i1) 9329 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 9330 SDValue ShAmtC = DAG.getConstant(C1Val.exactLogBase2(), DL, VT); 9331 return DAG.getNode(ISD::SHL, DL, VT, Cond, ShAmtC); 9332 } 9333 9334 if (SDValue V = foldSelectOfConstantsUsingSra(N, DAG)) 9335 return V; 9336 } 9337 9338 return SDValue(); 9339 } 9340 9341 // fold (select Cond, 0, 1) -> (xor Cond, 1) 9342 // We can't do this reliably if integer based booleans have different contents 9343 // to floating point based booleans. This is because we can't tell whether we 9344 // have an integer-based boolean or a floating-point-based boolean unless we 9345 // can find the SETCC that produced it and inspect its operands. This is 9346 // fairly easy if C is the SETCC node, but it can potentially be 9347 // undiscoverable (or not reasonably discoverable). For example, it could be 9348 // in another basic block or it could require searching a complicated 9349 // expression. 9350 if (CondVT.isInteger() && 9351 TLI.getBooleanContents(/*isVec*/false, /*isFloat*/true) == 9352 TargetLowering::ZeroOrOneBooleanContent && 9353 TLI.getBooleanContents(/*isVec*/false, /*isFloat*/false) == 9354 TargetLowering::ZeroOrOneBooleanContent && 9355 C1->isNullValue() && C2->isOne()) { 9356 SDValue NotCond = 9357 DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT)); 9358 if (VT.bitsEq(CondVT)) 9359 return NotCond; 9360 return DAG.getZExtOrTrunc(NotCond, DL, VT); 9361 } 9362 9363 return SDValue(); 9364 } 9365 9366 static SDValue foldBoolSelectToLogic(SDNode *N, SelectionDAG &DAG) { 9367 assert((N->getOpcode() == ISD::SELECT || N->getOpcode() == ISD::VSELECT) && 9368 "Expected a (v)select"); 9369 SDValue Cond = N->getOperand(0); 9370 SDValue T = N->getOperand(1), F = N->getOperand(2); 9371 EVT VT = N->getValueType(0); 9372 if (VT != Cond.getValueType() || VT.getScalarSizeInBits() != 1) 9373 return SDValue(); 9374 9375 // select Cond, Cond, F --> or Cond, F 9376 // select Cond, 1, F --> or Cond, F 9377 if (Cond == T || isOneOrOneSplat(T, /* AllowUndefs */ true)) 9378 return DAG.getNode(ISD::OR, SDLoc(N), VT, Cond, F); 9379 9380 // select Cond, T, Cond --> and Cond, T 9381 // select Cond, T, 0 --> and Cond, T 9382 if (Cond == F || isNullOrNullSplat(F, /* AllowUndefs */ true)) 9383 return DAG.getNode(ISD::AND, SDLoc(N), VT, Cond, T); 9384 9385 // select Cond, T, 1 --> or (not Cond), T 9386 if (isOneOrOneSplat(F, /* AllowUndefs */ true)) { 9387 SDValue NotCond = DAG.getNOT(SDLoc(N), Cond, VT); 9388 return DAG.getNode(ISD::OR, SDLoc(N), VT, NotCond, T); 9389 } 9390 9391 // select Cond, 0, F --> and (not Cond), F 9392 if (isNullOrNullSplat(T, /* AllowUndefs */ true)) { 9393 SDValue NotCond = DAG.getNOT(SDLoc(N), Cond, VT); 9394 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotCond, F); 9395 } 9396 9397 return SDValue(); 9398 } 9399 9400 SDValue DAGCombiner::visitSELECT(SDNode *N) { 9401 SDValue N0 = N->getOperand(0); 9402 SDValue N1 = N->getOperand(1); 9403 SDValue N2 = N->getOperand(2); 9404 EVT VT = N->getValueType(0); 9405 EVT VT0 = N0.getValueType(); 9406 SDLoc DL(N); 9407 SDNodeFlags Flags = N->getFlags(); 9408 9409 if (SDValue V = DAG.simplifySelect(N0, N1, N2)) 9410 return V; 9411 9412 if (SDValue V = foldSelectOfConstants(N)) 9413 return V; 9414 9415 if (SDValue V = foldBoolSelectToLogic(N, DAG)) 9416 return V; 9417 9418 // If we can fold this based on the true/false value, do so. 9419 if (SimplifySelectOps(N, N1, N2)) 9420 return SDValue(N, 0); // Don't revisit N. 9421 9422 if (VT0 == MVT::i1) { 9423 // The code in this block deals with the following 2 equivalences: 9424 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 9425 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 9426 // The target can specify its preferred form with the 9427 // shouldNormalizeToSelectSequence() callback. However we always transform 9428 // to the right anyway if we find the inner select exists in the DAG anyway 9429 // and we always transform to the left side if we know that we can further 9430 // optimize the combination of the conditions. 9431 bool normalizeToSequence = 9432 TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 9433 // select (and Cond0, Cond1), X, Y 9434 // -> select Cond0, (select Cond1, X, Y), Y 9435 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 9436 SDValue Cond0 = N0->getOperand(0); 9437 SDValue Cond1 = N0->getOperand(1); 9438 SDValue InnerSelect = 9439 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2, Flags); 9440 if (normalizeToSequence || !InnerSelect.use_empty()) 9441 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, 9442 InnerSelect, N2, Flags); 9443 // Cleanup on failure. 9444 if (InnerSelect.use_empty()) 9445 recursivelyDeleteUnusedNodes(InnerSelect.getNode()); 9446 } 9447 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 9448 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 9449 SDValue Cond0 = N0->getOperand(0); 9450 SDValue Cond1 = N0->getOperand(1); 9451 SDValue InnerSelect = DAG.getNode(ISD::SELECT, DL, N1.getValueType(), 9452 Cond1, N1, N2, Flags); 9453 if (normalizeToSequence || !InnerSelect.use_empty()) 9454 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1, 9455 InnerSelect, Flags); 9456 // Cleanup on failure. 9457 if (InnerSelect.use_empty()) 9458 recursivelyDeleteUnusedNodes(InnerSelect.getNode()); 9459 } 9460 9461 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 9462 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 9463 SDValue N1_0 = N1->getOperand(0); 9464 SDValue N1_1 = N1->getOperand(1); 9465 SDValue N1_2 = N1->getOperand(2); 9466 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 9467 // Create the actual and node if we can generate good code for it. 9468 if (!normalizeToSequence) { 9469 SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0); 9470 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, 9471 N2, Flags); 9472 } 9473 // Otherwise see if we can optimize the "and" to a better pattern. 9474 if (SDValue Combined = visitANDLike(N0, N1_0, N)) { 9475 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1, 9476 N2, Flags); 9477 } 9478 } 9479 } 9480 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 9481 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 9482 SDValue N2_0 = N2->getOperand(0); 9483 SDValue N2_1 = N2->getOperand(1); 9484 SDValue N2_2 = N2->getOperand(2); 9485 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 9486 // Create the actual or node if we can generate good code for it. 9487 if (!normalizeToSequence) { 9488 SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0); 9489 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, 9490 N2_2, Flags); 9491 } 9492 // Otherwise see if we can optimize to a better pattern. 9493 if (SDValue Combined = visitORLike(N0, N2_0, N)) 9494 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1, 9495 N2_2, Flags); 9496 } 9497 } 9498 } 9499 9500 // select (not Cond), N1, N2 -> select Cond, N2, N1 9501 if (SDValue F = extractBooleanFlip(N0, DAG, TLI, false)) { 9502 SDValue SelectOp = DAG.getSelect(DL, VT, F, N2, N1); 9503 SelectOp->setFlags(Flags); 9504 return SelectOp; 9505 } 9506 9507 // Fold selects based on a setcc into other things, such as min/max/abs. 9508 if (N0.getOpcode() == ISD::SETCC) { 9509 SDValue Cond0 = N0.getOperand(0), Cond1 = N0.getOperand(1); 9510 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 9511 9512 // select (fcmp lt x, y), x, y -> fminnum x, y 9513 // select (fcmp gt x, y), x, y -> fmaxnum x, y 9514 // 9515 // This is OK if we don't care what happens if either operand is a NaN. 9516 if (N0.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG, N1, N2, TLI)) 9517 if (SDValue FMinMax = combineMinNumMaxNum(DL, VT, Cond0, Cond1, N1, N2, 9518 CC, TLI, DAG)) 9519 return FMinMax; 9520 9521 // Use 'unsigned add with overflow' to optimize an unsigned saturating add. 9522 // This is conservatively limited to pre-legal-operations to give targets 9523 // a chance to reverse the transform if they want to do that. Also, it is 9524 // unlikely that the pattern would be formed late, so it's probably not 9525 // worth going through the other checks. 9526 if (!LegalOperations && TLI.isOperationLegalOrCustom(ISD::UADDO, VT) && 9527 CC == ISD::SETUGT && N0.hasOneUse() && isAllOnesConstant(N1) && 9528 N2.getOpcode() == ISD::ADD && Cond0 == N2.getOperand(0)) { 9529 auto *C = dyn_cast<ConstantSDNode>(N2.getOperand(1)); 9530 auto *NotC = dyn_cast<ConstantSDNode>(Cond1); 9531 if (C && NotC && C->getAPIntValue() == ~NotC->getAPIntValue()) { 9532 // select (setcc Cond0, ~C, ugt), -1, (add Cond0, C) --> 9533 // uaddo Cond0, C; select uaddo.1, -1, uaddo.0 9534 // 9535 // The IR equivalent of this transform would have this form: 9536 // %a = add %x, C 9537 // %c = icmp ugt %x, ~C 9538 // %r = select %c, -1, %a 9539 // => 9540 // %u = call {iN,i1} llvm.uadd.with.overflow(%x, C) 9541 // %u0 = extractvalue %u, 0 9542 // %u1 = extractvalue %u, 1 9543 // %r = select %u1, -1, %u0 9544 SDVTList VTs = DAG.getVTList(VT, VT0); 9545 SDValue UAO = DAG.getNode(ISD::UADDO, DL, VTs, Cond0, N2.getOperand(1)); 9546 return DAG.getSelect(DL, VT, UAO.getValue(1), N1, UAO.getValue(0)); 9547 } 9548 } 9549 9550 if (TLI.isOperationLegal(ISD::SELECT_CC, VT) || 9551 (!LegalOperations && 9552 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))) { 9553 // Any flags available in a select/setcc fold will be on the setcc as they 9554 // migrated from fcmp 9555 Flags = N0.getNode()->getFlags(); 9556 SDValue SelectNode = DAG.getNode(ISD::SELECT_CC, DL, VT, Cond0, Cond1, N1, 9557 N2, N0.getOperand(2)); 9558 SelectNode->setFlags(Flags); 9559 return SelectNode; 9560 } 9561 9562 return SimplifySelect(DL, N0, N1, N2); 9563 } 9564 9565 return SDValue(); 9566 } 9567 9568 // This function assumes all the vselect's arguments are CONCAT_VECTOR 9569 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 9570 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 9571 SDLoc DL(N); 9572 SDValue Cond = N->getOperand(0); 9573 SDValue LHS = N->getOperand(1); 9574 SDValue RHS = N->getOperand(2); 9575 EVT VT = N->getValueType(0); 9576 int NumElems = VT.getVectorNumElements(); 9577 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 9578 RHS.getOpcode() == ISD::CONCAT_VECTORS && 9579 Cond.getOpcode() == ISD::BUILD_VECTOR); 9580 9581 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 9582 // binary ones here. 9583 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 9584 return SDValue(); 9585 9586 // We're sure we have an even number of elements due to the 9587 // concat_vectors we have as arguments to vselect. 9588 // Skip BV elements until we find one that's not an UNDEF 9589 // After we find an UNDEF element, keep looping until we get to half the 9590 // length of the BV and see if all the non-undef nodes are the same. 9591 ConstantSDNode *BottomHalf = nullptr; 9592 for (int i = 0; i < NumElems / 2; ++i) { 9593 if (Cond->getOperand(i)->isUndef()) 9594 continue; 9595 9596 if (BottomHalf == nullptr) 9597 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 9598 else if (Cond->getOperand(i).getNode() != BottomHalf) 9599 return SDValue(); 9600 } 9601 9602 // Do the same for the second half of the BuildVector 9603 ConstantSDNode *TopHalf = nullptr; 9604 for (int i = NumElems / 2; i < NumElems; ++i) { 9605 if (Cond->getOperand(i)->isUndef()) 9606 continue; 9607 9608 if (TopHalf == nullptr) 9609 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 9610 else if (Cond->getOperand(i).getNode() != TopHalf) 9611 return SDValue(); 9612 } 9613 9614 assert(TopHalf && BottomHalf && 9615 "One half of the selector was all UNDEFs and the other was all the " 9616 "same value. This should have been addressed before this function."); 9617 return DAG.getNode( 9618 ISD::CONCAT_VECTORS, DL, VT, 9619 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 9620 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 9621 } 9622 9623 bool refineUniformBase(SDValue &BasePtr, SDValue &Index, SelectionDAG &DAG) { 9624 if (!isNullConstant(BasePtr) || Index.getOpcode() != ISD::ADD) 9625 return false; 9626 9627 // For now we check only the LHS of the add. 9628 SDValue LHS = Index.getOperand(0); 9629 SDValue SplatVal = DAG.getSplatValue(LHS); 9630 if (!SplatVal) 9631 return false; 9632 9633 BasePtr = SplatVal; 9634 Index = Index.getOperand(1); 9635 return true; 9636 } 9637 9638 // Fold sext/zext of index into index type. 9639 bool refineIndexType(MaskedGatherScatterSDNode *MGS, SDValue &Index, 9640 bool Scaled, SelectionDAG &DAG) { 9641 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9642 9643 if (Index.getOpcode() == ISD::ZERO_EXTEND) { 9644 SDValue Op = Index.getOperand(0); 9645 MGS->setIndexType(Scaled ? ISD::UNSIGNED_SCALED : ISD::UNSIGNED_UNSCALED); 9646 if (TLI.shouldRemoveExtendFromGSIndex(Op.getValueType())) { 9647 Index = Op; 9648 return true; 9649 } 9650 } 9651 9652 if (Index.getOpcode() == ISD::SIGN_EXTEND) { 9653 SDValue Op = Index.getOperand(0); 9654 MGS->setIndexType(Scaled ? ISD::SIGNED_SCALED : ISD::SIGNED_UNSCALED); 9655 if (TLI.shouldRemoveExtendFromGSIndex(Op.getValueType())) { 9656 Index = Op; 9657 return true; 9658 } 9659 } 9660 9661 return false; 9662 } 9663 9664 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 9665 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 9666 SDValue Mask = MSC->getMask(); 9667 SDValue Chain = MSC->getChain(); 9668 SDValue Index = MSC->getIndex(); 9669 SDValue Scale = MSC->getScale(); 9670 SDValue StoreVal = MSC->getValue(); 9671 SDValue BasePtr = MSC->getBasePtr(); 9672 SDLoc DL(N); 9673 9674 // Zap scatters with a zero mask. 9675 if (ISD::isConstantSplatVectorAllZeros(Mask.getNode())) 9676 return Chain; 9677 9678 if (refineUniformBase(BasePtr, Index, DAG)) { 9679 SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, Scale}; 9680 return DAG.getMaskedScatter( 9681 DAG.getVTList(MVT::Other), StoreVal.getValueType(), DL, Ops, 9682 MSC->getMemOperand(), MSC->getIndexType(), MSC->isTruncatingStore()); 9683 } 9684 9685 if (refineIndexType(MSC, Index, MSC->isIndexScaled(), DAG)) { 9686 SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, Scale}; 9687 return DAG.getMaskedScatter( 9688 DAG.getVTList(MVT::Other), StoreVal.getValueType(), DL, Ops, 9689 MSC->getMemOperand(), MSC->getIndexType(), MSC->isTruncatingStore()); 9690 } 9691 9692 return SDValue(); 9693 } 9694 9695 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 9696 MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N); 9697 SDValue Mask = MST->getMask(); 9698 SDValue Chain = MST->getChain(); 9699 SDLoc DL(N); 9700 9701 // Zap masked stores with a zero mask. 9702 if (ISD::isConstantSplatVectorAllZeros(Mask.getNode())) 9703 return Chain; 9704 9705 // If this is a masked load with an all ones mask, we can use a unmasked load. 9706 // FIXME: Can we do this for indexed, compressing, or truncating stores? 9707 if (ISD::isConstantSplatVectorAllOnes(Mask.getNode()) && 9708 MST->isUnindexed() && !MST->isCompressingStore() && 9709 !MST->isTruncatingStore()) 9710 return DAG.getStore(MST->getChain(), SDLoc(N), MST->getValue(), 9711 MST->getBasePtr(), MST->getMemOperand()); 9712 9713 // Try transforming N to an indexed store. 9714 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 9715 return SDValue(N, 0); 9716 9717 return SDValue(); 9718 } 9719 9720 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 9721 MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N); 9722 SDValue Mask = MGT->getMask(); 9723 SDValue Chain = MGT->getChain(); 9724 SDValue Index = MGT->getIndex(); 9725 SDValue Scale = MGT->getScale(); 9726 SDValue PassThru = MGT->getPassThru(); 9727 SDValue BasePtr = MGT->getBasePtr(); 9728 SDLoc DL(N); 9729 9730 // Zap gathers with a zero mask. 9731 if (ISD::isConstantSplatVectorAllZeros(Mask.getNode())) 9732 return CombineTo(N, PassThru, MGT->getChain()); 9733 9734 if (refineUniformBase(BasePtr, Index, DAG)) { 9735 SDValue Ops[] = {Chain, PassThru, Mask, BasePtr, Index, Scale}; 9736 return DAG.getMaskedGather(DAG.getVTList(N->getValueType(0), MVT::Other), 9737 PassThru.getValueType(), DL, Ops, 9738 MGT->getMemOperand(), MGT->getIndexType(), 9739 MGT->getExtensionType()); 9740 } 9741 9742 if (refineIndexType(MGT, Index, MGT->isIndexScaled(), DAG)) { 9743 SDValue Ops[] = {Chain, PassThru, Mask, BasePtr, Index, Scale}; 9744 return DAG.getMaskedGather(DAG.getVTList(N->getValueType(0), MVT::Other), 9745 PassThru.getValueType(), DL, Ops, 9746 MGT->getMemOperand(), MGT->getIndexType(), 9747 MGT->getExtensionType()); 9748 } 9749 9750 return SDValue(); 9751 } 9752 9753 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 9754 MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N); 9755 SDValue Mask = MLD->getMask(); 9756 SDLoc DL(N); 9757 9758 // Zap masked loads with a zero mask. 9759 if (ISD::isConstantSplatVectorAllZeros(Mask.getNode())) 9760 return CombineTo(N, MLD->getPassThru(), MLD->getChain()); 9761 9762 // If this is a masked load with an all ones mask, we can use a unmasked load. 9763 // FIXME: Can we do this for indexed, expanding, or extending loads? 9764 if (ISD::isConstantSplatVectorAllOnes(Mask.getNode()) && 9765 MLD->isUnindexed() && !MLD->isExpandingLoad() && 9766 MLD->getExtensionType() == ISD::NON_EXTLOAD) { 9767 SDValue NewLd = DAG.getLoad(N->getValueType(0), SDLoc(N), MLD->getChain(), 9768 MLD->getBasePtr(), MLD->getMemOperand()); 9769 return CombineTo(N, NewLd, NewLd.getValue(1)); 9770 } 9771 9772 // Try transforming N to an indexed load. 9773 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 9774 return SDValue(N, 0); 9775 9776 return SDValue(); 9777 } 9778 9779 /// A vector select of 2 constant vectors can be simplified to math/logic to 9780 /// avoid a variable select instruction and possibly avoid constant loads. 9781 SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) { 9782 SDValue Cond = N->getOperand(0); 9783 SDValue N1 = N->getOperand(1); 9784 SDValue N2 = N->getOperand(2); 9785 EVT VT = N->getValueType(0); 9786 if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 || 9787 !TLI.convertSelectOfConstantsToMath(VT) || 9788 !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()) || 9789 !ISD::isBuildVectorOfConstantSDNodes(N2.getNode())) 9790 return SDValue(); 9791 9792 // Check if we can use the condition value to increment/decrement a single 9793 // constant value. This simplifies a select to an add and removes a constant 9794 // load/materialization from the general case. 9795 bool AllAddOne = true; 9796 bool AllSubOne = true; 9797 unsigned Elts = VT.getVectorNumElements(); 9798 for (unsigned i = 0; i != Elts; ++i) { 9799 SDValue N1Elt = N1.getOperand(i); 9800 SDValue N2Elt = N2.getOperand(i); 9801 if (N1Elt.isUndef() || N2Elt.isUndef()) 9802 continue; 9803 if (N1Elt.getValueType() != N2Elt.getValueType()) 9804 continue; 9805 9806 const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue(); 9807 const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue(); 9808 if (C1 != C2 + 1) 9809 AllAddOne = false; 9810 if (C1 != C2 - 1) 9811 AllSubOne = false; 9812 } 9813 9814 // Further simplifications for the extra-special cases where the constants are 9815 // all 0 or all -1 should be implemented as folds of these patterns. 9816 SDLoc DL(N); 9817 if (AllAddOne || AllSubOne) { 9818 // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C 9819 // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C 9820 auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND; 9821 SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond); 9822 return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2); 9823 } 9824 9825 // select Cond, Pow2C, 0 --> (zext Cond) << log2(Pow2C) 9826 APInt Pow2C; 9827 if (ISD::isConstantSplatVector(N1.getNode(), Pow2C) && Pow2C.isPowerOf2() && 9828 isNullOrNullSplat(N2)) { 9829 SDValue ZextCond = DAG.getZExtOrTrunc(Cond, DL, VT); 9830 SDValue ShAmtC = DAG.getConstant(Pow2C.exactLogBase2(), DL, VT); 9831 return DAG.getNode(ISD::SHL, DL, VT, ZextCond, ShAmtC); 9832 } 9833 9834 if (SDValue V = foldSelectOfConstantsUsingSra(N, DAG)) 9835 return V; 9836 9837 // The general case for select-of-constants: 9838 // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2 9839 // ...but that only makes sense if a vselect is slower than 2 logic ops, so 9840 // leave that to a machine-specific pass. 9841 return SDValue(); 9842 } 9843 9844 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 9845 SDValue N0 = N->getOperand(0); 9846 SDValue N1 = N->getOperand(1); 9847 SDValue N2 = N->getOperand(2); 9848 EVT VT = N->getValueType(0); 9849 SDLoc DL(N); 9850 9851 if (SDValue V = DAG.simplifySelect(N0, N1, N2)) 9852 return V; 9853 9854 if (SDValue V = foldBoolSelectToLogic(N, DAG)) 9855 return V; 9856 9857 // vselect (not Cond), N1, N2 -> vselect Cond, N2, N1 9858 if (SDValue F = extractBooleanFlip(N0, DAG, TLI, false)) 9859 return DAG.getSelect(DL, VT, F, N2, N1); 9860 9861 // Canonicalize integer abs. 9862 // vselect (setg[te] X, 0), X, -X -> 9863 // vselect (setgt X, -1), X, -X -> 9864 // vselect (setl[te] X, 0), -X, X -> 9865 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 9866 if (N0.getOpcode() == ISD::SETCC) { 9867 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 9868 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 9869 bool isAbs = false; 9870 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 9871 9872 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 9873 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 9874 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 9875 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 9876 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 9877 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 9878 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 9879 9880 if (isAbs) { 9881 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) 9882 return DAG.getNode(ISD::ABS, DL, VT, LHS); 9883 9884 SDValue Shift = DAG.getNode(ISD::SRA, DL, VT, LHS, 9885 DAG.getConstant(VT.getScalarSizeInBits() - 1, 9886 DL, getShiftAmountTy(VT))); 9887 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 9888 AddToWorklist(Shift.getNode()); 9889 AddToWorklist(Add.getNode()); 9890 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 9891 } 9892 9893 // vselect x, y (fcmp lt x, y) -> fminnum x, y 9894 // vselect x, y (fcmp gt x, y) -> fmaxnum x, y 9895 // 9896 // This is OK if we don't care about what happens if either operand is a 9897 // NaN. 9898 // 9899 if (N0.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG, LHS, RHS, TLI)) { 9900 if (SDValue FMinMax = 9901 combineMinNumMaxNum(DL, VT, LHS, RHS, N1, N2, CC, TLI, DAG)) 9902 return FMinMax; 9903 } 9904 9905 // If this select has a condition (setcc) with narrower operands than the 9906 // select, try to widen the compare to match the select width. 9907 // TODO: This should be extended to handle any constant. 9908 // TODO: This could be extended to handle non-loading patterns, but that 9909 // requires thorough testing to avoid regressions. 9910 if (isNullOrNullSplat(RHS)) { 9911 EVT NarrowVT = LHS.getValueType(); 9912 EVT WideVT = N1.getValueType().changeVectorElementTypeToInteger(); 9913 EVT SetCCVT = getSetCCResultType(LHS.getValueType()); 9914 unsigned SetCCWidth = SetCCVT.getScalarSizeInBits(); 9915 unsigned WideWidth = WideVT.getScalarSizeInBits(); 9916 bool IsSigned = isSignedIntSetCC(CC); 9917 auto LoadExtOpcode = IsSigned ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 9918 if (LHS.getOpcode() == ISD::LOAD && LHS.hasOneUse() && 9919 SetCCWidth != 1 && SetCCWidth < WideWidth && 9920 TLI.isLoadExtLegalOrCustom(LoadExtOpcode, WideVT, NarrowVT) && 9921 TLI.isOperationLegalOrCustom(ISD::SETCC, WideVT)) { 9922 // Both compare operands can be widened for free. The LHS can use an 9923 // extended load, and the RHS is a constant: 9924 // vselect (ext (setcc load(X), C)), N1, N2 --> 9925 // vselect (setcc extload(X), C'), N1, N2 9926 auto ExtOpcode = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9927 SDValue WideLHS = DAG.getNode(ExtOpcode, DL, WideVT, LHS); 9928 SDValue WideRHS = DAG.getNode(ExtOpcode, DL, WideVT, RHS); 9929 EVT WideSetCCVT = getSetCCResultType(WideVT); 9930 SDValue WideSetCC = DAG.getSetCC(DL, WideSetCCVT, WideLHS, WideRHS, CC); 9931 return DAG.getSelect(DL, N1.getValueType(), WideSetCC, N1, N2); 9932 } 9933 } 9934 9935 // Match VSELECTs into add with unsigned saturation. 9936 if (hasOperation(ISD::UADDSAT, VT)) { 9937 // Check if one of the arms of the VSELECT is vector with all bits set. 9938 // If it's on the left side invert the predicate to simplify logic below. 9939 SDValue Other; 9940 ISD::CondCode SatCC = CC; 9941 if (ISD::isBuildVectorAllOnes(N1.getNode())) { 9942 Other = N2; 9943 SatCC = ISD::getSetCCInverse(SatCC, VT.getScalarType()); 9944 } else if (ISD::isBuildVectorAllOnes(N2.getNode())) { 9945 Other = N1; 9946 } 9947 9948 if (Other && Other.getOpcode() == ISD::ADD) { 9949 SDValue CondLHS = LHS, CondRHS = RHS; 9950 SDValue OpLHS = Other.getOperand(0), OpRHS = Other.getOperand(1); 9951 9952 // Canonicalize condition operands. 9953 if (SatCC == ISD::SETUGE) { 9954 std::swap(CondLHS, CondRHS); 9955 SatCC = ISD::SETULE; 9956 } 9957 9958 // We can test against either of the addition operands. 9959 // x <= x+y ? x+y : ~0 --> uaddsat x, y 9960 // x+y >= x ? x+y : ~0 --> uaddsat x, y 9961 if (SatCC == ISD::SETULE && Other == CondRHS && 9962 (OpLHS == CondLHS || OpRHS == CondLHS)) 9963 return DAG.getNode(ISD::UADDSAT, DL, VT, OpLHS, OpRHS); 9964 9965 if (isa<BuildVectorSDNode>(OpRHS) && isa<BuildVectorSDNode>(CondRHS) && 9966 CondLHS == OpLHS) { 9967 // If the RHS is a constant we have to reverse the const 9968 // canonicalization. 9969 // x >= ~C ? x+C : ~0 --> uaddsat x, C 9970 auto MatchUADDSAT = [](ConstantSDNode *Op, ConstantSDNode *Cond) { 9971 return Cond->getAPIntValue() == ~Op->getAPIntValue(); 9972 }; 9973 if (SatCC == ISD::SETULE && 9974 ISD::matchBinaryPredicate(OpRHS, CondRHS, MatchUADDSAT)) 9975 return DAG.getNode(ISD::UADDSAT, DL, VT, OpLHS, OpRHS); 9976 } 9977 } 9978 } 9979 9980 // Match VSELECTs into sub with unsigned saturation. 9981 if (hasOperation(ISD::USUBSAT, VT)) { 9982 // Check if one of the arms of the VSELECT is a zero vector. If it's on 9983 // the left side invert the predicate to simplify logic below. 9984 SDValue Other; 9985 ISD::CondCode SatCC = CC; 9986 if (ISD::isBuildVectorAllZeros(N1.getNode())) { 9987 Other = N2; 9988 SatCC = ISD::getSetCCInverse(SatCC, VT.getScalarType()); 9989 } else if (ISD::isBuildVectorAllZeros(N2.getNode())) { 9990 Other = N1; 9991 } 9992 9993 if (Other && Other.getNumOperands() == 2) { 9994 SDValue CondRHS = RHS; 9995 SDValue OpLHS = Other.getOperand(0), OpRHS = Other.getOperand(1); 9996 9997 if (Other.getOpcode() == ISD::SUB && 9998 LHS.getOpcode() == ISD::ZERO_EXTEND && LHS.getOperand(0) == OpLHS && 9999 OpRHS.getOpcode() == ISD::TRUNCATE && OpRHS.getOperand(0) == RHS) { 10000 // Look for a general sub with unsigned saturation first. 10001 // zext(x) >= y ? x - trunc(y) : 0 10002 // --> usubsat(x,trunc(umin(y,SatLimit))) 10003 // zext(x) > y ? x - trunc(y) : 0 10004 // --> usubsat(x,trunc(umin(y,SatLimit))) 10005 if (SatCC == ISD::SETUGE || SatCC == ISD::SETUGT) 10006 return getTruncatedUSUBSAT(VT, LHS.getValueType(), LHS, RHS, DAG, 10007 DL); 10008 } 10009 10010 if (OpLHS == LHS) { 10011 // Look for a general sub with unsigned saturation first. 10012 // x >= y ? x-y : 0 --> usubsat x, y 10013 // x > y ? x-y : 0 --> usubsat x, y 10014 if ((SatCC == ISD::SETUGE || SatCC == ISD::SETUGT) && 10015 Other.getOpcode() == ISD::SUB && OpRHS == CondRHS) 10016 return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS); 10017 10018 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS)) { 10019 if (isa<BuildVectorSDNode>(CondRHS)) { 10020 // If the RHS is a constant we have to reverse the const 10021 // canonicalization. 10022 // x > C-1 ? x+-C : 0 --> usubsat x, C 10023 auto MatchUSUBSAT = [](ConstantSDNode *Op, ConstantSDNode *Cond) { 10024 return (!Op && !Cond) || 10025 (Op && Cond && 10026 Cond->getAPIntValue() == (-Op->getAPIntValue() - 1)); 10027 }; 10028 if (SatCC == ISD::SETUGT && Other.getOpcode() == ISD::ADD && 10029 ISD::matchBinaryPredicate(OpRHS, CondRHS, MatchUSUBSAT, 10030 /*AllowUndefs*/ true)) { 10031 OpRHS = DAG.getNode(ISD::SUB, DL, VT, 10032 DAG.getConstant(0, DL, VT), OpRHS); 10033 return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS); 10034 } 10035 10036 // Another special case: If C was a sign bit, the sub has been 10037 // canonicalized into a xor. 10038 // FIXME: Would it be better to use computeKnownBits to determine 10039 // whether it's safe to decanonicalize the xor? 10040 // x s< 0 ? x^C : 0 --> usubsat x, C 10041 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) { 10042 if (SatCC == ISD::SETLT && Other.getOpcode() == ISD::XOR && 10043 ISD::isBuildVectorAllZeros(CondRHS.getNode()) && 10044 OpRHSConst->getAPIntValue().isSignMask()) { 10045 // Note that we have to rebuild the RHS constant here to 10046 // ensure we don't rely on particular values of undef lanes. 10047 OpRHS = DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT); 10048 return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS); 10049 } 10050 } 10051 } 10052 } 10053 } 10054 } 10055 } 10056 } 10057 10058 if (SimplifySelectOps(N, N1, N2)) 10059 return SDValue(N, 0); // Don't revisit N. 10060 10061 // Fold (vselect all_ones, N1, N2) -> N1 10062 if (ISD::isConstantSplatVectorAllOnes(N0.getNode())) 10063 return N1; 10064 // Fold (vselect all_zeros, N1, N2) -> N2 10065 if (ISD::isConstantSplatVectorAllZeros(N0.getNode())) 10066 return N2; 10067 10068 // The ConvertSelectToConcatVector function is assuming both the above 10069 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 10070 // and addressed. 10071 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 10072 N2.getOpcode() == ISD::CONCAT_VECTORS && 10073 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 10074 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 10075 return CV; 10076 } 10077 10078 if (SDValue V = foldVSelectOfConstants(N)) 10079 return V; 10080 10081 return SDValue(); 10082 } 10083 10084 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 10085 SDValue N0 = N->getOperand(0); 10086 SDValue N1 = N->getOperand(1); 10087 SDValue N2 = N->getOperand(2); 10088 SDValue N3 = N->getOperand(3); 10089 SDValue N4 = N->getOperand(4); 10090 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 10091 10092 // fold select_cc lhs, rhs, x, x, cc -> x 10093 if (N2 == N3) 10094 return N2; 10095 10096 // Determine if the condition we're dealing with is constant 10097 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 10098 CC, SDLoc(N), false)) { 10099 AddToWorklist(SCC.getNode()); 10100 10101 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 10102 if (!SCCC->isNullValue()) 10103 return N2; // cond always true -> true val 10104 else 10105 return N3; // cond always false -> false val 10106 } else if (SCC->isUndef()) { 10107 // When the condition is UNDEF, just return the first operand. This is 10108 // coherent the DAG creation, no setcc node is created in this case 10109 return N2; 10110 } else if (SCC.getOpcode() == ISD::SETCC) { 10111 // Fold to a simpler select_cc 10112 SDValue SelectOp = DAG.getNode( 10113 ISD::SELECT_CC, SDLoc(N), N2.getValueType(), SCC.getOperand(0), 10114 SCC.getOperand(1), N2, N3, SCC.getOperand(2)); 10115 SelectOp->setFlags(SCC->getFlags()); 10116 return SelectOp; 10117 } 10118 } 10119 10120 // If we can fold this based on the true/false value, do so. 10121 if (SimplifySelectOps(N, N2, N3)) 10122 return SDValue(N, 0); // Don't revisit N. 10123 10124 // fold select_cc into other things, such as min/max/abs 10125 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 10126 } 10127 10128 SDValue DAGCombiner::visitSETCC(SDNode *N) { 10129 // setcc is very commonly used as an argument to brcond. This pattern 10130 // also lend itself to numerous combines and, as a result, it is desired 10131 // we keep the argument to a brcond as a setcc as much as possible. 10132 bool PreferSetCC = 10133 N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BRCOND; 10134 10135 SDValue Combined = SimplifySetCC( 10136 N->getValueType(0), N->getOperand(0), N->getOperand(1), 10137 cast<CondCodeSDNode>(N->getOperand(2))->get(), SDLoc(N), !PreferSetCC); 10138 10139 if (!Combined) 10140 return SDValue(); 10141 10142 // If we prefer to have a setcc, and we don't, we'll try our best to 10143 // recreate one using rebuildSetCC. 10144 if (PreferSetCC && Combined.getOpcode() != ISD::SETCC) { 10145 SDValue NewSetCC = rebuildSetCC(Combined); 10146 10147 // We don't have anything interesting to combine to. 10148 if (NewSetCC.getNode() == N) 10149 return SDValue(); 10150 10151 if (NewSetCC) 10152 return NewSetCC; 10153 } 10154 10155 return Combined; 10156 } 10157 10158 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) { 10159 SDValue LHS = N->getOperand(0); 10160 SDValue RHS = N->getOperand(1); 10161 SDValue Carry = N->getOperand(2); 10162 SDValue Cond = N->getOperand(3); 10163 10164 // If Carry is false, fold to a regular SETCC. 10165 if (isNullConstant(Carry)) 10166 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 10167 10168 return SDValue(); 10169 } 10170 10171 /// Check if N satisfies: 10172 /// N is used once. 10173 /// N is a Load. 10174 /// The load is compatible with ExtOpcode. It means 10175 /// If load has explicit zero/sign extension, ExpOpcode must have the same 10176 /// extension. 10177 /// Otherwise returns true. 10178 static bool isCompatibleLoad(SDValue N, unsigned ExtOpcode) { 10179 if (!N.hasOneUse()) 10180 return false; 10181 10182 if (!isa<LoadSDNode>(N)) 10183 return false; 10184 10185 LoadSDNode *Load = cast<LoadSDNode>(N); 10186 ISD::LoadExtType LoadExt = Load->getExtensionType(); 10187 if (LoadExt == ISD::NON_EXTLOAD || LoadExt == ISD::EXTLOAD) 10188 return true; 10189 10190 // Now LoadExt is either SEXTLOAD or ZEXTLOAD, ExtOpcode must have the same 10191 // extension. 10192 if ((LoadExt == ISD::SEXTLOAD && ExtOpcode != ISD::SIGN_EXTEND) || 10193 (LoadExt == ISD::ZEXTLOAD && ExtOpcode != ISD::ZERO_EXTEND)) 10194 return false; 10195 10196 return true; 10197 } 10198 10199 /// Fold 10200 /// (sext (select c, load x, load y)) -> (select c, sextload x, sextload y) 10201 /// (zext (select c, load x, load y)) -> (select c, zextload x, zextload y) 10202 /// (aext (select c, load x, load y)) -> (select c, extload x, extload y) 10203 /// This function is called by the DAGCombiner when visiting sext/zext/aext 10204 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 10205 static SDValue tryToFoldExtendSelectLoad(SDNode *N, const TargetLowering &TLI, 10206 SelectionDAG &DAG) { 10207 unsigned Opcode = N->getOpcode(); 10208 SDValue N0 = N->getOperand(0); 10209 EVT VT = N->getValueType(0); 10210 SDLoc DL(N); 10211 10212 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 10213 Opcode == ISD::ANY_EXTEND) && 10214 "Expected EXTEND dag node in input!"); 10215 10216 if (!(N0->getOpcode() == ISD::SELECT || N0->getOpcode() == ISD::VSELECT) || 10217 !N0.hasOneUse()) 10218 return SDValue(); 10219 10220 SDValue Op1 = N0->getOperand(1); 10221 SDValue Op2 = N0->getOperand(2); 10222 if (!isCompatibleLoad(Op1, Opcode) || !isCompatibleLoad(Op2, Opcode)) 10223 return SDValue(); 10224 10225 auto ExtLoadOpcode = ISD::EXTLOAD; 10226 if (Opcode == ISD::SIGN_EXTEND) 10227 ExtLoadOpcode = ISD::SEXTLOAD; 10228 else if (Opcode == ISD::ZERO_EXTEND) 10229 ExtLoadOpcode = ISD::ZEXTLOAD; 10230 10231 LoadSDNode *Load1 = cast<LoadSDNode>(Op1); 10232 LoadSDNode *Load2 = cast<LoadSDNode>(Op2); 10233 if (!TLI.isLoadExtLegal(ExtLoadOpcode, VT, Load1->getMemoryVT()) || 10234 !TLI.isLoadExtLegal(ExtLoadOpcode, VT, Load2->getMemoryVT())) 10235 return SDValue(); 10236 10237 SDValue Ext1 = DAG.getNode(Opcode, DL, VT, Op1); 10238 SDValue Ext2 = DAG.getNode(Opcode, DL, VT, Op2); 10239 return DAG.getSelect(DL, VT, N0->getOperand(0), Ext1, Ext2); 10240 } 10241 10242 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 10243 /// a build_vector of constants. 10244 /// This function is called by the DAGCombiner when visiting sext/zext/aext 10245 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 10246 /// Vector extends are not folded if operations are legal; this is to 10247 /// avoid introducing illegal build_vector dag nodes. 10248 static SDValue tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 10249 SelectionDAG &DAG, bool LegalTypes) { 10250 unsigned Opcode = N->getOpcode(); 10251 SDValue N0 = N->getOperand(0); 10252 EVT VT = N->getValueType(0); 10253 SDLoc DL(N); 10254 10255 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 10256 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 10257 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 10258 && "Expected EXTEND dag node in input!"); 10259 10260 // fold (sext c1) -> c1 10261 // fold (zext c1) -> c1 10262 // fold (aext c1) -> c1 10263 if (isa<ConstantSDNode>(N0)) 10264 return DAG.getNode(Opcode, DL, VT, N0); 10265 10266 // fold (sext (select cond, c1, c2)) -> (select cond, sext c1, sext c2) 10267 // fold (zext (select cond, c1, c2)) -> (select cond, zext c1, zext c2) 10268 // fold (aext (select cond, c1, c2)) -> (select cond, sext c1, sext c2) 10269 if (N0->getOpcode() == ISD::SELECT) { 10270 SDValue Op1 = N0->getOperand(1); 10271 SDValue Op2 = N0->getOperand(2); 10272 if (isa<ConstantSDNode>(Op1) && isa<ConstantSDNode>(Op2) && 10273 (Opcode != ISD::ZERO_EXTEND || !TLI.isZExtFree(N0.getValueType(), VT))) { 10274 // For any_extend, choose sign extension of the constants to allow a 10275 // possible further transform to sign_extend_inreg.i.e. 10276 // 10277 // t1: i8 = select t0, Constant:i8<-1>, Constant:i8<0> 10278 // t2: i64 = any_extend t1 10279 // --> 10280 // t3: i64 = select t0, Constant:i64<-1>, Constant:i64<0> 10281 // --> 10282 // t4: i64 = sign_extend_inreg t3 10283 unsigned FoldOpc = Opcode; 10284 if (FoldOpc == ISD::ANY_EXTEND) 10285 FoldOpc = ISD::SIGN_EXTEND; 10286 return DAG.getSelect(DL, VT, N0->getOperand(0), 10287 DAG.getNode(FoldOpc, DL, VT, Op1), 10288 DAG.getNode(FoldOpc, DL, VT, Op2)); 10289 } 10290 } 10291 10292 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 10293 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 10294 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 10295 EVT SVT = VT.getScalarType(); 10296 if (!(VT.isVector() && (!LegalTypes || TLI.isTypeLegal(SVT)) && 10297 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 10298 return SDValue(); 10299 10300 // We can fold this node into a build_vector. 10301 unsigned VTBits = SVT.getSizeInBits(); 10302 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits(); 10303 SmallVector<SDValue, 8> Elts; 10304 unsigned NumElts = VT.getVectorNumElements(); 10305 10306 // For zero-extensions, UNDEF elements still guarantee to have the upper 10307 // bits set to zero. 10308 bool IsZext = 10309 Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ZERO_EXTEND_VECTOR_INREG; 10310 10311 for (unsigned i = 0; i != NumElts; ++i) { 10312 SDValue Op = N0.getOperand(i); 10313 if (Op.isUndef()) { 10314 Elts.push_back(IsZext ? DAG.getConstant(0, DL, SVT) : DAG.getUNDEF(SVT)); 10315 continue; 10316 } 10317 10318 SDLoc DL(Op); 10319 // Get the constant value and if needed trunc it to the size of the type. 10320 // Nodes like build_vector might have constants wider than the scalar type. 10321 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 10322 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 10323 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 10324 else 10325 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 10326 } 10327 10328 return DAG.getBuildVector(VT, DL, Elts); 10329 } 10330 10331 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 10332 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 10333 // transformation. Returns true if extension are possible and the above 10334 // mentioned transformation is profitable. 10335 static bool ExtendUsesToFormExtLoad(EVT VT, SDNode *N, SDValue N0, 10336 unsigned ExtOpc, 10337 SmallVectorImpl<SDNode *> &ExtendNodes, 10338 const TargetLowering &TLI) { 10339 bool HasCopyToRegUses = false; 10340 bool isTruncFree = TLI.isTruncateFree(VT, N0.getValueType()); 10341 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 10342 UE = N0.getNode()->use_end(); 10343 UI != UE; ++UI) { 10344 SDNode *User = *UI; 10345 if (User == N) 10346 continue; 10347 if (UI.getUse().getResNo() != N0.getResNo()) 10348 continue; 10349 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 10350 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 10351 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 10352 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 10353 // Sign bits will be lost after a zext. 10354 return false; 10355 bool Add = false; 10356 for (unsigned i = 0; i != 2; ++i) { 10357 SDValue UseOp = User->getOperand(i); 10358 if (UseOp == N0) 10359 continue; 10360 if (!isa<ConstantSDNode>(UseOp)) 10361 return false; 10362 Add = true; 10363 } 10364 if (Add) 10365 ExtendNodes.push_back(User); 10366 continue; 10367 } 10368 // If truncates aren't free and there are users we can't 10369 // extend, it isn't worthwhile. 10370 if (!isTruncFree) 10371 return false; 10372 // Remember if this value is live-out. 10373 if (User->getOpcode() == ISD::CopyToReg) 10374 HasCopyToRegUses = true; 10375 } 10376 10377 if (HasCopyToRegUses) { 10378 bool BothLiveOut = false; 10379 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 10380 UI != UE; ++UI) { 10381 SDUse &Use = UI.getUse(); 10382 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 10383 BothLiveOut = true; 10384 break; 10385 } 10386 } 10387 if (BothLiveOut) 10388 // Both unextended and extended values are live out. There had better be 10389 // a good reason for the transformation. 10390 return ExtendNodes.size(); 10391 } 10392 return true; 10393 } 10394 10395 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 10396 SDValue OrigLoad, SDValue ExtLoad, 10397 ISD::NodeType ExtType) { 10398 // Extend SetCC uses if necessary. 10399 SDLoc DL(ExtLoad); 10400 for (SDNode *SetCC : SetCCs) { 10401 SmallVector<SDValue, 4> Ops; 10402 10403 for (unsigned j = 0; j != 2; ++j) { 10404 SDValue SOp = SetCC->getOperand(j); 10405 if (SOp == OrigLoad) 10406 Ops.push_back(ExtLoad); 10407 else 10408 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 10409 } 10410 10411 Ops.push_back(SetCC->getOperand(2)); 10412 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 10413 } 10414 } 10415 10416 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 10417 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 10418 SDValue N0 = N->getOperand(0); 10419 EVT DstVT = N->getValueType(0); 10420 EVT SrcVT = N0.getValueType(); 10421 10422 assert((N->getOpcode() == ISD::SIGN_EXTEND || 10423 N->getOpcode() == ISD::ZERO_EXTEND) && 10424 "Unexpected node type (not an extend)!"); 10425 10426 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 10427 // For example, on a target with legal v4i32, but illegal v8i32, turn: 10428 // (v8i32 (sext (v8i16 (load x)))) 10429 // into: 10430 // (v8i32 (concat_vectors (v4i32 (sextload x)), 10431 // (v4i32 (sextload (x + 16))))) 10432 // Where uses of the original load, i.e.: 10433 // (v8i16 (load x)) 10434 // are replaced with: 10435 // (v8i16 (truncate 10436 // (v8i32 (concat_vectors (v4i32 (sextload x)), 10437 // (v4i32 (sextload (x + 16))))))) 10438 // 10439 // This combine is only applicable to illegal, but splittable, vectors. 10440 // All legal types, and illegal non-vector types, are handled elsewhere. 10441 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 10442 // 10443 if (N0->getOpcode() != ISD::LOAD) 10444 return SDValue(); 10445 10446 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 10447 10448 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 10449 !N0.hasOneUse() || !LN0->isSimple() || 10450 !DstVT.isVector() || !DstVT.isPow2VectorType() || 10451 !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 10452 return SDValue(); 10453 10454 SmallVector<SDNode *, 4> SetCCs; 10455 if (!ExtendUsesToFormExtLoad(DstVT, N, N0, N->getOpcode(), SetCCs, TLI)) 10456 return SDValue(); 10457 10458 ISD::LoadExtType ExtType = 10459 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 10460 10461 // Try to split the vector types to get down to legal types. 10462 EVT SplitSrcVT = SrcVT; 10463 EVT SplitDstVT = DstVT; 10464 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 10465 SplitSrcVT.getVectorNumElements() > 1) { 10466 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 10467 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 10468 } 10469 10470 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 10471 return SDValue(); 10472 10473 assert(!DstVT.isScalableVector() && "Unexpected scalable vector type"); 10474 10475 SDLoc DL(N); 10476 const unsigned NumSplits = 10477 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 10478 const unsigned Stride = SplitSrcVT.getStoreSize(); 10479 SmallVector<SDValue, 4> Loads; 10480 SmallVector<SDValue, 4> Chains; 10481 10482 SDValue BasePtr = LN0->getBasePtr(); 10483 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 10484 const unsigned Offset = Idx * Stride; 10485 const Align Align = commonAlignment(LN0->getAlign(), Offset); 10486 10487 SDValue SplitLoad = DAG.getExtLoad( 10488 ExtType, SDLoc(LN0), SplitDstVT, LN0->getChain(), BasePtr, 10489 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align, 10490 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 10491 10492 BasePtr = DAG.getMemBasePlusOffset(BasePtr, TypeSize::Fixed(Stride), DL); 10493 10494 Loads.push_back(SplitLoad.getValue(0)); 10495 Chains.push_back(SplitLoad.getValue(1)); 10496 } 10497 10498 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 10499 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 10500 10501 // Simplify TF. 10502 AddToWorklist(NewChain.getNode()); 10503 10504 CombineTo(N, NewValue); 10505 10506 // Replace uses of the original load (before extension) 10507 // with a truncate of the concatenated sextloaded vectors. 10508 SDValue Trunc = 10509 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 10510 ExtendSetCCUses(SetCCs, N0, NewValue, (ISD::NodeType)N->getOpcode()); 10511 CombineTo(N0.getNode(), Trunc, NewChain); 10512 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10513 } 10514 10515 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) -> 10516 // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst)) 10517 SDValue DAGCombiner::CombineZExtLogicopShiftLoad(SDNode *N) { 10518 assert(N->getOpcode() == ISD::ZERO_EXTEND); 10519 EVT VT = N->getValueType(0); 10520 EVT OrigVT = N->getOperand(0).getValueType(); 10521 if (TLI.isZExtFree(OrigVT, VT)) 10522 return SDValue(); 10523 10524 // and/or/xor 10525 SDValue N0 = N->getOperand(0); 10526 if (!(N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 10527 N0.getOpcode() == ISD::XOR) || 10528 N0.getOperand(1).getOpcode() != ISD::Constant || 10529 (LegalOperations && !TLI.isOperationLegal(N0.getOpcode(), VT))) 10530 return SDValue(); 10531 10532 // shl/shr 10533 SDValue N1 = N0->getOperand(0); 10534 if (!(N1.getOpcode() == ISD::SHL || N1.getOpcode() == ISD::SRL) || 10535 N1.getOperand(1).getOpcode() != ISD::Constant || 10536 (LegalOperations && !TLI.isOperationLegal(N1.getOpcode(), VT))) 10537 return SDValue(); 10538 10539 // load 10540 if (!isa<LoadSDNode>(N1.getOperand(0))) 10541 return SDValue(); 10542 LoadSDNode *Load = cast<LoadSDNode>(N1.getOperand(0)); 10543 EVT MemVT = Load->getMemoryVT(); 10544 if (!TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) || 10545 Load->getExtensionType() == ISD::SEXTLOAD || Load->isIndexed()) 10546 return SDValue(); 10547 10548 10549 // If the shift op is SHL, the logic op must be AND, otherwise the result 10550 // will be wrong. 10551 if (N1.getOpcode() == ISD::SHL && N0.getOpcode() != ISD::AND) 10552 return SDValue(); 10553 10554 if (!N0.hasOneUse() || !N1.hasOneUse()) 10555 return SDValue(); 10556 10557 SmallVector<SDNode*, 4> SetCCs; 10558 if (!ExtendUsesToFormExtLoad(VT, N1.getNode(), N1.getOperand(0), 10559 ISD::ZERO_EXTEND, SetCCs, TLI)) 10560 return SDValue(); 10561 10562 // Actually do the transformation. 10563 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(Load), VT, 10564 Load->getChain(), Load->getBasePtr(), 10565 Load->getMemoryVT(), Load->getMemOperand()); 10566 10567 SDLoc DL1(N1); 10568 SDValue Shift = DAG.getNode(N1.getOpcode(), DL1, VT, ExtLoad, 10569 N1.getOperand(1)); 10570 10571 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits()); 10572 SDLoc DL0(N0); 10573 SDValue And = DAG.getNode(N0.getOpcode(), DL0, VT, Shift, 10574 DAG.getConstant(Mask, DL0, VT)); 10575 10576 ExtendSetCCUses(SetCCs, N1.getOperand(0), ExtLoad, ISD::ZERO_EXTEND); 10577 CombineTo(N, And); 10578 if (SDValue(Load, 0).hasOneUse()) { 10579 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), ExtLoad.getValue(1)); 10580 } else { 10581 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(Load), 10582 Load->getValueType(0), ExtLoad); 10583 CombineTo(Load, Trunc, ExtLoad.getValue(1)); 10584 } 10585 10586 // N0 is dead at this point. 10587 recursivelyDeleteUnusedNodes(N0.getNode()); 10588 10589 return SDValue(N,0); // Return N so it doesn't get rechecked! 10590 } 10591 10592 /// If we're narrowing or widening the result of a vector select and the final 10593 /// size is the same size as a setcc (compare) feeding the select, then try to 10594 /// apply the cast operation to the select's operands because matching vector 10595 /// sizes for a select condition and other operands should be more efficient. 10596 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) { 10597 unsigned CastOpcode = Cast->getOpcode(); 10598 assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || 10599 CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || 10600 CastOpcode == ISD::FP_ROUND) && 10601 "Unexpected opcode for vector select narrowing/widening"); 10602 10603 // We only do this transform before legal ops because the pattern may be 10604 // obfuscated by target-specific operations after legalization. Do not create 10605 // an illegal select op, however, because that may be difficult to lower. 10606 EVT VT = Cast->getValueType(0); 10607 if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT)) 10608 return SDValue(); 10609 10610 SDValue VSel = Cast->getOperand(0); 10611 if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() || 10612 VSel.getOperand(0).getOpcode() != ISD::SETCC) 10613 return SDValue(); 10614 10615 // Does the setcc have the same vector size as the casted select? 10616 SDValue SetCC = VSel.getOperand(0); 10617 EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType()); 10618 if (SetCCVT.getSizeInBits() != VT.getSizeInBits()) 10619 return SDValue(); 10620 10621 // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B) 10622 SDValue A = VSel.getOperand(1); 10623 SDValue B = VSel.getOperand(2); 10624 SDValue CastA, CastB; 10625 SDLoc DL(Cast); 10626 if (CastOpcode == ISD::FP_ROUND) { 10627 // FP_ROUND (fptrunc) has an extra flag operand to pass along. 10628 CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1)); 10629 CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1)); 10630 } else { 10631 CastA = DAG.getNode(CastOpcode, DL, VT, A); 10632 CastB = DAG.getNode(CastOpcode, DL, VT, B); 10633 } 10634 return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB); 10635 } 10636 10637 // fold ([s|z]ext ([s|z]extload x)) -> ([s|z]ext (truncate ([s|z]extload x))) 10638 // fold ([s|z]ext ( extload x)) -> ([s|z]ext (truncate ([s|z]extload x))) 10639 static SDValue tryToFoldExtOfExtload(SelectionDAG &DAG, DAGCombiner &Combiner, 10640 const TargetLowering &TLI, EVT VT, 10641 bool LegalOperations, SDNode *N, 10642 SDValue N0, ISD::LoadExtType ExtLoadType) { 10643 SDNode *N0Node = N0.getNode(); 10644 bool isAExtLoad = (ExtLoadType == ISD::SEXTLOAD) ? ISD::isSEXTLoad(N0Node) 10645 : ISD::isZEXTLoad(N0Node); 10646 if ((!isAExtLoad && !ISD::isEXTLoad(N0Node)) || 10647 !ISD::isUNINDEXEDLoad(N0Node) || !N0.hasOneUse()) 10648 return SDValue(); 10649 10650 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 10651 EVT MemVT = LN0->getMemoryVT(); 10652 if ((LegalOperations || !LN0->isSimple() || 10653 VT.isVector()) && 10654 !TLI.isLoadExtLegal(ExtLoadType, VT, MemVT)) 10655 return SDValue(); 10656 10657 SDValue ExtLoad = 10658 DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(), 10659 LN0->getBasePtr(), MemVT, LN0->getMemOperand()); 10660 Combiner.CombineTo(N, ExtLoad); 10661 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 10662 if (LN0->use_empty()) 10663 Combiner.recursivelyDeleteUnusedNodes(LN0); 10664 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10665 } 10666 10667 // fold ([s|z]ext (load x)) -> ([s|z]ext (truncate ([s|z]extload x))) 10668 // Only generate vector extloads when 1) they're legal, and 2) they are 10669 // deemed desirable by the target. 10670 static SDValue tryToFoldExtOfLoad(SelectionDAG &DAG, DAGCombiner &Combiner, 10671 const TargetLowering &TLI, EVT VT, 10672 bool LegalOperations, SDNode *N, SDValue N0, 10673 ISD::LoadExtType ExtLoadType, 10674 ISD::NodeType ExtOpc) { 10675 if (!ISD::isNON_EXTLoad(N0.getNode()) || 10676 !ISD::isUNINDEXEDLoad(N0.getNode()) || 10677 ((LegalOperations || VT.isVector() || 10678 !cast<LoadSDNode>(N0)->isSimple()) && 10679 !TLI.isLoadExtLegal(ExtLoadType, VT, N0.getValueType()))) 10680 return {}; 10681 10682 bool DoXform = true; 10683 SmallVector<SDNode *, 4> SetCCs; 10684 if (!N0.hasOneUse()) 10685 DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ExtOpc, SetCCs, TLI); 10686 if (VT.isVector()) 10687 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 10688 if (!DoXform) 10689 return {}; 10690 10691 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 10692 SDValue ExtLoad = DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(), 10693 LN0->getBasePtr(), N0.getValueType(), 10694 LN0->getMemOperand()); 10695 Combiner.ExtendSetCCUses(SetCCs, N0, ExtLoad, ExtOpc); 10696 // If the load value is used only by N, replace it via CombineTo N. 10697 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); 10698 Combiner.CombineTo(N, ExtLoad); 10699 if (NoReplaceTrunc) { 10700 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 10701 Combiner.recursivelyDeleteUnusedNodes(LN0); 10702 } else { 10703 SDValue Trunc = 10704 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), ExtLoad); 10705 Combiner.CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 10706 } 10707 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10708 } 10709 10710 static SDValue tryToFoldExtOfMaskedLoad(SelectionDAG &DAG, 10711 const TargetLowering &TLI, EVT VT, 10712 SDNode *N, SDValue N0, 10713 ISD::LoadExtType ExtLoadType, 10714 ISD::NodeType ExtOpc) { 10715 if (!N0.hasOneUse()) 10716 return SDValue(); 10717 10718 MaskedLoadSDNode *Ld = dyn_cast<MaskedLoadSDNode>(N0); 10719 if (!Ld || Ld->getExtensionType() != ISD::NON_EXTLOAD) 10720 return SDValue(); 10721 10722 if (!TLI.isLoadExtLegal(ExtLoadType, VT, Ld->getValueType(0))) 10723 return SDValue(); 10724 10725 if (!TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 10726 return SDValue(); 10727 10728 SDLoc dl(Ld); 10729 SDValue PassThru = DAG.getNode(ExtOpc, dl, VT, Ld->getPassThru()); 10730 SDValue NewLoad = DAG.getMaskedLoad( 10731 VT, dl, Ld->getChain(), Ld->getBasePtr(), Ld->getOffset(), Ld->getMask(), 10732 PassThru, Ld->getMemoryVT(), Ld->getMemOperand(), Ld->getAddressingMode(), 10733 ExtLoadType, Ld->isExpandingLoad()); 10734 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), SDValue(NewLoad.getNode(), 1)); 10735 return NewLoad; 10736 } 10737 10738 static SDValue foldExtendedSignBitTest(SDNode *N, SelectionDAG &DAG, 10739 bool LegalOperations) { 10740 assert((N->getOpcode() == ISD::SIGN_EXTEND || 10741 N->getOpcode() == ISD::ZERO_EXTEND) && "Expected sext or zext"); 10742 10743 SDValue SetCC = N->getOperand(0); 10744 if (LegalOperations || SetCC.getOpcode() != ISD::SETCC || 10745 !SetCC.hasOneUse() || SetCC.getValueType() != MVT::i1) 10746 return SDValue(); 10747 10748 SDValue X = SetCC.getOperand(0); 10749 SDValue Ones = SetCC.getOperand(1); 10750 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get(); 10751 EVT VT = N->getValueType(0); 10752 EVT XVT = X.getValueType(); 10753 // setge X, C is canonicalized to setgt, so we do not need to match that 10754 // pattern. The setlt sibling is folded in SimplifySelectCC() because it does 10755 // not require the 'not' op. 10756 if (CC == ISD::SETGT && isAllOnesConstant(Ones) && VT == XVT) { 10757 // Invert and smear/shift the sign bit: 10758 // sext i1 (setgt iN X, -1) --> sra (not X), (N - 1) 10759 // zext i1 (setgt iN X, -1) --> srl (not X), (N - 1) 10760 SDLoc DL(N); 10761 unsigned ShCt = VT.getSizeInBits() - 1; 10762 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10763 if (!TLI.shouldAvoidTransformToShift(VT, ShCt)) { 10764 SDValue NotX = DAG.getNOT(DL, X, VT); 10765 SDValue ShiftAmount = DAG.getConstant(ShCt, DL, VT); 10766 auto ShiftOpcode = 10767 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SRA : ISD::SRL; 10768 return DAG.getNode(ShiftOpcode, DL, VT, NotX, ShiftAmount); 10769 } 10770 } 10771 return SDValue(); 10772 } 10773 10774 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 10775 SDValue N0 = N->getOperand(0); 10776 EVT VT = N->getValueType(0); 10777 SDLoc DL(N); 10778 10779 if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes)) 10780 return Res; 10781 10782 // fold (sext (sext x)) -> (sext x) 10783 // fold (sext (aext x)) -> (sext x) 10784 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 10785 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0)); 10786 10787 if (N0.getOpcode() == ISD::TRUNCATE) { 10788 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 10789 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 10790 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 10791 SDNode *oye = N0.getOperand(0).getNode(); 10792 if (NarrowLoad.getNode() != N0.getNode()) { 10793 CombineTo(N0.getNode(), NarrowLoad); 10794 // CombineTo deleted the truncate, if needed, but not what's under it. 10795 AddToWorklist(oye); 10796 } 10797 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10798 } 10799 10800 // See if the value being truncated is already sign extended. If so, just 10801 // eliminate the trunc/sext pair. 10802 SDValue Op = N0.getOperand(0); 10803 unsigned OpBits = Op.getScalarValueSizeInBits(); 10804 unsigned MidBits = N0.getScalarValueSizeInBits(); 10805 unsigned DestBits = VT.getScalarSizeInBits(); 10806 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 10807 10808 if (OpBits == DestBits) { 10809 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 10810 // bits, it is already ready. 10811 if (NumSignBits > DestBits-MidBits) 10812 return Op; 10813 } else if (OpBits < DestBits) { 10814 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 10815 // bits, just sext from i32. 10816 if (NumSignBits > OpBits-MidBits) 10817 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op); 10818 } else { 10819 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 10820 // bits, just truncate to i32. 10821 if (NumSignBits > OpBits-MidBits) 10822 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op); 10823 } 10824 10825 // fold (sext (truncate x)) -> (sextinreg x). 10826 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 10827 N0.getValueType())) { 10828 if (OpBits < DestBits) 10829 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 10830 else if (OpBits > DestBits) 10831 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 10832 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op, 10833 DAG.getValueType(N0.getValueType())); 10834 } 10835 } 10836 10837 // Try to simplify (sext (load x)). 10838 if (SDValue foldedExt = 10839 tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0, 10840 ISD::SEXTLOAD, ISD::SIGN_EXTEND)) 10841 return foldedExt; 10842 10843 if (SDValue foldedExt = 10844 tryToFoldExtOfMaskedLoad(DAG, TLI, VT, N, N0, ISD::SEXTLOAD, 10845 ISD::SIGN_EXTEND)) 10846 return foldedExt; 10847 10848 // fold (sext (load x)) to multiple smaller sextloads. 10849 // Only on illegal but splittable vectors. 10850 if (SDValue ExtLoad = CombineExtLoad(N)) 10851 return ExtLoad; 10852 10853 // Try to simplify (sext (sextload x)). 10854 if (SDValue foldedExt = tryToFoldExtOfExtload( 10855 DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::SEXTLOAD)) 10856 return foldedExt; 10857 10858 // fold (sext (and/or/xor (load x), cst)) -> 10859 // (and/or/xor (sextload x), (sext cst)) 10860 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 10861 N0.getOpcode() == ISD::XOR) && 10862 isa<LoadSDNode>(N0.getOperand(0)) && 10863 N0.getOperand(1).getOpcode() == ISD::Constant && 10864 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 10865 LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0)); 10866 EVT MemVT = LN00->getMemoryVT(); 10867 if (TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT) && 10868 LN00->getExtensionType() != ISD::ZEXTLOAD && LN00->isUnindexed()) { 10869 SmallVector<SDNode*, 4> SetCCs; 10870 bool DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0), 10871 ISD::SIGN_EXTEND, SetCCs, TLI); 10872 if (DoXform) { 10873 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN00), VT, 10874 LN00->getChain(), LN00->getBasePtr(), 10875 LN00->getMemoryVT(), 10876 LN00->getMemOperand()); 10877 APInt Mask = N0.getConstantOperandAPInt(1).sext(VT.getSizeInBits()); 10878 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 10879 ExtLoad, DAG.getConstant(Mask, DL, VT)); 10880 ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::SIGN_EXTEND); 10881 bool NoReplaceTruncAnd = !N0.hasOneUse(); 10882 bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse(); 10883 CombineTo(N, And); 10884 // If N0 has multiple uses, change other uses as well. 10885 if (NoReplaceTruncAnd) { 10886 SDValue TruncAnd = 10887 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And); 10888 CombineTo(N0.getNode(), TruncAnd); 10889 } 10890 if (NoReplaceTrunc) { 10891 DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1)); 10892 } else { 10893 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00), 10894 LN00->getValueType(0), ExtLoad); 10895 CombineTo(LN00, Trunc, ExtLoad.getValue(1)); 10896 } 10897 return SDValue(N,0); // Return N so it doesn't get rechecked! 10898 } 10899 } 10900 } 10901 10902 if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations)) 10903 return V; 10904 10905 if (N0.getOpcode() == ISD::SETCC) { 10906 SDValue N00 = N0.getOperand(0); 10907 SDValue N01 = N0.getOperand(1); 10908 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 10909 EVT N00VT = N00.getValueType(); 10910 10911 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 10912 // Only do this before legalize for now. 10913 if (VT.isVector() && !LegalOperations && 10914 TLI.getBooleanContents(N00VT) == 10915 TargetLowering::ZeroOrNegativeOneBooleanContent) { 10916 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 10917 // of the same size as the compared operands. Only optimize sext(setcc()) 10918 // if this is the case. 10919 EVT SVT = getSetCCResultType(N00VT); 10920 10921 // If we already have the desired type, don't change it. 10922 if (SVT != N0.getValueType()) { 10923 // We know that the # elements of the results is the same as the 10924 // # elements of the compare (and the # elements of the compare result 10925 // for that matter). Check to see that they are the same size. If so, 10926 // we know that the element size of the sext'd result matches the 10927 // element size of the compare operands. 10928 if (VT.getSizeInBits() == SVT.getSizeInBits()) 10929 return DAG.getSetCC(DL, VT, N00, N01, CC); 10930 10931 // If the desired elements are smaller or larger than the source 10932 // elements, we can use a matching integer vector type and then 10933 // truncate/sign extend. 10934 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger(); 10935 if (SVT == MatchingVecType) { 10936 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC); 10937 return DAG.getSExtOrTrunc(VsetCC, DL, VT); 10938 } 10939 } 10940 } 10941 10942 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0) 10943 // Here, T can be 1 or -1, depending on the type of the setcc and 10944 // getBooleanContents(). 10945 unsigned SetCCWidth = N0.getScalarValueSizeInBits(); 10946 10947 // To determine the "true" side of the select, we need to know the high bit 10948 // of the value returned by the setcc if it evaluates to true. 10949 // If the type of the setcc is i1, then the true case of the select is just 10950 // sext(i1 1), that is, -1. 10951 // If the type of the setcc is larger (say, i8) then the value of the high 10952 // bit depends on getBooleanContents(), so ask TLI for a real "true" value 10953 // of the appropriate width. 10954 SDValue ExtTrueVal = (SetCCWidth == 1) 10955 ? DAG.getAllOnesConstant(DL, VT) 10956 : DAG.getBoolConstant(true, DL, VT, N00VT); 10957 SDValue Zero = DAG.getConstant(0, DL, VT); 10958 if (SDValue SCC = 10959 SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true)) 10960 return SCC; 10961 10962 if (!VT.isVector() && !TLI.convertSelectOfConstantsToMath(VT)) { 10963 EVT SetCCVT = getSetCCResultType(N00VT); 10964 // Don't do this transform for i1 because there's a select transform 10965 // that would reverse it. 10966 // TODO: We should not do this transform at all without a target hook 10967 // because a sext is likely cheaper than a select? 10968 if (SetCCVT.getScalarSizeInBits() != 1 && 10969 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) { 10970 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC); 10971 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero); 10972 } 10973 } 10974 } 10975 10976 // fold (sext x) -> (zext x) if the sign bit is known zero. 10977 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 10978 DAG.SignBitIsZero(N0)) 10979 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0); 10980 10981 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 10982 return NewVSel; 10983 10984 // Eliminate this sign extend by doing a negation in the destination type: 10985 // sext i32 (0 - (zext i8 X to i32)) to i64 --> 0 - (zext i8 X to i64) 10986 if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() && 10987 isNullOrNullSplat(N0.getOperand(0)) && 10988 N0.getOperand(1).getOpcode() == ISD::ZERO_EXTEND && 10989 TLI.isOperationLegalOrCustom(ISD::SUB, VT)) { 10990 SDValue Zext = DAG.getZExtOrTrunc(N0.getOperand(1).getOperand(0), DL, VT); 10991 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Zext); 10992 } 10993 // Eliminate this sign extend by doing a decrement in the destination type: 10994 // sext i32 ((zext i8 X to i32) + (-1)) to i64 --> (zext i8 X to i64) + (-1) 10995 if (N0.getOpcode() == ISD::ADD && N0.hasOneUse() && 10996 isAllOnesOrAllOnesSplat(N0.getOperand(1)) && 10997 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 10998 TLI.isOperationLegalOrCustom(ISD::ADD, VT)) { 10999 SDValue Zext = DAG.getZExtOrTrunc(N0.getOperand(0).getOperand(0), DL, VT); 11000 return DAG.getNode(ISD::ADD, DL, VT, Zext, DAG.getAllOnesConstant(DL, VT)); 11001 } 11002 11003 // fold sext (not i1 X) -> add (zext i1 X), -1 11004 // TODO: This could be extended to handle bool vectors. 11005 if (N0.getValueType() == MVT::i1 && isBitwiseNot(N0) && N0.hasOneUse() && 11006 (!LegalOperations || (TLI.isOperationLegal(ISD::ZERO_EXTEND, VT) && 11007 TLI.isOperationLegal(ISD::ADD, VT)))) { 11008 // If we can eliminate the 'not', the sext form should be better 11009 if (SDValue NewXor = visitXOR(N0.getNode())) { 11010 // Returning N0 is a form of in-visit replacement that may have 11011 // invalidated N0. 11012 if (NewXor.getNode() == N0.getNode()) { 11013 // Return SDValue here as the xor should have already been replaced in 11014 // this sext. 11015 return SDValue(); 11016 } else { 11017 // Return a new sext with the new xor. 11018 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NewXor); 11019 } 11020 } 11021 11022 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 11023 return DAG.getNode(ISD::ADD, DL, VT, Zext, DAG.getAllOnesConstant(DL, VT)); 11024 } 11025 11026 if (SDValue Res = tryToFoldExtendSelectLoad(N, TLI, DAG)) 11027 return Res; 11028 11029 return SDValue(); 11030 } 11031 11032 // isTruncateOf - If N is a truncate of some other value, return true, record 11033 // the value being truncated in Op and which of Op's bits are zero/one in Known. 11034 // This function computes KnownBits to avoid a duplicated call to 11035 // computeKnownBits in the caller. 11036 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 11037 KnownBits &Known) { 11038 if (N->getOpcode() == ISD::TRUNCATE) { 11039 Op = N->getOperand(0); 11040 Known = DAG.computeKnownBits(Op); 11041 return true; 11042 } 11043 11044 if (N.getOpcode() != ISD::SETCC || 11045 N.getValueType().getScalarType() != MVT::i1 || 11046 cast<CondCodeSDNode>(N.getOperand(2))->get() != ISD::SETNE) 11047 return false; 11048 11049 SDValue Op0 = N->getOperand(0); 11050 SDValue Op1 = N->getOperand(1); 11051 assert(Op0.getValueType() == Op1.getValueType()); 11052 11053 if (isNullOrNullSplat(Op0)) 11054 Op = Op1; 11055 else if (isNullOrNullSplat(Op1)) 11056 Op = Op0; 11057 else 11058 return false; 11059 11060 Known = DAG.computeKnownBits(Op); 11061 11062 return (Known.Zero | 1).isAllOnesValue(); 11063 } 11064 11065 /// Given an extending node with a pop-count operand, if the target does not 11066 /// support a pop-count in the narrow source type but does support it in the 11067 /// destination type, widen the pop-count to the destination type. 11068 static SDValue widenCtPop(SDNode *Extend, SelectionDAG &DAG) { 11069 assert((Extend->getOpcode() == ISD::ZERO_EXTEND || 11070 Extend->getOpcode() == ISD::ANY_EXTEND) && "Expected extend op"); 11071 11072 SDValue CtPop = Extend->getOperand(0); 11073 if (CtPop.getOpcode() != ISD::CTPOP || !CtPop.hasOneUse()) 11074 return SDValue(); 11075 11076 EVT VT = Extend->getValueType(0); 11077 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11078 if (TLI.isOperationLegalOrCustom(ISD::CTPOP, CtPop.getValueType()) || 11079 !TLI.isOperationLegalOrCustom(ISD::CTPOP, VT)) 11080 return SDValue(); 11081 11082 // zext (ctpop X) --> ctpop (zext X) 11083 SDLoc DL(Extend); 11084 SDValue NewZext = DAG.getZExtOrTrunc(CtPop.getOperand(0), DL, VT); 11085 return DAG.getNode(ISD::CTPOP, DL, VT, NewZext); 11086 } 11087 11088 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 11089 SDValue N0 = N->getOperand(0); 11090 EVT VT = N->getValueType(0); 11091 11092 if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes)) 11093 return Res; 11094 11095 // fold (zext (zext x)) -> (zext x) 11096 // fold (zext (aext x)) -> (zext x) 11097 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 11098 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 11099 N0.getOperand(0)); 11100 11101 // fold (zext (truncate x)) -> (zext x) or 11102 // (zext (truncate x)) -> (truncate x) 11103 // This is valid when the truncated bits of x are already zero. 11104 SDValue Op; 11105 KnownBits Known; 11106 if (isTruncateOf(DAG, N0, Op, Known)) { 11107 APInt TruncatedBits = 11108 (Op.getScalarValueSizeInBits() == N0.getScalarValueSizeInBits()) ? 11109 APInt(Op.getScalarValueSizeInBits(), 0) : 11110 APInt::getBitsSet(Op.getScalarValueSizeInBits(), 11111 N0.getScalarValueSizeInBits(), 11112 std::min(Op.getScalarValueSizeInBits(), 11113 VT.getScalarSizeInBits())); 11114 if (TruncatedBits.isSubsetOf(Known.Zero)) 11115 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 11116 } 11117 11118 // fold (zext (truncate x)) -> (and x, mask) 11119 if (N0.getOpcode() == ISD::TRUNCATE) { 11120 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 11121 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 11122 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 11123 SDNode *oye = N0.getOperand(0).getNode(); 11124 if (NarrowLoad.getNode() != N0.getNode()) { 11125 CombineTo(N0.getNode(), NarrowLoad); 11126 // CombineTo deleted the truncate, if needed, but not what's under it. 11127 AddToWorklist(oye); 11128 } 11129 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11130 } 11131 11132 EVT SrcVT = N0.getOperand(0).getValueType(); 11133 EVT MinVT = N0.getValueType(); 11134 11135 // Try to mask before the extension to avoid having to generate a larger mask, 11136 // possibly over several sub-vectors. 11137 if (SrcVT.bitsLT(VT) && VT.isVector()) { 11138 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 11139 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 11140 SDValue Op = N0.getOperand(0); 11141 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT); 11142 AddToWorklist(Op.getNode()); 11143 SDValue ZExtOrTrunc = DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 11144 // Transfer the debug info; the new node is equivalent to N0. 11145 DAG.transferDbgValues(N0, ZExtOrTrunc); 11146 return ZExtOrTrunc; 11147 } 11148 } 11149 11150 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 11151 SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 11152 AddToWorklist(Op.getNode()); 11153 SDValue And = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT); 11154 // We may safely transfer the debug info describing the truncate node over 11155 // to the equivalent and operation. 11156 DAG.transferDbgValues(N0, And); 11157 return And; 11158 } 11159 } 11160 11161 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 11162 // if either of the casts is not free. 11163 if (N0.getOpcode() == ISD::AND && 11164 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 11165 N0.getOperand(1).getOpcode() == ISD::Constant && 11166 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 11167 N0.getValueType()) || 11168 !TLI.isZExtFree(N0.getValueType(), VT))) { 11169 SDValue X = N0.getOperand(0).getOperand(0); 11170 X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT); 11171 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits()); 11172 SDLoc DL(N); 11173 return DAG.getNode(ISD::AND, DL, VT, 11174 X, DAG.getConstant(Mask, DL, VT)); 11175 } 11176 11177 // Try to simplify (zext (load x)). 11178 if (SDValue foldedExt = 11179 tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0, 11180 ISD::ZEXTLOAD, ISD::ZERO_EXTEND)) 11181 return foldedExt; 11182 11183 if (SDValue foldedExt = 11184 tryToFoldExtOfMaskedLoad(DAG, TLI, VT, N, N0, ISD::ZEXTLOAD, 11185 ISD::ZERO_EXTEND)) 11186 return foldedExt; 11187 11188 // fold (zext (load x)) to multiple smaller zextloads. 11189 // Only on illegal but splittable vectors. 11190 if (SDValue ExtLoad = CombineExtLoad(N)) 11191 return ExtLoad; 11192 11193 // fold (zext (and/or/xor (load x), cst)) -> 11194 // (and/or/xor (zextload x), (zext cst)) 11195 // Unless (and (load x) cst) will match as a zextload already and has 11196 // additional users. 11197 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 11198 N0.getOpcode() == ISD::XOR) && 11199 isa<LoadSDNode>(N0.getOperand(0)) && 11200 N0.getOperand(1).getOpcode() == ISD::Constant && 11201 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 11202 LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0)); 11203 EVT MemVT = LN00->getMemoryVT(); 11204 if (TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) && 11205 LN00->getExtensionType() != ISD::SEXTLOAD && LN00->isUnindexed()) { 11206 bool DoXform = true; 11207 SmallVector<SDNode*, 4> SetCCs; 11208 if (!N0.hasOneUse()) { 11209 if (N0.getOpcode() == ISD::AND) { 11210 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 11211 EVT LoadResultTy = AndC->getValueType(0); 11212 EVT ExtVT; 11213 if (isAndLoadExtLoad(AndC, LN00, LoadResultTy, ExtVT)) 11214 DoXform = false; 11215 } 11216 } 11217 if (DoXform) 11218 DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0), 11219 ISD::ZERO_EXTEND, SetCCs, TLI); 11220 if (DoXform) { 11221 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN00), VT, 11222 LN00->getChain(), LN00->getBasePtr(), 11223 LN00->getMemoryVT(), 11224 LN00->getMemOperand()); 11225 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits()); 11226 SDLoc DL(N); 11227 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 11228 ExtLoad, DAG.getConstant(Mask, DL, VT)); 11229 ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::ZERO_EXTEND); 11230 bool NoReplaceTruncAnd = !N0.hasOneUse(); 11231 bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse(); 11232 CombineTo(N, And); 11233 // If N0 has multiple uses, change other uses as well. 11234 if (NoReplaceTruncAnd) { 11235 SDValue TruncAnd = 11236 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And); 11237 CombineTo(N0.getNode(), TruncAnd); 11238 } 11239 if (NoReplaceTrunc) { 11240 DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1)); 11241 } else { 11242 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00), 11243 LN00->getValueType(0), ExtLoad); 11244 CombineTo(LN00, Trunc, ExtLoad.getValue(1)); 11245 } 11246 return SDValue(N,0); // Return N so it doesn't get rechecked! 11247 } 11248 } 11249 } 11250 11251 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) -> 11252 // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst)) 11253 if (SDValue ZExtLoad = CombineZExtLogicopShiftLoad(N)) 11254 return ZExtLoad; 11255 11256 // Try to simplify (zext (zextload x)). 11257 if (SDValue foldedExt = tryToFoldExtOfExtload( 11258 DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::ZEXTLOAD)) 11259 return foldedExt; 11260 11261 if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations)) 11262 return V; 11263 11264 if (N0.getOpcode() == ISD::SETCC) { 11265 // Only do this before legalize for now. 11266 if (!LegalOperations && VT.isVector() && 11267 N0.getValueType().getVectorElementType() == MVT::i1) { 11268 EVT N00VT = N0.getOperand(0).getValueType(); 11269 if (getSetCCResultType(N00VT) == N0.getValueType()) 11270 return SDValue(); 11271 11272 // We know that the # elements of the results is the same as the # 11273 // elements of the compare (and the # elements of the compare result for 11274 // that matter). Check to see that they are the same size. If so, we know 11275 // that the element size of the sext'd result matches the element size of 11276 // the compare operands. 11277 SDLoc DL(N); 11278 if (VT.getSizeInBits() == N00VT.getSizeInBits()) { 11279 // zext(setcc) -> zext_in_reg(vsetcc) for vectors. 11280 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0), 11281 N0.getOperand(1), N0.getOperand(2)); 11282 return DAG.getZeroExtendInReg(VSetCC, DL, N0.getValueType()); 11283 } 11284 11285 // If the desired elements are smaller or larger than the source 11286 // elements we can use a matching integer vector type and then 11287 // truncate/any extend followed by zext_in_reg. 11288 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger(); 11289 SDValue VsetCC = 11290 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0), 11291 N0.getOperand(1), N0.getOperand(2)); 11292 return DAG.getZeroExtendInReg(DAG.getAnyExtOrTrunc(VsetCC, DL, VT), DL, 11293 N0.getValueType()); 11294 } 11295 11296 // zext(setcc x,y,cc) -> zext(select x, y, true, false, cc) 11297 SDLoc DL(N); 11298 EVT N0VT = N0.getValueType(); 11299 EVT N00VT = N0.getOperand(0).getValueType(); 11300 if (SDValue SCC = SimplifySelectCC( 11301 DL, N0.getOperand(0), N0.getOperand(1), 11302 DAG.getBoolConstant(true, DL, N0VT, N00VT), 11303 DAG.getBoolConstant(false, DL, N0VT, N00VT), 11304 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 11305 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, SCC); 11306 } 11307 11308 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 11309 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 11310 isa<ConstantSDNode>(N0.getOperand(1)) && 11311 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 11312 N0.hasOneUse()) { 11313 SDValue ShAmt = N0.getOperand(1); 11314 if (N0.getOpcode() == ISD::SHL) { 11315 SDValue InnerZExt = N0.getOperand(0); 11316 // If the original shl may be shifting out bits, do not perform this 11317 // transformation. 11318 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() - 11319 InnerZExt.getOperand(0).getValueSizeInBits(); 11320 if (cast<ConstantSDNode>(ShAmt)->getAPIntValue().ugt(KnownZeroBits)) 11321 return SDValue(); 11322 } 11323 11324 SDLoc DL(N); 11325 11326 // Ensure that the shift amount is wide enough for the shifted value. 11327 if (Log2_32_Ceil(VT.getSizeInBits()) > ShAmt.getValueSizeInBits()) 11328 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 11329 11330 return DAG.getNode(N0.getOpcode(), DL, VT, 11331 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 11332 ShAmt); 11333 } 11334 11335 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 11336 return NewVSel; 11337 11338 if (SDValue NewCtPop = widenCtPop(N, DAG)) 11339 return NewCtPop; 11340 11341 if (SDValue Res = tryToFoldExtendSelectLoad(N, TLI, DAG)) 11342 return Res; 11343 11344 return SDValue(); 11345 } 11346 11347 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 11348 SDValue N0 = N->getOperand(0); 11349 EVT VT = N->getValueType(0); 11350 11351 if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes)) 11352 return Res; 11353 11354 // fold (aext (aext x)) -> (aext x) 11355 // fold (aext (zext x)) -> (zext x) 11356 // fold (aext (sext x)) -> (sext x) 11357 if (N0.getOpcode() == ISD::ANY_EXTEND || 11358 N0.getOpcode() == ISD::ZERO_EXTEND || 11359 N0.getOpcode() == ISD::SIGN_EXTEND) 11360 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 11361 11362 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 11363 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 11364 if (N0.getOpcode() == ISD::TRUNCATE) { 11365 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 11366 SDNode *oye = N0.getOperand(0).getNode(); 11367 if (NarrowLoad.getNode() != N0.getNode()) { 11368 CombineTo(N0.getNode(), NarrowLoad); 11369 // CombineTo deleted the truncate, if needed, but not what's under it. 11370 AddToWorklist(oye); 11371 } 11372 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11373 } 11374 } 11375 11376 // fold (aext (truncate x)) 11377 if (N0.getOpcode() == ISD::TRUNCATE) 11378 return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 11379 11380 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 11381 // if the trunc is not free. 11382 if (N0.getOpcode() == ISD::AND && 11383 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 11384 N0.getOperand(1).getOpcode() == ISD::Constant && 11385 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 11386 N0.getValueType())) { 11387 SDLoc DL(N); 11388 SDValue X = N0.getOperand(0).getOperand(0); 11389 X = DAG.getAnyExtOrTrunc(X, DL, VT); 11390 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits()); 11391 return DAG.getNode(ISD::AND, DL, VT, 11392 X, DAG.getConstant(Mask, DL, VT)); 11393 } 11394 11395 // fold (aext (load x)) -> (aext (truncate (extload x))) 11396 // None of the supported targets knows how to perform load and any_ext 11397 // on vectors in one instruction, so attempt to fold to zext instead. 11398 if (VT.isVector()) { 11399 // Try to simplify (zext (load x)). 11400 if (SDValue foldedExt = 11401 tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0, 11402 ISD::ZEXTLOAD, ISD::ZERO_EXTEND)) 11403 return foldedExt; 11404 } else if (ISD::isNON_EXTLoad(N0.getNode()) && 11405 ISD::isUNINDEXEDLoad(N0.getNode()) && 11406 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 11407 bool DoXform = true; 11408 SmallVector<SDNode *, 4> SetCCs; 11409 if (!N0.hasOneUse()) 11410 DoXform = 11411 ExtendUsesToFormExtLoad(VT, N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 11412 if (DoXform) { 11413 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 11414 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 11415 LN0->getChain(), LN0->getBasePtr(), 11416 N0.getValueType(), LN0->getMemOperand()); 11417 ExtendSetCCUses(SetCCs, N0, ExtLoad, ISD::ANY_EXTEND); 11418 // If the load value is used only by N, replace it via CombineTo N. 11419 bool NoReplaceTrunc = N0.hasOneUse(); 11420 CombineTo(N, ExtLoad); 11421 if (NoReplaceTrunc) { 11422 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 11423 recursivelyDeleteUnusedNodes(LN0); 11424 } else { 11425 SDValue Trunc = 11426 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), ExtLoad); 11427 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 11428 } 11429 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11430 } 11431 } 11432 11433 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 11434 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 11435 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 11436 if (N0.getOpcode() == ISD::LOAD && !ISD::isNON_EXTLoad(N0.getNode()) && 11437 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 11438 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 11439 ISD::LoadExtType ExtType = LN0->getExtensionType(); 11440 EVT MemVT = LN0->getMemoryVT(); 11441 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 11442 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 11443 VT, LN0->getChain(), LN0->getBasePtr(), 11444 MemVT, LN0->getMemOperand()); 11445 CombineTo(N, ExtLoad); 11446 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 11447 recursivelyDeleteUnusedNodes(LN0); 11448 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11449 } 11450 } 11451 11452 if (N0.getOpcode() == ISD::SETCC) { 11453 // For vectors: 11454 // aext(setcc) -> vsetcc 11455 // aext(setcc) -> truncate(vsetcc) 11456 // aext(setcc) -> aext(vsetcc) 11457 // Only do this before legalize for now. 11458 if (VT.isVector() && !LegalOperations) { 11459 EVT N00VT = N0.getOperand(0).getValueType(); 11460 if (getSetCCResultType(N00VT) == N0.getValueType()) 11461 return SDValue(); 11462 11463 // We know that the # elements of the results is the same as the 11464 // # elements of the compare (and the # elements of the compare result 11465 // for that matter). Check to see that they are the same size. If so, 11466 // we know that the element size of the sext'd result matches the 11467 // element size of the compare operands. 11468 if (VT.getSizeInBits() == N00VT.getSizeInBits()) 11469 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 11470 N0.getOperand(1), 11471 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 11472 11473 // If the desired elements are smaller or larger than the source 11474 // elements we can use a matching integer vector type and then 11475 // truncate/any extend 11476 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger(); 11477 SDValue VsetCC = 11478 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 11479 N0.getOperand(1), 11480 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 11481 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 11482 } 11483 11484 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 11485 SDLoc DL(N); 11486 if (SDValue SCC = SimplifySelectCC( 11487 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 11488 DAG.getConstant(0, DL, VT), 11489 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 11490 return SCC; 11491 } 11492 11493 if (SDValue NewCtPop = widenCtPop(N, DAG)) 11494 return NewCtPop; 11495 11496 if (SDValue Res = tryToFoldExtendSelectLoad(N, TLI, DAG)) 11497 return Res; 11498 11499 return SDValue(); 11500 } 11501 11502 SDValue DAGCombiner::visitAssertExt(SDNode *N) { 11503 unsigned Opcode = N->getOpcode(); 11504 SDValue N0 = N->getOperand(0); 11505 SDValue N1 = N->getOperand(1); 11506 EVT AssertVT = cast<VTSDNode>(N1)->getVT(); 11507 11508 // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt) 11509 if (N0.getOpcode() == Opcode && 11510 AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT()) 11511 return N0; 11512 11513 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && 11514 N0.getOperand(0).getOpcode() == Opcode) { 11515 // We have an assert, truncate, assert sandwich. Make one stronger assert 11516 // by asserting on the smallest asserted type to the larger source type. 11517 // This eliminates the later assert: 11518 // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN 11519 // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN 11520 SDValue BigA = N0.getOperand(0); 11521 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT(); 11522 assert(BigA_AssertVT.bitsLE(N0.getValueType()) && 11523 "Asserting zero/sign-extended bits to a type larger than the " 11524 "truncated destination does not provide information"); 11525 11526 SDLoc DL(N); 11527 EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT; 11528 SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT); 11529 SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(), 11530 BigA.getOperand(0), MinAssertVTVal); 11531 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert); 11532 } 11533 11534 // If we have (AssertZext (truncate (AssertSext X, iX)), iY) and Y is smaller 11535 // than X. Just move the AssertZext in front of the truncate and drop the 11536 // AssertSExt. 11537 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && 11538 N0.getOperand(0).getOpcode() == ISD::AssertSext && 11539 Opcode == ISD::AssertZext) { 11540 SDValue BigA = N0.getOperand(0); 11541 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT(); 11542 assert(BigA_AssertVT.bitsLE(N0.getValueType()) && 11543 "Asserting zero/sign-extended bits to a type larger than the " 11544 "truncated destination does not provide information"); 11545 11546 if (AssertVT.bitsLT(BigA_AssertVT)) { 11547 SDLoc DL(N); 11548 SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(), 11549 BigA.getOperand(0), N1); 11550 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert); 11551 } 11552 } 11553 11554 return SDValue(); 11555 } 11556 11557 SDValue DAGCombiner::visitAssertAlign(SDNode *N) { 11558 SDLoc DL(N); 11559 11560 Align AL = cast<AssertAlignSDNode>(N)->getAlign(); 11561 SDValue N0 = N->getOperand(0); 11562 11563 // Fold (assertalign (assertalign x, AL0), AL1) -> 11564 // (assertalign x, max(AL0, AL1)) 11565 if (auto *AAN = dyn_cast<AssertAlignSDNode>(N0)) 11566 return DAG.getAssertAlign(DL, N0.getOperand(0), 11567 std::max(AL, AAN->getAlign())); 11568 11569 // In rare cases, there are trivial arithmetic ops in source operands. Sink 11570 // this assert down to source operands so that those arithmetic ops could be 11571 // exposed to the DAG combining. 11572 switch (N0.getOpcode()) { 11573 default: 11574 break; 11575 case ISD::ADD: 11576 case ISD::SUB: { 11577 unsigned AlignShift = Log2(AL); 11578 SDValue LHS = N0.getOperand(0); 11579 SDValue RHS = N0.getOperand(1); 11580 unsigned LHSAlignShift = DAG.computeKnownBits(LHS).countMinTrailingZeros(); 11581 unsigned RHSAlignShift = DAG.computeKnownBits(RHS).countMinTrailingZeros(); 11582 if (LHSAlignShift >= AlignShift || RHSAlignShift >= AlignShift) { 11583 if (LHSAlignShift < AlignShift) 11584 LHS = DAG.getAssertAlign(DL, LHS, AL); 11585 if (RHSAlignShift < AlignShift) 11586 RHS = DAG.getAssertAlign(DL, RHS, AL); 11587 return DAG.getNode(N0.getOpcode(), DL, N0.getValueType(), LHS, RHS); 11588 } 11589 break; 11590 } 11591 } 11592 11593 return SDValue(); 11594 } 11595 11596 /// If the result of a wider load is shifted to right of N bits and then 11597 /// truncated to a narrower type and where N is a multiple of number of bits of 11598 /// the narrower type, transform it to a narrower load from address + N / num of 11599 /// bits of new type. Also narrow the load if the result is masked with an AND 11600 /// to effectively produce a smaller type. If the result is to be extended, also 11601 /// fold the extension to form a extending load. 11602 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 11603 unsigned Opc = N->getOpcode(); 11604 11605 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 11606 SDValue N0 = N->getOperand(0); 11607 EVT VT = N->getValueType(0); 11608 EVT ExtVT = VT; 11609 11610 // This transformation isn't valid for vector loads. 11611 if (VT.isVector()) 11612 return SDValue(); 11613 11614 unsigned ShAmt = 0; 11615 bool HasShiftedOffset = false; 11616 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 11617 // extended to VT. 11618 if (Opc == ISD::SIGN_EXTEND_INREG) { 11619 ExtType = ISD::SEXTLOAD; 11620 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 11621 } else if (Opc == ISD::SRL) { 11622 // Another special-case: SRL is basically zero-extending a narrower value, 11623 // or it maybe shifting a higher subword, half or byte into the lowest 11624 // bits. 11625 ExtType = ISD::ZEXTLOAD; 11626 N0 = SDValue(N, 0); 11627 11628 auto *LN0 = dyn_cast<LoadSDNode>(N0.getOperand(0)); 11629 auto *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 11630 if (!N01 || !LN0) 11631 return SDValue(); 11632 11633 uint64_t ShiftAmt = N01->getZExtValue(); 11634 uint64_t MemoryWidth = LN0->getMemoryVT().getScalarSizeInBits(); 11635 if (LN0->getExtensionType() != ISD::SEXTLOAD && MemoryWidth > ShiftAmt) 11636 ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShiftAmt); 11637 else 11638 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 11639 VT.getScalarSizeInBits() - ShiftAmt); 11640 } else if (Opc == ISD::AND) { 11641 // An AND with a constant mask is the same as a truncate + zero-extend. 11642 auto AndC = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11643 if (!AndC) 11644 return SDValue(); 11645 11646 const APInt &Mask = AndC->getAPIntValue(); 11647 unsigned ActiveBits = 0; 11648 if (Mask.isMask()) { 11649 ActiveBits = Mask.countTrailingOnes(); 11650 } else if (Mask.isShiftedMask()) { 11651 ShAmt = Mask.countTrailingZeros(); 11652 APInt ShiftedMask = Mask.lshr(ShAmt); 11653 ActiveBits = ShiftedMask.countTrailingOnes(); 11654 HasShiftedOffset = true; 11655 } else 11656 return SDValue(); 11657 11658 ExtType = ISD::ZEXTLOAD; 11659 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 11660 } 11661 11662 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 11663 SDValue SRL = N0; 11664 if (auto *ConstShift = dyn_cast<ConstantSDNode>(SRL.getOperand(1))) { 11665 ShAmt = ConstShift->getZExtValue(); 11666 unsigned EVTBits = ExtVT.getScalarSizeInBits(); 11667 // Is the shift amount a multiple of size of VT? 11668 if ((ShAmt & (EVTBits-1)) == 0) { 11669 N0 = N0.getOperand(0); 11670 // Is the load width a multiple of size of VT? 11671 if ((N0.getScalarValueSizeInBits() & (EVTBits - 1)) != 0) 11672 return SDValue(); 11673 } 11674 11675 // At this point, we must have a load or else we can't do the transform. 11676 auto *LN0 = dyn_cast<LoadSDNode>(N0); 11677 if (!LN0) return SDValue(); 11678 11679 // Because a SRL must be assumed to *need* to zero-extend the high bits 11680 // (as opposed to anyext the high bits), we can't combine the zextload 11681 // lowering of SRL and an sextload. 11682 if (LN0->getExtensionType() == ISD::SEXTLOAD) 11683 return SDValue(); 11684 11685 // If the shift amount is larger than the input type then we're not 11686 // accessing any of the loaded bytes. If the load was a zextload/extload 11687 // then the result of the shift+trunc is zero/undef (handled elsewhere). 11688 if (ShAmt >= LN0->getMemoryVT().getSizeInBits()) 11689 return SDValue(); 11690 11691 // If the SRL is only used by a masking AND, we may be able to adjust 11692 // the ExtVT to make the AND redundant. 11693 SDNode *Mask = *(SRL->use_begin()); 11694 if (Mask->getOpcode() == ISD::AND && 11695 isa<ConstantSDNode>(Mask->getOperand(1))) { 11696 const APInt& ShiftMask = Mask->getConstantOperandAPInt(1); 11697 if (ShiftMask.isMask()) { 11698 EVT MaskedVT = EVT::getIntegerVT(*DAG.getContext(), 11699 ShiftMask.countTrailingOnes()); 11700 // If the mask is smaller, recompute the type. 11701 if ((ExtVT.getScalarSizeInBits() > MaskedVT.getScalarSizeInBits()) && 11702 TLI.isLoadExtLegal(ExtType, N0.getValueType(), MaskedVT)) 11703 ExtVT = MaskedVT; 11704 } 11705 } 11706 } 11707 } 11708 11709 // If the load is shifted left (and the result isn't shifted back right), 11710 // we can fold the truncate through the shift. 11711 unsigned ShLeftAmt = 0; 11712 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 11713 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 11714 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 11715 ShLeftAmt = N01->getZExtValue(); 11716 N0 = N0.getOperand(0); 11717 } 11718 } 11719 11720 // If we haven't found a load, we can't narrow it. 11721 if (!isa<LoadSDNode>(N0)) 11722 return SDValue(); 11723 11724 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 11725 // Reducing the width of a volatile load is illegal. For atomics, we may be 11726 // able to reduce the width provided we never widen again. (see D66309) 11727 if (!LN0->isSimple() || 11728 !isLegalNarrowLdSt(LN0, ExtType, ExtVT, ShAmt)) 11729 return SDValue(); 11730 11731 auto AdjustBigEndianShift = [&](unsigned ShAmt) { 11732 unsigned LVTStoreBits = 11733 LN0->getMemoryVT().getStoreSizeInBits().getFixedSize(); 11734 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits().getFixedSize(); 11735 return LVTStoreBits - EVTStoreBits - ShAmt; 11736 }; 11737 11738 // For big endian targets, we need to adjust the offset to the pointer to 11739 // load the correct bytes. 11740 if (DAG.getDataLayout().isBigEndian()) 11741 ShAmt = AdjustBigEndianShift(ShAmt); 11742 11743 uint64_t PtrOff = ShAmt / 8; 11744 Align NewAlign = commonAlignment(LN0->getAlign(), PtrOff); 11745 SDLoc DL(LN0); 11746 // The original load itself didn't wrap, so an offset within it doesn't. 11747 SDNodeFlags Flags; 11748 Flags.setNoUnsignedWrap(true); 11749 SDValue NewPtr = DAG.getMemBasePlusOffset(LN0->getBasePtr(), 11750 TypeSize::Fixed(PtrOff), DL, Flags); 11751 AddToWorklist(NewPtr.getNode()); 11752 11753 SDValue Load; 11754 if (ExtType == ISD::NON_EXTLOAD) 11755 Load = DAG.getLoad(VT, DL, LN0->getChain(), NewPtr, 11756 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign, 11757 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 11758 else 11759 Load = DAG.getExtLoad(ExtType, DL, VT, LN0->getChain(), NewPtr, 11760 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT, 11761 NewAlign, LN0->getMemOperand()->getFlags(), 11762 LN0->getAAInfo()); 11763 11764 // Replace the old load's chain with the new load's chain. 11765 WorklistRemover DeadNodes(*this); 11766 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 11767 11768 // Shift the result left, if we've swallowed a left shift. 11769 SDValue Result = Load; 11770 if (ShLeftAmt != 0) { 11771 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 11772 if (!isUIntN(ShImmTy.getScalarSizeInBits(), ShLeftAmt)) 11773 ShImmTy = VT; 11774 // If the shift amount is as large as the result size (but, presumably, 11775 // no larger than the source) then the useful bits of the result are 11776 // zero; we can't simply return the shortened shift, because the result 11777 // of that operation is undefined. 11778 if (ShLeftAmt >= VT.getScalarSizeInBits()) 11779 Result = DAG.getConstant(0, DL, VT); 11780 else 11781 Result = DAG.getNode(ISD::SHL, DL, VT, 11782 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 11783 } 11784 11785 if (HasShiftedOffset) { 11786 // Recalculate the shift amount after it has been altered to calculate 11787 // the offset. 11788 if (DAG.getDataLayout().isBigEndian()) 11789 ShAmt = AdjustBigEndianShift(ShAmt); 11790 11791 // We're using a shifted mask, so the load now has an offset. This means 11792 // that data has been loaded into the lower bytes than it would have been 11793 // before, so we need to shl the loaded data into the correct position in the 11794 // register. 11795 SDValue ShiftC = DAG.getConstant(ShAmt, DL, VT); 11796 Result = DAG.getNode(ISD::SHL, DL, VT, Result, ShiftC); 11797 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 11798 } 11799 11800 // Return the new loaded value. 11801 return Result; 11802 } 11803 11804 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 11805 SDValue N0 = N->getOperand(0); 11806 SDValue N1 = N->getOperand(1); 11807 EVT VT = N->getValueType(0); 11808 EVT ExtVT = cast<VTSDNode>(N1)->getVT(); 11809 unsigned VTBits = VT.getScalarSizeInBits(); 11810 unsigned ExtVTBits = ExtVT.getScalarSizeInBits(); 11811 11812 // sext_vector_inreg(undef) = 0 because the top bit will all be the same. 11813 if (N0.isUndef()) 11814 return DAG.getConstant(0, SDLoc(N), VT); 11815 11816 // fold (sext_in_reg c1) -> c1 11817 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 11818 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 11819 11820 // If the input is already sign extended, just drop the extension. 11821 if (DAG.ComputeNumSignBits(N0) >= (VTBits - ExtVTBits + 1)) 11822 return N0; 11823 11824 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 11825 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 11826 ExtVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 11827 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0.getOperand(0), 11828 N1); 11829 11830 // fold (sext_in_reg (sext x)) -> (sext x) 11831 // fold (sext_in_reg (aext x)) -> (sext x) 11832 // if x is small enough or if we know that x has more than 1 sign bit and the 11833 // sign_extend_inreg is extending from one of them. 11834 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 11835 SDValue N00 = N0.getOperand(0); 11836 unsigned N00Bits = N00.getScalarValueSizeInBits(); 11837 if ((N00Bits <= ExtVTBits || 11838 (N00Bits - DAG.ComputeNumSignBits(N00)) < ExtVTBits) && 11839 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 11840 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00); 11841 } 11842 11843 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_inreg x) 11844 // if x is small enough or if we know that x has more than 1 sign bit and the 11845 // sign_extend_inreg is extending from one of them. 11846 if (N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG || 11847 N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG || 11848 N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) { 11849 SDValue N00 = N0.getOperand(0); 11850 unsigned N00Bits = N00.getScalarValueSizeInBits(); 11851 unsigned DstElts = N0.getValueType().getVectorMinNumElements(); 11852 unsigned SrcElts = N00.getValueType().getVectorMinNumElements(); 11853 bool IsZext = N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG; 11854 APInt DemandedSrcElts = APInt::getLowBitsSet(SrcElts, DstElts); 11855 if ((N00Bits == ExtVTBits || 11856 (!IsZext && (N00Bits < ExtVTBits || 11857 (N00Bits - DAG.ComputeNumSignBits(N00, DemandedSrcElts)) < 11858 ExtVTBits))) && 11859 (!LegalOperations || 11860 TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))) 11861 return DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, SDLoc(N), VT, N00); 11862 } 11863 11864 // fold (sext_in_reg (zext x)) -> (sext x) 11865 // iff we are extending the source sign bit. 11866 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 11867 SDValue N00 = N0.getOperand(0); 11868 if (N00.getScalarValueSizeInBits() == ExtVTBits && 11869 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 11870 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 11871 } 11872 11873 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 11874 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, ExtVTBits - 1))) 11875 return DAG.getZeroExtendInReg(N0, SDLoc(N), ExtVT); 11876 11877 // fold operands of sext_in_reg based on knowledge that the top bits are not 11878 // demanded. 11879 if (SimplifyDemandedBits(SDValue(N, 0))) 11880 return SDValue(N, 0); 11881 11882 // fold (sext_in_reg (load x)) -> (smaller sextload x) 11883 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 11884 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 11885 return NarrowLoad; 11886 11887 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 11888 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 11889 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 11890 if (N0.getOpcode() == ISD::SRL) { 11891 if (auto *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 11892 if (ShAmt->getAPIntValue().ule(VTBits - ExtVTBits)) { 11893 // We can turn this into an SRA iff the input to the SRL is already sign 11894 // extended enough. 11895 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 11896 if (((VTBits - ExtVTBits) - ShAmt->getZExtValue()) < InSignBits) 11897 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0), 11898 N0.getOperand(1)); 11899 } 11900 } 11901 11902 // fold (sext_inreg (extload x)) -> (sextload x) 11903 // If sextload is not supported by target, we can only do the combine when 11904 // load has one use. Doing otherwise can block folding the extload with other 11905 // extends that the target does support. 11906 if (ISD::isEXTLoad(N0.getNode()) && 11907 ISD::isUNINDEXEDLoad(N0.getNode()) && 11908 ExtVT == cast<LoadSDNode>(N0)->getMemoryVT() && 11909 ((!LegalOperations && cast<LoadSDNode>(N0)->isSimple() && 11910 N0.hasOneUse()) || 11911 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, ExtVT))) { 11912 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 11913 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 11914 LN0->getChain(), 11915 LN0->getBasePtr(), ExtVT, 11916 LN0->getMemOperand()); 11917 CombineTo(N, ExtLoad); 11918 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 11919 AddToWorklist(ExtLoad.getNode()); 11920 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11921 } 11922 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 11923 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 11924 N0.hasOneUse() && 11925 ExtVT == cast<LoadSDNode>(N0)->getMemoryVT() && 11926 ((!LegalOperations && cast<LoadSDNode>(N0)->isSimple()) && 11927 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, ExtVT))) { 11928 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 11929 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 11930 LN0->getChain(), 11931 LN0->getBasePtr(), ExtVT, 11932 LN0->getMemOperand()); 11933 CombineTo(N, ExtLoad); 11934 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 11935 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11936 } 11937 11938 // fold (sext_inreg (masked_load x)) -> (sext_masked_load x) 11939 // ignore it if the masked load is already sign extended 11940 if (MaskedLoadSDNode *Ld = dyn_cast<MaskedLoadSDNode>(N0)) { 11941 if (ExtVT == Ld->getMemoryVT() && N0.hasOneUse() && 11942 Ld->getExtensionType() != ISD::LoadExtType::NON_EXTLOAD && 11943 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, ExtVT)) { 11944 SDValue ExtMaskedLoad = DAG.getMaskedLoad( 11945 VT, SDLoc(N), Ld->getChain(), Ld->getBasePtr(), Ld->getOffset(), 11946 Ld->getMask(), Ld->getPassThru(), ExtVT, Ld->getMemOperand(), 11947 Ld->getAddressingMode(), ISD::SEXTLOAD, Ld->isExpandingLoad()); 11948 CombineTo(N, ExtMaskedLoad); 11949 CombineTo(N0.getNode(), ExtMaskedLoad, ExtMaskedLoad.getValue(1)); 11950 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11951 } 11952 } 11953 11954 // fold (sext_inreg (masked_gather x)) -> (sext_masked_gather x) 11955 if (auto *GN0 = dyn_cast<MaskedGatherSDNode>(N0)) { 11956 if (SDValue(GN0, 0).hasOneUse() && 11957 ExtVT == GN0->getMemoryVT() && 11958 TLI.isVectorLoadExtDesirable(SDValue(SDValue(GN0, 0)))) { 11959 SDValue Ops[] = {GN0->getChain(), GN0->getPassThru(), GN0->getMask(), 11960 GN0->getBasePtr(), GN0->getIndex(), GN0->getScale()}; 11961 11962 SDValue ExtLoad = DAG.getMaskedGather( 11963 DAG.getVTList(VT, MVT::Other), ExtVT, SDLoc(N), Ops, 11964 GN0->getMemOperand(), GN0->getIndexType(), ISD::SEXTLOAD); 11965 11966 CombineTo(N, ExtLoad); 11967 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 11968 AddToWorklist(ExtLoad.getNode()); 11969 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11970 } 11971 } 11972 11973 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 11974 if (ExtVTBits <= 16 && N0.getOpcode() == ISD::OR) { 11975 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 11976 N0.getOperand(1), false)) 11977 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, BSwap, N1); 11978 } 11979 11980 return SDValue(); 11981 } 11982 11983 SDValue DAGCombiner::visitEXTEND_VECTOR_INREG(SDNode *N) { 11984 SDValue N0 = N->getOperand(0); 11985 EVT VT = N->getValueType(0); 11986 11987 // {s/z}ext_vector_inreg(undef) = 0 because the top bits must be the same. 11988 if (N0.isUndef()) 11989 return DAG.getConstant(0, SDLoc(N), VT); 11990 11991 if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes)) 11992 return Res; 11993 11994 if (SimplifyDemandedVectorElts(SDValue(N, 0))) 11995 return SDValue(N, 0); 11996 11997 return SDValue(); 11998 } 11999 12000 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 12001 SDValue N0 = N->getOperand(0); 12002 EVT VT = N->getValueType(0); 12003 EVT SrcVT = N0.getValueType(); 12004 bool isLE = DAG.getDataLayout().isLittleEndian(); 12005 12006 // noop truncate 12007 if (SrcVT == VT) 12008 return N0; 12009 12010 // fold (truncate (truncate x)) -> (truncate x) 12011 if (N0.getOpcode() == ISD::TRUNCATE) 12012 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 12013 12014 // fold (truncate c1) -> c1 12015 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 12016 SDValue C = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 12017 if (C.getNode() != N) 12018 return C; 12019 } 12020 12021 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 12022 if (N0.getOpcode() == ISD::ZERO_EXTEND || 12023 N0.getOpcode() == ISD::SIGN_EXTEND || 12024 N0.getOpcode() == ISD::ANY_EXTEND) { 12025 // if the source is smaller than the dest, we still need an extend. 12026 if (N0.getOperand(0).getValueType().bitsLT(VT)) 12027 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 12028 // if the source is larger than the dest, than we just need the truncate. 12029 if (N0.getOperand(0).getValueType().bitsGT(VT)) 12030 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 12031 // if the source and dest are the same type, we can drop both the extend 12032 // and the truncate. 12033 return N0.getOperand(0); 12034 } 12035 12036 // If this is anyext(trunc), don't fold it, allow ourselves to be folded. 12037 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND)) 12038 return SDValue(); 12039 12040 // Fold extract-and-trunc into a narrow extract. For example: 12041 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 12042 // i32 y = TRUNCATE(i64 x) 12043 // -- becomes -- 12044 // v16i8 b = BITCAST (v2i64 val) 12045 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 12046 // 12047 // Note: We only run this optimization after type legalization (which often 12048 // creates this pattern) and before operation legalization after which 12049 // we need to be more careful about the vector instructions that we generate. 12050 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 12051 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 12052 EVT VecTy = N0.getOperand(0).getValueType(); 12053 EVT ExTy = N0.getValueType(); 12054 EVT TrTy = N->getValueType(0); 12055 12056 auto EltCnt = VecTy.getVectorElementCount(); 12057 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 12058 auto NewEltCnt = EltCnt * SizeRatio; 12059 12060 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, NewEltCnt); 12061 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 12062 12063 SDValue EltNo = N0->getOperand(1); 12064 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 12065 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12066 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 12067 12068 SDLoc DL(N); 12069 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 12070 DAG.getBitcast(NVT, N0.getOperand(0)), 12071 DAG.getVectorIdxConstant(Index, DL)); 12072 } 12073 } 12074 12075 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 12076 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) { 12077 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 12078 TLI.isTruncateFree(SrcVT, VT)) { 12079 SDLoc SL(N0); 12080 SDValue Cond = N0.getOperand(0); 12081 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 12082 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 12083 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 12084 } 12085 } 12086 12087 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits() 12088 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 12089 (!LegalOperations || TLI.isOperationLegal(ISD::SHL, VT)) && 12090 TLI.isTypeDesirableForOp(ISD::SHL, VT)) { 12091 SDValue Amt = N0.getOperand(1); 12092 KnownBits Known = DAG.computeKnownBits(Amt); 12093 unsigned Size = VT.getScalarSizeInBits(); 12094 if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) { 12095 SDLoc SL(N); 12096 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 12097 12098 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 12099 if (AmtVT != Amt.getValueType()) { 12100 Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT); 12101 AddToWorklist(Amt.getNode()); 12102 } 12103 return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt); 12104 } 12105 } 12106 12107 if (SDValue V = foldSubToUSubSat(VT, N0.getNode())) 12108 return V; 12109 12110 // Attempt to pre-truncate BUILD_VECTOR sources. 12111 if (N0.getOpcode() == ISD::BUILD_VECTOR && !LegalOperations && 12112 TLI.isTruncateFree(SrcVT.getScalarType(), VT.getScalarType()) && 12113 // Avoid creating illegal types if running after type legalizer. 12114 (!LegalTypes || TLI.isTypeLegal(VT.getScalarType()))) { 12115 SDLoc DL(N); 12116 EVT SVT = VT.getScalarType(); 12117 SmallVector<SDValue, 8> TruncOps; 12118 for (const SDValue &Op : N0->op_values()) { 12119 SDValue TruncOp = DAG.getNode(ISD::TRUNCATE, DL, SVT, Op); 12120 TruncOps.push_back(TruncOp); 12121 } 12122 return DAG.getBuildVector(VT, DL, TruncOps); 12123 } 12124 12125 // Fold a series of buildvector, bitcast, and truncate if possible. 12126 // For example fold 12127 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 12128 // (2xi32 (buildvector x, y)). 12129 if (Level == AfterLegalizeVectorOps && VT.isVector() && 12130 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 12131 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 12132 N0.getOperand(0).hasOneUse()) { 12133 SDValue BuildVect = N0.getOperand(0); 12134 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 12135 EVT TruncVecEltTy = VT.getVectorElementType(); 12136 12137 // Check that the element types match. 12138 if (BuildVectEltTy == TruncVecEltTy) { 12139 // Now we only need to compute the offset of the truncated elements. 12140 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 12141 unsigned TruncVecNumElts = VT.getVectorNumElements(); 12142 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 12143 12144 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 12145 "Invalid number of elements"); 12146 12147 SmallVector<SDValue, 8> Opnds; 12148 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 12149 Opnds.push_back(BuildVect.getOperand(i)); 12150 12151 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 12152 } 12153 } 12154 12155 // See if we can simplify the input to this truncate through knowledge that 12156 // only the low bits are being used. 12157 // For example "trunc (or (shl x, 8), y)" // -> trunc y 12158 // Currently we only perform this optimization on scalars because vectors 12159 // may have different active low bits. 12160 if (!VT.isVector()) { 12161 APInt Mask = 12162 APInt::getLowBitsSet(N0.getValueSizeInBits(), VT.getSizeInBits()); 12163 if (SDValue Shorter = DAG.GetDemandedBits(N0, Mask)) 12164 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 12165 } 12166 12167 // fold (truncate (load x)) -> (smaller load x) 12168 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 12169 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 12170 if (SDValue Reduced = ReduceLoadWidth(N)) 12171 return Reduced; 12172 12173 // Handle the case where the load remains an extending load even 12174 // after truncation. 12175 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 12176 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 12177 if (LN0->isSimple() && LN0->getMemoryVT().bitsLT(VT)) { 12178 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 12179 VT, LN0->getChain(), LN0->getBasePtr(), 12180 LN0->getMemoryVT(), 12181 LN0->getMemOperand()); 12182 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 12183 return NewLoad; 12184 } 12185 } 12186 } 12187 12188 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 12189 // where ... are all 'undef'. 12190 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 12191 SmallVector<EVT, 8> VTs; 12192 SDValue V; 12193 unsigned Idx = 0; 12194 unsigned NumDefs = 0; 12195 12196 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 12197 SDValue X = N0.getOperand(i); 12198 if (!X.isUndef()) { 12199 V = X; 12200 Idx = i; 12201 NumDefs++; 12202 } 12203 // Stop if more than one members are non-undef. 12204 if (NumDefs > 1) 12205 break; 12206 12207 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 12208 VT.getVectorElementType(), 12209 X.getValueType().getVectorElementCount())); 12210 } 12211 12212 if (NumDefs == 0) 12213 return DAG.getUNDEF(VT); 12214 12215 if (NumDefs == 1) { 12216 assert(V.getNode() && "The single defined operand is empty!"); 12217 SmallVector<SDValue, 8> Opnds; 12218 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 12219 if (i != Idx) { 12220 Opnds.push_back(DAG.getUNDEF(VTs[i])); 12221 continue; 12222 } 12223 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 12224 AddToWorklist(NV.getNode()); 12225 Opnds.push_back(NV); 12226 } 12227 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 12228 } 12229 } 12230 12231 // Fold truncate of a bitcast of a vector to an extract of the low vector 12232 // element. 12233 // 12234 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx 12235 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 12236 SDValue VecSrc = N0.getOperand(0); 12237 EVT VecSrcVT = VecSrc.getValueType(); 12238 if (VecSrcVT.isVector() && VecSrcVT.getScalarType() == VT && 12239 (!LegalOperations || 12240 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VecSrcVT))) { 12241 SDLoc SL(N); 12242 12243 unsigned Idx = isLE ? 0 : VecSrcVT.getVectorNumElements() - 1; 12244 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, VecSrc, 12245 DAG.getVectorIdxConstant(Idx, SL)); 12246 } 12247 } 12248 12249 // Simplify the operands using demanded-bits information. 12250 if (SimplifyDemandedBits(SDValue(N, 0))) 12251 return SDValue(N, 0); 12252 12253 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry) 12254 // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry) 12255 // When the adde's carry is not used. 12256 if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) && 12257 N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) && 12258 // We only do for addcarry before legalize operation 12259 ((!LegalOperations && N0.getOpcode() == ISD::ADDCARRY) || 12260 TLI.isOperationLegal(N0.getOpcode(), VT))) { 12261 SDLoc SL(N); 12262 auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 12263 auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 12264 auto VTs = DAG.getVTList(VT, N0->getValueType(1)); 12265 return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2)); 12266 } 12267 12268 // fold (truncate (extract_subvector(ext x))) -> 12269 // (extract_subvector x) 12270 // TODO: This can be generalized to cover cases where the truncate and extract 12271 // do not fully cancel each other out. 12272 if (!LegalTypes && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) { 12273 SDValue N00 = N0.getOperand(0); 12274 if (N00.getOpcode() == ISD::SIGN_EXTEND || 12275 N00.getOpcode() == ISD::ZERO_EXTEND || 12276 N00.getOpcode() == ISD::ANY_EXTEND) { 12277 if (N00.getOperand(0)->getValueType(0).getVectorElementType() == 12278 VT.getVectorElementType()) 12279 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N0->getOperand(0)), VT, 12280 N00.getOperand(0), N0.getOperand(1)); 12281 } 12282 } 12283 12284 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 12285 return NewVSel; 12286 12287 // Narrow a suitable binary operation with a non-opaque constant operand by 12288 // moving it ahead of the truncate. This is limited to pre-legalization 12289 // because targets may prefer a wider type during later combines and invert 12290 // this transform. 12291 switch (N0.getOpcode()) { 12292 case ISD::ADD: 12293 case ISD::SUB: 12294 case ISD::MUL: 12295 case ISD::AND: 12296 case ISD::OR: 12297 case ISD::XOR: 12298 if (!LegalOperations && N0.hasOneUse() && 12299 (isConstantOrConstantVector(N0.getOperand(0), true) || 12300 isConstantOrConstantVector(N0.getOperand(1), true))) { 12301 // TODO: We already restricted this to pre-legalization, but for vectors 12302 // we are extra cautious to not create an unsupported operation. 12303 // Target-specific changes are likely needed to avoid regressions here. 12304 if (VT.isScalarInteger() || TLI.isOperationLegal(N0.getOpcode(), VT)) { 12305 SDLoc DL(N); 12306 SDValue NarrowL = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(0)); 12307 SDValue NarrowR = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(1)); 12308 return DAG.getNode(N0.getOpcode(), DL, VT, NarrowL, NarrowR); 12309 } 12310 } 12311 break; 12312 case ISD::USUBSAT: 12313 // Truncate the USUBSAT only if LHS is a known zero-extension, its not 12314 // enough to know that the upper bits are zero we must ensure that we don't 12315 // introduce an extra truncate. 12316 if (!LegalOperations && N0.hasOneUse() && 12317 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 12318 N0.getOperand(0).getOperand(0).getScalarValueSizeInBits() <= 12319 VT.getScalarSizeInBits() && 12320 hasOperation(N0.getOpcode(), VT)) { 12321 return getTruncatedUSUBSAT(VT, SrcVT, N0.getOperand(0), N0.getOperand(1), 12322 DAG, SDLoc(N)); 12323 } 12324 break; 12325 } 12326 12327 return SDValue(); 12328 } 12329 12330 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 12331 SDValue Elt = N->getOperand(i); 12332 if (Elt.getOpcode() != ISD::MERGE_VALUES) 12333 return Elt.getNode(); 12334 return Elt.getOperand(Elt.getResNo()).getNode(); 12335 } 12336 12337 /// build_pair (load, load) -> load 12338 /// if load locations are consecutive. 12339 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 12340 assert(N->getOpcode() == ISD::BUILD_PAIR); 12341 12342 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 12343 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 12344 12345 // A BUILD_PAIR is always having the least significant part in elt 0 and the 12346 // most significant part in elt 1. So when combining into one large load, we 12347 // need to consider the endianness. 12348 if (DAG.getDataLayout().isBigEndian()) 12349 std::swap(LD1, LD2); 12350 12351 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 12352 LD1->getAddressSpace() != LD2->getAddressSpace()) 12353 return SDValue(); 12354 EVT LD1VT = LD1->getValueType(0); 12355 unsigned LD1Bytes = LD1VT.getStoreSize(); 12356 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && 12357 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { 12358 Align Alignment = LD1->getAlign(); 12359 Align NewAlign = DAG.getDataLayout().getABITypeAlign( 12360 VT.getTypeForEVT(*DAG.getContext())); 12361 12362 if (NewAlign <= Alignment && 12363 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 12364 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(), 12365 LD1->getPointerInfo(), Alignment); 12366 } 12367 12368 return SDValue(); 12369 } 12370 12371 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 12372 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 12373 // and Lo parts; on big-endian machines it doesn't. 12374 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 12375 } 12376 12377 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG, 12378 const TargetLowering &TLI) { 12379 // If this is not a bitcast to an FP type or if the target doesn't have 12380 // IEEE754-compliant FP logic, we're done. 12381 EVT VT = N->getValueType(0); 12382 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT)) 12383 return SDValue(); 12384 12385 // TODO: Handle cases where the integer constant is a different scalar 12386 // bitwidth to the FP. 12387 SDValue N0 = N->getOperand(0); 12388 EVT SourceVT = N0.getValueType(); 12389 if (VT.getScalarSizeInBits() != SourceVT.getScalarSizeInBits()) 12390 return SDValue(); 12391 12392 unsigned FPOpcode; 12393 APInt SignMask; 12394 switch (N0.getOpcode()) { 12395 case ISD::AND: 12396 FPOpcode = ISD::FABS; 12397 SignMask = ~APInt::getSignMask(SourceVT.getScalarSizeInBits()); 12398 break; 12399 case ISD::XOR: 12400 FPOpcode = ISD::FNEG; 12401 SignMask = APInt::getSignMask(SourceVT.getScalarSizeInBits()); 12402 break; 12403 case ISD::OR: 12404 FPOpcode = ISD::FABS; 12405 SignMask = APInt::getSignMask(SourceVT.getScalarSizeInBits()); 12406 break; 12407 default: 12408 return SDValue(); 12409 } 12410 12411 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X 12412 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X 12413 // Fold (bitcast int (or (bitcast fp X to int), 0x8000...) to fp) -> 12414 // fneg (fabs X) 12415 SDValue LogicOp0 = N0.getOperand(0); 12416 ConstantSDNode *LogicOp1 = isConstOrConstSplat(N0.getOperand(1), true); 12417 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask && 12418 LogicOp0.getOpcode() == ISD::BITCAST && 12419 LogicOp0.getOperand(0).getValueType() == VT) { 12420 SDValue FPOp = DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0.getOperand(0)); 12421 NumFPLogicOpsConv++; 12422 if (N0.getOpcode() == ISD::OR) 12423 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, FPOp); 12424 return FPOp; 12425 } 12426 12427 return SDValue(); 12428 } 12429 12430 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 12431 SDValue N0 = N->getOperand(0); 12432 EVT VT = N->getValueType(0); 12433 12434 if (N0.isUndef()) 12435 return DAG.getUNDEF(VT); 12436 12437 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 12438 // Only do this before legalize types, unless both types are integer and the 12439 // scalar type is legal. Only do this before legalize ops, since the target 12440 // maybe depending on the bitcast. 12441 // First check to see if this is all constant. 12442 // TODO: Support FP bitcasts after legalize types. 12443 if (VT.isVector() && 12444 (!LegalTypes || 12445 (!LegalOperations && VT.isInteger() && N0.getValueType().isInteger() && 12446 TLI.isTypeLegal(VT.getVectorElementType()))) && 12447 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 12448 cast<BuildVectorSDNode>(N0)->isConstant()) 12449 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), 12450 VT.getVectorElementType()); 12451 12452 // If the input is a constant, let getNode fold it. 12453 if (isIntOrFPConstant(N0)) { 12454 // If we can't allow illegal operations, we need to check that this is just 12455 // a fp -> int or int -> conversion and that the resulting operation will 12456 // be legal. 12457 if (!LegalOperations || 12458 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 12459 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 12460 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 12461 TLI.isOperationLegal(ISD::Constant, VT))) { 12462 SDValue C = DAG.getBitcast(VT, N0); 12463 if (C.getNode() != N) 12464 return C; 12465 } 12466 } 12467 12468 // (conv (conv x, t1), t2) -> (conv x, t2) 12469 if (N0.getOpcode() == ISD::BITCAST) 12470 return DAG.getBitcast(VT, N0.getOperand(0)); 12471 12472 // fold (conv (load x)) -> (load (conv*)x) 12473 // If the resultant load doesn't need a higher alignment than the original! 12474 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 12475 // Do not remove the cast if the types differ in endian layout. 12476 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 12477 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 12478 // If the load is volatile, we only want to change the load type if the 12479 // resulting load is legal. Otherwise we might increase the number of 12480 // memory accesses. We don't care if the original type was legal or not 12481 // as we assume software couldn't rely on the number of accesses of an 12482 // illegal type. 12483 ((!LegalOperations && cast<LoadSDNode>(N0)->isSimple()) || 12484 TLI.isOperationLegal(ISD::LOAD, VT))) { 12485 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 12486 12487 if (TLI.isLoadBitCastBeneficial(N0.getValueType(), VT, DAG, 12488 *LN0->getMemOperand())) { 12489 SDValue Load = 12490 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 12491 LN0->getPointerInfo(), LN0->getAlign(), 12492 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 12493 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 12494 return Load; 12495 } 12496 } 12497 12498 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI)) 12499 return V; 12500 12501 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 12502 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 12503 // 12504 // For ppc_fp128: 12505 // fold (bitcast (fneg x)) -> 12506 // flipbit = signbit 12507 // (xor (bitcast x) (build_pair flipbit, flipbit)) 12508 // 12509 // fold (bitcast (fabs x)) -> 12510 // flipbit = (and (extract_element (bitcast x), 0), signbit) 12511 // (xor (bitcast x) (build_pair flipbit, flipbit)) 12512 // This often reduces constant pool loads. 12513 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 12514 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 12515 N0.getNode()->hasOneUse() && VT.isInteger() && 12516 !VT.isVector() && !N0.getValueType().isVector()) { 12517 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0)); 12518 AddToWorklist(NewConv.getNode()); 12519 12520 SDLoc DL(N); 12521 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 12522 assert(VT.getSizeInBits() == 128); 12523 SDValue SignBit = DAG.getConstant( 12524 APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 12525 SDValue FlipBit; 12526 if (N0.getOpcode() == ISD::FNEG) { 12527 FlipBit = SignBit; 12528 AddToWorklist(FlipBit.getNode()); 12529 } else { 12530 assert(N0.getOpcode() == ISD::FABS); 12531 SDValue Hi = 12532 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 12533 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 12534 SDLoc(NewConv))); 12535 AddToWorklist(Hi.getNode()); 12536 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 12537 AddToWorklist(FlipBit.getNode()); 12538 } 12539 SDValue FlipBits = 12540 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 12541 AddToWorklist(FlipBits.getNode()); 12542 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 12543 } 12544 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 12545 if (N0.getOpcode() == ISD::FNEG) 12546 return DAG.getNode(ISD::XOR, DL, VT, 12547 NewConv, DAG.getConstant(SignBit, DL, VT)); 12548 assert(N0.getOpcode() == ISD::FABS); 12549 return DAG.getNode(ISD::AND, DL, VT, 12550 NewConv, DAG.getConstant(~SignBit, DL, VT)); 12551 } 12552 12553 // fold (bitconvert (fcopysign cst, x)) -> 12554 // (or (and (bitconvert x), sign), (and cst, (not sign))) 12555 // Note that we don't handle (copysign x, cst) because this can always be 12556 // folded to an fneg or fabs. 12557 // 12558 // For ppc_fp128: 12559 // fold (bitcast (fcopysign cst, x)) -> 12560 // flipbit = (and (extract_element 12561 // (xor (bitcast cst), (bitcast x)), 0), 12562 // signbit) 12563 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 12564 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 12565 isa<ConstantFPSDNode>(N0.getOperand(0)) && 12566 VT.isInteger() && !VT.isVector()) { 12567 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits(); 12568 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 12569 if (isTypeLegal(IntXVT)) { 12570 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1)); 12571 AddToWorklist(X.getNode()); 12572 12573 // If X has a different width than the result/lhs, sext it or truncate it. 12574 unsigned VTWidth = VT.getSizeInBits(); 12575 if (OrigXWidth < VTWidth) { 12576 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 12577 AddToWorklist(X.getNode()); 12578 } else if (OrigXWidth > VTWidth) { 12579 // To get the sign bit in the right place, we have to shift it right 12580 // before truncating. 12581 SDLoc DL(X); 12582 X = DAG.getNode(ISD::SRL, DL, 12583 X.getValueType(), X, 12584 DAG.getConstant(OrigXWidth-VTWidth, DL, 12585 X.getValueType())); 12586 AddToWorklist(X.getNode()); 12587 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 12588 AddToWorklist(X.getNode()); 12589 } 12590 12591 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 12592 APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2); 12593 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 12594 AddToWorklist(Cst.getNode()); 12595 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 12596 AddToWorklist(X.getNode()); 12597 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 12598 AddToWorklist(XorResult.getNode()); 12599 SDValue XorResult64 = DAG.getNode( 12600 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 12601 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 12602 SDLoc(XorResult))); 12603 AddToWorklist(XorResult64.getNode()); 12604 SDValue FlipBit = 12605 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 12606 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 12607 AddToWorklist(FlipBit.getNode()); 12608 SDValue FlipBits = 12609 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 12610 AddToWorklist(FlipBits.getNode()); 12611 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 12612 } 12613 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 12614 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 12615 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 12616 AddToWorklist(X.getNode()); 12617 12618 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 12619 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 12620 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 12621 AddToWorklist(Cst.getNode()); 12622 12623 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 12624 } 12625 } 12626 12627 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 12628 if (N0.getOpcode() == ISD::BUILD_PAIR) 12629 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 12630 return CombineLD; 12631 12632 // Remove double bitcasts from shuffles - this is often a legacy of 12633 // XformToShuffleWithZero being used to combine bitmaskings (of 12634 // float vectors bitcast to integer vectors) into shuffles. 12635 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 12636 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 12637 N0->getOpcode() == ISD::VECTOR_SHUFFLE && N0.hasOneUse() && 12638 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 12639 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 12640 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 12641 12642 // If operands are a bitcast, peek through if it casts the original VT. 12643 // If operands are a constant, just bitcast back to original VT. 12644 auto PeekThroughBitcast = [&](SDValue Op) { 12645 if (Op.getOpcode() == ISD::BITCAST && 12646 Op.getOperand(0).getValueType() == VT) 12647 return SDValue(Op.getOperand(0)); 12648 if (Op.isUndef() || ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 12649 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 12650 return DAG.getBitcast(VT, Op); 12651 return SDValue(); 12652 }; 12653 12654 // FIXME: If either input vector is bitcast, try to convert the shuffle to 12655 // the result type of this bitcast. This would eliminate at least one 12656 // bitcast. See the transform in InstCombine. 12657 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 12658 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 12659 if (!(SV0 && SV1)) 12660 return SDValue(); 12661 12662 int MaskScale = 12663 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 12664 SmallVector<int, 8> NewMask; 12665 for (int M : SVN->getMask()) 12666 for (int i = 0; i != MaskScale; ++i) 12667 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 12668 12669 SDValue LegalShuffle = 12670 TLI.buildLegalVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask, DAG); 12671 if (LegalShuffle) 12672 return LegalShuffle; 12673 } 12674 12675 return SDValue(); 12676 } 12677 12678 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 12679 EVT VT = N->getValueType(0); 12680 return CombineConsecutiveLoads(N, VT); 12681 } 12682 12683 SDValue DAGCombiner::visitFREEZE(SDNode *N) { 12684 SDValue N0 = N->getOperand(0); 12685 12686 // (freeze (freeze x)) -> (freeze x) 12687 if (N0.getOpcode() == ISD::FREEZE) 12688 return N0; 12689 12690 // If the input is a constant, return it. 12691 if (isIntOrFPConstant(N0)) 12692 return N0; 12693 12694 return SDValue(); 12695 } 12696 12697 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 12698 /// operands. DstEltVT indicates the destination element value type. 12699 SDValue DAGCombiner:: 12700 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 12701 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 12702 12703 // If this is already the right type, we're done. 12704 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 12705 12706 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 12707 unsigned DstBitSize = DstEltVT.getSizeInBits(); 12708 12709 // If this is a conversion of N elements of one type to N elements of another 12710 // type, convert each element. This handles FP<->INT cases. 12711 if (SrcBitSize == DstBitSize) { 12712 SmallVector<SDValue, 8> Ops; 12713 for (SDValue Op : BV->op_values()) { 12714 // If the vector element type is not legal, the BUILD_VECTOR operands 12715 // are promoted and implicitly truncated. Make that explicit here. 12716 if (Op.getValueType() != SrcEltVT) 12717 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 12718 Ops.push_back(DAG.getBitcast(DstEltVT, Op)); 12719 AddToWorklist(Ops.back().getNode()); 12720 } 12721 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 12722 BV->getValueType(0).getVectorNumElements()); 12723 return DAG.getBuildVector(VT, SDLoc(BV), Ops); 12724 } 12725 12726 // Otherwise, we're growing or shrinking the elements. To avoid having to 12727 // handle annoying details of growing/shrinking FP values, we convert them to 12728 // int first. 12729 if (SrcEltVT.isFloatingPoint()) { 12730 // Convert the input float vector to a int vector where the elements are the 12731 // same sizes. 12732 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 12733 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 12734 SrcEltVT = IntVT; 12735 } 12736 12737 // Now we know the input is an integer vector. If the output is a FP type, 12738 // convert to integer first, then to FP of the right size. 12739 if (DstEltVT.isFloatingPoint()) { 12740 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 12741 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 12742 12743 // Next, convert to FP elements of the same size. 12744 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 12745 } 12746 12747 SDLoc DL(BV); 12748 12749 // Okay, we know the src/dst types are both integers of differing types. 12750 // Handling growing first. 12751 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 12752 if (SrcBitSize < DstBitSize) { 12753 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 12754 12755 SmallVector<SDValue, 8> Ops; 12756 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 12757 i += NumInputsPerOutput) { 12758 bool isLE = DAG.getDataLayout().isLittleEndian(); 12759 APInt NewBits = APInt(DstBitSize, 0); 12760 bool EltIsUndef = true; 12761 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 12762 // Shift the previously computed bits over. 12763 NewBits <<= SrcBitSize; 12764 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 12765 if (Op.isUndef()) continue; 12766 EltIsUndef = false; 12767 12768 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 12769 zextOrTrunc(SrcBitSize).zext(DstBitSize); 12770 } 12771 12772 if (EltIsUndef) 12773 Ops.push_back(DAG.getUNDEF(DstEltVT)); 12774 else 12775 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 12776 } 12777 12778 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 12779 return DAG.getBuildVector(VT, DL, Ops); 12780 } 12781 12782 // Finally, this must be the case where we are shrinking elements: each input 12783 // turns into multiple outputs. 12784 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 12785 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 12786 NumOutputsPerInput*BV->getNumOperands()); 12787 SmallVector<SDValue, 8> Ops; 12788 12789 for (const SDValue &Op : BV->op_values()) { 12790 if (Op.isUndef()) { 12791 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 12792 continue; 12793 } 12794 12795 APInt OpVal = cast<ConstantSDNode>(Op)-> 12796 getAPIntValue().zextOrTrunc(SrcBitSize); 12797 12798 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 12799 APInt ThisVal = OpVal.trunc(DstBitSize); 12800 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 12801 OpVal.lshrInPlace(DstBitSize); 12802 } 12803 12804 // For big endian targets, swap the order of the pieces of each element. 12805 if (DAG.getDataLayout().isBigEndian()) 12806 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 12807 } 12808 12809 return DAG.getBuildVector(VT, DL, Ops); 12810 } 12811 12812 static bool isContractable(SDNode *N) { 12813 SDNodeFlags F = N->getFlags(); 12814 return F.hasAllowContract() || F.hasAllowReassociation(); 12815 } 12816 12817 /// Try to perform FMA combining on a given FADD node. 12818 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 12819 SDValue N0 = N->getOperand(0); 12820 SDValue N1 = N->getOperand(1); 12821 EVT VT = N->getValueType(0); 12822 SDLoc SL(N); 12823 12824 const TargetOptions &Options = DAG.getTarget().Options; 12825 12826 // Floating-point multiply-add with intermediate rounding. 12827 bool HasFMAD = (LegalOperations && TLI.isFMADLegal(DAG, N)); 12828 12829 // Floating-point multiply-add without intermediate rounding. 12830 bool HasFMA = 12831 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT) && 12832 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 12833 12834 // No valid opcode, do not combine. 12835 if (!HasFMAD && !HasFMA) 12836 return SDValue(); 12837 12838 bool CanFuse = Options.UnsafeFPMath || isContractable(N); 12839 bool CanReassociate = 12840 Options.UnsafeFPMath || N->getFlags().hasAllowReassociation(); 12841 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 12842 CanFuse || HasFMAD); 12843 // If the addition is not contractable, do not combine. 12844 if (!AllowFusionGlobally && !isContractable(N)) 12845 return SDValue(); 12846 12847 if (TLI.generateFMAsInMachineCombiner(VT, OptLevel)) 12848 return SDValue(); 12849 12850 // Always prefer FMAD to FMA for precision. 12851 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 12852 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 12853 12854 // Is the node an FMUL and contractable either due to global flags or 12855 // SDNodeFlags. 12856 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 12857 if (N.getOpcode() != ISD::FMUL) 12858 return false; 12859 return AllowFusionGlobally || isContractable(N.getNode()); 12860 }; 12861 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 12862 // prefer to fold the multiply with fewer uses. 12863 if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) { 12864 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 12865 std::swap(N0, N1); 12866 } 12867 12868 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 12869 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 12870 return DAG.getNode(PreferredFusedOpcode, SL, VT, N0.getOperand(0), 12871 N0.getOperand(1), N1); 12872 } 12873 12874 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 12875 // Note: Commutes FADD operands. 12876 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) { 12877 return DAG.getNode(PreferredFusedOpcode, SL, VT, N1.getOperand(0), 12878 N1.getOperand(1), N0); 12879 } 12880 12881 // fadd (fma A, B, (fmul C, D)), E --> fma A, B, (fma C, D, E) 12882 // fadd E, (fma A, B, (fmul C, D)) --> fma A, B, (fma C, D, E) 12883 // This requires reassociation because it changes the order of operations. 12884 SDValue FMA, E; 12885 if (CanReassociate && N0.getOpcode() == PreferredFusedOpcode && 12886 N0.getOperand(2).getOpcode() == ISD::FMUL && N0.hasOneUse() && 12887 N0.getOperand(2).hasOneUse()) { 12888 FMA = N0; 12889 E = N1; 12890 } else if (CanReassociate && N1.getOpcode() == PreferredFusedOpcode && 12891 N1.getOperand(2).getOpcode() == ISD::FMUL && N1.hasOneUse() && 12892 N1.getOperand(2).hasOneUse()) { 12893 FMA = N1; 12894 E = N0; 12895 } 12896 if (FMA && E) { 12897 SDValue A = FMA.getOperand(0); 12898 SDValue B = FMA.getOperand(1); 12899 SDValue C = FMA.getOperand(2).getOperand(0); 12900 SDValue D = FMA.getOperand(2).getOperand(1); 12901 SDValue CDE = DAG.getNode(PreferredFusedOpcode, SL, VT, C, D, E); 12902 return DAG.getNode(PreferredFusedOpcode, SL, VT, A, B, CDE); 12903 } 12904 12905 // Look through FP_EXTEND nodes to do more combining. 12906 12907 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 12908 if (N0.getOpcode() == ISD::FP_EXTEND) { 12909 SDValue N00 = N0.getOperand(0); 12910 if (isContractableFMUL(N00) && 12911 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 12912 N00.getValueType())) { 12913 return DAG.getNode(PreferredFusedOpcode, SL, VT, 12914 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(0)), 12915 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(1)), 12916 N1); 12917 } 12918 } 12919 12920 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 12921 // Note: Commutes FADD operands. 12922 if (N1.getOpcode() == ISD::FP_EXTEND) { 12923 SDValue N10 = N1.getOperand(0); 12924 if (isContractableFMUL(N10) && 12925 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 12926 N10.getValueType())) { 12927 return DAG.getNode(PreferredFusedOpcode, SL, VT, 12928 DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(0)), 12929 DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(1)), 12930 N0); 12931 } 12932 } 12933 12934 // More folding opportunities when target permits. 12935 if (Aggressive) { 12936 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 12937 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 12938 auto FoldFAddFMAFPExtFMul = [&](SDValue X, SDValue Y, SDValue U, SDValue V, 12939 SDValue Z) { 12940 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 12941 DAG.getNode(PreferredFusedOpcode, SL, VT, 12942 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 12943 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 12944 Z)); 12945 }; 12946 if (N0.getOpcode() == PreferredFusedOpcode) { 12947 SDValue N02 = N0.getOperand(2); 12948 if (N02.getOpcode() == ISD::FP_EXTEND) { 12949 SDValue N020 = N02.getOperand(0); 12950 if (isContractableFMUL(N020) && 12951 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 12952 N020.getValueType())) { 12953 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 12954 N020.getOperand(0), N020.getOperand(1), 12955 N1); 12956 } 12957 } 12958 } 12959 12960 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 12961 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 12962 // FIXME: This turns two single-precision and one double-precision 12963 // operation into two double-precision operations, which might not be 12964 // interesting for all targets, especially GPUs. 12965 auto FoldFAddFPExtFMAFMul = [&](SDValue X, SDValue Y, SDValue U, SDValue V, 12966 SDValue Z) { 12967 return DAG.getNode( 12968 PreferredFusedOpcode, SL, VT, DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 12969 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 12970 DAG.getNode(PreferredFusedOpcode, SL, VT, 12971 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 12972 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), Z)); 12973 }; 12974 if (N0.getOpcode() == ISD::FP_EXTEND) { 12975 SDValue N00 = N0.getOperand(0); 12976 if (N00.getOpcode() == PreferredFusedOpcode) { 12977 SDValue N002 = N00.getOperand(2); 12978 if (isContractableFMUL(N002) && 12979 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 12980 N00.getValueType())) { 12981 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 12982 N002.getOperand(0), N002.getOperand(1), 12983 N1); 12984 } 12985 } 12986 } 12987 12988 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 12989 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 12990 if (N1.getOpcode() == PreferredFusedOpcode) { 12991 SDValue N12 = N1.getOperand(2); 12992 if (N12.getOpcode() == ISD::FP_EXTEND) { 12993 SDValue N120 = N12.getOperand(0); 12994 if (isContractableFMUL(N120) && 12995 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 12996 N120.getValueType())) { 12997 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 12998 N120.getOperand(0), N120.getOperand(1), 12999 N0); 13000 } 13001 } 13002 } 13003 13004 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 13005 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 13006 // FIXME: This turns two single-precision and one double-precision 13007 // operation into two double-precision operations, which might not be 13008 // interesting for all targets, especially GPUs. 13009 if (N1.getOpcode() == ISD::FP_EXTEND) { 13010 SDValue N10 = N1.getOperand(0); 13011 if (N10.getOpcode() == PreferredFusedOpcode) { 13012 SDValue N102 = N10.getOperand(2); 13013 if (isContractableFMUL(N102) && 13014 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 13015 N10.getValueType())) { 13016 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 13017 N102.getOperand(0), N102.getOperand(1), 13018 N0); 13019 } 13020 } 13021 } 13022 } 13023 13024 return SDValue(); 13025 } 13026 13027 /// Try to perform FMA combining on a given FSUB node. 13028 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 13029 SDValue N0 = N->getOperand(0); 13030 SDValue N1 = N->getOperand(1); 13031 EVT VT = N->getValueType(0); 13032 SDLoc SL(N); 13033 13034 const TargetOptions &Options = DAG.getTarget().Options; 13035 // Floating-point multiply-add with intermediate rounding. 13036 bool HasFMAD = (LegalOperations && TLI.isFMADLegal(DAG, N)); 13037 13038 // Floating-point multiply-add without intermediate rounding. 13039 bool HasFMA = 13040 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT) && 13041 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 13042 13043 // No valid opcode, do not combine. 13044 if (!HasFMAD && !HasFMA) 13045 return SDValue(); 13046 13047 const SDNodeFlags Flags = N->getFlags(); 13048 bool CanFuse = Options.UnsafeFPMath || isContractable(N); 13049 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 13050 CanFuse || HasFMAD); 13051 13052 // If the subtraction is not contractable, do not combine. 13053 if (!AllowFusionGlobally && !isContractable(N)) 13054 return SDValue(); 13055 13056 if (TLI.generateFMAsInMachineCombiner(VT, OptLevel)) 13057 return SDValue(); 13058 13059 // Always prefer FMAD to FMA for precision. 13060 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 13061 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 13062 bool NoSignedZero = Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros(); 13063 13064 // Is the node an FMUL and contractable either due to global flags or 13065 // SDNodeFlags. 13066 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 13067 if (N.getOpcode() != ISD::FMUL) 13068 return false; 13069 return AllowFusionGlobally || isContractable(N.getNode()); 13070 }; 13071 13072 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 13073 auto tryToFoldXYSubZ = [&](SDValue XY, SDValue Z) { 13074 if (isContractableFMUL(XY) && (Aggressive || XY->hasOneUse())) { 13075 return DAG.getNode(PreferredFusedOpcode, SL, VT, XY.getOperand(0), 13076 XY.getOperand(1), DAG.getNode(ISD::FNEG, SL, VT, Z)); 13077 } 13078 return SDValue(); 13079 }; 13080 13081 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 13082 // Note: Commutes FSUB operands. 13083 auto tryToFoldXSubYZ = [&](SDValue X, SDValue YZ) { 13084 if (isContractableFMUL(YZ) && (Aggressive || YZ->hasOneUse())) { 13085 return DAG.getNode(PreferredFusedOpcode, SL, VT, 13086 DAG.getNode(ISD::FNEG, SL, VT, YZ.getOperand(0)), 13087 YZ.getOperand(1), X); 13088 } 13089 return SDValue(); 13090 }; 13091 13092 // If we have two choices trying to fold (fsub (fmul u, v), (fmul x, y)), 13093 // prefer to fold the multiply with fewer uses. 13094 if (isContractableFMUL(N0) && isContractableFMUL(N1) && 13095 (N0.getNode()->use_size() > N1.getNode()->use_size())) { 13096 // fold (fsub (fmul a, b), (fmul c, d)) -> (fma (fneg c), d, (fmul a, b)) 13097 if (SDValue V = tryToFoldXSubYZ(N0, N1)) 13098 return V; 13099 // fold (fsub (fmul a, b), (fmul c, d)) -> (fma a, b, (fneg (fmul c, d))) 13100 if (SDValue V = tryToFoldXYSubZ(N0, N1)) 13101 return V; 13102 } else { 13103 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 13104 if (SDValue V = tryToFoldXYSubZ(N0, N1)) 13105 return V; 13106 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 13107 if (SDValue V = tryToFoldXSubYZ(N0, N1)) 13108 return V; 13109 } 13110 13111 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 13112 if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) && 13113 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 13114 SDValue N00 = N0.getOperand(0).getOperand(0); 13115 SDValue N01 = N0.getOperand(0).getOperand(1); 13116 return DAG.getNode(PreferredFusedOpcode, SL, VT, 13117 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 13118 DAG.getNode(ISD::FNEG, SL, VT, N1)); 13119 } 13120 13121 // Look through FP_EXTEND nodes to do more combining. 13122 13123 // fold (fsub (fpext (fmul x, y)), z) 13124 // -> (fma (fpext x), (fpext y), (fneg z)) 13125 if (N0.getOpcode() == ISD::FP_EXTEND) { 13126 SDValue N00 = N0.getOperand(0); 13127 if (isContractableFMUL(N00) && 13128 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 13129 N00.getValueType())) { 13130 return DAG.getNode(PreferredFusedOpcode, SL, VT, 13131 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(0)), 13132 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(1)), 13133 DAG.getNode(ISD::FNEG, SL, VT, N1)); 13134 } 13135 } 13136 13137 // fold (fsub x, (fpext (fmul y, z))) 13138 // -> (fma (fneg (fpext y)), (fpext z), x) 13139 // Note: Commutes FSUB operands. 13140 if (N1.getOpcode() == ISD::FP_EXTEND) { 13141 SDValue N10 = N1.getOperand(0); 13142 if (isContractableFMUL(N10) && 13143 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 13144 N10.getValueType())) { 13145 return DAG.getNode( 13146 PreferredFusedOpcode, SL, VT, 13147 DAG.getNode(ISD::FNEG, SL, VT, 13148 DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(0))), 13149 DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(1)), N0); 13150 } 13151 } 13152 13153 // fold (fsub (fpext (fneg (fmul, x, y))), z) 13154 // -> (fneg (fma (fpext x), (fpext y), z)) 13155 // Note: This could be removed with appropriate canonicalization of the 13156 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 13157 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 13158 // from implementing the canonicalization in visitFSUB. 13159 if (N0.getOpcode() == ISD::FP_EXTEND) { 13160 SDValue N00 = N0.getOperand(0); 13161 if (N00.getOpcode() == ISD::FNEG) { 13162 SDValue N000 = N00.getOperand(0); 13163 if (isContractableFMUL(N000) && 13164 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 13165 N00.getValueType())) { 13166 return DAG.getNode( 13167 ISD::FNEG, SL, VT, 13168 DAG.getNode(PreferredFusedOpcode, SL, VT, 13169 DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(0)), 13170 DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(1)), 13171 N1)); 13172 } 13173 } 13174 } 13175 13176 // fold (fsub (fneg (fpext (fmul, x, y))), z) 13177 // -> (fneg (fma (fpext x)), (fpext y), z) 13178 // Note: This could be removed with appropriate canonicalization of the 13179 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 13180 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 13181 // from implementing the canonicalization in visitFSUB. 13182 if (N0.getOpcode() == ISD::FNEG) { 13183 SDValue N00 = N0.getOperand(0); 13184 if (N00.getOpcode() == ISD::FP_EXTEND) { 13185 SDValue N000 = N00.getOperand(0); 13186 if (isContractableFMUL(N000) && 13187 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 13188 N000.getValueType())) { 13189 return DAG.getNode( 13190 ISD::FNEG, SL, VT, 13191 DAG.getNode(PreferredFusedOpcode, SL, VT, 13192 DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(0)), 13193 DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(1)), 13194 N1)); 13195 } 13196 } 13197 } 13198 13199 // More folding opportunities when target permits. 13200 if (Aggressive) { 13201 // fold (fsub (fma x, y, (fmul u, v)), z) 13202 // -> (fma x, y (fma u, v, (fneg z))) 13203 if (CanFuse && N0.getOpcode() == PreferredFusedOpcode && 13204 isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() && 13205 N0.getOperand(2)->hasOneUse()) { 13206 return DAG.getNode(PreferredFusedOpcode, SL, VT, N0.getOperand(0), 13207 N0.getOperand(1), 13208 DAG.getNode(PreferredFusedOpcode, SL, VT, 13209 N0.getOperand(2).getOperand(0), 13210 N0.getOperand(2).getOperand(1), 13211 DAG.getNode(ISD::FNEG, SL, VT, N1))); 13212 } 13213 13214 // fold (fsub x, (fma y, z, (fmul u, v))) 13215 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 13216 if (CanFuse && N1.getOpcode() == PreferredFusedOpcode && 13217 isContractableFMUL(N1.getOperand(2)) && 13218 N1->hasOneUse() && NoSignedZero) { 13219 SDValue N20 = N1.getOperand(2).getOperand(0); 13220 SDValue N21 = N1.getOperand(2).getOperand(1); 13221 return DAG.getNode( 13222 PreferredFusedOpcode, SL, VT, 13223 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), N1.getOperand(1), 13224 DAG.getNode(PreferredFusedOpcode, SL, VT, 13225 DAG.getNode(ISD::FNEG, SL, VT, N20), N21, N0)); 13226 } 13227 13228 13229 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 13230 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 13231 if (N0.getOpcode() == PreferredFusedOpcode && 13232 N0->hasOneUse()) { 13233 SDValue N02 = N0.getOperand(2); 13234 if (N02.getOpcode() == ISD::FP_EXTEND) { 13235 SDValue N020 = N02.getOperand(0); 13236 if (isContractableFMUL(N020) && 13237 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 13238 N020.getValueType())) { 13239 return DAG.getNode( 13240 PreferredFusedOpcode, SL, VT, N0.getOperand(0), N0.getOperand(1), 13241 DAG.getNode( 13242 PreferredFusedOpcode, SL, VT, 13243 DAG.getNode(ISD::FP_EXTEND, SL, VT, N020.getOperand(0)), 13244 DAG.getNode(ISD::FP_EXTEND, SL, VT, N020.getOperand(1)), 13245 DAG.getNode(ISD::FNEG, SL, VT, N1))); 13246 } 13247 } 13248 } 13249 13250 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 13251 // -> (fma (fpext x), (fpext y), 13252 // (fma (fpext u), (fpext v), (fneg z))) 13253 // FIXME: This turns two single-precision and one double-precision 13254 // operation into two double-precision operations, which might not be 13255 // interesting for all targets, especially GPUs. 13256 if (N0.getOpcode() == ISD::FP_EXTEND) { 13257 SDValue N00 = N0.getOperand(0); 13258 if (N00.getOpcode() == PreferredFusedOpcode) { 13259 SDValue N002 = N00.getOperand(2); 13260 if (isContractableFMUL(N002) && 13261 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 13262 N00.getValueType())) { 13263 return DAG.getNode( 13264 PreferredFusedOpcode, SL, VT, 13265 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(0)), 13266 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(1)), 13267 DAG.getNode( 13268 PreferredFusedOpcode, SL, VT, 13269 DAG.getNode(ISD::FP_EXTEND, SL, VT, N002.getOperand(0)), 13270 DAG.getNode(ISD::FP_EXTEND, SL, VT, N002.getOperand(1)), 13271 DAG.getNode(ISD::FNEG, SL, VT, N1))); 13272 } 13273 } 13274 } 13275 13276 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 13277 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 13278 if (N1.getOpcode() == PreferredFusedOpcode && 13279 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND && 13280 N1->hasOneUse()) { 13281 SDValue N120 = N1.getOperand(2).getOperand(0); 13282 if (isContractableFMUL(N120) && 13283 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 13284 N120.getValueType())) { 13285 SDValue N1200 = N120.getOperand(0); 13286 SDValue N1201 = N120.getOperand(1); 13287 return DAG.getNode( 13288 PreferredFusedOpcode, SL, VT, 13289 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), N1.getOperand(1), 13290 DAG.getNode(PreferredFusedOpcode, SL, VT, 13291 DAG.getNode(ISD::FNEG, SL, VT, 13292 DAG.getNode(ISD::FP_EXTEND, SL, VT, N1200)), 13293 DAG.getNode(ISD::FP_EXTEND, SL, VT, N1201), N0)); 13294 } 13295 } 13296 13297 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 13298 // -> (fma (fneg (fpext y)), (fpext z), 13299 // (fma (fneg (fpext u)), (fpext v), x)) 13300 // FIXME: This turns two single-precision and one double-precision 13301 // operation into two double-precision operations, which might not be 13302 // interesting for all targets, especially GPUs. 13303 if (N1.getOpcode() == ISD::FP_EXTEND && 13304 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 13305 SDValue CvtSrc = N1.getOperand(0); 13306 SDValue N100 = CvtSrc.getOperand(0); 13307 SDValue N101 = CvtSrc.getOperand(1); 13308 SDValue N102 = CvtSrc.getOperand(2); 13309 if (isContractableFMUL(N102) && 13310 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 13311 CvtSrc.getValueType())) { 13312 SDValue N1020 = N102.getOperand(0); 13313 SDValue N1021 = N102.getOperand(1); 13314 return DAG.getNode( 13315 PreferredFusedOpcode, SL, VT, 13316 DAG.getNode(ISD::FNEG, SL, VT, 13317 DAG.getNode(ISD::FP_EXTEND, SL, VT, N100)), 13318 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 13319 DAG.getNode(PreferredFusedOpcode, SL, VT, 13320 DAG.getNode(ISD::FNEG, SL, VT, 13321 DAG.getNode(ISD::FP_EXTEND, SL, VT, N1020)), 13322 DAG.getNode(ISD::FP_EXTEND, SL, VT, N1021), N0)); 13323 } 13324 } 13325 } 13326 13327 return SDValue(); 13328 } 13329 13330 /// Try to perform FMA combining on a given FMUL node based on the distributive 13331 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions, 13332 /// subtraction instead of addition). 13333 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) { 13334 SDValue N0 = N->getOperand(0); 13335 SDValue N1 = N->getOperand(1); 13336 EVT VT = N->getValueType(0); 13337 SDLoc SL(N); 13338 13339 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 13340 13341 const TargetOptions &Options = DAG.getTarget().Options; 13342 13343 // The transforms below are incorrect when x == 0 and y == inf, because the 13344 // intermediate multiplication produces a nan. 13345 if (!Options.NoInfsFPMath) 13346 return SDValue(); 13347 13348 // Floating-point multiply-add without intermediate rounding. 13349 bool HasFMA = 13350 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 13351 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT) && 13352 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 13353 13354 // Floating-point multiply-add with intermediate rounding. This can result 13355 // in a less precise result due to the changed rounding order. 13356 bool HasFMAD = Options.UnsafeFPMath && 13357 (LegalOperations && TLI.isFMADLegal(DAG, N)); 13358 13359 // No valid opcode, do not combine. 13360 if (!HasFMAD && !HasFMA) 13361 return SDValue(); 13362 13363 // Always prefer FMAD to FMA for precision. 13364 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 13365 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 13366 13367 // fold (fmul (fadd x0, +1.0), y) -> (fma x0, y, y) 13368 // fold (fmul (fadd x0, -1.0), y) -> (fma x0, y, (fneg y)) 13369 auto FuseFADD = [&](SDValue X, SDValue Y) { 13370 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 13371 if (auto *C = isConstOrConstSplatFP(X.getOperand(1), true)) { 13372 if (C->isExactlyValue(+1.0)) 13373 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 13374 Y); 13375 if (C->isExactlyValue(-1.0)) 13376 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 13377 DAG.getNode(ISD::FNEG, SL, VT, Y)); 13378 } 13379 } 13380 return SDValue(); 13381 }; 13382 13383 if (SDValue FMA = FuseFADD(N0, N1)) 13384 return FMA; 13385 if (SDValue FMA = FuseFADD(N1, N0)) 13386 return FMA; 13387 13388 // fold (fmul (fsub +1.0, x1), y) -> (fma (fneg x1), y, y) 13389 // fold (fmul (fsub -1.0, x1), y) -> (fma (fneg x1), y, (fneg y)) 13390 // fold (fmul (fsub x0, +1.0), y) -> (fma x0, y, (fneg y)) 13391 // fold (fmul (fsub x0, -1.0), y) -> (fma x0, y, y) 13392 auto FuseFSUB = [&](SDValue X, SDValue Y) { 13393 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 13394 if (auto *C0 = isConstOrConstSplatFP(X.getOperand(0), true)) { 13395 if (C0->isExactlyValue(+1.0)) 13396 return DAG.getNode(PreferredFusedOpcode, SL, VT, 13397 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 13398 Y); 13399 if (C0->isExactlyValue(-1.0)) 13400 return DAG.getNode(PreferredFusedOpcode, SL, VT, 13401 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 13402 DAG.getNode(ISD::FNEG, SL, VT, Y)); 13403 } 13404 if (auto *C1 = isConstOrConstSplatFP(X.getOperand(1), true)) { 13405 if (C1->isExactlyValue(+1.0)) 13406 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 13407 DAG.getNode(ISD::FNEG, SL, VT, Y)); 13408 if (C1->isExactlyValue(-1.0)) 13409 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 13410 Y); 13411 } 13412 } 13413 return SDValue(); 13414 }; 13415 13416 if (SDValue FMA = FuseFSUB(N0, N1)) 13417 return FMA; 13418 if (SDValue FMA = FuseFSUB(N1, N0)) 13419 return FMA; 13420 13421 return SDValue(); 13422 } 13423 13424 SDValue DAGCombiner::visitFADD(SDNode *N) { 13425 SDValue N0 = N->getOperand(0); 13426 SDValue N1 = N->getOperand(1); 13427 bool N0CFP = DAG.isConstantFPBuildVectorOrConstantFP(N0); 13428 bool N1CFP = DAG.isConstantFPBuildVectorOrConstantFP(N1); 13429 EVT VT = N->getValueType(0); 13430 SDLoc DL(N); 13431 const TargetOptions &Options = DAG.getTarget().Options; 13432 SDNodeFlags Flags = N->getFlags(); 13433 SelectionDAG::FlagInserter FlagsInserter(DAG, N); 13434 13435 if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags)) 13436 return R; 13437 13438 // fold vector ops 13439 if (VT.isVector()) 13440 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 13441 return FoldedVOp; 13442 13443 // fold (fadd c1, c2) -> c1 + c2 13444 if (N0CFP && N1CFP) 13445 return DAG.getNode(ISD::FADD, DL, VT, N0, N1); 13446 13447 // canonicalize constant to RHS 13448 if (N0CFP && !N1CFP) 13449 return DAG.getNode(ISD::FADD, DL, VT, N1, N0); 13450 13451 // N0 + -0.0 --> N0 (also allowed with +0.0 and fast-math) 13452 ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, true); 13453 if (N1C && N1C->isZero()) 13454 if (N1C->isNegative() || Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros()) 13455 return N0; 13456 13457 if (SDValue NewSel = foldBinOpIntoSelect(N)) 13458 return NewSel; 13459 13460 // fold (fadd A, (fneg B)) -> (fsub A, B) 13461 if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) 13462 if (SDValue NegN1 = TLI.getCheaperNegatedExpression( 13463 N1, DAG, LegalOperations, ForCodeSize)) 13464 return DAG.getNode(ISD::FSUB, DL, VT, N0, NegN1); 13465 13466 // fold (fadd (fneg A), B) -> (fsub B, A) 13467 if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) 13468 if (SDValue NegN0 = TLI.getCheaperNegatedExpression( 13469 N0, DAG, LegalOperations, ForCodeSize)) 13470 return DAG.getNode(ISD::FSUB, DL, VT, N1, NegN0); 13471 13472 auto isFMulNegTwo = [](SDValue FMul) { 13473 if (!FMul.hasOneUse() || FMul.getOpcode() != ISD::FMUL) 13474 return false; 13475 auto *C = isConstOrConstSplatFP(FMul.getOperand(1), true); 13476 return C && C->isExactlyValue(-2.0); 13477 }; 13478 13479 // fadd (fmul B, -2.0), A --> fsub A, (fadd B, B) 13480 if (isFMulNegTwo(N0)) { 13481 SDValue B = N0.getOperand(0); 13482 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, B, B); 13483 return DAG.getNode(ISD::FSUB, DL, VT, N1, Add); 13484 } 13485 // fadd A, (fmul B, -2.0) --> fsub A, (fadd B, B) 13486 if (isFMulNegTwo(N1)) { 13487 SDValue B = N1.getOperand(0); 13488 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, B, B); 13489 return DAG.getNode(ISD::FSUB, DL, VT, N0, Add); 13490 } 13491 13492 // No FP constant should be created after legalization as Instruction 13493 // Selection pass has a hard time dealing with FP constants. 13494 bool AllowNewConst = (Level < AfterLegalizeDAG); 13495 13496 // If nnan is enabled, fold lots of things. 13497 if ((Options.NoNaNsFPMath || Flags.hasNoNaNs()) && AllowNewConst) { 13498 // If allowed, fold (fadd (fneg x), x) -> 0.0 13499 if (N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 13500 return DAG.getConstantFP(0.0, DL, VT); 13501 13502 // If allowed, fold (fadd x, (fneg x)) -> 0.0 13503 if (N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 13504 return DAG.getConstantFP(0.0, DL, VT); 13505 } 13506 13507 // If 'unsafe math' or reassoc and nsz, fold lots of things. 13508 // TODO: break out portions of the transformations below for which Unsafe is 13509 // considered and which do not require both nsz and reassoc 13510 if (((Options.UnsafeFPMath && Options.NoSignedZerosFPMath) || 13511 (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros())) && 13512 AllowNewConst) { 13513 // fadd (fadd x, c1), c2 -> fadd x, c1 + c2 13514 if (N1CFP && N0.getOpcode() == ISD::FADD && 13515 DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 13516 SDValue NewC = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1); 13517 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), NewC); 13518 } 13519 13520 // We can fold chains of FADD's of the same value into multiplications. 13521 // This transform is not safe in general because we are reducing the number 13522 // of rounding steps. 13523 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 13524 if (N0.getOpcode() == ISD::FMUL) { 13525 bool CFP00 = DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 13526 bool CFP01 = DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 13527 13528 // (fadd (fmul x, c), x) -> (fmul x, c+1) 13529 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 13530 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 13531 DAG.getConstantFP(1.0, DL, VT)); 13532 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP); 13533 } 13534 13535 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 13536 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 13537 N1.getOperand(0) == N1.getOperand(1) && 13538 N0.getOperand(0) == N1.getOperand(0)) { 13539 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 13540 DAG.getConstantFP(2.0, DL, VT)); 13541 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP); 13542 } 13543 } 13544 13545 if (N1.getOpcode() == ISD::FMUL) { 13546 bool CFP10 = DAG.isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 13547 bool CFP11 = DAG.isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 13548 13549 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 13550 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 13551 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 13552 DAG.getConstantFP(1.0, DL, VT)); 13553 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP); 13554 } 13555 13556 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 13557 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 13558 N0.getOperand(0) == N0.getOperand(1) && 13559 N1.getOperand(0) == N0.getOperand(0)) { 13560 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 13561 DAG.getConstantFP(2.0, DL, VT)); 13562 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP); 13563 } 13564 } 13565 13566 if (N0.getOpcode() == ISD::FADD) { 13567 bool CFP00 = DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 13568 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 13569 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 13570 (N0.getOperand(0) == N1)) { 13571 return DAG.getNode(ISD::FMUL, DL, VT, N1, 13572 DAG.getConstantFP(3.0, DL, VT)); 13573 } 13574 } 13575 13576 if (N1.getOpcode() == ISD::FADD) { 13577 bool CFP10 = DAG.isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 13578 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 13579 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 13580 N1.getOperand(0) == N0) { 13581 return DAG.getNode(ISD::FMUL, DL, VT, N0, 13582 DAG.getConstantFP(3.0, DL, VT)); 13583 } 13584 } 13585 13586 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 13587 if (N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 13588 N0.getOperand(0) == N0.getOperand(1) && 13589 N1.getOperand(0) == N1.getOperand(1) && 13590 N0.getOperand(0) == N1.getOperand(0)) { 13591 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 13592 DAG.getConstantFP(4.0, DL, VT)); 13593 } 13594 } 13595 } // enable-unsafe-fp-math 13596 13597 // FADD -> FMA combines: 13598 if (SDValue Fused = visitFADDForFMACombine(N)) { 13599 AddToWorklist(Fused.getNode()); 13600 return Fused; 13601 } 13602 return SDValue(); 13603 } 13604 13605 SDValue DAGCombiner::visitSTRICT_FADD(SDNode *N) { 13606 SDValue Chain = N->getOperand(0); 13607 SDValue N0 = N->getOperand(1); 13608 SDValue N1 = N->getOperand(2); 13609 EVT VT = N->getValueType(0); 13610 EVT ChainVT = N->getValueType(1); 13611 SDLoc DL(N); 13612 SelectionDAG::FlagInserter FlagsInserter(DAG, N); 13613 13614 // fold (strict_fadd A, (fneg B)) -> (strict_fsub A, B) 13615 if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::STRICT_FSUB, VT)) 13616 if (SDValue NegN1 = TLI.getCheaperNegatedExpression( 13617 N1, DAG, LegalOperations, ForCodeSize)) { 13618 return DAG.getNode(ISD::STRICT_FSUB, DL, DAG.getVTList(VT, ChainVT), 13619 {Chain, N0, NegN1}); 13620 } 13621 13622 // fold (strict_fadd (fneg A), B) -> (strict_fsub B, A) 13623 if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::STRICT_FSUB, VT)) 13624 if (SDValue NegN0 = TLI.getCheaperNegatedExpression( 13625 N0, DAG, LegalOperations, ForCodeSize)) { 13626 return DAG.getNode(ISD::STRICT_FSUB, DL, DAG.getVTList(VT, ChainVT), 13627 {Chain, N1, NegN0}); 13628 } 13629 return SDValue(); 13630 } 13631 13632 SDValue DAGCombiner::visitFSUB(SDNode *N) { 13633 SDValue N0 = N->getOperand(0); 13634 SDValue N1 = N->getOperand(1); 13635 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, true); 13636 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, true); 13637 EVT VT = N->getValueType(0); 13638 SDLoc DL(N); 13639 const TargetOptions &Options = DAG.getTarget().Options; 13640 const SDNodeFlags Flags = N->getFlags(); 13641 SelectionDAG::FlagInserter FlagsInserter(DAG, N); 13642 13643 if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags)) 13644 return R; 13645 13646 // fold vector ops 13647 if (VT.isVector()) 13648 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 13649 return FoldedVOp; 13650 13651 // fold (fsub c1, c2) -> c1-c2 13652 if (N0CFP && N1CFP) 13653 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1); 13654 13655 if (SDValue NewSel = foldBinOpIntoSelect(N)) 13656 return NewSel; 13657 13658 // (fsub A, 0) -> A 13659 if (N1CFP && N1CFP->isZero()) { 13660 if (!N1CFP->isNegative() || Options.NoSignedZerosFPMath || 13661 Flags.hasNoSignedZeros()) { 13662 return N0; 13663 } 13664 } 13665 13666 if (N0 == N1) { 13667 // (fsub x, x) -> 0.0 13668 if (Options.NoNaNsFPMath || Flags.hasNoNaNs()) 13669 return DAG.getConstantFP(0.0f, DL, VT); 13670 } 13671 13672 // (fsub -0.0, N1) -> -N1 13673 if (N0CFP && N0CFP->isZero()) { 13674 if (N0CFP->isNegative() || 13675 (Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros())) { 13676 // We cannot replace an FSUB(+-0.0,X) with FNEG(X) when denormals are 13677 // flushed to zero, unless all users treat denorms as zero (DAZ). 13678 // FIXME: This transform will change the sign of a NaN and the behavior 13679 // of a signaling NaN. It is only valid when a NoNaN flag is present. 13680 DenormalMode DenormMode = DAG.getDenormalMode(VT); 13681 if (DenormMode == DenormalMode::getIEEE()) { 13682 if (SDValue NegN1 = 13683 TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize)) 13684 return NegN1; 13685 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 13686 return DAG.getNode(ISD::FNEG, DL, VT, N1); 13687 } 13688 } 13689 } 13690 13691 if (((Options.UnsafeFPMath && Options.NoSignedZerosFPMath) || 13692 (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros())) && 13693 N1.getOpcode() == ISD::FADD) { 13694 // X - (X + Y) -> -Y 13695 if (N0 == N1->getOperand(0)) 13696 return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(1)); 13697 // X - (Y + X) -> -Y 13698 if (N0 == N1->getOperand(1)) 13699 return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(0)); 13700 } 13701 13702 // fold (fsub A, (fneg B)) -> (fadd A, B) 13703 if (SDValue NegN1 = 13704 TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize)) 13705 return DAG.getNode(ISD::FADD, DL, VT, N0, NegN1); 13706 13707 // FSUB -> FMA combines: 13708 if (SDValue Fused = visitFSUBForFMACombine(N)) { 13709 AddToWorklist(Fused.getNode()); 13710 return Fused; 13711 } 13712 13713 return SDValue(); 13714 } 13715 13716 SDValue DAGCombiner::visitFMUL(SDNode *N) { 13717 SDValue N0 = N->getOperand(0); 13718 SDValue N1 = N->getOperand(1); 13719 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, true); 13720 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, true); 13721 EVT VT = N->getValueType(0); 13722 SDLoc DL(N); 13723 const TargetOptions &Options = DAG.getTarget().Options; 13724 const SDNodeFlags Flags = N->getFlags(); 13725 SelectionDAG::FlagInserter FlagsInserter(DAG, N); 13726 13727 if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags)) 13728 return R; 13729 13730 // fold vector ops 13731 if (VT.isVector()) { 13732 // This just handles C1 * C2 for vectors. Other vector folds are below. 13733 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 13734 return FoldedVOp; 13735 } 13736 13737 // fold (fmul c1, c2) -> c1*c2 13738 if (N0CFP && N1CFP) 13739 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1); 13740 13741 // canonicalize constant to RHS 13742 if (DAG.isConstantFPBuildVectorOrConstantFP(N0) && 13743 !DAG.isConstantFPBuildVectorOrConstantFP(N1)) 13744 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0); 13745 13746 if (SDValue NewSel = foldBinOpIntoSelect(N)) 13747 return NewSel; 13748 13749 if (Options.UnsafeFPMath || Flags.hasAllowReassociation()) { 13750 // fmul (fmul X, C1), C2 -> fmul X, C1 * C2 13751 if (DAG.isConstantFPBuildVectorOrConstantFP(N1) && 13752 N0.getOpcode() == ISD::FMUL) { 13753 SDValue N00 = N0.getOperand(0); 13754 SDValue N01 = N0.getOperand(1); 13755 // Avoid an infinite loop by making sure that N00 is not a constant 13756 // (the inner multiply has not been constant folded yet). 13757 if (DAG.isConstantFPBuildVectorOrConstantFP(N01) && 13758 !DAG.isConstantFPBuildVectorOrConstantFP(N00)) { 13759 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1); 13760 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts); 13761 } 13762 } 13763 13764 // Match a special-case: we convert X * 2.0 into fadd. 13765 // fmul (fadd X, X), C -> fmul X, 2.0 * C 13766 if (N0.getOpcode() == ISD::FADD && N0.hasOneUse() && 13767 N0.getOperand(0) == N0.getOperand(1)) { 13768 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 13769 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1); 13770 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts); 13771 } 13772 } 13773 13774 // fold (fmul X, 2.0) -> (fadd X, X) 13775 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 13776 return DAG.getNode(ISD::FADD, DL, VT, N0, N0); 13777 13778 // fold (fmul X, -1.0) -> (fneg X) 13779 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 13780 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 13781 return DAG.getNode(ISD::FNEG, DL, VT, N0); 13782 13783 // -N0 * -N1 --> N0 * N1 13784 TargetLowering::NegatibleCost CostN0 = 13785 TargetLowering::NegatibleCost::Expensive; 13786 TargetLowering::NegatibleCost CostN1 = 13787 TargetLowering::NegatibleCost::Expensive; 13788 SDValue NegN0 = 13789 TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0); 13790 SDValue NegN1 = 13791 TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1); 13792 if (NegN0 && NegN1 && 13793 (CostN0 == TargetLowering::NegatibleCost::Cheaper || 13794 CostN1 == TargetLowering::NegatibleCost::Cheaper)) 13795 return DAG.getNode(ISD::FMUL, DL, VT, NegN0, NegN1); 13796 13797 // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X)) 13798 // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X) 13799 if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() && 13800 (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) && 13801 TLI.isOperationLegal(ISD::FABS, VT)) { 13802 SDValue Select = N0, X = N1; 13803 if (Select.getOpcode() != ISD::SELECT) 13804 std::swap(Select, X); 13805 13806 SDValue Cond = Select.getOperand(0); 13807 auto TrueOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(1)); 13808 auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2)); 13809 13810 if (TrueOpnd && FalseOpnd && 13811 Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X && 13812 isa<ConstantFPSDNode>(Cond.getOperand(1)) && 13813 cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) { 13814 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 13815 switch (CC) { 13816 default: break; 13817 case ISD::SETOLT: 13818 case ISD::SETULT: 13819 case ISD::SETOLE: 13820 case ISD::SETULE: 13821 case ISD::SETLT: 13822 case ISD::SETLE: 13823 std::swap(TrueOpnd, FalseOpnd); 13824 LLVM_FALLTHROUGH; 13825 case ISD::SETOGT: 13826 case ISD::SETUGT: 13827 case ISD::SETOGE: 13828 case ISD::SETUGE: 13829 case ISD::SETGT: 13830 case ISD::SETGE: 13831 if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) && 13832 TLI.isOperationLegal(ISD::FNEG, VT)) 13833 return DAG.getNode(ISD::FNEG, DL, VT, 13834 DAG.getNode(ISD::FABS, DL, VT, X)); 13835 if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0)) 13836 return DAG.getNode(ISD::FABS, DL, VT, X); 13837 13838 break; 13839 } 13840 } 13841 } 13842 13843 // FMUL -> FMA combines: 13844 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) { 13845 AddToWorklist(Fused.getNode()); 13846 return Fused; 13847 } 13848 13849 return SDValue(); 13850 } 13851 13852 SDValue DAGCombiner::visitFMA(SDNode *N) { 13853 SDValue N0 = N->getOperand(0); 13854 SDValue N1 = N->getOperand(1); 13855 SDValue N2 = N->getOperand(2); 13856 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 13857 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 13858 EVT VT = N->getValueType(0); 13859 SDLoc DL(N); 13860 const TargetOptions &Options = DAG.getTarget().Options; 13861 // FMA nodes have flags that propagate to the created nodes. 13862 SelectionDAG::FlagInserter FlagsInserter(DAG, N); 13863 13864 bool UnsafeFPMath = 13865 Options.UnsafeFPMath || N->getFlags().hasAllowReassociation(); 13866 13867 // Constant fold FMA. 13868 if (isa<ConstantFPSDNode>(N0) && 13869 isa<ConstantFPSDNode>(N1) && 13870 isa<ConstantFPSDNode>(N2)) { 13871 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2); 13872 } 13873 13874 // (-N0 * -N1) + N2 --> (N0 * N1) + N2 13875 TargetLowering::NegatibleCost CostN0 = 13876 TargetLowering::NegatibleCost::Expensive; 13877 TargetLowering::NegatibleCost CostN1 = 13878 TargetLowering::NegatibleCost::Expensive; 13879 SDValue NegN0 = 13880 TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0); 13881 SDValue NegN1 = 13882 TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1); 13883 if (NegN0 && NegN1 && 13884 (CostN0 == TargetLowering::NegatibleCost::Cheaper || 13885 CostN1 == TargetLowering::NegatibleCost::Cheaper)) 13886 return DAG.getNode(ISD::FMA, DL, VT, NegN0, NegN1, N2); 13887 13888 if (UnsafeFPMath) { 13889 if (N0CFP && N0CFP->isZero()) 13890 return N2; 13891 if (N1CFP && N1CFP->isZero()) 13892 return N2; 13893 } 13894 13895 if (N0CFP && N0CFP->isExactlyValue(1.0)) 13896 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 13897 if (N1CFP && N1CFP->isExactlyValue(1.0)) 13898 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 13899 13900 // Canonicalize (fma c, x, y) -> (fma x, c, y) 13901 if (DAG.isConstantFPBuildVectorOrConstantFP(N0) && 13902 !DAG.isConstantFPBuildVectorOrConstantFP(N1)) 13903 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 13904 13905 if (UnsafeFPMath) { 13906 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 13907 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 13908 DAG.isConstantFPBuildVectorOrConstantFP(N1) && 13909 DAG.isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 13910 return DAG.getNode(ISD::FMUL, DL, VT, N0, 13911 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1))); 13912 } 13913 13914 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 13915 if (N0.getOpcode() == ISD::FMUL && 13916 DAG.isConstantFPBuildVectorOrConstantFP(N1) && 13917 DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 13918 return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0), 13919 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1)), 13920 N2); 13921 } 13922 } 13923 13924 // (fma x, -1, y) -> (fadd (fneg x), y) 13925 if (N1CFP) { 13926 if (N1CFP->isExactlyValue(1.0)) 13927 return DAG.getNode(ISD::FADD, DL, VT, N0, N2); 13928 13929 if (N1CFP->isExactlyValue(-1.0) && 13930 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 13931 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0); 13932 AddToWorklist(RHSNeg.getNode()); 13933 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg); 13934 } 13935 13936 // fma (fneg x), K, y -> fma x -K, y 13937 if (N0.getOpcode() == ISD::FNEG && 13938 (TLI.isOperationLegal(ISD::ConstantFP, VT) || 13939 (N1.hasOneUse() && !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT, 13940 ForCodeSize)))) { 13941 return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0), 13942 DAG.getNode(ISD::FNEG, DL, VT, N1), N2); 13943 } 13944 } 13945 13946 if (UnsafeFPMath) { 13947 // (fma x, c, x) -> (fmul x, (c+1)) 13948 if (N1CFP && N0 == N2) { 13949 return DAG.getNode( 13950 ISD::FMUL, DL, VT, N0, 13951 DAG.getNode(ISD::FADD, DL, VT, N1, DAG.getConstantFP(1.0, DL, VT))); 13952 } 13953 13954 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 13955 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 13956 return DAG.getNode( 13957 ISD::FMUL, DL, VT, N0, 13958 DAG.getNode(ISD::FADD, DL, VT, N1, DAG.getConstantFP(-1.0, DL, VT))); 13959 } 13960 } 13961 13962 // fold ((fma (fneg X), Y, (fneg Z)) -> fneg (fma X, Y, Z)) 13963 // fold ((fma X, (fneg Y), (fneg Z)) -> fneg (fma X, Y, Z)) 13964 if (!TLI.isFNegFree(VT)) 13965 if (SDValue Neg = TLI.getCheaperNegatedExpression( 13966 SDValue(N, 0), DAG, LegalOperations, ForCodeSize)) 13967 return DAG.getNode(ISD::FNEG, DL, VT, Neg); 13968 return SDValue(); 13969 } 13970 13971 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 13972 // reciprocal. 13973 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 13974 // Notice that this is not always beneficial. One reason is different targets 13975 // may have different costs for FDIV and FMUL, so sometimes the cost of two 13976 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 13977 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 13978 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 13979 // TODO: Limit this transform based on optsize/minsize - it always creates at 13980 // least 1 extra instruction. But the perf win may be substantial enough 13981 // that only minsize should restrict this. 13982 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 13983 const SDNodeFlags Flags = N->getFlags(); 13984 if (LegalDAG || (!UnsafeMath && !Flags.hasAllowReciprocal())) 13985 return SDValue(); 13986 13987 // Skip if current node is a reciprocal/fneg-reciprocal. 13988 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 13989 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, /* AllowUndefs */ true); 13990 if (N0CFP && (N0CFP->isExactlyValue(1.0) || N0CFP->isExactlyValue(-1.0))) 13991 return SDValue(); 13992 13993 // Exit early if the target does not want this transform or if there can't 13994 // possibly be enough uses of the divisor to make the transform worthwhile. 13995 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 13996 13997 // For splat vectors, scale the number of uses by the splat factor. If we can 13998 // convert the division into a scalar op, that will likely be much faster. 13999 unsigned NumElts = 1; 14000 EVT VT = N->getValueType(0); 14001 if (VT.isVector() && DAG.isSplatValue(N1)) 14002 NumElts = VT.getVectorNumElements(); 14003 14004 if (!MinUses || (N1->use_size() * NumElts) < MinUses) 14005 return SDValue(); 14006 14007 // Find all FDIV users of the same divisor. 14008 // Use a set because duplicates may be present in the user list. 14009 SetVector<SDNode *> Users; 14010 for (auto *U : N1->uses()) { 14011 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 14012 // Skip X/sqrt(X) that has not been simplified to sqrt(X) yet. 14013 if (U->getOperand(1).getOpcode() == ISD::FSQRT && 14014 U->getOperand(0) == U->getOperand(1).getOperand(0) && 14015 U->getFlags().hasAllowReassociation() && 14016 U->getFlags().hasNoSignedZeros()) 14017 continue; 14018 14019 // This division is eligible for optimization only if global unsafe math 14020 // is enabled or if this division allows reciprocal formation. 14021 if (UnsafeMath || U->getFlags().hasAllowReciprocal()) 14022 Users.insert(U); 14023 } 14024 } 14025 14026 // Now that we have the actual number of divisor uses, make sure it meets 14027 // the minimum threshold specified by the target. 14028 if ((Users.size() * NumElts) < MinUses) 14029 return SDValue(); 14030 14031 SDLoc DL(N); 14032 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 14033 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 14034 14035 // Dividend / Divisor -> Dividend * Reciprocal 14036 for (auto *U : Users) { 14037 SDValue Dividend = U->getOperand(0); 14038 if (Dividend != FPOne) { 14039 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 14040 Reciprocal, Flags); 14041 CombineTo(U, NewNode); 14042 } else if (U != Reciprocal.getNode()) { 14043 // In the absence of fast-math-flags, this user node is always the 14044 // same node as Reciprocal, but with FMF they may be different nodes. 14045 CombineTo(U, Reciprocal); 14046 } 14047 } 14048 return SDValue(N, 0); // N was replaced. 14049 } 14050 14051 SDValue DAGCombiner::visitFDIV(SDNode *N) { 14052 SDValue N0 = N->getOperand(0); 14053 SDValue N1 = N->getOperand(1); 14054 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 14055 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 14056 EVT VT = N->getValueType(0); 14057 SDLoc DL(N); 14058 const TargetOptions &Options = DAG.getTarget().Options; 14059 SDNodeFlags Flags = N->getFlags(); 14060 SelectionDAG::FlagInserter FlagsInserter(DAG, N); 14061 14062 if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags)) 14063 return R; 14064 14065 // fold vector ops 14066 if (VT.isVector()) 14067 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 14068 return FoldedVOp; 14069 14070 // fold (fdiv c1, c2) -> c1/c2 14071 if (N0CFP && N1CFP) 14072 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1); 14073 14074 if (SDValue NewSel = foldBinOpIntoSelect(N)) 14075 return NewSel; 14076 14077 if (SDValue V = combineRepeatedFPDivisors(N)) 14078 return V; 14079 14080 if (Options.UnsafeFPMath || Flags.hasAllowReciprocal()) { 14081 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 14082 if (N1CFP) { 14083 // Compute the reciprocal 1.0 / c2. 14084 const APFloat &N1APF = N1CFP->getValueAPF(); 14085 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 14086 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 14087 // Only do the transform if the reciprocal is a legal fp immediate that 14088 // isn't too nasty (eg NaN, denormal, ...). 14089 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 14090 (!LegalOperations || 14091 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 14092 // backend)... we should handle this gracefully after Legalize. 14093 // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) || 14094 TLI.isOperationLegal(ISD::ConstantFP, VT) || 14095 TLI.isFPImmLegal(Recip, VT, ForCodeSize))) 14096 return DAG.getNode(ISD::FMUL, DL, VT, N0, 14097 DAG.getConstantFP(Recip, DL, VT)); 14098 } 14099 14100 // If this FDIV is part of a reciprocal square root, it may be folded 14101 // into a target-specific square root estimate instruction. 14102 if (N1.getOpcode() == ISD::FSQRT) { 14103 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) 14104 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 14105 } else if (N1.getOpcode() == ISD::FP_EXTEND && 14106 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 14107 if (SDValue RV = 14108 buildRsqrtEstimate(N1.getOperand(0).getOperand(0), Flags)) { 14109 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 14110 AddToWorklist(RV.getNode()); 14111 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 14112 } 14113 } else if (N1.getOpcode() == ISD::FP_ROUND && 14114 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 14115 if (SDValue RV = 14116 buildRsqrtEstimate(N1.getOperand(0).getOperand(0), Flags)) { 14117 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 14118 AddToWorklist(RV.getNode()); 14119 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 14120 } 14121 } else if (N1.getOpcode() == ISD::FMUL) { 14122 // Look through an FMUL. Even though this won't remove the FDIV directly, 14123 // it's still worthwhile to get rid of the FSQRT if possible. 14124 SDValue Sqrt, Y; 14125 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 14126 Sqrt = N1.getOperand(0); 14127 Y = N1.getOperand(1); 14128 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 14129 Sqrt = N1.getOperand(1); 14130 Y = N1.getOperand(0); 14131 } 14132 if (Sqrt.getNode()) { 14133 // If the other multiply operand is known positive, pull it into the 14134 // sqrt. That will eliminate the division if we convert to an estimate. 14135 if (Flags.hasAllowReassociation() && N1.hasOneUse() && 14136 N1->getFlags().hasAllowReassociation() && Sqrt.hasOneUse()) { 14137 SDValue A; 14138 if (Y.getOpcode() == ISD::FABS && Y.hasOneUse()) 14139 A = Y.getOperand(0); 14140 else if (Y == Sqrt.getOperand(0)) 14141 A = Y; 14142 if (A) { 14143 // X / (fabs(A) * sqrt(Z)) --> X / sqrt(A*A*Z) --> X * rsqrt(A*A*Z) 14144 // X / (A * sqrt(A)) --> X / sqrt(A*A*A) --> X * rsqrt(A*A*A) 14145 SDValue AA = DAG.getNode(ISD::FMUL, DL, VT, A, A); 14146 SDValue AAZ = 14147 DAG.getNode(ISD::FMUL, DL, VT, AA, Sqrt.getOperand(0)); 14148 if (SDValue Rsqrt = buildRsqrtEstimate(AAZ, Flags)) 14149 return DAG.getNode(ISD::FMUL, DL, VT, N0, Rsqrt); 14150 14151 // Estimate creation failed. Clean up speculatively created nodes. 14152 recursivelyDeleteUnusedNodes(AAZ.getNode()); 14153 } 14154 } 14155 14156 // We found a FSQRT, so try to make this fold: 14157 // X / (Y * sqrt(Z)) -> X * (rsqrt(Z) / Y) 14158 if (SDValue Rsqrt = buildRsqrtEstimate(Sqrt.getOperand(0), Flags)) { 14159 SDValue Div = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, Rsqrt, Y); 14160 AddToWorklist(Div.getNode()); 14161 return DAG.getNode(ISD::FMUL, DL, VT, N0, Div); 14162 } 14163 } 14164 } 14165 14166 // Fold into a reciprocal estimate and multiply instead of a real divide. 14167 if (Options.NoInfsFPMath || Flags.hasNoInfs()) 14168 if (SDValue RV = BuildDivEstimate(N0, N1, Flags)) 14169 return RV; 14170 } 14171 14172 // Fold X/Sqrt(X) -> Sqrt(X) 14173 if ((Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros()) && 14174 (Options.UnsafeFPMath || Flags.hasAllowReassociation())) 14175 if (N1.getOpcode() == ISD::FSQRT && N0 == N1.getOperand(0)) 14176 return N1; 14177 14178 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 14179 TargetLowering::NegatibleCost CostN0 = 14180 TargetLowering::NegatibleCost::Expensive; 14181 TargetLowering::NegatibleCost CostN1 = 14182 TargetLowering::NegatibleCost::Expensive; 14183 SDValue NegN0 = 14184 TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0); 14185 SDValue NegN1 = 14186 TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1); 14187 if (NegN0 && NegN1 && 14188 (CostN0 == TargetLowering::NegatibleCost::Cheaper || 14189 CostN1 == TargetLowering::NegatibleCost::Cheaper)) 14190 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, NegN0, NegN1); 14191 14192 return SDValue(); 14193 } 14194 14195 SDValue DAGCombiner::visitFREM(SDNode *N) { 14196 SDValue N0 = N->getOperand(0); 14197 SDValue N1 = N->getOperand(1); 14198 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 14199 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 14200 EVT VT = N->getValueType(0); 14201 SDNodeFlags Flags = N->getFlags(); 14202 SelectionDAG::FlagInserter FlagsInserter(DAG, N); 14203 14204 if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags)) 14205 return R; 14206 14207 // fold (frem c1, c2) -> fmod(c1,c2) 14208 if (N0CFP && N1CFP) 14209 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1); 14210 14211 if (SDValue NewSel = foldBinOpIntoSelect(N)) 14212 return NewSel; 14213 14214 return SDValue(); 14215 } 14216 14217 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 14218 SDNodeFlags Flags = N->getFlags(); 14219 const TargetOptions &Options = DAG.getTarget().Options; 14220 14221 // Require 'ninf' flag since sqrt(+Inf) = +Inf, but the estimation goes as: 14222 // sqrt(+Inf) == rsqrt(+Inf) * +Inf = 0 * +Inf = NaN 14223 if (!Flags.hasApproximateFuncs() || 14224 (!Options.NoInfsFPMath && !Flags.hasNoInfs())) 14225 return SDValue(); 14226 14227 SDValue N0 = N->getOperand(0); 14228 if (TLI.isFsqrtCheap(N0, DAG)) 14229 return SDValue(); 14230 14231 // FSQRT nodes have flags that propagate to the created nodes. 14232 // TODO: If this is N0/sqrt(N0), and we reach this node before trying to 14233 // transform the fdiv, we may produce a sub-optimal estimate sequence 14234 // because the reciprocal calculation may not have to filter out a 14235 // 0.0 input. 14236 return buildSqrtEstimate(N0, Flags); 14237 } 14238 14239 /// copysign(x, fp_extend(y)) -> copysign(x, y) 14240 /// copysign(x, fp_round(y)) -> copysign(x, y) 14241 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 14242 SDValue N1 = N->getOperand(1); 14243 if ((N1.getOpcode() == ISD::FP_EXTEND || 14244 N1.getOpcode() == ISD::FP_ROUND)) { 14245 EVT N1VT = N1->getValueType(0); 14246 EVT N1Op0VT = N1->getOperand(0).getValueType(); 14247 14248 // Always fold no-op FP casts. 14249 if (N1VT == N1Op0VT) 14250 return true; 14251 14252 // Do not optimize out type conversion of f128 type yet. 14253 // For some targets like x86_64, configuration is changed to keep one f128 14254 // value in one SSE register, but instruction selection cannot handle 14255 // FCOPYSIGN on SSE registers yet. 14256 if (N1Op0VT == MVT::f128) 14257 return false; 14258 14259 // Avoid mismatched vector operand types, for better instruction selection. 14260 if (N1Op0VT.isVector()) 14261 return false; 14262 14263 return true; 14264 } 14265 return false; 14266 } 14267 14268 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 14269 SDValue N0 = N->getOperand(0); 14270 SDValue N1 = N->getOperand(1); 14271 bool N0CFP = DAG.isConstantFPBuildVectorOrConstantFP(N0); 14272 bool N1CFP = DAG.isConstantFPBuildVectorOrConstantFP(N1); 14273 EVT VT = N->getValueType(0); 14274 14275 if (N0CFP && N1CFP) // Constant fold 14276 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 14277 14278 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N->getOperand(1))) { 14279 const APFloat &V = N1C->getValueAPF(); 14280 // copysign(x, c1) -> fabs(x) iff ispos(c1) 14281 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 14282 if (!V.isNegative()) { 14283 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 14284 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 14285 } else { 14286 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 14287 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 14288 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 14289 } 14290 } 14291 14292 // copysign(fabs(x), y) -> copysign(x, y) 14293 // copysign(fneg(x), y) -> copysign(x, y) 14294 // copysign(copysign(x,z), y) -> copysign(x, y) 14295 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 14296 N0.getOpcode() == ISD::FCOPYSIGN) 14297 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1); 14298 14299 // copysign(x, abs(y)) -> abs(x) 14300 if (N1.getOpcode() == ISD::FABS) 14301 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 14302 14303 // copysign(x, copysign(y,z)) -> copysign(x, z) 14304 if (N1.getOpcode() == ISD::FCOPYSIGN) 14305 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1)); 14306 14307 // copysign(x, fp_extend(y)) -> copysign(x, y) 14308 // copysign(x, fp_round(y)) -> copysign(x, y) 14309 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 14310 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0)); 14311 14312 return SDValue(); 14313 } 14314 14315 SDValue DAGCombiner::visitFPOW(SDNode *N) { 14316 ConstantFPSDNode *ExponentC = isConstOrConstSplatFP(N->getOperand(1)); 14317 if (!ExponentC) 14318 return SDValue(); 14319 SelectionDAG::FlagInserter FlagsInserter(DAG, N); 14320 14321 // Try to convert x ** (1/3) into cube root. 14322 // TODO: Handle the various flavors of long double. 14323 // TODO: Since we're approximating, we don't need an exact 1/3 exponent. 14324 // Some range near 1/3 should be fine. 14325 EVT VT = N->getValueType(0); 14326 if ((VT == MVT::f32 && ExponentC->getValueAPF().isExactlyValue(1.0f/3.0f)) || 14327 (VT == MVT::f64 && ExponentC->getValueAPF().isExactlyValue(1.0/3.0))) { 14328 // pow(-0.0, 1/3) = +0.0; cbrt(-0.0) = -0.0. 14329 // pow(-inf, 1/3) = +inf; cbrt(-inf) = -inf. 14330 // pow(-val, 1/3) = nan; cbrt(-val) = -num. 14331 // For regular numbers, rounding may cause the results to differ. 14332 // Therefore, we require { nsz ninf nnan afn } for this transform. 14333 // TODO: We could select out the special cases if we don't have nsz/ninf. 14334 SDNodeFlags Flags = N->getFlags(); 14335 if (!Flags.hasNoSignedZeros() || !Flags.hasNoInfs() || !Flags.hasNoNaNs() || 14336 !Flags.hasApproximateFuncs()) 14337 return SDValue(); 14338 14339 // Do not create a cbrt() libcall if the target does not have it, and do not 14340 // turn a pow that has lowering support into a cbrt() libcall. 14341 if (!DAG.getLibInfo().has(LibFunc_cbrt) || 14342 (!DAG.getTargetLoweringInfo().isOperationExpand(ISD::FPOW, VT) && 14343 DAG.getTargetLoweringInfo().isOperationExpand(ISD::FCBRT, VT))) 14344 return SDValue(); 14345 14346 return DAG.getNode(ISD::FCBRT, SDLoc(N), VT, N->getOperand(0)); 14347 } 14348 14349 // Try to convert x ** (1/4) and x ** (3/4) into square roots. 14350 // x ** (1/2) is canonicalized to sqrt, so we do not bother with that case. 14351 // TODO: This could be extended (using a target hook) to handle smaller 14352 // power-of-2 fractional exponents. 14353 bool ExponentIs025 = ExponentC->getValueAPF().isExactlyValue(0.25); 14354 bool ExponentIs075 = ExponentC->getValueAPF().isExactlyValue(0.75); 14355 if (ExponentIs025 || ExponentIs075) { 14356 // pow(-0.0, 0.25) = +0.0; sqrt(sqrt(-0.0)) = -0.0. 14357 // pow(-inf, 0.25) = +inf; sqrt(sqrt(-inf)) = NaN. 14358 // pow(-0.0, 0.75) = +0.0; sqrt(-0.0) * sqrt(sqrt(-0.0)) = +0.0. 14359 // pow(-inf, 0.75) = +inf; sqrt(-inf) * sqrt(sqrt(-inf)) = NaN. 14360 // For regular numbers, rounding may cause the results to differ. 14361 // Therefore, we require { nsz ninf afn } for this transform. 14362 // TODO: We could select out the special cases if we don't have nsz/ninf. 14363 SDNodeFlags Flags = N->getFlags(); 14364 14365 // We only need no signed zeros for the 0.25 case. 14366 if ((!Flags.hasNoSignedZeros() && ExponentIs025) || !Flags.hasNoInfs() || 14367 !Flags.hasApproximateFuncs()) 14368 return SDValue(); 14369 14370 // Don't double the number of libcalls. We are trying to inline fast code. 14371 if (!DAG.getTargetLoweringInfo().isOperationLegalOrCustom(ISD::FSQRT, VT)) 14372 return SDValue(); 14373 14374 // Assume that libcalls are the smallest code. 14375 // TODO: This restriction should probably be lifted for vectors. 14376 if (ForCodeSize) 14377 return SDValue(); 14378 14379 // pow(X, 0.25) --> sqrt(sqrt(X)) 14380 SDLoc DL(N); 14381 SDValue Sqrt = DAG.getNode(ISD::FSQRT, DL, VT, N->getOperand(0)); 14382 SDValue SqrtSqrt = DAG.getNode(ISD::FSQRT, DL, VT, Sqrt); 14383 if (ExponentIs025) 14384 return SqrtSqrt; 14385 // pow(X, 0.75) --> sqrt(X) * sqrt(sqrt(X)) 14386 return DAG.getNode(ISD::FMUL, DL, VT, Sqrt, SqrtSqrt); 14387 } 14388 14389 return SDValue(); 14390 } 14391 14392 static SDValue foldFPToIntToFP(SDNode *N, SelectionDAG &DAG, 14393 const TargetLowering &TLI) { 14394 // This optimization is guarded by a function attribute because it may produce 14395 // unexpected results. Ie, programs may be relying on the platform-specific 14396 // undefined behavior when the float-to-int conversion overflows. 14397 const Function &F = DAG.getMachineFunction().getFunction(); 14398 Attribute StrictOverflow = F.getFnAttribute("strict-float-cast-overflow"); 14399 if (StrictOverflow.getValueAsString().equals("false")) 14400 return SDValue(); 14401 14402 // We only do this if the target has legal ftrunc. Otherwise, we'd likely be 14403 // replacing casts with a libcall. We also must be allowed to ignore -0.0 14404 // because FTRUNC will return -0.0 for (-1.0, -0.0), but using integer 14405 // conversions would return +0.0. 14406 // FIXME: We should be able to use node-level FMF here. 14407 // TODO: If strict math, should we use FABS (+ range check for signed cast)? 14408 EVT VT = N->getValueType(0); 14409 if (!TLI.isOperationLegal(ISD::FTRUNC, VT) || 14410 !DAG.getTarget().Options.NoSignedZerosFPMath) 14411 return SDValue(); 14412 14413 // fptosi/fptoui round towards zero, so converting from FP to integer and 14414 // back is the same as an 'ftrunc': [us]itofp (fpto[us]i X) --> ftrunc X 14415 SDValue N0 = N->getOperand(0); 14416 if (N->getOpcode() == ISD::SINT_TO_FP && N0.getOpcode() == ISD::FP_TO_SINT && 14417 N0.getOperand(0).getValueType() == VT) 14418 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0)); 14419 14420 if (N->getOpcode() == ISD::UINT_TO_FP && N0.getOpcode() == ISD::FP_TO_UINT && 14421 N0.getOperand(0).getValueType() == VT) 14422 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0)); 14423 14424 return SDValue(); 14425 } 14426 14427 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 14428 SDValue N0 = N->getOperand(0); 14429 EVT VT = N->getValueType(0); 14430 EVT OpVT = N0.getValueType(); 14431 14432 // [us]itofp(undef) = 0, because the result value is bounded. 14433 if (N0.isUndef()) 14434 return DAG.getConstantFP(0.0, SDLoc(N), VT); 14435 14436 // fold (sint_to_fp c1) -> c1fp 14437 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 14438 // ...but only if the target supports immediate floating-point values 14439 (!LegalOperations || 14440 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) 14441 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 14442 14443 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 14444 // but UINT_TO_FP is legal on this target, try to convert. 14445 if (!hasOperation(ISD::SINT_TO_FP, OpVT) && 14446 hasOperation(ISD::UINT_TO_FP, OpVT)) { 14447 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 14448 if (DAG.SignBitIsZero(N0)) 14449 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 14450 } 14451 14452 // The next optimizations are desirable only if SELECT_CC can be lowered. 14453 // fold (sint_to_fp (setcc x, y, cc)) -> (select (setcc x, y, cc), -1.0, 0.0) 14454 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 14455 !VT.isVector() && 14456 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 14457 SDLoc DL(N); 14458 return DAG.getSelect(DL, VT, N0, DAG.getConstantFP(-1.0, DL, VT), 14459 DAG.getConstantFP(0.0, DL, VT)); 14460 } 14461 14462 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 14463 // (select (setcc x, y, cc), 1.0, 0.0) 14464 if (N0.getOpcode() == ISD::ZERO_EXTEND && 14465 N0.getOperand(0).getOpcode() == ISD::SETCC && !VT.isVector() && 14466 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 14467 SDLoc DL(N); 14468 return DAG.getSelect(DL, VT, N0.getOperand(0), 14469 DAG.getConstantFP(1.0, DL, VT), 14470 DAG.getConstantFP(0.0, DL, VT)); 14471 } 14472 14473 if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI)) 14474 return FTrunc; 14475 14476 return SDValue(); 14477 } 14478 14479 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 14480 SDValue N0 = N->getOperand(0); 14481 EVT VT = N->getValueType(0); 14482 EVT OpVT = N0.getValueType(); 14483 14484 // [us]itofp(undef) = 0, because the result value is bounded. 14485 if (N0.isUndef()) 14486 return DAG.getConstantFP(0.0, SDLoc(N), VT); 14487 14488 // fold (uint_to_fp c1) -> c1fp 14489 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 14490 // ...but only if the target supports immediate floating-point values 14491 (!LegalOperations || 14492 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) 14493 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 14494 14495 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 14496 // but SINT_TO_FP is legal on this target, try to convert. 14497 if (!hasOperation(ISD::UINT_TO_FP, OpVT) && 14498 hasOperation(ISD::SINT_TO_FP, OpVT)) { 14499 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 14500 if (DAG.SignBitIsZero(N0)) 14501 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 14502 } 14503 14504 // fold (uint_to_fp (setcc x, y, cc)) -> (select (setcc x, y, cc), 1.0, 0.0) 14505 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 14506 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 14507 SDLoc DL(N); 14508 return DAG.getSelect(DL, VT, N0, DAG.getConstantFP(1.0, DL, VT), 14509 DAG.getConstantFP(0.0, DL, VT)); 14510 } 14511 14512 if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI)) 14513 return FTrunc; 14514 14515 return SDValue(); 14516 } 14517 14518 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 14519 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 14520 SDValue N0 = N->getOperand(0); 14521 EVT VT = N->getValueType(0); 14522 14523 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 14524 return SDValue(); 14525 14526 SDValue Src = N0.getOperand(0); 14527 EVT SrcVT = Src.getValueType(); 14528 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 14529 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 14530 14531 // We can safely assume the conversion won't overflow the output range, 14532 // because (for example) (uint8_t)18293.f is undefined behavior. 14533 14534 // Since we can assume the conversion won't overflow, our decision as to 14535 // whether the input will fit in the float should depend on the minimum 14536 // of the input range and output range. 14537 14538 // This means this is also safe for a signed input and unsigned output, since 14539 // a negative input would lead to undefined behavior. 14540 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 14541 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 14542 unsigned ActualSize = std::min(InputSize, OutputSize); 14543 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 14544 14545 // We can only fold away the float conversion if the input range can be 14546 // represented exactly in the float range. 14547 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 14548 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 14549 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 14550 : ISD::ZERO_EXTEND; 14551 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 14552 } 14553 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 14554 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 14555 return DAG.getBitcast(VT, Src); 14556 } 14557 return SDValue(); 14558 } 14559 14560 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 14561 SDValue N0 = N->getOperand(0); 14562 EVT VT = N->getValueType(0); 14563 14564 // fold (fp_to_sint undef) -> undef 14565 if (N0.isUndef()) 14566 return DAG.getUNDEF(VT); 14567 14568 // fold (fp_to_sint c1fp) -> c1 14569 if (DAG.isConstantFPBuildVectorOrConstantFP(N0)) 14570 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 14571 14572 return FoldIntToFPToInt(N, DAG); 14573 } 14574 14575 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 14576 SDValue N0 = N->getOperand(0); 14577 EVT VT = N->getValueType(0); 14578 14579 // fold (fp_to_uint undef) -> undef 14580 if (N0.isUndef()) 14581 return DAG.getUNDEF(VT); 14582 14583 // fold (fp_to_uint c1fp) -> c1 14584 if (DAG.isConstantFPBuildVectorOrConstantFP(N0)) 14585 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 14586 14587 return FoldIntToFPToInt(N, DAG); 14588 } 14589 14590 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 14591 SDValue N0 = N->getOperand(0); 14592 SDValue N1 = N->getOperand(1); 14593 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 14594 EVT VT = N->getValueType(0); 14595 14596 // fold (fp_round c1fp) -> c1fp 14597 if (N0CFP) 14598 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 14599 14600 // fold (fp_round (fp_extend x)) -> x 14601 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 14602 return N0.getOperand(0); 14603 14604 // fold (fp_round (fp_round x)) -> (fp_round x) 14605 if (N0.getOpcode() == ISD::FP_ROUND) { 14606 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 14607 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1; 14608 14609 // Skip this folding if it results in an fp_round from f80 to f16. 14610 // 14611 // f80 to f16 always generates an expensive (and as yet, unimplemented) 14612 // libcall to __truncxfhf2 instead of selecting native f16 conversion 14613 // instructions from f32 or f64. Moreover, the first (value-preserving) 14614 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 14615 // x86. 14616 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 14617 return SDValue(); 14618 14619 // If the first fp_round isn't a value preserving truncation, it might 14620 // introduce a tie in the second fp_round, that wouldn't occur in the 14621 // single-step fp_round we want to fold to. 14622 // In other words, double rounding isn't the same as rounding. 14623 // Also, this is a value preserving truncation iff both fp_round's are. 14624 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 14625 SDLoc DL(N); 14626 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 14627 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 14628 } 14629 } 14630 14631 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 14632 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 14633 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 14634 N0.getOperand(0), N1); 14635 AddToWorklist(Tmp.getNode()); 14636 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 14637 Tmp, N0.getOperand(1)); 14638 } 14639 14640 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 14641 return NewVSel; 14642 14643 return SDValue(); 14644 } 14645 14646 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 14647 SDValue N0 = N->getOperand(0); 14648 EVT VT = N->getValueType(0); 14649 14650 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 14651 if (N->hasOneUse() && 14652 N->use_begin()->getOpcode() == ISD::FP_ROUND) 14653 return SDValue(); 14654 14655 // fold (fp_extend c1fp) -> c1fp 14656 if (DAG.isConstantFPBuildVectorOrConstantFP(N0)) 14657 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 14658 14659 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 14660 if (N0.getOpcode() == ISD::FP16_TO_FP && 14661 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 14662 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 14663 14664 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 14665 // value of X. 14666 if (N0.getOpcode() == ISD::FP_ROUND 14667 && N0.getConstantOperandVal(1) == 1) { 14668 SDValue In = N0.getOperand(0); 14669 if (In.getValueType() == VT) return In; 14670 if (VT.bitsLT(In.getValueType())) 14671 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 14672 In, N0.getOperand(1)); 14673 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 14674 } 14675 14676 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 14677 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 14678 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 14679 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 14680 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 14681 LN0->getChain(), 14682 LN0->getBasePtr(), N0.getValueType(), 14683 LN0->getMemOperand()); 14684 CombineTo(N, ExtLoad); 14685 CombineTo(N0.getNode(), 14686 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 14687 N0.getValueType(), ExtLoad, 14688 DAG.getIntPtrConstant(1, SDLoc(N0))), 14689 ExtLoad.getValue(1)); 14690 return SDValue(N, 0); // Return N so it doesn't get rechecked! 14691 } 14692 14693 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 14694 return NewVSel; 14695 14696 return SDValue(); 14697 } 14698 14699 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 14700 SDValue N0 = N->getOperand(0); 14701 EVT VT = N->getValueType(0); 14702 14703 // fold (fceil c1) -> fceil(c1) 14704 if (DAG.isConstantFPBuildVectorOrConstantFP(N0)) 14705 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 14706 14707 return SDValue(); 14708 } 14709 14710 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 14711 SDValue N0 = N->getOperand(0); 14712 EVT VT = N->getValueType(0); 14713 14714 // fold (ftrunc c1) -> ftrunc(c1) 14715 if (DAG.isConstantFPBuildVectorOrConstantFP(N0)) 14716 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 14717 14718 // fold ftrunc (known rounded int x) -> x 14719 // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is 14720 // likely to be generated to extract integer from a rounded floating value. 14721 switch (N0.getOpcode()) { 14722 default: break; 14723 case ISD::FRINT: 14724 case ISD::FTRUNC: 14725 case ISD::FNEARBYINT: 14726 case ISD::FFLOOR: 14727 case ISD::FCEIL: 14728 return N0; 14729 } 14730 14731 return SDValue(); 14732 } 14733 14734 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 14735 SDValue N0 = N->getOperand(0); 14736 EVT VT = N->getValueType(0); 14737 14738 // fold (ffloor c1) -> ffloor(c1) 14739 if (DAG.isConstantFPBuildVectorOrConstantFP(N0)) 14740 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 14741 14742 return SDValue(); 14743 } 14744 14745 SDValue DAGCombiner::visitFNEG(SDNode *N) { 14746 SDValue N0 = N->getOperand(0); 14747 EVT VT = N->getValueType(0); 14748 SelectionDAG::FlagInserter FlagsInserter(DAG, N); 14749 14750 // Constant fold FNEG. 14751 if (DAG.isConstantFPBuildVectorOrConstantFP(N0)) 14752 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 14753 14754 if (SDValue NegN0 = 14755 TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize)) 14756 return NegN0; 14757 14758 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0 14759 // FIXME: This is duplicated in getNegatibleCost, but getNegatibleCost doesn't 14760 // know it was called from a context with a nsz flag if the input fsub does 14761 // not. 14762 if (N0.getOpcode() == ISD::FSUB && 14763 (DAG.getTarget().Options.NoSignedZerosFPMath || 14764 N->getFlags().hasNoSignedZeros()) && N0.hasOneUse()) { 14765 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0.getOperand(1), 14766 N0.getOperand(0)); 14767 } 14768 14769 if (SDValue Cast = foldSignChangeInBitcast(N)) 14770 return Cast; 14771 14772 return SDValue(); 14773 } 14774 14775 static SDValue visitFMinMax(SelectionDAG &DAG, SDNode *N, 14776 APFloat (*Op)(const APFloat &, const APFloat &)) { 14777 SDValue N0 = N->getOperand(0); 14778 SDValue N1 = N->getOperand(1); 14779 EVT VT = N->getValueType(0); 14780 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 14781 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 14782 const SDNodeFlags Flags = N->getFlags(); 14783 unsigned Opc = N->getOpcode(); 14784 bool PropagatesNaN = Opc == ISD::FMINIMUM || Opc == ISD::FMAXIMUM; 14785 bool IsMin = Opc == ISD::FMINNUM || Opc == ISD::FMINIMUM; 14786 SelectionDAG::FlagInserter FlagsInserter(DAG, N); 14787 14788 if (N0CFP && N1CFP) { 14789 const APFloat &C0 = N0CFP->getValueAPF(); 14790 const APFloat &C1 = N1CFP->getValueAPF(); 14791 return DAG.getConstantFP(Op(C0, C1), SDLoc(N), VT); 14792 } 14793 14794 // Canonicalize to constant on RHS. 14795 if (DAG.isConstantFPBuildVectorOrConstantFP(N0) && 14796 !DAG.isConstantFPBuildVectorOrConstantFP(N1)) 14797 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 14798 14799 if (N1CFP) { 14800 const APFloat &AF = N1CFP->getValueAPF(); 14801 14802 // minnum(X, nan) -> X 14803 // maxnum(X, nan) -> X 14804 // minimum(X, nan) -> nan 14805 // maximum(X, nan) -> nan 14806 if (AF.isNaN()) 14807 return PropagatesNaN ? N->getOperand(1) : N->getOperand(0); 14808 14809 // In the following folds, inf can be replaced with the largest finite 14810 // float, if the ninf flag is set. 14811 if (AF.isInfinity() || (Flags.hasNoInfs() && AF.isLargest())) { 14812 // minnum(X, -inf) -> -inf 14813 // maxnum(X, +inf) -> +inf 14814 // minimum(X, -inf) -> -inf if nnan 14815 // maximum(X, +inf) -> +inf if nnan 14816 if (IsMin == AF.isNegative() && (!PropagatesNaN || Flags.hasNoNaNs())) 14817 return N->getOperand(1); 14818 14819 // minnum(X, +inf) -> X if nnan 14820 // maxnum(X, -inf) -> X if nnan 14821 // minimum(X, +inf) -> X 14822 // maximum(X, -inf) -> X 14823 if (IsMin != AF.isNegative() && (PropagatesNaN || Flags.hasNoNaNs())) 14824 return N->getOperand(0); 14825 } 14826 } 14827 14828 return SDValue(); 14829 } 14830 14831 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 14832 return visitFMinMax(DAG, N, minnum); 14833 } 14834 14835 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 14836 return visitFMinMax(DAG, N, maxnum); 14837 } 14838 14839 SDValue DAGCombiner::visitFMINIMUM(SDNode *N) { 14840 return visitFMinMax(DAG, N, minimum); 14841 } 14842 14843 SDValue DAGCombiner::visitFMAXIMUM(SDNode *N) { 14844 return visitFMinMax(DAG, N, maximum); 14845 } 14846 14847 SDValue DAGCombiner::visitFABS(SDNode *N) { 14848 SDValue N0 = N->getOperand(0); 14849 EVT VT = N->getValueType(0); 14850 14851 // fold (fabs c1) -> fabs(c1) 14852 if (DAG.isConstantFPBuildVectorOrConstantFP(N0)) 14853 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 14854 14855 // fold (fabs (fabs x)) -> (fabs x) 14856 if (N0.getOpcode() == ISD::FABS) 14857 return N->getOperand(0); 14858 14859 // fold (fabs (fneg x)) -> (fabs x) 14860 // fold (fabs (fcopysign x, y)) -> (fabs x) 14861 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 14862 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 14863 14864 if (SDValue Cast = foldSignChangeInBitcast(N)) 14865 return Cast; 14866 14867 return SDValue(); 14868 } 14869 14870 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 14871 SDValue Chain = N->getOperand(0); 14872 SDValue N1 = N->getOperand(1); 14873 SDValue N2 = N->getOperand(2); 14874 14875 // BRCOND(FREEZE(cond)) is equivalent to BRCOND(cond) (both are 14876 // nondeterministic jumps). 14877 if (N1->getOpcode() == ISD::FREEZE && N1.hasOneUse()) { 14878 return DAG.getNode(ISD::BRCOND, SDLoc(N), MVT::Other, Chain, 14879 N1->getOperand(0), N2); 14880 } 14881 14882 // If N is a constant we could fold this into a fallthrough or unconditional 14883 // branch. However that doesn't happen very often in normal code, because 14884 // Instcombine/SimplifyCFG should have handled the available opportunities. 14885 // If we did this folding here, it would be necessary to update the 14886 // MachineBasicBlock CFG, which is awkward. 14887 14888 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 14889 // on the target. 14890 if (N1.getOpcode() == ISD::SETCC && 14891 TLI.isOperationLegalOrCustom(ISD::BR_CC, 14892 N1.getOperand(0).getValueType())) { 14893 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 14894 Chain, N1.getOperand(2), 14895 N1.getOperand(0), N1.getOperand(1), N2); 14896 } 14897 14898 if (N1.hasOneUse()) { 14899 // rebuildSetCC calls visitXor which may change the Chain when there is a 14900 // STRICT_FSETCC/STRICT_FSETCCS involved. Use a handle to track changes. 14901 HandleSDNode ChainHandle(Chain); 14902 if (SDValue NewN1 = rebuildSetCC(N1)) 14903 return DAG.getNode(ISD::BRCOND, SDLoc(N), MVT::Other, 14904 ChainHandle.getValue(), NewN1, N2); 14905 } 14906 14907 return SDValue(); 14908 } 14909 14910 SDValue DAGCombiner::rebuildSetCC(SDValue N) { 14911 if (N.getOpcode() == ISD::SRL || 14912 (N.getOpcode() == ISD::TRUNCATE && 14913 (N.getOperand(0).hasOneUse() && 14914 N.getOperand(0).getOpcode() == ISD::SRL))) { 14915 // Look pass the truncate. 14916 if (N.getOpcode() == ISD::TRUNCATE) 14917 N = N.getOperand(0); 14918 14919 // Match this pattern so that we can generate simpler code: 14920 // 14921 // %a = ... 14922 // %b = and i32 %a, 2 14923 // %c = srl i32 %b, 1 14924 // brcond i32 %c ... 14925 // 14926 // into 14927 // 14928 // %a = ... 14929 // %b = and i32 %a, 2 14930 // %c = setcc eq %b, 0 14931 // brcond %c ... 14932 // 14933 // This applies only when the AND constant value has one bit set and the 14934 // SRL constant is equal to the log2 of the AND constant. The back-end is 14935 // smart enough to convert the result into a TEST/JMP sequence. 14936 SDValue Op0 = N.getOperand(0); 14937 SDValue Op1 = N.getOperand(1); 14938 14939 if (Op0.getOpcode() == ISD::AND && Op1.getOpcode() == ISD::Constant) { 14940 SDValue AndOp1 = Op0.getOperand(1); 14941 14942 if (AndOp1.getOpcode() == ISD::Constant) { 14943 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 14944 14945 if (AndConst.isPowerOf2() && 14946 cast<ConstantSDNode>(Op1)->getAPIntValue() == AndConst.logBase2()) { 14947 SDLoc DL(N); 14948 return DAG.getSetCC(DL, getSetCCResultType(Op0.getValueType()), 14949 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 14950 ISD::SETNE); 14951 } 14952 } 14953 } 14954 } 14955 14956 // Transform (brcond (xor x, y)) -> (brcond (setcc, x, y, ne)) 14957 // Transform (brcond (xor (xor x, y), -1)) -> (brcond (setcc, x, y, eq)) 14958 if (N.getOpcode() == ISD::XOR) { 14959 // Because we may call this on a speculatively constructed 14960 // SimplifiedSetCC Node, we need to simplify this node first. 14961 // Ideally this should be folded into SimplifySetCC and not 14962 // here. For now, grab a handle to N so we don't lose it from 14963 // replacements interal to the visit. 14964 HandleSDNode XORHandle(N); 14965 while (N.getOpcode() == ISD::XOR) { 14966 SDValue Tmp = visitXOR(N.getNode()); 14967 // No simplification done. 14968 if (!Tmp.getNode()) 14969 break; 14970 // Returning N is form in-visit replacement that may invalidated 14971 // N. Grab value from Handle. 14972 if (Tmp.getNode() == N.getNode()) 14973 N = XORHandle.getValue(); 14974 else // Node simplified. Try simplifying again. 14975 N = Tmp; 14976 } 14977 14978 if (N.getOpcode() != ISD::XOR) 14979 return N; 14980 14981 SDValue Op0 = N->getOperand(0); 14982 SDValue Op1 = N->getOperand(1); 14983 14984 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 14985 bool Equal = false; 14986 // (brcond (xor (xor x, y), -1)) -> (brcond (setcc x, y, eq)) 14987 if (isBitwiseNot(N) && Op0.hasOneUse() && Op0.getOpcode() == ISD::XOR && 14988 Op0.getValueType() == MVT::i1) { 14989 N = Op0; 14990 Op0 = N->getOperand(0); 14991 Op1 = N->getOperand(1); 14992 Equal = true; 14993 } 14994 14995 EVT SetCCVT = N.getValueType(); 14996 if (LegalTypes) 14997 SetCCVT = getSetCCResultType(SetCCVT); 14998 // Replace the uses of XOR with SETCC 14999 return DAG.getSetCC(SDLoc(N), SetCCVT, Op0, Op1, 15000 Equal ? ISD::SETEQ : ISD::SETNE); 15001 } 15002 } 15003 15004 return SDValue(); 15005 } 15006 15007 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 15008 // 15009 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 15010 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 15011 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 15012 15013 // If N is a constant we could fold this into a fallthrough or unconditional 15014 // branch. However that doesn't happen very often in normal code, because 15015 // Instcombine/SimplifyCFG should have handled the available opportunities. 15016 // If we did this folding here, it would be necessary to update the 15017 // MachineBasicBlock CFG, which is awkward. 15018 15019 // Use SimplifySetCC to simplify SETCC's. 15020 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 15021 CondLHS, CondRHS, CC->get(), SDLoc(N), 15022 false); 15023 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 15024 15025 // fold to a simpler setcc 15026 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 15027 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 15028 N->getOperand(0), Simp.getOperand(2), 15029 Simp.getOperand(0), Simp.getOperand(1), 15030 N->getOperand(4)); 15031 15032 return SDValue(); 15033 } 15034 15035 static bool getCombineLoadStoreParts(SDNode *N, unsigned Inc, unsigned Dec, 15036 bool &IsLoad, bool &IsMasked, SDValue &Ptr, 15037 const TargetLowering &TLI) { 15038 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 15039 if (LD->isIndexed()) 15040 return false; 15041 EVT VT = LD->getMemoryVT(); 15042 if (!TLI.isIndexedLoadLegal(Inc, VT) && !TLI.isIndexedLoadLegal(Dec, VT)) 15043 return false; 15044 Ptr = LD->getBasePtr(); 15045 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 15046 if (ST->isIndexed()) 15047 return false; 15048 EVT VT = ST->getMemoryVT(); 15049 if (!TLI.isIndexedStoreLegal(Inc, VT) && !TLI.isIndexedStoreLegal(Dec, VT)) 15050 return false; 15051 Ptr = ST->getBasePtr(); 15052 IsLoad = false; 15053 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) { 15054 if (LD->isIndexed()) 15055 return false; 15056 EVT VT = LD->getMemoryVT(); 15057 if (!TLI.isIndexedMaskedLoadLegal(Inc, VT) && 15058 !TLI.isIndexedMaskedLoadLegal(Dec, VT)) 15059 return false; 15060 Ptr = LD->getBasePtr(); 15061 IsMasked = true; 15062 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) { 15063 if (ST->isIndexed()) 15064 return false; 15065 EVT VT = ST->getMemoryVT(); 15066 if (!TLI.isIndexedMaskedStoreLegal(Inc, VT) && 15067 !TLI.isIndexedMaskedStoreLegal(Dec, VT)) 15068 return false; 15069 Ptr = ST->getBasePtr(); 15070 IsLoad = false; 15071 IsMasked = true; 15072 } else { 15073 return false; 15074 } 15075 return true; 15076 } 15077 15078 /// Try turning a load/store into a pre-indexed load/store when the base 15079 /// pointer is an add or subtract and it has other uses besides the load/store. 15080 /// After the transformation, the new indexed load/store has effectively folded 15081 /// the add/subtract in and all of its other uses are redirected to the 15082 /// new load/store. 15083 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 15084 if (Level < AfterLegalizeDAG) 15085 return false; 15086 15087 bool IsLoad = true; 15088 bool IsMasked = false; 15089 SDValue Ptr; 15090 if (!getCombineLoadStoreParts(N, ISD::PRE_INC, ISD::PRE_DEC, IsLoad, IsMasked, 15091 Ptr, TLI)) 15092 return false; 15093 15094 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 15095 // out. There is no reason to make this a preinc/predec. 15096 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 15097 Ptr.getNode()->hasOneUse()) 15098 return false; 15099 15100 // Ask the target to do addressing mode selection. 15101 SDValue BasePtr; 15102 SDValue Offset; 15103 ISD::MemIndexedMode AM = ISD::UNINDEXED; 15104 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 15105 return false; 15106 15107 // Backends without true r+i pre-indexed forms may need to pass a 15108 // constant base with a variable offset so that constant coercion 15109 // will work with the patterns in canonical form. 15110 bool Swapped = false; 15111 if (isa<ConstantSDNode>(BasePtr)) { 15112 std::swap(BasePtr, Offset); 15113 Swapped = true; 15114 } 15115 15116 // Don't create a indexed load / store with zero offset. 15117 if (isNullConstant(Offset)) 15118 return false; 15119 15120 // Try turning it into a pre-indexed load / store except when: 15121 // 1) The new base ptr is a frame index. 15122 // 2) If N is a store and the new base ptr is either the same as or is a 15123 // predecessor of the value being stored. 15124 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 15125 // that would create a cycle. 15126 // 4) All uses are load / store ops that use it as old base ptr. 15127 15128 // Check #1. Preinc'ing a frame index would require copying the stack pointer 15129 // (plus the implicit offset) to a register to preinc anyway. 15130 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 15131 return false; 15132 15133 // Check #2. 15134 if (!IsLoad) { 15135 SDValue Val = IsMasked ? cast<MaskedStoreSDNode>(N)->getValue() 15136 : cast<StoreSDNode>(N)->getValue(); 15137 15138 // Would require a copy. 15139 if (Val == BasePtr) 15140 return false; 15141 15142 // Would create a cycle. 15143 if (Val == Ptr || Ptr->isPredecessorOf(Val.getNode())) 15144 return false; 15145 } 15146 15147 // Caches for hasPredecessorHelper. 15148 SmallPtrSet<const SDNode *, 32> Visited; 15149 SmallVector<const SDNode *, 16> Worklist; 15150 Worklist.push_back(N); 15151 15152 // If the offset is a constant, there may be other adds of constants that 15153 // can be folded with this one. We should do this to avoid having to keep 15154 // a copy of the original base pointer. 15155 SmallVector<SDNode *, 16> OtherUses; 15156 if (isa<ConstantSDNode>(Offset)) 15157 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 15158 UE = BasePtr.getNode()->use_end(); 15159 UI != UE; ++UI) { 15160 SDUse &Use = UI.getUse(); 15161 // Skip the use that is Ptr and uses of other results from BasePtr's 15162 // node (important for nodes that return multiple results). 15163 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 15164 continue; 15165 15166 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 15167 continue; 15168 15169 if (Use.getUser()->getOpcode() != ISD::ADD && 15170 Use.getUser()->getOpcode() != ISD::SUB) { 15171 OtherUses.clear(); 15172 break; 15173 } 15174 15175 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 15176 if (!isa<ConstantSDNode>(Op1)) { 15177 OtherUses.clear(); 15178 break; 15179 } 15180 15181 // FIXME: In some cases, we can be smarter about this. 15182 if (Op1.getValueType() != Offset.getValueType()) { 15183 OtherUses.clear(); 15184 break; 15185 } 15186 15187 OtherUses.push_back(Use.getUser()); 15188 } 15189 15190 if (Swapped) 15191 std::swap(BasePtr, Offset); 15192 15193 // Now check for #3 and #4. 15194 bool RealUse = false; 15195 15196 for (SDNode *Use : Ptr.getNode()->uses()) { 15197 if (Use == N) 15198 continue; 15199 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 15200 return false; 15201 15202 // If Ptr may be folded in addressing mode of other use, then it's 15203 // not profitable to do this transformation. 15204 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 15205 RealUse = true; 15206 } 15207 15208 if (!RealUse) 15209 return false; 15210 15211 SDValue Result; 15212 if (!IsMasked) { 15213 if (IsLoad) 15214 Result = DAG.getIndexedLoad(SDValue(N, 0), SDLoc(N), BasePtr, Offset, AM); 15215 else 15216 Result = 15217 DAG.getIndexedStore(SDValue(N, 0), SDLoc(N), BasePtr, Offset, AM); 15218 } else { 15219 if (IsLoad) 15220 Result = DAG.getIndexedMaskedLoad(SDValue(N, 0), SDLoc(N), BasePtr, 15221 Offset, AM); 15222 else 15223 Result = DAG.getIndexedMaskedStore(SDValue(N, 0), SDLoc(N), BasePtr, 15224 Offset, AM); 15225 } 15226 ++PreIndexedNodes; 15227 ++NodesCombined; 15228 LLVM_DEBUG(dbgs() << "\nReplacing.4 "; N->dump(&DAG); dbgs() << "\nWith: "; 15229 Result.getNode()->dump(&DAG); dbgs() << '\n'); 15230 WorklistRemover DeadNodes(*this); 15231 if (IsLoad) { 15232 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 15233 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 15234 } else { 15235 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 15236 } 15237 15238 // Finally, since the node is now dead, remove it from the graph. 15239 deleteAndRecombine(N); 15240 15241 if (Swapped) 15242 std::swap(BasePtr, Offset); 15243 15244 // Replace other uses of BasePtr that can be updated to use Ptr 15245 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 15246 unsigned OffsetIdx = 1; 15247 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 15248 OffsetIdx = 0; 15249 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 15250 BasePtr.getNode() && "Expected BasePtr operand"); 15251 15252 // We need to replace ptr0 in the following expression: 15253 // x0 * offset0 + y0 * ptr0 = t0 15254 // knowing that 15255 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 15256 // 15257 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 15258 // indexed load/store and the expression that needs to be re-written. 15259 // 15260 // Therefore, we have: 15261 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 15262 15263 auto *CN = cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 15264 const APInt &Offset0 = CN->getAPIntValue(); 15265 const APInt &Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 15266 int X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 15267 int Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 15268 int X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 15269 int Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 15270 15271 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 15272 15273 APInt CNV = Offset0; 15274 if (X0 < 0) CNV = -CNV; 15275 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 15276 else CNV = CNV - Offset1; 15277 15278 SDLoc DL(OtherUses[i]); 15279 15280 // We can now generate the new expression. 15281 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 15282 SDValue NewOp2 = Result.getValue(IsLoad ? 1 : 0); 15283 15284 SDValue NewUse = DAG.getNode(Opcode, 15285 DL, 15286 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 15287 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 15288 deleteAndRecombine(OtherUses[i]); 15289 } 15290 15291 // Replace the uses of Ptr with uses of the updated base value. 15292 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(IsLoad ? 1 : 0)); 15293 deleteAndRecombine(Ptr.getNode()); 15294 AddToWorklist(Result.getNode()); 15295 15296 return true; 15297 } 15298 15299 static bool shouldCombineToPostInc(SDNode *N, SDValue Ptr, SDNode *PtrUse, 15300 SDValue &BasePtr, SDValue &Offset, 15301 ISD::MemIndexedMode &AM, 15302 SelectionDAG &DAG, 15303 const TargetLowering &TLI) { 15304 if (PtrUse == N || 15305 (PtrUse->getOpcode() != ISD::ADD && PtrUse->getOpcode() != ISD::SUB)) 15306 return false; 15307 15308 if (!TLI.getPostIndexedAddressParts(N, PtrUse, BasePtr, Offset, AM, DAG)) 15309 return false; 15310 15311 // Don't create a indexed load / store with zero offset. 15312 if (isNullConstant(Offset)) 15313 return false; 15314 15315 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 15316 return false; 15317 15318 SmallPtrSet<const SDNode *, 32> Visited; 15319 for (SDNode *Use : BasePtr.getNode()->uses()) { 15320 if (Use == Ptr.getNode()) 15321 continue; 15322 15323 // No if there's a later user which could perform the index instead. 15324 if (isa<MemSDNode>(Use)) { 15325 bool IsLoad = true; 15326 bool IsMasked = false; 15327 SDValue OtherPtr; 15328 if (getCombineLoadStoreParts(Use, ISD::POST_INC, ISD::POST_DEC, IsLoad, 15329 IsMasked, OtherPtr, TLI)) { 15330 SmallVector<const SDNode *, 2> Worklist; 15331 Worklist.push_back(Use); 15332 if (SDNode::hasPredecessorHelper(N, Visited, Worklist)) 15333 return false; 15334 } 15335 } 15336 15337 // If all the uses are load / store addresses, then don't do the 15338 // transformation. 15339 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB) { 15340 for (SDNode *UseUse : Use->uses()) 15341 if (canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 15342 return false; 15343 } 15344 } 15345 return true; 15346 } 15347 15348 static SDNode *getPostIndexedLoadStoreOp(SDNode *N, bool &IsLoad, 15349 bool &IsMasked, SDValue &Ptr, 15350 SDValue &BasePtr, SDValue &Offset, 15351 ISD::MemIndexedMode &AM, 15352 SelectionDAG &DAG, 15353 const TargetLowering &TLI) { 15354 if (!getCombineLoadStoreParts(N, ISD::POST_INC, ISD::POST_DEC, IsLoad, 15355 IsMasked, Ptr, TLI) || 15356 Ptr.getNode()->hasOneUse()) 15357 return nullptr; 15358 15359 // Try turning it into a post-indexed load / store except when 15360 // 1) All uses are load / store ops that use it as base ptr (and 15361 // it may be folded as addressing mmode). 15362 // 2) Op must be independent of N, i.e. Op is neither a predecessor 15363 // nor a successor of N. Otherwise, if Op is folded that would 15364 // create a cycle. 15365 for (SDNode *Op : Ptr->uses()) { 15366 // Check for #1. 15367 if (!shouldCombineToPostInc(N, Ptr, Op, BasePtr, Offset, AM, DAG, TLI)) 15368 continue; 15369 15370 // Check for #2. 15371 SmallPtrSet<const SDNode *, 32> Visited; 15372 SmallVector<const SDNode *, 8> Worklist; 15373 // Ptr is predecessor to both N and Op. 15374 Visited.insert(Ptr.getNode()); 15375 Worklist.push_back(N); 15376 Worklist.push_back(Op); 15377 if (!SDNode::hasPredecessorHelper(N, Visited, Worklist) && 15378 !SDNode::hasPredecessorHelper(Op, Visited, Worklist)) 15379 return Op; 15380 } 15381 return nullptr; 15382 } 15383 15384 /// Try to combine a load/store with a add/sub of the base pointer node into a 15385 /// post-indexed load/store. The transformation folded the add/subtract into the 15386 /// new indexed load/store effectively and all of its uses are redirected to the 15387 /// new load/store. 15388 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 15389 if (Level < AfterLegalizeDAG) 15390 return false; 15391 15392 bool IsLoad = true; 15393 bool IsMasked = false; 15394 SDValue Ptr; 15395 SDValue BasePtr; 15396 SDValue Offset; 15397 ISD::MemIndexedMode AM = ISD::UNINDEXED; 15398 SDNode *Op = getPostIndexedLoadStoreOp(N, IsLoad, IsMasked, Ptr, BasePtr, 15399 Offset, AM, DAG, TLI); 15400 if (!Op) 15401 return false; 15402 15403 SDValue Result; 15404 if (!IsMasked) 15405 Result = IsLoad ? DAG.getIndexedLoad(SDValue(N, 0), SDLoc(N), BasePtr, 15406 Offset, AM) 15407 : DAG.getIndexedStore(SDValue(N, 0), SDLoc(N), 15408 BasePtr, Offset, AM); 15409 else 15410 Result = IsLoad ? DAG.getIndexedMaskedLoad(SDValue(N, 0), SDLoc(N), 15411 BasePtr, Offset, AM) 15412 : DAG.getIndexedMaskedStore(SDValue(N, 0), SDLoc(N), 15413 BasePtr, Offset, AM); 15414 ++PostIndexedNodes; 15415 ++NodesCombined; 15416 LLVM_DEBUG(dbgs() << "\nReplacing.5 "; N->dump(&DAG); 15417 dbgs() << "\nWith: "; Result.getNode()->dump(&DAG); 15418 dbgs() << '\n'); 15419 WorklistRemover DeadNodes(*this); 15420 if (IsLoad) { 15421 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 15422 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 15423 } else { 15424 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 15425 } 15426 15427 // Finally, since the node is now dead, remove it from the graph. 15428 deleteAndRecombine(N); 15429 15430 // Replace the uses of Use with uses of the updated base value. 15431 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 15432 Result.getValue(IsLoad ? 1 : 0)); 15433 deleteAndRecombine(Op); 15434 return true; 15435 } 15436 15437 /// Return the base-pointer arithmetic from an indexed \p LD. 15438 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 15439 ISD::MemIndexedMode AM = LD->getAddressingMode(); 15440 assert(AM != ISD::UNINDEXED); 15441 SDValue BP = LD->getOperand(1); 15442 SDValue Inc = LD->getOperand(2); 15443 15444 // Some backends use TargetConstants for load offsets, but don't expect 15445 // TargetConstants in general ADD nodes. We can convert these constants into 15446 // regular Constants (if the constant is not opaque). 15447 assert((Inc.getOpcode() != ISD::TargetConstant || 15448 !cast<ConstantSDNode>(Inc)->isOpaque()) && 15449 "Cannot split out indexing using opaque target constants"); 15450 if (Inc.getOpcode() == ISD::TargetConstant) { 15451 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 15452 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 15453 ConstInc->getValueType(0)); 15454 } 15455 15456 unsigned Opc = 15457 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 15458 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 15459 } 15460 15461 static inline ElementCount numVectorEltsOrZero(EVT T) { 15462 return T.isVector() ? T.getVectorElementCount() : ElementCount::getFixed(0); 15463 } 15464 15465 bool DAGCombiner::getTruncatedStoreValue(StoreSDNode *ST, SDValue &Val) { 15466 Val = ST->getValue(); 15467 EVT STType = Val.getValueType(); 15468 EVT STMemType = ST->getMemoryVT(); 15469 if (STType == STMemType) 15470 return true; 15471 if (isTypeLegal(STMemType)) 15472 return false; // fail. 15473 if (STType.isFloatingPoint() && STMemType.isFloatingPoint() && 15474 TLI.isOperationLegal(ISD::FTRUNC, STMemType)) { 15475 Val = DAG.getNode(ISD::FTRUNC, SDLoc(ST), STMemType, Val); 15476 return true; 15477 } 15478 if (numVectorEltsOrZero(STType) == numVectorEltsOrZero(STMemType) && 15479 STType.isInteger() && STMemType.isInteger()) { 15480 Val = DAG.getNode(ISD::TRUNCATE, SDLoc(ST), STMemType, Val); 15481 return true; 15482 } 15483 if (STType.getSizeInBits() == STMemType.getSizeInBits()) { 15484 Val = DAG.getBitcast(STMemType, Val); 15485 return true; 15486 } 15487 return false; // fail. 15488 } 15489 15490 bool DAGCombiner::extendLoadedValueToExtension(LoadSDNode *LD, SDValue &Val) { 15491 EVT LDMemType = LD->getMemoryVT(); 15492 EVT LDType = LD->getValueType(0); 15493 assert(Val.getValueType() == LDMemType && 15494 "Attempting to extend value of non-matching type"); 15495 if (LDType == LDMemType) 15496 return true; 15497 if (LDMemType.isInteger() && LDType.isInteger()) { 15498 switch (LD->getExtensionType()) { 15499 case ISD::NON_EXTLOAD: 15500 Val = DAG.getBitcast(LDType, Val); 15501 return true; 15502 case ISD::EXTLOAD: 15503 Val = DAG.getNode(ISD::ANY_EXTEND, SDLoc(LD), LDType, Val); 15504 return true; 15505 case ISD::SEXTLOAD: 15506 Val = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(LD), LDType, Val); 15507 return true; 15508 case ISD::ZEXTLOAD: 15509 Val = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(LD), LDType, Val); 15510 return true; 15511 } 15512 } 15513 return false; 15514 } 15515 15516 SDValue DAGCombiner::ForwardStoreValueToDirectLoad(LoadSDNode *LD) { 15517 if (OptLevel == CodeGenOpt::None || !LD->isSimple()) 15518 return SDValue(); 15519 SDValue Chain = LD->getOperand(0); 15520 StoreSDNode *ST = dyn_cast<StoreSDNode>(Chain.getNode()); 15521 // TODO: Relax this restriction for unordered atomics (see D66309) 15522 if (!ST || !ST->isSimple()) 15523 return SDValue(); 15524 15525 EVT LDType = LD->getValueType(0); 15526 EVT LDMemType = LD->getMemoryVT(); 15527 EVT STMemType = ST->getMemoryVT(); 15528 EVT STType = ST->getValue().getValueType(); 15529 15530 // There are two cases to consider here: 15531 // 1. The store is fixed width and the load is scalable. In this case we 15532 // don't know at compile time if the store completely envelops the load 15533 // so we abandon the optimisation. 15534 // 2. The store is scalable and the load is fixed width. We could 15535 // potentially support a limited number of cases here, but there has been 15536 // no cost-benefit analysis to prove it's worth it. 15537 bool LdStScalable = LDMemType.isScalableVector(); 15538 if (LdStScalable != STMemType.isScalableVector()) 15539 return SDValue(); 15540 15541 // If we are dealing with scalable vectors on a big endian platform the 15542 // calculation of offsets below becomes trickier, since we do not know at 15543 // compile time the absolute size of the vector. Until we've done more 15544 // analysis on big-endian platforms it seems better to bail out for now. 15545 if (LdStScalable && DAG.getDataLayout().isBigEndian()) 15546 return SDValue(); 15547 15548 BaseIndexOffset BasePtrLD = BaseIndexOffset::match(LD, DAG); 15549 BaseIndexOffset BasePtrST = BaseIndexOffset::match(ST, DAG); 15550 int64_t Offset; 15551 if (!BasePtrST.equalBaseIndex(BasePtrLD, DAG, Offset)) 15552 return SDValue(); 15553 15554 // Normalize for Endianness. After this Offset=0 will denote that the least 15555 // significant bit in the loaded value maps to the least significant bit in 15556 // the stored value). With Offset=n (for n > 0) the loaded value starts at the 15557 // n:th least significant byte of the stored value. 15558 if (DAG.getDataLayout().isBigEndian()) 15559 Offset = ((int64_t)STMemType.getStoreSizeInBits().getFixedSize() - 15560 (int64_t)LDMemType.getStoreSizeInBits().getFixedSize()) / 15561 8 - 15562 Offset; 15563 15564 // Check that the stored value cover all bits that are loaded. 15565 bool STCoversLD; 15566 15567 TypeSize LdMemSize = LDMemType.getSizeInBits(); 15568 TypeSize StMemSize = STMemType.getSizeInBits(); 15569 if (LdStScalable) 15570 STCoversLD = (Offset == 0) && LdMemSize == StMemSize; 15571 else 15572 STCoversLD = (Offset >= 0) && (Offset * 8 + LdMemSize.getFixedSize() <= 15573 StMemSize.getFixedSize()); 15574 15575 auto ReplaceLd = [&](LoadSDNode *LD, SDValue Val, SDValue Chain) -> SDValue { 15576 if (LD->isIndexed()) { 15577 // Cannot handle opaque target constants and we must respect the user's 15578 // request not to split indexes from loads. 15579 if (!canSplitIdx(LD)) 15580 return SDValue(); 15581 SDValue Idx = SplitIndexingFromLoad(LD); 15582 SDValue Ops[] = {Val, Idx, Chain}; 15583 return CombineTo(LD, Ops, 3); 15584 } 15585 return CombineTo(LD, Val, Chain); 15586 }; 15587 15588 if (!STCoversLD) 15589 return SDValue(); 15590 15591 // Memory as copy space (potentially masked). 15592 if (Offset == 0 && LDType == STType && STMemType == LDMemType) { 15593 // Simple case: Direct non-truncating forwarding 15594 if (LDType.getSizeInBits() == LdMemSize) 15595 return ReplaceLd(LD, ST->getValue(), Chain); 15596 // Can we model the truncate and extension with an and mask? 15597 if (STType.isInteger() && LDMemType.isInteger() && !STType.isVector() && 15598 !LDMemType.isVector() && LD->getExtensionType() != ISD::SEXTLOAD) { 15599 // Mask to size of LDMemType 15600 auto Mask = 15601 DAG.getConstant(APInt::getLowBitsSet(STType.getFixedSizeInBits(), 15602 StMemSize.getFixedSize()), 15603 SDLoc(ST), STType); 15604 auto Val = DAG.getNode(ISD::AND, SDLoc(LD), LDType, ST->getValue(), Mask); 15605 return ReplaceLd(LD, Val, Chain); 15606 } 15607 } 15608 15609 // TODO: Deal with nonzero offset. 15610 if (LD->getBasePtr().isUndef() || Offset != 0) 15611 return SDValue(); 15612 // Model necessary truncations / extenstions. 15613 SDValue Val; 15614 // Truncate Value To Stored Memory Size. 15615 do { 15616 if (!getTruncatedStoreValue(ST, Val)) 15617 continue; 15618 if (!isTypeLegal(LDMemType)) 15619 continue; 15620 if (STMemType != LDMemType) { 15621 // TODO: Support vectors? This requires extract_subvector/bitcast. 15622 if (!STMemType.isVector() && !LDMemType.isVector() && 15623 STMemType.isInteger() && LDMemType.isInteger()) 15624 Val = DAG.getNode(ISD::TRUNCATE, SDLoc(LD), LDMemType, Val); 15625 else 15626 continue; 15627 } 15628 if (!extendLoadedValueToExtension(LD, Val)) 15629 continue; 15630 return ReplaceLd(LD, Val, Chain); 15631 } while (false); 15632 15633 // On failure, cleanup dead nodes we may have created. 15634 if (Val->use_empty()) 15635 deleteAndRecombine(Val.getNode()); 15636 return SDValue(); 15637 } 15638 15639 SDValue DAGCombiner::visitLOAD(SDNode *N) { 15640 LoadSDNode *LD = cast<LoadSDNode>(N); 15641 SDValue Chain = LD->getChain(); 15642 SDValue Ptr = LD->getBasePtr(); 15643 15644 // If load is not volatile and there are no uses of the loaded value (and 15645 // the updated indexed value in case of indexed loads), change uses of the 15646 // chain value into uses of the chain input (i.e. delete the dead load). 15647 // TODO: Allow this for unordered atomics (see D66309) 15648 if (LD->isSimple()) { 15649 if (N->getValueType(1) == MVT::Other) { 15650 // Unindexed loads. 15651 if (!N->hasAnyUseOfValue(0)) { 15652 // It's not safe to use the two value CombineTo variant here. e.g. 15653 // v1, chain2 = load chain1, loc 15654 // v2, chain3 = load chain2, loc 15655 // v3 = add v2, c 15656 // Now we replace use of chain2 with chain1. This makes the second load 15657 // isomorphic to the one we are deleting, and thus makes this load live. 15658 LLVM_DEBUG(dbgs() << "\nReplacing.6 "; N->dump(&DAG); 15659 dbgs() << "\nWith chain: "; Chain.getNode()->dump(&DAG); 15660 dbgs() << "\n"); 15661 WorklistRemover DeadNodes(*this); 15662 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 15663 AddUsersToWorklist(Chain.getNode()); 15664 if (N->use_empty()) 15665 deleteAndRecombine(N); 15666 15667 return SDValue(N, 0); // Return N so it doesn't get rechecked! 15668 } 15669 } else { 15670 // Indexed loads. 15671 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 15672 15673 // If this load has an opaque TargetConstant offset, then we cannot split 15674 // the indexing into an add/sub directly (that TargetConstant may not be 15675 // valid for a different type of node, and we cannot convert an opaque 15676 // target constant into a regular constant). 15677 bool CanSplitIdx = canSplitIdx(LD); 15678 15679 if (!N->hasAnyUseOfValue(0) && (CanSplitIdx || !N->hasAnyUseOfValue(1))) { 15680 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 15681 SDValue Index; 15682 if (N->hasAnyUseOfValue(1) && CanSplitIdx) { 15683 Index = SplitIndexingFromLoad(LD); 15684 // Try to fold the base pointer arithmetic into subsequent loads and 15685 // stores. 15686 AddUsersToWorklist(N); 15687 } else 15688 Index = DAG.getUNDEF(N->getValueType(1)); 15689 LLVM_DEBUG(dbgs() << "\nReplacing.7 "; N->dump(&DAG); 15690 dbgs() << "\nWith: "; Undef.getNode()->dump(&DAG); 15691 dbgs() << " and 2 other values\n"); 15692 WorklistRemover DeadNodes(*this); 15693 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 15694 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 15695 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 15696 deleteAndRecombine(N); 15697 return SDValue(N, 0); // Return N so it doesn't get rechecked! 15698 } 15699 } 15700 } 15701 15702 // If this load is directly stored, replace the load value with the stored 15703 // value. 15704 if (auto V = ForwardStoreValueToDirectLoad(LD)) 15705 return V; 15706 15707 // Try to infer better alignment information than the load already has. 15708 if (OptLevel != CodeGenOpt::None && LD->isUnindexed() && !LD->isAtomic()) { 15709 if (MaybeAlign Alignment = DAG.InferPtrAlign(Ptr)) { 15710 if (*Alignment > LD->getAlign() && 15711 isAligned(*Alignment, LD->getSrcValueOffset())) { 15712 SDValue NewLoad = DAG.getExtLoad( 15713 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr, 15714 LD->getPointerInfo(), LD->getMemoryVT(), *Alignment, 15715 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 15716 // NewLoad will always be N as we are only refining the alignment 15717 assert(NewLoad.getNode() == N); 15718 (void)NewLoad; 15719 } 15720 } 15721 } 15722 15723 if (LD->isUnindexed()) { 15724 // Walk up chain skipping non-aliasing memory nodes. 15725 SDValue BetterChain = FindBetterChain(LD, Chain); 15726 15727 // If there is a better chain. 15728 if (Chain != BetterChain) { 15729 SDValue ReplLoad; 15730 15731 // Replace the chain to void dependency. 15732 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 15733 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 15734 BetterChain, Ptr, LD->getMemOperand()); 15735 } else { 15736 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 15737 LD->getValueType(0), 15738 BetterChain, Ptr, LD->getMemoryVT(), 15739 LD->getMemOperand()); 15740 } 15741 15742 // Create token factor to keep old chain connected. 15743 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 15744 MVT::Other, Chain, ReplLoad.getValue(1)); 15745 15746 // Replace uses with load result and token factor 15747 return CombineTo(N, ReplLoad.getValue(0), Token); 15748 } 15749 } 15750 15751 // Try transforming N to an indexed load. 15752 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 15753 return SDValue(N, 0); 15754 15755 // Try to slice up N to more direct loads if the slices are mapped to 15756 // different register banks or pairing can take place. 15757 if (SliceUpLoad(N)) 15758 return SDValue(N, 0); 15759 15760 return SDValue(); 15761 } 15762 15763 namespace { 15764 15765 /// Helper structure used to slice a load in smaller loads. 15766 /// Basically a slice is obtained from the following sequence: 15767 /// Origin = load Ty1, Base 15768 /// Shift = srl Ty1 Origin, CstTy Amount 15769 /// Inst = trunc Shift to Ty2 15770 /// 15771 /// Then, it will be rewritten into: 15772 /// Slice = load SliceTy, Base + SliceOffset 15773 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 15774 /// 15775 /// SliceTy is deduced from the number of bits that are actually used to 15776 /// build Inst. 15777 struct LoadedSlice { 15778 /// Helper structure used to compute the cost of a slice. 15779 struct Cost { 15780 /// Are we optimizing for code size. 15781 bool ForCodeSize = false; 15782 15783 /// Various cost. 15784 unsigned Loads = 0; 15785 unsigned Truncates = 0; 15786 unsigned CrossRegisterBanksCopies = 0; 15787 unsigned ZExts = 0; 15788 unsigned Shift = 0; 15789 15790 explicit Cost(bool ForCodeSize) : ForCodeSize(ForCodeSize) {} 15791 15792 /// Get the cost of one isolated slice. 15793 Cost(const LoadedSlice &LS, bool ForCodeSize) 15794 : ForCodeSize(ForCodeSize), Loads(1) { 15795 EVT TruncType = LS.Inst->getValueType(0); 15796 EVT LoadedType = LS.getLoadedType(); 15797 if (TruncType != LoadedType && 15798 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 15799 ZExts = 1; 15800 } 15801 15802 /// Account for slicing gain in the current cost. 15803 /// Slicing provide a few gains like removing a shift or a 15804 /// truncate. This method allows to grow the cost of the original 15805 /// load with the gain from this slice. 15806 void addSliceGain(const LoadedSlice &LS) { 15807 // Each slice saves a truncate. 15808 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 15809 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 15810 LS.Inst->getValueType(0))) 15811 ++Truncates; 15812 // If there is a shift amount, this slice gets rid of it. 15813 if (LS.Shift) 15814 ++Shift; 15815 // If this slice can merge a cross register bank copy, account for it. 15816 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 15817 ++CrossRegisterBanksCopies; 15818 } 15819 15820 Cost &operator+=(const Cost &RHS) { 15821 Loads += RHS.Loads; 15822 Truncates += RHS.Truncates; 15823 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 15824 ZExts += RHS.ZExts; 15825 Shift += RHS.Shift; 15826 return *this; 15827 } 15828 15829 bool operator==(const Cost &RHS) const { 15830 return Loads == RHS.Loads && Truncates == RHS.Truncates && 15831 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 15832 ZExts == RHS.ZExts && Shift == RHS.Shift; 15833 } 15834 15835 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 15836 15837 bool operator<(const Cost &RHS) const { 15838 // Assume cross register banks copies are as expensive as loads. 15839 // FIXME: Do we want some more target hooks? 15840 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 15841 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 15842 // Unless we are optimizing for code size, consider the 15843 // expensive operation first. 15844 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 15845 return ExpensiveOpsLHS < ExpensiveOpsRHS; 15846 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 15847 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 15848 } 15849 15850 bool operator>(const Cost &RHS) const { return RHS < *this; } 15851 15852 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 15853 15854 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 15855 }; 15856 15857 // The last instruction that represent the slice. This should be a 15858 // truncate instruction. 15859 SDNode *Inst; 15860 15861 // The original load instruction. 15862 LoadSDNode *Origin; 15863 15864 // The right shift amount in bits from the original load. 15865 unsigned Shift; 15866 15867 // The DAG from which Origin came from. 15868 // This is used to get some contextual information about legal types, etc. 15869 SelectionDAG *DAG; 15870 15871 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 15872 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 15873 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 15874 15875 /// Get the bits used in a chunk of bits \p BitWidth large. 15876 /// \return Result is \p BitWidth and has used bits set to 1 and 15877 /// not used bits set to 0. 15878 APInt getUsedBits() const { 15879 // Reproduce the trunc(lshr) sequence: 15880 // - Start from the truncated value. 15881 // - Zero extend to the desired bit width. 15882 // - Shift left. 15883 assert(Origin && "No original load to compare against."); 15884 unsigned BitWidth = Origin->getValueSizeInBits(0); 15885 assert(Inst && "This slice is not bound to an instruction"); 15886 assert(Inst->getValueSizeInBits(0) <= BitWidth && 15887 "Extracted slice is bigger than the whole type!"); 15888 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 15889 UsedBits.setAllBits(); 15890 UsedBits = UsedBits.zext(BitWidth); 15891 UsedBits <<= Shift; 15892 return UsedBits; 15893 } 15894 15895 /// Get the size of the slice to be loaded in bytes. 15896 unsigned getLoadedSize() const { 15897 unsigned SliceSize = getUsedBits().countPopulation(); 15898 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 15899 return SliceSize / 8; 15900 } 15901 15902 /// Get the type that will be loaded for this slice. 15903 /// Note: This may not be the final type for the slice. 15904 EVT getLoadedType() const { 15905 assert(DAG && "Missing context"); 15906 LLVMContext &Ctxt = *DAG->getContext(); 15907 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 15908 } 15909 15910 /// Get the alignment of the load used for this slice. 15911 Align getAlign() const { 15912 Align Alignment = Origin->getAlign(); 15913 uint64_t Offset = getOffsetFromBase(); 15914 if (Offset != 0) 15915 Alignment = commonAlignment(Alignment, Alignment.value() + Offset); 15916 return Alignment; 15917 } 15918 15919 /// Check if this slice can be rewritten with legal operations. 15920 bool isLegal() const { 15921 // An invalid slice is not legal. 15922 if (!Origin || !Inst || !DAG) 15923 return false; 15924 15925 // Offsets are for indexed load only, we do not handle that. 15926 if (!Origin->getOffset().isUndef()) 15927 return false; 15928 15929 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 15930 15931 // Check that the type is legal. 15932 EVT SliceType = getLoadedType(); 15933 if (!TLI.isTypeLegal(SliceType)) 15934 return false; 15935 15936 // Check that the load is legal for this type. 15937 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 15938 return false; 15939 15940 // Check that the offset can be computed. 15941 // 1. Check its type. 15942 EVT PtrType = Origin->getBasePtr().getValueType(); 15943 if (PtrType == MVT::Untyped || PtrType.isExtended()) 15944 return false; 15945 15946 // 2. Check that it fits in the immediate. 15947 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 15948 return false; 15949 15950 // 3. Check that the computation is legal. 15951 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 15952 return false; 15953 15954 // Check that the zext is legal if it needs one. 15955 EVT TruncateType = Inst->getValueType(0); 15956 if (TruncateType != SliceType && 15957 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 15958 return false; 15959 15960 return true; 15961 } 15962 15963 /// Get the offset in bytes of this slice in the original chunk of 15964 /// bits. 15965 /// \pre DAG != nullptr. 15966 uint64_t getOffsetFromBase() const { 15967 assert(DAG && "Missing context."); 15968 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 15969 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 15970 uint64_t Offset = Shift / 8; 15971 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 15972 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 15973 "The size of the original loaded type is not a multiple of a" 15974 " byte."); 15975 // If Offset is bigger than TySizeInBytes, it means we are loading all 15976 // zeros. This should have been optimized before in the process. 15977 assert(TySizeInBytes > Offset && 15978 "Invalid shift amount for given loaded size"); 15979 if (IsBigEndian) 15980 Offset = TySizeInBytes - Offset - getLoadedSize(); 15981 return Offset; 15982 } 15983 15984 /// Generate the sequence of instructions to load the slice 15985 /// represented by this object and redirect the uses of this slice to 15986 /// this new sequence of instructions. 15987 /// \pre this->Inst && this->Origin are valid Instructions and this 15988 /// object passed the legal check: LoadedSlice::isLegal returned true. 15989 /// \return The last instruction of the sequence used to load the slice. 15990 SDValue loadSlice() const { 15991 assert(Inst && Origin && "Unable to replace a non-existing slice."); 15992 const SDValue &OldBaseAddr = Origin->getBasePtr(); 15993 SDValue BaseAddr = OldBaseAddr; 15994 // Get the offset in that chunk of bytes w.r.t. the endianness. 15995 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 15996 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 15997 if (Offset) { 15998 // BaseAddr = BaseAddr + Offset. 15999 EVT ArithType = BaseAddr.getValueType(); 16000 SDLoc DL(Origin); 16001 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 16002 DAG->getConstant(Offset, DL, ArithType)); 16003 } 16004 16005 // Create the type of the loaded slice according to its size. 16006 EVT SliceType = getLoadedType(); 16007 16008 // Create the load for the slice. 16009 SDValue LastInst = 16010 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 16011 Origin->getPointerInfo().getWithOffset(Offset), getAlign(), 16012 Origin->getMemOperand()->getFlags()); 16013 // If the final type is not the same as the loaded type, this means that 16014 // we have to pad with zero. Create a zero extend for that. 16015 EVT FinalType = Inst->getValueType(0); 16016 if (SliceType != FinalType) 16017 LastInst = 16018 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 16019 return LastInst; 16020 } 16021 16022 /// Check if this slice can be merged with an expensive cross register 16023 /// bank copy. E.g., 16024 /// i = load i32 16025 /// f = bitcast i32 i to float 16026 bool canMergeExpensiveCrossRegisterBankCopy() const { 16027 if (!Inst || !Inst->hasOneUse()) 16028 return false; 16029 SDNode *Use = *Inst->use_begin(); 16030 if (Use->getOpcode() != ISD::BITCAST) 16031 return false; 16032 assert(DAG && "Missing context"); 16033 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 16034 EVT ResVT = Use->getValueType(0); 16035 const TargetRegisterClass *ResRC = 16036 TLI.getRegClassFor(ResVT.getSimpleVT(), Use->isDivergent()); 16037 const TargetRegisterClass *ArgRC = 16038 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT(), 16039 Use->getOperand(0)->isDivergent()); 16040 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 16041 return false; 16042 16043 // At this point, we know that we perform a cross-register-bank copy. 16044 // Check if it is expensive. 16045 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 16046 // Assume bitcasts are cheap, unless both register classes do not 16047 // explicitly share a common sub class. 16048 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 16049 return false; 16050 16051 // Check if it will be merged with the load. 16052 // 1. Check the alignment constraint. 16053 Align RequiredAlignment = DAG->getDataLayout().getABITypeAlign( 16054 ResVT.getTypeForEVT(*DAG->getContext())); 16055 16056 if (RequiredAlignment > getAlign()) 16057 return false; 16058 16059 // 2. Check that the load is a legal operation for that type. 16060 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 16061 return false; 16062 16063 // 3. Check that we do not have a zext in the way. 16064 if (Inst->getValueType(0) != getLoadedType()) 16065 return false; 16066 16067 return true; 16068 } 16069 }; 16070 16071 } // end anonymous namespace 16072 16073 /// Check that all bits set in \p UsedBits form a dense region, i.e., 16074 /// \p UsedBits looks like 0..0 1..1 0..0. 16075 static bool areUsedBitsDense(const APInt &UsedBits) { 16076 // If all the bits are one, this is dense! 16077 if (UsedBits.isAllOnesValue()) 16078 return true; 16079 16080 // Get rid of the unused bits on the right. 16081 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 16082 // Get rid of the unused bits on the left. 16083 if (NarrowedUsedBits.countLeadingZeros()) 16084 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 16085 // Check that the chunk of bits is completely used. 16086 return NarrowedUsedBits.isAllOnesValue(); 16087 } 16088 16089 /// Check whether or not \p First and \p Second are next to each other 16090 /// in memory. This means that there is no hole between the bits loaded 16091 /// by \p First and the bits loaded by \p Second. 16092 static bool areSlicesNextToEachOther(const LoadedSlice &First, 16093 const LoadedSlice &Second) { 16094 assert(First.Origin == Second.Origin && First.Origin && 16095 "Unable to match different memory origins."); 16096 APInt UsedBits = First.getUsedBits(); 16097 assert((UsedBits & Second.getUsedBits()) == 0 && 16098 "Slices are not supposed to overlap."); 16099 UsedBits |= Second.getUsedBits(); 16100 return areUsedBitsDense(UsedBits); 16101 } 16102 16103 /// Adjust the \p GlobalLSCost according to the target 16104 /// paring capabilities and the layout of the slices. 16105 /// \pre \p GlobalLSCost should account for at least as many loads as 16106 /// there is in the slices in \p LoadedSlices. 16107 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 16108 LoadedSlice::Cost &GlobalLSCost) { 16109 unsigned NumberOfSlices = LoadedSlices.size(); 16110 // If there is less than 2 elements, no pairing is possible. 16111 if (NumberOfSlices < 2) 16112 return; 16113 16114 // Sort the slices so that elements that are likely to be next to each 16115 // other in memory are next to each other in the list. 16116 llvm::sort(LoadedSlices, [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 16117 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 16118 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 16119 }); 16120 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 16121 // First (resp. Second) is the first (resp. Second) potentially candidate 16122 // to be placed in a paired load. 16123 const LoadedSlice *First = nullptr; 16124 const LoadedSlice *Second = nullptr; 16125 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 16126 // Set the beginning of the pair. 16127 First = Second) { 16128 Second = &LoadedSlices[CurrSlice]; 16129 16130 // If First is NULL, it means we start a new pair. 16131 // Get to the next slice. 16132 if (!First) 16133 continue; 16134 16135 EVT LoadedType = First->getLoadedType(); 16136 16137 // If the types of the slices are different, we cannot pair them. 16138 if (LoadedType != Second->getLoadedType()) 16139 continue; 16140 16141 // Check if the target supplies paired loads for this type. 16142 Align RequiredAlignment; 16143 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 16144 // move to the next pair, this type is hopeless. 16145 Second = nullptr; 16146 continue; 16147 } 16148 // Check if we meet the alignment requirement. 16149 if (First->getAlign() < RequiredAlignment) 16150 continue; 16151 16152 // Check that both loads are next to each other in memory. 16153 if (!areSlicesNextToEachOther(*First, *Second)) 16154 continue; 16155 16156 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 16157 --GlobalLSCost.Loads; 16158 // Move to the next pair. 16159 Second = nullptr; 16160 } 16161 } 16162 16163 /// Check the profitability of all involved LoadedSlice. 16164 /// Currently, it is considered profitable if there is exactly two 16165 /// involved slices (1) which are (2) next to each other in memory, and 16166 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 16167 /// 16168 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 16169 /// the elements themselves. 16170 /// 16171 /// FIXME: When the cost model will be mature enough, we can relax 16172 /// constraints (1) and (2). 16173 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 16174 const APInt &UsedBits, bool ForCodeSize) { 16175 unsigned NumberOfSlices = LoadedSlices.size(); 16176 if (StressLoadSlicing) 16177 return NumberOfSlices > 1; 16178 16179 // Check (1). 16180 if (NumberOfSlices != 2) 16181 return false; 16182 16183 // Check (2). 16184 if (!areUsedBitsDense(UsedBits)) 16185 return false; 16186 16187 // Check (3). 16188 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 16189 // The original code has one big load. 16190 OrigCost.Loads = 1; 16191 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 16192 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 16193 // Accumulate the cost of all the slices. 16194 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 16195 GlobalSlicingCost += SliceCost; 16196 16197 // Account as cost in the original configuration the gain obtained 16198 // with the current slices. 16199 OrigCost.addSliceGain(LS); 16200 } 16201 16202 // If the target supports paired load, adjust the cost accordingly. 16203 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 16204 return OrigCost > GlobalSlicingCost; 16205 } 16206 16207 /// If the given load, \p LI, is used only by trunc or trunc(lshr) 16208 /// operations, split it in the various pieces being extracted. 16209 /// 16210 /// This sort of thing is introduced by SROA. 16211 /// This slicing takes care not to insert overlapping loads. 16212 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 16213 bool DAGCombiner::SliceUpLoad(SDNode *N) { 16214 if (Level < AfterLegalizeDAG) 16215 return false; 16216 16217 LoadSDNode *LD = cast<LoadSDNode>(N); 16218 if (!LD->isSimple() || !ISD::isNormalLoad(LD) || 16219 !LD->getValueType(0).isInteger()) 16220 return false; 16221 16222 // The algorithm to split up a load of a scalable vector into individual 16223 // elements currently requires knowing the length of the loaded type, 16224 // so will need adjusting to work on scalable vectors. 16225 if (LD->getValueType(0).isScalableVector()) 16226 return false; 16227 16228 // Keep track of already used bits to detect overlapping values. 16229 // In that case, we will just abort the transformation. 16230 APInt UsedBits(LD->getValueSizeInBits(0), 0); 16231 16232 SmallVector<LoadedSlice, 4> LoadedSlices; 16233 16234 // Check if this load is used as several smaller chunks of bits. 16235 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 16236 // of computation for each trunc. 16237 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 16238 UI != UIEnd; ++UI) { 16239 // Skip the uses of the chain. 16240 if (UI.getUse().getResNo() != 0) 16241 continue; 16242 16243 SDNode *User = *UI; 16244 unsigned Shift = 0; 16245 16246 // Check if this is a trunc(lshr). 16247 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 16248 isa<ConstantSDNode>(User->getOperand(1))) { 16249 Shift = User->getConstantOperandVal(1); 16250 User = *User->use_begin(); 16251 } 16252 16253 // At this point, User is a Truncate, iff we encountered, trunc or 16254 // trunc(lshr). 16255 if (User->getOpcode() != ISD::TRUNCATE) 16256 return false; 16257 16258 // The width of the type must be a power of 2 and greater than 8-bits. 16259 // Otherwise the load cannot be represented in LLVM IR. 16260 // Moreover, if we shifted with a non-8-bits multiple, the slice 16261 // will be across several bytes. We do not support that. 16262 unsigned Width = User->getValueSizeInBits(0); 16263 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 16264 return false; 16265 16266 // Build the slice for this chain of computations. 16267 LoadedSlice LS(User, LD, Shift, &DAG); 16268 APInt CurrentUsedBits = LS.getUsedBits(); 16269 16270 // Check if this slice overlaps with another. 16271 if ((CurrentUsedBits & UsedBits) != 0) 16272 return false; 16273 // Update the bits used globally. 16274 UsedBits |= CurrentUsedBits; 16275 16276 // Check if the new slice would be legal. 16277 if (!LS.isLegal()) 16278 return false; 16279 16280 // Record the slice. 16281 LoadedSlices.push_back(LS); 16282 } 16283 16284 // Abort slicing if it does not seem to be profitable. 16285 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 16286 return false; 16287 16288 ++SlicedLoads; 16289 16290 // Rewrite each chain to use an independent load. 16291 // By construction, each chain can be represented by a unique load. 16292 16293 // Prepare the argument for the new token factor for all the slices. 16294 SmallVector<SDValue, 8> ArgChains; 16295 for (const LoadedSlice &LS : LoadedSlices) { 16296 SDValue SliceInst = LS.loadSlice(); 16297 CombineTo(LS.Inst, SliceInst, true); 16298 if (SliceInst.getOpcode() != ISD::LOAD) 16299 SliceInst = SliceInst.getOperand(0); 16300 assert(SliceInst->getOpcode() == ISD::LOAD && 16301 "It takes more than a zext to get to the loaded slice!!"); 16302 ArgChains.push_back(SliceInst.getValue(1)); 16303 } 16304 16305 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 16306 ArgChains); 16307 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 16308 AddToWorklist(Chain.getNode()); 16309 return true; 16310 } 16311 16312 /// Check to see if V is (and load (ptr), imm), where the load is having 16313 /// specific bytes cleared out. If so, return the byte size being masked out 16314 /// and the shift amount. 16315 static std::pair<unsigned, unsigned> 16316 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 16317 std::pair<unsigned, unsigned> Result(0, 0); 16318 16319 // Check for the structure we're looking for. 16320 if (V->getOpcode() != ISD::AND || 16321 !isa<ConstantSDNode>(V->getOperand(1)) || 16322 !ISD::isNormalLoad(V->getOperand(0).getNode())) 16323 return Result; 16324 16325 // Check the chain and pointer. 16326 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 16327 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 16328 16329 // This only handles simple types. 16330 if (V.getValueType() != MVT::i16 && 16331 V.getValueType() != MVT::i32 && 16332 V.getValueType() != MVT::i64) 16333 return Result; 16334 16335 // Check the constant mask. Invert it so that the bits being masked out are 16336 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 16337 // follow the sign bit for uniformity. 16338 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 16339 unsigned NotMaskLZ = countLeadingZeros(NotMask); 16340 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 16341 unsigned NotMaskTZ = countTrailingZeros(NotMask); 16342 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 16343 if (NotMaskLZ == 64) return Result; // All zero mask. 16344 16345 // See if we have a continuous run of bits. If so, we have 0*1+0* 16346 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 16347 return Result; 16348 16349 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 16350 if (V.getValueType() != MVT::i64 && NotMaskLZ) 16351 NotMaskLZ -= 64-V.getValueSizeInBits(); 16352 16353 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 16354 switch (MaskedBytes) { 16355 case 1: 16356 case 2: 16357 case 4: break; 16358 default: return Result; // All one mask, or 5-byte mask. 16359 } 16360 16361 // Verify that the first bit starts at a multiple of mask so that the access 16362 // is aligned the same as the access width. 16363 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 16364 16365 // For narrowing to be valid, it must be the case that the load the 16366 // immediately preceding memory operation before the store. 16367 if (LD == Chain.getNode()) 16368 ; // ok. 16369 else if (Chain->getOpcode() == ISD::TokenFactor && 16370 SDValue(LD, 1).hasOneUse()) { 16371 // LD has only 1 chain use so they are no indirect dependencies. 16372 if (!LD->isOperandOf(Chain.getNode())) 16373 return Result; 16374 } else 16375 return Result; // Fail. 16376 16377 Result.first = MaskedBytes; 16378 Result.second = NotMaskTZ/8; 16379 return Result; 16380 } 16381 16382 /// Check to see if IVal is something that provides a value as specified by 16383 /// MaskInfo. If so, replace the specified store with a narrower store of 16384 /// truncated IVal. 16385 static SDValue 16386 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 16387 SDValue IVal, StoreSDNode *St, 16388 DAGCombiner *DC) { 16389 unsigned NumBytes = MaskInfo.first; 16390 unsigned ByteShift = MaskInfo.second; 16391 SelectionDAG &DAG = DC->getDAG(); 16392 16393 // Check to see if IVal is all zeros in the part being masked in by the 'or' 16394 // that uses this. If not, this is not a replacement. 16395 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 16396 ByteShift*8, (ByteShift+NumBytes)*8); 16397 if (!DAG.MaskedValueIsZero(IVal, Mask)) return SDValue(); 16398 16399 // Check that it is legal on the target to do this. It is legal if the new 16400 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 16401 // legalization (and the target doesn't explicitly think this is a bad idea). 16402 MVT VT = MVT::getIntegerVT(NumBytes * 8); 16403 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 16404 if (!DC->isTypeLegal(VT)) 16405 return SDValue(); 16406 if (St->getMemOperand() && 16407 !TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 16408 *St->getMemOperand())) 16409 return SDValue(); 16410 16411 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 16412 // shifted by ByteShift and truncated down to NumBytes. 16413 if (ByteShift) { 16414 SDLoc DL(IVal); 16415 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 16416 DAG.getConstant(ByteShift*8, DL, 16417 DC->getShiftAmountTy(IVal.getValueType()))); 16418 } 16419 16420 // Figure out the offset for the store and the alignment of the access. 16421 unsigned StOffset; 16422 if (DAG.getDataLayout().isLittleEndian()) 16423 StOffset = ByteShift; 16424 else 16425 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 16426 16427 SDValue Ptr = St->getBasePtr(); 16428 if (StOffset) { 16429 SDLoc DL(IVal); 16430 Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(StOffset), DL); 16431 } 16432 16433 // Truncate down to the new size. 16434 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 16435 16436 ++OpsNarrowed; 16437 return DAG 16438 .getStore(St->getChain(), SDLoc(St), IVal, Ptr, 16439 St->getPointerInfo().getWithOffset(StOffset), 16440 St->getOriginalAlign()); 16441 } 16442 16443 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 16444 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 16445 /// narrowing the load and store if it would end up being a win for performance 16446 /// or code size. 16447 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 16448 StoreSDNode *ST = cast<StoreSDNode>(N); 16449 if (!ST->isSimple()) 16450 return SDValue(); 16451 16452 SDValue Chain = ST->getChain(); 16453 SDValue Value = ST->getValue(); 16454 SDValue Ptr = ST->getBasePtr(); 16455 EVT VT = Value.getValueType(); 16456 16457 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 16458 return SDValue(); 16459 16460 unsigned Opc = Value.getOpcode(); 16461 16462 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 16463 // is a byte mask indicating a consecutive number of bytes, check to see if 16464 // Y is known to provide just those bytes. If so, we try to replace the 16465 // load + replace + store sequence with a single (narrower) store, which makes 16466 // the load dead. 16467 if (Opc == ISD::OR && EnableShrinkLoadReplaceStoreWithStore) { 16468 std::pair<unsigned, unsigned> MaskedLoad; 16469 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 16470 if (MaskedLoad.first) 16471 if (SDValue NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 16472 Value.getOperand(1), ST,this)) 16473 return NewST; 16474 16475 // Or is commutative, so try swapping X and Y. 16476 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 16477 if (MaskedLoad.first) 16478 if (SDValue NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 16479 Value.getOperand(0), ST,this)) 16480 return NewST; 16481 } 16482 16483 if (!EnableReduceLoadOpStoreWidth) 16484 return SDValue(); 16485 16486 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 16487 Value.getOperand(1).getOpcode() != ISD::Constant) 16488 return SDValue(); 16489 16490 SDValue N0 = Value.getOperand(0); 16491 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 16492 Chain == SDValue(N0.getNode(), 1)) { 16493 LoadSDNode *LD = cast<LoadSDNode>(N0); 16494 if (LD->getBasePtr() != Ptr || 16495 LD->getPointerInfo().getAddrSpace() != 16496 ST->getPointerInfo().getAddrSpace()) 16497 return SDValue(); 16498 16499 // Find the type to narrow it the load / op / store to. 16500 SDValue N1 = Value.getOperand(1); 16501 unsigned BitWidth = N1.getValueSizeInBits(); 16502 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 16503 if (Opc == ISD::AND) 16504 Imm ^= APInt::getAllOnesValue(BitWidth); 16505 if (Imm == 0 || Imm.isAllOnesValue()) 16506 return SDValue(); 16507 unsigned ShAmt = Imm.countTrailingZeros(); 16508 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 16509 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 16510 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 16511 // The narrowing should be profitable, the load/store operation should be 16512 // legal (or custom) and the store size should be equal to the NewVT width. 16513 while (NewBW < BitWidth && 16514 (NewVT.getStoreSizeInBits() != NewBW || 16515 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 16516 !TLI.isNarrowingProfitable(VT, NewVT))) { 16517 NewBW = NextPowerOf2(NewBW); 16518 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 16519 } 16520 if (NewBW >= BitWidth) 16521 return SDValue(); 16522 16523 // If the lsb changed does not start at the type bitwidth boundary, 16524 // start at the previous one. 16525 if (ShAmt % NewBW) 16526 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 16527 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 16528 std::min(BitWidth, ShAmt + NewBW)); 16529 if ((Imm & Mask) == Imm) { 16530 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 16531 if (Opc == ISD::AND) 16532 NewImm ^= APInt::getAllOnesValue(NewBW); 16533 uint64_t PtrOff = ShAmt / 8; 16534 // For big endian targets, we need to adjust the offset to the pointer to 16535 // load the correct bytes. 16536 if (DAG.getDataLayout().isBigEndian()) 16537 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 16538 16539 Align NewAlign = commonAlignment(LD->getAlign(), PtrOff); 16540 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 16541 if (NewAlign < DAG.getDataLayout().getABITypeAlign(NewVTTy)) 16542 return SDValue(); 16543 16544 SDValue NewPtr = 16545 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(PtrOff), SDLoc(LD)); 16546 SDValue NewLD = 16547 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr, 16548 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign, 16549 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 16550 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 16551 DAG.getConstant(NewImm, SDLoc(Value), 16552 NewVT)); 16553 SDValue NewST = 16554 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr, 16555 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign); 16556 16557 AddToWorklist(NewPtr.getNode()); 16558 AddToWorklist(NewLD.getNode()); 16559 AddToWorklist(NewVal.getNode()); 16560 WorklistRemover DeadNodes(*this); 16561 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 16562 ++OpsNarrowed; 16563 return NewST; 16564 } 16565 } 16566 16567 return SDValue(); 16568 } 16569 16570 /// For a given floating point load / store pair, if the load value isn't used 16571 /// by any other operations, then consider transforming the pair to integer 16572 /// load / store operations if the target deems the transformation profitable. 16573 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 16574 StoreSDNode *ST = cast<StoreSDNode>(N); 16575 SDValue Value = ST->getValue(); 16576 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 16577 Value.hasOneUse()) { 16578 LoadSDNode *LD = cast<LoadSDNode>(Value); 16579 EVT VT = LD->getMemoryVT(); 16580 if (!VT.isFloatingPoint() || 16581 VT != ST->getMemoryVT() || 16582 LD->isNonTemporal() || 16583 ST->isNonTemporal() || 16584 LD->getPointerInfo().getAddrSpace() != 0 || 16585 ST->getPointerInfo().getAddrSpace() != 0) 16586 return SDValue(); 16587 16588 TypeSize VTSize = VT.getSizeInBits(); 16589 16590 // We don't know the size of scalable types at compile time so we cannot 16591 // create an integer of the equivalent size. 16592 if (VTSize.isScalable()) 16593 return SDValue(); 16594 16595 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VTSize.getFixedSize()); 16596 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 16597 !TLI.isOperationLegal(ISD::STORE, IntVT) || 16598 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 16599 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 16600 return SDValue(); 16601 16602 Align LDAlign = LD->getAlign(); 16603 Align STAlign = ST->getAlign(); 16604 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 16605 Align ABIAlign = DAG.getDataLayout().getABITypeAlign(IntVTTy); 16606 if (LDAlign < ABIAlign || STAlign < ABIAlign) 16607 return SDValue(); 16608 16609 SDValue NewLD = 16610 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(), 16611 LD->getPointerInfo(), LDAlign); 16612 16613 SDValue NewST = 16614 DAG.getStore(ST->getChain(), SDLoc(N), NewLD, ST->getBasePtr(), 16615 ST->getPointerInfo(), STAlign); 16616 16617 AddToWorklist(NewLD.getNode()); 16618 AddToWorklist(NewST.getNode()); 16619 WorklistRemover DeadNodes(*this); 16620 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 16621 ++LdStFP2Int; 16622 return NewST; 16623 } 16624 16625 return SDValue(); 16626 } 16627 16628 // This is a helper function for visitMUL to check the profitability 16629 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 16630 // MulNode is the original multiply, AddNode is (add x, c1), 16631 // and ConstNode is c2. 16632 // 16633 // If the (add x, c1) has multiple uses, we could increase 16634 // the number of adds if we make this transformation. 16635 // It would only be worth doing this if we can remove a 16636 // multiply in the process. Check for that here. 16637 // To illustrate: 16638 // (A + c1) * c3 16639 // (A + c2) * c3 16640 // We're checking for cases where we have common "c3 * A" expressions. 16641 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 16642 SDValue &AddNode, 16643 SDValue &ConstNode) { 16644 APInt Val; 16645 16646 // If the add only has one use, this would be OK to do. 16647 if (AddNode.getNode()->hasOneUse()) 16648 return true; 16649 16650 // Walk all the users of the constant with which we're multiplying. 16651 for (SDNode *Use : ConstNode->uses()) { 16652 if (Use == MulNode) // This use is the one we're on right now. Skip it. 16653 continue; 16654 16655 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 16656 SDNode *OtherOp; 16657 SDNode *MulVar = AddNode.getOperand(0).getNode(); 16658 16659 // OtherOp is what we're multiplying against the constant. 16660 if (Use->getOperand(0) == ConstNode) 16661 OtherOp = Use->getOperand(1).getNode(); 16662 else 16663 OtherOp = Use->getOperand(0).getNode(); 16664 16665 // Check to see if multiply is with the same operand of our "add". 16666 // 16667 // ConstNode = CONST 16668 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 16669 // ... 16670 // AddNode = (A + c1) <-- MulVar is A. 16671 // = AddNode * ConstNode <-- current visiting instruction. 16672 // 16673 // If we make this transformation, we will have a common 16674 // multiply (ConstNode * A) that we can save. 16675 if (OtherOp == MulVar) 16676 return true; 16677 16678 // Now check to see if a future expansion will give us a common 16679 // multiply. 16680 // 16681 // ConstNode = CONST 16682 // AddNode = (A + c1) 16683 // ... = AddNode * ConstNode <-- current visiting instruction. 16684 // ... 16685 // OtherOp = (A + c2) 16686 // Use = OtherOp * ConstNode <-- visiting Use. 16687 // 16688 // If we make this transformation, we will have a common 16689 // multiply (CONST * A) after we also do the same transformation 16690 // to the "t2" instruction. 16691 if (OtherOp->getOpcode() == ISD::ADD && 16692 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 16693 OtherOp->getOperand(0).getNode() == MulVar) 16694 return true; 16695 } 16696 } 16697 16698 // Didn't find a case where this would be profitable. 16699 return false; 16700 } 16701 16702 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 16703 unsigned NumStores) { 16704 SmallVector<SDValue, 8> Chains; 16705 SmallPtrSet<const SDNode *, 8> Visited; 16706 SDLoc StoreDL(StoreNodes[0].MemNode); 16707 16708 for (unsigned i = 0; i < NumStores; ++i) { 16709 Visited.insert(StoreNodes[i].MemNode); 16710 } 16711 16712 // don't include nodes that are children or repeated nodes. 16713 for (unsigned i = 0; i < NumStores; ++i) { 16714 if (Visited.insert(StoreNodes[i].MemNode->getChain().getNode()).second) 16715 Chains.push_back(StoreNodes[i].MemNode->getChain()); 16716 } 16717 16718 assert(Chains.size() > 0 && "Chain should have generated a chain"); 16719 return DAG.getTokenFactor(StoreDL, Chains); 16720 } 16721 16722 bool DAGCombiner::mergeStoresOfConstantsOrVecElts( 16723 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores, 16724 bool IsConstantSrc, bool UseVector, bool UseTrunc) { 16725 // Make sure we have something to merge. 16726 if (NumStores < 2) 16727 return false; 16728 16729 // The latest Node in the DAG. 16730 SDLoc DL(StoreNodes[0].MemNode); 16731 16732 TypeSize ElementSizeBits = MemVT.getStoreSizeInBits(); 16733 unsigned SizeInBits = NumStores * ElementSizeBits; 16734 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; 16735 16736 EVT StoreTy; 16737 if (UseVector) { 16738 unsigned Elts = NumStores * NumMemElts; 16739 // Get the type for the merged vector store. 16740 StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 16741 } else 16742 StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 16743 16744 SDValue StoredVal; 16745 if (UseVector) { 16746 if (IsConstantSrc) { 16747 SmallVector<SDValue, 8> BuildVector; 16748 for (unsigned I = 0; I != NumStores; ++I) { 16749 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode); 16750 SDValue Val = St->getValue(); 16751 // If constant is of the wrong type, convert it now. 16752 if (MemVT != Val.getValueType()) { 16753 Val = peekThroughBitcasts(Val); 16754 // Deal with constants of wrong size. 16755 if (ElementSizeBits != Val.getValueSizeInBits()) { 16756 EVT IntMemVT = 16757 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 16758 if (isa<ConstantFPSDNode>(Val)) { 16759 // Not clear how to truncate FP values. 16760 return false; 16761 } else if (auto *C = dyn_cast<ConstantSDNode>(Val)) 16762 Val = DAG.getConstant(C->getAPIntValue() 16763 .zextOrTrunc(Val.getValueSizeInBits()) 16764 .zextOrTrunc(ElementSizeBits), 16765 SDLoc(C), IntMemVT); 16766 } 16767 // Make sure correctly size type is the correct type. 16768 Val = DAG.getBitcast(MemVT, Val); 16769 } 16770 BuildVector.push_back(Val); 16771 } 16772 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS 16773 : ISD::BUILD_VECTOR, 16774 DL, StoreTy, BuildVector); 16775 } else { 16776 SmallVector<SDValue, 8> Ops; 16777 for (unsigned i = 0; i < NumStores; ++i) { 16778 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 16779 SDValue Val = peekThroughBitcasts(St->getValue()); 16780 // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of 16781 // type MemVT. If the underlying value is not the correct 16782 // type, but it is an extraction of an appropriate vector we 16783 // can recast Val to be of the correct type. This may require 16784 // converting between EXTRACT_VECTOR_ELT and 16785 // EXTRACT_SUBVECTOR. 16786 if ((MemVT != Val.getValueType()) && 16787 (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 16788 Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) { 16789 EVT MemVTScalarTy = MemVT.getScalarType(); 16790 // We may need to add a bitcast here to get types to line up. 16791 if (MemVTScalarTy != Val.getValueType().getScalarType()) { 16792 Val = DAG.getBitcast(MemVT, Val); 16793 } else { 16794 unsigned OpC = MemVT.isVector() ? ISD::EXTRACT_SUBVECTOR 16795 : ISD::EXTRACT_VECTOR_ELT; 16796 SDValue Vec = Val.getOperand(0); 16797 SDValue Idx = Val.getOperand(1); 16798 Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Idx); 16799 } 16800 } 16801 Ops.push_back(Val); 16802 } 16803 16804 // Build the extracted vector elements back into a vector. 16805 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS 16806 : ISD::BUILD_VECTOR, 16807 DL, StoreTy, Ops); 16808 } 16809 } else { 16810 // We should always use a vector store when merging extracted vector 16811 // elements, so this path implies a store of constants. 16812 assert(IsConstantSrc && "Merged vector elements should use vector store"); 16813 16814 APInt StoreInt(SizeInBits, 0); 16815 16816 // Construct a single integer constant which is made of the smaller 16817 // constant inputs. 16818 bool IsLE = DAG.getDataLayout().isLittleEndian(); 16819 for (unsigned i = 0; i < NumStores; ++i) { 16820 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 16821 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 16822 16823 SDValue Val = St->getValue(); 16824 Val = peekThroughBitcasts(Val); 16825 StoreInt <<= ElementSizeBits; 16826 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 16827 StoreInt |= C->getAPIntValue() 16828 .zextOrTrunc(ElementSizeBits) 16829 .zextOrTrunc(SizeInBits); 16830 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 16831 StoreInt |= C->getValueAPF() 16832 .bitcastToAPInt() 16833 .zextOrTrunc(ElementSizeBits) 16834 .zextOrTrunc(SizeInBits); 16835 // If fp truncation is necessary give up for now. 16836 if (MemVT.getSizeInBits() != ElementSizeBits) 16837 return false; 16838 } else { 16839 llvm_unreachable("Invalid constant element type"); 16840 } 16841 } 16842 16843 // Create the new Load and Store operations. 16844 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 16845 } 16846 16847 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 16848 SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores); 16849 16850 // make sure we use trunc store if it's necessary to be legal. 16851 SDValue NewStore; 16852 if (!UseTrunc) { 16853 NewStore = 16854 DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(), 16855 FirstInChain->getPointerInfo(), FirstInChain->getAlign()); 16856 } else { // Must be realized as a trunc store 16857 EVT LegalizedStoredValTy = 16858 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 16859 unsigned LegalizedStoreSize = LegalizedStoredValTy.getSizeInBits(); 16860 ConstantSDNode *C = cast<ConstantSDNode>(StoredVal); 16861 SDValue ExtendedStoreVal = 16862 DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL, 16863 LegalizedStoredValTy); 16864 NewStore = DAG.getTruncStore( 16865 NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(), 16866 FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/, 16867 FirstInChain->getAlign(), FirstInChain->getMemOperand()->getFlags()); 16868 } 16869 16870 // Replace all merged stores with the new store. 16871 for (unsigned i = 0; i < NumStores; ++i) 16872 CombineTo(StoreNodes[i].MemNode, NewStore); 16873 16874 AddToWorklist(NewChain.getNode()); 16875 return true; 16876 } 16877 16878 void DAGCombiner::getStoreMergeCandidates( 16879 StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes, 16880 SDNode *&RootNode) { 16881 // This holds the base pointer, index, and the offset in bytes from the base 16882 // pointer. We must have a base and an offset. Do not handle stores to undef 16883 // base pointers. 16884 BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG); 16885 if (!BasePtr.getBase().getNode() || BasePtr.getBase().isUndef()) 16886 return; 16887 16888 SDValue Val = peekThroughBitcasts(St->getValue()); 16889 StoreSource StoreSrc = getStoreSource(Val); 16890 assert(StoreSrc != StoreSource::Unknown && "Expected known source for store"); 16891 16892 // Match on loadbaseptr if relevant. 16893 EVT MemVT = St->getMemoryVT(); 16894 BaseIndexOffset LBasePtr; 16895 EVT LoadVT; 16896 if (StoreSrc == StoreSource::Load) { 16897 auto *Ld = cast<LoadSDNode>(Val); 16898 LBasePtr = BaseIndexOffset::match(Ld, DAG); 16899 LoadVT = Ld->getMemoryVT(); 16900 // Load and store should be the same type. 16901 if (MemVT != LoadVT) 16902 return; 16903 // Loads must only have one use. 16904 if (!Ld->hasNUsesOfValue(1, 0)) 16905 return; 16906 // The memory operands must not be volatile/indexed/atomic. 16907 // TODO: May be able to relax for unordered atomics (see D66309) 16908 if (!Ld->isSimple() || Ld->isIndexed()) 16909 return; 16910 } 16911 auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr, 16912 int64_t &Offset) -> bool { 16913 // The memory operands must not be volatile/indexed/atomic. 16914 // TODO: May be able to relax for unordered atomics (see D66309) 16915 if (!Other->isSimple() || Other->isIndexed()) 16916 return false; 16917 // Don't mix temporal stores with non-temporal stores. 16918 if (St->isNonTemporal() != Other->isNonTemporal()) 16919 return false; 16920 SDValue OtherBC = peekThroughBitcasts(Other->getValue()); 16921 // Allow merging constants of different types as integers. 16922 bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT()) 16923 : Other->getMemoryVT() != MemVT; 16924 switch (StoreSrc) { 16925 case StoreSource::Load: { 16926 if (NoTypeMatch) 16927 return false; 16928 // The Load's Base Ptr must also match. 16929 auto *OtherLd = dyn_cast<LoadSDNode>(OtherBC); 16930 if (!OtherLd) 16931 return false; 16932 BaseIndexOffset LPtr = BaseIndexOffset::match(OtherLd, DAG); 16933 if (LoadVT != OtherLd->getMemoryVT()) 16934 return false; 16935 // Loads must only have one use. 16936 if (!OtherLd->hasNUsesOfValue(1, 0)) 16937 return false; 16938 // The memory operands must not be volatile/indexed/atomic. 16939 // TODO: May be able to relax for unordered atomics (see D66309) 16940 if (!OtherLd->isSimple() || OtherLd->isIndexed()) 16941 return false; 16942 // Don't mix temporal loads with non-temporal loads. 16943 if (cast<LoadSDNode>(Val)->isNonTemporal() != OtherLd->isNonTemporal()) 16944 return false; 16945 if (!(LBasePtr.equalBaseIndex(LPtr, DAG))) 16946 return false; 16947 break; 16948 } 16949 case StoreSource::Constant: 16950 if (NoTypeMatch) 16951 return false; 16952 if (!isIntOrFPConstant(OtherBC)) 16953 return false; 16954 break; 16955 case StoreSource::Extract: 16956 // Do not merge truncated stores here. 16957 if (Other->isTruncatingStore()) 16958 return false; 16959 if (!MemVT.bitsEq(OtherBC.getValueType())) 16960 return false; 16961 if (OtherBC.getOpcode() != ISD::EXTRACT_VECTOR_ELT && 16962 OtherBC.getOpcode() != ISD::EXTRACT_SUBVECTOR) 16963 return false; 16964 break; 16965 default: 16966 llvm_unreachable("Unhandled store source for merging"); 16967 } 16968 Ptr = BaseIndexOffset::match(Other, DAG); 16969 return (BasePtr.equalBaseIndex(Ptr, DAG, Offset)); 16970 }; 16971 16972 // Check if the pair of StoreNode and the RootNode already bail out many 16973 // times which is over the limit in dependence check. 16974 auto OverLimitInDependenceCheck = [&](SDNode *StoreNode, 16975 SDNode *RootNode) -> bool { 16976 auto RootCount = StoreRootCountMap.find(StoreNode); 16977 return RootCount != StoreRootCountMap.end() && 16978 RootCount->second.first == RootNode && 16979 RootCount->second.second > StoreMergeDependenceLimit; 16980 }; 16981 16982 auto TryToAddCandidate = [&](SDNode::use_iterator UseIter) { 16983 // This must be a chain use. 16984 if (UseIter.getOperandNo() != 0) 16985 return; 16986 if (auto *OtherStore = dyn_cast<StoreSDNode>(*UseIter)) { 16987 BaseIndexOffset Ptr; 16988 int64_t PtrDiff; 16989 if (CandidateMatch(OtherStore, Ptr, PtrDiff) && 16990 !OverLimitInDependenceCheck(OtherStore, RootNode)) 16991 StoreNodes.push_back(MemOpLink(OtherStore, PtrDiff)); 16992 } 16993 }; 16994 16995 // We looking for a root node which is an ancestor to all mergable 16996 // stores. We search up through a load, to our root and then down 16997 // through all children. For instance we will find Store{1,2,3} if 16998 // St is Store1, Store2. or Store3 where the root is not a load 16999 // which always true for nonvolatile ops. TODO: Expand 17000 // the search to find all valid candidates through multiple layers of loads. 17001 // 17002 // Root 17003 // |-------|-------| 17004 // Load Load Store3 17005 // | | 17006 // Store1 Store2 17007 // 17008 // FIXME: We should be able to climb and 17009 // descend TokenFactors to find candidates as well. 17010 17011 RootNode = St->getChain().getNode(); 17012 17013 unsigned NumNodesExplored = 0; 17014 const unsigned MaxSearchNodes = 1024; 17015 if (auto *Ldn = dyn_cast<LoadSDNode>(RootNode)) { 17016 RootNode = Ldn->getChain().getNode(); 17017 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); 17018 I != E && NumNodesExplored < MaxSearchNodes; ++I, ++NumNodesExplored) { 17019 if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) { // walk down chain 17020 for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2) 17021 TryToAddCandidate(I2); 17022 } 17023 } 17024 } else { 17025 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); 17026 I != E && NumNodesExplored < MaxSearchNodes; ++I, ++NumNodesExplored) 17027 TryToAddCandidate(I); 17028 } 17029 } 17030 17031 // We need to check that merging these stores does not cause a loop in 17032 // the DAG. Any store candidate may depend on another candidate 17033 // indirectly through its operand (we already consider dependencies 17034 // through the chain). Check in parallel by searching up from 17035 // non-chain operands of candidates. 17036 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 17037 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores, 17038 SDNode *RootNode) { 17039 // FIXME: We should be able to truncate a full search of 17040 // predecessors by doing a BFS and keeping tabs the originating 17041 // stores from which worklist nodes come from in a similar way to 17042 // TokenFactor simplfication. 17043 17044 SmallPtrSet<const SDNode *, 32> Visited; 17045 SmallVector<const SDNode *, 8> Worklist; 17046 17047 // RootNode is a predecessor to all candidates so we need not search 17048 // past it. Add RootNode (peeking through TokenFactors). Do not count 17049 // these towards size check. 17050 17051 Worklist.push_back(RootNode); 17052 while (!Worklist.empty()) { 17053 auto N = Worklist.pop_back_val(); 17054 if (!Visited.insert(N).second) 17055 continue; // Already present in Visited. 17056 if (N->getOpcode() == ISD::TokenFactor) { 17057 for (SDValue Op : N->ops()) 17058 Worklist.push_back(Op.getNode()); 17059 } 17060 } 17061 17062 // Don't count pruning nodes towards max. 17063 unsigned int Max = 1024 + Visited.size(); 17064 // Search Ops of store candidates. 17065 for (unsigned i = 0; i < NumStores; ++i) { 17066 SDNode *N = StoreNodes[i].MemNode; 17067 // Of the 4 Store Operands: 17068 // * Chain (Op 0) -> We have already considered these 17069 // in candidate selection and can be 17070 // safely ignored 17071 // * Value (Op 1) -> Cycles may happen (e.g. through load chains) 17072 // * Address (Op 2) -> Merged addresses may only vary by a fixed constant, 17073 // but aren't necessarily fromt the same base node, so 17074 // cycles possible (e.g. via indexed store). 17075 // * (Op 3) -> Represents the pre or post-indexing offset (or undef for 17076 // non-indexed stores). Not constant on all targets (e.g. ARM) 17077 // and so can participate in a cycle. 17078 for (unsigned j = 1; j < N->getNumOperands(); ++j) 17079 Worklist.push_back(N->getOperand(j).getNode()); 17080 } 17081 // Search through DAG. We can stop early if we find a store node. 17082 for (unsigned i = 0; i < NumStores; ++i) 17083 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist, 17084 Max)) { 17085 // If the searching bail out, record the StoreNode and RootNode in the 17086 // StoreRootCountMap. If we have seen the pair many times over a limit, 17087 // we won't add the StoreNode into StoreNodes set again. 17088 if (Visited.size() >= Max) { 17089 auto &RootCount = StoreRootCountMap[StoreNodes[i].MemNode]; 17090 if (RootCount.first == RootNode) 17091 RootCount.second++; 17092 else 17093 RootCount = {RootNode, 1}; 17094 } 17095 return false; 17096 } 17097 return true; 17098 } 17099 17100 unsigned 17101 DAGCombiner::getConsecutiveStores(SmallVectorImpl<MemOpLink> &StoreNodes, 17102 int64_t ElementSizeBytes) const { 17103 while (true) { 17104 // Find a store past the width of the first store. 17105 size_t StartIdx = 0; 17106 while ((StartIdx + 1 < StoreNodes.size()) && 17107 StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes != 17108 StoreNodes[StartIdx + 1].OffsetFromBase) 17109 ++StartIdx; 17110 17111 // Bail if we don't have enough candidates to merge. 17112 if (StartIdx + 1 >= StoreNodes.size()) 17113 return 0; 17114 17115 // Trim stores that overlapped with the first store. 17116 if (StartIdx) 17117 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx); 17118 17119 // Scan the memory operations on the chain and find the first 17120 // non-consecutive store memory address. 17121 unsigned NumConsecutiveStores = 1; 17122 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 17123 // Check that the addresses are consecutive starting from the second 17124 // element in the list of stores. 17125 for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) { 17126 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 17127 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 17128 break; 17129 NumConsecutiveStores = i + 1; 17130 } 17131 if (NumConsecutiveStores > 1) 17132 return NumConsecutiveStores; 17133 17134 // There are no consecutive stores at the start of the list. 17135 // Remove the first store and try again. 17136 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1); 17137 } 17138 } 17139 17140 bool DAGCombiner::tryStoreMergeOfConstants( 17141 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumConsecutiveStores, 17142 EVT MemVT, SDNode *RootNode, bool AllowVectors) { 17143 LLVMContext &Context = *DAG.getContext(); 17144 const DataLayout &DL = DAG.getDataLayout(); 17145 int64_t ElementSizeBytes = MemVT.getStoreSize(); 17146 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; 17147 bool MadeChange = false; 17148 17149 // Store the constants into memory as one consecutive store. 17150 while (NumConsecutiveStores >= 2) { 17151 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 17152 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 17153 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 17154 unsigned LastLegalType = 1; 17155 unsigned LastLegalVectorType = 1; 17156 bool LastIntegerTrunc = false; 17157 bool NonZero = false; 17158 unsigned FirstZeroAfterNonZero = NumConsecutiveStores; 17159 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 17160 StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode); 17161 SDValue StoredVal = ST->getValue(); 17162 bool IsElementZero = false; 17163 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) 17164 IsElementZero = C->isNullValue(); 17165 else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) 17166 IsElementZero = C->getConstantFPValue()->isNullValue(); 17167 if (IsElementZero) { 17168 if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores) 17169 FirstZeroAfterNonZero = i; 17170 } 17171 NonZero |= !IsElementZero; 17172 17173 // Find a legal type for the constant store. 17174 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 17175 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 17176 bool IsFast = false; 17177 17178 // Break early when size is too large to be legal. 17179 if (StoreTy.getSizeInBits() > MaximumLegalStoreInBits) 17180 break; 17181 17182 if (TLI.isTypeLegal(StoreTy) && 17183 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 17184 TLI.allowsMemoryAccess(Context, DL, StoreTy, 17185 *FirstInChain->getMemOperand(), &IsFast) && 17186 IsFast) { 17187 LastIntegerTrunc = false; 17188 LastLegalType = i + 1; 17189 // Or check whether a truncstore is legal. 17190 } else if (TLI.getTypeAction(Context, StoreTy) == 17191 TargetLowering::TypePromoteInteger) { 17192 EVT LegalizedStoredValTy = 17193 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 17194 if (TLI.isTruncStoreLegal(LegalizedStoredValTy, StoreTy) && 17195 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValTy, DAG) && 17196 TLI.allowsMemoryAccess(Context, DL, StoreTy, 17197 *FirstInChain->getMemOperand(), &IsFast) && 17198 IsFast) { 17199 LastIntegerTrunc = true; 17200 LastLegalType = i + 1; 17201 } 17202 } 17203 17204 // We only use vectors if the constant is known to be zero or the 17205 // target allows it and the function is not marked with the 17206 // noimplicitfloat attribute. 17207 if ((!NonZero || 17208 TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) && 17209 AllowVectors) { 17210 // Find a legal type for the vector store. 17211 unsigned Elts = (i + 1) * NumMemElts; 17212 EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 17213 if (TLI.isTypeLegal(Ty) && TLI.isTypeLegal(MemVT) && 17214 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) && 17215 TLI.allowsMemoryAccess(Context, DL, Ty, 17216 *FirstInChain->getMemOperand(), &IsFast) && 17217 IsFast) 17218 LastLegalVectorType = i + 1; 17219 } 17220 } 17221 17222 bool UseVector = (LastLegalVectorType > LastLegalType) && AllowVectors; 17223 unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType; 17224 17225 // Check if we found a legal integer type that creates a meaningful 17226 // merge. 17227 if (NumElem < 2) { 17228 // We know that candidate stores are in order and of correct 17229 // shape. While there is no mergeable sequence from the 17230 // beginning one may start later in the sequence. The only 17231 // reason a merge of size N could have failed where another of 17232 // the same size would not have, is if the alignment has 17233 // improved or we've dropped a non-zero value. Drop as many 17234 // candidates as we can here. 17235 unsigned NumSkip = 1; 17236 while ((NumSkip < NumConsecutiveStores) && 17237 (NumSkip < FirstZeroAfterNonZero) && 17238 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) 17239 NumSkip++; 17240 17241 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 17242 NumConsecutiveStores -= NumSkip; 17243 continue; 17244 } 17245 17246 // Check that we can merge these candidates without causing a cycle. 17247 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem, 17248 RootNode)) { 17249 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 17250 NumConsecutiveStores -= NumElem; 17251 continue; 17252 } 17253 17254 MadeChange |= mergeStoresOfConstantsOrVecElts( 17255 StoreNodes, MemVT, NumElem, true, UseVector, LastIntegerTrunc); 17256 17257 // Remove merged stores for next iteration. 17258 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 17259 NumConsecutiveStores -= NumElem; 17260 } 17261 return MadeChange; 17262 } 17263 17264 bool DAGCombiner::tryStoreMergeOfExtracts( 17265 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumConsecutiveStores, 17266 EVT MemVT, SDNode *RootNode) { 17267 LLVMContext &Context = *DAG.getContext(); 17268 const DataLayout &DL = DAG.getDataLayout(); 17269 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; 17270 bool MadeChange = false; 17271 17272 // Loop on Consecutive Stores on success. 17273 while (NumConsecutiveStores >= 2) { 17274 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 17275 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 17276 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 17277 unsigned NumStoresToMerge = 1; 17278 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 17279 // Find a legal type for the vector store. 17280 unsigned Elts = (i + 1) * NumMemElts; 17281 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 17282 bool IsFast = false; 17283 17284 // Break early when size is too large to be legal. 17285 if (Ty.getSizeInBits() > MaximumLegalStoreInBits) 17286 break; 17287 17288 if (TLI.isTypeLegal(Ty) && TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) && 17289 TLI.allowsMemoryAccess(Context, DL, Ty, 17290 *FirstInChain->getMemOperand(), &IsFast) && 17291 IsFast) 17292 NumStoresToMerge = i + 1; 17293 } 17294 17295 // Check if we found a legal integer type creating a meaningful 17296 // merge. 17297 if (NumStoresToMerge < 2) { 17298 // We know that candidate stores are in order and of correct 17299 // shape. While there is no mergeable sequence from the 17300 // beginning one may start later in the sequence. The only 17301 // reason a merge of size N could have failed where another of 17302 // the same size would not have, is if the alignment has 17303 // improved. Drop as many candidates as we can here. 17304 unsigned NumSkip = 1; 17305 while ((NumSkip < NumConsecutiveStores) && 17306 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) 17307 NumSkip++; 17308 17309 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 17310 NumConsecutiveStores -= NumSkip; 17311 continue; 17312 } 17313 17314 // Check that we can merge these candidates without causing a cycle. 17315 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumStoresToMerge, 17316 RootNode)) { 17317 StoreNodes.erase(StoreNodes.begin(), 17318 StoreNodes.begin() + NumStoresToMerge); 17319 NumConsecutiveStores -= NumStoresToMerge; 17320 continue; 17321 } 17322 17323 MadeChange |= mergeStoresOfConstantsOrVecElts( 17324 StoreNodes, MemVT, NumStoresToMerge, false, true, false); 17325 17326 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumStoresToMerge); 17327 NumConsecutiveStores -= NumStoresToMerge; 17328 } 17329 return MadeChange; 17330 } 17331 17332 bool DAGCombiner::tryStoreMergeOfLoads(SmallVectorImpl<MemOpLink> &StoreNodes, 17333 unsigned NumConsecutiveStores, EVT MemVT, 17334 SDNode *RootNode, bool AllowVectors, 17335 bool IsNonTemporalStore, 17336 bool IsNonTemporalLoad) { 17337 LLVMContext &Context = *DAG.getContext(); 17338 const DataLayout &DL = DAG.getDataLayout(); 17339 int64_t ElementSizeBytes = MemVT.getStoreSize(); 17340 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; 17341 bool MadeChange = false; 17342 17343 // Look for load nodes which are used by the stored values. 17344 SmallVector<MemOpLink, 8> LoadNodes; 17345 17346 // Find acceptable loads. Loads need to have the same chain (token factor), 17347 // must not be zext, volatile, indexed, and they must be consecutive. 17348 BaseIndexOffset LdBasePtr; 17349 17350 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 17351 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 17352 SDValue Val = peekThroughBitcasts(St->getValue()); 17353 LoadSDNode *Ld = cast<LoadSDNode>(Val); 17354 17355 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld, DAG); 17356 // If this is not the first ptr that we check. 17357 int64_t LdOffset = 0; 17358 if (LdBasePtr.getBase().getNode()) { 17359 // The base ptr must be the same. 17360 if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset)) 17361 break; 17362 } else { 17363 // Check that all other base pointers are the same as this one. 17364 LdBasePtr = LdPtr; 17365 } 17366 17367 // We found a potential memory operand to merge. 17368 LoadNodes.push_back(MemOpLink(Ld, LdOffset)); 17369 } 17370 17371 while (NumConsecutiveStores >= 2 && LoadNodes.size() >= 2) { 17372 Align RequiredAlignment; 17373 bool NeedRotate = false; 17374 if (LoadNodes.size() == 2) { 17375 // If we have load/store pair instructions and we only have two values, 17376 // don't bother merging. 17377 if (TLI.hasPairedLoad(MemVT, RequiredAlignment) && 17378 StoreNodes[0].MemNode->getAlign() >= RequiredAlignment) { 17379 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2); 17380 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + 2); 17381 break; 17382 } 17383 // If the loads are reversed, see if we can rotate the halves into place. 17384 int64_t Offset0 = LoadNodes[0].OffsetFromBase; 17385 int64_t Offset1 = LoadNodes[1].OffsetFromBase; 17386 EVT PairVT = EVT::getIntegerVT(Context, ElementSizeBytes * 8 * 2); 17387 if (Offset0 - Offset1 == ElementSizeBytes && 17388 (hasOperation(ISD::ROTL, PairVT) || 17389 hasOperation(ISD::ROTR, PairVT))) { 17390 std::swap(LoadNodes[0], LoadNodes[1]); 17391 NeedRotate = true; 17392 } 17393 } 17394 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 17395 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 17396 Align FirstStoreAlign = FirstInChain->getAlign(); 17397 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 17398 17399 // Scan the memory operations on the chain and find the first 17400 // non-consecutive load memory address. These variables hold the index in 17401 // the store node array. 17402 17403 unsigned LastConsecutiveLoad = 1; 17404 17405 // This variable refers to the size and not index in the array. 17406 unsigned LastLegalVectorType = 1; 17407 unsigned LastLegalIntegerType = 1; 17408 bool isDereferenceable = true; 17409 bool DoIntegerTruncate = false; 17410 int64_t StartAddress = LoadNodes[0].OffsetFromBase; 17411 SDValue LoadChain = FirstLoad->getChain(); 17412 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 17413 // All loads must share the same chain. 17414 if (LoadNodes[i].MemNode->getChain() != LoadChain) 17415 break; 17416 17417 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 17418 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 17419 break; 17420 LastConsecutiveLoad = i; 17421 17422 if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable()) 17423 isDereferenceable = false; 17424 17425 // Find a legal type for the vector store. 17426 unsigned Elts = (i + 1) * NumMemElts; 17427 EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 17428 17429 // Break early when size is too large to be legal. 17430 if (StoreTy.getSizeInBits() > MaximumLegalStoreInBits) 17431 break; 17432 17433 bool IsFastSt = false; 17434 bool IsFastLd = false; 17435 if (TLI.isTypeLegal(StoreTy) && 17436 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 17437 TLI.allowsMemoryAccess(Context, DL, StoreTy, 17438 *FirstInChain->getMemOperand(), &IsFastSt) && 17439 IsFastSt && 17440 TLI.allowsMemoryAccess(Context, DL, StoreTy, 17441 *FirstLoad->getMemOperand(), &IsFastLd) && 17442 IsFastLd) { 17443 LastLegalVectorType = i + 1; 17444 } 17445 17446 // Find a legal type for the integer store. 17447 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 17448 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 17449 if (TLI.isTypeLegal(StoreTy) && 17450 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 17451 TLI.allowsMemoryAccess(Context, DL, StoreTy, 17452 *FirstInChain->getMemOperand(), &IsFastSt) && 17453 IsFastSt && 17454 TLI.allowsMemoryAccess(Context, DL, StoreTy, 17455 *FirstLoad->getMemOperand(), &IsFastLd) && 17456 IsFastLd) { 17457 LastLegalIntegerType = i + 1; 17458 DoIntegerTruncate = false; 17459 // Or check whether a truncstore and extload is legal. 17460 } else if (TLI.getTypeAction(Context, StoreTy) == 17461 TargetLowering::TypePromoteInteger) { 17462 EVT LegalizedStoredValTy = TLI.getTypeToTransformTo(Context, StoreTy); 17463 if (TLI.isTruncStoreLegal(LegalizedStoredValTy, StoreTy) && 17464 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValTy, DAG) && 17465 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValTy, StoreTy) && 17466 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValTy, StoreTy) && 17467 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValTy, StoreTy) && 17468 TLI.allowsMemoryAccess(Context, DL, StoreTy, 17469 *FirstInChain->getMemOperand(), &IsFastSt) && 17470 IsFastSt && 17471 TLI.allowsMemoryAccess(Context, DL, StoreTy, 17472 *FirstLoad->getMemOperand(), &IsFastLd) && 17473 IsFastLd) { 17474 LastLegalIntegerType = i + 1; 17475 DoIntegerTruncate = true; 17476 } 17477 } 17478 } 17479 17480 // Only use vector types if the vector type is larger than the integer 17481 // type. If they are the same, use integers. 17482 bool UseVectorTy = 17483 LastLegalVectorType > LastLegalIntegerType && AllowVectors; 17484 unsigned LastLegalType = 17485 std::max(LastLegalVectorType, LastLegalIntegerType); 17486 17487 // We add +1 here because the LastXXX variables refer to location while 17488 // the NumElem refers to array/index size. 17489 unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1); 17490 NumElem = std::min(LastLegalType, NumElem); 17491 Align FirstLoadAlign = FirstLoad->getAlign(); 17492 17493 if (NumElem < 2) { 17494 // We know that candidate stores are in order and of correct 17495 // shape. While there is no mergeable sequence from the 17496 // beginning one may start later in the sequence. The only 17497 // reason a merge of size N could have failed where another of 17498 // the same size would not have is if the alignment or either 17499 // the load or store has improved. Drop as many candidates as we 17500 // can here. 17501 unsigned NumSkip = 1; 17502 while ((NumSkip < LoadNodes.size()) && 17503 (LoadNodes[NumSkip].MemNode->getAlign() <= FirstLoadAlign) && 17504 (StoreNodes[NumSkip].MemNode->getAlign() <= FirstStoreAlign)) 17505 NumSkip++; 17506 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 17507 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumSkip); 17508 NumConsecutiveStores -= NumSkip; 17509 continue; 17510 } 17511 17512 // Check that we can merge these candidates without causing a cycle. 17513 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem, 17514 RootNode)) { 17515 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 17516 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumElem); 17517 NumConsecutiveStores -= NumElem; 17518 continue; 17519 } 17520 17521 // Find if it is better to use vectors or integers to load and store 17522 // to memory. 17523 EVT JointMemOpVT; 17524 if (UseVectorTy) { 17525 // Find a legal type for the vector store. 17526 unsigned Elts = NumElem * NumMemElts; 17527 JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 17528 } else { 17529 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 17530 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 17531 } 17532 17533 SDLoc LoadDL(LoadNodes[0].MemNode); 17534 SDLoc StoreDL(StoreNodes[0].MemNode); 17535 17536 // The merged loads are required to have the same incoming chain, so 17537 // using the first's chain is acceptable. 17538 17539 SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem); 17540 AddToWorklist(NewStoreChain.getNode()); 17541 17542 MachineMemOperand::Flags LdMMOFlags = 17543 isDereferenceable ? MachineMemOperand::MODereferenceable 17544 : MachineMemOperand::MONone; 17545 if (IsNonTemporalLoad) 17546 LdMMOFlags |= MachineMemOperand::MONonTemporal; 17547 17548 MachineMemOperand::Flags StMMOFlags = IsNonTemporalStore 17549 ? MachineMemOperand::MONonTemporal 17550 : MachineMemOperand::MONone; 17551 17552 SDValue NewLoad, NewStore; 17553 if (UseVectorTy || !DoIntegerTruncate) { 17554 NewLoad = DAG.getLoad( 17555 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(), 17556 FirstLoad->getPointerInfo(), FirstLoadAlign, LdMMOFlags); 17557 SDValue StoreOp = NewLoad; 17558 if (NeedRotate) { 17559 unsigned LoadWidth = ElementSizeBytes * 8 * 2; 17560 assert(JointMemOpVT == EVT::getIntegerVT(Context, LoadWidth) && 17561 "Unexpected type for rotate-able load pair"); 17562 SDValue RotAmt = 17563 DAG.getShiftAmountConstant(LoadWidth / 2, JointMemOpVT, LoadDL); 17564 // Target can convert to the identical ROTR if it does not have ROTL. 17565 StoreOp = DAG.getNode(ISD::ROTL, LoadDL, JointMemOpVT, NewLoad, RotAmt); 17566 } 17567 NewStore = DAG.getStore( 17568 NewStoreChain, StoreDL, StoreOp, FirstInChain->getBasePtr(), 17569 FirstInChain->getPointerInfo(), FirstStoreAlign, StMMOFlags); 17570 } else { // This must be the truncstore/extload case 17571 EVT ExtendedTy = 17572 TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT); 17573 NewLoad = DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, 17574 FirstLoad->getChain(), FirstLoad->getBasePtr(), 17575 FirstLoad->getPointerInfo(), JointMemOpVT, 17576 FirstLoadAlign, LdMMOFlags); 17577 NewStore = DAG.getTruncStore( 17578 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), 17579 FirstInChain->getPointerInfo(), JointMemOpVT, 17580 FirstInChain->getAlign(), FirstInChain->getMemOperand()->getFlags()); 17581 } 17582 17583 // Transfer chain users from old loads to the new load. 17584 for (unsigned i = 0; i < NumElem; ++i) { 17585 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 17586 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 17587 SDValue(NewLoad.getNode(), 1)); 17588 } 17589 17590 // Replace all stores with the new store. Recursively remove corresponding 17591 // values if they are no longer used. 17592 for (unsigned i = 0; i < NumElem; ++i) { 17593 SDValue Val = StoreNodes[i].MemNode->getOperand(1); 17594 CombineTo(StoreNodes[i].MemNode, NewStore); 17595 if (Val.getNode()->use_empty()) 17596 recursivelyDeleteUnusedNodes(Val.getNode()); 17597 } 17598 17599 MadeChange = true; 17600 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 17601 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumElem); 17602 NumConsecutiveStores -= NumElem; 17603 } 17604 return MadeChange; 17605 } 17606 17607 bool DAGCombiner::mergeConsecutiveStores(StoreSDNode *St) { 17608 if (OptLevel == CodeGenOpt::None || !EnableStoreMerging) 17609 return false; 17610 17611 // TODO: Extend this function to merge stores of scalable vectors. 17612 // (i.e. two <vscale x 8 x i8> stores can be merged to one <vscale x 16 x i8> 17613 // store since we know <vscale x 16 x i8> is exactly twice as large as 17614 // <vscale x 8 x i8>). Until then, bail out for scalable vectors. 17615 EVT MemVT = St->getMemoryVT(); 17616 if (MemVT.isScalableVector()) 17617 return false; 17618 if (!MemVT.isSimple() || MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits) 17619 return false; 17620 17621 // This function cannot currently deal with non-byte-sized memory sizes. 17622 int64_t ElementSizeBytes = MemVT.getStoreSize(); 17623 if (ElementSizeBytes * 8 != (int64_t)MemVT.getSizeInBits()) 17624 return false; 17625 17626 // Do not bother looking at stored values that are not constants, loads, or 17627 // extracted vector elements. 17628 SDValue StoredVal = peekThroughBitcasts(St->getValue()); 17629 const StoreSource StoreSrc = getStoreSource(StoredVal); 17630 if (StoreSrc == StoreSource::Unknown) 17631 return false; 17632 17633 SmallVector<MemOpLink, 8> StoreNodes; 17634 SDNode *RootNode; 17635 // Find potential store merge candidates by searching through chain sub-DAG 17636 getStoreMergeCandidates(St, StoreNodes, RootNode); 17637 17638 // Check if there is anything to merge. 17639 if (StoreNodes.size() < 2) 17640 return false; 17641 17642 // Sort the memory operands according to their distance from the 17643 // base pointer. 17644 llvm::sort(StoreNodes, [](MemOpLink LHS, MemOpLink RHS) { 17645 return LHS.OffsetFromBase < RHS.OffsetFromBase; 17646 }); 17647 17648 bool AllowVectors = !DAG.getMachineFunction().getFunction().hasFnAttribute( 17649 Attribute::NoImplicitFloat); 17650 bool IsNonTemporalStore = St->isNonTemporal(); 17651 bool IsNonTemporalLoad = StoreSrc == StoreSource::Load && 17652 cast<LoadSDNode>(StoredVal)->isNonTemporal(); 17653 17654 // Store Merge attempts to merge the lowest stores. This generally 17655 // works out as if successful, as the remaining stores are checked 17656 // after the first collection of stores is merged. However, in the 17657 // case that a non-mergeable store is found first, e.g., {p[-2], 17658 // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent 17659 // mergeable cases. To prevent this, we prune such stores from the 17660 // front of StoreNodes here. 17661 bool MadeChange = false; 17662 while (StoreNodes.size() > 1) { 17663 unsigned NumConsecutiveStores = 17664 getConsecutiveStores(StoreNodes, ElementSizeBytes); 17665 // There are no more stores in the list to examine. 17666 if (NumConsecutiveStores == 0) 17667 return MadeChange; 17668 17669 // We have at least 2 consecutive stores. Try to merge them. 17670 assert(NumConsecutiveStores >= 2 && "Expected at least 2 stores"); 17671 switch (StoreSrc) { 17672 case StoreSource::Constant: 17673 MadeChange |= tryStoreMergeOfConstants(StoreNodes, NumConsecutiveStores, 17674 MemVT, RootNode, AllowVectors); 17675 break; 17676 17677 case StoreSource::Extract: 17678 MadeChange |= tryStoreMergeOfExtracts(StoreNodes, NumConsecutiveStores, 17679 MemVT, RootNode); 17680 break; 17681 17682 case StoreSource::Load: 17683 MadeChange |= tryStoreMergeOfLoads(StoreNodes, NumConsecutiveStores, 17684 MemVT, RootNode, AllowVectors, 17685 IsNonTemporalStore, IsNonTemporalLoad); 17686 break; 17687 17688 default: 17689 llvm_unreachable("Unhandled store source type"); 17690 } 17691 } 17692 return MadeChange; 17693 } 17694 17695 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 17696 SDLoc SL(ST); 17697 SDValue ReplStore; 17698 17699 // Replace the chain to avoid dependency. 17700 if (ST->isTruncatingStore()) { 17701 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 17702 ST->getBasePtr(), ST->getMemoryVT(), 17703 ST->getMemOperand()); 17704 } else { 17705 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 17706 ST->getMemOperand()); 17707 } 17708 17709 // Create token to keep both nodes around. 17710 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 17711 MVT::Other, ST->getChain(), ReplStore); 17712 17713 // Make sure the new and old chains are cleaned up. 17714 AddToWorklist(Token.getNode()); 17715 17716 // Don't add users to work list. 17717 return CombineTo(ST, Token, false); 17718 } 17719 17720 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 17721 SDValue Value = ST->getValue(); 17722 if (Value.getOpcode() == ISD::TargetConstantFP) 17723 return SDValue(); 17724 17725 if (!ISD::isNormalStore(ST)) 17726 return SDValue(); 17727 17728 SDLoc DL(ST); 17729 17730 SDValue Chain = ST->getChain(); 17731 SDValue Ptr = ST->getBasePtr(); 17732 17733 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 17734 17735 // NOTE: If the original store is volatile, this transform must not increase 17736 // the number of stores. For example, on x86-32 an f64 can be stored in one 17737 // processor operation but an i64 (which is not legal) requires two. So the 17738 // transform should not be done in this case. 17739 17740 SDValue Tmp; 17741 switch (CFP->getSimpleValueType(0).SimpleTy) { 17742 default: 17743 llvm_unreachable("Unknown FP type"); 17744 case MVT::f16: // We don't do this for these yet. 17745 case MVT::f80: 17746 case MVT::f128: 17747 case MVT::ppcf128: 17748 return SDValue(); 17749 case MVT::f32: 17750 if ((isTypeLegal(MVT::i32) && !LegalOperations && ST->isSimple()) || 17751 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 17752 ; 17753 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 17754 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 17755 MVT::i32); 17756 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 17757 } 17758 17759 return SDValue(); 17760 case MVT::f64: 17761 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 17762 ST->isSimple()) || 17763 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 17764 ; 17765 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 17766 getZExtValue(), SDLoc(CFP), MVT::i64); 17767 return DAG.getStore(Chain, DL, Tmp, 17768 Ptr, ST->getMemOperand()); 17769 } 17770 17771 if (ST->isSimple() && 17772 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 17773 // Many FP stores are not made apparent until after legalize, e.g. for 17774 // argument passing. Since this is so common, custom legalize the 17775 // 64-bit integer store into two 32-bit stores. 17776 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 17777 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 17778 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 17779 if (DAG.getDataLayout().isBigEndian()) 17780 std::swap(Lo, Hi); 17781 17782 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 17783 AAMDNodes AAInfo = ST->getAAInfo(); 17784 17785 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 17786 ST->getOriginalAlign(), MMOFlags, AAInfo); 17787 Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(4), DL); 17788 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr, 17789 ST->getPointerInfo().getWithOffset(4), 17790 ST->getOriginalAlign(), MMOFlags, AAInfo); 17791 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 17792 St0, St1); 17793 } 17794 17795 return SDValue(); 17796 } 17797 } 17798 17799 SDValue DAGCombiner::visitSTORE(SDNode *N) { 17800 StoreSDNode *ST = cast<StoreSDNode>(N); 17801 SDValue Chain = ST->getChain(); 17802 SDValue Value = ST->getValue(); 17803 SDValue Ptr = ST->getBasePtr(); 17804 17805 // If this is a store of a bit convert, store the input value if the 17806 // resultant store does not need a higher alignment than the original. 17807 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 17808 ST->isUnindexed()) { 17809 EVT SVT = Value.getOperand(0).getValueType(); 17810 // If the store is volatile, we only want to change the store type if the 17811 // resulting store is legal. Otherwise we might increase the number of 17812 // memory accesses. We don't care if the original type was legal or not 17813 // as we assume software couldn't rely on the number of accesses of an 17814 // illegal type. 17815 // TODO: May be able to relax for unordered atomics (see D66309) 17816 if (((!LegalOperations && ST->isSimple()) || 17817 TLI.isOperationLegal(ISD::STORE, SVT)) && 17818 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT, 17819 DAG, *ST->getMemOperand())) { 17820 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr, 17821 ST->getMemOperand()); 17822 } 17823 } 17824 17825 // Turn 'store undef, Ptr' -> nothing. 17826 if (Value.isUndef() && ST->isUnindexed()) 17827 return Chain; 17828 17829 // Try to infer better alignment information than the store already has. 17830 if (OptLevel != CodeGenOpt::None && ST->isUnindexed() && !ST->isAtomic()) { 17831 if (MaybeAlign Alignment = DAG.InferPtrAlign(Ptr)) { 17832 if (*Alignment > ST->getAlign() && 17833 isAligned(*Alignment, ST->getSrcValueOffset())) { 17834 SDValue NewStore = 17835 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(), 17836 ST->getMemoryVT(), *Alignment, 17837 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 17838 // NewStore will always be N as we are only refining the alignment 17839 assert(NewStore.getNode() == N); 17840 (void)NewStore; 17841 } 17842 } 17843 } 17844 17845 // Try transforming a pair floating point load / store ops to integer 17846 // load / store ops. 17847 if (SDValue NewST = TransformFPLoadStorePair(N)) 17848 return NewST; 17849 17850 // Try transforming several stores into STORE (BSWAP). 17851 if (SDValue Store = mergeTruncStores(ST)) 17852 return Store; 17853 17854 if (ST->isUnindexed()) { 17855 // Walk up chain skipping non-aliasing memory nodes, on this store and any 17856 // adjacent stores. 17857 if (findBetterNeighborChains(ST)) { 17858 // replaceStoreChain uses CombineTo, which handled all of the worklist 17859 // manipulation. Return the original node to not do anything else. 17860 return SDValue(ST, 0); 17861 } 17862 Chain = ST->getChain(); 17863 } 17864 17865 // FIXME: is there such a thing as a truncating indexed store? 17866 if (ST->isTruncatingStore() && ST->isUnindexed() && 17867 Value.getValueType().isInteger() && 17868 (!isa<ConstantSDNode>(Value) || 17869 !cast<ConstantSDNode>(Value)->isOpaque())) { 17870 APInt TruncDemandedBits = 17871 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 17872 ST->getMemoryVT().getScalarSizeInBits()); 17873 17874 // See if we can simplify the input to this truncstore with knowledge that 17875 // only the low bits are being used. For example: 17876 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 17877 AddToWorklist(Value.getNode()); 17878 if (SDValue Shorter = DAG.GetDemandedBits(Value, TruncDemandedBits)) 17879 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, Ptr, ST->getMemoryVT(), 17880 ST->getMemOperand()); 17881 17882 // Otherwise, see if we can simplify the operation with 17883 // SimplifyDemandedBits, which only works if the value has a single use. 17884 if (SimplifyDemandedBits(Value, TruncDemandedBits)) { 17885 // Re-visit the store if anything changed and the store hasn't been merged 17886 // with another node (N is deleted) SimplifyDemandedBits will add Value's 17887 // node back to the worklist if necessary, but we also need to re-visit 17888 // the Store node itself. 17889 if (N->getOpcode() != ISD::DELETED_NODE) 17890 AddToWorklist(N); 17891 return SDValue(N, 0); 17892 } 17893 } 17894 17895 // If this is a load followed by a store to the same location, then the store 17896 // is dead/noop. 17897 // TODO: Can relax for unordered atomics (see D66309) 17898 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 17899 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 17900 ST->isUnindexed() && ST->isSimple() && 17901 Ld->getAddressSpace() == ST->getAddressSpace() && 17902 // There can't be any side effects between the load and store, such as 17903 // a call or store. 17904 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 17905 // The store is dead, remove it. 17906 return Chain; 17907 } 17908 } 17909 17910 // TODO: Can relax for unordered atomics (see D66309) 17911 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 17912 if (ST->isUnindexed() && ST->isSimple() && 17913 ST1->isUnindexed() && ST1->isSimple()) { 17914 if (ST1->getBasePtr() == Ptr && ST1->getValue() == Value && 17915 ST->getMemoryVT() == ST1->getMemoryVT() && 17916 ST->getAddressSpace() == ST1->getAddressSpace()) { 17917 // If this is a store followed by a store with the same value to the 17918 // same location, then the store is dead/noop. 17919 return Chain; 17920 } 17921 17922 if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() && 17923 !ST1->getBasePtr().isUndef() && 17924 // BaseIndexOffset and the code below requires knowing the size 17925 // of a vector, so bail out if MemoryVT is scalable. 17926 !ST->getMemoryVT().isScalableVector() && 17927 !ST1->getMemoryVT().isScalableVector() && 17928 ST->getAddressSpace() == ST1->getAddressSpace()) { 17929 const BaseIndexOffset STBase = BaseIndexOffset::match(ST, DAG); 17930 const BaseIndexOffset ChainBase = BaseIndexOffset::match(ST1, DAG); 17931 unsigned STBitSize = ST->getMemoryVT().getFixedSizeInBits(); 17932 unsigned ChainBitSize = ST1->getMemoryVT().getFixedSizeInBits(); 17933 // If this is a store who's preceding store to a subset of the current 17934 // location and no one other node is chained to that store we can 17935 // effectively drop the store. Do not remove stores to undef as they may 17936 // be used as data sinks. 17937 if (STBase.contains(DAG, STBitSize, ChainBase, ChainBitSize)) { 17938 CombineTo(ST1, ST1->getChain()); 17939 return SDValue(); 17940 } 17941 } 17942 } 17943 } 17944 17945 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 17946 // truncating store. We can do this even if this is already a truncstore. 17947 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 17948 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 17949 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 17950 ST->getMemoryVT())) { 17951 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 17952 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 17953 } 17954 17955 // Always perform this optimization before types are legal. If the target 17956 // prefers, also try this after legalization to catch stores that were created 17957 // by intrinsics or other nodes. 17958 if (!LegalTypes || (TLI.mergeStoresAfterLegalization(ST->getMemoryVT()))) { 17959 while (true) { 17960 // There can be multiple store sequences on the same chain. 17961 // Keep trying to merge store sequences until we are unable to do so 17962 // or until we merge the last store on the chain. 17963 bool Changed = mergeConsecutiveStores(ST); 17964 if (!Changed) break; 17965 // Return N as merge only uses CombineTo and no worklist clean 17966 // up is necessary. 17967 if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N)) 17968 return SDValue(N, 0); 17969 } 17970 } 17971 17972 // Try transforming N to an indexed store. 17973 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 17974 return SDValue(N, 0); 17975 17976 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 17977 // 17978 // Make sure to do this only after attempting to merge stores in order to 17979 // avoid changing the types of some subset of stores due to visit order, 17980 // preventing their merging. 17981 if (isa<ConstantFPSDNode>(ST->getValue())) { 17982 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 17983 return NewSt; 17984 } 17985 17986 if (SDValue NewSt = splitMergedValStore(ST)) 17987 return NewSt; 17988 17989 return ReduceLoadOpStoreWidth(N); 17990 } 17991 17992 SDValue DAGCombiner::visitLIFETIME_END(SDNode *N) { 17993 const auto *LifetimeEnd = cast<LifetimeSDNode>(N); 17994 if (!LifetimeEnd->hasOffset()) 17995 return SDValue(); 17996 17997 const BaseIndexOffset LifetimeEndBase(N->getOperand(1), SDValue(), 17998 LifetimeEnd->getOffset(), false); 17999 18000 // We walk up the chains to find stores. 18001 SmallVector<SDValue, 8> Chains = {N->getOperand(0)}; 18002 while (!Chains.empty()) { 18003 SDValue Chain = Chains.pop_back_val(); 18004 if (!Chain.hasOneUse()) 18005 continue; 18006 switch (Chain.getOpcode()) { 18007 case ISD::TokenFactor: 18008 for (unsigned Nops = Chain.getNumOperands(); Nops;) 18009 Chains.push_back(Chain.getOperand(--Nops)); 18010 break; 18011 case ISD::LIFETIME_START: 18012 case ISD::LIFETIME_END: 18013 // We can forward past any lifetime start/end that can be proven not to 18014 // alias the node. 18015 if (!isAlias(Chain.getNode(), N)) 18016 Chains.push_back(Chain.getOperand(0)); 18017 break; 18018 case ISD::STORE: { 18019 StoreSDNode *ST = dyn_cast<StoreSDNode>(Chain); 18020 // TODO: Can relax for unordered atomics (see D66309) 18021 if (!ST->isSimple() || ST->isIndexed()) 18022 continue; 18023 const TypeSize StoreSize = ST->getMemoryVT().getStoreSize(); 18024 // The bounds of a scalable store are not known until runtime, so this 18025 // store cannot be elided. 18026 if (StoreSize.isScalable()) 18027 continue; 18028 const BaseIndexOffset StoreBase = BaseIndexOffset::match(ST, DAG); 18029 // If we store purely within object bounds just before its lifetime ends, 18030 // we can remove the store. 18031 if (LifetimeEndBase.contains(DAG, LifetimeEnd->getSize() * 8, StoreBase, 18032 StoreSize.getFixedSize() * 8)) { 18033 LLVM_DEBUG(dbgs() << "\nRemoving store:"; StoreBase.dump(); 18034 dbgs() << "\nwithin LIFETIME_END of : "; 18035 LifetimeEndBase.dump(); dbgs() << "\n"); 18036 CombineTo(ST, ST->getChain()); 18037 return SDValue(N, 0); 18038 } 18039 } 18040 } 18041 } 18042 return SDValue(); 18043 } 18044 18045 /// For the instruction sequence of store below, F and I values 18046 /// are bundled together as an i64 value before being stored into memory. 18047 /// Sometimes it is more efficent to generate separate stores for F and I, 18048 /// which can remove the bitwise instructions or sink them to colder places. 18049 /// 18050 /// (store (or (zext (bitcast F to i32) to i64), 18051 /// (shl (zext I to i64), 32)), addr) --> 18052 /// (store F, addr) and (store I, addr+4) 18053 /// 18054 /// Similarly, splitting for other merged store can also be beneficial, like: 18055 /// For pair of {i32, i32}, i64 store --> two i32 stores. 18056 /// For pair of {i32, i16}, i64 store --> two i32 stores. 18057 /// For pair of {i16, i16}, i32 store --> two i16 stores. 18058 /// For pair of {i16, i8}, i32 store --> two i16 stores. 18059 /// For pair of {i8, i8}, i16 store --> two i8 stores. 18060 /// 18061 /// We allow each target to determine specifically which kind of splitting is 18062 /// supported. 18063 /// 18064 /// The store patterns are commonly seen from the simple code snippet below 18065 /// if only std::make_pair(...) is sroa transformed before inlined into hoo. 18066 /// void goo(const std::pair<int, float> &); 18067 /// hoo() { 18068 /// ... 18069 /// goo(std::make_pair(tmp, ftmp)); 18070 /// ... 18071 /// } 18072 /// 18073 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) { 18074 if (OptLevel == CodeGenOpt::None) 18075 return SDValue(); 18076 18077 // Can't change the number of memory accesses for a volatile store or break 18078 // atomicity for an atomic one. 18079 if (!ST->isSimple()) 18080 return SDValue(); 18081 18082 SDValue Val = ST->getValue(); 18083 SDLoc DL(ST); 18084 18085 // Match OR operand. 18086 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR) 18087 return SDValue(); 18088 18089 // Match SHL operand and get Lower and Higher parts of Val. 18090 SDValue Op1 = Val.getOperand(0); 18091 SDValue Op2 = Val.getOperand(1); 18092 SDValue Lo, Hi; 18093 if (Op1.getOpcode() != ISD::SHL) { 18094 std::swap(Op1, Op2); 18095 if (Op1.getOpcode() != ISD::SHL) 18096 return SDValue(); 18097 } 18098 Lo = Op2; 18099 Hi = Op1.getOperand(0); 18100 if (!Op1.hasOneUse()) 18101 return SDValue(); 18102 18103 // Match shift amount to HalfValBitSize. 18104 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2; 18105 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1)); 18106 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize) 18107 return SDValue(); 18108 18109 // Lo and Hi are zero-extended from int with size less equal than 32 18110 // to i64. 18111 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() || 18112 !Lo.getOperand(0).getValueType().isScalarInteger() || 18113 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize || 18114 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() || 18115 !Hi.getOperand(0).getValueType().isScalarInteger() || 18116 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize) 18117 return SDValue(); 18118 18119 // Use the EVT of low and high parts before bitcast as the input 18120 // of target query. 18121 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST) 18122 ? Lo.getOperand(0).getValueType() 18123 : Lo.getValueType(); 18124 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST) 18125 ? Hi.getOperand(0).getValueType() 18126 : Hi.getValueType(); 18127 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) 18128 return SDValue(); 18129 18130 // Start to split store. 18131 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 18132 AAMDNodes AAInfo = ST->getAAInfo(); 18133 18134 // Change the sizes of Lo and Hi's value types to HalfValBitSize. 18135 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize); 18136 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0)); 18137 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0)); 18138 18139 SDValue Chain = ST->getChain(); 18140 SDValue Ptr = ST->getBasePtr(); 18141 // Lower value store. 18142 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 18143 ST->getOriginalAlign(), MMOFlags, AAInfo); 18144 Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(HalfValBitSize / 8), DL); 18145 // Higher value store. 18146 SDValue St1 = DAG.getStore( 18147 St0, DL, Hi, Ptr, ST->getPointerInfo().getWithOffset(HalfValBitSize / 8), 18148 ST->getOriginalAlign(), MMOFlags, AAInfo); 18149 return St1; 18150 } 18151 18152 /// Convert a disguised subvector insertion into a shuffle: 18153 SDValue DAGCombiner::combineInsertEltToShuffle(SDNode *N, unsigned InsIndex) { 18154 assert(N->getOpcode() == ISD::INSERT_VECTOR_ELT && 18155 "Expected extract_vector_elt"); 18156 SDValue InsertVal = N->getOperand(1); 18157 SDValue Vec = N->getOperand(0); 18158 18159 // (insert_vector_elt (vector_shuffle X, Y), (extract_vector_elt X, N), 18160 // InsIndex) 18161 // --> (vector_shuffle X, Y) and variations where shuffle operands may be 18162 // CONCAT_VECTORS. 18163 if (Vec.getOpcode() == ISD::VECTOR_SHUFFLE && Vec.hasOneUse() && 18164 InsertVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 18165 isa<ConstantSDNode>(InsertVal.getOperand(1))) { 18166 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Vec.getNode()); 18167 ArrayRef<int> Mask = SVN->getMask(); 18168 18169 SDValue X = Vec.getOperand(0); 18170 SDValue Y = Vec.getOperand(1); 18171 18172 // Vec's operand 0 is using indices from 0 to N-1 and 18173 // operand 1 from N to 2N - 1, where N is the number of 18174 // elements in the vectors. 18175 SDValue InsertVal0 = InsertVal.getOperand(0); 18176 int ElementOffset = -1; 18177 18178 // We explore the inputs of the shuffle in order to see if we find the 18179 // source of the extract_vector_elt. If so, we can use it to modify the 18180 // shuffle rather than perform an insert_vector_elt. 18181 SmallVector<std::pair<int, SDValue>, 8> ArgWorkList; 18182 ArgWorkList.emplace_back(Mask.size(), Y); 18183 ArgWorkList.emplace_back(0, X); 18184 18185 while (!ArgWorkList.empty()) { 18186 int ArgOffset; 18187 SDValue ArgVal; 18188 std::tie(ArgOffset, ArgVal) = ArgWorkList.pop_back_val(); 18189 18190 if (ArgVal == InsertVal0) { 18191 ElementOffset = ArgOffset; 18192 break; 18193 } 18194 18195 // Peek through concat_vector. 18196 if (ArgVal.getOpcode() == ISD::CONCAT_VECTORS) { 18197 int CurrentArgOffset = 18198 ArgOffset + ArgVal.getValueType().getVectorNumElements(); 18199 int Step = ArgVal.getOperand(0).getValueType().getVectorNumElements(); 18200 for (SDValue Op : reverse(ArgVal->ops())) { 18201 CurrentArgOffset -= Step; 18202 ArgWorkList.emplace_back(CurrentArgOffset, Op); 18203 } 18204 18205 // Make sure we went through all the elements and did not screw up index 18206 // computation. 18207 assert(CurrentArgOffset == ArgOffset); 18208 } 18209 } 18210 18211 if (ElementOffset != -1) { 18212 SmallVector<int, 16> NewMask(Mask.begin(), Mask.end()); 18213 18214 auto *ExtrIndex = cast<ConstantSDNode>(InsertVal.getOperand(1)); 18215 NewMask[InsIndex] = ElementOffset + ExtrIndex->getZExtValue(); 18216 assert(NewMask[InsIndex] < 18217 (int)(2 * Vec.getValueType().getVectorNumElements()) && 18218 NewMask[InsIndex] >= 0 && "NewMask[InsIndex] is out of bound"); 18219 18220 SDValue LegalShuffle = 18221 TLI.buildLegalVectorShuffle(Vec.getValueType(), SDLoc(N), X, 18222 Y, NewMask, DAG); 18223 if (LegalShuffle) 18224 return LegalShuffle; 18225 } 18226 } 18227 18228 // insert_vector_elt V, (bitcast X from vector type), IdxC --> 18229 // bitcast(shuffle (bitcast V), (extended X), Mask) 18230 // Note: We do not use an insert_subvector node because that requires a 18231 // legal subvector type. 18232 if (InsertVal.getOpcode() != ISD::BITCAST || !InsertVal.hasOneUse() || 18233 !InsertVal.getOperand(0).getValueType().isVector()) 18234 return SDValue(); 18235 18236 SDValue SubVec = InsertVal.getOperand(0); 18237 SDValue DestVec = N->getOperand(0); 18238 EVT SubVecVT = SubVec.getValueType(); 18239 EVT VT = DestVec.getValueType(); 18240 unsigned NumSrcElts = SubVecVT.getVectorNumElements(); 18241 // If the source only has a single vector element, the cost of creating adding 18242 // it to a vector is likely to exceed the cost of a insert_vector_elt. 18243 if (NumSrcElts == 1) 18244 return SDValue(); 18245 unsigned ExtendRatio = VT.getSizeInBits() / SubVecVT.getSizeInBits(); 18246 unsigned NumMaskVals = ExtendRatio * NumSrcElts; 18247 18248 // Step 1: Create a shuffle mask that implements this insert operation. The 18249 // vector that we are inserting into will be operand 0 of the shuffle, so 18250 // those elements are just 'i'. The inserted subvector is in the first 18251 // positions of operand 1 of the shuffle. Example: 18252 // insert v4i32 V, (v2i16 X), 2 --> shuffle v8i16 V', X', {0,1,2,3,8,9,6,7} 18253 SmallVector<int, 16> Mask(NumMaskVals); 18254 for (unsigned i = 0; i != NumMaskVals; ++i) { 18255 if (i / NumSrcElts == InsIndex) 18256 Mask[i] = (i % NumSrcElts) + NumMaskVals; 18257 else 18258 Mask[i] = i; 18259 } 18260 18261 // Bail out if the target can not handle the shuffle we want to create. 18262 EVT SubVecEltVT = SubVecVT.getVectorElementType(); 18263 EVT ShufVT = EVT::getVectorVT(*DAG.getContext(), SubVecEltVT, NumMaskVals); 18264 if (!TLI.isShuffleMaskLegal(Mask, ShufVT)) 18265 return SDValue(); 18266 18267 // Step 2: Create a wide vector from the inserted source vector by appending 18268 // undefined elements. This is the same size as our destination vector. 18269 SDLoc DL(N); 18270 SmallVector<SDValue, 8> ConcatOps(ExtendRatio, DAG.getUNDEF(SubVecVT)); 18271 ConcatOps[0] = SubVec; 18272 SDValue PaddedSubV = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShufVT, ConcatOps); 18273 18274 // Step 3: Shuffle in the padded subvector. 18275 SDValue DestVecBC = DAG.getBitcast(ShufVT, DestVec); 18276 SDValue Shuf = DAG.getVectorShuffle(ShufVT, DL, DestVecBC, PaddedSubV, Mask); 18277 AddToWorklist(PaddedSubV.getNode()); 18278 AddToWorklist(DestVecBC.getNode()); 18279 AddToWorklist(Shuf.getNode()); 18280 return DAG.getBitcast(VT, Shuf); 18281 } 18282 18283 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 18284 SDValue InVec = N->getOperand(0); 18285 SDValue InVal = N->getOperand(1); 18286 SDValue EltNo = N->getOperand(2); 18287 SDLoc DL(N); 18288 18289 EVT VT = InVec.getValueType(); 18290 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo); 18291 18292 // Insert into out-of-bounds element is undefined. 18293 if (IndexC && VT.isFixedLengthVector() && 18294 IndexC->getZExtValue() >= VT.getVectorNumElements()) 18295 return DAG.getUNDEF(VT); 18296 18297 // Remove redundant insertions: 18298 // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x 18299 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 18300 InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1)) 18301 return InVec; 18302 18303 if (!IndexC) { 18304 // If this is variable insert to undef vector, it might be better to splat: 18305 // inselt undef, InVal, EltNo --> build_vector < InVal, InVal, ... > 18306 if (InVec.isUndef() && TLI.shouldSplatInsEltVarIndex(VT)) { 18307 if (VT.isScalableVector()) 18308 return DAG.getSplatVector(VT, DL, InVal); 18309 else { 18310 SmallVector<SDValue, 8> Ops(VT.getVectorNumElements(), InVal); 18311 return DAG.getBuildVector(VT, DL, Ops); 18312 } 18313 } 18314 return SDValue(); 18315 } 18316 18317 if (VT.isScalableVector()) 18318 return SDValue(); 18319 18320 unsigned NumElts = VT.getVectorNumElements(); 18321 18322 // We must know which element is being inserted for folds below here. 18323 unsigned Elt = IndexC->getZExtValue(); 18324 if (SDValue Shuf = combineInsertEltToShuffle(N, Elt)) 18325 return Shuf; 18326 18327 // Canonicalize insert_vector_elt dag nodes. 18328 // Example: 18329 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 18330 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 18331 // 18332 // Do this only if the child insert_vector node has one use; also 18333 // do this only if indices are both constants and Idx1 < Idx0. 18334 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 18335 && isa<ConstantSDNode>(InVec.getOperand(2))) { 18336 unsigned OtherElt = InVec.getConstantOperandVal(2); 18337 if (Elt < OtherElt) { 18338 // Swap nodes. 18339 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, 18340 InVec.getOperand(0), InVal, EltNo); 18341 AddToWorklist(NewOp.getNode()); 18342 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 18343 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 18344 } 18345 } 18346 18347 // If we can't generate a legal BUILD_VECTOR, exit 18348 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 18349 return SDValue(); 18350 18351 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 18352 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 18353 // vector elements. 18354 SmallVector<SDValue, 8> Ops; 18355 // Do not combine these two vectors if the output vector will not replace 18356 // the input vector. 18357 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 18358 Ops.append(InVec.getNode()->op_begin(), 18359 InVec.getNode()->op_end()); 18360 } else if (InVec.isUndef()) { 18361 Ops.append(NumElts, DAG.getUNDEF(InVal.getValueType())); 18362 } else { 18363 return SDValue(); 18364 } 18365 assert(Ops.size() == NumElts && "Unexpected vector size"); 18366 18367 // Insert the element 18368 if (Elt < Ops.size()) { 18369 // All the operands of BUILD_VECTOR must have the same type; 18370 // we enforce that here. 18371 EVT OpVT = Ops[0].getValueType(); 18372 Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal; 18373 } 18374 18375 // Return the new vector 18376 return DAG.getBuildVector(VT, DL, Ops); 18377 } 18378 18379 SDValue DAGCombiner::scalarizeExtractedVectorLoad(SDNode *EVE, EVT InVecVT, 18380 SDValue EltNo, 18381 LoadSDNode *OriginalLoad) { 18382 assert(OriginalLoad->isSimple()); 18383 18384 EVT ResultVT = EVE->getValueType(0); 18385 EVT VecEltVT = InVecVT.getVectorElementType(); 18386 18387 // If the vector element type is not a multiple of a byte then we are unable 18388 // to correctly compute an address to load only the extracted element as a 18389 // scalar. 18390 if (!VecEltVT.isByteSized()) 18391 return SDValue(); 18392 18393 Align Alignment = OriginalLoad->getAlign(); 18394 Align NewAlign = DAG.getDataLayout().getABITypeAlign( 18395 VecEltVT.getTypeForEVT(*DAG.getContext())); 18396 18397 if (NewAlign > Alignment || 18398 !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 18399 return SDValue(); 18400 18401 ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ? 18402 ISD::NON_EXTLOAD : ISD::EXTLOAD; 18403 if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT)) 18404 return SDValue(); 18405 18406 Alignment = NewAlign; 18407 18408 SDValue NewPtr = OriginalLoad->getBasePtr(); 18409 SDValue Offset; 18410 EVT PtrType = NewPtr.getValueType(); 18411 MachinePointerInfo MPI; 18412 SDLoc DL(EVE); 18413 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 18414 int Elt = ConstEltNo->getZExtValue(); 18415 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 18416 Offset = DAG.getConstant(PtrOff, DL, PtrType); 18417 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 18418 } else { 18419 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 18420 Offset = DAG.getNode( 18421 ISD::MUL, DL, PtrType, Offset, 18422 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 18423 // Discard the pointer info except the address space because the memory 18424 // operand can't represent this new access since the offset is variable. 18425 MPI = MachinePointerInfo(OriginalLoad->getPointerInfo().getAddrSpace()); 18426 } 18427 NewPtr = DAG.getMemBasePlusOffset(NewPtr, Offset, DL); 18428 18429 // The replacement we need to do here is a little tricky: we need to 18430 // replace an extractelement of a load with a load. 18431 // Use ReplaceAllUsesOfValuesWith to do the replacement. 18432 // Note that this replacement assumes that the extractvalue is the only 18433 // use of the load; that's okay because we don't want to perform this 18434 // transformation in other cases anyway. 18435 SDValue Load; 18436 SDValue Chain; 18437 if (ResultVT.bitsGT(VecEltVT)) { 18438 // If the result type of vextract is wider than the load, then issue an 18439 // extending load instead. 18440 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 18441 VecEltVT) 18442 ? ISD::ZEXTLOAD 18443 : ISD::EXTLOAD; 18444 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, 18445 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT, 18446 Alignment, OriginalLoad->getMemOperand()->getFlags(), 18447 OriginalLoad->getAAInfo()); 18448 Chain = Load.getValue(1); 18449 } else { 18450 Load = DAG.getLoad( 18451 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI, Alignment, 18452 OriginalLoad->getMemOperand()->getFlags(), OriginalLoad->getAAInfo()); 18453 Chain = Load.getValue(1); 18454 if (ResultVT.bitsLT(VecEltVT)) 18455 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 18456 else 18457 Load = DAG.getBitcast(ResultVT, Load); 18458 } 18459 WorklistRemover DeadNodes(*this); 18460 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 18461 SDValue To[] = { Load, Chain }; 18462 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 18463 // Make sure to revisit this node to clean it up; it will usually be dead. 18464 AddToWorklist(EVE); 18465 // Since we're explicitly calling ReplaceAllUses, add the new node to the 18466 // worklist explicitly as well. 18467 AddToWorklistWithUsers(Load.getNode()); 18468 ++OpsNarrowed; 18469 return SDValue(EVE, 0); 18470 } 18471 18472 /// Transform a vector binary operation into a scalar binary operation by moving 18473 /// the math/logic after an extract element of a vector. 18474 static SDValue scalarizeExtractedBinop(SDNode *ExtElt, SelectionDAG &DAG, 18475 bool LegalOperations) { 18476 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 18477 SDValue Vec = ExtElt->getOperand(0); 18478 SDValue Index = ExtElt->getOperand(1); 18479 auto *IndexC = dyn_cast<ConstantSDNode>(Index); 18480 if (!IndexC || !TLI.isBinOp(Vec.getOpcode()) || !Vec.hasOneUse() || 18481 Vec.getNode()->getNumValues() != 1) 18482 return SDValue(); 18483 18484 // Targets may want to avoid this to prevent an expensive register transfer. 18485 if (!TLI.shouldScalarizeBinop(Vec)) 18486 return SDValue(); 18487 18488 // Extracting an element of a vector constant is constant-folded, so this 18489 // transform is just replacing a vector op with a scalar op while moving the 18490 // extract. 18491 SDValue Op0 = Vec.getOperand(0); 18492 SDValue Op1 = Vec.getOperand(1); 18493 if (isAnyConstantBuildVector(Op0, true) || 18494 isAnyConstantBuildVector(Op1, true)) { 18495 // extractelt (binop X, C), IndexC --> binop (extractelt X, IndexC), C' 18496 // extractelt (binop C, X), IndexC --> binop C', (extractelt X, IndexC) 18497 SDLoc DL(ExtElt); 18498 EVT VT = ExtElt->getValueType(0); 18499 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op0, Index); 18500 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op1, Index); 18501 return DAG.getNode(Vec.getOpcode(), DL, VT, Ext0, Ext1); 18502 } 18503 18504 return SDValue(); 18505 } 18506 18507 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 18508 SDValue VecOp = N->getOperand(0); 18509 SDValue Index = N->getOperand(1); 18510 EVT ScalarVT = N->getValueType(0); 18511 EVT VecVT = VecOp.getValueType(); 18512 if (VecOp.isUndef()) 18513 return DAG.getUNDEF(ScalarVT); 18514 18515 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val 18516 // 18517 // This only really matters if the index is non-constant since other combines 18518 // on the constant elements already work. 18519 SDLoc DL(N); 18520 if (VecOp.getOpcode() == ISD::INSERT_VECTOR_ELT && 18521 Index == VecOp.getOperand(2)) { 18522 SDValue Elt = VecOp.getOperand(1); 18523 return VecVT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, DL, ScalarVT) : Elt; 18524 } 18525 18526 // (vextract (scalar_to_vector val, 0) -> val 18527 if (VecOp.getOpcode() == ISD::SCALAR_TO_VECTOR) { 18528 // Only 0'th element of SCALAR_TO_VECTOR is defined. 18529 if (DAG.isKnownNeverZero(Index)) 18530 return DAG.getUNDEF(ScalarVT); 18531 18532 // Check if the result type doesn't match the inserted element type. A 18533 // SCALAR_TO_VECTOR may truncate the inserted element and the 18534 // EXTRACT_VECTOR_ELT may widen the extracted vector. 18535 SDValue InOp = VecOp.getOperand(0); 18536 if (InOp.getValueType() != ScalarVT) { 18537 assert(InOp.getValueType().isInteger() && ScalarVT.isInteger()); 18538 return DAG.getSExtOrTrunc(InOp, DL, ScalarVT); 18539 } 18540 return InOp; 18541 } 18542 18543 // extract_vector_elt of out-of-bounds element -> UNDEF 18544 auto *IndexC = dyn_cast<ConstantSDNode>(Index); 18545 if (IndexC && VecVT.isFixedLengthVector() && 18546 IndexC->getAPIntValue().uge(VecVT.getVectorNumElements())) 18547 return DAG.getUNDEF(ScalarVT); 18548 18549 // extract_vector_elt (build_vector x, y), 1 -> y 18550 if (((IndexC && VecOp.getOpcode() == ISD::BUILD_VECTOR) || 18551 VecOp.getOpcode() == ISD::SPLAT_VECTOR) && 18552 TLI.isTypeLegal(VecVT) && 18553 (VecOp.hasOneUse() || TLI.aggressivelyPreferBuildVectorSources(VecVT))) { 18554 assert((VecOp.getOpcode() != ISD::BUILD_VECTOR || 18555 VecVT.isFixedLengthVector()) && 18556 "BUILD_VECTOR used for scalable vectors"); 18557 unsigned IndexVal = 18558 VecOp.getOpcode() == ISD::BUILD_VECTOR ? IndexC->getZExtValue() : 0; 18559 SDValue Elt = VecOp.getOperand(IndexVal); 18560 EVT InEltVT = Elt.getValueType(); 18561 18562 // Sometimes build_vector's scalar input types do not match result type. 18563 if (ScalarVT == InEltVT) 18564 return Elt; 18565 18566 // TODO: It may be useful to truncate if free if the build_vector implicitly 18567 // converts. 18568 } 18569 18570 if (VecVT.isScalableVector()) 18571 return SDValue(); 18572 18573 // All the code from this point onwards assumes fixed width vectors, but it's 18574 // possible that some of the combinations could be made to work for scalable 18575 // vectors too. 18576 unsigned NumElts = VecVT.getVectorNumElements(); 18577 unsigned VecEltBitWidth = VecVT.getScalarSizeInBits(); 18578 18579 // TODO: These transforms should not require the 'hasOneUse' restriction, but 18580 // there are regressions on multiple targets without it. We can end up with a 18581 // mess of scalar and vector code if we reduce only part of the DAG to scalar. 18582 if (IndexC && VecOp.getOpcode() == ISD::BITCAST && VecVT.isInteger() && 18583 VecOp.hasOneUse()) { 18584 // The vector index of the LSBs of the source depend on the endian-ness. 18585 bool IsLE = DAG.getDataLayout().isLittleEndian(); 18586 unsigned ExtractIndex = IndexC->getZExtValue(); 18587 // extract_elt (v2i32 (bitcast i64:x)), BCTruncElt -> i32 (trunc i64:x) 18588 unsigned BCTruncElt = IsLE ? 0 : NumElts - 1; 18589 SDValue BCSrc = VecOp.getOperand(0); 18590 if (ExtractIndex == BCTruncElt && BCSrc.getValueType().isScalarInteger()) 18591 return DAG.getNode(ISD::TRUNCATE, DL, ScalarVT, BCSrc); 18592 18593 if (LegalTypes && BCSrc.getValueType().isInteger() && 18594 BCSrc.getOpcode() == ISD::SCALAR_TO_VECTOR) { 18595 // ext_elt (bitcast (scalar_to_vec i64 X to v2i64) to v4i32), TruncElt --> 18596 // trunc i64 X to i32 18597 SDValue X = BCSrc.getOperand(0); 18598 assert(X.getValueType().isScalarInteger() && ScalarVT.isScalarInteger() && 18599 "Extract element and scalar to vector can't change element type " 18600 "from FP to integer."); 18601 unsigned XBitWidth = X.getValueSizeInBits(); 18602 BCTruncElt = IsLE ? 0 : XBitWidth / VecEltBitWidth - 1; 18603 18604 // An extract element return value type can be wider than its vector 18605 // operand element type. In that case, the high bits are undefined, so 18606 // it's possible that we may need to extend rather than truncate. 18607 if (ExtractIndex == BCTruncElt && XBitWidth > VecEltBitWidth) { 18608 assert(XBitWidth % VecEltBitWidth == 0 && 18609 "Scalar bitwidth must be a multiple of vector element bitwidth"); 18610 return DAG.getAnyExtOrTrunc(X, DL, ScalarVT); 18611 } 18612 } 18613 } 18614 18615 if (SDValue BO = scalarizeExtractedBinop(N, DAG, LegalOperations)) 18616 return BO; 18617 18618 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 18619 // We only perform this optimization before the op legalization phase because 18620 // we may introduce new vector instructions which are not backed by TD 18621 // patterns. For example on AVX, extracting elements from a wide vector 18622 // without using extract_subvector. However, if we can find an underlying 18623 // scalar value, then we can always use that. 18624 if (IndexC && VecOp.getOpcode() == ISD::VECTOR_SHUFFLE) { 18625 auto *Shuf = cast<ShuffleVectorSDNode>(VecOp); 18626 // Find the new index to extract from. 18627 int OrigElt = Shuf->getMaskElt(IndexC->getZExtValue()); 18628 18629 // Extracting an undef index is undef. 18630 if (OrigElt == -1) 18631 return DAG.getUNDEF(ScalarVT); 18632 18633 // Select the right vector half to extract from. 18634 SDValue SVInVec; 18635 if (OrigElt < (int)NumElts) { 18636 SVInVec = VecOp.getOperand(0); 18637 } else { 18638 SVInVec = VecOp.getOperand(1); 18639 OrigElt -= NumElts; 18640 } 18641 18642 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 18643 SDValue InOp = SVInVec.getOperand(OrigElt); 18644 if (InOp.getValueType() != ScalarVT) { 18645 assert(InOp.getValueType().isInteger() && ScalarVT.isInteger()); 18646 InOp = DAG.getSExtOrTrunc(InOp, DL, ScalarVT); 18647 } 18648 18649 return InOp; 18650 } 18651 18652 // FIXME: We should handle recursing on other vector shuffles and 18653 // scalar_to_vector here as well. 18654 18655 if (!LegalOperations || 18656 // FIXME: Should really be just isOperationLegalOrCustom. 18657 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VecVT) || 18658 TLI.isOperationExpand(ISD::VECTOR_SHUFFLE, VecVT)) { 18659 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, SVInVec, 18660 DAG.getVectorIdxConstant(OrigElt, DL)); 18661 } 18662 } 18663 18664 // If only EXTRACT_VECTOR_ELT nodes use the source vector we can 18665 // simplify it based on the (valid) extraction indices. 18666 if (llvm::all_of(VecOp->uses(), [&](SDNode *Use) { 18667 return Use->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 18668 Use->getOperand(0) == VecOp && 18669 isa<ConstantSDNode>(Use->getOperand(1)); 18670 })) { 18671 APInt DemandedElts = APInt::getNullValue(NumElts); 18672 for (SDNode *Use : VecOp->uses()) { 18673 auto *CstElt = cast<ConstantSDNode>(Use->getOperand(1)); 18674 if (CstElt->getAPIntValue().ult(NumElts)) 18675 DemandedElts.setBit(CstElt->getZExtValue()); 18676 } 18677 if (SimplifyDemandedVectorElts(VecOp, DemandedElts, true)) { 18678 // We simplified the vector operand of this extract element. If this 18679 // extract is not dead, visit it again so it is folded properly. 18680 if (N->getOpcode() != ISD::DELETED_NODE) 18681 AddToWorklist(N); 18682 return SDValue(N, 0); 18683 } 18684 APInt DemandedBits = APInt::getAllOnesValue(VecEltBitWidth); 18685 if (SimplifyDemandedBits(VecOp, DemandedBits, DemandedElts, true)) { 18686 // We simplified the vector operand of this extract element. If this 18687 // extract is not dead, visit it again so it is folded properly. 18688 if (N->getOpcode() != ISD::DELETED_NODE) 18689 AddToWorklist(N); 18690 return SDValue(N, 0); 18691 } 18692 } 18693 18694 // Everything under here is trying to match an extract of a loaded value. 18695 // If the result of load has to be truncated, then it's not necessarily 18696 // profitable. 18697 bool BCNumEltsChanged = false; 18698 EVT ExtVT = VecVT.getVectorElementType(); 18699 EVT LVT = ExtVT; 18700 if (ScalarVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, ScalarVT)) 18701 return SDValue(); 18702 18703 if (VecOp.getOpcode() == ISD::BITCAST) { 18704 // Don't duplicate a load with other uses. 18705 if (!VecOp.hasOneUse()) 18706 return SDValue(); 18707 18708 EVT BCVT = VecOp.getOperand(0).getValueType(); 18709 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 18710 return SDValue(); 18711 if (NumElts != BCVT.getVectorNumElements()) 18712 BCNumEltsChanged = true; 18713 VecOp = VecOp.getOperand(0); 18714 ExtVT = BCVT.getVectorElementType(); 18715 } 18716 18717 // extract (vector load $addr), i --> load $addr + i * size 18718 if (!LegalOperations && !IndexC && VecOp.hasOneUse() && 18719 ISD::isNormalLoad(VecOp.getNode()) && 18720 !Index->hasPredecessor(VecOp.getNode())) { 18721 auto *VecLoad = dyn_cast<LoadSDNode>(VecOp); 18722 if (VecLoad && VecLoad->isSimple()) 18723 return scalarizeExtractedVectorLoad(N, VecVT, Index, VecLoad); 18724 } 18725 18726 // Perform only after legalization to ensure build_vector / vector_shuffle 18727 // optimizations have already been done. 18728 if (!LegalOperations || !IndexC) 18729 return SDValue(); 18730 18731 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 18732 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 18733 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 18734 int Elt = IndexC->getZExtValue(); 18735 LoadSDNode *LN0 = nullptr; 18736 if (ISD::isNormalLoad(VecOp.getNode())) { 18737 LN0 = cast<LoadSDNode>(VecOp); 18738 } else if (VecOp.getOpcode() == ISD::SCALAR_TO_VECTOR && 18739 VecOp.getOperand(0).getValueType() == ExtVT && 18740 ISD::isNormalLoad(VecOp.getOperand(0).getNode())) { 18741 // Don't duplicate a load with other uses. 18742 if (!VecOp.hasOneUse()) 18743 return SDValue(); 18744 18745 LN0 = cast<LoadSDNode>(VecOp.getOperand(0)); 18746 } 18747 if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(VecOp)) { 18748 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 18749 // => 18750 // (load $addr+1*size) 18751 18752 // Don't duplicate a load with other uses. 18753 if (!VecOp.hasOneUse()) 18754 return SDValue(); 18755 18756 // If the bit convert changed the number of elements, it is unsafe 18757 // to examine the mask. 18758 if (BCNumEltsChanged) 18759 return SDValue(); 18760 18761 // Select the input vector, guarding against out of range extract vector. 18762 int Idx = (Elt > (int)NumElts) ? -1 : Shuf->getMaskElt(Elt); 18763 VecOp = (Idx < (int)NumElts) ? VecOp.getOperand(0) : VecOp.getOperand(1); 18764 18765 if (VecOp.getOpcode() == ISD::BITCAST) { 18766 // Don't duplicate a load with other uses. 18767 if (!VecOp.hasOneUse()) 18768 return SDValue(); 18769 18770 VecOp = VecOp.getOperand(0); 18771 } 18772 if (ISD::isNormalLoad(VecOp.getNode())) { 18773 LN0 = cast<LoadSDNode>(VecOp); 18774 Elt = (Idx < (int)NumElts) ? Idx : Idx - (int)NumElts; 18775 Index = DAG.getConstant(Elt, DL, Index.getValueType()); 18776 } 18777 } else if (VecOp.getOpcode() == ISD::CONCAT_VECTORS && !BCNumEltsChanged && 18778 VecVT.getVectorElementType() == ScalarVT && 18779 (!LegalTypes || 18780 TLI.isTypeLegal( 18781 VecOp.getOperand(0).getValueType().getVectorElementType()))) { 18782 // extract_vector_elt (concat_vectors v2i16:a, v2i16:b), 0 18783 // -> extract_vector_elt a, 0 18784 // extract_vector_elt (concat_vectors v2i16:a, v2i16:b), 1 18785 // -> extract_vector_elt a, 1 18786 // extract_vector_elt (concat_vectors v2i16:a, v2i16:b), 2 18787 // -> extract_vector_elt b, 0 18788 // extract_vector_elt (concat_vectors v2i16:a, v2i16:b), 3 18789 // -> extract_vector_elt b, 1 18790 SDLoc SL(N); 18791 EVT ConcatVT = VecOp.getOperand(0).getValueType(); 18792 unsigned ConcatNumElts = ConcatVT.getVectorNumElements(); 18793 SDValue NewIdx = DAG.getConstant(Elt % ConcatNumElts, SL, 18794 Index.getValueType()); 18795 18796 SDValue ConcatOp = VecOp.getOperand(Elt / ConcatNumElts); 18797 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, 18798 ConcatVT.getVectorElementType(), 18799 ConcatOp, NewIdx); 18800 return DAG.getNode(ISD::BITCAST, SL, ScalarVT, Elt); 18801 } 18802 18803 // Make sure we found a non-volatile load and the extractelement is 18804 // the only use. 18805 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || !LN0->isSimple()) 18806 return SDValue(); 18807 18808 // If Idx was -1 above, Elt is going to be -1, so just return undef. 18809 if (Elt == -1) 18810 return DAG.getUNDEF(LVT); 18811 18812 return scalarizeExtractedVectorLoad(N, VecVT, Index, LN0); 18813 } 18814 18815 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 18816 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 18817 // We perform this optimization post type-legalization because 18818 // the type-legalizer often scalarizes integer-promoted vectors. 18819 // Performing this optimization before may create bit-casts which 18820 // will be type-legalized to complex code sequences. 18821 // We perform this optimization only before the operation legalizer because we 18822 // may introduce illegal operations. 18823 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 18824 return SDValue(); 18825 18826 unsigned NumInScalars = N->getNumOperands(); 18827 SDLoc DL(N); 18828 EVT VT = N->getValueType(0); 18829 18830 // Check to see if this is a BUILD_VECTOR of a bunch of values 18831 // which come from any_extend or zero_extend nodes. If so, we can create 18832 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 18833 // optimizations. We do not handle sign-extend because we can't fill the sign 18834 // using shuffles. 18835 EVT SourceType = MVT::Other; 18836 bool AllAnyExt = true; 18837 18838 for (unsigned i = 0; i != NumInScalars; ++i) { 18839 SDValue In = N->getOperand(i); 18840 // Ignore undef inputs. 18841 if (In.isUndef()) continue; 18842 18843 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 18844 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 18845 18846 // Abort if the element is not an extension. 18847 if (!ZeroExt && !AnyExt) { 18848 SourceType = MVT::Other; 18849 break; 18850 } 18851 18852 // The input is a ZeroExt or AnyExt. Check the original type. 18853 EVT InTy = In.getOperand(0).getValueType(); 18854 18855 // Check that all of the widened source types are the same. 18856 if (SourceType == MVT::Other) 18857 // First time. 18858 SourceType = InTy; 18859 else if (InTy != SourceType) { 18860 // Multiple income types. Abort. 18861 SourceType = MVT::Other; 18862 break; 18863 } 18864 18865 // Check if all of the extends are ANY_EXTENDs. 18866 AllAnyExt &= AnyExt; 18867 } 18868 18869 // In order to have valid types, all of the inputs must be extended from the 18870 // same source type and all of the inputs must be any or zero extend. 18871 // Scalar sizes must be a power of two. 18872 EVT OutScalarTy = VT.getScalarType(); 18873 bool ValidTypes = SourceType != MVT::Other && 18874 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 18875 isPowerOf2_32(SourceType.getSizeInBits()); 18876 18877 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 18878 // turn into a single shuffle instruction. 18879 if (!ValidTypes) 18880 return SDValue(); 18881 18882 // If we already have a splat buildvector, then don't fold it if it means 18883 // introducing zeros. 18884 if (!AllAnyExt && DAG.isSplatValue(SDValue(N, 0), /*AllowUndefs*/ true)) 18885 return SDValue(); 18886 18887 bool isLE = DAG.getDataLayout().isLittleEndian(); 18888 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 18889 assert(ElemRatio > 1 && "Invalid element size ratio"); 18890 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 18891 DAG.getConstant(0, DL, SourceType); 18892 18893 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 18894 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 18895 18896 // Populate the new build_vector 18897 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 18898 SDValue Cast = N->getOperand(i); 18899 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 18900 Cast.getOpcode() == ISD::ZERO_EXTEND || 18901 Cast.isUndef()) && "Invalid cast opcode"); 18902 SDValue In; 18903 if (Cast.isUndef()) 18904 In = DAG.getUNDEF(SourceType); 18905 else 18906 In = Cast->getOperand(0); 18907 unsigned Index = isLE ? (i * ElemRatio) : 18908 (i * ElemRatio + (ElemRatio - 1)); 18909 18910 assert(Index < Ops.size() && "Invalid index"); 18911 Ops[Index] = In; 18912 } 18913 18914 // The type of the new BUILD_VECTOR node. 18915 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 18916 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 18917 "Invalid vector size"); 18918 // Check if the new vector type is legal. 18919 if (!isTypeLegal(VecVT) || 18920 (!TLI.isOperationLegal(ISD::BUILD_VECTOR, VecVT) && 18921 TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))) 18922 return SDValue(); 18923 18924 // Make the new BUILD_VECTOR. 18925 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops); 18926 18927 // The new BUILD_VECTOR node has the potential to be further optimized. 18928 AddToWorklist(BV.getNode()); 18929 // Bitcast to the desired type. 18930 return DAG.getBitcast(VT, BV); 18931 } 18932 18933 // Simplify (build_vec (trunc $1) 18934 // (trunc (srl $1 half-width)) 18935 // (trunc (srl $1 (2 * half-width))) ) 18936 // to (bitcast $1) 18937 SDValue DAGCombiner::reduceBuildVecTruncToBitCast(SDNode *N) { 18938 assert(N->getOpcode() == ISD::BUILD_VECTOR && "Expected build vector"); 18939 18940 // Only for little endian 18941 if (!DAG.getDataLayout().isLittleEndian()) 18942 return SDValue(); 18943 18944 SDLoc DL(N); 18945 EVT VT = N->getValueType(0); 18946 EVT OutScalarTy = VT.getScalarType(); 18947 uint64_t ScalarTypeBitsize = OutScalarTy.getSizeInBits(); 18948 18949 // Only for power of two types to be sure that bitcast works well 18950 if (!isPowerOf2_64(ScalarTypeBitsize)) 18951 return SDValue(); 18952 18953 unsigned NumInScalars = N->getNumOperands(); 18954 18955 // Look through bitcasts 18956 auto PeekThroughBitcast = [](SDValue Op) { 18957 if (Op.getOpcode() == ISD::BITCAST) 18958 return Op.getOperand(0); 18959 return Op; 18960 }; 18961 18962 // The source value where all the parts are extracted. 18963 SDValue Src; 18964 for (unsigned i = 0; i != NumInScalars; ++i) { 18965 SDValue In = PeekThroughBitcast(N->getOperand(i)); 18966 // Ignore undef inputs. 18967 if (In.isUndef()) continue; 18968 18969 if (In.getOpcode() != ISD::TRUNCATE) 18970 return SDValue(); 18971 18972 In = PeekThroughBitcast(In.getOperand(0)); 18973 18974 if (In.getOpcode() != ISD::SRL) { 18975 // For now only build_vec without shuffling, handle shifts here in the 18976 // future. 18977 if (i != 0) 18978 return SDValue(); 18979 18980 Src = In; 18981 } else { 18982 // In is SRL 18983 SDValue part = PeekThroughBitcast(In.getOperand(0)); 18984 18985 if (!Src) { 18986 Src = part; 18987 } else if (Src != part) { 18988 // Vector parts do not stem from the same variable 18989 return SDValue(); 18990 } 18991 18992 SDValue ShiftAmtVal = In.getOperand(1); 18993 if (!isa<ConstantSDNode>(ShiftAmtVal)) 18994 return SDValue(); 18995 18996 uint64_t ShiftAmt = In.getNode()->getConstantOperandVal(1); 18997 18998 // The extracted value is not extracted at the right position 18999 if (ShiftAmt != i * ScalarTypeBitsize) 19000 return SDValue(); 19001 } 19002 } 19003 19004 // Only cast if the size is the same 19005 if (Src.getValueType().getSizeInBits() != VT.getSizeInBits()) 19006 return SDValue(); 19007 19008 return DAG.getBitcast(VT, Src); 19009 } 19010 19011 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N, 19012 ArrayRef<int> VectorMask, 19013 SDValue VecIn1, SDValue VecIn2, 19014 unsigned LeftIdx, bool DidSplitVec) { 19015 SDValue ZeroIdx = DAG.getVectorIdxConstant(0, DL); 19016 19017 EVT VT = N->getValueType(0); 19018 EVT InVT1 = VecIn1.getValueType(); 19019 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1; 19020 19021 unsigned NumElems = VT.getVectorNumElements(); 19022 unsigned ShuffleNumElems = NumElems; 19023 19024 // If we artificially split a vector in two already, then the offsets in the 19025 // operands will all be based off of VecIn1, even those in VecIn2. 19026 unsigned Vec2Offset = DidSplitVec ? 0 : InVT1.getVectorNumElements(); 19027 19028 uint64_t VTSize = VT.getFixedSizeInBits(); 19029 uint64_t InVT1Size = InVT1.getFixedSizeInBits(); 19030 uint64_t InVT2Size = InVT2.getFixedSizeInBits(); 19031 19032 // We can't generate a shuffle node with mismatched input and output types. 19033 // Try to make the types match the type of the output. 19034 if (InVT1 != VT || InVT2 != VT) { 19035 if ((VTSize % InVT1Size == 0) && InVT1 == InVT2) { 19036 // If the output vector length is a multiple of both input lengths, 19037 // we can concatenate them and pad the rest with undefs. 19038 unsigned NumConcats = VTSize / InVT1Size; 19039 assert(NumConcats >= 2 && "Concat needs at least two inputs!"); 19040 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1)); 19041 ConcatOps[0] = VecIn1; 19042 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1); 19043 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 19044 VecIn2 = SDValue(); 19045 } else if (InVT1Size == VTSize * 2) { 19046 if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems)) 19047 return SDValue(); 19048 19049 if (!VecIn2.getNode()) { 19050 // If we only have one input vector, and it's twice the size of the 19051 // output, split it in two. 19052 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, 19053 DAG.getVectorIdxConstant(NumElems, DL)); 19054 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx); 19055 // Since we now have shorter input vectors, adjust the offset of the 19056 // second vector's start. 19057 Vec2Offset = NumElems; 19058 } else if (InVT2Size <= InVT1Size) { 19059 // VecIn1 is wider than the output, and we have another, possibly 19060 // smaller input. Pad the smaller input with undefs, shuffle at the 19061 // input vector width, and extract the output. 19062 // The shuffle type is different than VT, so check legality again. 19063 if (LegalOperations && 19064 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1)) 19065 return SDValue(); 19066 19067 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to 19068 // lower it back into a BUILD_VECTOR. So if the inserted type is 19069 // illegal, don't even try. 19070 if (InVT1 != InVT2) { 19071 if (!TLI.isTypeLegal(InVT2)) 19072 return SDValue(); 19073 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1, 19074 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx); 19075 } 19076 ShuffleNumElems = NumElems * 2; 19077 } else { 19078 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider 19079 // than VecIn1. We can't handle this for now - this case will disappear 19080 // when we start sorting the vectors by type. 19081 return SDValue(); 19082 } 19083 } else if (InVT2Size * 2 == VTSize && InVT1Size == VTSize) { 19084 SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2)); 19085 ConcatOps[0] = VecIn2; 19086 VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 19087 } else { 19088 // TODO: Support cases where the length mismatch isn't exactly by a 19089 // factor of 2. 19090 // TODO: Move this check upwards, so that if we have bad type 19091 // mismatches, we don't create any DAG nodes. 19092 return SDValue(); 19093 } 19094 } 19095 19096 // Initialize mask to undef. 19097 SmallVector<int, 8> Mask(ShuffleNumElems, -1); 19098 19099 // Only need to run up to the number of elements actually used, not the 19100 // total number of elements in the shuffle - if we are shuffling a wider 19101 // vector, the high lanes should be set to undef. 19102 for (unsigned i = 0; i != NumElems; ++i) { 19103 if (VectorMask[i] <= 0) 19104 continue; 19105 19106 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1); 19107 if (VectorMask[i] == (int)LeftIdx) { 19108 Mask[i] = ExtIndex; 19109 } else if (VectorMask[i] == (int)LeftIdx + 1) { 19110 Mask[i] = Vec2Offset + ExtIndex; 19111 } 19112 } 19113 19114 // The type the input vectors may have changed above. 19115 InVT1 = VecIn1.getValueType(); 19116 19117 // If we already have a VecIn2, it should have the same type as VecIn1. 19118 // If we don't, get an undef/zero vector of the appropriate type. 19119 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1); 19120 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type."); 19121 19122 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask); 19123 if (ShuffleNumElems > NumElems) 19124 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx); 19125 19126 return Shuffle; 19127 } 19128 19129 static SDValue reduceBuildVecToShuffleWithZero(SDNode *BV, SelectionDAG &DAG) { 19130 assert(BV->getOpcode() == ISD::BUILD_VECTOR && "Expected build vector"); 19131 19132 // First, determine where the build vector is not undef. 19133 // TODO: We could extend this to handle zero elements as well as undefs. 19134 int NumBVOps = BV->getNumOperands(); 19135 int ZextElt = -1; 19136 for (int i = 0; i != NumBVOps; ++i) { 19137 SDValue Op = BV->getOperand(i); 19138 if (Op.isUndef()) 19139 continue; 19140 if (ZextElt == -1) 19141 ZextElt = i; 19142 else 19143 return SDValue(); 19144 } 19145 // Bail out if there's no non-undef element. 19146 if (ZextElt == -1) 19147 return SDValue(); 19148 19149 // The build vector contains some number of undef elements and exactly 19150 // one other element. That other element must be a zero-extended scalar 19151 // extracted from a vector at a constant index to turn this into a shuffle. 19152 // Also, require that the build vector does not implicitly truncate/extend 19153 // its elements. 19154 // TODO: This could be enhanced to allow ANY_EXTEND as well as ZERO_EXTEND. 19155 EVT VT = BV->getValueType(0); 19156 SDValue Zext = BV->getOperand(ZextElt); 19157 if (Zext.getOpcode() != ISD::ZERO_EXTEND || !Zext.hasOneUse() || 19158 Zext.getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 19159 !isa<ConstantSDNode>(Zext.getOperand(0).getOperand(1)) || 19160 Zext.getValueSizeInBits() != VT.getScalarSizeInBits()) 19161 return SDValue(); 19162 19163 // The zero-extend must be a multiple of the source size, and we must be 19164 // building a vector of the same size as the source of the extract element. 19165 SDValue Extract = Zext.getOperand(0); 19166 unsigned DestSize = Zext.getValueSizeInBits(); 19167 unsigned SrcSize = Extract.getValueSizeInBits(); 19168 if (DestSize % SrcSize != 0 || 19169 Extract.getOperand(0).getValueSizeInBits() != VT.getSizeInBits()) 19170 return SDValue(); 19171 19172 // Create a shuffle mask that will combine the extracted element with zeros 19173 // and undefs. 19174 int ZextRatio = DestSize / SrcSize; 19175 int NumMaskElts = NumBVOps * ZextRatio; 19176 SmallVector<int, 32> ShufMask(NumMaskElts, -1); 19177 for (int i = 0; i != NumMaskElts; ++i) { 19178 if (i / ZextRatio == ZextElt) { 19179 // The low bits of the (potentially translated) extracted element map to 19180 // the source vector. The high bits map to zero. We will use a zero vector 19181 // as the 2nd source operand of the shuffle, so use the 1st element of 19182 // that vector (mask value is number-of-elements) for the high bits. 19183 if (i % ZextRatio == 0) 19184 ShufMask[i] = Extract.getConstantOperandVal(1); 19185 else 19186 ShufMask[i] = NumMaskElts; 19187 } 19188 19189 // Undef elements of the build vector remain undef because we initialize 19190 // the shuffle mask with -1. 19191 } 19192 19193 // buildvec undef, ..., (zext (extractelt V, IndexC)), undef... --> 19194 // bitcast (shuffle V, ZeroVec, VectorMask) 19195 SDLoc DL(BV); 19196 EVT VecVT = Extract.getOperand(0).getValueType(); 19197 SDValue ZeroVec = DAG.getConstant(0, DL, VecVT); 19198 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 19199 SDValue Shuf = TLI.buildLegalVectorShuffle(VecVT, DL, Extract.getOperand(0), 19200 ZeroVec, ShufMask, DAG); 19201 if (!Shuf) 19202 return SDValue(); 19203 return DAG.getBitcast(VT, Shuf); 19204 } 19205 19206 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 19207 // operations. If the types of the vectors we're extracting from allow it, 19208 // turn this into a vector_shuffle node. 19209 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) { 19210 SDLoc DL(N); 19211 EVT VT = N->getValueType(0); 19212 19213 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 19214 if (!isTypeLegal(VT)) 19215 return SDValue(); 19216 19217 if (SDValue V = reduceBuildVecToShuffleWithZero(N, DAG)) 19218 return V; 19219 19220 // May only combine to shuffle after legalize if shuffle is legal. 19221 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 19222 return SDValue(); 19223 19224 bool UsesZeroVector = false; 19225 unsigned NumElems = N->getNumOperands(); 19226 19227 // Record, for each element of the newly built vector, which input vector 19228 // that element comes from. -1 stands for undef, 0 for the zero vector, 19229 // and positive values for the input vectors. 19230 // VectorMask maps each element to its vector number, and VecIn maps vector 19231 // numbers to their initial SDValues. 19232 19233 SmallVector<int, 8> VectorMask(NumElems, -1); 19234 SmallVector<SDValue, 8> VecIn; 19235 VecIn.push_back(SDValue()); 19236 19237 for (unsigned i = 0; i != NumElems; ++i) { 19238 SDValue Op = N->getOperand(i); 19239 19240 if (Op.isUndef()) 19241 continue; 19242 19243 // See if we can use a blend with a zero vector. 19244 // TODO: Should we generalize this to a blend with an arbitrary constant 19245 // vector? 19246 if (isNullConstant(Op) || isNullFPConstant(Op)) { 19247 UsesZeroVector = true; 19248 VectorMask[i] = 0; 19249 continue; 19250 } 19251 19252 // Not an undef or zero. If the input is something other than an 19253 // EXTRACT_VECTOR_ELT with an in-range constant index, bail out. 19254 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 19255 !isa<ConstantSDNode>(Op.getOperand(1))) 19256 return SDValue(); 19257 SDValue ExtractedFromVec = Op.getOperand(0); 19258 19259 if (ExtractedFromVec.getValueType().isScalableVector()) 19260 return SDValue(); 19261 19262 const APInt &ExtractIdx = Op.getConstantOperandAPInt(1); 19263 if (ExtractIdx.uge(ExtractedFromVec.getValueType().getVectorNumElements())) 19264 return SDValue(); 19265 19266 // All inputs must have the same element type as the output. 19267 if (VT.getVectorElementType() != 19268 ExtractedFromVec.getValueType().getVectorElementType()) 19269 return SDValue(); 19270 19271 // Have we seen this input vector before? 19272 // The vectors are expected to be tiny (usually 1 or 2 elements), so using 19273 // a map back from SDValues to numbers isn't worth it. 19274 unsigned Idx = std::distance(VecIn.begin(), find(VecIn, ExtractedFromVec)); 19275 if (Idx == VecIn.size()) 19276 VecIn.push_back(ExtractedFromVec); 19277 19278 VectorMask[i] = Idx; 19279 } 19280 19281 // If we didn't find at least one input vector, bail out. 19282 if (VecIn.size() < 2) 19283 return SDValue(); 19284 19285 // If all the Operands of BUILD_VECTOR extract from same 19286 // vector, then split the vector efficiently based on the maximum 19287 // vector access index and adjust the VectorMask and 19288 // VecIn accordingly. 19289 bool DidSplitVec = false; 19290 if (VecIn.size() == 2) { 19291 unsigned MaxIndex = 0; 19292 unsigned NearestPow2 = 0; 19293 SDValue Vec = VecIn.back(); 19294 EVT InVT = Vec.getValueType(); 19295 SmallVector<unsigned, 8> IndexVec(NumElems, 0); 19296 19297 for (unsigned i = 0; i < NumElems; i++) { 19298 if (VectorMask[i] <= 0) 19299 continue; 19300 unsigned Index = N->getOperand(i).getConstantOperandVal(1); 19301 IndexVec[i] = Index; 19302 MaxIndex = std::max(MaxIndex, Index); 19303 } 19304 19305 NearestPow2 = PowerOf2Ceil(MaxIndex); 19306 if (InVT.isSimple() && NearestPow2 > 2 && MaxIndex < NearestPow2 && 19307 NumElems * 2 < NearestPow2) { 19308 unsigned SplitSize = NearestPow2 / 2; 19309 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), 19310 InVT.getVectorElementType(), SplitSize); 19311 if (TLI.isTypeLegal(SplitVT)) { 19312 SDValue VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec, 19313 DAG.getVectorIdxConstant(SplitSize, DL)); 19314 SDValue VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec, 19315 DAG.getVectorIdxConstant(0, DL)); 19316 VecIn.pop_back(); 19317 VecIn.push_back(VecIn1); 19318 VecIn.push_back(VecIn2); 19319 DidSplitVec = true; 19320 19321 for (unsigned i = 0; i < NumElems; i++) { 19322 if (VectorMask[i] <= 0) 19323 continue; 19324 VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2; 19325 } 19326 } 19327 } 19328 } 19329 19330 // TODO: We want to sort the vectors by descending length, so that adjacent 19331 // pairs have similar length, and the longer vector is always first in the 19332 // pair. 19333 19334 // TODO: Should this fire if some of the input vectors has illegal type (like 19335 // it does now), or should we let legalization run its course first? 19336 19337 // Shuffle phase: 19338 // Take pairs of vectors, and shuffle them so that the result has elements 19339 // from these vectors in the correct places. 19340 // For example, given: 19341 // t10: i32 = extract_vector_elt t1, Constant:i64<0> 19342 // t11: i32 = extract_vector_elt t2, Constant:i64<0> 19343 // t12: i32 = extract_vector_elt t3, Constant:i64<0> 19344 // t13: i32 = extract_vector_elt t1, Constant:i64<1> 19345 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13 19346 // We will generate: 19347 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2 19348 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef 19349 SmallVector<SDValue, 4> Shuffles; 19350 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) { 19351 unsigned LeftIdx = 2 * In + 1; 19352 SDValue VecLeft = VecIn[LeftIdx]; 19353 SDValue VecRight = 19354 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue(); 19355 19356 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft, 19357 VecRight, LeftIdx, DidSplitVec)) 19358 Shuffles.push_back(Shuffle); 19359 else 19360 return SDValue(); 19361 } 19362 19363 // If we need the zero vector as an "ingredient" in the blend tree, add it 19364 // to the list of shuffles. 19365 if (UsesZeroVector) 19366 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT) 19367 : DAG.getConstantFP(0.0, DL, VT)); 19368 19369 // If we only have one shuffle, we're done. 19370 if (Shuffles.size() == 1) 19371 return Shuffles[0]; 19372 19373 // Update the vector mask to point to the post-shuffle vectors. 19374 for (int &Vec : VectorMask) 19375 if (Vec == 0) 19376 Vec = Shuffles.size() - 1; 19377 else 19378 Vec = (Vec - 1) / 2; 19379 19380 // More than one shuffle. Generate a binary tree of blends, e.g. if from 19381 // the previous step we got the set of shuffles t10, t11, t12, t13, we will 19382 // generate: 19383 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2 19384 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4 19385 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6 19386 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8 19387 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11 19388 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13 19389 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21 19390 19391 // Make sure the initial size of the shuffle list is even. 19392 if (Shuffles.size() % 2) 19393 Shuffles.push_back(DAG.getUNDEF(VT)); 19394 19395 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) { 19396 if (CurSize % 2) { 19397 Shuffles[CurSize] = DAG.getUNDEF(VT); 19398 CurSize++; 19399 } 19400 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) { 19401 int Left = 2 * In; 19402 int Right = 2 * In + 1; 19403 SmallVector<int, 8> Mask(NumElems, -1); 19404 for (unsigned i = 0; i != NumElems; ++i) { 19405 if (VectorMask[i] == Left) { 19406 Mask[i] = i; 19407 VectorMask[i] = In; 19408 } else if (VectorMask[i] == Right) { 19409 Mask[i] = i + NumElems; 19410 VectorMask[i] = In; 19411 } 19412 } 19413 19414 Shuffles[In] = 19415 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask); 19416 } 19417 } 19418 return Shuffles[0]; 19419 } 19420 19421 // Try to turn a build vector of zero extends of extract vector elts into a 19422 // a vector zero extend and possibly an extract subvector. 19423 // TODO: Support sign extend? 19424 // TODO: Allow undef elements? 19425 SDValue DAGCombiner::convertBuildVecZextToZext(SDNode *N) { 19426 if (LegalOperations) 19427 return SDValue(); 19428 19429 EVT VT = N->getValueType(0); 19430 19431 bool FoundZeroExtend = false; 19432 SDValue Op0 = N->getOperand(0); 19433 auto checkElem = [&](SDValue Op) -> int64_t { 19434 unsigned Opc = Op.getOpcode(); 19435 FoundZeroExtend |= (Opc == ISD::ZERO_EXTEND); 19436 if ((Opc == ISD::ZERO_EXTEND || Opc == ISD::ANY_EXTEND) && 19437 Op.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT && 19438 Op0.getOperand(0).getOperand(0) == Op.getOperand(0).getOperand(0)) 19439 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(0).getOperand(1))) 19440 return C->getZExtValue(); 19441 return -1; 19442 }; 19443 19444 // Make sure the first element matches 19445 // (zext (extract_vector_elt X, C)) 19446 int64_t Offset = checkElem(Op0); 19447 if (Offset < 0) 19448 return SDValue(); 19449 19450 unsigned NumElems = N->getNumOperands(); 19451 SDValue In = Op0.getOperand(0).getOperand(0); 19452 EVT InSVT = In.getValueType().getScalarType(); 19453 EVT InVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumElems); 19454 19455 // Don't create an illegal input type after type legalization. 19456 if (LegalTypes && !TLI.isTypeLegal(InVT)) 19457 return SDValue(); 19458 19459 // Ensure all the elements come from the same vector and are adjacent. 19460 for (unsigned i = 1; i != NumElems; ++i) { 19461 if ((Offset + i) != checkElem(N->getOperand(i))) 19462 return SDValue(); 19463 } 19464 19465 SDLoc DL(N); 19466 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InVT, In, 19467 Op0.getOperand(0).getOperand(1)); 19468 return DAG.getNode(FoundZeroExtend ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND, DL, 19469 VT, In); 19470 } 19471 19472 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 19473 EVT VT = N->getValueType(0); 19474 19475 // A vector built entirely of undefs is undef. 19476 if (ISD::allOperandsUndef(N)) 19477 return DAG.getUNDEF(VT); 19478 19479 // If this is a splat of a bitcast from another vector, change to a 19480 // concat_vector. 19481 // For example: 19482 // (build_vector (i64 (bitcast (v2i32 X))), (i64 (bitcast (v2i32 X)))) -> 19483 // (v2i64 (bitcast (concat_vectors (v2i32 X), (v2i32 X)))) 19484 // 19485 // If X is a build_vector itself, the concat can become a larger build_vector. 19486 // TODO: Maybe this is useful for non-splat too? 19487 if (!LegalOperations) { 19488 if (SDValue Splat = cast<BuildVectorSDNode>(N)->getSplatValue()) { 19489 Splat = peekThroughBitcasts(Splat); 19490 EVT SrcVT = Splat.getValueType(); 19491 if (SrcVT.isVector()) { 19492 unsigned NumElts = N->getNumOperands() * SrcVT.getVectorNumElements(); 19493 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), 19494 SrcVT.getVectorElementType(), NumElts); 19495 if (!LegalTypes || TLI.isTypeLegal(NewVT)) { 19496 SmallVector<SDValue, 8> Ops(N->getNumOperands(), Splat); 19497 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), 19498 NewVT, Ops); 19499 return DAG.getBitcast(VT, Concat); 19500 } 19501 } 19502 } 19503 } 19504 19505 // Check if we can express BUILD VECTOR via subvector extract. 19506 if (!LegalTypes && (N->getNumOperands() > 1)) { 19507 SDValue Op0 = N->getOperand(0); 19508 auto checkElem = [&](SDValue Op) -> uint64_t { 19509 if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) && 19510 (Op0.getOperand(0) == Op.getOperand(0))) 19511 if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 19512 return CNode->getZExtValue(); 19513 return -1; 19514 }; 19515 19516 int Offset = checkElem(Op0); 19517 for (unsigned i = 0; i < N->getNumOperands(); ++i) { 19518 if (Offset + i != checkElem(N->getOperand(i))) { 19519 Offset = -1; 19520 break; 19521 } 19522 } 19523 19524 if ((Offset == 0) && 19525 (Op0.getOperand(0).getValueType() == N->getValueType(0))) 19526 return Op0.getOperand(0); 19527 if ((Offset != -1) && 19528 ((Offset % N->getValueType(0).getVectorNumElements()) == 19529 0)) // IDX must be multiple of output size. 19530 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0), 19531 Op0.getOperand(0), Op0.getOperand(1)); 19532 } 19533 19534 if (SDValue V = convertBuildVecZextToZext(N)) 19535 return V; 19536 19537 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 19538 return V; 19539 19540 if (SDValue V = reduceBuildVecTruncToBitCast(N)) 19541 return V; 19542 19543 if (SDValue V = reduceBuildVecToShuffle(N)) 19544 return V; 19545 19546 // A splat of a single element is a SPLAT_VECTOR if supported on the target. 19547 // Do this late as some of the above may replace the splat. 19548 if (TLI.getOperationAction(ISD::SPLAT_VECTOR, VT) != TargetLowering::Expand) 19549 if (SDValue V = cast<BuildVectorSDNode>(N)->getSplatValue()) { 19550 assert(!V.isUndef() && "Splat of undef should have been handled earlier"); 19551 return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), VT, V); 19552 } 19553 19554 return SDValue(); 19555 } 19556 19557 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 19558 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 19559 EVT OpVT = N->getOperand(0).getValueType(); 19560 19561 // If the operands are legal vectors, leave them alone. 19562 if (TLI.isTypeLegal(OpVT)) 19563 return SDValue(); 19564 19565 SDLoc DL(N); 19566 EVT VT = N->getValueType(0); 19567 SmallVector<SDValue, 8> Ops; 19568 19569 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 19570 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 19571 19572 // Keep track of what we encounter. 19573 bool AnyInteger = false; 19574 bool AnyFP = false; 19575 for (const SDValue &Op : N->ops()) { 19576 if (ISD::BITCAST == Op.getOpcode() && 19577 !Op.getOperand(0).getValueType().isVector()) 19578 Ops.push_back(Op.getOperand(0)); 19579 else if (ISD::UNDEF == Op.getOpcode()) 19580 Ops.push_back(ScalarUndef); 19581 else 19582 return SDValue(); 19583 19584 // Note whether we encounter an integer or floating point scalar. 19585 // If it's neither, bail out, it could be something weird like x86mmx. 19586 EVT LastOpVT = Ops.back().getValueType(); 19587 if (LastOpVT.isFloatingPoint()) 19588 AnyFP = true; 19589 else if (LastOpVT.isInteger()) 19590 AnyInteger = true; 19591 else 19592 return SDValue(); 19593 } 19594 19595 // If any of the operands is a floating point scalar bitcast to a vector, 19596 // use floating point types throughout, and bitcast everything. 19597 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 19598 if (AnyFP) { 19599 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 19600 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 19601 if (AnyInteger) { 19602 for (SDValue &Op : Ops) { 19603 if (Op.getValueType() == SVT) 19604 continue; 19605 if (Op.isUndef()) 19606 Op = ScalarUndef; 19607 else 19608 Op = DAG.getBitcast(SVT, Op); 19609 } 19610 } 19611 } 19612 19613 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 19614 VT.getSizeInBits() / SVT.getSizeInBits()); 19615 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops)); 19616 } 19617 19618 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 19619 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 19620 // most two distinct vectors the same size as the result, attempt to turn this 19621 // into a legal shuffle. 19622 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 19623 EVT VT = N->getValueType(0); 19624 EVT OpVT = N->getOperand(0).getValueType(); 19625 19626 // We currently can't generate an appropriate shuffle for a scalable vector. 19627 if (VT.isScalableVector()) 19628 return SDValue(); 19629 19630 int NumElts = VT.getVectorNumElements(); 19631 int NumOpElts = OpVT.getVectorNumElements(); 19632 19633 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 19634 SmallVector<int, 8> Mask; 19635 19636 for (SDValue Op : N->ops()) { 19637 Op = peekThroughBitcasts(Op); 19638 19639 // UNDEF nodes convert to UNDEF shuffle mask values. 19640 if (Op.isUndef()) { 19641 Mask.append((unsigned)NumOpElts, -1); 19642 continue; 19643 } 19644 19645 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 19646 return SDValue(); 19647 19648 // What vector are we extracting the subvector from and at what index? 19649 SDValue ExtVec = Op.getOperand(0); 19650 int ExtIdx = Op.getConstantOperandVal(1); 19651 19652 // We want the EVT of the original extraction to correctly scale the 19653 // extraction index. 19654 EVT ExtVT = ExtVec.getValueType(); 19655 ExtVec = peekThroughBitcasts(ExtVec); 19656 19657 // UNDEF nodes convert to UNDEF shuffle mask values. 19658 if (ExtVec.isUndef()) { 19659 Mask.append((unsigned)NumOpElts, -1); 19660 continue; 19661 } 19662 19663 // Ensure that we are extracting a subvector from a vector the same 19664 // size as the result. 19665 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 19666 return SDValue(); 19667 19668 // Scale the subvector index to account for any bitcast. 19669 int NumExtElts = ExtVT.getVectorNumElements(); 19670 if (0 == (NumExtElts % NumElts)) 19671 ExtIdx /= (NumExtElts / NumElts); 19672 else if (0 == (NumElts % NumExtElts)) 19673 ExtIdx *= (NumElts / NumExtElts); 19674 else 19675 return SDValue(); 19676 19677 // At most we can reference 2 inputs in the final shuffle. 19678 if (SV0.isUndef() || SV0 == ExtVec) { 19679 SV0 = ExtVec; 19680 for (int i = 0; i != NumOpElts; ++i) 19681 Mask.push_back(i + ExtIdx); 19682 } else if (SV1.isUndef() || SV1 == ExtVec) { 19683 SV1 = ExtVec; 19684 for (int i = 0; i != NumOpElts; ++i) 19685 Mask.push_back(i + ExtIdx + NumElts); 19686 } else { 19687 return SDValue(); 19688 } 19689 } 19690 19691 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 19692 return TLI.buildLegalVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 19693 DAG.getBitcast(VT, SV1), Mask, DAG); 19694 } 19695 19696 static SDValue combineConcatVectorOfCasts(SDNode *N, SelectionDAG &DAG) { 19697 unsigned CastOpcode = N->getOperand(0).getOpcode(); 19698 switch (CastOpcode) { 19699 case ISD::SINT_TO_FP: 19700 case ISD::UINT_TO_FP: 19701 case ISD::FP_TO_SINT: 19702 case ISD::FP_TO_UINT: 19703 // TODO: Allow more opcodes? 19704 // case ISD::BITCAST: 19705 // case ISD::TRUNCATE: 19706 // case ISD::ZERO_EXTEND: 19707 // case ISD::SIGN_EXTEND: 19708 // case ISD::FP_EXTEND: 19709 break; 19710 default: 19711 return SDValue(); 19712 } 19713 19714 EVT SrcVT = N->getOperand(0).getOperand(0).getValueType(); 19715 if (!SrcVT.isVector()) 19716 return SDValue(); 19717 19718 // All operands of the concat must be the same kind of cast from the same 19719 // source type. 19720 SmallVector<SDValue, 4> SrcOps; 19721 for (SDValue Op : N->ops()) { 19722 if (Op.getOpcode() != CastOpcode || !Op.hasOneUse() || 19723 Op.getOperand(0).getValueType() != SrcVT) 19724 return SDValue(); 19725 SrcOps.push_back(Op.getOperand(0)); 19726 } 19727 19728 // The wider cast must be supported by the target. This is unusual because 19729 // the operation support type parameter depends on the opcode. In addition, 19730 // check the other type in the cast to make sure this is really legal. 19731 EVT VT = N->getValueType(0); 19732 EVT SrcEltVT = SrcVT.getVectorElementType(); 19733 ElementCount NumElts = SrcVT.getVectorElementCount() * N->getNumOperands(); 19734 EVT ConcatSrcVT = EVT::getVectorVT(*DAG.getContext(), SrcEltVT, NumElts); 19735 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 19736 switch (CastOpcode) { 19737 case ISD::SINT_TO_FP: 19738 case ISD::UINT_TO_FP: 19739 if (!TLI.isOperationLegalOrCustom(CastOpcode, ConcatSrcVT) || 19740 !TLI.isTypeLegal(VT)) 19741 return SDValue(); 19742 break; 19743 case ISD::FP_TO_SINT: 19744 case ISD::FP_TO_UINT: 19745 if (!TLI.isOperationLegalOrCustom(CastOpcode, VT) || 19746 !TLI.isTypeLegal(ConcatSrcVT)) 19747 return SDValue(); 19748 break; 19749 default: 19750 llvm_unreachable("Unexpected cast opcode"); 19751 } 19752 19753 // concat (cast X), (cast Y)... -> cast (concat X, Y...) 19754 SDLoc DL(N); 19755 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, DL, ConcatSrcVT, SrcOps); 19756 return DAG.getNode(CastOpcode, DL, VT, NewConcat); 19757 } 19758 19759 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 19760 // If we only have one input vector, we don't need to do any concatenation. 19761 if (N->getNumOperands() == 1) 19762 return N->getOperand(0); 19763 19764 // Check if all of the operands are undefs. 19765 EVT VT = N->getValueType(0); 19766 if (ISD::allOperandsUndef(N)) 19767 return DAG.getUNDEF(VT); 19768 19769 // Optimize concat_vectors where all but the first of the vectors are undef. 19770 if (all_of(drop_begin(N->ops()), 19771 [](const SDValue &Op) { return Op.isUndef(); })) { 19772 SDValue In = N->getOperand(0); 19773 assert(In.getValueType().isVector() && "Must concat vectors"); 19774 19775 // If the input is a concat_vectors, just make a larger concat by padding 19776 // with smaller undefs. 19777 if (In.getOpcode() == ISD::CONCAT_VECTORS && In.hasOneUse()) { 19778 unsigned NumOps = N->getNumOperands() * In.getNumOperands(); 19779 SmallVector<SDValue, 4> Ops(In->op_begin(), In->op_end()); 19780 Ops.resize(NumOps, DAG.getUNDEF(Ops[0].getValueType())); 19781 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 19782 } 19783 19784 SDValue Scalar = peekThroughOneUseBitcasts(In); 19785 19786 // concat_vectors(scalar_to_vector(scalar), undef) -> 19787 // scalar_to_vector(scalar) 19788 if (!LegalOperations && Scalar.getOpcode() == ISD::SCALAR_TO_VECTOR && 19789 Scalar.hasOneUse()) { 19790 EVT SVT = Scalar.getValueType().getVectorElementType(); 19791 if (SVT == Scalar.getOperand(0).getValueType()) 19792 Scalar = Scalar.getOperand(0); 19793 } 19794 19795 // concat_vectors(scalar, undef) -> scalar_to_vector(scalar) 19796 if (!Scalar.getValueType().isVector()) { 19797 // If the bitcast type isn't legal, it might be a trunc of a legal type; 19798 // look through the trunc so we can still do the transform: 19799 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 19800 if (Scalar->getOpcode() == ISD::TRUNCATE && 19801 !TLI.isTypeLegal(Scalar.getValueType()) && 19802 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 19803 Scalar = Scalar->getOperand(0); 19804 19805 EVT SclTy = Scalar.getValueType(); 19806 19807 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 19808 return SDValue(); 19809 19810 // Bail out if the vector size is not a multiple of the scalar size. 19811 if (VT.getSizeInBits() % SclTy.getSizeInBits()) 19812 return SDValue(); 19813 19814 unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits(); 19815 if (VNTNumElms < 2) 19816 return SDValue(); 19817 19818 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms); 19819 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 19820 return SDValue(); 19821 19822 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar); 19823 return DAG.getBitcast(VT, Res); 19824 } 19825 } 19826 19827 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 19828 // We have already tested above for an UNDEF only concatenation. 19829 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 19830 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 19831 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 19832 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 19833 }; 19834 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) { 19835 SmallVector<SDValue, 8> Opnds; 19836 EVT SVT = VT.getScalarType(); 19837 19838 EVT MinVT = SVT; 19839 if (!SVT.isFloatingPoint()) { 19840 // If BUILD_VECTOR are from built from integer, they may have different 19841 // operand types. Get the smallest type and truncate all operands to it. 19842 bool FoundMinVT = false; 19843 for (const SDValue &Op : N->ops()) 19844 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 19845 EVT OpSVT = Op.getOperand(0).getValueType(); 19846 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 19847 FoundMinVT = true; 19848 } 19849 assert(FoundMinVT && "Concat vector type mismatch"); 19850 } 19851 19852 for (const SDValue &Op : N->ops()) { 19853 EVT OpVT = Op.getValueType(); 19854 unsigned NumElts = OpVT.getVectorNumElements(); 19855 19856 if (ISD::UNDEF == Op.getOpcode()) 19857 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 19858 19859 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 19860 if (SVT.isFloatingPoint()) { 19861 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 19862 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 19863 } else { 19864 for (unsigned i = 0; i != NumElts; ++i) 19865 Opnds.push_back( 19866 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 19867 } 19868 } 19869 } 19870 19871 assert(VT.getVectorNumElements() == Opnds.size() && 19872 "Concat vector type mismatch"); 19873 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 19874 } 19875 19876 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 19877 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 19878 return V; 19879 19880 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 19881 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 19882 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 19883 return V; 19884 19885 if (SDValue V = combineConcatVectorOfCasts(N, DAG)) 19886 return V; 19887 19888 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 19889 // nodes often generate nop CONCAT_VECTOR nodes. Scan the CONCAT_VECTOR 19890 // operands and look for a CONCAT operations that place the incoming vectors 19891 // at the exact same location. 19892 // 19893 // For scalable vectors, EXTRACT_SUBVECTOR indexes are implicitly scaled. 19894 SDValue SingleSource = SDValue(); 19895 unsigned PartNumElem = 19896 N->getOperand(0).getValueType().getVectorMinNumElements(); 19897 19898 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 19899 SDValue Op = N->getOperand(i); 19900 19901 if (Op.isUndef()) 19902 continue; 19903 19904 // Check if this is the identity extract: 19905 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 19906 return SDValue(); 19907 19908 // Find the single incoming vector for the extract_subvector. 19909 if (SingleSource.getNode()) { 19910 if (Op.getOperand(0) != SingleSource) 19911 return SDValue(); 19912 } else { 19913 SingleSource = Op.getOperand(0); 19914 19915 // Check the source type is the same as the type of the result. 19916 // If not, this concat may extend the vector, so we can not 19917 // optimize it away. 19918 if (SingleSource.getValueType() != N->getValueType(0)) 19919 return SDValue(); 19920 } 19921 19922 // Check that we are reading from the identity index. 19923 unsigned IdentityIndex = i * PartNumElem; 19924 if (Op.getConstantOperandAPInt(1) != IdentityIndex) 19925 return SDValue(); 19926 } 19927 19928 if (SingleSource.getNode()) 19929 return SingleSource; 19930 19931 return SDValue(); 19932 } 19933 19934 // Helper that peeks through INSERT_SUBVECTOR/CONCAT_VECTORS to find 19935 // if the subvector can be sourced for free. 19936 static SDValue getSubVectorSrc(SDValue V, SDValue Index, EVT SubVT) { 19937 if (V.getOpcode() == ISD::INSERT_SUBVECTOR && 19938 V.getOperand(1).getValueType() == SubVT && V.getOperand(2) == Index) { 19939 return V.getOperand(1); 19940 } 19941 auto *IndexC = dyn_cast<ConstantSDNode>(Index); 19942 if (IndexC && V.getOpcode() == ISD::CONCAT_VECTORS && 19943 V.getOperand(0).getValueType() == SubVT && 19944 (IndexC->getZExtValue() % SubVT.getVectorMinNumElements()) == 0) { 19945 uint64_t SubIdx = IndexC->getZExtValue() / SubVT.getVectorMinNumElements(); 19946 return V.getOperand(SubIdx); 19947 } 19948 return SDValue(); 19949 } 19950 19951 static SDValue narrowInsertExtractVectorBinOp(SDNode *Extract, 19952 SelectionDAG &DAG, 19953 bool LegalOperations) { 19954 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 19955 SDValue BinOp = Extract->getOperand(0); 19956 unsigned BinOpcode = BinOp.getOpcode(); 19957 if (!TLI.isBinOp(BinOpcode) || BinOp.getNode()->getNumValues() != 1) 19958 return SDValue(); 19959 19960 EVT VecVT = BinOp.getValueType(); 19961 SDValue Bop0 = BinOp.getOperand(0), Bop1 = BinOp.getOperand(1); 19962 if (VecVT != Bop0.getValueType() || VecVT != Bop1.getValueType()) 19963 return SDValue(); 19964 19965 SDValue Index = Extract->getOperand(1); 19966 EVT SubVT = Extract->getValueType(0); 19967 if (!TLI.isOperationLegalOrCustom(BinOpcode, SubVT, LegalOperations)) 19968 return SDValue(); 19969 19970 SDValue Sub0 = getSubVectorSrc(Bop0, Index, SubVT); 19971 SDValue Sub1 = getSubVectorSrc(Bop1, Index, SubVT); 19972 19973 // TODO: We could handle the case where only 1 operand is being inserted by 19974 // creating an extract of the other operand, but that requires checking 19975 // number of uses and/or costs. 19976 if (!Sub0 || !Sub1) 19977 return SDValue(); 19978 19979 // We are inserting both operands of the wide binop only to extract back 19980 // to the narrow vector size. Eliminate all of the insert/extract: 19981 // ext (binop (ins ?, X, Index), (ins ?, Y, Index)), Index --> binop X, Y 19982 return DAG.getNode(BinOpcode, SDLoc(Extract), SubVT, Sub0, Sub1, 19983 BinOp->getFlags()); 19984 } 19985 19986 /// If we are extracting a subvector produced by a wide binary operator try 19987 /// to use a narrow binary operator and/or avoid concatenation and extraction. 19988 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG, 19989 bool LegalOperations) { 19990 // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share 19991 // some of these bailouts with other transforms. 19992 19993 if (SDValue V = narrowInsertExtractVectorBinOp(Extract, DAG, LegalOperations)) 19994 return V; 19995 19996 // The extract index must be a constant, so we can map it to a concat operand. 19997 auto *ExtractIndexC = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); 19998 if (!ExtractIndexC) 19999 return SDValue(); 20000 20001 // We are looking for an optionally bitcasted wide vector binary operator 20002 // feeding an extract subvector. 20003 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 20004 SDValue BinOp = peekThroughBitcasts(Extract->getOperand(0)); 20005 unsigned BOpcode = BinOp.getOpcode(); 20006 if (!TLI.isBinOp(BOpcode) || BinOp.getNode()->getNumValues() != 1) 20007 return SDValue(); 20008 20009 // Exclude the fake form of fneg (fsub -0.0, x) because that is likely to be 20010 // reduced to the unary fneg when it is visited, and we probably want to deal 20011 // with fneg in a target-specific way. 20012 if (BOpcode == ISD::FSUB) { 20013 auto *C = isConstOrConstSplatFP(BinOp.getOperand(0), /*AllowUndefs*/ true); 20014 if (C && C->getValueAPF().isNegZero()) 20015 return SDValue(); 20016 } 20017 20018 // The binop must be a vector type, so we can extract some fraction of it. 20019 EVT WideBVT = BinOp.getValueType(); 20020 // The optimisations below currently assume we are dealing with fixed length 20021 // vectors. It is possible to add support for scalable vectors, but at the 20022 // moment we've done no analysis to prove whether they are profitable or not. 20023 if (!WideBVT.isFixedLengthVector()) 20024 return SDValue(); 20025 20026 EVT VT = Extract->getValueType(0); 20027 unsigned ExtractIndex = ExtractIndexC->getZExtValue(); 20028 assert(ExtractIndex % VT.getVectorNumElements() == 0 && 20029 "Extract index is not a multiple of the vector length."); 20030 20031 // Bail out if this is not a proper multiple width extraction. 20032 unsigned WideWidth = WideBVT.getSizeInBits(); 20033 unsigned NarrowWidth = VT.getSizeInBits(); 20034 if (WideWidth % NarrowWidth != 0) 20035 return SDValue(); 20036 20037 // Bail out if we are extracting a fraction of a single operation. This can 20038 // occur because we potentially looked through a bitcast of the binop. 20039 unsigned NarrowingRatio = WideWidth / NarrowWidth; 20040 unsigned WideNumElts = WideBVT.getVectorNumElements(); 20041 if (WideNumElts % NarrowingRatio != 0) 20042 return SDValue(); 20043 20044 // Bail out if the target does not support a narrower version of the binop. 20045 EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(), 20046 WideNumElts / NarrowingRatio); 20047 if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT)) 20048 return SDValue(); 20049 20050 // If extraction is cheap, we don't need to look at the binop operands 20051 // for concat ops. The narrow binop alone makes this transform profitable. 20052 // We can't just reuse the original extract index operand because we may have 20053 // bitcasted. 20054 unsigned ConcatOpNum = ExtractIndex / VT.getVectorNumElements(); 20055 unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements(); 20056 if (TLI.isExtractSubvectorCheap(NarrowBVT, WideBVT, ExtBOIdx) && 20057 BinOp.hasOneUse() && Extract->getOperand(0)->hasOneUse()) { 20058 // extract (binop B0, B1), N --> binop (extract B0, N), (extract B1, N) 20059 SDLoc DL(Extract); 20060 SDValue NewExtIndex = DAG.getVectorIdxConstant(ExtBOIdx, DL); 20061 SDValue X = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 20062 BinOp.getOperand(0), NewExtIndex); 20063 SDValue Y = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 20064 BinOp.getOperand(1), NewExtIndex); 20065 SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y, 20066 BinOp.getNode()->getFlags()); 20067 return DAG.getBitcast(VT, NarrowBinOp); 20068 } 20069 20070 // Only handle the case where we are doubling and then halving. A larger ratio 20071 // may require more than two narrow binops to replace the wide binop. 20072 if (NarrowingRatio != 2) 20073 return SDValue(); 20074 20075 // TODO: The motivating case for this transform is an x86 AVX1 target. That 20076 // target has temptingly almost legal versions of bitwise logic ops in 256-bit 20077 // flavors, but no other 256-bit integer support. This could be extended to 20078 // handle any binop, but that may require fixing/adding other folds to avoid 20079 // codegen regressions. 20080 if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR) 20081 return SDValue(); 20082 20083 // We need at least one concatenation operation of a binop operand to make 20084 // this transform worthwhile. The concat must double the input vector sizes. 20085 auto GetSubVector = [ConcatOpNum](SDValue V) -> SDValue { 20086 if (V.getOpcode() == ISD::CONCAT_VECTORS && V.getNumOperands() == 2) 20087 return V.getOperand(ConcatOpNum); 20088 return SDValue(); 20089 }; 20090 SDValue SubVecL = GetSubVector(peekThroughBitcasts(BinOp.getOperand(0))); 20091 SDValue SubVecR = GetSubVector(peekThroughBitcasts(BinOp.getOperand(1))); 20092 20093 if (SubVecL || SubVecR) { 20094 // If a binop operand was not the result of a concat, we must extract a 20095 // half-sized operand for our new narrow binop: 20096 // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN 20097 // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, IndexC) 20098 // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, IndexC), YN 20099 SDLoc DL(Extract); 20100 SDValue IndexC = DAG.getVectorIdxConstant(ExtBOIdx, DL); 20101 SDValue X = SubVecL ? DAG.getBitcast(NarrowBVT, SubVecL) 20102 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 20103 BinOp.getOperand(0), IndexC); 20104 20105 SDValue Y = SubVecR ? DAG.getBitcast(NarrowBVT, SubVecR) 20106 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 20107 BinOp.getOperand(1), IndexC); 20108 20109 SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y); 20110 return DAG.getBitcast(VT, NarrowBinOp); 20111 } 20112 20113 return SDValue(); 20114 } 20115 20116 /// If we are extracting a subvector from a wide vector load, convert to a 20117 /// narrow load to eliminate the extraction: 20118 /// (extract_subvector (load wide vector)) --> (load narrow vector) 20119 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) { 20120 // TODO: Add support for big-endian. The offset calculation must be adjusted. 20121 if (DAG.getDataLayout().isBigEndian()) 20122 return SDValue(); 20123 20124 auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0)); 20125 auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); 20126 if (!Ld || Ld->getExtensionType() || !Ld->isSimple() || 20127 !ExtIdx) 20128 return SDValue(); 20129 20130 // Allow targets to opt-out. 20131 EVT VT = Extract->getValueType(0); 20132 20133 // We can only create byte sized loads. 20134 if (!VT.isByteSized()) 20135 return SDValue(); 20136 20137 unsigned Index = ExtIdx->getZExtValue(); 20138 unsigned NumElts = VT.getVectorMinNumElements(); 20139 20140 // The definition of EXTRACT_SUBVECTOR states that the index must be a 20141 // multiple of the minimum number of elements in the result type. 20142 assert(Index % NumElts == 0 && "The extract subvector index is not a " 20143 "multiple of the result's element count"); 20144 20145 // It's fine to use TypeSize here as we know the offset will not be negative. 20146 TypeSize Offset = VT.getStoreSize() * (Index / NumElts); 20147 20148 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 20149 if (!TLI.shouldReduceLoadWidth(Ld, Ld->getExtensionType(), VT)) 20150 return SDValue(); 20151 20152 // The narrow load will be offset from the base address of the old load if 20153 // we are extracting from something besides index 0 (little-endian). 20154 SDLoc DL(Extract); 20155 20156 // TODO: Use "BaseIndexOffset" to make this more effective. 20157 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), Offset, DL); 20158 20159 uint64_t StoreSize = MemoryLocation::getSizeOrUnknown(VT.getStoreSize()); 20160 MachineFunction &MF = DAG.getMachineFunction(); 20161 MachineMemOperand *MMO; 20162 if (Offset.isScalable()) { 20163 MachinePointerInfo MPI = 20164 MachinePointerInfo(Ld->getPointerInfo().getAddrSpace()); 20165 MMO = MF.getMachineMemOperand(Ld->getMemOperand(), MPI, StoreSize); 20166 } else 20167 MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset.getFixedSize(), 20168 StoreSize); 20169 20170 SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO); 20171 DAG.makeEquivalentMemoryOrdering(Ld, NewLd); 20172 return NewLd; 20173 } 20174 20175 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode *N) { 20176 EVT NVT = N->getValueType(0); 20177 SDValue V = N->getOperand(0); 20178 uint64_t ExtIdx = N->getConstantOperandVal(1); 20179 20180 // Extract from UNDEF is UNDEF. 20181 if (V.isUndef()) 20182 return DAG.getUNDEF(NVT); 20183 20184 if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT)) 20185 if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG)) 20186 return NarrowLoad; 20187 20188 // Combine an extract of an extract into a single extract_subvector. 20189 // ext (ext X, C), 0 --> ext X, C 20190 if (ExtIdx == 0 && V.getOpcode() == ISD::EXTRACT_SUBVECTOR && V.hasOneUse()) { 20191 if (TLI.isExtractSubvectorCheap(NVT, V.getOperand(0).getValueType(), 20192 V.getConstantOperandVal(1)) && 20193 TLI.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, NVT)) { 20194 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, V.getOperand(0), 20195 V.getOperand(1)); 20196 } 20197 } 20198 20199 // Try to move vector bitcast after extract_subv by scaling extraction index: 20200 // extract_subv (bitcast X), Index --> bitcast (extract_subv X, Index') 20201 if (V.getOpcode() == ISD::BITCAST && 20202 V.getOperand(0).getValueType().isVector() && 20203 (!LegalOperations || TLI.isOperationLegal(ISD::BITCAST, NVT))) { 20204 SDValue SrcOp = V.getOperand(0); 20205 EVT SrcVT = SrcOp.getValueType(); 20206 unsigned SrcNumElts = SrcVT.getVectorMinNumElements(); 20207 unsigned DestNumElts = V.getValueType().getVectorMinNumElements(); 20208 if ((SrcNumElts % DestNumElts) == 0) { 20209 unsigned SrcDestRatio = SrcNumElts / DestNumElts; 20210 ElementCount NewExtEC = NVT.getVectorElementCount() * SrcDestRatio; 20211 EVT NewExtVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getScalarType(), 20212 NewExtEC); 20213 if (TLI.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, NewExtVT)) { 20214 SDLoc DL(N); 20215 SDValue NewIndex = DAG.getVectorIdxConstant(ExtIdx * SrcDestRatio, DL); 20216 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewExtVT, 20217 V.getOperand(0), NewIndex); 20218 return DAG.getBitcast(NVT, NewExtract); 20219 } 20220 } 20221 if ((DestNumElts % SrcNumElts) == 0) { 20222 unsigned DestSrcRatio = DestNumElts / SrcNumElts; 20223 if (NVT.getVectorElementCount().isKnownMultipleOf(DestSrcRatio)) { 20224 ElementCount NewExtEC = 20225 NVT.getVectorElementCount().divideCoefficientBy(DestSrcRatio); 20226 EVT ScalarVT = SrcVT.getScalarType(); 20227 if ((ExtIdx % DestSrcRatio) == 0) { 20228 SDLoc DL(N); 20229 unsigned IndexValScaled = ExtIdx / DestSrcRatio; 20230 EVT NewExtVT = 20231 EVT::getVectorVT(*DAG.getContext(), ScalarVT, NewExtEC); 20232 if (TLI.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, NewExtVT)) { 20233 SDValue NewIndex = DAG.getVectorIdxConstant(IndexValScaled, DL); 20234 SDValue NewExtract = 20235 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewExtVT, 20236 V.getOperand(0), NewIndex); 20237 return DAG.getBitcast(NVT, NewExtract); 20238 } 20239 if (NewExtEC.isScalar() && 20240 TLI.isOperationLegalOrCustom(ISD::EXTRACT_VECTOR_ELT, ScalarVT)) { 20241 SDValue NewIndex = DAG.getVectorIdxConstant(IndexValScaled, DL); 20242 SDValue NewExtract = 20243 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, 20244 V.getOperand(0), NewIndex); 20245 return DAG.getBitcast(NVT, NewExtract); 20246 } 20247 } 20248 } 20249 } 20250 } 20251 20252 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 20253 unsigned ExtNumElts = NVT.getVectorMinNumElements(); 20254 EVT ConcatSrcVT = V.getOperand(0).getValueType(); 20255 assert(ConcatSrcVT.getVectorElementType() == NVT.getVectorElementType() && 20256 "Concat and extract subvector do not change element type"); 20257 assert((ExtIdx % ExtNumElts) == 0 && 20258 "Extract index is not a multiple of the input vector length."); 20259 20260 unsigned ConcatSrcNumElts = ConcatSrcVT.getVectorMinNumElements(); 20261 unsigned ConcatOpIdx = ExtIdx / ConcatSrcNumElts; 20262 20263 // If the concatenated source types match this extract, it's a direct 20264 // simplification: 20265 // extract_subvec (concat V1, V2, ...), i --> Vi 20266 if (ConcatSrcNumElts == ExtNumElts) 20267 return V.getOperand(ConcatOpIdx); 20268 20269 // If the concatenated source vectors are a multiple length of this extract, 20270 // then extract a fraction of one of those source vectors directly from a 20271 // concat operand. Example: 20272 // v2i8 extract_subvec (v16i8 concat (v8i8 X), (v8i8 Y), 14 --> 20273 // v2i8 extract_subvec v8i8 Y, 6 20274 if (NVT.isFixedLengthVector() && ConcatSrcNumElts % ExtNumElts == 0) { 20275 SDLoc DL(N); 20276 unsigned NewExtIdx = ExtIdx - ConcatOpIdx * ConcatSrcNumElts; 20277 assert(NewExtIdx + ExtNumElts <= ConcatSrcNumElts && 20278 "Trying to extract from >1 concat operand?"); 20279 assert(NewExtIdx % ExtNumElts == 0 && 20280 "Extract index is not a multiple of the input vector length."); 20281 SDValue NewIndexC = DAG.getVectorIdxConstant(NewExtIdx, DL); 20282 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NVT, 20283 V.getOperand(ConcatOpIdx), NewIndexC); 20284 } 20285 } 20286 20287 V = peekThroughBitcasts(V); 20288 20289 // If the input is a build vector. Try to make a smaller build vector. 20290 if (V.getOpcode() == ISD::BUILD_VECTOR) { 20291 EVT InVT = V.getValueType(); 20292 unsigned ExtractSize = NVT.getSizeInBits(); 20293 unsigned EltSize = InVT.getScalarSizeInBits(); 20294 // Only do this if we won't split any elements. 20295 if (ExtractSize % EltSize == 0) { 20296 unsigned NumElems = ExtractSize / EltSize; 20297 EVT EltVT = InVT.getVectorElementType(); 20298 EVT ExtractVT = 20299 NumElems == 1 ? EltVT 20300 : EVT::getVectorVT(*DAG.getContext(), EltVT, NumElems); 20301 if ((Level < AfterLegalizeDAG || 20302 (NumElems == 1 || 20303 TLI.isOperationLegal(ISD::BUILD_VECTOR, ExtractVT))) && 20304 (!LegalTypes || TLI.isTypeLegal(ExtractVT))) { 20305 unsigned IdxVal = (ExtIdx * NVT.getScalarSizeInBits()) / EltSize; 20306 20307 if (NumElems == 1) { 20308 SDValue Src = V->getOperand(IdxVal); 20309 if (EltVT != Src.getValueType()) 20310 Src = DAG.getNode(ISD::TRUNCATE, SDLoc(N), InVT, Src); 20311 return DAG.getBitcast(NVT, Src); 20312 } 20313 20314 // Extract the pieces from the original build_vector. 20315 SDValue BuildVec = DAG.getBuildVector(ExtractVT, SDLoc(N), 20316 V->ops().slice(IdxVal, NumElems)); 20317 return DAG.getBitcast(NVT, BuildVec); 20318 } 20319 } 20320 } 20321 20322 if (V.getOpcode() == ISD::INSERT_SUBVECTOR) { 20323 // Handle only simple case where vector being inserted and vector 20324 // being extracted are of same size. 20325 EVT SmallVT = V.getOperand(1).getValueType(); 20326 if (!NVT.bitsEq(SmallVT)) 20327 return SDValue(); 20328 20329 // Combine: 20330 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 20331 // Into: 20332 // indices are equal or bit offsets are equal => V1 20333 // otherwise => (extract_subvec V1, ExtIdx) 20334 uint64_t InsIdx = V.getConstantOperandVal(2); 20335 if (InsIdx * SmallVT.getScalarSizeInBits() == 20336 ExtIdx * NVT.getScalarSizeInBits()) 20337 return DAG.getBitcast(NVT, V.getOperand(1)); 20338 return DAG.getNode( 20339 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, 20340 DAG.getBitcast(N->getOperand(0).getValueType(), V.getOperand(0)), 20341 N->getOperand(1)); 20342 } 20343 20344 if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG, LegalOperations)) 20345 return NarrowBOp; 20346 20347 if (SimplifyDemandedVectorElts(SDValue(N, 0))) 20348 return SDValue(N, 0); 20349 20350 return SDValue(); 20351 } 20352 20353 /// Try to convert a wide shuffle of concatenated vectors into 2 narrow shuffles 20354 /// followed by concatenation. Narrow vector ops may have better performance 20355 /// than wide ops, and this can unlock further narrowing of other vector ops. 20356 /// Targets can invert this transform later if it is not profitable. 20357 static SDValue foldShuffleOfConcatUndefs(ShuffleVectorSDNode *Shuf, 20358 SelectionDAG &DAG) { 20359 SDValue N0 = Shuf->getOperand(0), N1 = Shuf->getOperand(1); 20360 if (N0.getOpcode() != ISD::CONCAT_VECTORS || N0.getNumOperands() != 2 || 20361 N1.getOpcode() != ISD::CONCAT_VECTORS || N1.getNumOperands() != 2 || 20362 !N0.getOperand(1).isUndef() || !N1.getOperand(1).isUndef()) 20363 return SDValue(); 20364 20365 // Split the wide shuffle mask into halves. Any mask element that is accessing 20366 // operand 1 is offset down to account for narrowing of the vectors. 20367 ArrayRef<int> Mask = Shuf->getMask(); 20368 EVT VT = Shuf->getValueType(0); 20369 unsigned NumElts = VT.getVectorNumElements(); 20370 unsigned HalfNumElts = NumElts / 2; 20371 SmallVector<int, 16> Mask0(HalfNumElts, -1); 20372 SmallVector<int, 16> Mask1(HalfNumElts, -1); 20373 for (unsigned i = 0; i != NumElts; ++i) { 20374 if (Mask[i] == -1) 20375 continue; 20376 int M = Mask[i] < (int)NumElts ? Mask[i] : Mask[i] - (int)HalfNumElts; 20377 if (i < HalfNumElts) 20378 Mask0[i] = M; 20379 else 20380 Mask1[i - HalfNumElts] = M; 20381 } 20382 20383 // Ask the target if this is a valid transform. 20384 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 20385 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 20386 HalfNumElts); 20387 if (!TLI.isShuffleMaskLegal(Mask0, HalfVT) || 20388 !TLI.isShuffleMaskLegal(Mask1, HalfVT)) 20389 return SDValue(); 20390 20391 // shuffle (concat X, undef), (concat Y, undef), Mask --> 20392 // concat (shuffle X, Y, Mask0), (shuffle X, Y, Mask1) 20393 SDValue X = N0.getOperand(0), Y = N1.getOperand(0); 20394 SDLoc DL(Shuf); 20395 SDValue Shuf0 = DAG.getVectorShuffle(HalfVT, DL, X, Y, Mask0); 20396 SDValue Shuf1 = DAG.getVectorShuffle(HalfVT, DL, X, Y, Mask1); 20397 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Shuf0, Shuf1); 20398 } 20399 20400 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 20401 // or turn a shuffle of a single concat into simpler shuffle then concat. 20402 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 20403 EVT VT = N->getValueType(0); 20404 unsigned NumElts = VT.getVectorNumElements(); 20405 20406 SDValue N0 = N->getOperand(0); 20407 SDValue N1 = N->getOperand(1); 20408 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 20409 ArrayRef<int> Mask = SVN->getMask(); 20410 20411 SmallVector<SDValue, 4> Ops; 20412 EVT ConcatVT = N0.getOperand(0).getValueType(); 20413 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 20414 unsigned NumConcats = NumElts / NumElemsPerConcat; 20415 20416 auto IsUndefMaskElt = [](int i) { return i == -1; }; 20417 20418 // Special case: shuffle(concat(A,B)) can be more efficiently represented 20419 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 20420 // half vector elements. 20421 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 20422 llvm::all_of(Mask.slice(NumElemsPerConcat, NumElemsPerConcat), 20423 IsUndefMaskElt)) { 20424 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), 20425 N0.getOperand(1), 20426 Mask.slice(0, NumElemsPerConcat)); 20427 N1 = DAG.getUNDEF(ConcatVT); 20428 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 20429 } 20430 20431 // Look at every vector that's inserted. We're looking for exact 20432 // subvector-sized copies from a concatenated vector 20433 for (unsigned I = 0; I != NumConcats; ++I) { 20434 unsigned Begin = I * NumElemsPerConcat; 20435 ArrayRef<int> SubMask = Mask.slice(Begin, NumElemsPerConcat); 20436 20437 // Make sure we're dealing with a copy. 20438 if (llvm::all_of(SubMask, IsUndefMaskElt)) { 20439 Ops.push_back(DAG.getUNDEF(ConcatVT)); 20440 continue; 20441 } 20442 20443 int OpIdx = -1; 20444 for (int i = 0; i != (int)NumElemsPerConcat; ++i) { 20445 if (IsUndefMaskElt(SubMask[i])) 20446 continue; 20447 if ((SubMask[i] % (int)NumElemsPerConcat) != i) 20448 return SDValue(); 20449 int EltOpIdx = SubMask[i] / NumElemsPerConcat; 20450 if (0 <= OpIdx && EltOpIdx != OpIdx) 20451 return SDValue(); 20452 OpIdx = EltOpIdx; 20453 } 20454 assert(0 <= OpIdx && "Unknown concat_vectors op"); 20455 20456 if (OpIdx < (int)N0.getNumOperands()) 20457 Ops.push_back(N0.getOperand(OpIdx)); 20458 else 20459 Ops.push_back(N1.getOperand(OpIdx - N0.getNumOperands())); 20460 } 20461 20462 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 20463 } 20464 20465 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 20466 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 20467 // 20468 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always 20469 // a simplification in some sense, but it isn't appropriate in general: some 20470 // BUILD_VECTORs are substantially cheaper than others. The general case 20471 // of a BUILD_VECTOR requires inserting each element individually (or 20472 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of 20473 // all constants is a single constant pool load. A BUILD_VECTOR where each 20474 // element is identical is a splat. A BUILD_VECTOR where most of the operands 20475 // are undef lowers to a small number of element insertions. 20476 // 20477 // To deal with this, we currently use a bunch of mostly arbitrary heuristics. 20478 // We don't fold shuffles where one side is a non-zero constant, and we don't 20479 // fold shuffles if the resulting (non-splat) BUILD_VECTOR would have duplicate 20480 // non-constant operands. This seems to work out reasonably well in practice. 20481 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN, 20482 SelectionDAG &DAG, 20483 const TargetLowering &TLI) { 20484 EVT VT = SVN->getValueType(0); 20485 unsigned NumElts = VT.getVectorNumElements(); 20486 SDValue N0 = SVN->getOperand(0); 20487 SDValue N1 = SVN->getOperand(1); 20488 20489 if (!N0->hasOneUse()) 20490 return SDValue(); 20491 20492 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as 20493 // discussed above. 20494 if (!N1.isUndef()) { 20495 if (!N1->hasOneUse()) 20496 return SDValue(); 20497 20498 bool N0AnyConst = isAnyConstantBuildVector(N0); 20499 bool N1AnyConst = isAnyConstantBuildVector(N1); 20500 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode())) 20501 return SDValue(); 20502 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode())) 20503 return SDValue(); 20504 } 20505 20506 // If both inputs are splats of the same value then we can safely merge this 20507 // to a single BUILD_VECTOR with undef elements based on the shuffle mask. 20508 bool IsSplat = false; 20509 auto *BV0 = dyn_cast<BuildVectorSDNode>(N0); 20510 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 20511 if (BV0 && BV1) 20512 if (SDValue Splat0 = BV0->getSplatValue()) 20513 IsSplat = (Splat0 == BV1->getSplatValue()); 20514 20515 SmallVector<SDValue, 8> Ops; 20516 SmallSet<SDValue, 16> DuplicateOps; 20517 for (int M : SVN->getMask()) { 20518 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 20519 if (M >= 0) { 20520 int Idx = M < (int)NumElts ? M : M - NumElts; 20521 SDValue &S = (M < (int)NumElts ? N0 : N1); 20522 if (S.getOpcode() == ISD::BUILD_VECTOR) { 20523 Op = S.getOperand(Idx); 20524 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) { 20525 SDValue Op0 = S.getOperand(0); 20526 Op = Idx == 0 ? Op0 : DAG.getUNDEF(Op0.getValueType()); 20527 } else { 20528 // Operand can't be combined - bail out. 20529 return SDValue(); 20530 } 20531 } 20532 20533 // Don't duplicate a non-constant BUILD_VECTOR operand unless we're 20534 // generating a splat; semantically, this is fine, but it's likely to 20535 // generate low-quality code if the target can't reconstruct an appropriate 20536 // shuffle. 20537 if (!Op.isUndef() && !isIntOrFPConstant(Op)) 20538 if (!IsSplat && !DuplicateOps.insert(Op).second) 20539 return SDValue(); 20540 20541 Ops.push_back(Op); 20542 } 20543 20544 // BUILD_VECTOR requires all inputs to be of the same type, find the 20545 // maximum type and extend them all. 20546 EVT SVT = VT.getScalarType(); 20547 if (SVT.isInteger()) 20548 for (SDValue &Op : Ops) 20549 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 20550 if (SVT != VT.getScalarType()) 20551 for (SDValue &Op : Ops) 20552 Op = TLI.isZExtFree(Op.getValueType(), SVT) 20553 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT) 20554 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT); 20555 return DAG.getBuildVector(VT, SDLoc(SVN), Ops); 20556 } 20557 20558 // Match shuffles that can be converted to any_vector_extend_in_reg. 20559 // This is often generated during legalization. 20560 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src)) 20561 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case. 20562 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN, 20563 SelectionDAG &DAG, 20564 const TargetLowering &TLI, 20565 bool LegalOperations) { 20566 EVT VT = SVN->getValueType(0); 20567 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 20568 20569 // TODO Add support for big-endian when we have a test case. 20570 if (!VT.isInteger() || IsBigEndian) 20571 return SDValue(); 20572 20573 unsigned NumElts = VT.getVectorNumElements(); 20574 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 20575 ArrayRef<int> Mask = SVN->getMask(); 20576 SDValue N0 = SVN->getOperand(0); 20577 20578 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32)) 20579 auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) { 20580 for (unsigned i = 0; i != NumElts; ++i) { 20581 if (Mask[i] < 0) 20582 continue; 20583 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale)) 20584 continue; 20585 return false; 20586 } 20587 return true; 20588 }; 20589 20590 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for 20591 // power-of-2 extensions as they are the most likely. 20592 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) { 20593 // Check for non power of 2 vector sizes 20594 if (NumElts % Scale != 0) 20595 continue; 20596 if (!isAnyExtend(Scale)) 20597 continue; 20598 20599 EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale); 20600 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale); 20601 // Never create an illegal type. Only create unsupported operations if we 20602 // are pre-legalization. 20603 if (TLI.isTypeLegal(OutVT)) 20604 if (!LegalOperations || 20605 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT)) 20606 return DAG.getBitcast(VT, 20607 DAG.getNode(ISD::ANY_EXTEND_VECTOR_INREG, 20608 SDLoc(SVN), OutVT, N0)); 20609 } 20610 20611 return SDValue(); 20612 } 20613 20614 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of 20615 // each source element of a large type into the lowest elements of a smaller 20616 // destination type. This is often generated during legalization. 20617 // If the source node itself was a '*_extend_vector_inreg' node then we should 20618 // then be able to remove it. 20619 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, 20620 SelectionDAG &DAG) { 20621 EVT VT = SVN->getValueType(0); 20622 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 20623 20624 // TODO Add support for big-endian when we have a test case. 20625 if (!VT.isInteger() || IsBigEndian) 20626 return SDValue(); 20627 20628 SDValue N0 = peekThroughBitcasts(SVN->getOperand(0)); 20629 20630 unsigned Opcode = N0.getOpcode(); 20631 if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG && 20632 Opcode != ISD::SIGN_EXTEND_VECTOR_INREG && 20633 Opcode != ISD::ZERO_EXTEND_VECTOR_INREG) 20634 return SDValue(); 20635 20636 SDValue N00 = N0.getOperand(0); 20637 ArrayRef<int> Mask = SVN->getMask(); 20638 unsigned NumElts = VT.getVectorNumElements(); 20639 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 20640 unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits(); 20641 unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits(); 20642 20643 if (ExtDstSizeInBits % ExtSrcSizeInBits != 0) 20644 return SDValue(); 20645 unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits; 20646 20647 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1> 20648 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1> 20649 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1> 20650 auto isTruncate = [&Mask, &NumElts](unsigned Scale) { 20651 for (unsigned i = 0; i != NumElts; ++i) { 20652 if (Mask[i] < 0) 20653 continue; 20654 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale)) 20655 continue; 20656 return false; 20657 } 20658 return true; 20659 }; 20660 20661 // At the moment we just handle the case where we've truncated back to the 20662 // same size as before the extension. 20663 // TODO: handle more extension/truncation cases as cases arise. 20664 if (EltSizeInBits != ExtSrcSizeInBits) 20665 return SDValue(); 20666 20667 // We can remove *extend_vector_inreg only if the truncation happens at 20668 // the same scale as the extension. 20669 if (isTruncate(ExtScale)) 20670 return DAG.getBitcast(VT, N00); 20671 20672 return SDValue(); 20673 } 20674 20675 // Combine shuffles of splat-shuffles of the form: 20676 // shuffle (shuffle V, undef, splat-mask), undef, M 20677 // If splat-mask contains undef elements, we need to be careful about 20678 // introducing undef's in the folded mask which are not the result of composing 20679 // the masks of the shuffles. 20680 static SDValue combineShuffleOfSplatVal(ShuffleVectorSDNode *Shuf, 20681 SelectionDAG &DAG) { 20682 if (!Shuf->getOperand(1).isUndef()) 20683 return SDValue(); 20684 auto *Splat = dyn_cast<ShuffleVectorSDNode>(Shuf->getOperand(0)); 20685 if (!Splat || !Splat->isSplat()) 20686 return SDValue(); 20687 20688 ArrayRef<int> ShufMask = Shuf->getMask(); 20689 ArrayRef<int> SplatMask = Splat->getMask(); 20690 assert(ShufMask.size() == SplatMask.size() && "Mask length mismatch"); 20691 20692 // Prefer simplifying to the splat-shuffle, if possible. This is legal if 20693 // every undef mask element in the splat-shuffle has a corresponding undef 20694 // element in the user-shuffle's mask or if the composition of mask elements 20695 // would result in undef. 20696 // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask): 20697 // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u] 20698 // In this case it is not legal to simplify to the splat-shuffle because we 20699 // may be exposing the users of the shuffle an undef element at index 1 20700 // which was not there before the combine. 20701 // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u] 20702 // In this case the composition of masks yields SplatMask, so it's ok to 20703 // simplify to the splat-shuffle. 20704 // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u] 20705 // In this case the composed mask includes all undef elements of SplatMask 20706 // and in addition sets element zero to undef. It is safe to simplify to 20707 // the splat-shuffle. 20708 auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask, 20709 ArrayRef<int> SplatMask) { 20710 for (unsigned i = 0, e = UserMask.size(); i != e; ++i) 20711 if (UserMask[i] != -1 && SplatMask[i] == -1 && 20712 SplatMask[UserMask[i]] != -1) 20713 return false; 20714 return true; 20715 }; 20716 if (CanSimplifyToExistingSplat(ShufMask, SplatMask)) 20717 return Shuf->getOperand(0); 20718 20719 // Create a new shuffle with a mask that is composed of the two shuffles' 20720 // masks. 20721 SmallVector<int, 32> NewMask; 20722 for (int Idx : ShufMask) 20723 NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]); 20724 20725 return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat), 20726 Splat->getOperand(0), Splat->getOperand(1), 20727 NewMask); 20728 } 20729 20730 /// Combine shuffle of shuffle of the form: 20731 /// shuf (shuf X, undef, InnerMask), undef, OuterMask --> splat X 20732 static SDValue formSplatFromShuffles(ShuffleVectorSDNode *OuterShuf, 20733 SelectionDAG &DAG) { 20734 if (!OuterShuf->getOperand(1).isUndef()) 20735 return SDValue(); 20736 auto *InnerShuf = dyn_cast<ShuffleVectorSDNode>(OuterShuf->getOperand(0)); 20737 if (!InnerShuf || !InnerShuf->getOperand(1).isUndef()) 20738 return SDValue(); 20739 20740 ArrayRef<int> OuterMask = OuterShuf->getMask(); 20741 ArrayRef<int> InnerMask = InnerShuf->getMask(); 20742 unsigned NumElts = OuterMask.size(); 20743 assert(NumElts == InnerMask.size() && "Mask length mismatch"); 20744 SmallVector<int, 32> CombinedMask(NumElts, -1); 20745 int SplatIndex = -1; 20746 for (unsigned i = 0; i != NumElts; ++i) { 20747 // Undef lanes remain undef. 20748 int OuterMaskElt = OuterMask[i]; 20749 if (OuterMaskElt == -1) 20750 continue; 20751 20752 // Peek through the shuffle masks to get the underlying source element. 20753 int InnerMaskElt = InnerMask[OuterMaskElt]; 20754 if (InnerMaskElt == -1) 20755 continue; 20756 20757 // Initialize the splatted element. 20758 if (SplatIndex == -1) 20759 SplatIndex = InnerMaskElt; 20760 20761 // Non-matching index - this is not a splat. 20762 if (SplatIndex != InnerMaskElt) 20763 return SDValue(); 20764 20765 CombinedMask[i] = InnerMaskElt; 20766 } 20767 assert((all_of(CombinedMask, [](int M) { return M == -1; }) || 20768 getSplatIndex(CombinedMask) != -1) && 20769 "Expected a splat mask"); 20770 20771 // TODO: The transform may be a win even if the mask is not legal. 20772 EVT VT = OuterShuf->getValueType(0); 20773 assert(VT == InnerShuf->getValueType(0) && "Expected matching shuffle types"); 20774 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(CombinedMask, VT)) 20775 return SDValue(); 20776 20777 return DAG.getVectorShuffle(VT, SDLoc(OuterShuf), InnerShuf->getOperand(0), 20778 InnerShuf->getOperand(1), CombinedMask); 20779 } 20780 20781 /// If the shuffle mask is taking exactly one element from the first vector 20782 /// operand and passing through all other elements from the second vector 20783 /// operand, return the index of the mask element that is choosing an element 20784 /// from the first operand. Otherwise, return -1. 20785 static int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef<int> Mask) { 20786 int MaskSize = Mask.size(); 20787 int EltFromOp0 = -1; 20788 // TODO: This does not match if there are undef elements in the shuffle mask. 20789 // Should we ignore undefs in the shuffle mask instead? The trade-off is 20790 // removing an instruction (a shuffle), but losing the knowledge that some 20791 // vector lanes are not needed. 20792 for (int i = 0; i != MaskSize; ++i) { 20793 if (Mask[i] >= 0 && Mask[i] < MaskSize) { 20794 // We're looking for a shuffle of exactly one element from operand 0. 20795 if (EltFromOp0 != -1) 20796 return -1; 20797 EltFromOp0 = i; 20798 } else if (Mask[i] != i + MaskSize) { 20799 // Nothing from operand 1 can change lanes. 20800 return -1; 20801 } 20802 } 20803 return EltFromOp0; 20804 } 20805 20806 /// If a shuffle inserts exactly one element from a source vector operand into 20807 /// another vector operand and we can access the specified element as a scalar, 20808 /// then we can eliminate the shuffle. 20809 static SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf, 20810 SelectionDAG &DAG) { 20811 // First, check if we are taking one element of a vector and shuffling that 20812 // element into another vector. 20813 ArrayRef<int> Mask = Shuf->getMask(); 20814 SmallVector<int, 16> CommutedMask(Mask.begin(), Mask.end()); 20815 SDValue Op0 = Shuf->getOperand(0); 20816 SDValue Op1 = Shuf->getOperand(1); 20817 int ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(Mask); 20818 if (ShufOp0Index == -1) { 20819 // Commute mask and check again. 20820 ShuffleVectorSDNode::commuteMask(CommutedMask); 20821 ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(CommutedMask); 20822 if (ShufOp0Index == -1) 20823 return SDValue(); 20824 // Commute operands to match the commuted shuffle mask. 20825 std::swap(Op0, Op1); 20826 Mask = CommutedMask; 20827 } 20828 20829 // The shuffle inserts exactly one element from operand 0 into operand 1. 20830 // Now see if we can access that element as a scalar via a real insert element 20831 // instruction. 20832 // TODO: We can try harder to locate the element as a scalar. Examples: it 20833 // could be an operand of SCALAR_TO_VECTOR, BUILD_VECTOR, or a constant. 20834 assert(Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() && 20835 "Shuffle mask value must be from operand 0"); 20836 if (Op0.getOpcode() != ISD::INSERT_VECTOR_ELT) 20837 return SDValue(); 20838 20839 auto *InsIndexC = dyn_cast<ConstantSDNode>(Op0.getOperand(2)); 20840 if (!InsIndexC || InsIndexC->getSExtValue() != Mask[ShufOp0Index]) 20841 return SDValue(); 20842 20843 // There's an existing insertelement with constant insertion index, so we 20844 // don't need to check the legality/profitability of a replacement operation 20845 // that differs at most in the constant value. The target should be able to 20846 // lower any of those in a similar way. If not, legalization will expand this 20847 // to a scalar-to-vector plus shuffle. 20848 // 20849 // Note that the shuffle may move the scalar from the position that the insert 20850 // element used. Therefore, our new insert element occurs at the shuffle's 20851 // mask index value, not the insert's index value. 20852 // shuffle (insertelt v1, x, C), v2, mask --> insertelt v2, x, C' 20853 SDValue NewInsIndex = DAG.getVectorIdxConstant(ShufOp0Index, SDLoc(Shuf)); 20854 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Shuf), Op0.getValueType(), 20855 Op1, Op0.getOperand(1), NewInsIndex); 20856 } 20857 20858 /// If we have a unary shuffle of a shuffle, see if it can be folded away 20859 /// completely. This has the potential to lose undef knowledge because the first 20860 /// shuffle may not have an undef mask element where the second one does. So 20861 /// only call this after doing simplifications based on demanded elements. 20862 static SDValue simplifyShuffleOfShuffle(ShuffleVectorSDNode *Shuf) { 20863 // shuf (shuf0 X, Y, Mask0), undef, Mask 20864 auto *Shuf0 = dyn_cast<ShuffleVectorSDNode>(Shuf->getOperand(0)); 20865 if (!Shuf0 || !Shuf->getOperand(1).isUndef()) 20866 return SDValue(); 20867 20868 ArrayRef<int> Mask = Shuf->getMask(); 20869 ArrayRef<int> Mask0 = Shuf0->getMask(); 20870 for (int i = 0, e = (int)Mask.size(); i != e; ++i) { 20871 // Ignore undef elements. 20872 if (Mask[i] == -1) 20873 continue; 20874 assert(Mask[i] >= 0 && Mask[i] < e && "Unexpected shuffle mask value"); 20875 20876 // Is the element of the shuffle operand chosen by this shuffle the same as 20877 // the element chosen by the shuffle operand itself? 20878 if (Mask0[Mask[i]] != Mask0[i]) 20879 return SDValue(); 20880 } 20881 // Every element of this shuffle is identical to the result of the previous 20882 // shuffle, so we can replace this value. 20883 return Shuf->getOperand(0); 20884 } 20885 20886 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 20887 EVT VT = N->getValueType(0); 20888 unsigned NumElts = VT.getVectorNumElements(); 20889 20890 SDValue N0 = N->getOperand(0); 20891 SDValue N1 = N->getOperand(1); 20892 20893 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 20894 20895 // Canonicalize shuffle undef, undef -> undef 20896 if (N0.isUndef() && N1.isUndef()) 20897 return DAG.getUNDEF(VT); 20898 20899 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 20900 20901 // Canonicalize shuffle v, v -> v, undef 20902 if (N0 == N1) { 20903 SmallVector<int, 8> NewMask; 20904 for (unsigned i = 0; i != NumElts; ++i) { 20905 int Idx = SVN->getMaskElt(i); 20906 if (Idx >= (int)NumElts) Idx -= NumElts; 20907 NewMask.push_back(Idx); 20908 } 20909 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask); 20910 } 20911 20912 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 20913 if (N0.isUndef()) 20914 return DAG.getCommutedVectorShuffle(*SVN); 20915 20916 // Remove references to rhs if it is undef 20917 if (N1.isUndef()) { 20918 bool Changed = false; 20919 SmallVector<int, 8> NewMask; 20920 for (unsigned i = 0; i != NumElts; ++i) { 20921 int Idx = SVN->getMaskElt(i); 20922 if (Idx >= (int)NumElts) { 20923 Idx = -1; 20924 Changed = true; 20925 } 20926 NewMask.push_back(Idx); 20927 } 20928 if (Changed) 20929 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask); 20930 } 20931 20932 if (SDValue InsElt = replaceShuffleOfInsert(SVN, DAG)) 20933 return InsElt; 20934 20935 // A shuffle of a single vector that is a splatted value can always be folded. 20936 if (SDValue V = combineShuffleOfSplatVal(SVN, DAG)) 20937 return V; 20938 20939 if (SDValue V = formSplatFromShuffles(SVN, DAG)) 20940 return V; 20941 20942 // If it is a splat, check if the argument vector is another splat or a 20943 // build_vector. 20944 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 20945 int SplatIndex = SVN->getSplatIndex(); 20946 if (N0.hasOneUse() && TLI.isExtractVecEltCheap(VT, SplatIndex) && 20947 TLI.isBinOp(N0.getOpcode()) && N0.getNode()->getNumValues() == 1) { 20948 // splat (vector_bo L, R), Index --> 20949 // splat (scalar_bo (extelt L, Index), (extelt R, Index)) 20950 SDValue L = N0.getOperand(0), R = N0.getOperand(1); 20951 SDLoc DL(N); 20952 EVT EltVT = VT.getScalarType(); 20953 SDValue Index = DAG.getVectorIdxConstant(SplatIndex, DL); 20954 SDValue ExtL = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, L, Index); 20955 SDValue ExtR = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, R, Index); 20956 SDValue NewBO = DAG.getNode(N0.getOpcode(), DL, EltVT, ExtL, ExtR, 20957 N0.getNode()->getFlags()); 20958 SDValue Insert = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, NewBO); 20959 SmallVector<int, 16> ZeroMask(VT.getVectorNumElements(), 0); 20960 return DAG.getVectorShuffle(VT, DL, Insert, DAG.getUNDEF(VT), ZeroMask); 20961 } 20962 20963 // If this is a bit convert that changes the element type of the vector but 20964 // not the number of vector elements, look through it. Be careful not to 20965 // look though conversions that change things like v4f32 to v2f64. 20966 SDNode *V = N0.getNode(); 20967 if (V->getOpcode() == ISD::BITCAST) { 20968 SDValue ConvInput = V->getOperand(0); 20969 if (ConvInput.getValueType().isVector() && 20970 ConvInput.getValueType().getVectorNumElements() == NumElts) 20971 V = ConvInput.getNode(); 20972 } 20973 20974 if (V->getOpcode() == ISD::BUILD_VECTOR) { 20975 assert(V->getNumOperands() == NumElts && 20976 "BUILD_VECTOR has wrong number of operands"); 20977 SDValue Base; 20978 bool AllSame = true; 20979 for (unsigned i = 0; i != NumElts; ++i) { 20980 if (!V->getOperand(i).isUndef()) { 20981 Base = V->getOperand(i); 20982 break; 20983 } 20984 } 20985 // Splat of <u, u, u, u>, return <u, u, u, u> 20986 if (!Base.getNode()) 20987 return N0; 20988 for (unsigned i = 0; i != NumElts; ++i) { 20989 if (V->getOperand(i) != Base) { 20990 AllSame = false; 20991 break; 20992 } 20993 } 20994 // Splat of <x, x, x, x>, return <x, x, x, x> 20995 if (AllSame) 20996 return N0; 20997 20998 // Canonicalize any other splat as a build_vector. 20999 SDValue Splatted = V->getOperand(SplatIndex); 21000 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 21001 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); 21002 21003 // We may have jumped through bitcasts, so the type of the 21004 // BUILD_VECTOR may not match the type of the shuffle. 21005 if (V->getValueType(0) != VT) 21006 NewBV = DAG.getBitcast(VT, NewBV); 21007 return NewBV; 21008 } 21009 } 21010 21011 // Simplify source operands based on shuffle mask. 21012 if (SimplifyDemandedVectorElts(SDValue(N, 0))) 21013 return SDValue(N, 0); 21014 21015 // This is intentionally placed after demanded elements simplification because 21016 // it could eliminate knowledge of undef elements created by this shuffle. 21017 if (SDValue ShufOp = simplifyShuffleOfShuffle(SVN)) 21018 return ShufOp; 21019 21020 // Match shuffles that can be converted to any_vector_extend_in_reg. 21021 if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations)) 21022 return V; 21023 21024 // Combine "truncate_vector_in_reg" style shuffles. 21025 if (SDValue V = combineTruncationShuffle(SVN, DAG)) 21026 return V; 21027 21028 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 21029 Level < AfterLegalizeVectorOps && 21030 (N1.isUndef() || 21031 (N1.getOpcode() == ISD::CONCAT_VECTORS && 21032 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 21033 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 21034 return V; 21035 } 21036 21037 // A shuffle of a concat of the same narrow vector can be reduced to use 21038 // only low-half elements of a concat with undef: 21039 // shuf (concat X, X), undef, Mask --> shuf (concat X, undef), undef, Mask' 21040 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N1.isUndef() && 21041 N0.getNumOperands() == 2 && 21042 N0.getOperand(0) == N0.getOperand(1)) { 21043 int HalfNumElts = (int)NumElts / 2; 21044 SmallVector<int, 8> NewMask; 21045 for (unsigned i = 0; i != NumElts; ++i) { 21046 int Idx = SVN->getMaskElt(i); 21047 if (Idx >= HalfNumElts) { 21048 assert(Idx < (int)NumElts && "Shuffle mask chooses undef op"); 21049 Idx -= HalfNumElts; 21050 } 21051 NewMask.push_back(Idx); 21052 } 21053 if (TLI.isShuffleMaskLegal(NewMask, VT)) { 21054 SDValue UndefVec = DAG.getUNDEF(N0.getOperand(0).getValueType()); 21055 SDValue NewCat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 21056 N0.getOperand(0), UndefVec); 21057 return DAG.getVectorShuffle(VT, SDLoc(N), NewCat, N1, NewMask); 21058 } 21059 } 21060 21061 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 21062 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 21063 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) 21064 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI)) 21065 return Res; 21066 21067 // If this shuffle only has a single input that is a bitcasted shuffle, 21068 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 21069 // back to their original types. 21070 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 21071 N1.isUndef() && Level < AfterLegalizeVectorOps && 21072 TLI.isTypeLegal(VT)) { 21073 21074 SDValue BC0 = peekThroughOneUseBitcasts(N0); 21075 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 21076 EVT SVT = VT.getScalarType(); 21077 EVT InnerVT = BC0->getValueType(0); 21078 EVT InnerSVT = InnerVT.getScalarType(); 21079 21080 // Determine which shuffle works with the smaller scalar type. 21081 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 21082 EVT ScaleSVT = ScaleVT.getScalarType(); 21083 21084 if (TLI.isTypeLegal(ScaleVT) && 21085 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 21086 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 21087 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 21088 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 21089 21090 // Scale the shuffle masks to the smaller scalar type. 21091 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 21092 SmallVector<int, 8> InnerMask; 21093 SmallVector<int, 8> OuterMask; 21094 narrowShuffleMaskElts(InnerScale, InnerSVN->getMask(), InnerMask); 21095 narrowShuffleMaskElts(OuterScale, SVN->getMask(), OuterMask); 21096 21097 // Merge the shuffle masks. 21098 SmallVector<int, 8> NewMask; 21099 for (int M : OuterMask) 21100 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 21101 21102 // Test for shuffle mask legality over both commutations. 21103 SDValue SV0 = BC0->getOperand(0); 21104 SDValue SV1 = BC0->getOperand(1); 21105 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 21106 if (!LegalMask) { 21107 std::swap(SV0, SV1); 21108 ShuffleVectorSDNode::commuteMask(NewMask); 21109 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 21110 } 21111 21112 if (LegalMask) { 21113 SV0 = DAG.getBitcast(ScaleVT, SV0); 21114 SV1 = DAG.getBitcast(ScaleVT, SV1); 21115 return DAG.getBitcast( 21116 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 21117 } 21118 } 21119 } 21120 } 21121 21122 // Compute the combined shuffle mask for a shuffle with SV0 as the first 21123 // operand, and SV1 as the second operand. 21124 // i.e. Merge SVN(OtherSVN, N1) -> shuffle(SV0, SV1, Mask) iff Commute = false 21125 // Merge SVN(N1, OtherSVN) -> shuffle(SV0, SV1, Mask') iff Commute = true 21126 auto MergeInnerShuffle = 21127 [NumElts, &VT](bool Commute, ShuffleVectorSDNode *SVN, 21128 ShuffleVectorSDNode *OtherSVN, SDValue N1, 21129 const TargetLowering &TLI, SDValue &SV0, SDValue &SV1, 21130 SmallVectorImpl<int> &Mask) -> bool { 21131 // Don't try to fold splats; they're likely to simplify somehow, or they 21132 // might be free. 21133 if (OtherSVN->isSplat()) 21134 return false; 21135 21136 SV0 = SV1 = SDValue(); 21137 Mask.clear(); 21138 21139 for (unsigned i = 0; i != NumElts; ++i) { 21140 int Idx = SVN->getMaskElt(i); 21141 if (Idx < 0) { 21142 // Propagate Undef. 21143 Mask.push_back(Idx); 21144 continue; 21145 } 21146 21147 if (Commute) 21148 Idx = (Idx < (int)NumElts) ? (Idx + NumElts) : (Idx - NumElts); 21149 21150 SDValue CurrentVec; 21151 if (Idx < (int)NumElts) { 21152 // This shuffle index refers to the inner shuffle N0. Lookup the inner 21153 // shuffle mask to identify which vector is actually referenced. 21154 Idx = OtherSVN->getMaskElt(Idx); 21155 if (Idx < 0) { 21156 // Propagate Undef. 21157 Mask.push_back(Idx); 21158 continue; 21159 } 21160 CurrentVec = (Idx < (int)NumElts) ? OtherSVN->getOperand(0) 21161 : OtherSVN->getOperand(1); 21162 } else { 21163 // This shuffle index references an element within N1. 21164 CurrentVec = N1; 21165 } 21166 21167 // Simple case where 'CurrentVec' is UNDEF. 21168 if (CurrentVec.isUndef()) { 21169 Mask.push_back(-1); 21170 continue; 21171 } 21172 21173 // Canonicalize the shuffle index. We don't know yet if CurrentVec 21174 // will be the first or second operand of the combined shuffle. 21175 Idx = Idx % NumElts; 21176 if (!SV0.getNode() || SV0 == CurrentVec) { 21177 // Ok. CurrentVec is the left hand side. 21178 // Update the mask accordingly. 21179 SV0 = CurrentVec; 21180 Mask.push_back(Idx); 21181 continue; 21182 } 21183 if (!SV1.getNode() || SV1 == CurrentVec) { 21184 // Ok. CurrentVec is the right hand side. 21185 // Update the mask accordingly. 21186 SV1 = CurrentVec; 21187 Mask.push_back(Idx + NumElts); 21188 continue; 21189 } 21190 21191 // Last chance - see if the vector is another shuffle and if it 21192 // uses one of the existing candidate shuffle ops. 21193 if (auto *CurrentSVN = dyn_cast<ShuffleVectorSDNode>(CurrentVec)) { 21194 int InnerIdx = CurrentSVN->getMaskElt(Idx); 21195 if (InnerIdx < 0) { 21196 Mask.push_back(-1); 21197 continue; 21198 } 21199 SDValue InnerVec = (InnerIdx < (int)NumElts) 21200 ? CurrentSVN->getOperand(0) 21201 : CurrentSVN->getOperand(1); 21202 if (InnerVec.isUndef()) { 21203 Mask.push_back(-1); 21204 continue; 21205 } 21206 InnerIdx %= NumElts; 21207 if (InnerVec == SV0) { 21208 Mask.push_back(InnerIdx); 21209 continue; 21210 } 21211 if (InnerVec == SV1) { 21212 Mask.push_back(InnerIdx + NumElts); 21213 continue; 21214 } 21215 } 21216 21217 // Bail out if we cannot convert the shuffle pair into a single shuffle. 21218 return false; 21219 } 21220 21221 if (llvm::all_of(Mask, [](int M) { return M < 0; })) 21222 return true; 21223 21224 // Avoid introducing shuffles with illegal mask. 21225 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 21226 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 21227 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 21228 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 21229 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 21230 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 21231 if (TLI.isShuffleMaskLegal(Mask, VT)) 21232 return true; 21233 21234 std::swap(SV0, SV1); 21235 ShuffleVectorSDNode::commuteMask(Mask); 21236 return TLI.isShuffleMaskLegal(Mask, VT); 21237 }; 21238 21239 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 21240 // Canonicalize shuffles according to rules: 21241 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 21242 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 21243 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 21244 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 21245 N0.getOpcode() != ISD::VECTOR_SHUFFLE) { 21246 // The incoming shuffle must be of the same type as the result of the 21247 // current shuffle. 21248 assert(N1->getOperand(0).getValueType() == VT && 21249 "Shuffle types don't match"); 21250 21251 SDValue SV0 = N1->getOperand(0); 21252 SDValue SV1 = N1->getOperand(1); 21253 bool HasSameOp0 = N0 == SV0; 21254 bool IsSV1Undef = SV1.isUndef(); 21255 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 21256 // Commute the operands of this shuffle so merging below will trigger. 21257 return DAG.getCommutedVectorShuffle(*SVN); 21258 } 21259 21260 // Canonicalize splat shuffles to the RHS to improve merging below. 21261 // shuffle(splat(A,u), shuffle(C,D)) -> shuffle'(shuffle(C,D), splat(A,u)) 21262 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && 21263 N1.getOpcode() == ISD::VECTOR_SHUFFLE && 21264 cast<ShuffleVectorSDNode>(N0)->isSplat() && 21265 !cast<ShuffleVectorSDNode>(N1)->isSplat()) { 21266 return DAG.getCommutedVectorShuffle(*SVN); 21267 } 21268 21269 // Try to fold according to rules: 21270 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 21271 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 21272 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 21273 // Don't try to fold shuffles with illegal type. 21274 // Only fold if this shuffle is the only user of the other shuffle. 21275 // Try matching shuffle(C,shuffle(A,B)) commutted patterns as well. 21276 for (int i = 0; i != 2; ++i) { 21277 if (N->getOperand(i).getOpcode() == ISD::VECTOR_SHUFFLE && 21278 N->isOnlyUserOf(N->getOperand(i).getNode())) { 21279 // The incoming shuffle must be of the same type as the result of the 21280 // current shuffle. 21281 auto *OtherSV = cast<ShuffleVectorSDNode>(N->getOperand(i)); 21282 assert(OtherSV->getOperand(0).getValueType() == VT && 21283 "Shuffle types don't match"); 21284 21285 SDValue SV0, SV1; 21286 SmallVector<int, 4> Mask; 21287 if (MergeInnerShuffle(i != 0, SVN, OtherSV, N->getOperand(1 - i), TLI, 21288 SV0, SV1, Mask)) { 21289 // Check if all indices in Mask are Undef. In case, propagate Undef. 21290 if (llvm::all_of(Mask, [](int M) { return M < 0; })) 21291 return DAG.getUNDEF(VT); 21292 21293 return DAG.getVectorShuffle(VT, SDLoc(N), 21294 SV0 ? SV0 : DAG.getUNDEF(VT), 21295 SV1 ? SV1 : DAG.getUNDEF(VT), Mask); 21296 } 21297 } 21298 } 21299 21300 // Merge shuffles through binops if we are able to merge it with at least 21301 // one other shuffles. 21302 // shuffle(bop(shuffle(x,y),shuffle(z,w)),undef) 21303 // shuffle(bop(shuffle(x,y),shuffle(z,w)),bop(shuffle(a,b),shuffle(c,d))) 21304 unsigned SrcOpcode = N0.getOpcode(); 21305 if (TLI.isBinOp(SrcOpcode) && N->isOnlyUserOf(N0.getNode()) && 21306 (N1.isUndef() || 21307 (SrcOpcode == N1.getOpcode() && N->isOnlyUserOf(N1.getNode())))) { 21308 // Get binop source ops, or just pass on the undef. 21309 SDValue Op00 = N0.getOperand(0); 21310 SDValue Op01 = N0.getOperand(1); 21311 SDValue Op10 = N1.isUndef() ? N1 : N1.getOperand(0); 21312 SDValue Op11 = N1.isUndef() ? N1 : N1.getOperand(1); 21313 // TODO: We might be able to relax the VT check but we don't currently 21314 // have any isBinOp() that has different result/ops VTs so play safe until 21315 // we have test coverage. 21316 if (Op00.getValueType() == VT && Op10.getValueType() == VT && 21317 Op01.getValueType() == VT && Op11.getValueType() == VT && 21318 (Op00.getOpcode() == ISD::VECTOR_SHUFFLE || 21319 Op10.getOpcode() == ISD::VECTOR_SHUFFLE || 21320 Op01.getOpcode() == ISD::VECTOR_SHUFFLE || 21321 Op11.getOpcode() == ISD::VECTOR_SHUFFLE)) { 21322 auto CanMergeInnerShuffle = [&](SDValue &SV0, SDValue &SV1, 21323 SmallVectorImpl<int> &Mask, bool LeftOp, 21324 bool Commute) { 21325 SDValue InnerN = Commute ? N1 : N0; 21326 SDValue Op0 = LeftOp ? Op00 : Op01; 21327 SDValue Op1 = LeftOp ? Op10 : Op11; 21328 if (Commute) 21329 std::swap(Op0, Op1); 21330 // Only accept the merged shuffle if we don't introduce undef elements, 21331 // or the inner shuffle already contained undef elements. 21332 auto *SVN0 = dyn_cast<ShuffleVectorSDNode>(Op0); 21333 return SVN0 && InnerN->isOnlyUserOf(SVN0) && 21334 MergeInnerShuffle(Commute, SVN, SVN0, Op1, TLI, SV0, SV1, 21335 Mask) && 21336 (llvm::any_of(SVN0->getMask(), [](int M) { return M < 0; }) || 21337 llvm::none_of(Mask, [](int M) { return M < 0; })); 21338 }; 21339 21340 // Ensure we don't increase the number of shuffles - we must merge a 21341 // shuffle from at least one of the LHS and RHS ops. 21342 bool MergedLeft = false; 21343 SDValue LeftSV0, LeftSV1; 21344 SmallVector<int, 4> LeftMask; 21345 if (CanMergeInnerShuffle(LeftSV0, LeftSV1, LeftMask, true, false) || 21346 CanMergeInnerShuffle(LeftSV0, LeftSV1, LeftMask, true, true)) { 21347 MergedLeft = true; 21348 } else { 21349 LeftMask.assign(SVN->getMask().begin(), SVN->getMask().end()); 21350 LeftSV0 = Op00, LeftSV1 = Op10; 21351 } 21352 21353 bool MergedRight = false; 21354 SDValue RightSV0, RightSV1; 21355 SmallVector<int, 4> RightMask; 21356 if (CanMergeInnerShuffle(RightSV0, RightSV1, RightMask, false, false) || 21357 CanMergeInnerShuffle(RightSV0, RightSV1, RightMask, false, true)) { 21358 MergedRight = true; 21359 } else { 21360 RightMask.assign(SVN->getMask().begin(), SVN->getMask().end()); 21361 RightSV0 = Op01, RightSV1 = Op11; 21362 } 21363 21364 if (MergedLeft || MergedRight) { 21365 SDLoc DL(N); 21366 SDValue LHS = DAG.getVectorShuffle( 21367 VT, DL, LeftSV0 ? LeftSV0 : DAG.getUNDEF(VT), 21368 LeftSV1 ? LeftSV1 : DAG.getUNDEF(VT), LeftMask); 21369 SDValue RHS = DAG.getVectorShuffle( 21370 VT, DL, RightSV0 ? RightSV0 : DAG.getUNDEF(VT), 21371 RightSV1 ? RightSV1 : DAG.getUNDEF(VT), RightMask); 21372 return DAG.getNode(SrcOpcode, DL, VT, LHS, RHS); 21373 } 21374 } 21375 } 21376 } 21377 21378 if (SDValue V = foldShuffleOfConcatUndefs(SVN, DAG)) 21379 return V; 21380 21381 return SDValue(); 21382 } 21383 21384 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 21385 SDValue InVal = N->getOperand(0); 21386 EVT VT = N->getValueType(0); 21387 21388 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 21389 // with a VECTOR_SHUFFLE and possible truncate. 21390 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 21391 VT.isFixedLengthVector() && 21392 InVal->getOperand(0).getValueType().isFixedLengthVector()) { 21393 SDValue InVec = InVal->getOperand(0); 21394 SDValue EltNo = InVal->getOperand(1); 21395 auto InVecT = InVec.getValueType(); 21396 if (ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo)) { 21397 SmallVector<int, 8> NewMask(InVecT.getVectorNumElements(), -1); 21398 int Elt = C0->getZExtValue(); 21399 NewMask[0] = Elt; 21400 // If we have an implict truncate do truncate here as long as it's legal. 21401 // if it's not legal, this should 21402 if (VT.getScalarType() != InVal.getValueType() && 21403 InVal.getValueType().isScalarInteger() && 21404 isTypeLegal(VT.getScalarType())) { 21405 SDValue Val = 21406 DAG.getNode(ISD::TRUNCATE, SDLoc(InVal), VT.getScalarType(), InVal); 21407 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val); 21408 } 21409 if (VT.getScalarType() == InVecT.getScalarType() && 21410 VT.getVectorNumElements() <= InVecT.getVectorNumElements()) { 21411 SDValue LegalShuffle = 21412 TLI.buildLegalVectorShuffle(InVecT, SDLoc(N), InVec, 21413 DAG.getUNDEF(InVecT), NewMask, DAG); 21414 if (LegalShuffle) { 21415 // If the initial vector is the correct size this shuffle is a 21416 // valid result. 21417 if (VT == InVecT) 21418 return LegalShuffle; 21419 // If not we must truncate the vector. 21420 if (VT.getVectorNumElements() != InVecT.getVectorNumElements()) { 21421 SDValue ZeroIdx = DAG.getVectorIdxConstant(0, SDLoc(N)); 21422 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), 21423 InVecT.getVectorElementType(), 21424 VT.getVectorNumElements()); 21425 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT, 21426 LegalShuffle, ZeroIdx); 21427 } 21428 } 21429 } 21430 } 21431 } 21432 21433 return SDValue(); 21434 } 21435 21436 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 21437 EVT VT = N->getValueType(0); 21438 SDValue N0 = N->getOperand(0); 21439 SDValue N1 = N->getOperand(1); 21440 SDValue N2 = N->getOperand(2); 21441 uint64_t InsIdx = N->getConstantOperandVal(2); 21442 21443 // If inserting an UNDEF, just return the original vector. 21444 if (N1.isUndef()) 21445 return N0; 21446 21447 // If this is an insert of an extracted vector into an undef vector, we can 21448 // just use the input to the extract. 21449 if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 21450 N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT) 21451 return N1.getOperand(0); 21452 21453 // If we are inserting a bitcast value into an undef, with the same 21454 // number of elements, just use the bitcast input of the extract. 21455 // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 -> 21456 // BITCAST (INSERT_SUBVECTOR UNDEF N1 N2) 21457 if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST && 21458 N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR && 21459 N1.getOperand(0).getOperand(1) == N2 && 21460 N1.getOperand(0).getOperand(0).getValueType().getVectorElementCount() == 21461 VT.getVectorElementCount() && 21462 N1.getOperand(0).getOperand(0).getValueType().getSizeInBits() == 21463 VT.getSizeInBits()) { 21464 return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0)); 21465 } 21466 21467 // If both N1 and N2 are bitcast values on which insert_subvector 21468 // would makes sense, pull the bitcast through. 21469 // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 -> 21470 // BITCAST (INSERT_SUBVECTOR N0 N1 N2) 21471 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) { 21472 SDValue CN0 = N0.getOperand(0); 21473 SDValue CN1 = N1.getOperand(0); 21474 EVT CN0VT = CN0.getValueType(); 21475 EVT CN1VT = CN1.getValueType(); 21476 if (CN0VT.isVector() && CN1VT.isVector() && 21477 CN0VT.getVectorElementType() == CN1VT.getVectorElementType() && 21478 CN0VT.getVectorElementCount() == VT.getVectorElementCount()) { 21479 SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), 21480 CN0.getValueType(), CN0, CN1, N2); 21481 return DAG.getBitcast(VT, NewINSERT); 21482 } 21483 } 21484 21485 // Combine INSERT_SUBVECTORs where we are inserting to the same index. 21486 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx ) 21487 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx ) 21488 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && 21489 N0.getOperand(1).getValueType() == N1.getValueType() && 21490 N0.getOperand(2) == N2) 21491 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0), 21492 N1, N2); 21493 21494 // Eliminate an intermediate insert into an undef vector: 21495 // insert_subvector undef, (insert_subvector undef, X, 0), N2 --> 21496 // insert_subvector undef, X, N2 21497 if (N0.isUndef() && N1.getOpcode() == ISD::INSERT_SUBVECTOR && 21498 N1.getOperand(0).isUndef() && isNullConstant(N1.getOperand(2))) 21499 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0, 21500 N1.getOperand(1), N2); 21501 21502 // Push subvector bitcasts to the output, adjusting the index as we go. 21503 // insert_subvector(bitcast(v), bitcast(s), c1) 21504 // -> bitcast(insert_subvector(v, s, c2)) 21505 if ((N0.isUndef() || N0.getOpcode() == ISD::BITCAST) && 21506 N1.getOpcode() == ISD::BITCAST) { 21507 SDValue N0Src = peekThroughBitcasts(N0); 21508 SDValue N1Src = peekThroughBitcasts(N1); 21509 EVT N0SrcSVT = N0Src.getValueType().getScalarType(); 21510 EVT N1SrcSVT = N1Src.getValueType().getScalarType(); 21511 if ((N0.isUndef() || N0SrcSVT == N1SrcSVT) && 21512 N0Src.getValueType().isVector() && N1Src.getValueType().isVector()) { 21513 EVT NewVT; 21514 SDLoc DL(N); 21515 SDValue NewIdx; 21516 LLVMContext &Ctx = *DAG.getContext(); 21517 ElementCount NumElts = VT.getVectorElementCount(); 21518 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 21519 if ((EltSizeInBits % N1SrcSVT.getSizeInBits()) == 0) { 21520 unsigned Scale = EltSizeInBits / N1SrcSVT.getSizeInBits(); 21521 NewVT = EVT::getVectorVT(Ctx, N1SrcSVT, NumElts * Scale); 21522 NewIdx = DAG.getVectorIdxConstant(InsIdx * Scale, DL); 21523 } else if ((N1SrcSVT.getSizeInBits() % EltSizeInBits) == 0) { 21524 unsigned Scale = N1SrcSVT.getSizeInBits() / EltSizeInBits; 21525 if (NumElts.isKnownMultipleOf(Scale) && (InsIdx % Scale) == 0) { 21526 NewVT = EVT::getVectorVT(Ctx, N1SrcSVT, 21527 NumElts.divideCoefficientBy(Scale)); 21528 NewIdx = DAG.getVectorIdxConstant(InsIdx / Scale, DL); 21529 } 21530 } 21531 if (NewIdx && hasOperation(ISD::INSERT_SUBVECTOR, NewVT)) { 21532 SDValue Res = DAG.getBitcast(NewVT, N0Src); 21533 Res = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, NewVT, Res, N1Src, NewIdx); 21534 return DAG.getBitcast(VT, Res); 21535 } 21536 } 21537 } 21538 21539 // Canonicalize insert_subvector dag nodes. 21540 // Example: 21541 // (insert_subvector (insert_subvector A, Idx0), Idx1) 21542 // -> (insert_subvector (insert_subvector A, Idx1), Idx0) 21543 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() && 21544 N1.getValueType() == N0.getOperand(1).getValueType()) { 21545 unsigned OtherIdx = N0.getConstantOperandVal(2); 21546 if (InsIdx < OtherIdx) { 21547 // Swap nodes. 21548 SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, 21549 N0.getOperand(0), N1, N2); 21550 AddToWorklist(NewOp.getNode()); 21551 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()), 21552 VT, NewOp, N0.getOperand(1), N0.getOperand(2)); 21553 } 21554 } 21555 21556 // If the input vector is a concatenation, and the insert replaces 21557 // one of the pieces, we can optimize into a single concat_vectors. 21558 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() && 21559 N0.getOperand(0).getValueType() == N1.getValueType() && 21560 N0.getOperand(0).getValueType().isScalableVector() == 21561 N1.getValueType().isScalableVector()) { 21562 unsigned Factor = N1.getValueType().getVectorMinNumElements(); 21563 SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end()); 21564 Ops[InsIdx / Factor] = N1; 21565 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 21566 } 21567 21568 // Simplify source operands based on insertion. 21569 if (SimplifyDemandedVectorElts(SDValue(N, 0))) 21570 return SDValue(N, 0); 21571 21572 return SDValue(); 21573 } 21574 21575 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 21576 SDValue N0 = N->getOperand(0); 21577 21578 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 21579 if (N0->getOpcode() == ISD::FP16_TO_FP) 21580 return N0->getOperand(0); 21581 21582 return SDValue(); 21583 } 21584 21585 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 21586 SDValue N0 = N->getOperand(0); 21587 21588 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 21589 if (!TLI.shouldKeepZExtForFP16Conv() && N0->getOpcode() == ISD::AND) { 21590 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 21591 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 21592 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 21593 N0.getOperand(0)); 21594 } 21595 } 21596 21597 return SDValue(); 21598 } 21599 21600 SDValue DAGCombiner::visitVECREDUCE(SDNode *N) { 21601 SDValue N0 = N->getOperand(0); 21602 EVT VT = N0.getValueType(); 21603 unsigned Opcode = N->getOpcode(); 21604 21605 // VECREDUCE over 1-element vector is just an extract. 21606 if (VT.getVectorElementCount().isScalar()) { 21607 SDLoc dl(N); 21608 SDValue Res = 21609 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT.getVectorElementType(), N0, 21610 DAG.getVectorIdxConstant(0, dl)); 21611 if (Res.getValueType() != N->getValueType(0)) 21612 Res = DAG.getNode(ISD::ANY_EXTEND, dl, N->getValueType(0), Res); 21613 return Res; 21614 } 21615 21616 // On an boolean vector an and/or reduction is the same as a umin/umax 21617 // reduction. Convert them if the latter is legal while the former isn't. 21618 if (Opcode == ISD::VECREDUCE_AND || Opcode == ISD::VECREDUCE_OR) { 21619 unsigned NewOpcode = Opcode == ISD::VECREDUCE_AND 21620 ? ISD::VECREDUCE_UMIN : ISD::VECREDUCE_UMAX; 21621 if (!TLI.isOperationLegalOrCustom(Opcode, VT) && 21622 TLI.isOperationLegalOrCustom(NewOpcode, VT) && 21623 DAG.ComputeNumSignBits(N0) == VT.getScalarSizeInBits()) 21624 return DAG.getNode(NewOpcode, SDLoc(N), N->getValueType(0), N0); 21625 } 21626 21627 return SDValue(); 21628 } 21629 21630 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 21631 /// with the destination vector and a zero vector. 21632 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 21633 /// vector_shuffle V, Zero, <0, 4, 2, 4> 21634 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 21635 assert(N->getOpcode() == ISD::AND && "Unexpected opcode!"); 21636 21637 EVT VT = N->getValueType(0); 21638 SDValue LHS = N->getOperand(0); 21639 SDValue RHS = peekThroughBitcasts(N->getOperand(1)); 21640 SDLoc DL(N); 21641 21642 // Make sure we're not running after operation legalization where it 21643 // may have custom lowered the vector shuffles. 21644 if (LegalOperations) 21645 return SDValue(); 21646 21647 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 21648 return SDValue(); 21649 21650 EVT RVT = RHS.getValueType(); 21651 unsigned NumElts = RHS.getNumOperands(); 21652 21653 // Attempt to create a valid clear mask, splitting the mask into 21654 // sub elements and checking to see if each is 21655 // all zeros or all ones - suitable for shuffle masking. 21656 auto BuildClearMask = [&](int Split) { 21657 int NumSubElts = NumElts * Split; 21658 int NumSubBits = RVT.getScalarSizeInBits() / Split; 21659 21660 SmallVector<int, 8> Indices; 21661 for (int i = 0; i != NumSubElts; ++i) { 21662 int EltIdx = i / Split; 21663 int SubIdx = i % Split; 21664 SDValue Elt = RHS.getOperand(EltIdx); 21665 // X & undef --> 0 (not undef). So this lane must be converted to choose 21666 // from the zero constant vector (same as if the element had all 0-bits). 21667 if (Elt.isUndef()) { 21668 Indices.push_back(i + NumSubElts); 21669 continue; 21670 } 21671 21672 APInt Bits; 21673 if (isa<ConstantSDNode>(Elt)) 21674 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 21675 else if (isa<ConstantFPSDNode>(Elt)) 21676 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 21677 else 21678 return SDValue(); 21679 21680 // Extract the sub element from the constant bit mask. 21681 if (DAG.getDataLayout().isBigEndian()) 21682 Bits = Bits.extractBits(NumSubBits, (Split - SubIdx - 1) * NumSubBits); 21683 else 21684 Bits = Bits.extractBits(NumSubBits, SubIdx * NumSubBits); 21685 21686 if (Bits.isAllOnesValue()) 21687 Indices.push_back(i); 21688 else if (Bits == 0) 21689 Indices.push_back(i + NumSubElts); 21690 else 21691 return SDValue(); 21692 } 21693 21694 // Let's see if the target supports this vector_shuffle. 21695 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 21696 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 21697 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 21698 return SDValue(); 21699 21700 SDValue Zero = DAG.getConstant(0, DL, ClearVT); 21701 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL, 21702 DAG.getBitcast(ClearVT, LHS), 21703 Zero, Indices)); 21704 }; 21705 21706 // Determine maximum split level (byte level masking). 21707 int MaxSplit = 1; 21708 if (RVT.getScalarSizeInBits() % 8 == 0) 21709 MaxSplit = RVT.getScalarSizeInBits() / 8; 21710 21711 for (int Split = 1; Split <= MaxSplit; ++Split) 21712 if (RVT.getScalarSizeInBits() % Split == 0) 21713 if (SDValue S = BuildClearMask(Split)) 21714 return S; 21715 21716 return SDValue(); 21717 } 21718 21719 /// If a vector binop is performed on splat values, it may be profitable to 21720 /// extract, scalarize, and insert/splat. 21721 static SDValue scalarizeBinOpOfSplats(SDNode *N, SelectionDAG &DAG) { 21722 SDValue N0 = N->getOperand(0); 21723 SDValue N1 = N->getOperand(1); 21724 unsigned Opcode = N->getOpcode(); 21725 EVT VT = N->getValueType(0); 21726 EVT EltVT = VT.getVectorElementType(); 21727 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 21728 21729 // TODO: Remove/replace the extract cost check? If the elements are available 21730 // as scalars, then there may be no extract cost. Should we ask if 21731 // inserting a scalar back into a vector is cheap instead? 21732 int Index0, Index1; 21733 SDValue Src0 = DAG.getSplatSourceVector(N0, Index0); 21734 SDValue Src1 = DAG.getSplatSourceVector(N1, Index1); 21735 if (!Src0 || !Src1 || Index0 != Index1 || 21736 Src0.getValueType().getVectorElementType() != EltVT || 21737 Src1.getValueType().getVectorElementType() != EltVT || 21738 !TLI.isExtractVecEltCheap(VT, Index0) || 21739 !TLI.isOperationLegalOrCustom(Opcode, EltVT)) 21740 return SDValue(); 21741 21742 SDLoc DL(N); 21743 SDValue IndexC = DAG.getVectorIdxConstant(Index0, DL); 21744 SDValue X = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src0, IndexC); 21745 SDValue Y = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src1, IndexC); 21746 SDValue ScalarBO = DAG.getNode(Opcode, DL, EltVT, X, Y, N->getFlags()); 21747 21748 // If all lanes but 1 are undefined, no need to splat the scalar result. 21749 // TODO: Keep track of undefs and use that info in the general case. 21750 if (N0.getOpcode() == ISD::BUILD_VECTOR && N0.getOpcode() == N1.getOpcode() && 21751 count_if(N0->ops(), [](SDValue V) { return !V.isUndef(); }) == 1 && 21752 count_if(N1->ops(), [](SDValue V) { return !V.isUndef(); }) == 1) { 21753 // bo (build_vec ..undef, X, undef...), (build_vec ..undef, Y, undef...) --> 21754 // build_vec ..undef, (bo X, Y), undef... 21755 SmallVector<SDValue, 8> Ops(VT.getVectorNumElements(), DAG.getUNDEF(EltVT)); 21756 Ops[Index0] = ScalarBO; 21757 return DAG.getBuildVector(VT, DL, Ops); 21758 } 21759 21760 // bo (splat X, Index), (splat Y, Index) --> splat (bo X, Y), Index 21761 SmallVector<SDValue, 8> Ops(VT.getVectorNumElements(), ScalarBO); 21762 return DAG.getBuildVector(VT, DL, Ops); 21763 } 21764 21765 /// Visit a binary vector operation, like ADD. 21766 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 21767 assert(N->getValueType(0).isVector() && 21768 "SimplifyVBinOp only works on vectors!"); 21769 21770 SDValue LHS = N->getOperand(0); 21771 SDValue RHS = N->getOperand(1); 21772 SDValue Ops[] = {LHS, RHS}; 21773 EVT VT = N->getValueType(0); 21774 unsigned Opcode = N->getOpcode(); 21775 SDNodeFlags Flags = N->getFlags(); 21776 21777 // See if we can constant fold the vector operation. 21778 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 21779 Opcode, SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 21780 return Fold; 21781 21782 // Move unary shuffles with identical masks after a vector binop: 21783 // VBinOp (shuffle A, Undef, Mask), (shuffle B, Undef, Mask)) 21784 // --> shuffle (VBinOp A, B), Undef, Mask 21785 // This does not require type legality checks because we are creating the 21786 // same types of operations that are in the original sequence. We do have to 21787 // restrict ops like integer div that have immediate UB (eg, div-by-zero) 21788 // though. This code is adapted from the identical transform in instcombine. 21789 if (Opcode != ISD::UDIV && Opcode != ISD::SDIV && 21790 Opcode != ISD::UREM && Opcode != ISD::SREM && 21791 Opcode != ISD::UDIVREM && Opcode != ISD::SDIVREM) { 21792 auto *Shuf0 = dyn_cast<ShuffleVectorSDNode>(LHS); 21793 auto *Shuf1 = dyn_cast<ShuffleVectorSDNode>(RHS); 21794 if (Shuf0 && Shuf1 && Shuf0->getMask().equals(Shuf1->getMask()) && 21795 LHS.getOperand(1).isUndef() && RHS.getOperand(1).isUndef() && 21796 (LHS.hasOneUse() || RHS.hasOneUse() || LHS == RHS)) { 21797 SDLoc DL(N); 21798 SDValue NewBinOp = DAG.getNode(Opcode, DL, VT, LHS.getOperand(0), 21799 RHS.getOperand(0), Flags); 21800 SDValue UndefV = LHS.getOperand(1); 21801 return DAG.getVectorShuffle(VT, DL, NewBinOp, UndefV, Shuf0->getMask()); 21802 } 21803 21804 // Try to sink a splat shuffle after a binop with a uniform constant. 21805 // This is limited to cases where neither the shuffle nor the constant have 21806 // undefined elements because that could be poison-unsafe or inhibit 21807 // demanded elements analysis. It is further limited to not change a splat 21808 // of an inserted scalar because that may be optimized better by 21809 // load-folding or other target-specific behaviors. 21810 if (isConstOrConstSplat(RHS) && Shuf0 && is_splat(Shuf0->getMask()) && 21811 Shuf0->hasOneUse() && Shuf0->getOperand(1).isUndef() && 21812 Shuf0->getOperand(0).getOpcode() != ISD::INSERT_VECTOR_ELT) { 21813 // binop (splat X), (splat C) --> splat (binop X, C) 21814 SDLoc DL(N); 21815 SDValue X = Shuf0->getOperand(0); 21816 SDValue NewBinOp = DAG.getNode(Opcode, DL, VT, X, RHS, Flags); 21817 return DAG.getVectorShuffle(VT, DL, NewBinOp, DAG.getUNDEF(VT), 21818 Shuf0->getMask()); 21819 } 21820 if (isConstOrConstSplat(LHS) && Shuf1 && is_splat(Shuf1->getMask()) && 21821 Shuf1->hasOneUse() && Shuf1->getOperand(1).isUndef() && 21822 Shuf1->getOperand(0).getOpcode() != ISD::INSERT_VECTOR_ELT) { 21823 // binop (splat C), (splat X) --> splat (binop C, X) 21824 SDLoc DL(N); 21825 SDValue X = Shuf1->getOperand(0); 21826 SDValue NewBinOp = DAG.getNode(Opcode, DL, VT, LHS, X, Flags); 21827 return DAG.getVectorShuffle(VT, DL, NewBinOp, DAG.getUNDEF(VT), 21828 Shuf1->getMask()); 21829 } 21830 } 21831 21832 // The following pattern is likely to emerge with vector reduction ops. Moving 21833 // the binary operation ahead of insertion may allow using a narrower vector 21834 // instruction that has better performance than the wide version of the op: 21835 // VBinOp (ins undef, X, Z), (ins undef, Y, Z) --> ins VecC, (VBinOp X, Y), Z 21836 if (LHS.getOpcode() == ISD::INSERT_SUBVECTOR && LHS.getOperand(0).isUndef() && 21837 RHS.getOpcode() == ISD::INSERT_SUBVECTOR && RHS.getOperand(0).isUndef() && 21838 LHS.getOperand(2) == RHS.getOperand(2) && 21839 (LHS.hasOneUse() || RHS.hasOneUse())) { 21840 SDValue X = LHS.getOperand(1); 21841 SDValue Y = RHS.getOperand(1); 21842 SDValue Z = LHS.getOperand(2); 21843 EVT NarrowVT = X.getValueType(); 21844 if (NarrowVT == Y.getValueType() && 21845 TLI.isOperationLegalOrCustomOrPromote(Opcode, NarrowVT, 21846 LegalOperations)) { 21847 // (binop undef, undef) may not return undef, so compute that result. 21848 SDLoc DL(N); 21849 SDValue VecC = 21850 DAG.getNode(Opcode, DL, VT, DAG.getUNDEF(VT), DAG.getUNDEF(VT)); 21851 SDValue NarrowBO = DAG.getNode(Opcode, DL, NarrowVT, X, Y); 21852 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, VecC, NarrowBO, Z); 21853 } 21854 } 21855 21856 // Make sure all but the first op are undef or constant. 21857 auto ConcatWithConstantOrUndef = [](SDValue Concat) { 21858 return Concat.getOpcode() == ISD::CONCAT_VECTORS && 21859 all_of(drop_begin(Concat->ops()), [](const SDValue &Op) { 21860 return Op.isUndef() || 21861 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()); 21862 }); 21863 }; 21864 21865 // The following pattern is likely to emerge with vector reduction ops. Moving 21866 // the binary operation ahead of the concat may allow using a narrower vector 21867 // instruction that has better performance than the wide version of the op: 21868 // VBinOp (concat X, undef/constant), (concat Y, undef/constant) --> 21869 // concat (VBinOp X, Y), VecC 21870 if (ConcatWithConstantOrUndef(LHS) && ConcatWithConstantOrUndef(RHS) && 21871 (LHS.hasOneUse() || RHS.hasOneUse())) { 21872 EVT NarrowVT = LHS.getOperand(0).getValueType(); 21873 if (NarrowVT == RHS.getOperand(0).getValueType() && 21874 TLI.isOperationLegalOrCustomOrPromote(Opcode, NarrowVT)) { 21875 SDLoc DL(N); 21876 unsigned NumOperands = LHS.getNumOperands(); 21877 SmallVector<SDValue, 4> ConcatOps; 21878 for (unsigned i = 0; i != NumOperands; ++i) { 21879 // This constant fold for operands 1 and up. 21880 ConcatOps.push_back(DAG.getNode(Opcode, DL, NarrowVT, LHS.getOperand(i), 21881 RHS.getOperand(i))); 21882 } 21883 21884 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 21885 } 21886 } 21887 21888 if (SDValue V = scalarizeBinOpOfSplats(N, DAG)) 21889 return V; 21890 21891 return SDValue(); 21892 } 21893 21894 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, 21895 SDValue N2) { 21896 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 21897 21898 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 21899 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 21900 21901 // If we got a simplified select_cc node back from SimplifySelectCC, then 21902 // break it down into a new SETCC node, and a new SELECT node, and then return 21903 // the SELECT node, since we were called with a SELECT node. 21904 if (SCC.getNode()) { 21905 // Check to see if we got a select_cc back (to turn into setcc/select). 21906 // Otherwise, just return whatever node we got back, like fabs. 21907 if (SCC.getOpcode() == ISD::SELECT_CC) { 21908 const SDNodeFlags Flags = N0.getNode()->getFlags(); 21909 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 21910 N0.getValueType(), 21911 SCC.getOperand(0), SCC.getOperand(1), 21912 SCC.getOperand(4), Flags); 21913 AddToWorklist(SETCC.getNode()); 21914 SDValue SelectNode = DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 21915 SCC.getOperand(2), SCC.getOperand(3)); 21916 SelectNode->setFlags(Flags); 21917 return SelectNode; 21918 } 21919 21920 return SCC; 21921 } 21922 return SDValue(); 21923 } 21924 21925 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 21926 /// being selected between, see if we can simplify the select. Callers of this 21927 /// should assume that TheSelect is deleted if this returns true. As such, they 21928 /// should return the appropriate thing (e.g. the node) back to the top-level of 21929 /// the DAG combiner loop to avoid it being looked at. 21930 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 21931 SDValue RHS) { 21932 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 21933 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 21934 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 21935 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 21936 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 21937 SDValue Sqrt = RHS; 21938 ISD::CondCode CC; 21939 SDValue CmpLHS; 21940 const ConstantFPSDNode *Zero = nullptr; 21941 21942 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 21943 CC = cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 21944 CmpLHS = TheSelect->getOperand(0); 21945 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 21946 } else { 21947 // SELECT or VSELECT 21948 SDValue Cmp = TheSelect->getOperand(0); 21949 if (Cmp.getOpcode() == ISD::SETCC) { 21950 CC = cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 21951 CmpLHS = Cmp.getOperand(0); 21952 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 21953 } 21954 } 21955 if (Zero && Zero->isZero() && 21956 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 21957 CC == ISD::SETULT || CC == ISD::SETLT)) { 21958 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 21959 CombineTo(TheSelect, Sqrt); 21960 return true; 21961 } 21962 } 21963 } 21964 // Cannot simplify select with vector condition 21965 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 21966 21967 // If this is a select from two identical things, try to pull the operation 21968 // through the select. 21969 if (LHS.getOpcode() != RHS.getOpcode() || 21970 !LHS.hasOneUse() || !RHS.hasOneUse()) 21971 return false; 21972 21973 // If this is a load and the token chain is identical, replace the select 21974 // of two loads with a load through a select of the address to load from. 21975 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 21976 // constants have been dropped into the constant pool. 21977 if (LHS.getOpcode() == ISD::LOAD) { 21978 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 21979 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 21980 21981 // Token chains must be identical. 21982 if (LHS.getOperand(0) != RHS.getOperand(0) || 21983 // Do not let this transformation reduce the number of volatile loads. 21984 // Be conservative for atomics for the moment 21985 // TODO: This does appear to be legal for unordered atomics (see D66309) 21986 !LLD->isSimple() || !RLD->isSimple() || 21987 // FIXME: If either is a pre/post inc/dec load, 21988 // we'd need to split out the address adjustment. 21989 LLD->isIndexed() || RLD->isIndexed() || 21990 // If this is an EXTLOAD, the VT's must match. 21991 LLD->getMemoryVT() != RLD->getMemoryVT() || 21992 // If this is an EXTLOAD, the kind of extension must match. 21993 (LLD->getExtensionType() != RLD->getExtensionType() && 21994 // The only exception is if one of the extensions is anyext. 21995 LLD->getExtensionType() != ISD::EXTLOAD && 21996 RLD->getExtensionType() != ISD::EXTLOAD) || 21997 // FIXME: this discards src value information. This is 21998 // over-conservative. It would be beneficial to be able to remember 21999 // both potential memory locations. Since we are discarding 22000 // src value info, don't do the transformation if the memory 22001 // locations are not in the default address space. 22002 LLD->getPointerInfo().getAddrSpace() != 0 || 22003 RLD->getPointerInfo().getAddrSpace() != 0 || 22004 // We can't produce a CMOV of a TargetFrameIndex since we won't 22005 // generate the address generation required. 22006 LLD->getBasePtr().getOpcode() == ISD::TargetFrameIndex || 22007 RLD->getBasePtr().getOpcode() == ISD::TargetFrameIndex || 22008 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 22009 LLD->getBasePtr().getValueType())) 22010 return false; 22011 22012 // The loads must not depend on one another. 22013 if (LLD->isPredecessorOf(RLD) || RLD->isPredecessorOf(LLD)) 22014 return false; 22015 22016 // Check that the select condition doesn't reach either load. If so, 22017 // folding this will induce a cycle into the DAG. If not, this is safe to 22018 // xform, so create a select of the addresses. 22019 22020 SmallPtrSet<const SDNode *, 32> Visited; 22021 SmallVector<const SDNode *, 16> Worklist; 22022 22023 // Always fail if LLD and RLD are not independent. TheSelect is a 22024 // predecessor to all Nodes in question so we need not search past it. 22025 22026 Visited.insert(TheSelect); 22027 Worklist.push_back(LLD); 22028 Worklist.push_back(RLD); 22029 22030 if (SDNode::hasPredecessorHelper(LLD, Visited, Worklist) || 22031 SDNode::hasPredecessorHelper(RLD, Visited, Worklist)) 22032 return false; 22033 22034 SDValue Addr; 22035 if (TheSelect->getOpcode() == ISD::SELECT) { 22036 // We cannot do this optimization if any pair of {RLD, LLD} is a 22037 // predecessor to {RLD, LLD, CondNode}. As we've already compared the 22038 // Loads, we only need to check if CondNode is a successor to one of the 22039 // loads. We can further avoid this if there's no use of their chain 22040 // value. 22041 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 22042 Worklist.push_back(CondNode); 22043 22044 if ((LLD->hasAnyUseOfValue(1) && 22045 SDNode::hasPredecessorHelper(LLD, Visited, Worklist)) || 22046 (RLD->hasAnyUseOfValue(1) && 22047 SDNode::hasPredecessorHelper(RLD, Visited, Worklist))) 22048 return false; 22049 22050 Addr = DAG.getSelect(SDLoc(TheSelect), 22051 LLD->getBasePtr().getValueType(), 22052 TheSelect->getOperand(0), LLD->getBasePtr(), 22053 RLD->getBasePtr()); 22054 } else { // Otherwise SELECT_CC 22055 // We cannot do this optimization if any pair of {RLD, LLD} is a 22056 // predecessor to {RLD, LLD, CondLHS, CondRHS}. As we've already compared 22057 // the Loads, we only need to check if CondLHS/CondRHS is a successor to 22058 // one of the loads. We can further avoid this if there's no use of their 22059 // chain value. 22060 22061 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 22062 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 22063 Worklist.push_back(CondLHS); 22064 Worklist.push_back(CondRHS); 22065 22066 if ((LLD->hasAnyUseOfValue(1) && 22067 SDNode::hasPredecessorHelper(LLD, Visited, Worklist)) || 22068 (RLD->hasAnyUseOfValue(1) && 22069 SDNode::hasPredecessorHelper(RLD, Visited, Worklist))) 22070 return false; 22071 22072 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 22073 LLD->getBasePtr().getValueType(), 22074 TheSelect->getOperand(0), 22075 TheSelect->getOperand(1), 22076 LLD->getBasePtr(), RLD->getBasePtr(), 22077 TheSelect->getOperand(4)); 22078 } 22079 22080 SDValue Load; 22081 // It is safe to replace the two loads if they have different alignments, 22082 // but the new load must be the minimum (most restrictive) alignment of the 22083 // inputs. 22084 Align Alignment = std::min(LLD->getAlign(), RLD->getAlign()); 22085 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags(); 22086 if (!RLD->isInvariant()) 22087 MMOFlags &= ~MachineMemOperand::MOInvariant; 22088 if (!RLD->isDereferenceable()) 22089 MMOFlags &= ~MachineMemOperand::MODereferenceable; 22090 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 22091 // FIXME: Discards pointer and AA info. 22092 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect), 22093 LLD->getChain(), Addr, MachinePointerInfo(), Alignment, 22094 MMOFlags); 22095 } else { 22096 // FIXME: Discards pointer and AA info. 22097 Load = DAG.getExtLoad( 22098 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType() 22099 : LLD->getExtensionType(), 22100 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr, 22101 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags); 22102 } 22103 22104 // Users of the select now use the result of the load. 22105 CombineTo(TheSelect, Load); 22106 22107 // Users of the old loads now use the new load's chain. We know the 22108 // old-load value is dead now. 22109 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 22110 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 22111 return true; 22112 } 22113 22114 return false; 22115 } 22116 22117 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and 22118 /// bitwise 'and'. 22119 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, 22120 SDValue N1, SDValue N2, SDValue N3, 22121 ISD::CondCode CC) { 22122 // If this is a select where the false operand is zero and the compare is a 22123 // check of the sign bit, see if we can perform the "gzip trick": 22124 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A 22125 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A 22126 EVT XType = N0.getValueType(); 22127 EVT AType = N2.getValueType(); 22128 if (!isNullConstant(N3) || !XType.bitsGE(AType)) 22129 return SDValue(); 22130 22131 // If the comparison is testing for a positive value, we have to invert 22132 // the sign bit mask, so only do that transform if the target has a bitwise 22133 // 'and not' instruction (the invert is free). 22134 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) { 22135 // (X > -1) ? A : 0 22136 // (X > 0) ? X : 0 <-- This is canonical signed max. 22137 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2))) 22138 return SDValue(); 22139 } else if (CC == ISD::SETLT) { 22140 // (X < 0) ? A : 0 22141 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min. 22142 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2))) 22143 return SDValue(); 22144 } else { 22145 return SDValue(); 22146 } 22147 22148 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit 22149 // constant. 22150 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); 22151 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 22152 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 22153 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1; 22154 if (!TLI.shouldAvoidTransformToShift(XType, ShCt)) { 22155 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy); 22156 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt); 22157 AddToWorklist(Shift.getNode()); 22158 22159 if (XType.bitsGT(AType)) { 22160 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 22161 AddToWorklist(Shift.getNode()); 22162 } 22163 22164 if (CC == ISD::SETGT) 22165 Shift = DAG.getNOT(DL, Shift, AType); 22166 22167 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 22168 } 22169 } 22170 22171 unsigned ShCt = XType.getSizeInBits() - 1; 22172 if (TLI.shouldAvoidTransformToShift(XType, ShCt)) 22173 return SDValue(); 22174 22175 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy); 22176 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt); 22177 AddToWorklist(Shift.getNode()); 22178 22179 if (XType.bitsGT(AType)) { 22180 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 22181 AddToWorklist(Shift.getNode()); 22182 } 22183 22184 if (CC == ISD::SETGT) 22185 Shift = DAG.getNOT(DL, Shift, AType); 22186 22187 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 22188 } 22189 22190 // Transform (fneg/fabs (bitconvert x)) to avoid loading constant pool values. 22191 SDValue DAGCombiner::foldSignChangeInBitcast(SDNode *N) { 22192 SDValue N0 = N->getOperand(0); 22193 EVT VT = N->getValueType(0); 22194 bool IsFabs = N->getOpcode() == ISD::FABS; 22195 bool IsFree = IsFabs ? TLI.isFAbsFree(VT) : TLI.isFNegFree(VT); 22196 22197 if (IsFree || N0.getOpcode() != ISD::BITCAST || !N0.hasOneUse()) 22198 return SDValue(); 22199 22200 SDValue Int = N0.getOperand(0); 22201 EVT IntVT = Int.getValueType(); 22202 22203 // The operand to cast should be integer. 22204 if (!IntVT.isInteger() || IntVT.isVector()) 22205 return SDValue(); 22206 22207 // (fneg (bitconvert x)) -> (bitconvert (xor x sign)) 22208 // (fabs (bitconvert x)) -> (bitconvert (and x ~sign)) 22209 APInt SignMask; 22210 if (N0.getValueType().isVector()) { 22211 // For vector, create a sign mask (0x80...) or its inverse (for fabs, 22212 // 0x7f...) per element and splat it. 22213 SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits()); 22214 if (IsFabs) 22215 SignMask = ~SignMask; 22216 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 22217 } else { 22218 // For scalar, just use the sign mask (0x80... or the inverse, 0x7f...) 22219 SignMask = APInt::getSignMask(IntVT.getSizeInBits()); 22220 if (IsFabs) 22221 SignMask = ~SignMask; 22222 } 22223 SDLoc DL(N0); 22224 Int = DAG.getNode(IsFabs ? ISD::AND : ISD::XOR, DL, IntVT, Int, 22225 DAG.getConstant(SignMask, DL, IntVT)); 22226 AddToWorklist(Int.getNode()); 22227 return DAG.getBitcast(VT, Int); 22228 } 22229 22230 /// Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 22231 /// where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 22232 /// in it. This may be a win when the constant is not otherwise available 22233 /// because it replaces two constant pool loads with one. 22234 SDValue DAGCombiner::convertSelectOfFPConstantsToLoadOffset( 22235 const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2, SDValue N3, 22236 ISD::CondCode CC) { 22237 if (!TLI.reduceSelectOfFPConstantLoads(N0.getValueType())) 22238 return SDValue(); 22239 22240 // If we are before legalize types, we want the other legalization to happen 22241 // first (for example, to avoid messing with soft float). 22242 auto *TV = dyn_cast<ConstantFPSDNode>(N2); 22243 auto *FV = dyn_cast<ConstantFPSDNode>(N3); 22244 EVT VT = N2.getValueType(); 22245 if (!TV || !FV || !TLI.isTypeLegal(VT)) 22246 return SDValue(); 22247 22248 // If a constant can be materialized without loads, this does not make sense. 22249 if (TLI.getOperationAction(ISD::ConstantFP, VT) == TargetLowering::Legal || 22250 TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0), ForCodeSize) || 22251 TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0), ForCodeSize)) 22252 return SDValue(); 22253 22254 // If both constants have multiple uses, then we won't need to do an extra 22255 // load. The values are likely around in registers for other users. 22256 if (!TV->hasOneUse() && !FV->hasOneUse()) 22257 return SDValue(); 22258 22259 Constant *Elts[] = { const_cast<ConstantFP*>(FV->getConstantFPValue()), 22260 const_cast<ConstantFP*>(TV->getConstantFPValue()) }; 22261 Type *FPTy = Elts[0]->getType(); 22262 const DataLayout &TD = DAG.getDataLayout(); 22263 22264 // Create a ConstantArray of the two constants. 22265 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 22266 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 22267 TD.getPrefTypeAlign(FPTy)); 22268 Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign(); 22269 22270 // Get offsets to the 0 and 1 elements of the array, so we can select between 22271 // them. 22272 SDValue Zero = DAG.getIntPtrConstant(0, DL); 22273 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 22274 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 22275 SDValue Cond = 22276 DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), N0, N1, CC); 22277 AddToWorklist(Cond.getNode()); 22278 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), Cond, One, Zero); 22279 AddToWorklist(CstOffset.getNode()); 22280 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, CstOffset); 22281 AddToWorklist(CPIdx.getNode()); 22282 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 22283 MachinePointerInfo::getConstantPool( 22284 DAG.getMachineFunction()), Alignment); 22285 } 22286 22287 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 22288 /// where 'cond' is the comparison specified by CC. 22289 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 22290 SDValue N2, SDValue N3, ISD::CondCode CC, 22291 bool NotExtCompare) { 22292 // (x ? y : y) -> y. 22293 if (N2 == N3) return N2; 22294 22295 EVT CmpOpVT = N0.getValueType(); 22296 EVT CmpResVT = getSetCCResultType(CmpOpVT); 22297 EVT VT = N2.getValueType(); 22298 auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 22299 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 22300 auto *N3C = dyn_cast<ConstantSDNode>(N3.getNode()); 22301 22302 // Determine if the condition we're dealing with is constant. 22303 if (SDValue SCC = DAG.FoldSetCC(CmpResVT, N0, N1, CC, DL)) { 22304 AddToWorklist(SCC.getNode()); 22305 if (auto *SCCC = dyn_cast<ConstantSDNode>(SCC)) { 22306 // fold select_cc true, x, y -> x 22307 // fold select_cc false, x, y -> y 22308 return !(SCCC->isNullValue()) ? N2 : N3; 22309 } 22310 } 22311 22312 if (SDValue V = 22313 convertSelectOfFPConstantsToLoadOffset(DL, N0, N1, N2, N3, CC)) 22314 return V; 22315 22316 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC)) 22317 return V; 22318 22319 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 22320 // where y is has a single bit set. 22321 // A plaintext description would be, we can turn the SELECT_CC into an AND 22322 // when the condition can be materialized as an all-ones register. Any 22323 // single bit-test can be materialized as an all-ones register with 22324 // shift-left and shift-right-arith. 22325 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 22326 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 22327 SDValue AndLHS = N0->getOperand(0); 22328 auto *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 22329 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 22330 // Shift the tested bit over the sign bit. 22331 const APInt &AndMask = ConstAndRHS->getAPIntValue(); 22332 unsigned ShCt = AndMask.getBitWidth() - 1; 22333 if (!TLI.shouldAvoidTransformToShift(VT, ShCt)) { 22334 SDValue ShlAmt = 22335 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 22336 getShiftAmountTy(AndLHS.getValueType())); 22337 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 22338 22339 // Now arithmetic right shift it all the way over, so the result is 22340 // either all-ones, or zero. 22341 SDValue ShrAmt = 22342 DAG.getConstant(ShCt, SDLoc(Shl), 22343 getShiftAmountTy(Shl.getValueType())); 22344 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 22345 22346 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 22347 } 22348 } 22349 } 22350 22351 // fold select C, 16, 0 -> shl C, 4 22352 bool Fold = N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2(); 22353 bool Swap = N3C && isNullConstant(N2) && N3C->getAPIntValue().isPowerOf2(); 22354 22355 if ((Fold || Swap) && 22356 TLI.getBooleanContents(CmpOpVT) == 22357 TargetLowering::ZeroOrOneBooleanContent && 22358 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, CmpOpVT))) { 22359 22360 if (Swap) { 22361 CC = ISD::getSetCCInverse(CC, CmpOpVT); 22362 std::swap(N2C, N3C); 22363 } 22364 22365 // If the caller doesn't want us to simplify this into a zext of a compare, 22366 // don't do it. 22367 if (NotExtCompare && N2C->isOne()) 22368 return SDValue(); 22369 22370 SDValue Temp, SCC; 22371 // zext (setcc n0, n1) 22372 if (LegalTypes) { 22373 SCC = DAG.getSetCC(DL, CmpResVT, N0, N1, CC); 22374 if (VT.bitsLT(SCC.getValueType())) 22375 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), VT); 22376 else 22377 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), VT, SCC); 22378 } else { 22379 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 22380 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), VT, SCC); 22381 } 22382 22383 AddToWorklist(SCC.getNode()); 22384 AddToWorklist(Temp.getNode()); 22385 22386 if (N2C->isOne()) 22387 return Temp; 22388 22389 unsigned ShCt = N2C->getAPIntValue().logBase2(); 22390 if (TLI.shouldAvoidTransformToShift(VT, ShCt)) 22391 return SDValue(); 22392 22393 // shl setcc result by log2 n2c 22394 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp, 22395 DAG.getConstant(ShCt, SDLoc(Temp), 22396 getShiftAmountTy(Temp.getValueType()))); 22397 } 22398 22399 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) 22400 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) 22401 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) 22402 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) 22403 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) 22404 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) 22405 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) 22406 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) 22407 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 22408 SDValue ValueOnZero = N2; 22409 SDValue Count = N3; 22410 // If the condition is NE instead of E, swap the operands. 22411 if (CC == ISD::SETNE) 22412 std::swap(ValueOnZero, Count); 22413 // Check if the value on zero is a constant equal to the bits in the type. 22414 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { 22415 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { 22416 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is 22417 // legal, combine to just cttz. 22418 if ((Count.getOpcode() == ISD::CTTZ || 22419 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && 22420 N0 == Count.getOperand(0) && 22421 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) 22422 return DAG.getNode(ISD::CTTZ, DL, VT, N0); 22423 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is 22424 // legal, combine to just ctlz. 22425 if ((Count.getOpcode() == ISD::CTLZ || 22426 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && 22427 N0 == Count.getOperand(0) && 22428 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) 22429 return DAG.getNode(ISD::CTLZ, DL, VT, N0); 22430 } 22431 } 22432 } 22433 22434 return SDValue(); 22435 } 22436 22437 /// This is a stub for TargetLowering::SimplifySetCC. 22438 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 22439 ISD::CondCode Cond, const SDLoc &DL, 22440 bool foldBooleans) { 22441 TargetLowering::DAGCombinerInfo 22442 DagCombineInfo(DAG, Level, false, this); 22443 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 22444 } 22445 22446 /// Given an ISD::SDIV node expressing a divide by constant, return 22447 /// a DAG expression to select that will generate the same value by multiplying 22448 /// by a magic number. 22449 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 22450 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 22451 // when optimising for minimum size, we don't want to expand a div to a mul 22452 // and a shift. 22453 if (DAG.getMachineFunction().getFunction().hasMinSize()) 22454 return SDValue(); 22455 22456 SmallVector<SDNode *, 8> Built; 22457 if (SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, Built)) { 22458 for (SDNode *N : Built) 22459 AddToWorklist(N); 22460 return S; 22461 } 22462 22463 return SDValue(); 22464 } 22465 22466 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 22467 /// DAG expression that will generate the same value by right shifting. 22468 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 22469 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 22470 if (!C) 22471 return SDValue(); 22472 22473 // Avoid division by zero. 22474 if (C->isNullValue()) 22475 return SDValue(); 22476 22477 SmallVector<SDNode *, 8> Built; 22478 if (SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, Built)) { 22479 for (SDNode *N : Built) 22480 AddToWorklist(N); 22481 return S; 22482 } 22483 22484 return SDValue(); 22485 } 22486 22487 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 22488 /// expression that will generate the same value by multiplying by a magic 22489 /// number. 22490 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 22491 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 22492 // when optimising for minimum size, we don't want to expand a div to a mul 22493 // and a shift. 22494 if (DAG.getMachineFunction().getFunction().hasMinSize()) 22495 return SDValue(); 22496 22497 SmallVector<SDNode *, 8> Built; 22498 if (SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, Built)) { 22499 for (SDNode *N : Built) 22500 AddToWorklist(N); 22501 return S; 22502 } 22503 22504 return SDValue(); 22505 } 22506 22507 /// Determines the LogBase2 value for a non-null input value using the 22508 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V). 22509 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) { 22510 EVT VT = V.getValueType(); 22511 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V); 22512 SDValue Base = DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT); 22513 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz); 22514 return LogBase2; 22515 } 22516 22517 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 22518 /// For the reciprocal, we need to find the zero of the function: 22519 /// F(X) = A X - 1 [which has a zero at X = 1/A] 22520 /// => 22521 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 22522 /// does not require additional intermediate precision] 22523 /// For the last iteration, put numerator N into it to gain more precision: 22524 /// Result = N X_i + X_i (N - N A X_i) 22525 SDValue DAGCombiner::BuildDivEstimate(SDValue N, SDValue Op, 22526 SDNodeFlags Flags) { 22527 if (LegalDAG) 22528 return SDValue(); 22529 22530 // TODO: Handle half and/or extended types? 22531 EVT VT = Op.getValueType(); 22532 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 22533 return SDValue(); 22534 22535 // If estimates are explicitly disabled for this function, we're done. 22536 MachineFunction &MF = DAG.getMachineFunction(); 22537 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF); 22538 if (Enabled == TLI.ReciprocalEstimate::Disabled) 22539 return SDValue(); 22540 22541 // Estimates may be explicitly enabled for this type with a custom number of 22542 // refinement steps. 22543 int Iterations = TLI.getDivRefinementSteps(VT, MF); 22544 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) { 22545 AddToWorklist(Est.getNode()); 22546 22547 SDLoc DL(Op); 22548 if (Iterations) { 22549 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 22550 22551 // Newton iterations: Est = Est + Est (N - Arg * Est) 22552 // If this is the last iteration, also multiply by the numerator. 22553 for (int i = 0; i < Iterations; ++i) { 22554 SDValue MulEst = Est; 22555 22556 if (i == Iterations - 1) { 22557 MulEst = DAG.getNode(ISD::FMUL, DL, VT, N, Est, Flags); 22558 AddToWorklist(MulEst.getNode()); 22559 } 22560 22561 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, MulEst, Flags); 22562 AddToWorklist(NewEst.getNode()); 22563 22564 NewEst = DAG.getNode(ISD::FSUB, DL, VT, 22565 (i == Iterations - 1 ? N : FPOne), NewEst, Flags); 22566 AddToWorklist(NewEst.getNode()); 22567 22568 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 22569 AddToWorklist(NewEst.getNode()); 22570 22571 Est = DAG.getNode(ISD::FADD, DL, VT, MulEst, NewEst, Flags); 22572 AddToWorklist(Est.getNode()); 22573 } 22574 } else { 22575 // If no iterations are available, multiply with N. 22576 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, N, Flags); 22577 AddToWorklist(Est.getNode()); 22578 } 22579 22580 return Est; 22581 } 22582 22583 return SDValue(); 22584 } 22585 22586 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 22587 /// For the reciprocal sqrt, we need to find the zero of the function: 22588 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 22589 /// => 22590 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 22591 /// As a result, we precompute A/2 prior to the iteration loop. 22592 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est, 22593 unsigned Iterations, 22594 SDNodeFlags Flags, bool Reciprocal) { 22595 EVT VT = Arg.getValueType(); 22596 SDLoc DL(Arg); 22597 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 22598 22599 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 22600 // this entire sequence requires only one FP constant. 22601 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 22602 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 22603 22604 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 22605 for (unsigned i = 0; i < Iterations; ++i) { 22606 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 22607 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 22608 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 22609 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 22610 } 22611 22612 // If non-reciprocal square root is requested, multiply the result by Arg. 22613 if (!Reciprocal) 22614 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 22615 22616 return Est; 22617 } 22618 22619 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 22620 /// For the reciprocal sqrt, we need to find the zero of the function: 22621 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 22622 /// => 22623 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 22624 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est, 22625 unsigned Iterations, 22626 SDNodeFlags Flags, bool Reciprocal) { 22627 EVT VT = Arg.getValueType(); 22628 SDLoc DL(Arg); 22629 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 22630 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 22631 22632 // This routine must enter the loop below to work correctly 22633 // when (Reciprocal == false). 22634 assert(Iterations > 0); 22635 22636 // Newton iterations for reciprocal square root: 22637 // E = (E * -0.5) * ((A * E) * E + -3.0) 22638 for (unsigned i = 0; i < Iterations; ++i) { 22639 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags); 22640 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags); 22641 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags); 22642 22643 // When calculating a square root at the last iteration build: 22644 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0) 22645 // (notice a common subexpression) 22646 SDValue LHS; 22647 if (Reciprocal || (i + 1) < Iterations) { 22648 // RSQRT: LHS = (E * -0.5) 22649 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 22650 } else { 22651 // SQRT: LHS = (A * E) * -0.5 22652 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags); 22653 } 22654 22655 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags); 22656 } 22657 22658 return Est; 22659 } 22660 22661 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case 22662 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if 22663 /// Op can be zero. 22664 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, 22665 bool Reciprocal) { 22666 if (LegalDAG) 22667 return SDValue(); 22668 22669 // TODO: Handle half and/or extended types? 22670 EVT VT = Op.getValueType(); 22671 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 22672 return SDValue(); 22673 22674 // If estimates are explicitly disabled for this function, we're done. 22675 MachineFunction &MF = DAG.getMachineFunction(); 22676 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF); 22677 if (Enabled == TLI.ReciprocalEstimate::Disabled) 22678 return SDValue(); 22679 22680 // Estimates may be explicitly enabled for this type with a custom number of 22681 // refinement steps. 22682 int Iterations = TLI.getSqrtRefinementSteps(VT, MF); 22683 22684 bool UseOneConstNR = false; 22685 if (SDValue Est = 22686 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR, 22687 Reciprocal)) { 22688 AddToWorklist(Est.getNode()); 22689 22690 if (Iterations) 22691 Est = UseOneConstNR 22692 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal) 22693 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal); 22694 if (!Reciprocal) { 22695 SDLoc DL(Op); 22696 // Try the target specific test first. 22697 SDValue Test = TLI.getSqrtInputTest(Op, DAG, DAG.getDenormalMode(VT)); 22698 22699 // The estimate is now completely wrong if the input was exactly 0.0 or 22700 // possibly a denormal. Force the answer to 0.0 or value provided by 22701 // target for those cases. 22702 Est = DAG.getNode( 22703 Test.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, 22704 Test, TLI.getSqrtResultForDenormInput(Op, DAG), Est); 22705 } 22706 return Est; 22707 } 22708 22709 return SDValue(); 22710 } 22711 22712 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) { 22713 return buildSqrtEstimateImpl(Op, Flags, true); 22714 } 22715 22716 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) { 22717 return buildSqrtEstimateImpl(Op, Flags, false); 22718 } 22719 22720 /// Return true if there is any possibility that the two addresses overlap. 22721 bool DAGCombiner::isAlias(SDNode *Op0, SDNode *Op1) const { 22722 22723 struct MemUseCharacteristics { 22724 bool IsVolatile; 22725 bool IsAtomic; 22726 SDValue BasePtr; 22727 int64_t Offset; 22728 Optional<int64_t> NumBytes; 22729 MachineMemOperand *MMO; 22730 }; 22731 22732 auto getCharacteristics = [](SDNode *N) -> MemUseCharacteristics { 22733 if (const auto *LSN = dyn_cast<LSBaseSDNode>(N)) { 22734 int64_t Offset = 0; 22735 if (auto *C = dyn_cast<ConstantSDNode>(LSN->getOffset())) 22736 Offset = (LSN->getAddressingMode() == ISD::PRE_INC) 22737 ? C->getSExtValue() 22738 : (LSN->getAddressingMode() == ISD::PRE_DEC) 22739 ? -1 * C->getSExtValue() 22740 : 0; 22741 uint64_t Size = 22742 MemoryLocation::getSizeOrUnknown(LSN->getMemoryVT().getStoreSize()); 22743 return {LSN->isVolatile(), LSN->isAtomic(), LSN->getBasePtr(), 22744 Offset /*base offset*/, 22745 Optional<int64_t>(Size), 22746 LSN->getMemOperand()}; 22747 } 22748 if (const auto *LN = cast<LifetimeSDNode>(N)) 22749 return {false /*isVolatile*/, /*isAtomic*/ false, LN->getOperand(1), 22750 (LN->hasOffset()) ? LN->getOffset() : 0, 22751 (LN->hasOffset()) ? Optional<int64_t>(LN->getSize()) 22752 : Optional<int64_t>(), 22753 (MachineMemOperand *)nullptr}; 22754 // Default. 22755 return {false /*isvolatile*/, /*isAtomic*/ false, SDValue(), 22756 (int64_t)0 /*offset*/, 22757 Optional<int64_t>() /*size*/, (MachineMemOperand *)nullptr}; 22758 }; 22759 22760 MemUseCharacteristics MUC0 = getCharacteristics(Op0), 22761 MUC1 = getCharacteristics(Op1); 22762 22763 // If they are to the same address, then they must be aliases. 22764 if (MUC0.BasePtr.getNode() && MUC0.BasePtr == MUC1.BasePtr && 22765 MUC0.Offset == MUC1.Offset) 22766 return true; 22767 22768 // If they are both volatile then they cannot be reordered. 22769 if (MUC0.IsVolatile && MUC1.IsVolatile) 22770 return true; 22771 22772 // Be conservative about atomics for the moment 22773 // TODO: This is way overconservative for unordered atomics (see D66309) 22774 if (MUC0.IsAtomic && MUC1.IsAtomic) 22775 return true; 22776 22777 if (MUC0.MMO && MUC1.MMO) { 22778 if ((MUC0.MMO->isInvariant() && MUC1.MMO->isStore()) || 22779 (MUC1.MMO->isInvariant() && MUC0.MMO->isStore())) 22780 return false; 22781 } 22782 22783 // Try to prove that there is aliasing, or that there is no aliasing. Either 22784 // way, we can return now. If nothing can be proved, proceed with more tests. 22785 bool IsAlias; 22786 if (BaseIndexOffset::computeAliasing(Op0, MUC0.NumBytes, Op1, MUC1.NumBytes, 22787 DAG, IsAlias)) 22788 return IsAlias; 22789 22790 // The following all rely on MMO0 and MMO1 being valid. Fail conservatively if 22791 // either are not known. 22792 if (!MUC0.MMO || !MUC1.MMO) 22793 return true; 22794 22795 // If one operation reads from invariant memory, and the other may store, they 22796 // cannot alias. These should really be checking the equivalent of mayWrite, 22797 // but it only matters for memory nodes other than load /store. 22798 if ((MUC0.MMO->isInvariant() && MUC1.MMO->isStore()) || 22799 (MUC1.MMO->isInvariant() && MUC0.MMO->isStore())) 22800 return false; 22801 22802 // If we know required SrcValue1 and SrcValue2 have relatively large 22803 // alignment compared to the size and offset of the access, we may be able 22804 // to prove they do not alias. This check is conservative for now to catch 22805 // cases created by splitting vector types, it only works when the offsets are 22806 // multiples of the size of the data. 22807 int64_t SrcValOffset0 = MUC0.MMO->getOffset(); 22808 int64_t SrcValOffset1 = MUC1.MMO->getOffset(); 22809 Align OrigAlignment0 = MUC0.MMO->getBaseAlign(); 22810 Align OrigAlignment1 = MUC1.MMO->getBaseAlign(); 22811 auto &Size0 = MUC0.NumBytes; 22812 auto &Size1 = MUC1.NumBytes; 22813 if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 && 22814 Size0.hasValue() && Size1.hasValue() && *Size0 == *Size1 && 22815 OrigAlignment0 > *Size0 && SrcValOffset0 % *Size0 == 0 && 22816 SrcValOffset1 % *Size1 == 0) { 22817 int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0.value(); 22818 int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1.value(); 22819 22820 // There is no overlap between these relatively aligned accesses of 22821 // similar size. Return no alias. 22822 if ((OffAlign0 + *Size0) <= OffAlign1 || (OffAlign1 + *Size1) <= OffAlign0) 22823 return false; 22824 } 22825 22826 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 22827 ? CombinerGlobalAA 22828 : DAG.getSubtarget().useAA(); 22829 #ifndef NDEBUG 22830 if (CombinerAAOnlyFunc.getNumOccurrences() && 22831 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 22832 UseAA = false; 22833 #endif 22834 22835 if (UseAA && AA && MUC0.MMO->getValue() && MUC1.MMO->getValue() && 22836 Size0.hasValue() && Size1.hasValue()) { 22837 // Use alias analysis information. 22838 int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1); 22839 int64_t Overlap0 = *Size0 + SrcValOffset0 - MinOffset; 22840 int64_t Overlap1 = *Size1 + SrcValOffset1 - MinOffset; 22841 if (AA->isNoAlias( 22842 MemoryLocation(MUC0.MMO->getValue(), Overlap0, 22843 UseTBAA ? MUC0.MMO->getAAInfo() : AAMDNodes()), 22844 MemoryLocation(MUC1.MMO->getValue(), Overlap1, 22845 UseTBAA ? MUC1.MMO->getAAInfo() : AAMDNodes()))) 22846 return false; 22847 } 22848 22849 // Otherwise we have to assume they alias. 22850 return true; 22851 } 22852 22853 /// Walk up chain skipping non-aliasing memory nodes, 22854 /// looking for aliasing nodes and adding them to the Aliases vector. 22855 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 22856 SmallVectorImpl<SDValue> &Aliases) { 22857 SmallVector<SDValue, 8> Chains; // List of chains to visit. 22858 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 22859 22860 // Get alias information for node. 22861 // TODO: relax aliasing for unordered atomics (see D66309) 22862 const bool IsLoad = isa<LoadSDNode>(N) && cast<LoadSDNode>(N)->isSimple(); 22863 22864 // Starting off. 22865 Chains.push_back(OriginalChain); 22866 unsigned Depth = 0; 22867 22868 // Attempt to improve chain by a single step 22869 std::function<bool(SDValue &)> ImproveChain = [&](SDValue &C) -> bool { 22870 switch (C.getOpcode()) { 22871 case ISD::EntryToken: 22872 // No need to mark EntryToken. 22873 C = SDValue(); 22874 return true; 22875 case ISD::LOAD: 22876 case ISD::STORE: { 22877 // Get alias information for C. 22878 // TODO: Relax aliasing for unordered atomics (see D66309) 22879 bool IsOpLoad = isa<LoadSDNode>(C.getNode()) && 22880 cast<LSBaseSDNode>(C.getNode())->isSimple(); 22881 if ((IsLoad && IsOpLoad) || !isAlias(N, C.getNode())) { 22882 // Look further up the chain. 22883 C = C.getOperand(0); 22884 return true; 22885 } 22886 // Alias, so stop here. 22887 return false; 22888 } 22889 22890 case ISD::CopyFromReg: 22891 // Always forward past past CopyFromReg. 22892 C = C.getOperand(0); 22893 return true; 22894 22895 case ISD::LIFETIME_START: 22896 case ISD::LIFETIME_END: { 22897 // We can forward past any lifetime start/end that can be proven not to 22898 // alias the memory access. 22899 if (!isAlias(N, C.getNode())) { 22900 // Look further up the chain. 22901 C = C.getOperand(0); 22902 return true; 22903 } 22904 return false; 22905 } 22906 default: 22907 return false; 22908 } 22909 }; 22910 22911 // Look at each chain and determine if it is an alias. If so, add it to the 22912 // aliases list. If not, then continue up the chain looking for the next 22913 // candidate. 22914 while (!Chains.empty()) { 22915 SDValue Chain = Chains.pop_back_val(); 22916 22917 // Don't bother if we've seen Chain before. 22918 if (!Visited.insert(Chain.getNode()).second) 22919 continue; 22920 22921 // For TokenFactor nodes, look at each operand and only continue up the 22922 // chain until we reach the depth limit. 22923 // 22924 // FIXME: The depth check could be made to return the last non-aliasing 22925 // chain we found before we hit a tokenfactor rather than the original 22926 // chain. 22927 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 22928 Aliases.clear(); 22929 Aliases.push_back(OriginalChain); 22930 return; 22931 } 22932 22933 if (Chain.getOpcode() == ISD::TokenFactor) { 22934 // We have to check each of the operands of the token factor for "small" 22935 // token factors, so we queue them up. Adding the operands to the queue 22936 // (stack) in reverse order maintains the original order and increases the 22937 // likelihood that getNode will find a matching token factor (CSE.) 22938 if (Chain.getNumOperands() > 16) { 22939 Aliases.push_back(Chain); 22940 continue; 22941 } 22942 for (unsigned n = Chain.getNumOperands(); n;) 22943 Chains.push_back(Chain.getOperand(--n)); 22944 ++Depth; 22945 continue; 22946 } 22947 // Everything else 22948 if (ImproveChain(Chain)) { 22949 // Updated Chain Found, Consider new chain if one exists. 22950 if (Chain.getNode()) 22951 Chains.push_back(Chain); 22952 ++Depth; 22953 continue; 22954 } 22955 // No Improved Chain Possible, treat as Alias. 22956 Aliases.push_back(Chain); 22957 } 22958 } 22959 22960 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 22961 /// (aliasing node.) 22962 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 22963 if (OptLevel == CodeGenOpt::None) 22964 return OldChain; 22965 22966 // Ops for replacing token factor. 22967 SmallVector<SDValue, 8> Aliases; 22968 22969 // Accumulate all the aliases to this node. 22970 GatherAllAliases(N, OldChain, Aliases); 22971 22972 // If no operands then chain to entry token. 22973 if (Aliases.size() == 0) 22974 return DAG.getEntryNode(); 22975 22976 // If a single operand then chain to it. We don't need to revisit it. 22977 if (Aliases.size() == 1) 22978 return Aliases[0]; 22979 22980 // Construct a custom tailored token factor. 22981 return DAG.getTokenFactor(SDLoc(N), Aliases); 22982 } 22983 22984 namespace { 22985 // TODO: Replace with with std::monostate when we move to C++17. 22986 struct UnitT { } Unit; 22987 bool operator==(const UnitT &, const UnitT &) { return true; } 22988 bool operator!=(const UnitT &, const UnitT &) { return false; } 22989 } // namespace 22990 22991 // This function tries to collect a bunch of potentially interesting 22992 // nodes to improve the chains of, all at once. This might seem 22993 // redundant, as this function gets called when visiting every store 22994 // node, so why not let the work be done on each store as it's visited? 22995 // 22996 // I believe this is mainly important because mergeConsecutiveStores 22997 // is unable to deal with merging stores of different sizes, so unless 22998 // we improve the chains of all the potential candidates up-front 22999 // before running mergeConsecutiveStores, it might only see some of 23000 // the nodes that will eventually be candidates, and then not be able 23001 // to go from a partially-merged state to the desired final 23002 // fully-merged state. 23003 23004 bool DAGCombiner::parallelizeChainedStores(StoreSDNode *St) { 23005 SmallVector<StoreSDNode *, 8> ChainedStores; 23006 StoreSDNode *STChain = St; 23007 // Intervals records which offsets from BaseIndex have been covered. In 23008 // the common case, every store writes to the immediately previous address 23009 // space and thus merged with the previous interval at insertion time. 23010 23011 using IMap = 23012 llvm::IntervalMap<int64_t, UnitT, 8, IntervalMapHalfOpenInfo<int64_t>>; 23013 IMap::Allocator A; 23014 IMap Intervals(A); 23015 23016 // This holds the base pointer, index, and the offset in bytes from the base 23017 // pointer. 23018 const BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG); 23019 23020 // We must have a base and an offset. 23021 if (!BasePtr.getBase().getNode()) 23022 return false; 23023 23024 // Do not handle stores to undef base pointers. 23025 if (BasePtr.getBase().isUndef()) 23026 return false; 23027 23028 // BaseIndexOffset assumes that offsets are fixed-size, which 23029 // is not valid for scalable vectors where the offsets are 23030 // scaled by `vscale`, so bail out early. 23031 if (St->getMemoryVT().isScalableVector()) 23032 return false; 23033 23034 // Add ST's interval. 23035 Intervals.insert(0, (St->getMemoryVT().getSizeInBits() + 7) / 8, Unit); 23036 23037 while (StoreSDNode *Chain = dyn_cast<StoreSDNode>(STChain->getChain())) { 23038 if (Chain->getMemoryVT().isScalableVector()) 23039 return false; 23040 23041 // If the chain has more than one use, then we can't reorder the mem ops. 23042 if (!SDValue(Chain, 0)->hasOneUse()) 23043 break; 23044 // TODO: Relax for unordered atomics (see D66309) 23045 if (!Chain->isSimple() || Chain->isIndexed()) 23046 break; 23047 23048 // Find the base pointer and offset for this memory node. 23049 const BaseIndexOffset Ptr = BaseIndexOffset::match(Chain, DAG); 23050 // Check that the base pointer is the same as the original one. 23051 int64_t Offset; 23052 if (!BasePtr.equalBaseIndex(Ptr, DAG, Offset)) 23053 break; 23054 int64_t Length = (Chain->getMemoryVT().getSizeInBits() + 7) / 8; 23055 // Make sure we don't overlap with other intervals by checking the ones to 23056 // the left or right before inserting. 23057 auto I = Intervals.find(Offset); 23058 // If there's a next interval, we should end before it. 23059 if (I != Intervals.end() && I.start() < (Offset + Length)) 23060 break; 23061 // If there's a previous interval, we should start after it. 23062 if (I != Intervals.begin() && (--I).stop() <= Offset) 23063 break; 23064 Intervals.insert(Offset, Offset + Length, Unit); 23065 23066 ChainedStores.push_back(Chain); 23067 STChain = Chain; 23068 } 23069 23070 // If we didn't find a chained store, exit. 23071 if (ChainedStores.size() == 0) 23072 return false; 23073 23074 // Improve all chained stores (St and ChainedStores members) starting from 23075 // where the store chain ended and return single TokenFactor. 23076 SDValue NewChain = STChain->getChain(); 23077 SmallVector<SDValue, 8> TFOps; 23078 for (unsigned I = ChainedStores.size(); I;) { 23079 StoreSDNode *S = ChainedStores[--I]; 23080 SDValue BetterChain = FindBetterChain(S, NewChain); 23081 S = cast<StoreSDNode>(DAG.UpdateNodeOperands( 23082 S, BetterChain, S->getOperand(1), S->getOperand(2), S->getOperand(3))); 23083 TFOps.push_back(SDValue(S, 0)); 23084 ChainedStores[I] = S; 23085 } 23086 23087 // Improve St's chain. Use a new node to avoid creating a loop from CombineTo. 23088 SDValue BetterChain = FindBetterChain(St, NewChain); 23089 SDValue NewST; 23090 if (St->isTruncatingStore()) 23091 NewST = DAG.getTruncStore(BetterChain, SDLoc(St), St->getValue(), 23092 St->getBasePtr(), St->getMemoryVT(), 23093 St->getMemOperand()); 23094 else 23095 NewST = DAG.getStore(BetterChain, SDLoc(St), St->getValue(), 23096 St->getBasePtr(), St->getMemOperand()); 23097 23098 TFOps.push_back(NewST); 23099 23100 // If we improved every element of TFOps, then we've lost the dependence on 23101 // NewChain to successors of St and we need to add it back to TFOps. Do so at 23102 // the beginning to keep relative order consistent with FindBetterChains. 23103 auto hasImprovedChain = [&](SDValue ST) -> bool { 23104 return ST->getOperand(0) != NewChain; 23105 }; 23106 bool AddNewChain = llvm::all_of(TFOps, hasImprovedChain); 23107 if (AddNewChain) 23108 TFOps.insert(TFOps.begin(), NewChain); 23109 23110 SDValue TF = DAG.getTokenFactor(SDLoc(STChain), TFOps); 23111 CombineTo(St, TF); 23112 23113 // Add TF and its operands to the worklist. 23114 AddToWorklist(TF.getNode()); 23115 for (const SDValue &Op : TF->ops()) 23116 AddToWorklist(Op.getNode()); 23117 AddToWorklist(STChain); 23118 return true; 23119 } 23120 23121 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) { 23122 if (OptLevel == CodeGenOpt::None) 23123 return false; 23124 23125 const BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG); 23126 23127 // We must have a base and an offset. 23128 if (!BasePtr.getBase().getNode()) 23129 return false; 23130 23131 // Do not handle stores to undef base pointers. 23132 if (BasePtr.getBase().isUndef()) 23133 return false; 23134 23135 // Directly improve a chain of disjoint stores starting at St. 23136 if (parallelizeChainedStores(St)) 23137 return true; 23138 23139 // Improve St's Chain.. 23140 SDValue BetterChain = FindBetterChain(St, St->getChain()); 23141 if (St->getChain() != BetterChain) { 23142 replaceStoreChain(St, BetterChain); 23143 return true; 23144 } 23145 return false; 23146 } 23147 23148 /// This is the entry point for the file. 23149 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA, 23150 CodeGenOpt::Level OptLevel) { 23151 /// This is the main entry point to this class. 23152 DAGCombiner(*this, AA, OptLevel).Run(Level); 23153 } 23154