1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11 // both before and after the DAG is legalized.
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetLowering.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
42 #define DEBUG_TYPE "dagcombine"
44 STATISTIC(NodesCombined , "Number of dag nodes combined");
45 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
46 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
47 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
48 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
49 STATISTIC(SlicedLoads, "Number of load sliced");
53 CombinerAA("combiner-alias-analysis", cl::Hidden,
54 cl::desc("Enable DAG combiner alias-analysis heuristics"));
57 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
58 cl::desc("Enable DAG combiner's use of IR alias analysis"));
61 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
62 cl::desc("Enable DAG combiner's use of TBAA"));
65 static cl::opt<std::string>
66 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
67 cl::desc("Only use DAG-combiner alias analysis in this"
71 /// Hidden option to stress test load slicing, i.e., when this option
72 /// is enabled, load slicing bypasses most of its profitability guards.
74 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
75 cl::desc("Bypass the profitability model of load "
79 //------------------------------ DAGCombiner ---------------------------------//
83 const TargetLowering &TLI;
85 CodeGenOpt::Level OptLevel;
90 // Worklist of all of the nodes that need to be simplified.
92 // This has the semantics that when adding to the worklist,
93 // the item added must be next to be processed. It should
94 // also only appear once. The naive approach to this takes
97 // To reduce the insert/remove time to logarithmic, we use
98 // a set and a vector to maintain our worklist.
100 // The set contains the items on the worklist, but does not
101 // maintain the order they should be visited.
103 // The vector maintains the order nodes should be visited, but may
104 // contain duplicate or removed nodes. When choosing a node to
105 // visit, we pop off the order stack until we find an item that is
106 // also in the contents set. All operations are O(log N).
107 SmallPtrSet<SDNode*, 64> WorkListContents;
108 SmallVector<SDNode*, 64> WorkListOrder;
110 // AA - Used for DAG load/store alias analysis.
113 /// AddUsersToWorkList - When an instruction is simplified, add all users of
114 /// the instruction to the work lists because they might get more simplified
117 void AddUsersToWorkList(SDNode *N) {
118 for (SDNode *Node : N->uses())
122 /// visit - call the node-specific routine that knows how to fold each
123 /// particular type of node.
124 SDValue visit(SDNode *N);
127 /// AddToWorkList - Add to the work list making sure its instance is at the
128 /// back (next to be processed.)
129 void AddToWorkList(SDNode *N) {
130 WorkListContents.insert(N);
131 WorkListOrder.push_back(N);
134 /// removeFromWorkList - remove all instances of N from the worklist.
136 void removeFromWorkList(SDNode *N) {
137 WorkListContents.erase(N);
140 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
143 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
144 return CombineTo(N, &Res, 1, AddTo);
147 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
149 SDValue To[] = { Res0, Res1 };
150 return CombineTo(N, To, 2, AddTo);
153 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
157 /// SimplifyDemandedBits - Check the specified integer node value to see if
158 /// it can be simplified or if things it uses can be simplified by bit
159 /// propagation. If so, return true.
160 bool SimplifyDemandedBits(SDValue Op) {
161 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
162 APInt Demanded = APInt::getAllOnesValue(BitWidth);
163 return SimplifyDemandedBits(Op, Demanded);
166 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
168 bool CombineToPreIndexedLoadStore(SDNode *N);
169 bool CombineToPostIndexedLoadStore(SDNode *N);
170 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
171 bool SliceUpLoad(SDNode *N);
173 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
174 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
175 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
176 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
177 SDValue PromoteIntBinOp(SDValue Op);
178 SDValue PromoteIntShiftOp(SDValue Op);
179 SDValue PromoteExtend(SDValue Op);
180 bool PromoteLoad(SDValue Op);
182 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
183 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
184 ISD::NodeType ExtType);
186 /// combine - call the node-specific routine that knows how to fold each
187 /// particular type of node. If that doesn't do anything, try the
188 /// target-specific DAG combines.
189 SDValue combine(SDNode *N);
191 // Visitation implementation - Implement dag node combining for different
192 // node types. The semantics are as follows:
194 // SDValue.getNode() == 0 - No change was made
195 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
196 // otherwise - N should be replaced by the returned Operand.
198 SDValue visitTokenFactor(SDNode *N);
199 SDValue visitMERGE_VALUES(SDNode *N);
200 SDValue visitADD(SDNode *N);
201 SDValue visitSUB(SDNode *N);
202 SDValue visitADDC(SDNode *N);
203 SDValue visitSUBC(SDNode *N);
204 SDValue visitADDE(SDNode *N);
205 SDValue visitSUBE(SDNode *N);
206 SDValue visitMUL(SDNode *N);
207 SDValue visitSDIV(SDNode *N);
208 SDValue visitUDIV(SDNode *N);
209 SDValue visitSREM(SDNode *N);
210 SDValue visitUREM(SDNode *N);
211 SDValue visitMULHU(SDNode *N);
212 SDValue visitMULHS(SDNode *N);
213 SDValue visitSMUL_LOHI(SDNode *N);
214 SDValue visitUMUL_LOHI(SDNode *N);
215 SDValue visitSMULO(SDNode *N);
216 SDValue visitUMULO(SDNode *N);
217 SDValue visitSDIVREM(SDNode *N);
218 SDValue visitUDIVREM(SDNode *N);
219 SDValue visitAND(SDNode *N);
220 SDValue visitOR(SDNode *N);
221 SDValue visitXOR(SDNode *N);
222 SDValue SimplifyVBinOp(SDNode *N);
223 SDValue SimplifyVUnaryOp(SDNode *N);
224 SDValue visitSHL(SDNode *N);
225 SDValue visitSRA(SDNode *N);
226 SDValue visitSRL(SDNode *N);
227 SDValue visitRotate(SDNode *N);
228 SDValue visitCTLZ(SDNode *N);
229 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
230 SDValue visitCTTZ(SDNode *N);
231 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
232 SDValue visitCTPOP(SDNode *N);
233 SDValue visitSELECT(SDNode *N);
234 SDValue visitVSELECT(SDNode *N);
235 SDValue visitSELECT_CC(SDNode *N);
236 SDValue visitSETCC(SDNode *N);
237 SDValue visitSIGN_EXTEND(SDNode *N);
238 SDValue visitZERO_EXTEND(SDNode *N);
239 SDValue visitANY_EXTEND(SDNode *N);
240 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
241 SDValue visitTRUNCATE(SDNode *N);
242 SDValue visitBITCAST(SDNode *N);
243 SDValue visitBUILD_PAIR(SDNode *N);
244 SDValue visitFADD(SDNode *N);
245 SDValue visitFSUB(SDNode *N);
246 SDValue visitFMUL(SDNode *N);
247 SDValue visitFMA(SDNode *N);
248 SDValue visitFDIV(SDNode *N);
249 SDValue visitFREM(SDNode *N);
250 SDValue visitFCOPYSIGN(SDNode *N);
251 SDValue visitSINT_TO_FP(SDNode *N);
252 SDValue visitUINT_TO_FP(SDNode *N);
253 SDValue visitFP_TO_SINT(SDNode *N);
254 SDValue visitFP_TO_UINT(SDNode *N);
255 SDValue visitFP_ROUND(SDNode *N);
256 SDValue visitFP_ROUND_INREG(SDNode *N);
257 SDValue visitFP_EXTEND(SDNode *N);
258 SDValue visitFNEG(SDNode *N);
259 SDValue visitFABS(SDNode *N);
260 SDValue visitFCEIL(SDNode *N);
261 SDValue visitFTRUNC(SDNode *N);
262 SDValue visitFFLOOR(SDNode *N);
263 SDValue visitBRCOND(SDNode *N);
264 SDValue visitBR_CC(SDNode *N);
265 SDValue visitLOAD(SDNode *N);
266 SDValue visitSTORE(SDNode *N);
267 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
268 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
269 SDValue visitBUILD_VECTOR(SDNode *N);
270 SDValue visitCONCAT_VECTORS(SDNode *N);
271 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
272 SDValue visitVECTOR_SHUFFLE(SDNode *N);
273 SDValue visitINSERT_SUBVECTOR(SDNode *N);
275 SDValue XformToShuffleWithZero(SDNode *N);
276 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
278 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
280 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
281 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
282 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
283 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
284 SDValue N3, ISD::CondCode CC,
285 bool NotExtCompare = false);
286 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
287 SDLoc DL, bool foldBooleans = true);
289 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
291 bool isOneUseSetCC(SDValue N) const;
293 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
295 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
296 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
297 SDValue BuildSDIV(SDNode *N);
298 SDValue BuildUDIV(SDNode *N);
299 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
300 bool DemandHighBits = true);
301 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
302 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
303 SDValue InnerPos, SDValue InnerNeg,
304 unsigned PosOpcode, unsigned NegOpcode,
306 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
307 SDValue ReduceLoadWidth(SDNode *N);
308 SDValue ReduceLoadOpStoreWidth(SDNode *N);
309 SDValue TransformFPLoadStorePair(SDNode *N);
310 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
311 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
313 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
315 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
316 /// looking for aliasing nodes and adding them to the Aliases vector.
317 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
318 SmallVectorImpl<SDValue> &Aliases);
320 /// isAlias - Return true if there is any possibility that the two addresses
322 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
324 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
325 /// looking for a better chain (aliasing node.)
326 SDValue FindBetterChain(SDNode *N, SDValue Chain);
328 /// Merge consecutive store operations into a wide store.
329 /// This optimization uses wide integers or vectors when possible.
330 /// \return True if some memory operations were changed.
331 bool MergeConsecutiveStores(StoreSDNode *N);
333 /// \brief Try to transform a truncation where C is a constant:
334 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
336 /// \p N needs to be a truncation and its first operand an AND. Other
337 /// requirements are checked by the function (e.g. that trunc is
338 /// single-use) and if missed an empty SDValue is returned.
339 SDValue distributeTruncateThroughAnd(SDNode *N);
342 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
343 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
344 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
345 AttributeSet FnAttrs =
346 DAG.getMachineFunction().getFunction()->getAttributes();
348 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
349 Attribute::OptimizeForSize) ||
350 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
353 /// Run - runs the dag combiner on all nodes in the work list
354 void Run(CombineLevel AtLevel);
356 SelectionDAG &getDAG() const { return DAG; }
358 /// getShiftAmountTy - Returns a type large enough to hold any valid
359 /// shift amount - before type legalization these can be huge.
360 EVT getShiftAmountTy(EVT LHSTy) {
361 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
362 if (LHSTy.isVector())
364 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
365 : TLI.getPointerTy();
368 /// isTypeLegal - This method returns true if we are running before type
369 /// legalization or if the specified VT is legal.
370 bool isTypeLegal(const EVT &VT) {
371 if (!LegalTypes) return true;
372 return TLI.isTypeLegal(VT);
375 /// getSetCCResultType - Convenience wrapper around
376 /// TargetLowering::getSetCCResultType
377 EVT getSetCCResultType(EVT VT) const {
378 return TLI.getSetCCResultType(*DAG.getContext(), VT);
385 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
386 /// nodes from the worklist.
387 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
390 explicit WorkListRemover(DAGCombiner &dc)
391 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
393 void NodeDeleted(SDNode *N, SDNode *E) override {
394 DC.removeFromWorkList(N);
399 //===----------------------------------------------------------------------===//
400 // TargetLowering::DAGCombinerInfo implementation
401 //===----------------------------------------------------------------------===//
403 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
404 ((DAGCombiner*)DC)->AddToWorkList(N);
407 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
408 ((DAGCombiner*)DC)->removeFromWorkList(N);
411 SDValue TargetLowering::DAGCombinerInfo::
412 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
413 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
416 SDValue TargetLowering::DAGCombinerInfo::
417 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
418 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
422 SDValue TargetLowering::DAGCombinerInfo::
423 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
424 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
427 void TargetLowering::DAGCombinerInfo::
428 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
429 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
432 //===----------------------------------------------------------------------===//
434 //===----------------------------------------------------------------------===//
436 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
437 /// specified expression for the same cost as the expression itself, or 2 if we
438 /// can compute the negated form more cheaply than the expression itself.
439 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
440 const TargetLowering &TLI,
441 const TargetOptions *Options,
442 unsigned Depth = 0) {
443 // fneg is removable even if it has multiple uses.
444 if (Op.getOpcode() == ISD::FNEG) return 2;
446 // Don't allow anything with multiple uses.
447 if (!Op.hasOneUse()) return 0;
449 // Don't recurse exponentially.
450 if (Depth > 6) return 0;
452 switch (Op.getOpcode()) {
453 default: return false;
454 case ISD::ConstantFP:
455 // Don't invert constant FP values after legalize. The negated constant
456 // isn't necessarily legal.
457 return LegalOperations ? 0 : 1;
459 // FIXME: determine better conditions for this xform.
460 if (!Options->UnsafeFPMath) return 0;
462 // After operation legalization, it might not be legal to create new FSUBs.
463 if (LegalOperations &&
464 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
467 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
468 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
471 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
472 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
475 // We can't turn -(A-B) into B-A when we honor signed zeros.
476 if (!Options->UnsafeFPMath) return 0;
478 // fold (fneg (fsub A, B)) -> (fsub B, A)
483 if (Options->HonorSignDependentRoundingFPMath()) return 0;
485 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
486 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
490 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
496 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
501 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
502 /// returns the newly negated expression.
503 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
504 bool LegalOperations, unsigned Depth = 0) {
505 // fneg is removable even if it has multiple uses.
506 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
508 // Don't allow anything with multiple uses.
509 assert(Op.hasOneUse() && "Unknown reuse!");
511 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
512 switch (Op.getOpcode()) {
513 default: llvm_unreachable("Unknown code");
514 case ISD::ConstantFP: {
515 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
517 return DAG.getConstantFP(V, Op.getValueType());
520 // FIXME: determine better conditions for this xform.
521 assert(DAG.getTarget().Options.UnsafeFPMath);
523 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
524 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
525 DAG.getTargetLoweringInfo(),
526 &DAG.getTarget().Options, Depth+1))
527 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
528 GetNegatedExpression(Op.getOperand(0), DAG,
529 LegalOperations, Depth+1),
531 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
532 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
533 GetNegatedExpression(Op.getOperand(1), DAG,
534 LegalOperations, Depth+1),
537 // We can't turn -(A-B) into B-A when we honor signed zeros.
538 assert(DAG.getTarget().Options.UnsafeFPMath);
540 // fold (fneg (fsub 0, B)) -> B
541 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
542 if (N0CFP->getValueAPF().isZero())
543 return Op.getOperand(1);
545 // fold (fneg (fsub A, B)) -> (fsub B, A)
546 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
547 Op.getOperand(1), Op.getOperand(0));
551 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
553 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
554 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
555 DAG.getTargetLoweringInfo(),
556 &DAG.getTarget().Options, Depth+1))
557 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
558 GetNegatedExpression(Op.getOperand(0), DAG,
559 LegalOperations, Depth+1),
562 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
563 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
565 GetNegatedExpression(Op.getOperand(1), DAG,
566 LegalOperations, Depth+1));
570 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
571 GetNegatedExpression(Op.getOperand(0), DAG,
572 LegalOperations, Depth+1));
574 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
575 GetNegatedExpression(Op.getOperand(0), DAG,
576 LegalOperations, Depth+1),
581 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
582 // that selects between the target values used for true and false, making it
583 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
584 // the appropriate nodes based on the type of node we are checking. This
585 // simplifies life a bit for the callers.
586 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
588 if (N.getOpcode() == ISD::SETCC) {
589 LHS = N.getOperand(0);
590 RHS = N.getOperand(1);
591 CC = N.getOperand(2);
595 if (N.getOpcode() != ISD::SELECT_CC ||
596 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
597 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
600 LHS = N.getOperand(0);
601 RHS = N.getOperand(1);
602 CC = N.getOperand(4);
606 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
607 // one use. If this is true, it allows the users to invert the operation for
608 // free when it is profitable to do so.
609 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
611 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
616 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
617 /// elements are all the same constant or undefined.
618 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
619 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
624 unsigned SplatBitSize;
626 EVT EltVT = N->getValueType(0).getVectorElementType();
627 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
629 EltVT.getSizeInBits() >= SplatBitSize);
632 // \brief Returns the SDNode if it is a constant BuildVector or constant.
633 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
634 if (isa<ConstantSDNode>(N))
636 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
637 if(BV && BV->isConstant())
642 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
644 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
645 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
648 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
649 ConstantSDNode *CN = BV->getConstantSplatValue();
651 // BuildVectors can truncate their operands. Ignore that case here.
652 if (CN && CN->getValueType(0) == N.getValueType().getScalarType())
659 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
660 SDValue N0, SDValue N1) {
661 EVT VT = N0.getValueType();
662 if (N0.getOpcode() == Opc) {
663 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
664 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
665 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
666 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
667 if (!OpNode.getNode())
669 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
671 if (N0.hasOneUse()) {
672 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
674 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
675 if (!OpNode.getNode())
677 AddToWorkList(OpNode.getNode());
678 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
683 if (N1.getOpcode() == Opc) {
684 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
685 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
686 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
687 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
688 if (!OpNode.getNode())
690 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
692 if (N1.hasOneUse()) {
693 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
695 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
696 if (!OpNode.getNode())
698 AddToWorkList(OpNode.getNode());
699 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
707 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
709 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
711 DEBUG(dbgs() << "\nReplacing.1 ";
713 dbgs() << "\nWith: ";
714 To[0].getNode()->dump(&DAG);
715 dbgs() << " and " << NumTo-1 << " other values\n";
716 for (unsigned i = 0, e = NumTo; i != e; ++i)
717 assert((!To[i].getNode() ||
718 N->getValueType(i) == To[i].getValueType()) &&
719 "Cannot combine value to value of different type!"));
720 WorkListRemover DeadNodes(*this);
721 DAG.ReplaceAllUsesWith(N, To);
723 // Push the new nodes and any users onto the worklist
724 for (unsigned i = 0, e = NumTo; i != e; ++i) {
725 if (To[i].getNode()) {
726 AddToWorkList(To[i].getNode());
727 AddUsersToWorkList(To[i].getNode());
732 // Finally, if the node is now dead, remove it from the graph. The node
733 // may not be dead if the replacement process recursively simplified to
734 // something else needing this node.
735 if (N->use_empty()) {
736 // Nodes can be reintroduced into the worklist. Make sure we do not
737 // process a node that has been replaced.
738 removeFromWorkList(N);
740 // Finally, since the node is now dead, remove it from the graph.
743 return SDValue(N, 0);
747 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
748 // Replace all uses. If any nodes become isomorphic to other nodes and
749 // are deleted, make sure to remove them from our worklist.
750 WorkListRemover DeadNodes(*this);
751 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
753 // Push the new node and any (possibly new) users onto the worklist.
754 AddToWorkList(TLO.New.getNode());
755 AddUsersToWorkList(TLO.New.getNode());
757 // Finally, if the node is now dead, remove it from the graph. The node
758 // may not be dead if the replacement process recursively simplified to
759 // something else needing this node.
760 if (TLO.Old.getNode()->use_empty()) {
761 removeFromWorkList(TLO.Old.getNode());
763 // If the operands of this node are only used by the node, they will now
764 // be dead. Make sure to visit them first to delete dead nodes early.
765 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i) {
766 SDNode *Op = TLO.Old.getNode()->getOperand(i).getNode();
767 // For an operand generating multiple values, one of the values may
768 // become dead allowing further simplification (e.g. split index
769 // arithmetic from an indexed load).
770 if (Op->hasOneUse() || Op->getNumValues() > 1)
773 DAG.DeleteNode(TLO.Old.getNode());
777 /// SimplifyDemandedBits - Check the specified integer node value to see if
778 /// it can be simplified or if things it uses can be simplified by bit
779 /// propagation. If so, return true.
780 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
781 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
782 APInt KnownZero, KnownOne;
783 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
787 AddToWorkList(Op.getNode());
789 // Replace the old value with the new one.
791 DEBUG(dbgs() << "\nReplacing.2 ";
792 TLO.Old.getNode()->dump(&DAG);
793 dbgs() << "\nWith: ";
794 TLO.New.getNode()->dump(&DAG);
797 CommitTargetLoweringOpt(TLO);
801 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
803 EVT VT = Load->getValueType(0);
804 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
806 DEBUG(dbgs() << "\nReplacing.9 ";
808 dbgs() << "\nWith: ";
809 Trunc.getNode()->dump(&DAG);
811 WorkListRemover DeadNodes(*this);
812 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
813 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
814 removeFromWorkList(Load);
815 DAG.DeleteNode(Load);
816 AddToWorkList(Trunc.getNode());
819 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
822 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
823 EVT MemVT = LD->getMemoryVT();
824 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
825 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
827 : LD->getExtensionType();
829 return DAG.getExtLoad(ExtType, dl, PVT,
830 LD->getChain(), LD->getBasePtr(),
831 MemVT, LD->getMemOperand());
834 unsigned Opc = Op.getOpcode();
837 case ISD::AssertSext:
838 return DAG.getNode(ISD::AssertSext, dl, PVT,
839 SExtPromoteOperand(Op.getOperand(0), PVT),
841 case ISD::AssertZext:
842 return DAG.getNode(ISD::AssertZext, dl, PVT,
843 ZExtPromoteOperand(Op.getOperand(0), PVT),
845 case ISD::Constant: {
847 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
848 return DAG.getNode(ExtOpc, dl, PVT, Op);
852 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
854 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
857 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
858 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
860 EVT OldVT = Op.getValueType();
862 bool Replace = false;
863 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
864 if (!NewOp.getNode())
866 AddToWorkList(NewOp.getNode());
869 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
870 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
871 DAG.getValueType(OldVT));
874 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
875 EVT OldVT = Op.getValueType();
877 bool Replace = false;
878 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
879 if (!NewOp.getNode())
881 AddToWorkList(NewOp.getNode());
884 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
885 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
888 /// PromoteIntBinOp - Promote the specified integer binary operation if the
889 /// target indicates it is beneficial. e.g. On x86, it's usually better to
890 /// promote i16 operations to i32 since i16 instructions are longer.
891 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
892 if (!LegalOperations)
895 EVT VT = Op.getValueType();
896 if (VT.isVector() || !VT.isInteger())
899 // If operation type is 'undesirable', e.g. i16 on x86, consider
901 unsigned Opc = Op.getOpcode();
902 if (TLI.isTypeDesirableForOp(Opc, VT))
906 // Consult target whether it is a good idea to promote this operation and
907 // what's the right type to promote it to.
908 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
909 assert(PVT != VT && "Don't know what type to promote to!");
911 bool Replace0 = false;
912 SDValue N0 = Op.getOperand(0);
913 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
917 bool Replace1 = false;
918 SDValue N1 = Op.getOperand(1);
923 NN1 = PromoteOperand(N1, PVT, Replace1);
928 AddToWorkList(NN0.getNode());
930 AddToWorkList(NN1.getNode());
933 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
935 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
937 DEBUG(dbgs() << "\nPromoting ";
938 Op.getNode()->dump(&DAG));
940 return DAG.getNode(ISD::TRUNCATE, dl, VT,
941 DAG.getNode(Opc, dl, PVT, NN0, NN1));
946 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
947 /// target indicates it is beneficial. e.g. On x86, it's usually better to
948 /// promote i16 operations to i32 since i16 instructions are longer.
949 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
950 if (!LegalOperations)
953 EVT VT = Op.getValueType();
954 if (VT.isVector() || !VT.isInteger())
957 // If operation type is 'undesirable', e.g. i16 on x86, consider
959 unsigned Opc = Op.getOpcode();
960 if (TLI.isTypeDesirableForOp(Opc, VT))
964 // Consult target whether it is a good idea to promote this operation and
965 // what's the right type to promote it to.
966 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
967 assert(PVT != VT && "Don't know what type to promote to!");
969 bool Replace = false;
970 SDValue N0 = Op.getOperand(0);
972 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
973 else if (Opc == ISD::SRL)
974 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
976 N0 = PromoteOperand(N0, PVT, Replace);
980 AddToWorkList(N0.getNode());
982 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
984 DEBUG(dbgs() << "\nPromoting ";
985 Op.getNode()->dump(&DAG));
987 return DAG.getNode(ISD::TRUNCATE, dl, VT,
988 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
993 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
994 if (!LegalOperations)
997 EVT VT = Op.getValueType();
998 if (VT.isVector() || !VT.isInteger())
1001 // If operation type is 'undesirable', e.g. i16 on x86, consider
1003 unsigned Opc = Op.getOpcode();
1004 if (TLI.isTypeDesirableForOp(Opc, VT))
1008 // Consult target whether it is a good idea to promote this operation and
1009 // what's the right type to promote it to.
1010 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1011 assert(PVT != VT && "Don't know what type to promote to!");
1012 // fold (aext (aext x)) -> (aext x)
1013 // fold (aext (zext x)) -> (zext x)
1014 // fold (aext (sext x)) -> (sext x)
1015 DEBUG(dbgs() << "\nPromoting ";
1016 Op.getNode()->dump(&DAG));
1017 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1022 bool DAGCombiner::PromoteLoad(SDValue Op) {
1023 if (!LegalOperations)
1026 EVT VT = Op.getValueType();
1027 if (VT.isVector() || !VT.isInteger())
1030 // If operation type is 'undesirable', e.g. i16 on x86, consider
1032 unsigned Opc = Op.getOpcode();
1033 if (TLI.isTypeDesirableForOp(Opc, VT))
1037 // Consult target whether it is a good idea to promote this operation and
1038 // what's the right type to promote it to.
1039 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1040 assert(PVT != VT && "Don't know what type to promote to!");
1043 SDNode *N = Op.getNode();
1044 LoadSDNode *LD = cast<LoadSDNode>(N);
1045 EVT MemVT = LD->getMemoryVT();
1046 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1047 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1049 : LD->getExtensionType();
1050 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1051 LD->getChain(), LD->getBasePtr(),
1052 MemVT, LD->getMemOperand());
1053 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1055 DEBUG(dbgs() << "\nPromoting ";
1058 Result.getNode()->dump(&DAG);
1060 WorkListRemover DeadNodes(*this);
1061 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1062 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1063 removeFromWorkList(N);
1065 AddToWorkList(Result.getNode());
1072 //===----------------------------------------------------------------------===//
1073 // Main DAG Combiner implementation
1074 //===----------------------------------------------------------------------===//
1076 void DAGCombiner::Run(CombineLevel AtLevel) {
1077 // set the instance variables, so that the various visit routines may use it.
1079 LegalOperations = Level >= AfterLegalizeVectorOps;
1080 LegalTypes = Level >= AfterLegalizeTypes;
1082 // Add all the dag nodes to the worklist.
1083 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1084 E = DAG.allnodes_end(); I != E; ++I)
1087 // Create a dummy node (which is not added to allnodes), that adds a reference
1088 // to the root node, preventing it from being deleted, and tracking any
1089 // changes of the root.
1090 HandleSDNode Dummy(DAG.getRoot());
1092 // The root of the dag may dangle to deleted nodes until the dag combiner is
1093 // done. Set it to null to avoid confusion.
1094 DAG.setRoot(SDValue());
1096 // while the worklist isn't empty, find a node and
1097 // try and combine it.
1098 while (!WorkListContents.empty()) {
1100 // The WorkListOrder holds the SDNodes in order, but it may contain
1102 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1103 // worklist *should* contain, and check the node we want to visit is should
1104 // actually be visited.
1106 N = WorkListOrder.pop_back_val();
1107 } while (!WorkListContents.erase(N));
1109 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1110 // N is deleted from the DAG, since they too may now be dead or may have a
1111 // reduced number of uses, allowing other xforms.
1112 if (N->use_empty() && N != &Dummy) {
1113 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1114 AddToWorkList(N->getOperand(i).getNode());
1120 SDValue RV = combine(N);
1127 // If we get back the same node we passed in, rather than a new node or
1128 // zero, we know that the node must have defined multiple values and
1129 // CombineTo was used. Since CombineTo takes care of the worklist
1130 // mechanics for us, we have no work to do in this case.
1131 if (RV.getNode() == N)
1134 assert(N->getOpcode() != ISD::DELETED_NODE &&
1135 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1136 "Node was deleted but visit returned new node!");
1138 DEBUG(dbgs() << "\nReplacing.3 ";
1140 dbgs() << "\nWith: ";
1141 RV.getNode()->dump(&DAG);
1144 // Transfer debug value.
1145 DAG.TransferDbgValues(SDValue(N, 0), RV);
1146 WorkListRemover DeadNodes(*this);
1147 if (N->getNumValues() == RV.getNode()->getNumValues())
1148 DAG.ReplaceAllUsesWith(N, RV.getNode());
1150 assert(N->getValueType(0) == RV.getValueType() &&
1151 N->getNumValues() == 1 && "Type mismatch");
1153 DAG.ReplaceAllUsesWith(N, &OpV);
1156 // Push the new node and any users onto the worklist
1157 AddToWorkList(RV.getNode());
1158 AddUsersToWorkList(RV.getNode());
1160 // Add any uses of the old node to the worklist in case this node is the
1161 // last one that uses them. They may become dead after this node is
1163 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1164 AddToWorkList(N->getOperand(i).getNode());
1166 // Finally, if the node is now dead, remove it from the graph. The node
1167 // may not be dead if the replacement process recursively simplified to
1168 // something else needing this node.
1169 if (N->use_empty()) {
1170 // Nodes can be reintroduced into the worklist. Make sure we do not
1171 // process a node that has been replaced.
1172 removeFromWorkList(N);
1174 // Finally, since the node is now dead, remove it from the graph.
1179 // If the root changed (e.g. it was a dead load, update the root).
1180 DAG.setRoot(Dummy.getValue());
1181 DAG.RemoveDeadNodes();
1184 SDValue DAGCombiner::visit(SDNode *N) {
1185 switch (N->getOpcode()) {
1187 case ISD::TokenFactor: return visitTokenFactor(N);
1188 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1189 case ISD::ADD: return visitADD(N);
1190 case ISD::SUB: return visitSUB(N);
1191 case ISD::ADDC: return visitADDC(N);
1192 case ISD::SUBC: return visitSUBC(N);
1193 case ISD::ADDE: return visitADDE(N);
1194 case ISD::SUBE: return visitSUBE(N);
1195 case ISD::MUL: return visitMUL(N);
1196 case ISD::SDIV: return visitSDIV(N);
1197 case ISD::UDIV: return visitUDIV(N);
1198 case ISD::SREM: return visitSREM(N);
1199 case ISD::UREM: return visitUREM(N);
1200 case ISD::MULHU: return visitMULHU(N);
1201 case ISD::MULHS: return visitMULHS(N);
1202 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1203 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1204 case ISD::SMULO: return visitSMULO(N);
1205 case ISD::UMULO: return visitUMULO(N);
1206 case ISD::SDIVREM: return visitSDIVREM(N);
1207 case ISD::UDIVREM: return visitUDIVREM(N);
1208 case ISD::AND: return visitAND(N);
1209 case ISD::OR: return visitOR(N);
1210 case ISD::XOR: return visitXOR(N);
1211 case ISD::SHL: return visitSHL(N);
1212 case ISD::SRA: return visitSRA(N);
1213 case ISD::SRL: return visitSRL(N);
1215 case ISD::ROTL: return visitRotate(N);
1216 case ISD::CTLZ: return visitCTLZ(N);
1217 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1218 case ISD::CTTZ: return visitCTTZ(N);
1219 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1220 case ISD::CTPOP: return visitCTPOP(N);
1221 case ISD::SELECT: return visitSELECT(N);
1222 case ISD::VSELECT: return visitVSELECT(N);
1223 case ISD::SELECT_CC: return visitSELECT_CC(N);
1224 case ISD::SETCC: return visitSETCC(N);
1225 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1226 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1227 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1228 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1229 case ISD::TRUNCATE: return visitTRUNCATE(N);
1230 case ISD::BITCAST: return visitBITCAST(N);
1231 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1232 case ISD::FADD: return visitFADD(N);
1233 case ISD::FSUB: return visitFSUB(N);
1234 case ISD::FMUL: return visitFMUL(N);
1235 case ISD::FMA: return visitFMA(N);
1236 case ISD::FDIV: return visitFDIV(N);
1237 case ISD::FREM: return visitFREM(N);
1238 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1239 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1240 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1241 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1242 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1243 case ISD::FP_ROUND: return visitFP_ROUND(N);
1244 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1245 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1246 case ISD::FNEG: return visitFNEG(N);
1247 case ISD::FABS: return visitFABS(N);
1248 case ISD::FFLOOR: return visitFFLOOR(N);
1249 case ISD::FCEIL: return visitFCEIL(N);
1250 case ISD::FTRUNC: return visitFTRUNC(N);
1251 case ISD::BRCOND: return visitBRCOND(N);
1252 case ISD::BR_CC: return visitBR_CC(N);
1253 case ISD::LOAD: return visitLOAD(N);
1254 case ISD::STORE: return visitSTORE(N);
1255 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1256 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1257 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1258 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1259 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1260 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1261 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1266 SDValue DAGCombiner::combine(SDNode *N) {
1267 SDValue RV = visit(N);
1269 // If nothing happened, try a target-specific DAG combine.
1270 if (!RV.getNode()) {
1271 assert(N->getOpcode() != ISD::DELETED_NODE &&
1272 "Node was deleted but visit returned NULL!");
1274 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1275 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1277 // Expose the DAG combiner to the target combiner impls.
1278 TargetLowering::DAGCombinerInfo
1279 DagCombineInfo(DAG, Level, false, this);
1281 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1285 // If nothing happened still, try promoting the operation.
1286 if (!RV.getNode()) {
1287 switch (N->getOpcode()) {
1295 RV = PromoteIntBinOp(SDValue(N, 0));
1300 RV = PromoteIntShiftOp(SDValue(N, 0));
1302 case ISD::SIGN_EXTEND:
1303 case ISD::ZERO_EXTEND:
1304 case ISD::ANY_EXTEND:
1305 RV = PromoteExtend(SDValue(N, 0));
1308 if (PromoteLoad(SDValue(N, 0)))
1314 // If N is a commutative binary node, try commuting it to enable more
1316 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1317 N->getNumValues() == 1) {
1318 SDValue N0 = N->getOperand(0);
1319 SDValue N1 = N->getOperand(1);
1321 // Constant operands are canonicalized to RHS.
1322 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1323 SDValue Ops[] = { N1, N0 };
1324 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1327 return SDValue(CSENode, 0);
1334 /// getInputChainForNode - Given a node, return its input chain if it has one,
1335 /// otherwise return a null sd operand.
1336 static SDValue getInputChainForNode(SDNode *N) {
1337 if (unsigned NumOps = N->getNumOperands()) {
1338 if (N->getOperand(0).getValueType() == MVT::Other)
1339 return N->getOperand(0);
1340 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1341 return N->getOperand(NumOps-1);
1342 for (unsigned i = 1; i < NumOps-1; ++i)
1343 if (N->getOperand(i).getValueType() == MVT::Other)
1344 return N->getOperand(i);
1349 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1350 // If N has two operands, where one has an input chain equal to the other,
1351 // the 'other' chain is redundant.
1352 if (N->getNumOperands() == 2) {
1353 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1354 return N->getOperand(0);
1355 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1356 return N->getOperand(1);
1359 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1360 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1361 SmallPtrSet<SDNode*, 16> SeenOps;
1362 bool Changed = false; // If we should replace this token factor.
1364 // Start out with this token factor.
1367 // Iterate through token factors. The TFs grows when new token factors are
1369 for (unsigned i = 0; i < TFs.size(); ++i) {
1370 SDNode *TF = TFs[i];
1372 // Check each of the operands.
1373 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1374 SDValue Op = TF->getOperand(i);
1376 switch (Op.getOpcode()) {
1377 case ISD::EntryToken:
1378 // Entry tokens don't need to be added to the list. They are
1383 case ISD::TokenFactor:
1384 if (Op.hasOneUse() &&
1385 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1386 // Queue up for processing.
1387 TFs.push_back(Op.getNode());
1388 // Clean up in case the token factor is removed.
1389 AddToWorkList(Op.getNode());
1396 // Only add if it isn't already in the list.
1397 if (SeenOps.insert(Op.getNode()))
1408 // If we've change things around then replace token factor.
1411 // The entry token is the only possible outcome.
1412 Result = DAG.getEntryNode();
1414 // New and improved token factor.
1415 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1418 // Don't add users to work list.
1419 return CombineTo(N, Result, false);
1425 /// MERGE_VALUES can always be eliminated.
1426 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1427 WorkListRemover DeadNodes(*this);
1428 // Replacing results may cause a different MERGE_VALUES to suddenly
1429 // be CSE'd with N, and carry its uses with it. Iterate until no
1430 // uses remain, to ensure that the node can be safely deleted.
1431 // First add the users of this node to the work list so that they
1432 // can be tried again once they have new operands.
1433 AddUsersToWorkList(N);
1435 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1436 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1437 } while (!N->use_empty());
1438 removeFromWorkList(N);
1440 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1444 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1445 SelectionDAG &DAG) {
1446 EVT VT = N0.getValueType();
1447 SDValue N00 = N0.getOperand(0);
1448 SDValue N01 = N0.getOperand(1);
1449 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1451 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1452 isa<ConstantSDNode>(N00.getOperand(1))) {
1453 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1454 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1455 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1456 N00.getOperand(0), N01),
1457 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1458 N00.getOperand(1), N01));
1459 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1465 SDValue DAGCombiner::visitADD(SDNode *N) {
1466 SDValue N0 = N->getOperand(0);
1467 SDValue N1 = N->getOperand(1);
1468 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1469 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1470 EVT VT = N0.getValueType();
1473 if (VT.isVector()) {
1474 SDValue FoldedVOp = SimplifyVBinOp(N);
1475 if (FoldedVOp.getNode()) return FoldedVOp;
1477 // fold (add x, 0) -> x, vector edition
1478 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1480 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1484 // fold (add x, undef) -> undef
1485 if (N0.getOpcode() == ISD::UNDEF)
1487 if (N1.getOpcode() == ISD::UNDEF)
1489 // fold (add c1, c2) -> c1+c2
1491 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1492 // canonicalize constant to RHS
1494 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1495 // fold (add x, 0) -> x
1496 if (N1C && N1C->isNullValue())
1498 // fold (add Sym, c) -> Sym+c
1499 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1500 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1501 GA->getOpcode() == ISD::GlobalAddress)
1502 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1504 (uint64_t)N1C->getSExtValue());
1505 // fold ((c1-A)+c2) -> (c1+c2)-A
1506 if (N1C && N0.getOpcode() == ISD::SUB)
1507 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1508 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1509 DAG.getConstant(N1C->getAPIntValue()+
1510 N0C->getAPIntValue(), VT),
1513 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1516 // fold ((0-A) + B) -> B-A
1517 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1518 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1519 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1520 // fold (A + (0-B)) -> A-B
1521 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1522 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1523 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1524 // fold (A+(B-A)) -> B
1525 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1526 return N1.getOperand(0);
1527 // fold ((B-A)+A) -> B
1528 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1529 return N0.getOperand(0);
1530 // fold (A+(B-(A+C))) to (B-C)
1531 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1532 N0 == N1.getOperand(1).getOperand(0))
1533 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1534 N1.getOperand(1).getOperand(1));
1535 // fold (A+(B-(C+A))) to (B-C)
1536 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1537 N0 == N1.getOperand(1).getOperand(1))
1538 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1539 N1.getOperand(1).getOperand(0));
1540 // fold (A+((B-A)+or-C)) to (B+or-C)
1541 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1542 N1.getOperand(0).getOpcode() == ISD::SUB &&
1543 N0 == N1.getOperand(0).getOperand(1))
1544 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1545 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1547 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1548 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1549 SDValue N00 = N0.getOperand(0);
1550 SDValue N01 = N0.getOperand(1);
1551 SDValue N10 = N1.getOperand(0);
1552 SDValue N11 = N1.getOperand(1);
1554 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1555 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1556 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1557 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1560 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1561 return SDValue(N, 0);
1563 // fold (a+b) -> (a|b) iff a and b share no bits.
1564 if (VT.isInteger() && !VT.isVector()) {
1565 APInt LHSZero, LHSOne;
1566 APInt RHSZero, RHSOne;
1567 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1569 if (LHSZero.getBoolValue()) {
1570 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1572 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1573 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1574 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1575 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1576 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1581 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1582 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1583 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1584 if (Result.getNode()) return Result;
1586 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1587 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1588 if (Result.getNode()) return Result;
1591 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1592 if (N1.getOpcode() == ISD::SHL &&
1593 N1.getOperand(0).getOpcode() == ISD::SUB)
1594 if (ConstantSDNode *C =
1595 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1596 if (C->getAPIntValue() == 0)
1597 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1598 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1599 N1.getOperand(0).getOperand(1),
1601 if (N0.getOpcode() == ISD::SHL &&
1602 N0.getOperand(0).getOpcode() == ISD::SUB)
1603 if (ConstantSDNode *C =
1604 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1605 if (C->getAPIntValue() == 0)
1606 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1607 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1608 N0.getOperand(0).getOperand(1),
1611 if (N1.getOpcode() == ISD::AND) {
1612 SDValue AndOp0 = N1.getOperand(0);
1613 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1614 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1615 unsigned DestBits = VT.getScalarType().getSizeInBits();
1617 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1618 // and similar xforms where the inner op is either ~0 or 0.
1619 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1621 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1625 // add (sext i1), X -> sub X, (zext i1)
1626 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1627 N0.getOperand(0).getValueType() == MVT::i1 &&
1628 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1630 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1631 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1637 SDValue DAGCombiner::visitADDC(SDNode *N) {
1638 SDValue N0 = N->getOperand(0);
1639 SDValue N1 = N->getOperand(1);
1640 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1641 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1642 EVT VT = N0.getValueType();
1644 // If the flag result is dead, turn this into an ADD.
1645 if (!N->hasAnyUseOfValue(1))
1646 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1647 DAG.getNode(ISD::CARRY_FALSE,
1648 SDLoc(N), MVT::Glue));
1650 // canonicalize constant to RHS.
1652 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1654 // fold (addc x, 0) -> x + no carry out
1655 if (N1C && N1C->isNullValue())
1656 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1657 SDLoc(N), MVT::Glue));
1659 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1660 APInt LHSZero, LHSOne;
1661 APInt RHSZero, RHSOne;
1662 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1664 if (LHSZero.getBoolValue()) {
1665 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1667 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1668 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1669 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1670 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1671 DAG.getNode(ISD::CARRY_FALSE,
1672 SDLoc(N), MVT::Glue));
1678 SDValue DAGCombiner::visitADDE(SDNode *N) {
1679 SDValue N0 = N->getOperand(0);
1680 SDValue N1 = N->getOperand(1);
1681 SDValue CarryIn = N->getOperand(2);
1682 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1683 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1685 // canonicalize constant to RHS
1687 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1690 // fold (adde x, y, false) -> (addc x, y)
1691 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1692 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1697 // Since it may not be valid to emit a fold to zero for vector initializers
1698 // check if we can before folding.
1699 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1701 bool LegalOperations, bool LegalTypes) {
1703 return DAG.getConstant(0, VT);
1704 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1705 return DAG.getConstant(0, VT);
1709 SDValue DAGCombiner::visitSUB(SDNode *N) {
1710 SDValue N0 = N->getOperand(0);
1711 SDValue N1 = N->getOperand(1);
1712 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1713 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1714 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1715 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1716 EVT VT = N0.getValueType();
1719 if (VT.isVector()) {
1720 SDValue FoldedVOp = SimplifyVBinOp(N);
1721 if (FoldedVOp.getNode()) return FoldedVOp;
1723 // fold (sub x, 0) -> x, vector edition
1724 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1728 // fold (sub x, x) -> 0
1729 // FIXME: Refactor this and xor and other similar operations together.
1731 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1732 // fold (sub c1, c2) -> c1-c2
1734 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1735 // fold (sub x, c) -> (add x, -c)
1737 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1738 DAG.getConstant(-N1C->getAPIntValue(), VT));
1739 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1740 if (N0C && N0C->isAllOnesValue())
1741 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1742 // fold A-(A-B) -> B
1743 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1744 return N1.getOperand(1);
1745 // fold (A+B)-A -> B
1746 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1747 return N0.getOperand(1);
1748 // fold (A+B)-B -> A
1749 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1750 return N0.getOperand(0);
1751 // fold C2-(A+C1) -> (C2-C1)-A
1752 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1753 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1755 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1758 // fold ((A+(B+or-C))-B) -> A+or-C
1759 if (N0.getOpcode() == ISD::ADD &&
1760 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1761 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1762 N0.getOperand(1).getOperand(0) == N1)
1763 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1764 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1765 // fold ((A+(C+B))-B) -> A+C
1766 if (N0.getOpcode() == ISD::ADD &&
1767 N0.getOperand(1).getOpcode() == ISD::ADD &&
1768 N0.getOperand(1).getOperand(1) == N1)
1769 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1770 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1771 // fold ((A-(B-C))-C) -> A-B
1772 if (N0.getOpcode() == ISD::SUB &&
1773 N0.getOperand(1).getOpcode() == ISD::SUB &&
1774 N0.getOperand(1).getOperand(1) == N1)
1775 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1776 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1778 // If either operand of a sub is undef, the result is undef
1779 if (N0.getOpcode() == ISD::UNDEF)
1781 if (N1.getOpcode() == ISD::UNDEF)
1784 // If the relocation model supports it, consider symbol offsets.
1785 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1786 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1787 // fold (sub Sym, c) -> Sym-c
1788 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1789 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1791 (uint64_t)N1C->getSExtValue());
1792 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1793 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1794 if (GA->getGlobal() == GB->getGlobal())
1795 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1802 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1803 SDValue N0 = N->getOperand(0);
1804 SDValue N1 = N->getOperand(1);
1805 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1806 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1807 EVT VT = N0.getValueType();
1809 // If the flag result is dead, turn this into an SUB.
1810 if (!N->hasAnyUseOfValue(1))
1811 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1812 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1815 // fold (subc x, x) -> 0 + no borrow
1817 return CombineTo(N, DAG.getConstant(0, VT),
1818 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1821 // fold (subc x, 0) -> x + no borrow
1822 if (N1C && N1C->isNullValue())
1823 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1826 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1827 if (N0C && N0C->isAllOnesValue())
1828 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1829 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1835 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1836 SDValue N0 = N->getOperand(0);
1837 SDValue N1 = N->getOperand(1);
1838 SDValue CarryIn = N->getOperand(2);
1840 // fold (sube x, y, false) -> (subc x, y)
1841 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1842 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1847 SDValue DAGCombiner::visitMUL(SDNode *N) {
1848 SDValue N0 = N->getOperand(0);
1849 SDValue N1 = N->getOperand(1);
1850 EVT VT = N0.getValueType();
1852 // fold (mul x, undef) -> 0
1853 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1854 return DAG.getConstant(0, VT);
1856 bool N0IsConst = false;
1857 bool N1IsConst = false;
1858 APInt ConstValue0, ConstValue1;
1860 if (VT.isVector()) {
1861 SDValue FoldedVOp = SimplifyVBinOp(N);
1862 if (FoldedVOp.getNode()) return FoldedVOp;
1864 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1865 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1867 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1868 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1870 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1871 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1875 // fold (mul c1, c2) -> c1*c2
1876 if (N0IsConst && N1IsConst)
1877 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1879 // canonicalize constant to RHS
1880 if (N0IsConst && !N1IsConst)
1881 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1882 // fold (mul x, 0) -> 0
1883 if (N1IsConst && ConstValue1 == 0)
1885 // We require a splat of the entire scalar bit width for non-contiguous
1888 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1889 // fold (mul x, 1) -> x
1890 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1892 // fold (mul x, -1) -> 0-x
1893 if (N1IsConst && ConstValue1.isAllOnesValue())
1894 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1895 DAG.getConstant(0, VT), N0);
1896 // fold (mul x, (1 << c)) -> x << c
1897 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1898 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1899 DAG.getConstant(ConstValue1.logBase2(),
1900 getShiftAmountTy(N0.getValueType())));
1901 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1902 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1903 unsigned Log2Val = (-ConstValue1).logBase2();
1904 // FIXME: If the input is something that is easily negated (e.g. a
1905 // single-use add), we should put the negate there.
1906 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1907 DAG.getConstant(0, VT),
1908 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1909 DAG.getConstant(Log2Val,
1910 getShiftAmountTy(N0.getValueType()))));
1914 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1915 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1916 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1917 isa<ConstantSDNode>(N0.getOperand(1)))) {
1918 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1919 N1, N0.getOperand(1));
1920 AddToWorkList(C3.getNode());
1921 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1922 N0.getOperand(0), C3);
1925 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1928 SDValue Sh(nullptr,0), Y(nullptr,0);
1929 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1930 if (N0.getOpcode() == ISD::SHL &&
1931 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1932 isa<ConstantSDNode>(N0.getOperand(1))) &&
1933 N0.getNode()->hasOneUse()) {
1935 } else if (N1.getOpcode() == ISD::SHL &&
1936 isa<ConstantSDNode>(N1.getOperand(1)) &&
1937 N1.getNode()->hasOneUse()) {
1942 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1943 Sh.getOperand(0), Y);
1944 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1945 Mul, Sh.getOperand(1));
1949 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1950 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1951 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1952 isa<ConstantSDNode>(N0.getOperand(1))))
1953 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1954 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1955 N0.getOperand(0), N1),
1956 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1957 N0.getOperand(1), N1));
1960 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1967 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1968 SDValue N0 = N->getOperand(0);
1969 SDValue N1 = N->getOperand(1);
1970 ConstantSDNode *N0C = isConstOrConstSplat(N0);
1971 ConstantSDNode *N1C = isConstOrConstSplat(N1);
1972 EVT VT = N->getValueType(0);
1975 if (VT.isVector()) {
1976 SDValue FoldedVOp = SimplifyVBinOp(N);
1977 if (FoldedVOp.getNode()) return FoldedVOp;
1980 // fold (sdiv c1, c2) -> c1/c2
1981 if (N0C && N1C && !N1C->isNullValue())
1982 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1983 // fold (sdiv X, 1) -> X
1984 if (N1C && N1C->getAPIntValue() == 1LL)
1986 // fold (sdiv X, -1) -> 0-X
1987 if (N1C && N1C->isAllOnesValue())
1988 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1989 DAG.getConstant(0, VT), N0);
1990 // If we know the sign bits of both operands are zero, strength reduce to a
1991 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1992 if (!VT.isVector()) {
1993 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1994 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1998 // fold (sdiv X, pow2) -> simple ops after legalize
1999 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2000 (-N1C->getAPIntValue()).isPowerOf2())) {
2001 // If dividing by powers of two is cheap, then don't perform the following
2003 if (TLI.isPow2DivCheap())
2006 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2008 // Splat the sign bit into the register
2010 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2011 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2012 getShiftAmountTy(N0.getValueType())));
2013 AddToWorkList(SGN.getNode());
2015 // Add (N0 < 0) ? abs2 - 1 : 0;
2017 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2018 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2019 getShiftAmountTy(SGN.getValueType())));
2020 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2021 AddToWorkList(SRL.getNode());
2022 AddToWorkList(ADD.getNode()); // Divide by pow2
2023 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2024 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2026 // If we're dividing by a positive value, we're done. Otherwise, we must
2027 // negate the result.
2028 if (N1C->getAPIntValue().isNonNegative())
2031 AddToWorkList(SRA.getNode());
2032 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2035 // if integer divide is expensive and we satisfy the requirements, emit an
2036 // alternate sequence.
2037 if (N1C && !TLI.isIntDivCheap()) {
2038 SDValue Op = BuildSDIV(N);
2039 if (Op.getNode()) return Op;
2043 if (N0.getOpcode() == ISD::UNDEF)
2044 return DAG.getConstant(0, VT);
2045 // X / undef -> undef
2046 if (N1.getOpcode() == ISD::UNDEF)
2052 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2053 SDValue N0 = N->getOperand(0);
2054 SDValue N1 = N->getOperand(1);
2055 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2056 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2057 EVT VT = N->getValueType(0);
2060 if (VT.isVector()) {
2061 SDValue FoldedVOp = SimplifyVBinOp(N);
2062 if (FoldedVOp.getNode()) return FoldedVOp;
2065 // fold (udiv c1, c2) -> c1/c2
2066 if (N0C && N1C && !N1C->isNullValue())
2067 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2068 // fold (udiv x, (1 << c)) -> x >>u c
2069 if (N1C && N1C->getAPIntValue().isPowerOf2())
2070 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2071 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2072 getShiftAmountTy(N0.getValueType())));
2073 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2074 if (N1.getOpcode() == ISD::SHL) {
2075 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2076 if (SHC->getAPIntValue().isPowerOf2()) {
2077 EVT ADDVT = N1.getOperand(1).getValueType();
2078 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2080 DAG.getConstant(SHC->getAPIntValue()
2083 AddToWorkList(Add.getNode());
2084 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2088 // fold (udiv x, c) -> alternate
2089 if (N1C && !TLI.isIntDivCheap()) {
2090 SDValue Op = BuildUDIV(N);
2091 if (Op.getNode()) return Op;
2095 if (N0.getOpcode() == ISD::UNDEF)
2096 return DAG.getConstant(0, VT);
2097 // X / undef -> undef
2098 if (N1.getOpcode() == ISD::UNDEF)
2104 SDValue DAGCombiner::visitSREM(SDNode *N) {
2105 SDValue N0 = N->getOperand(0);
2106 SDValue N1 = N->getOperand(1);
2107 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2108 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2109 EVT VT = N->getValueType(0);
2111 // fold (srem c1, c2) -> c1%c2
2112 if (N0C && N1C && !N1C->isNullValue())
2113 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2114 // If we know the sign bits of both operands are zero, strength reduce to a
2115 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2116 if (!VT.isVector()) {
2117 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2118 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2121 // If X/C can be simplified by the division-by-constant logic, lower
2122 // X%C to the equivalent of X-X/C*C.
2123 if (N1C && !N1C->isNullValue()) {
2124 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2125 AddToWorkList(Div.getNode());
2126 SDValue OptimizedDiv = combine(Div.getNode());
2127 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2128 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2130 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2131 AddToWorkList(Mul.getNode());
2137 if (N0.getOpcode() == ISD::UNDEF)
2138 return DAG.getConstant(0, VT);
2139 // X % undef -> undef
2140 if (N1.getOpcode() == ISD::UNDEF)
2146 SDValue DAGCombiner::visitUREM(SDNode *N) {
2147 SDValue N0 = N->getOperand(0);
2148 SDValue N1 = N->getOperand(1);
2149 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2150 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2151 EVT VT = N->getValueType(0);
2153 // fold (urem c1, c2) -> c1%c2
2154 if (N0C && N1C && !N1C->isNullValue())
2155 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2156 // fold (urem x, pow2) -> (and x, pow2-1)
2157 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2158 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2159 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2160 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2161 if (N1.getOpcode() == ISD::SHL) {
2162 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2163 if (SHC->getAPIntValue().isPowerOf2()) {
2165 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2166 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2168 AddToWorkList(Add.getNode());
2169 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2174 // If X/C can be simplified by the division-by-constant logic, lower
2175 // X%C to the equivalent of X-X/C*C.
2176 if (N1C && !N1C->isNullValue()) {
2177 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2178 AddToWorkList(Div.getNode());
2179 SDValue OptimizedDiv = combine(Div.getNode());
2180 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2181 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2183 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2184 AddToWorkList(Mul.getNode());
2190 if (N0.getOpcode() == ISD::UNDEF)
2191 return DAG.getConstant(0, VT);
2192 // X % undef -> undef
2193 if (N1.getOpcode() == ISD::UNDEF)
2199 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2200 SDValue N0 = N->getOperand(0);
2201 SDValue N1 = N->getOperand(1);
2202 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2203 EVT VT = N->getValueType(0);
2206 // fold (mulhs x, 0) -> 0
2207 if (N1C && N1C->isNullValue())
2209 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2210 if (N1C && N1C->getAPIntValue() == 1)
2211 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2212 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2213 getShiftAmountTy(N0.getValueType())));
2214 // fold (mulhs x, undef) -> 0
2215 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2216 return DAG.getConstant(0, VT);
2218 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2220 if (VT.isSimple() && !VT.isVector()) {
2221 MVT Simple = VT.getSimpleVT();
2222 unsigned SimpleSize = Simple.getSizeInBits();
2223 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2224 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2225 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2226 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2227 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2228 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2229 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2230 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2237 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2238 SDValue N0 = N->getOperand(0);
2239 SDValue N1 = N->getOperand(1);
2240 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2241 EVT VT = N->getValueType(0);
2244 // fold (mulhu x, 0) -> 0
2245 if (N1C && N1C->isNullValue())
2247 // fold (mulhu x, 1) -> 0
2248 if (N1C && N1C->getAPIntValue() == 1)
2249 return DAG.getConstant(0, N0.getValueType());
2250 // fold (mulhu x, undef) -> 0
2251 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2252 return DAG.getConstant(0, VT);
2254 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2256 if (VT.isSimple() && !VT.isVector()) {
2257 MVT Simple = VT.getSimpleVT();
2258 unsigned SimpleSize = Simple.getSizeInBits();
2259 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2260 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2261 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2262 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2263 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2264 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2265 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2266 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2273 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2274 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2275 /// that are being performed. Return true if a simplification was made.
2277 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2279 // If the high half is not needed, just compute the low half.
2280 bool HiExists = N->hasAnyUseOfValue(1);
2282 (!LegalOperations ||
2283 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2284 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2285 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2286 return CombineTo(N, Res, Res);
2289 // If the low half is not needed, just compute the high half.
2290 bool LoExists = N->hasAnyUseOfValue(0);
2292 (!LegalOperations ||
2293 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2294 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2295 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2296 return CombineTo(N, Res, Res);
2299 // If both halves are used, return as it is.
2300 if (LoExists && HiExists)
2303 // If the two computed results can be simplified separately, separate them.
2305 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2306 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2307 AddToWorkList(Lo.getNode());
2308 SDValue LoOpt = combine(Lo.getNode());
2309 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2310 (!LegalOperations ||
2311 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2312 return CombineTo(N, LoOpt, LoOpt);
2316 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2317 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2318 AddToWorkList(Hi.getNode());
2319 SDValue HiOpt = combine(Hi.getNode());
2320 if (HiOpt.getNode() && HiOpt != Hi &&
2321 (!LegalOperations ||
2322 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2323 return CombineTo(N, HiOpt, HiOpt);
2329 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2330 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2331 if (Res.getNode()) return Res;
2333 EVT VT = N->getValueType(0);
2336 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2338 if (VT.isSimple() && !VT.isVector()) {
2339 MVT Simple = VT.getSimpleVT();
2340 unsigned SimpleSize = Simple.getSizeInBits();
2341 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2342 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2343 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2344 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2345 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2346 // Compute the high part as N1.
2347 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2348 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2349 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2350 // Compute the low part as N0.
2351 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2352 return CombineTo(N, Lo, Hi);
2359 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2360 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2361 if (Res.getNode()) return Res;
2363 EVT VT = N->getValueType(0);
2366 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2368 if (VT.isSimple() && !VT.isVector()) {
2369 MVT Simple = VT.getSimpleVT();
2370 unsigned SimpleSize = Simple.getSizeInBits();
2371 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2372 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2373 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2374 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2375 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2376 // Compute the high part as N1.
2377 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2378 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2379 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2380 // Compute the low part as N0.
2381 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2382 return CombineTo(N, Lo, Hi);
2389 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2390 // (smulo x, 2) -> (saddo x, x)
2391 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2392 if (C2->getAPIntValue() == 2)
2393 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2394 N->getOperand(0), N->getOperand(0));
2399 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2400 // (umulo x, 2) -> (uaddo x, x)
2401 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2402 if (C2->getAPIntValue() == 2)
2403 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2404 N->getOperand(0), N->getOperand(0));
2409 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2410 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2411 if (Res.getNode()) return Res;
2416 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2417 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2418 if (Res.getNode()) return Res;
2423 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2424 /// two operands of the same opcode, try to simplify it.
2425 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2426 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2427 EVT VT = N0.getValueType();
2428 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2430 // Bail early if none of these transforms apply.
2431 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2433 // For each of OP in AND/OR/XOR:
2434 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2435 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2436 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2437 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2439 // do not sink logical op inside of a vector extend, since it may combine
2441 EVT Op0VT = N0.getOperand(0).getValueType();
2442 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2443 N0.getOpcode() == ISD::SIGN_EXTEND ||
2444 // Avoid infinite looping with PromoteIntBinOp.
2445 (N0.getOpcode() == ISD::ANY_EXTEND &&
2446 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2447 (N0.getOpcode() == ISD::TRUNCATE &&
2448 (!TLI.isZExtFree(VT, Op0VT) ||
2449 !TLI.isTruncateFree(Op0VT, VT)) &&
2450 TLI.isTypeLegal(Op0VT))) &&
2452 Op0VT == N1.getOperand(0).getValueType() &&
2453 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2454 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2455 N0.getOperand(0).getValueType(),
2456 N0.getOperand(0), N1.getOperand(0));
2457 AddToWorkList(ORNode.getNode());
2458 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2461 // For each of OP in SHL/SRL/SRA/AND...
2462 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2463 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2464 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2465 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2466 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2467 N0.getOperand(1) == N1.getOperand(1)) {
2468 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2469 N0.getOperand(0).getValueType(),
2470 N0.getOperand(0), N1.getOperand(0));
2471 AddToWorkList(ORNode.getNode());
2472 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2473 ORNode, N0.getOperand(1));
2476 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2477 // Only perform this optimization after type legalization and before
2478 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2479 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2480 // we don't want to undo this promotion.
2481 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2483 if ((N0.getOpcode() == ISD::BITCAST ||
2484 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2485 Level == AfterLegalizeTypes) {
2486 SDValue In0 = N0.getOperand(0);
2487 SDValue In1 = N1.getOperand(0);
2488 EVT In0Ty = In0.getValueType();
2489 EVT In1Ty = In1.getValueType();
2491 // If both incoming values are integers, and the original types are the
2493 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2494 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2495 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2496 AddToWorkList(Op.getNode());
2501 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2502 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2503 // If both shuffles use the same mask, and both shuffle within a single
2504 // vector, then it is worthwhile to move the swizzle after the operation.
2505 // The type-legalizer generates this pattern when loading illegal
2506 // vector types from memory. In many cases this allows additional shuffle
2508 // There are other cases where moving the shuffle after the xor/and/or
2509 // is profitable even if shuffles don't perform a swizzle.
2510 // If both shuffles use the same mask, and both shuffles have the same first
2511 // or second operand, then it might still be profitable to move the shuffle
2512 // after the xor/and/or operation.
2513 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2514 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2515 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2517 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2518 "Inputs to shuffles are not the same type");
2520 // Check that both shuffles use the same mask. The masks are known to be of
2521 // the same length because the result vector type is the same.
2522 // Check also that shuffles have only one use to avoid introducing extra
2524 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2525 SVN0->getMask().equals(SVN1->getMask())) {
2526 SDValue ShOp = N0->getOperand(1);
2528 // Don't try to fold this node if it requires introducing a
2529 // build vector of all zeros that might be illegal at this stage.
2530 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2532 ShOp = DAG.getConstant(0, VT);
2537 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2538 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2539 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2540 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2541 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2542 N0->getOperand(0), N1->getOperand(0));
2543 AddToWorkList(NewNode.getNode());
2544 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2545 &SVN0->getMask()[0]);
2548 // Don't try to fold this node if it requires introducing a
2549 // build vector of all zeros that might be illegal at this stage.
2550 ShOp = N0->getOperand(0);
2551 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2553 ShOp = DAG.getConstant(0, VT);
2558 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2559 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2560 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2561 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2562 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2563 N0->getOperand(1), N1->getOperand(1));
2564 AddToWorkList(NewNode.getNode());
2565 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2566 &SVN0->getMask()[0]);
2574 SDValue DAGCombiner::visitAND(SDNode *N) {
2575 SDValue N0 = N->getOperand(0);
2576 SDValue N1 = N->getOperand(1);
2577 SDValue LL, LR, RL, RR, CC0, CC1;
2578 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2579 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2580 EVT VT = N1.getValueType();
2581 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2584 if (VT.isVector()) {
2585 SDValue FoldedVOp = SimplifyVBinOp(N);
2586 if (FoldedVOp.getNode()) return FoldedVOp;
2588 // fold (and x, 0) -> 0, vector edition
2589 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2591 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2594 // fold (and x, -1) -> x, vector edition
2595 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2597 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2601 // fold (and x, undef) -> 0
2602 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2603 return DAG.getConstant(0, VT);
2604 // fold (and c1, c2) -> c1&c2
2606 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2607 // canonicalize constant to RHS
2609 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2610 // fold (and x, -1) -> x
2611 if (N1C && N1C->isAllOnesValue())
2613 // if (and x, c) is known to be zero, return 0
2614 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2615 APInt::getAllOnesValue(BitWidth)))
2616 return DAG.getConstant(0, VT);
2618 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2621 // fold (and (or x, C), D) -> D if (C & D) == D
2622 if (N1C && N0.getOpcode() == ISD::OR)
2623 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2624 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2626 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2627 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2628 SDValue N0Op0 = N0.getOperand(0);
2629 APInt Mask = ~N1C->getAPIntValue();
2630 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2631 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2632 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2633 N0.getValueType(), N0Op0);
2635 // Replace uses of the AND with uses of the Zero extend node.
2638 // We actually want to replace all uses of the any_extend with the
2639 // zero_extend, to avoid duplicating things. This will later cause this
2640 // AND to be folded.
2641 CombineTo(N0.getNode(), Zext);
2642 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2645 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2646 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2647 // already be zero by virtue of the width of the base type of the load.
2649 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2651 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2652 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2653 N0.getOpcode() == ISD::LOAD) {
2654 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2655 N0 : N0.getOperand(0) );
2657 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2658 // This can be a pure constant or a vector splat, in which case we treat the
2659 // vector as a scalar and use the splat value.
2660 APInt Constant = APInt::getNullValue(1);
2661 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2662 Constant = C->getAPIntValue();
2663 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2664 APInt SplatValue, SplatUndef;
2665 unsigned SplatBitSize;
2667 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2668 SplatBitSize, HasAnyUndefs);
2670 // Undef bits can contribute to a possible optimisation if set, so
2672 SplatValue |= SplatUndef;
2674 // The splat value may be something like "0x00FFFFFF", which means 0 for
2675 // the first vector value and FF for the rest, repeating. We need a mask
2676 // that will apply equally to all members of the vector, so AND all the
2677 // lanes of the constant together.
2678 EVT VT = Vector->getValueType(0);
2679 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2681 // If the splat value has been compressed to a bitlength lower
2682 // than the size of the vector lane, we need to re-expand it to
2684 if (BitWidth > SplatBitSize)
2685 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2686 SplatBitSize < BitWidth;
2687 SplatBitSize = SplatBitSize * 2)
2688 SplatValue |= SplatValue.shl(SplatBitSize);
2690 Constant = APInt::getAllOnesValue(BitWidth);
2691 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2692 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2696 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2697 // actually legal and isn't going to get expanded, else this is a false
2699 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2700 Load->getMemoryVT());
2702 // Resize the constant to the same size as the original memory access before
2703 // extension. If it is still the AllOnesValue then this AND is completely
2706 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2709 switch (Load->getExtensionType()) {
2710 default: B = false; break;
2711 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2713 case ISD::NON_EXTLOAD: B = true; break;
2716 if (B && Constant.isAllOnesValue()) {
2717 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2718 // preserve semantics once we get rid of the AND.
2719 SDValue NewLoad(Load, 0);
2720 if (Load->getExtensionType() == ISD::EXTLOAD) {
2721 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2722 Load->getValueType(0), SDLoc(Load),
2723 Load->getChain(), Load->getBasePtr(),
2724 Load->getOffset(), Load->getMemoryVT(),
2725 Load->getMemOperand());
2726 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2727 if (Load->getNumValues() == 3) {
2728 // PRE/POST_INC loads have 3 values.
2729 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2730 NewLoad.getValue(2) };
2731 CombineTo(Load, To, 3, true);
2733 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2737 // Fold the AND away, taking care not to fold to the old load node if we
2739 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2741 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2744 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2745 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2746 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2747 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2749 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2750 LL.getValueType().isInteger()) {
2751 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2752 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2753 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2754 LR.getValueType(), LL, RL);
2755 AddToWorkList(ORNode.getNode());
2756 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2758 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2759 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2760 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2761 LR.getValueType(), LL, RL);
2762 AddToWorkList(ANDNode.getNode());
2763 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2765 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2766 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2767 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2768 LR.getValueType(), LL, RL);
2769 AddToWorkList(ORNode.getNode());
2770 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2773 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2774 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2775 Op0 == Op1 && LL.getValueType().isInteger() &&
2776 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2777 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2778 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2779 cast<ConstantSDNode>(RR)->isNullValue()))) {
2780 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2781 LL, DAG.getConstant(1, LL.getValueType()));
2782 AddToWorkList(ADDNode.getNode());
2783 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2784 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2786 // canonicalize equivalent to ll == rl
2787 if (LL == RR && LR == RL) {
2788 Op1 = ISD::getSetCCSwappedOperands(Op1);
2791 if (LL == RL && LR == RR) {
2792 bool isInteger = LL.getValueType().isInteger();
2793 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2794 if (Result != ISD::SETCC_INVALID &&
2795 (!LegalOperations ||
2796 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2797 TLI.isOperationLegal(ISD::SETCC,
2798 getSetCCResultType(N0.getSimpleValueType())))))
2799 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2804 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2805 if (N0.getOpcode() == N1.getOpcode()) {
2806 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2807 if (Tmp.getNode()) return Tmp;
2810 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2811 // fold (and (sra)) -> (and (srl)) when possible.
2812 if (!VT.isVector() &&
2813 SimplifyDemandedBits(SDValue(N, 0)))
2814 return SDValue(N, 0);
2816 // fold (zext_inreg (extload x)) -> (zextload x)
2817 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2818 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2819 EVT MemVT = LN0->getMemoryVT();
2820 // If we zero all the possible extended bits, then we can turn this into
2821 // a zextload if we are running before legalize or the operation is legal.
2822 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2823 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2824 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2825 ((!LegalOperations && !LN0->isVolatile()) ||
2826 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2827 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2828 LN0->getChain(), LN0->getBasePtr(),
2829 MemVT, LN0->getMemOperand());
2831 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2832 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2835 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2836 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2838 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2839 EVT MemVT = LN0->getMemoryVT();
2840 // If we zero all the possible extended bits, then we can turn this into
2841 // a zextload if we are running before legalize or the operation is legal.
2842 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2843 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2844 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2845 ((!LegalOperations && !LN0->isVolatile()) ||
2846 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2847 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2848 LN0->getChain(), LN0->getBasePtr(),
2849 MemVT, LN0->getMemOperand());
2851 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2852 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2856 // fold (and (load x), 255) -> (zextload x, i8)
2857 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2858 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2859 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2860 (N0.getOpcode() == ISD::ANY_EXTEND &&
2861 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2862 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2863 LoadSDNode *LN0 = HasAnyExt
2864 ? cast<LoadSDNode>(N0.getOperand(0))
2865 : cast<LoadSDNode>(N0);
2866 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2867 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2868 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2869 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2870 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2871 EVT LoadedVT = LN0->getMemoryVT();
2873 if (ExtVT == LoadedVT &&
2874 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2875 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2878 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2879 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2880 LN0->getMemOperand());
2882 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2883 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2886 // Do not change the width of a volatile load.
2887 // Do not generate loads of non-round integer types since these can
2888 // be expensive (and would be wrong if the type is not byte sized).
2889 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2890 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2891 EVT PtrType = LN0->getOperand(1).getValueType();
2893 unsigned Alignment = LN0->getAlignment();
2894 SDValue NewPtr = LN0->getBasePtr();
2896 // For big endian targets, we need to add an offset to the pointer
2897 // to load the correct bytes. For little endian systems, we merely
2898 // need to read fewer bytes from the same pointer.
2899 if (TLI.isBigEndian()) {
2900 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2901 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2902 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2903 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2904 NewPtr, DAG.getConstant(PtrOff, PtrType));
2905 Alignment = MinAlign(Alignment, PtrOff);
2908 AddToWorkList(NewPtr.getNode());
2910 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2912 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2913 LN0->getChain(), NewPtr,
2914 LN0->getPointerInfo(),
2915 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2916 Alignment, LN0->getTBAAInfo());
2918 CombineTo(LN0, Load, Load.getValue(1));
2919 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2925 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2926 VT.getSizeInBits() <= 64) {
2927 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2928 APInt ADDC = ADDI->getAPIntValue();
2929 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2930 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2931 // immediate for an add, but it is legal if its top c2 bits are set,
2932 // transform the ADD so the immediate doesn't need to be materialized
2934 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2935 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2936 SRLI->getZExtValue());
2937 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2939 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2941 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2942 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2943 CombineTo(N0.getNode(), NewAdd);
2944 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2952 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2953 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2954 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2955 N0.getOperand(1), false);
2956 if (BSwap.getNode())
2963 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2965 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2966 bool DemandHighBits) {
2967 if (!LegalOperations)
2970 EVT VT = N->getValueType(0);
2971 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2973 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2976 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2977 bool LookPassAnd0 = false;
2978 bool LookPassAnd1 = false;
2979 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2981 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2983 if (N0.getOpcode() == ISD::AND) {
2984 if (!N0.getNode()->hasOneUse())
2986 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2987 if (!N01C || N01C->getZExtValue() != 0xFF00)
2989 N0 = N0.getOperand(0);
2990 LookPassAnd0 = true;
2993 if (N1.getOpcode() == ISD::AND) {
2994 if (!N1.getNode()->hasOneUse())
2996 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2997 if (!N11C || N11C->getZExtValue() != 0xFF)
2999 N1 = N1.getOperand(0);
3000 LookPassAnd1 = true;
3003 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3005 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3007 if (!N0.getNode()->hasOneUse() ||
3008 !N1.getNode()->hasOneUse())
3011 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3012 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3015 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3018 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3019 SDValue N00 = N0->getOperand(0);
3020 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3021 if (!N00.getNode()->hasOneUse())
3023 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3024 if (!N001C || N001C->getZExtValue() != 0xFF)
3026 N00 = N00.getOperand(0);
3027 LookPassAnd0 = true;
3030 SDValue N10 = N1->getOperand(0);
3031 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3032 if (!N10.getNode()->hasOneUse())
3034 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3035 if (!N101C || N101C->getZExtValue() != 0xFF00)
3037 N10 = N10.getOperand(0);
3038 LookPassAnd1 = true;
3044 // Make sure everything beyond the low halfword gets set to zero since the SRL
3045 // 16 will clear the top bits.
3046 unsigned OpSizeInBits = VT.getSizeInBits();
3047 if (DemandHighBits && OpSizeInBits > 16) {
3048 // If the left-shift isn't masked out then the only way this is a bswap is
3049 // if all bits beyond the low 8 are 0. In that case the entire pattern
3050 // reduces to a left shift anyway: leave it for other parts of the combiner.
3054 // However, if the right shift isn't masked out then it might be because
3055 // it's not needed. See if we can spot that too.
3056 if (!LookPassAnd1 &&
3057 !DAG.MaskedValueIsZero(
3058 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3062 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3063 if (OpSizeInBits > 16)
3064 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3065 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3069 /// isBSwapHWordElement - Return true if the specified node is an element
3070 /// that makes up a 32-bit packed halfword byteswap. i.e.
3071 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3072 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3073 if (!N.getNode()->hasOneUse())
3076 unsigned Opc = N.getOpcode();
3077 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3080 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3085 switch (N1C->getZExtValue()) {
3088 case 0xFF: Num = 0; break;
3089 case 0xFF00: Num = 1; break;
3090 case 0xFF0000: Num = 2; break;
3091 case 0xFF000000: Num = 3; break;
3094 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3095 SDValue N0 = N.getOperand(0);
3096 if (Opc == ISD::AND) {
3097 if (Num == 0 || Num == 2) {
3099 // (x >> 8) & 0xff0000
3100 if (N0.getOpcode() != ISD::SRL)
3102 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3103 if (!C || C->getZExtValue() != 8)
3106 // (x << 8) & 0xff00
3107 // (x << 8) & 0xff000000
3108 if (N0.getOpcode() != ISD::SHL)
3110 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3111 if (!C || C->getZExtValue() != 8)
3114 } else if (Opc == ISD::SHL) {
3116 // (x & 0xff0000) << 8
3117 if (Num != 0 && Num != 2)
3119 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3120 if (!C || C->getZExtValue() != 8)
3122 } else { // Opc == ISD::SRL
3123 // (x & 0xff00) >> 8
3124 // (x & 0xff000000) >> 8
3125 if (Num != 1 && Num != 3)
3127 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3128 if (!C || C->getZExtValue() != 8)
3135 Parts[Num] = N0.getOperand(0).getNode();
3139 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3140 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3141 /// => (rotl (bswap x), 16)
3142 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3143 if (!LegalOperations)
3146 EVT VT = N->getValueType(0);
3149 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3152 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3154 // (or (or (and), (and)), (or (and), (and)))
3155 // (or (or (or (and), (and)), (and)), (and))
3156 if (N0.getOpcode() != ISD::OR)
3158 SDValue N00 = N0.getOperand(0);
3159 SDValue N01 = N0.getOperand(1);
3161 if (N1.getOpcode() == ISD::OR &&
3162 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3163 // (or (or (and), (and)), (or (and), (and)))
3164 SDValue N000 = N00.getOperand(0);
3165 if (!isBSwapHWordElement(N000, Parts))
3168 SDValue N001 = N00.getOperand(1);
3169 if (!isBSwapHWordElement(N001, Parts))
3171 SDValue N010 = N01.getOperand(0);
3172 if (!isBSwapHWordElement(N010, Parts))
3174 SDValue N011 = N01.getOperand(1);
3175 if (!isBSwapHWordElement(N011, Parts))
3178 // (or (or (or (and), (and)), (and)), (and))
3179 if (!isBSwapHWordElement(N1, Parts))
3181 if (!isBSwapHWordElement(N01, Parts))
3183 if (N00.getOpcode() != ISD::OR)
3185 SDValue N000 = N00.getOperand(0);
3186 if (!isBSwapHWordElement(N000, Parts))
3188 SDValue N001 = N00.getOperand(1);
3189 if (!isBSwapHWordElement(N001, Parts))
3193 // Make sure the parts are all coming from the same node.
3194 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3197 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3198 SDValue(Parts[0],0));
3200 // Result of the bswap should be rotated by 16. If it's not legal, then
3201 // do (x << 16) | (x >> 16).
3202 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3203 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3204 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3205 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3206 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3207 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3208 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3209 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3212 SDValue DAGCombiner::visitOR(SDNode *N) {
3213 SDValue N0 = N->getOperand(0);
3214 SDValue N1 = N->getOperand(1);
3215 SDValue LL, LR, RL, RR, CC0, CC1;
3216 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3217 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3218 EVT VT = N1.getValueType();
3221 if (VT.isVector()) {
3222 SDValue FoldedVOp = SimplifyVBinOp(N);
3223 if (FoldedVOp.getNode()) return FoldedVOp;
3225 // fold (or x, 0) -> x, vector edition
3226 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3228 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3231 // fold (or x, -1) -> -1, vector edition
3232 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3234 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3237 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3238 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3239 // Do this only if the resulting shuffle is legal.
3240 if (isa<ShuffleVectorSDNode>(N0) &&
3241 isa<ShuffleVectorSDNode>(N1) &&
3242 N0->getOperand(1) == N1->getOperand(1) &&
3243 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3244 bool CanFold = true;
3245 unsigned NumElts = VT.getVectorNumElements();
3246 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3247 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3248 // We construct two shuffle masks:
3249 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3250 // and N1 as the second operand.
3251 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3252 // and N0 as the second operand.
3253 // We do this because OR is commutable and therefore there might be
3254 // two ways to fold this node into a shuffle.
3255 SmallVector<int,4> Mask1;
3256 SmallVector<int,4> Mask2;
3258 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3259 int M0 = SV0->getMaskElt(i);
3260 int M1 = SV1->getMaskElt(i);
3262 // Both shuffle indexes are undef. Propagate Undef.
3263 if (M0 < 0 && M1 < 0) {
3264 Mask1.push_back(M0);
3265 Mask2.push_back(M0);
3269 if (M0 < 0 || M1 < 0 ||
3270 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3271 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3276 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3277 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3281 // Fold this sequence only if the resulting shuffle is 'legal'.
3282 if (TLI.isShuffleMaskLegal(Mask1, VT))
3283 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3284 N1->getOperand(0), &Mask1[0]);
3285 if (TLI.isShuffleMaskLegal(Mask2, VT))
3286 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3287 N0->getOperand(0), &Mask2[0]);
3292 // fold (or x, undef) -> -1
3293 if (!LegalOperations &&
3294 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3295 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3296 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3298 // fold (or c1, c2) -> c1|c2
3300 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3301 // canonicalize constant to RHS
3303 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3304 // fold (or x, 0) -> x
3305 if (N1C && N1C->isNullValue())
3307 // fold (or x, -1) -> -1
3308 if (N1C && N1C->isAllOnesValue())
3310 // fold (or x, c) -> c iff (x & ~c) == 0
3311 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3314 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3315 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3316 if (BSwap.getNode())
3318 BSwap = MatchBSwapHWordLow(N, N0, N1);
3319 if (BSwap.getNode())
3323 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3326 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3327 // iff (c1 & c2) == 0.
3328 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3329 isa<ConstantSDNode>(N0.getOperand(1))) {
3330 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3331 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3332 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3335 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3336 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3337 N0.getOperand(0), N1), COR);
3340 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3341 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3342 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3343 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3345 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3346 LL.getValueType().isInteger()) {
3347 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3348 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3349 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3350 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3351 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3352 LR.getValueType(), LL, RL);
3353 AddToWorkList(ORNode.getNode());
3354 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3356 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3357 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3358 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3359 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3360 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3361 LR.getValueType(), LL, RL);
3362 AddToWorkList(ANDNode.getNode());
3363 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3366 // canonicalize equivalent to ll == rl
3367 if (LL == RR && LR == RL) {
3368 Op1 = ISD::getSetCCSwappedOperands(Op1);
3371 if (LL == RL && LR == RR) {
3372 bool isInteger = LL.getValueType().isInteger();
3373 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3374 if (Result != ISD::SETCC_INVALID &&
3375 (!LegalOperations ||
3376 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3377 TLI.isOperationLegal(ISD::SETCC,
3378 getSetCCResultType(N0.getValueType())))))
3379 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3384 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3385 if (N0.getOpcode() == N1.getOpcode()) {
3386 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3387 if (Tmp.getNode()) return Tmp;
3390 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3391 if (N0.getOpcode() == ISD::AND &&
3392 N1.getOpcode() == ISD::AND &&
3393 N0.getOperand(1).getOpcode() == ISD::Constant &&
3394 N1.getOperand(1).getOpcode() == ISD::Constant &&
3395 // Don't increase # computations.
3396 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3397 // We can only do this xform if we know that bits from X that are set in C2
3398 // but not in C1 are already zero. Likewise for Y.
3399 const APInt &LHSMask =
3400 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3401 const APInt &RHSMask =
3402 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3404 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3405 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3406 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3407 N0.getOperand(0), N1.getOperand(0));
3408 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3409 DAG.getConstant(LHSMask | RHSMask, VT));
3413 // See if this is some rotate idiom.
3414 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3415 return SDValue(Rot, 0);
3417 // Simplify the operands using demanded-bits information.
3418 if (!VT.isVector() &&
3419 SimplifyDemandedBits(SDValue(N, 0)))
3420 return SDValue(N, 0);
3425 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3426 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3427 if (Op.getOpcode() == ISD::AND) {
3428 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3429 Mask = Op.getOperand(1);
3430 Op = Op.getOperand(0);
3436 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3444 // Return true if we can prove that, whenever Neg and Pos are both in the
3445 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3446 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3448 // (or (shift1 X, Neg), (shift2 X, Pos))
3450 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3451 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3452 // to consider shift amounts with defined behavior.
3453 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3454 // If OpSize is a power of 2 then:
3456 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3457 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3459 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3460 // for the stronger condition:
3462 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3464 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3465 // we can just replace Neg with Neg' for the rest of the function.
3467 // In other cases we check for the even stronger condition:
3469 // Neg == OpSize - Pos [B]
3471 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3472 // behavior if Pos == 0 (and consequently Neg == OpSize).
3474 // We could actually use [A] whenever OpSize is a power of 2, but the
3475 // only extra cases that it would match are those uninteresting ones
3476 // where Neg and Pos are never in range at the same time. E.g. for
3477 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3478 // as well as (sub 32, Pos), but:
3480 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3482 // always invokes undefined behavior for 32-bit X.
3484 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3485 unsigned MaskLoBits = 0;
3486 if (Neg.getOpcode() == ISD::AND &&
3487 isPowerOf2_64(OpSize) &&
3488 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3489 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3490 Neg = Neg.getOperand(0);
3491 MaskLoBits = Log2_64(OpSize);
3494 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3495 if (Neg.getOpcode() != ISD::SUB)
3497 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3500 SDValue NegOp1 = Neg.getOperand(1);
3502 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3503 // Pos'. The truncation is redundant for the purpose of the equality.
3505 Pos.getOpcode() == ISD::AND &&
3506 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3507 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3508 Pos = Pos.getOperand(0);
3510 // The condition we need is now:
3512 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3514 // If NegOp1 == Pos then we need:
3516 // OpSize & Mask == NegC & Mask
3518 // (because "x & Mask" is a truncation and distributes through subtraction).
3521 Width = NegC->getAPIntValue();
3522 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3523 // Then the condition we want to prove becomes:
3525 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3527 // which, again because "x & Mask" is a truncation, becomes:
3529 // NegC & Mask == (OpSize - PosC) & Mask
3530 // OpSize & Mask == (NegC + PosC) & Mask
3531 else if (Pos.getOpcode() == ISD::ADD &&
3532 Pos.getOperand(0) == NegOp1 &&
3533 Pos.getOperand(1).getOpcode() == ISD::Constant)
3534 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3535 NegC->getAPIntValue());
3539 // Now we just need to check that OpSize & Mask == Width & Mask.
3541 // Opsize & Mask is 0 since Mask is Opsize - 1.
3542 return Width.getLoBits(MaskLoBits) == 0;
3543 return Width == OpSize;
3546 // A subroutine of MatchRotate used once we have found an OR of two opposite
3547 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3548 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3549 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3550 // Neg with outer conversions stripped away.
3551 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3552 SDValue Neg, SDValue InnerPos,
3553 SDValue InnerNeg, unsigned PosOpcode,
3554 unsigned NegOpcode, SDLoc DL) {
3555 // fold (or (shl x, (*ext y)),
3556 // (srl x, (*ext (sub 32, y)))) ->
3557 // (rotl x, y) or (rotr x, (sub 32, y))
3559 // fold (or (shl x, (*ext (sub 32, y))),
3560 // (srl x, (*ext y))) ->
3561 // (rotr x, y) or (rotl x, (sub 32, y))
3562 EVT VT = Shifted.getValueType();
3563 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3564 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3565 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3566 HasPos ? Pos : Neg).getNode();
3572 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3573 // idioms for rotate, and if the target supports rotation instructions, generate
3575 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3576 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3577 EVT VT = LHS.getValueType();
3578 if (!TLI.isTypeLegal(VT)) return nullptr;
3580 // The target must have at least one rotate flavor.
3581 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3582 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3583 if (!HasROTL && !HasROTR) return nullptr;
3585 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3586 SDValue LHSShift; // The shift.
3587 SDValue LHSMask; // AND value if any.
3588 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3589 return nullptr; // Not part of a rotate.
3591 SDValue RHSShift; // The shift.
3592 SDValue RHSMask; // AND value if any.
3593 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3594 return nullptr; // Not part of a rotate.
3596 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3597 return nullptr; // Not shifting the same value.
3599 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3600 return nullptr; // Shifts must disagree.
3602 // Canonicalize shl to left side in a shl/srl pair.
3603 if (RHSShift.getOpcode() == ISD::SHL) {
3604 std::swap(LHS, RHS);
3605 std::swap(LHSShift, RHSShift);
3606 std::swap(LHSMask , RHSMask );
3609 unsigned OpSizeInBits = VT.getSizeInBits();
3610 SDValue LHSShiftArg = LHSShift.getOperand(0);
3611 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3612 SDValue RHSShiftArg = RHSShift.getOperand(0);
3613 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3615 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3616 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3617 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3618 RHSShiftAmt.getOpcode() == ISD::Constant) {
3619 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3620 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3621 if ((LShVal + RShVal) != OpSizeInBits)
3624 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3625 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3627 // If there is an AND of either shifted operand, apply it to the result.
3628 if (LHSMask.getNode() || RHSMask.getNode()) {
3629 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3631 if (LHSMask.getNode()) {
3632 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3633 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3635 if (RHSMask.getNode()) {
3636 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3637 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3640 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3643 return Rot.getNode();
3646 // If there is a mask here, and we have a variable shift, we can't be sure
3647 // that we're masking out the right stuff.
3648 if (LHSMask.getNode() || RHSMask.getNode())
3651 // If the shift amount is sign/zext/any-extended just peel it off.
3652 SDValue LExtOp0 = LHSShiftAmt;
3653 SDValue RExtOp0 = RHSShiftAmt;
3654 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3655 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3656 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3657 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3658 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3659 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3660 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3661 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3662 LExtOp0 = LHSShiftAmt.getOperand(0);
3663 RExtOp0 = RHSShiftAmt.getOperand(0);
3666 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3667 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3671 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3672 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3679 SDValue DAGCombiner::visitXOR(SDNode *N) {
3680 SDValue N0 = N->getOperand(0);
3681 SDValue N1 = N->getOperand(1);
3682 SDValue LHS, RHS, CC;
3683 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3684 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3685 EVT VT = N0.getValueType();
3688 if (VT.isVector()) {
3689 SDValue FoldedVOp = SimplifyVBinOp(N);
3690 if (FoldedVOp.getNode()) return FoldedVOp;
3692 // fold (xor x, 0) -> x, vector edition
3693 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3695 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3699 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3700 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3701 return DAG.getConstant(0, VT);
3702 // fold (xor x, undef) -> undef
3703 if (N0.getOpcode() == ISD::UNDEF)
3705 if (N1.getOpcode() == ISD::UNDEF)
3707 // fold (xor c1, c2) -> c1^c2
3709 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3710 // canonicalize constant to RHS
3712 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3713 // fold (xor x, 0) -> x
3714 if (N1C && N1C->isNullValue())
3717 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3721 // fold !(x cc y) -> (x !cc y)
3722 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3723 bool isInt = LHS.getValueType().isInteger();
3724 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3727 if (!LegalOperations ||
3728 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3729 switch (N0.getOpcode()) {
3731 llvm_unreachable("Unhandled SetCC Equivalent!");
3733 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3734 case ISD::SELECT_CC:
3735 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3736 N0.getOperand(3), NotCC);
3741 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3742 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3743 N0.getNode()->hasOneUse() &&
3744 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3745 SDValue V = N0.getOperand(0);
3746 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3747 DAG.getConstant(1, V.getValueType()));
3748 AddToWorkList(V.getNode());
3749 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3752 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3753 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3754 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3755 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3756 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3757 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3758 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3759 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3760 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3761 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3764 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3765 if (N1C && N1C->isAllOnesValue() &&
3766 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3767 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3768 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3769 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3770 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3771 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3772 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3773 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3776 // fold (xor (and x, y), y) -> (and (not x), y)
3777 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3778 N0->getOperand(1) == N1) {
3779 SDValue X = N0->getOperand(0);
3780 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3781 AddToWorkList(NotX.getNode());
3782 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3784 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3785 if (N1C && N0.getOpcode() == ISD::XOR) {
3786 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3787 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3789 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3790 DAG.getConstant(N1C->getAPIntValue() ^
3791 N00C->getAPIntValue(), VT));
3793 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3794 DAG.getConstant(N1C->getAPIntValue() ^
3795 N01C->getAPIntValue(), VT));
3797 // fold (xor x, x) -> 0
3799 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3801 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3802 if (N0.getOpcode() == N1.getOpcode()) {
3803 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3804 if (Tmp.getNode()) return Tmp;
3807 // Simplify the expression using non-local knowledge.
3808 if (!VT.isVector() &&
3809 SimplifyDemandedBits(SDValue(N, 0)))
3810 return SDValue(N, 0);
3815 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3816 /// the shift amount is a constant.
3817 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3818 // We can't and shouldn't fold opaque constants.
3819 if (Amt->isOpaque())
3822 SDNode *LHS = N->getOperand(0).getNode();
3823 if (!LHS->hasOneUse()) return SDValue();
3825 // We want to pull some binops through shifts, so that we have (and (shift))
3826 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3827 // thing happens with address calculations, so it's important to canonicalize
3829 bool HighBitSet = false; // Can we transform this if the high bit is set?
3831 switch (LHS->getOpcode()) {
3832 default: return SDValue();
3835 HighBitSet = false; // We can only transform sra if the high bit is clear.
3838 HighBitSet = true; // We can only transform sra if the high bit is set.
3841 if (N->getOpcode() != ISD::SHL)
3842 return SDValue(); // only shl(add) not sr[al](add).
3843 HighBitSet = false; // We can only transform sra if the high bit is clear.
3847 // We require the RHS of the binop to be a constant and not opaque as well.
3848 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3849 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3851 // FIXME: disable this unless the input to the binop is a shift by a constant.
3852 // If it is not a shift, it pessimizes some common cases like:
3854 // void foo(int *X, int i) { X[i & 1235] = 1; }
3855 // int bar(int *X, int i) { return X[i & 255]; }
3856 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3857 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3858 BinOpLHSVal->getOpcode() != ISD::SRA &&
3859 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3860 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3863 EVT VT = N->getValueType(0);
3865 // If this is a signed shift right, and the high bit is modified by the
3866 // logical operation, do not perform the transformation. The highBitSet
3867 // boolean indicates the value of the high bit of the constant which would
3868 // cause it to be modified for this operation.
3869 if (N->getOpcode() == ISD::SRA) {
3870 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3871 if (BinOpRHSSignSet != HighBitSet)
3875 if (!TLI.isDesirableToCommuteWithShift(LHS))
3878 // Fold the constants, shifting the binop RHS by the shift amount.
3879 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3881 LHS->getOperand(1), N->getOperand(1));
3882 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3884 // Create the new shift.
3885 SDValue NewShift = DAG.getNode(N->getOpcode(),
3886 SDLoc(LHS->getOperand(0)),
3887 VT, LHS->getOperand(0), N->getOperand(1));
3889 // Create the new binop.
3890 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3893 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3894 assert(N->getOpcode() == ISD::TRUNCATE);
3895 assert(N->getOperand(0).getOpcode() == ISD::AND);
3897 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3898 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3899 SDValue N01 = N->getOperand(0).getOperand(1);
3901 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3902 EVT TruncVT = N->getValueType(0);
3903 SDValue N00 = N->getOperand(0).getOperand(0);
3904 APInt TruncC = N01C->getAPIntValue();
3905 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3907 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3908 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3909 DAG.getConstant(TruncC, TruncVT));
3916 SDValue DAGCombiner::visitRotate(SDNode *N) {
3917 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3918 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3919 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3920 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3921 if (NewOp1.getNode())
3922 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3923 N->getOperand(0), NewOp1);
3928 SDValue DAGCombiner::visitSHL(SDNode *N) {
3929 SDValue N0 = N->getOperand(0);
3930 SDValue N1 = N->getOperand(1);
3931 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3932 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3933 EVT VT = N0.getValueType();
3934 unsigned OpSizeInBits = VT.getScalarSizeInBits();
3937 if (VT.isVector()) {
3938 SDValue FoldedVOp = SimplifyVBinOp(N);
3939 if (FoldedVOp.getNode()) return FoldedVOp;
3941 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3942 // If setcc produces all-one true value then:
3943 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3944 if (N1CV && N1CV->isConstant()) {
3945 if (N0.getOpcode() == ISD::AND &&
3946 TLI.getBooleanContents(true) ==
3947 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3948 SDValue N00 = N0->getOperand(0);
3949 SDValue N01 = N0->getOperand(1);
3950 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3952 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3953 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3955 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3958 N1C = isConstOrConstSplat(N1);
3963 // fold (shl c1, c2) -> c1<<c2
3965 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3966 // fold (shl 0, x) -> 0
3967 if (N0C && N0C->isNullValue())
3969 // fold (shl x, c >= size(x)) -> undef
3970 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3971 return DAG.getUNDEF(VT);
3972 // fold (shl x, 0) -> x
3973 if (N1C && N1C->isNullValue())
3975 // fold (shl undef, x) -> 0
3976 if (N0.getOpcode() == ISD::UNDEF)
3977 return DAG.getConstant(0, VT);
3978 // if (shl x, c) is known to be zero, return 0
3979 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3980 APInt::getAllOnesValue(OpSizeInBits)))
3981 return DAG.getConstant(0, VT);
3982 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3983 if (N1.getOpcode() == ISD::TRUNCATE &&
3984 N1.getOperand(0).getOpcode() == ISD::AND) {
3985 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3986 if (NewOp1.getNode())
3987 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
3990 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3991 return SDValue(N, 0);
3993 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3994 if (N1C && N0.getOpcode() == ISD::SHL) {
3995 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
3996 uint64_t c1 = N0C1->getZExtValue();
3997 uint64_t c2 = N1C->getZExtValue();
3998 if (c1 + c2 >= OpSizeInBits)
3999 return DAG.getConstant(0, VT);
4000 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4001 DAG.getConstant(c1 + c2, N1.getValueType()));
4005 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4006 // For this to be valid, the second form must not preserve any of the bits
4007 // that are shifted out by the inner shift in the first form. This means
4008 // the outer shift size must be >= the number of bits added by the ext.
4009 // As a corollary, we don't care what kind of ext it is.
4010 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4011 N0.getOpcode() == ISD::ANY_EXTEND ||
4012 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4013 N0.getOperand(0).getOpcode() == ISD::SHL) {
4014 SDValue N0Op0 = N0.getOperand(0);
4015 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4016 uint64_t c1 = N0Op0C1->getZExtValue();
4017 uint64_t c2 = N1C->getZExtValue();
4018 EVT InnerShiftVT = N0Op0.getValueType();
4019 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4020 if (c2 >= OpSizeInBits - InnerShiftSize) {
4021 if (c1 + c2 >= OpSizeInBits)
4022 return DAG.getConstant(0, VT);
4023 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4024 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4025 N0Op0->getOperand(0)),
4026 DAG.getConstant(c1 + c2, N1.getValueType()));
4031 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4032 // Only fold this if the inner zext has no other uses to avoid increasing
4033 // the total number of instructions.
4034 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4035 N0.getOperand(0).getOpcode() == ISD::SRL) {
4036 SDValue N0Op0 = N0.getOperand(0);
4037 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4038 uint64_t c1 = N0Op0C1->getZExtValue();
4039 if (c1 < VT.getScalarSizeInBits()) {
4040 uint64_t c2 = N1C->getZExtValue();
4042 SDValue NewOp0 = N0.getOperand(0);
4043 EVT CountVT = NewOp0.getOperand(1).getValueType();
4044 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4045 NewOp0, DAG.getConstant(c2, CountVT));
4046 AddToWorkList(NewSHL.getNode());
4047 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4053 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4054 // (and (srl x, (sub c1, c2), MASK)
4055 // Only fold this if the inner shift has no other uses -- if it does, folding
4056 // this will increase the total number of instructions.
4057 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4058 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4059 uint64_t c1 = N0C1->getZExtValue();
4060 if (c1 < OpSizeInBits) {
4061 uint64_t c2 = N1C->getZExtValue();
4062 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4065 Mask = Mask.shl(c2 - c1);
4066 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4067 DAG.getConstant(c2 - c1, N1.getValueType()));
4069 Mask = Mask.lshr(c1 - c2);
4070 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4071 DAG.getConstant(c1 - c2, N1.getValueType()));
4073 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4074 DAG.getConstant(Mask, VT));
4078 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4079 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4080 unsigned BitSize = VT.getScalarSizeInBits();
4081 SDValue HiBitsMask =
4082 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4083 BitSize - N1C->getZExtValue()), VT);
4084 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4089 SDValue NewSHL = visitShiftByConstant(N, N1C);
4090 if (NewSHL.getNode())
4097 SDValue DAGCombiner::visitSRA(SDNode *N) {
4098 SDValue N0 = N->getOperand(0);
4099 SDValue N1 = N->getOperand(1);
4100 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4101 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4102 EVT VT = N0.getValueType();
4103 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4106 if (VT.isVector()) {
4107 SDValue FoldedVOp = SimplifyVBinOp(N);
4108 if (FoldedVOp.getNode()) return FoldedVOp;
4110 N1C = isConstOrConstSplat(N1);
4113 // fold (sra c1, c2) -> (sra c1, c2)
4115 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4116 // fold (sra 0, x) -> 0
4117 if (N0C && N0C->isNullValue())
4119 // fold (sra -1, x) -> -1
4120 if (N0C && N0C->isAllOnesValue())
4122 // fold (sra x, (setge c, size(x))) -> undef
4123 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4124 return DAG.getUNDEF(VT);
4125 // fold (sra x, 0) -> x
4126 if (N1C && N1C->isNullValue())
4128 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4130 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4131 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4132 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4134 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4135 ExtVT, VT.getVectorNumElements());
4136 if ((!LegalOperations ||
4137 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4138 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4139 N0.getOperand(0), DAG.getValueType(ExtVT));
4142 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4143 if (N1C && N0.getOpcode() == ISD::SRA) {
4144 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4145 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4146 if (Sum >= OpSizeInBits)
4147 Sum = OpSizeInBits - 1;
4148 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4149 DAG.getConstant(Sum, N1.getValueType()));
4153 // fold (sra (shl X, m), (sub result_size, n))
4154 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4155 // result_size - n != m.
4156 // If truncate is free for the target sext(shl) is likely to result in better
4158 if (N0.getOpcode() == ISD::SHL && N1C) {
4159 // Get the two constanst of the shifts, CN0 = m, CN = n.
4160 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4162 LLVMContext &Ctx = *DAG.getContext();
4163 // Determine what the truncate's result bitsize and type would be.
4164 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4167 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4169 // Determine the residual right-shift amount.
4170 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4172 // If the shift is not a no-op (in which case this should be just a sign
4173 // extend already), the truncated to type is legal, sign_extend is legal
4174 // on that type, and the truncate to that type is both legal and free,
4175 // perform the transform.
4176 if ((ShiftAmt > 0) &&
4177 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4178 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4179 TLI.isTruncateFree(VT, TruncVT)) {
4181 SDValue Amt = DAG.getConstant(ShiftAmt,
4182 getShiftAmountTy(N0.getOperand(0).getValueType()));
4183 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4184 N0.getOperand(0), Amt);
4185 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4187 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4188 N->getValueType(0), Trunc);
4193 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4194 if (N1.getOpcode() == ISD::TRUNCATE &&
4195 N1.getOperand(0).getOpcode() == ISD::AND) {
4196 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4197 if (NewOp1.getNode())
4198 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4201 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4202 // if c1 is equal to the number of bits the trunc removes
4203 if (N0.getOpcode() == ISD::TRUNCATE &&
4204 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4205 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4206 N0.getOperand(0).hasOneUse() &&
4207 N0.getOperand(0).getOperand(1).hasOneUse() &&
4209 SDValue N0Op0 = N0.getOperand(0);
4210 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4211 unsigned LargeShiftVal = LargeShift->getZExtValue();
4212 EVT LargeVT = N0Op0.getValueType();
4214 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4216 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4217 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4218 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4219 N0Op0.getOperand(0), Amt);
4220 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4225 // Simplify, based on bits shifted out of the LHS.
4226 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4227 return SDValue(N, 0);
4230 // If the sign bit is known to be zero, switch this to a SRL.
4231 if (DAG.SignBitIsZero(N0))
4232 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4235 SDValue NewSRA = visitShiftByConstant(N, N1C);
4236 if (NewSRA.getNode())
4243 SDValue DAGCombiner::visitSRL(SDNode *N) {
4244 SDValue N0 = N->getOperand(0);
4245 SDValue N1 = N->getOperand(1);
4246 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4247 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4248 EVT VT = N0.getValueType();
4249 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4252 if (VT.isVector()) {
4253 SDValue FoldedVOp = SimplifyVBinOp(N);
4254 if (FoldedVOp.getNode()) return FoldedVOp;
4256 N1C = isConstOrConstSplat(N1);
4259 // fold (srl c1, c2) -> c1 >>u c2
4261 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4262 // fold (srl 0, x) -> 0
4263 if (N0C && N0C->isNullValue())
4265 // fold (srl x, c >= size(x)) -> undef
4266 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4267 return DAG.getUNDEF(VT);
4268 // fold (srl x, 0) -> x
4269 if (N1C && N1C->isNullValue())
4271 // if (srl x, c) is known to be zero, return 0
4272 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4273 APInt::getAllOnesValue(OpSizeInBits)))
4274 return DAG.getConstant(0, VT);
4276 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4277 if (N1C && N0.getOpcode() == ISD::SRL) {
4278 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4279 uint64_t c1 = N01C->getZExtValue();
4280 uint64_t c2 = N1C->getZExtValue();
4281 if (c1 + c2 >= OpSizeInBits)
4282 return DAG.getConstant(0, VT);
4283 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4284 DAG.getConstant(c1 + c2, N1.getValueType()));
4288 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4289 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4290 N0.getOperand(0).getOpcode() == ISD::SRL &&
4291 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4293 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4294 uint64_t c2 = N1C->getZExtValue();
4295 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4296 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4297 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4298 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4299 if (c1 + OpSizeInBits == InnerShiftSize) {
4300 if (c1 + c2 >= InnerShiftSize)
4301 return DAG.getConstant(0, VT);
4302 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4303 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4304 N0.getOperand(0)->getOperand(0),
4305 DAG.getConstant(c1 + c2, ShiftCountVT)));
4309 // fold (srl (shl x, c), c) -> (and x, cst2)
4310 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4311 unsigned BitSize = N0.getScalarValueSizeInBits();
4312 if (BitSize <= 64) {
4313 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4314 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4315 DAG.getConstant(~0ULL >> ShAmt, VT));
4319 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4320 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4321 // Shifting in all undef bits?
4322 EVT SmallVT = N0.getOperand(0).getValueType();
4323 unsigned BitSize = SmallVT.getScalarSizeInBits();
4324 if (N1C->getZExtValue() >= BitSize)
4325 return DAG.getUNDEF(VT);
4327 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4328 uint64_t ShiftAmt = N1C->getZExtValue();
4329 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4331 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4332 AddToWorkList(SmallShift.getNode());
4333 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4334 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4335 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4336 DAG.getConstant(Mask, VT));
4340 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4341 // bit, which is unmodified by sra.
4342 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4343 if (N0.getOpcode() == ISD::SRA)
4344 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4347 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4348 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4349 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4350 APInt KnownZero, KnownOne;
4351 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4353 // If any of the input bits are KnownOne, then the input couldn't be all
4354 // zeros, thus the result of the srl will always be zero.
4355 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4357 // If all of the bits input the to ctlz node are known to be zero, then
4358 // the result of the ctlz is "32" and the result of the shift is one.
4359 APInt UnknownBits = ~KnownZero;
4360 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4362 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4363 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4364 // Okay, we know that only that the single bit specified by UnknownBits
4365 // could be set on input to the CTLZ node. If this bit is set, the SRL
4366 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4367 // to an SRL/XOR pair, which is likely to simplify more.
4368 unsigned ShAmt = UnknownBits.countTrailingZeros();
4369 SDValue Op = N0.getOperand(0);
4372 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4373 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4374 AddToWorkList(Op.getNode());
4377 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4378 Op, DAG.getConstant(1, VT));
4382 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4383 if (N1.getOpcode() == ISD::TRUNCATE &&
4384 N1.getOperand(0).getOpcode() == ISD::AND) {
4385 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4386 if (NewOp1.getNode())
4387 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4390 // fold operands of srl based on knowledge that the low bits are not
4392 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4393 return SDValue(N, 0);
4396 SDValue NewSRL = visitShiftByConstant(N, N1C);
4397 if (NewSRL.getNode())
4401 // Attempt to convert a srl of a load into a narrower zero-extending load.
4402 SDValue NarrowLoad = ReduceLoadWidth(N);
4403 if (NarrowLoad.getNode())
4406 // Here is a common situation. We want to optimize:
4409 // %b = and i32 %a, 2
4410 // %c = srl i32 %b, 1
4411 // brcond i32 %c ...
4417 // %c = setcc eq %b, 0
4420 // However when after the source operand of SRL is optimized into AND, the SRL
4421 // itself may not be optimized further. Look for it and add the BRCOND into
4423 if (N->hasOneUse()) {
4424 SDNode *Use = *N->use_begin();
4425 if (Use->getOpcode() == ISD::BRCOND)
4427 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4428 // Also look pass the truncate.
4429 Use = *Use->use_begin();
4430 if (Use->getOpcode() == ISD::BRCOND)
4438 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4439 SDValue N0 = N->getOperand(0);
4440 EVT VT = N->getValueType(0);
4442 // fold (ctlz c1) -> c2
4443 if (isa<ConstantSDNode>(N0))
4444 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4448 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4449 SDValue N0 = N->getOperand(0);
4450 EVT VT = N->getValueType(0);
4452 // fold (ctlz_zero_undef c1) -> c2
4453 if (isa<ConstantSDNode>(N0))
4454 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4458 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4459 SDValue N0 = N->getOperand(0);
4460 EVT VT = N->getValueType(0);
4462 // fold (cttz c1) -> c2
4463 if (isa<ConstantSDNode>(N0))
4464 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4468 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4469 SDValue N0 = N->getOperand(0);
4470 EVT VT = N->getValueType(0);
4472 // fold (cttz_zero_undef c1) -> c2
4473 if (isa<ConstantSDNode>(N0))
4474 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4478 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4479 SDValue N0 = N->getOperand(0);
4480 EVT VT = N->getValueType(0);
4482 // fold (ctpop c1) -> c2
4483 if (isa<ConstantSDNode>(N0))
4484 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4488 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4489 SDValue N0 = N->getOperand(0);
4490 SDValue N1 = N->getOperand(1);
4491 SDValue N2 = N->getOperand(2);
4492 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4493 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4494 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4495 EVT VT = N->getValueType(0);
4496 EVT VT0 = N0.getValueType();
4498 // fold (select C, X, X) -> X
4501 // fold (select true, X, Y) -> X
4502 if (N0C && !N0C->isNullValue())
4504 // fold (select false, X, Y) -> Y
4505 if (N0C && N0C->isNullValue())
4507 // fold (select C, 1, X) -> (or C, X)
4508 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4509 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4510 // fold (select C, 0, 1) -> (xor C, 1)
4511 if (VT.isInteger() &&
4514 TLI.getBooleanContents(false) ==
4515 TargetLowering::ZeroOrOneBooleanContent)) &&
4516 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4519 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4520 N0, DAG.getConstant(1, VT0));
4521 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4522 N0, DAG.getConstant(1, VT0));
4523 AddToWorkList(XORNode.getNode());
4525 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4526 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4528 // fold (select C, 0, X) -> (and (not C), X)
4529 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4530 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4531 AddToWorkList(NOTNode.getNode());
4532 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4534 // fold (select C, X, 1) -> (or (not C), X)
4535 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4536 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4537 AddToWorkList(NOTNode.getNode());
4538 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4540 // fold (select C, X, 0) -> (and C, X)
4541 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4542 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4543 // fold (select X, X, Y) -> (or X, Y)
4544 // fold (select X, 1, Y) -> (or X, Y)
4545 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4546 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4547 // fold (select X, Y, X) -> (and X, Y)
4548 // fold (select X, Y, 0) -> (and X, Y)
4549 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4550 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4552 // If we can fold this based on the true/false value, do so.
4553 if (SimplifySelectOps(N, N1, N2))
4554 return SDValue(N, 0); // Don't revisit N.
4556 // fold selects based on a setcc into other things, such as min/max/abs
4557 if (N0.getOpcode() == ISD::SETCC) {
4559 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4560 // having to say they don't support SELECT_CC on every type the DAG knows
4561 // about, since there is no way to mark an opcode illegal at all value types
4562 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4563 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4564 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4565 N0.getOperand(0), N0.getOperand(1),
4566 N1, N2, N0.getOperand(2));
4567 return SimplifySelect(SDLoc(N), N0, N1, N2);
4574 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4577 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4579 // Split the inputs.
4580 SDValue Lo, Hi, LL, LH, RL, RH;
4581 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4582 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4584 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4585 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4587 return std::make_pair(Lo, Hi);
4590 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4591 SDValue N0 = N->getOperand(0);
4592 SDValue N1 = N->getOperand(1);
4593 SDValue N2 = N->getOperand(2);
4596 // Canonicalize integer abs.
4597 // vselect (setg[te] X, 0), X, -X ->
4598 // vselect (setgt X, -1), X, -X ->
4599 // vselect (setl[te] X, 0), -X, X ->
4600 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4601 if (N0.getOpcode() == ISD::SETCC) {
4602 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4603 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4605 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4607 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4608 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4609 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4610 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4611 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4612 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4613 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4616 EVT VT = LHS.getValueType();
4617 SDValue Shift = DAG.getNode(
4618 ISD::SRA, DL, VT, LHS,
4619 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4620 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4621 AddToWorkList(Shift.getNode());
4622 AddToWorkList(Add.getNode());
4623 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4627 // If the VSELECT result requires splitting and the mask is provided by a
4628 // SETCC, then split both nodes and its operands before legalization. This
4629 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4630 // and enables future optimizations (e.g. min/max pattern matching on X86).
4631 if (N0.getOpcode() == ISD::SETCC) {
4632 EVT VT = N->getValueType(0);
4634 // Check if any splitting is required.
4635 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4636 TargetLowering::TypeSplitVector)
4639 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4640 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4641 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4642 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4644 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4645 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4647 // Add the new VSELECT nodes to the work list in case they need to be split
4649 AddToWorkList(Lo.getNode());
4650 AddToWorkList(Hi.getNode());
4652 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4655 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4656 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4658 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4659 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4665 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4666 SDValue N0 = N->getOperand(0);
4667 SDValue N1 = N->getOperand(1);
4668 SDValue N2 = N->getOperand(2);
4669 SDValue N3 = N->getOperand(3);
4670 SDValue N4 = N->getOperand(4);
4671 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4673 // fold select_cc lhs, rhs, x, x, cc -> x
4677 // Determine if the condition we're dealing with is constant
4678 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4679 N0, N1, CC, SDLoc(N), false);
4680 if (SCC.getNode()) {
4681 AddToWorkList(SCC.getNode());
4683 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4684 if (!SCCC->isNullValue())
4685 return N2; // cond always true -> true val
4687 return N3; // cond always false -> false val
4690 // Fold to a simpler select_cc
4691 if (SCC.getOpcode() == ISD::SETCC)
4692 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4693 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4697 // If we can fold this based on the true/false value, do so.
4698 if (SimplifySelectOps(N, N2, N3))
4699 return SDValue(N, 0); // Don't revisit N.
4701 // fold select_cc into other things, such as min/max/abs
4702 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4705 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4706 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4707 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4711 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4712 // dag node into a ConstantSDNode or a build_vector of constants.
4713 // This function is called by the DAGCombiner when visiting sext/zext/aext
4714 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4715 // Vector extends are not folded if operations are legal; this is to
4716 // avoid introducing illegal build_vector dag nodes.
4717 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4718 SelectionDAG &DAG, bool LegalTypes,
4719 bool LegalOperations) {
4720 unsigned Opcode = N->getOpcode();
4721 SDValue N0 = N->getOperand(0);
4722 EVT VT = N->getValueType(0);
4724 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4725 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4727 // fold (sext c1) -> c1
4728 // fold (zext c1) -> c1
4729 // fold (aext c1) -> c1
4730 if (isa<ConstantSDNode>(N0))
4731 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4733 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4734 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4735 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4736 EVT SVT = VT.getScalarType();
4737 if (!(VT.isVector() &&
4738 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4739 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4742 // We can fold this node into a build_vector.
4743 unsigned VTBits = SVT.getSizeInBits();
4744 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4745 unsigned ShAmt = VTBits - EVTBits;
4746 SmallVector<SDValue, 8> Elts;
4747 unsigned NumElts = N0->getNumOperands();
4750 for (unsigned i=0; i != NumElts; ++i) {
4751 SDValue Op = N0->getOperand(i);
4752 if (Op->getOpcode() == ISD::UNDEF) {
4753 Elts.push_back(DAG.getUNDEF(SVT));
4757 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4758 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4759 if (Opcode == ISD::SIGN_EXTEND)
4760 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4763 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4767 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4770 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4771 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4772 // transformation. Returns true if extension are possible and the above
4773 // mentioned transformation is profitable.
4774 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4776 SmallVectorImpl<SDNode *> &ExtendNodes,
4777 const TargetLowering &TLI) {
4778 bool HasCopyToRegUses = false;
4779 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4780 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4781 UE = N0.getNode()->use_end();
4786 if (UI.getUse().getResNo() != N0.getResNo())
4788 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4789 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4790 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4791 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4792 // Sign bits will be lost after a zext.
4795 for (unsigned i = 0; i != 2; ++i) {
4796 SDValue UseOp = User->getOperand(i);
4799 if (!isa<ConstantSDNode>(UseOp))
4804 ExtendNodes.push_back(User);
4807 // If truncates aren't free and there are users we can't
4808 // extend, it isn't worthwhile.
4811 // Remember if this value is live-out.
4812 if (User->getOpcode() == ISD::CopyToReg)
4813 HasCopyToRegUses = true;
4816 if (HasCopyToRegUses) {
4817 bool BothLiveOut = false;
4818 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4820 SDUse &Use = UI.getUse();
4821 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4827 // Both unextended and extended values are live out. There had better be
4828 // a good reason for the transformation.
4829 return ExtendNodes.size();
4834 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4835 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4836 ISD::NodeType ExtType) {
4837 // Extend SetCC uses if necessary.
4838 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4839 SDNode *SetCC = SetCCs[i];
4840 SmallVector<SDValue, 4> Ops;
4842 for (unsigned j = 0; j != 2; ++j) {
4843 SDValue SOp = SetCC->getOperand(j);
4845 Ops.push_back(ExtLoad);
4847 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4850 Ops.push_back(SetCC->getOperand(2));
4851 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4855 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4856 SDValue N0 = N->getOperand(0);
4857 EVT VT = N->getValueType(0);
4859 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4861 return SDValue(Res, 0);
4863 // fold (sext (sext x)) -> (sext x)
4864 // fold (sext (aext x)) -> (sext x)
4865 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4866 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4869 if (N0.getOpcode() == ISD::TRUNCATE) {
4870 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4871 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4872 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4873 if (NarrowLoad.getNode()) {
4874 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4875 if (NarrowLoad.getNode() != N0.getNode()) {
4876 CombineTo(N0.getNode(), NarrowLoad);
4877 // CombineTo deleted the truncate, if needed, but not what's under it.
4880 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4883 // See if the value being truncated is already sign extended. If so, just
4884 // eliminate the trunc/sext pair.
4885 SDValue Op = N0.getOperand(0);
4886 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4887 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4888 unsigned DestBits = VT.getScalarType().getSizeInBits();
4889 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4891 if (OpBits == DestBits) {
4892 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4893 // bits, it is already ready.
4894 if (NumSignBits > DestBits-MidBits)
4896 } else if (OpBits < DestBits) {
4897 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4898 // bits, just sext from i32.
4899 if (NumSignBits > OpBits-MidBits)
4900 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4902 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4903 // bits, just truncate to i32.
4904 if (NumSignBits > OpBits-MidBits)
4905 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4908 // fold (sext (truncate x)) -> (sextinreg x).
4909 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4910 N0.getValueType())) {
4911 if (OpBits < DestBits)
4912 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4913 else if (OpBits > DestBits)
4914 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4915 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4916 DAG.getValueType(N0.getValueType()));
4920 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4921 // None of the supported targets knows how to perform load and sign extend
4922 // on vectors in one instruction. We only perform this transformation on
4924 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4925 ISD::isUNINDEXEDLoad(N0.getNode()) &&
4926 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4927 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4928 bool DoXform = true;
4929 SmallVector<SDNode*, 4> SetCCs;
4930 if (!N0.hasOneUse())
4931 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4933 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4934 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4936 LN0->getBasePtr(), N0.getValueType(),
4937 LN0->getMemOperand());
4938 CombineTo(N, ExtLoad);
4939 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4940 N0.getValueType(), ExtLoad);
4941 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4942 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4944 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4948 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4949 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4950 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4951 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4952 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4953 EVT MemVT = LN0->getMemoryVT();
4954 if ((!LegalOperations && !LN0->isVolatile()) ||
4955 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4956 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4958 LN0->getBasePtr(), MemVT,
4959 LN0->getMemOperand());
4960 CombineTo(N, ExtLoad);
4961 CombineTo(N0.getNode(),
4962 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4963 N0.getValueType(), ExtLoad),
4964 ExtLoad.getValue(1));
4965 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4969 // fold (sext (and/or/xor (load x), cst)) ->
4970 // (and/or/xor (sextload x), (sext cst))
4971 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4972 N0.getOpcode() == ISD::XOR) &&
4973 isa<LoadSDNode>(N0.getOperand(0)) &&
4974 N0.getOperand(1).getOpcode() == ISD::Constant &&
4975 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4976 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4977 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4978 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
4979 bool DoXform = true;
4980 SmallVector<SDNode*, 4> SetCCs;
4981 if (!N0.hasOneUse())
4982 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4985 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4986 LN0->getChain(), LN0->getBasePtr(),
4988 LN0->getMemOperand());
4989 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4990 Mask = Mask.sext(VT.getSizeInBits());
4991 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4992 ExtLoad, DAG.getConstant(Mask, VT));
4993 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4994 SDLoc(N0.getOperand(0)),
4995 N0.getOperand(0).getValueType(), ExtLoad);
4997 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4998 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5000 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5005 if (N0.getOpcode() == ISD::SETCC) {
5006 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5007 // Only do this before legalize for now.
5008 if (VT.isVector() && !LegalOperations &&
5009 TLI.getBooleanContents(true) ==
5010 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5011 EVT N0VT = N0.getOperand(0).getValueType();
5012 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5013 // of the same size as the compared operands. Only optimize sext(setcc())
5014 // if this is the case.
5015 EVT SVT = getSetCCResultType(N0VT);
5017 // We know that the # elements of the results is the same as the
5018 // # elements of the compare (and the # elements of the compare result
5019 // for that matter). Check to see that they are the same size. If so,
5020 // we know that the element size of the sext'd result matches the
5021 // element size of the compare operands.
5022 if (VT.getSizeInBits() == SVT.getSizeInBits())
5023 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5025 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5027 // If the desired elements are smaller or larger than the source
5028 // elements we can use a matching integer vector type and then
5029 // truncate/sign extend
5030 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5031 if (SVT == MatchingVectorType) {
5032 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5033 N0.getOperand(0), N0.getOperand(1),
5034 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5035 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5039 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5040 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5042 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5044 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5045 NegOne, DAG.getConstant(0, VT),
5046 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5047 if (SCC.getNode()) return SCC;
5049 if (!VT.isVector()) {
5050 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5051 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5053 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5054 SDValue SetCC = DAG.getSetCC(DL,
5056 N0.getOperand(0), N0.getOperand(1), CC);
5057 EVT SelectVT = getSetCCResultType(VT);
5058 return DAG.getSelect(DL, VT,
5059 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5060 NegOne, DAG.getConstant(0, VT));
5066 // fold (sext x) -> (zext x) if the sign bit is known zero.
5067 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5068 DAG.SignBitIsZero(N0))
5069 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5074 // isTruncateOf - If N is a truncate of some other value, return true, record
5075 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5076 // This function computes KnownZero to avoid a duplicated call to
5077 // computeKnownBits in the caller.
5078 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5081 if (N->getOpcode() == ISD::TRUNCATE) {
5082 Op = N->getOperand(0);
5083 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5087 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5088 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5091 SDValue Op0 = N->getOperand(0);
5092 SDValue Op1 = N->getOperand(1);
5093 assert(Op0.getValueType() == Op1.getValueType());
5095 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5096 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5097 if (COp0 && COp0->isNullValue())
5099 else if (COp1 && COp1->isNullValue())
5104 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5106 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5112 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5113 SDValue N0 = N->getOperand(0);
5114 EVT VT = N->getValueType(0);
5116 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5118 return SDValue(Res, 0);
5120 // fold (zext (zext x)) -> (zext x)
5121 // fold (zext (aext x)) -> (zext x)
5122 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5123 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5126 // fold (zext (truncate x)) -> (zext x) or
5127 // (zext (truncate x)) -> (truncate x)
5128 // This is valid when the truncated bits of x are already zero.
5129 // FIXME: We should extend this to work for vectors too.
5132 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5133 APInt TruncatedBits =
5134 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5135 APInt(Op.getValueSizeInBits(), 0) :
5136 APInt::getBitsSet(Op.getValueSizeInBits(),
5137 N0.getValueSizeInBits(),
5138 std::min(Op.getValueSizeInBits(),
5139 VT.getSizeInBits()));
5140 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5141 if (VT.bitsGT(Op.getValueType()))
5142 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5143 if (VT.bitsLT(Op.getValueType()))
5144 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5150 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5151 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5152 if (N0.getOpcode() == ISD::TRUNCATE) {
5153 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5154 if (NarrowLoad.getNode()) {
5155 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5156 if (NarrowLoad.getNode() != N0.getNode()) {
5157 CombineTo(N0.getNode(), NarrowLoad);
5158 // CombineTo deleted the truncate, if needed, but not what's under it.
5161 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5165 // fold (zext (truncate x)) -> (and x, mask)
5166 if (N0.getOpcode() == ISD::TRUNCATE &&
5167 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5169 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5170 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5171 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5172 if (NarrowLoad.getNode()) {
5173 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5174 if (NarrowLoad.getNode() != N0.getNode()) {
5175 CombineTo(N0.getNode(), NarrowLoad);
5176 // CombineTo deleted the truncate, if needed, but not what's under it.
5179 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5182 SDValue Op = N0.getOperand(0);
5183 if (Op.getValueType().bitsLT(VT)) {
5184 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5185 AddToWorkList(Op.getNode());
5186 } else if (Op.getValueType().bitsGT(VT)) {
5187 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5188 AddToWorkList(Op.getNode());
5190 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5191 N0.getValueType().getScalarType());
5194 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5195 // if either of the casts is not free.
5196 if (N0.getOpcode() == ISD::AND &&
5197 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5198 N0.getOperand(1).getOpcode() == ISD::Constant &&
5199 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5200 N0.getValueType()) ||
5201 !TLI.isZExtFree(N0.getValueType(), VT))) {
5202 SDValue X = N0.getOperand(0).getOperand(0);
5203 if (X.getValueType().bitsLT(VT)) {
5204 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5205 } else if (X.getValueType().bitsGT(VT)) {
5206 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5208 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5209 Mask = Mask.zext(VT.getSizeInBits());
5210 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5211 X, DAG.getConstant(Mask, VT));
5214 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5215 // None of the supported targets knows how to perform load and vector_zext
5216 // on vectors in one instruction. We only perform this transformation on
5218 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5219 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5220 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5221 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5222 bool DoXform = true;
5223 SmallVector<SDNode*, 4> SetCCs;
5224 if (!N0.hasOneUse())
5225 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5227 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5228 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5230 LN0->getBasePtr(), N0.getValueType(),
5231 LN0->getMemOperand());
5232 CombineTo(N, ExtLoad);
5233 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5234 N0.getValueType(), ExtLoad);
5235 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5237 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5239 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5243 // fold (zext (and/or/xor (load x), cst)) ->
5244 // (and/or/xor (zextload x), (zext cst))
5245 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5246 N0.getOpcode() == ISD::XOR) &&
5247 isa<LoadSDNode>(N0.getOperand(0)) &&
5248 N0.getOperand(1).getOpcode() == ISD::Constant &&
5249 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5250 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5251 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5252 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5253 bool DoXform = true;
5254 SmallVector<SDNode*, 4> SetCCs;
5255 if (!N0.hasOneUse())
5256 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5259 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5260 LN0->getChain(), LN0->getBasePtr(),
5262 LN0->getMemOperand());
5263 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5264 Mask = Mask.zext(VT.getSizeInBits());
5265 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5266 ExtLoad, DAG.getConstant(Mask, VT));
5267 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5268 SDLoc(N0.getOperand(0)),
5269 N0.getOperand(0).getValueType(), ExtLoad);
5271 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5272 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5274 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5279 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5280 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5281 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5282 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5283 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5284 EVT MemVT = LN0->getMemoryVT();
5285 if ((!LegalOperations && !LN0->isVolatile()) ||
5286 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5287 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5289 LN0->getBasePtr(), MemVT,
5290 LN0->getMemOperand());
5291 CombineTo(N, ExtLoad);
5292 CombineTo(N0.getNode(),
5293 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5295 ExtLoad.getValue(1));
5296 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5300 if (N0.getOpcode() == ISD::SETCC) {
5301 if (!LegalOperations && VT.isVector() &&
5302 N0.getValueType().getVectorElementType() == MVT::i1) {
5303 EVT N0VT = N0.getOperand(0).getValueType();
5304 if (getSetCCResultType(N0VT) == N0.getValueType())
5307 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5308 // Only do this before legalize for now.
5309 EVT EltVT = VT.getVectorElementType();
5310 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5311 DAG.getConstant(1, EltVT));
5312 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5313 // We know that the # elements of the results is the same as the
5314 // # elements of the compare (and the # elements of the compare result
5315 // for that matter). Check to see that they are the same size. If so,
5316 // we know that the element size of the sext'd result matches the
5317 // element size of the compare operands.
5318 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5319 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5321 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5322 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5325 // If the desired elements are smaller or larger than the source
5326 // elements we can use a matching integer vector type and then
5327 // truncate/sign extend
5328 EVT MatchingElementType =
5329 EVT::getIntegerVT(*DAG.getContext(),
5330 N0VT.getScalarType().getSizeInBits());
5331 EVT MatchingVectorType =
5332 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5333 N0VT.getVectorNumElements());
5335 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5337 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5338 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5339 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5340 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5343 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5345 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5346 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5347 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5348 if (SCC.getNode()) return SCC;
5351 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5352 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5353 isa<ConstantSDNode>(N0.getOperand(1)) &&
5354 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5356 SDValue ShAmt = N0.getOperand(1);
5357 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5358 if (N0.getOpcode() == ISD::SHL) {
5359 SDValue InnerZExt = N0.getOperand(0);
5360 // If the original shl may be shifting out bits, do not perform this
5362 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5363 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5364 if (ShAmtVal > KnownZeroBits)
5370 // Ensure that the shift amount is wide enough for the shifted value.
5371 if (VT.getSizeInBits() >= 256)
5372 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5374 return DAG.getNode(N0.getOpcode(), DL, VT,
5375 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5382 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5383 SDValue N0 = N->getOperand(0);
5384 EVT VT = N->getValueType(0);
5386 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5388 return SDValue(Res, 0);
5390 // fold (aext (aext x)) -> (aext x)
5391 // fold (aext (zext x)) -> (zext x)
5392 // fold (aext (sext x)) -> (sext x)
5393 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5394 N0.getOpcode() == ISD::ZERO_EXTEND ||
5395 N0.getOpcode() == ISD::SIGN_EXTEND)
5396 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5398 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5399 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5400 if (N0.getOpcode() == ISD::TRUNCATE) {
5401 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5402 if (NarrowLoad.getNode()) {
5403 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5404 if (NarrowLoad.getNode() != N0.getNode()) {
5405 CombineTo(N0.getNode(), NarrowLoad);
5406 // CombineTo deleted the truncate, if needed, but not what's under it.
5409 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5413 // fold (aext (truncate x))
5414 if (N0.getOpcode() == ISD::TRUNCATE) {
5415 SDValue TruncOp = N0.getOperand(0);
5416 if (TruncOp.getValueType() == VT)
5417 return TruncOp; // x iff x size == zext size.
5418 if (TruncOp.getValueType().bitsGT(VT))
5419 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5420 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5423 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5424 // if the trunc is not free.
5425 if (N0.getOpcode() == ISD::AND &&
5426 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5427 N0.getOperand(1).getOpcode() == ISD::Constant &&
5428 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5429 N0.getValueType())) {
5430 SDValue X = N0.getOperand(0).getOperand(0);
5431 if (X.getValueType().bitsLT(VT)) {
5432 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5433 } else if (X.getValueType().bitsGT(VT)) {
5434 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5436 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5437 Mask = Mask.zext(VT.getSizeInBits());
5438 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5439 X, DAG.getConstant(Mask, VT));
5442 // fold (aext (load x)) -> (aext (truncate (extload x)))
5443 // None of the supported targets knows how to perform load and any_ext
5444 // on vectors in one instruction. We only perform this transformation on
5446 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5447 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5448 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5449 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5450 bool DoXform = true;
5451 SmallVector<SDNode*, 4> SetCCs;
5452 if (!N0.hasOneUse())
5453 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5455 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5456 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5458 LN0->getBasePtr(), N0.getValueType(),
5459 LN0->getMemOperand());
5460 CombineTo(N, ExtLoad);
5461 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5462 N0.getValueType(), ExtLoad);
5463 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5464 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5466 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5470 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5471 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5472 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5473 if (N0.getOpcode() == ISD::LOAD &&
5474 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5476 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5477 ISD::LoadExtType ExtType = LN0->getExtensionType();
5478 EVT MemVT = LN0->getMemoryVT();
5479 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5480 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5481 VT, LN0->getChain(), LN0->getBasePtr(),
5482 MemVT, LN0->getMemOperand());
5483 CombineTo(N, ExtLoad);
5484 CombineTo(N0.getNode(),
5485 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5486 N0.getValueType(), ExtLoad),
5487 ExtLoad.getValue(1));
5488 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5492 if (N0.getOpcode() == ISD::SETCC) {
5494 // aext(setcc) -> vsetcc
5495 // aext(setcc) -> truncate(vsetcc)
5496 // aext(setcc) -> aext(vsetcc)
5497 // Only do this before legalize for now.
5498 if (VT.isVector() && !LegalOperations) {
5499 EVT N0VT = N0.getOperand(0).getValueType();
5500 // We know that the # elements of the results is the same as the
5501 // # elements of the compare (and the # elements of the compare result
5502 // for that matter). Check to see that they are the same size. If so,
5503 // we know that the element size of the sext'd result matches the
5504 // element size of the compare operands.
5505 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5506 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5508 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5509 // If the desired elements are smaller or larger than the source
5510 // elements we can use a matching integer vector type and then
5511 // truncate/any extend
5513 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5515 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5517 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5518 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5522 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5524 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5525 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5526 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5534 /// GetDemandedBits - See if the specified operand can be simplified with the
5535 /// knowledge that only the bits specified by Mask are used. If so, return the
5536 /// simpler operand, otherwise return a null SDValue.
5537 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5538 switch (V.getOpcode()) {
5540 case ISD::Constant: {
5541 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5542 assert(CV && "Const value should be ConstSDNode.");
5543 const APInt &CVal = CV->getAPIntValue();
5544 APInt NewVal = CVal & Mask;
5546 return DAG.getConstant(NewVal, V.getValueType());
5551 // If the LHS or RHS don't contribute bits to the or, drop them.
5552 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5553 return V.getOperand(1);
5554 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5555 return V.getOperand(0);
5558 // Only look at single-use SRLs.
5559 if (!V.getNode()->hasOneUse())
5561 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5562 // See if we can recursively simplify the LHS.
5563 unsigned Amt = RHSC->getZExtValue();
5565 // Watch out for shift count overflow though.
5566 if (Amt >= Mask.getBitWidth()) break;
5567 APInt NewMask = Mask << Amt;
5568 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5569 if (SimplifyLHS.getNode())
5570 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5571 SimplifyLHS, V.getOperand(1));
5577 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5578 /// bits and then truncated to a narrower type and where N is a multiple
5579 /// of number of bits of the narrower type, transform it to a narrower load
5580 /// from address + N / num of bits of new type. If the result is to be
5581 /// extended, also fold the extension to form a extending load.
5582 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5583 unsigned Opc = N->getOpcode();
5585 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5586 SDValue N0 = N->getOperand(0);
5587 EVT VT = N->getValueType(0);
5590 // This transformation isn't valid for vector loads.
5594 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5596 if (Opc == ISD::SIGN_EXTEND_INREG) {
5597 ExtType = ISD::SEXTLOAD;
5598 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5599 } else if (Opc == ISD::SRL) {
5600 // Another special-case: SRL is basically zero-extending a narrower value.
5601 ExtType = ISD::ZEXTLOAD;
5603 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5604 if (!N01) return SDValue();
5605 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5606 VT.getSizeInBits() - N01->getZExtValue());
5608 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5611 unsigned EVTBits = ExtVT.getSizeInBits();
5613 // Do not generate loads of non-round integer types since these can
5614 // be expensive (and would be wrong if the type is not byte sized).
5615 if (!ExtVT.isRound())
5619 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5620 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5621 ShAmt = N01->getZExtValue();
5622 // Is the shift amount a multiple of size of VT?
5623 if ((ShAmt & (EVTBits-1)) == 0) {
5624 N0 = N0.getOperand(0);
5625 // Is the load width a multiple of size of VT?
5626 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5630 // At this point, we must have a load or else we can't do the transform.
5631 if (!isa<LoadSDNode>(N0)) return SDValue();
5633 // Because a SRL must be assumed to *need* to zero-extend the high bits
5634 // (as opposed to anyext the high bits), we can't combine the zextload
5635 // lowering of SRL and an sextload.
5636 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5639 // If the shift amount is larger than the input type then we're not
5640 // accessing any of the loaded bytes. If the load was a zextload/extload
5641 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5642 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5647 // If the load is shifted left (and the result isn't shifted back right),
5648 // we can fold the truncate through the shift.
5649 unsigned ShLeftAmt = 0;
5650 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5651 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5652 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5653 ShLeftAmt = N01->getZExtValue();
5654 N0 = N0.getOperand(0);
5658 // If we haven't found a load, we can't narrow it. Don't transform one with
5659 // multiple uses, this would require adding a new load.
5660 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5663 // Don't change the width of a volatile load.
5664 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5665 if (LN0->isVolatile())
5668 // Verify that we are actually reducing a load width here.
5669 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5672 // For the transform to be legal, the load must produce only two values
5673 // (the value loaded and the chain). Don't transform a pre-increment
5674 // load, for example, which produces an extra value. Otherwise the
5675 // transformation is not equivalent, and the downstream logic to replace
5676 // uses gets things wrong.
5677 if (LN0->getNumValues() > 2)
5680 // If the load that we're shrinking is an extload and we're not just
5681 // discarding the extension we can't simply shrink the load. Bail.
5682 // TODO: It would be possible to merge the extensions in some cases.
5683 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5684 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5687 EVT PtrType = N0.getOperand(1).getValueType();
5689 if (PtrType == MVT::Untyped || PtrType.isExtended())
5690 // It's not possible to generate a constant of extended or untyped type.
5693 // For big endian targets, we need to adjust the offset to the pointer to
5694 // load the correct bytes.
5695 if (TLI.isBigEndian()) {
5696 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5697 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5698 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5701 uint64_t PtrOff = ShAmt / 8;
5702 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5703 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5704 PtrType, LN0->getBasePtr(),
5705 DAG.getConstant(PtrOff, PtrType));
5706 AddToWorkList(NewPtr.getNode());
5709 if (ExtType == ISD::NON_EXTLOAD)
5710 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5711 LN0->getPointerInfo().getWithOffset(PtrOff),
5712 LN0->isVolatile(), LN0->isNonTemporal(),
5713 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5715 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5716 LN0->getPointerInfo().getWithOffset(PtrOff),
5717 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5718 NewAlign, LN0->getTBAAInfo());
5720 // Replace the old load's chain with the new load's chain.
5721 WorkListRemover DeadNodes(*this);
5722 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5724 // Shift the result left, if we've swallowed a left shift.
5725 SDValue Result = Load;
5726 if (ShLeftAmt != 0) {
5727 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5728 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5730 // If the shift amount is as large as the result size (but, presumably,
5731 // no larger than the source) then the useful bits of the result are
5732 // zero; we can't simply return the shortened shift, because the result
5733 // of that operation is undefined.
5734 if (ShLeftAmt >= VT.getSizeInBits())
5735 Result = DAG.getConstant(0, VT);
5737 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5738 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5741 // Return the new loaded value.
5745 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5746 SDValue N0 = N->getOperand(0);
5747 SDValue N1 = N->getOperand(1);
5748 EVT VT = N->getValueType(0);
5749 EVT EVT = cast<VTSDNode>(N1)->getVT();
5750 unsigned VTBits = VT.getScalarType().getSizeInBits();
5751 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5753 // fold (sext_in_reg c1) -> c1
5754 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5755 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5757 // If the input is already sign extended, just drop the extension.
5758 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5761 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5762 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5763 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5764 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5765 N0.getOperand(0), N1);
5767 // fold (sext_in_reg (sext x)) -> (sext x)
5768 // fold (sext_in_reg (aext x)) -> (sext x)
5769 // if x is small enough.
5770 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5771 SDValue N00 = N0.getOperand(0);
5772 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5773 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5774 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5777 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5778 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5779 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5781 // fold operands of sext_in_reg based on knowledge that the top bits are not
5783 if (SimplifyDemandedBits(SDValue(N, 0)))
5784 return SDValue(N, 0);
5786 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5787 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5788 SDValue NarrowLoad = ReduceLoadWidth(N);
5789 if (NarrowLoad.getNode())
5792 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5793 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5794 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5795 if (N0.getOpcode() == ISD::SRL) {
5796 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5797 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5798 // We can turn this into an SRA iff the input to the SRL is already sign
5800 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5801 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5802 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5803 N0.getOperand(0), N0.getOperand(1));
5807 // fold (sext_inreg (extload x)) -> (sextload x)
5808 if (ISD::isEXTLoad(N0.getNode()) &&
5809 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5810 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5811 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5812 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5813 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5814 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5816 LN0->getBasePtr(), EVT,
5817 LN0->getMemOperand());
5818 CombineTo(N, ExtLoad);
5819 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5820 AddToWorkList(ExtLoad.getNode());
5821 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5823 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5824 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5826 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5827 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5828 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5829 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5830 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5832 LN0->getBasePtr(), EVT,
5833 LN0->getMemOperand());
5834 CombineTo(N, ExtLoad);
5835 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5836 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5839 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5840 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5841 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5842 N0.getOperand(1), false);
5843 if (BSwap.getNode())
5844 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5848 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5849 // into a build_vector.
5850 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5851 SmallVector<SDValue, 8> Elts;
5852 unsigned NumElts = N0->getNumOperands();
5853 unsigned ShAmt = VTBits - EVTBits;
5855 for (unsigned i = 0; i != NumElts; ++i) {
5856 SDValue Op = N0->getOperand(i);
5857 if (Op->getOpcode() == ISD::UNDEF) {
5862 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5863 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5864 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5865 Op.getValueType()));
5868 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
5874 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5875 SDValue N0 = N->getOperand(0);
5876 EVT VT = N->getValueType(0);
5877 bool isLE = TLI.isLittleEndian();
5880 if (N0.getValueType() == N->getValueType(0))
5882 // fold (truncate c1) -> c1
5883 if (isa<ConstantSDNode>(N0))
5884 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5885 // fold (truncate (truncate x)) -> (truncate x)
5886 if (N0.getOpcode() == ISD::TRUNCATE)
5887 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5888 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5889 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5890 N0.getOpcode() == ISD::SIGN_EXTEND ||
5891 N0.getOpcode() == ISD::ANY_EXTEND) {
5892 if (N0.getOperand(0).getValueType().bitsLT(VT))
5893 // if the source is smaller than the dest, we still need an extend
5894 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5896 if (N0.getOperand(0).getValueType().bitsGT(VT))
5897 // if the source is larger than the dest, than we just need the truncate
5898 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5899 // if the source and dest are the same type, we can drop both the extend
5900 // and the truncate.
5901 return N0.getOperand(0);
5904 // Fold extract-and-trunc into a narrow extract. For example:
5905 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5906 // i32 y = TRUNCATE(i64 x)
5908 // v16i8 b = BITCAST (v2i64 val)
5909 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5911 // Note: We only run this optimization after type legalization (which often
5912 // creates this pattern) and before operation legalization after which
5913 // we need to be more careful about the vector instructions that we generate.
5914 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5915 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5917 EVT VecTy = N0.getOperand(0).getValueType();
5918 EVT ExTy = N0.getValueType();
5919 EVT TrTy = N->getValueType(0);
5921 unsigned NumElem = VecTy.getVectorNumElements();
5922 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5924 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5925 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5927 SDValue EltNo = N0->getOperand(1);
5928 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5929 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5930 EVT IndexTy = TLI.getVectorIdxTy();
5931 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5933 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5934 NVT, N0.getOperand(0));
5936 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5938 DAG.getConstant(Index, IndexTy));
5942 // Fold a series of buildvector, bitcast, and truncate if possible.
5944 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5945 // (2xi32 (buildvector x, y)).
5946 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5947 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5948 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5949 N0.getOperand(0).hasOneUse()) {
5951 SDValue BuildVect = N0.getOperand(0);
5952 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5953 EVT TruncVecEltTy = VT.getVectorElementType();
5955 // Check that the element types match.
5956 if (BuildVectEltTy == TruncVecEltTy) {
5957 // Now we only need to compute the offset of the truncated elements.
5958 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5959 unsigned TruncVecNumElts = VT.getVectorNumElements();
5960 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5962 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5963 "Invalid number of elements");
5965 SmallVector<SDValue, 8> Opnds;
5966 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5967 Opnds.push_back(BuildVect.getOperand(i));
5969 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
5973 // See if we can simplify the input to this truncate through knowledge that
5974 // only the low bits are being used.
5975 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5976 // Currently we only perform this optimization on scalars because vectors
5977 // may have different active low bits.
5978 if (!VT.isVector()) {
5980 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5981 VT.getSizeInBits()));
5982 if (Shorter.getNode())
5983 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5985 // fold (truncate (load x)) -> (smaller load x)
5986 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5987 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5988 SDValue Reduced = ReduceLoadWidth(N);
5989 if (Reduced.getNode())
5991 // Handle the case where the load remains an extending load even
5992 // after truncation.
5993 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5994 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5995 if (!LN0->isVolatile() &&
5996 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5997 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5998 VT, LN0->getChain(), LN0->getBasePtr(),
6000 LN0->getMemOperand());
6001 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6006 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6007 // where ... are all 'undef'.
6008 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6009 SmallVector<EVT, 8> VTs;
6012 unsigned NumDefs = 0;
6014 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6015 SDValue X = N0.getOperand(i);
6016 if (X.getOpcode() != ISD::UNDEF) {
6021 // Stop if more than one members are non-undef.
6024 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6025 VT.getVectorElementType(),
6026 X.getValueType().getVectorNumElements()));
6030 return DAG.getUNDEF(VT);
6033 assert(V.getNode() && "The single defined operand is empty!");
6034 SmallVector<SDValue, 8> Opnds;
6035 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6037 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6040 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6041 AddToWorkList(NV.getNode());
6042 Opnds.push_back(NV);
6044 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6048 // Simplify the operands using demanded-bits information.
6049 if (!VT.isVector() &&
6050 SimplifyDemandedBits(SDValue(N, 0)))
6051 return SDValue(N, 0);
6056 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6057 SDValue Elt = N->getOperand(i);
6058 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6059 return Elt.getNode();
6060 return Elt.getOperand(Elt.getResNo()).getNode();
6063 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6064 /// if load locations are consecutive.
6065 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6066 assert(N->getOpcode() == ISD::BUILD_PAIR);
6068 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6069 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6070 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6071 LD1->getAddressSpace() != LD2->getAddressSpace())
6073 EVT LD1VT = LD1->getValueType(0);
6075 if (ISD::isNON_EXTLoad(LD2) &&
6077 // If both are volatile this would reduce the number of volatile loads.
6078 // If one is volatile it might be ok, but play conservative and bail out.
6079 !LD1->isVolatile() &&
6080 !LD2->isVolatile() &&
6081 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6082 unsigned Align = LD1->getAlignment();
6083 unsigned NewAlign = TLI.getDataLayout()->
6084 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6086 if (NewAlign <= Align &&
6087 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6088 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6089 LD1->getBasePtr(), LD1->getPointerInfo(),
6090 false, false, false, Align);
6096 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6097 SDValue N0 = N->getOperand(0);
6098 EVT VT = N->getValueType(0);
6100 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6101 // Only do this before legalize, since afterward the target may be depending
6102 // on the bitconvert.
6103 // First check to see if this is all constant.
6105 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6107 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6109 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6110 assert(!DestEltVT.isVector() &&
6111 "Element type of vector ValueType must not be vector!");
6113 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6116 // If the input is a constant, let getNode fold it.
6117 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6118 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6119 if (Res.getNode() != N) {
6120 if (!LegalOperations ||
6121 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6124 // Folding it resulted in an illegal node, and it's too late to
6125 // do that. Clean up the old node and forego the transformation.
6126 // Ideally this won't happen very often, because instcombine
6127 // and the earlier dagcombine runs (where illegal nodes are
6128 // permitted) should have folded most of them already.
6129 DAG.DeleteNode(Res.getNode());
6133 // (conv (conv x, t1), t2) -> (conv x, t2)
6134 if (N0.getOpcode() == ISD::BITCAST)
6135 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6138 // fold (conv (load x)) -> (load (conv*)x)
6139 // If the resultant load doesn't need a higher alignment than the original!
6140 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6141 // Do not change the width of a volatile load.
6142 !cast<LoadSDNode>(N0)->isVolatile() &&
6143 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6144 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6145 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6146 unsigned Align = TLI.getDataLayout()->
6147 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6148 unsigned OrigAlign = LN0->getAlignment();
6150 if (Align <= OrigAlign) {
6151 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6152 LN0->getBasePtr(), LN0->getPointerInfo(),
6153 LN0->isVolatile(), LN0->isNonTemporal(),
6154 LN0->isInvariant(), OrigAlign,
6155 LN0->getTBAAInfo());
6157 CombineTo(N0.getNode(),
6158 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6159 N0.getValueType(), Load),
6165 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6166 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6167 // This often reduces constant pool loads.
6168 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6169 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6170 N0.getNode()->hasOneUse() && VT.isInteger() &&
6171 !VT.isVector() && !N0.getValueType().isVector()) {
6172 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6174 AddToWorkList(NewConv.getNode());
6176 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6177 if (N0.getOpcode() == ISD::FNEG)
6178 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6179 NewConv, DAG.getConstant(SignBit, VT));
6180 assert(N0.getOpcode() == ISD::FABS);
6181 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6182 NewConv, DAG.getConstant(~SignBit, VT));
6185 // fold (bitconvert (fcopysign cst, x)) ->
6186 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6187 // Note that we don't handle (copysign x, cst) because this can always be
6188 // folded to an fneg or fabs.
6189 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6190 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6191 VT.isInteger() && !VT.isVector()) {
6192 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6193 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6194 if (isTypeLegal(IntXVT)) {
6195 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6196 IntXVT, N0.getOperand(1));
6197 AddToWorkList(X.getNode());
6199 // If X has a different width than the result/lhs, sext it or truncate it.
6200 unsigned VTWidth = VT.getSizeInBits();
6201 if (OrigXWidth < VTWidth) {
6202 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6203 AddToWorkList(X.getNode());
6204 } else if (OrigXWidth > VTWidth) {
6205 // To get the sign bit in the right place, we have to shift it right
6206 // before truncating.
6207 X = DAG.getNode(ISD::SRL, SDLoc(X),
6208 X.getValueType(), X,
6209 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6210 AddToWorkList(X.getNode());
6211 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6212 AddToWorkList(X.getNode());
6215 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6216 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6217 X, DAG.getConstant(SignBit, VT));
6218 AddToWorkList(X.getNode());
6220 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6221 VT, N0.getOperand(0));
6222 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6223 Cst, DAG.getConstant(~SignBit, VT));
6224 AddToWorkList(Cst.getNode());
6226 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6230 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6231 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6232 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6233 if (CombineLD.getNode())
6240 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6241 EVT VT = N->getValueType(0);
6242 return CombineConsecutiveLoads(N, VT);
6245 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6246 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6247 /// destination element value type.
6248 SDValue DAGCombiner::
6249 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6250 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6252 // If this is already the right type, we're done.
6253 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6255 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6256 unsigned DstBitSize = DstEltVT.getSizeInBits();
6258 // If this is a conversion of N elements of one type to N elements of another
6259 // type, convert each element. This handles FP<->INT cases.
6260 if (SrcBitSize == DstBitSize) {
6261 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6262 BV->getValueType(0).getVectorNumElements());
6264 // Due to the FP element handling below calling this routine recursively,
6265 // we can end up with a scalar-to-vector node here.
6266 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6267 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6268 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6269 DstEltVT, BV->getOperand(0)));
6271 SmallVector<SDValue, 8> Ops;
6272 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6273 SDValue Op = BV->getOperand(i);
6274 // If the vector element type is not legal, the BUILD_VECTOR operands
6275 // are promoted and implicitly truncated. Make that explicit here.
6276 if (Op.getValueType() != SrcEltVT)
6277 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6278 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6280 AddToWorkList(Ops.back().getNode());
6282 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6285 // Otherwise, we're growing or shrinking the elements. To avoid having to
6286 // handle annoying details of growing/shrinking FP values, we convert them to
6288 if (SrcEltVT.isFloatingPoint()) {
6289 // Convert the input float vector to a int vector where the elements are the
6291 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6292 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6293 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6297 // Now we know the input is an integer vector. If the output is a FP type,
6298 // convert to integer first, then to FP of the right size.
6299 if (DstEltVT.isFloatingPoint()) {
6300 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6301 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6302 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6304 // Next, convert to FP elements of the same size.
6305 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6308 // Okay, we know the src/dst types are both integers of differing types.
6309 // Handling growing first.
6310 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6311 if (SrcBitSize < DstBitSize) {
6312 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6314 SmallVector<SDValue, 8> Ops;
6315 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6316 i += NumInputsPerOutput) {
6317 bool isLE = TLI.isLittleEndian();
6318 APInt NewBits = APInt(DstBitSize, 0);
6319 bool EltIsUndef = true;
6320 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6321 // Shift the previously computed bits over.
6322 NewBits <<= SrcBitSize;
6323 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6324 if (Op.getOpcode() == ISD::UNDEF) continue;
6327 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6328 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6332 Ops.push_back(DAG.getUNDEF(DstEltVT));
6334 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6337 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6338 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6341 // Finally, this must be the case where we are shrinking elements: each input
6342 // turns into multiple outputs.
6343 bool isS2V = ISD::isScalarToVector(BV);
6344 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6345 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6346 NumOutputsPerInput*BV->getNumOperands());
6347 SmallVector<SDValue, 8> Ops;
6349 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6350 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6351 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6352 Ops.push_back(DAG.getUNDEF(DstEltVT));
6356 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6357 getAPIntValue().zextOrTrunc(SrcBitSize);
6359 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6360 APInt ThisVal = OpVal.trunc(DstBitSize);
6361 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6362 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6363 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6364 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6366 OpVal = OpVal.lshr(DstBitSize);
6369 // For big endian targets, swap the order of the pieces of each element.
6370 if (TLI.isBigEndian())
6371 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6374 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6377 SDValue DAGCombiner::visitFADD(SDNode *N) {
6378 SDValue N0 = N->getOperand(0);
6379 SDValue N1 = N->getOperand(1);
6380 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6381 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6382 EVT VT = N->getValueType(0);
6385 if (VT.isVector()) {
6386 SDValue FoldedVOp = SimplifyVBinOp(N);
6387 if (FoldedVOp.getNode()) return FoldedVOp;
6390 // fold (fadd c1, c2) -> c1 + c2
6392 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6393 // canonicalize constant to RHS
6394 if (N0CFP && !N1CFP)
6395 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6396 // fold (fadd A, 0) -> A
6397 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6398 N1CFP->getValueAPF().isZero())
6400 // fold (fadd A, (fneg B)) -> (fsub A, B)
6401 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6402 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6403 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6404 GetNegatedExpression(N1, DAG, LegalOperations));
6405 // fold (fadd (fneg A), B) -> (fsub B, A)
6406 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6407 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6408 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6409 GetNegatedExpression(N0, DAG, LegalOperations));
6411 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6412 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6413 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6414 isa<ConstantFPSDNode>(N0.getOperand(1)))
6415 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6416 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6417 N0.getOperand(1), N1));
6419 // No FP constant should be created after legalization as Instruction
6420 // Selection pass has hard time in dealing with FP constant.
6422 // We don't need test this condition for transformation like following, as
6423 // the DAG being transformed implies it is legal to take FP constant as
6426 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6428 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6430 // If allow, fold (fadd (fneg x), x) -> 0.0
6431 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6432 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6433 return DAG.getConstantFP(0.0, VT);
6435 // If allow, fold (fadd x, (fneg x)) -> 0.0
6436 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6437 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6438 return DAG.getConstantFP(0.0, VT);
6440 // In unsafe math mode, we can fold chains of FADD's of the same value
6441 // into multiplications. This transform is not safe in general because
6442 // we are reducing the number of rounding steps.
6443 if (DAG.getTarget().Options.UnsafeFPMath &&
6444 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6446 if (N0.getOpcode() == ISD::FMUL) {
6447 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6448 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6450 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6451 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6452 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6454 DAG.getConstantFP(1.0, VT));
6455 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6459 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6460 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6461 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6463 DAG.getConstantFP(1.0, VT));
6464 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6468 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6469 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6470 N1.getOperand(0) == N1.getOperand(1) &&
6471 N0.getOperand(1) == N1.getOperand(0)) {
6472 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6474 DAG.getConstantFP(2.0, VT));
6475 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6476 N0.getOperand(1), NewCFP);
6479 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6480 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6481 N1.getOperand(0) == N1.getOperand(1) &&
6482 N0.getOperand(0) == N1.getOperand(0)) {
6483 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6485 DAG.getConstantFP(2.0, VT));
6486 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6487 N0.getOperand(0), NewCFP);
6491 if (N1.getOpcode() == ISD::FMUL) {
6492 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6493 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6495 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6496 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6497 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6499 DAG.getConstantFP(1.0, VT));
6500 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6504 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6505 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6506 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6508 DAG.getConstantFP(1.0, VT));
6509 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6514 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6515 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6516 N0.getOperand(0) == N0.getOperand(1) &&
6517 N1.getOperand(1) == N0.getOperand(0)) {
6518 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6520 DAG.getConstantFP(2.0, VT));
6521 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6522 N1.getOperand(1), NewCFP);
6525 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6526 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6527 N0.getOperand(0) == N0.getOperand(1) &&
6528 N1.getOperand(0) == N0.getOperand(0)) {
6529 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6531 DAG.getConstantFP(2.0, VT));
6532 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6533 N1.getOperand(0), NewCFP);
6537 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6538 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6539 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6540 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6541 (N0.getOperand(0) == N1))
6542 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6543 N1, DAG.getConstantFP(3.0, VT));
6546 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6547 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6548 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6549 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6550 N1.getOperand(0) == N0)
6551 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6552 N0, DAG.getConstantFP(3.0, VT));
6555 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6556 if (AllowNewFpConst &&
6557 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6558 N0.getOperand(0) == N0.getOperand(1) &&
6559 N1.getOperand(0) == N1.getOperand(1) &&
6560 N0.getOperand(0) == N1.getOperand(0))
6561 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6563 DAG.getConstantFP(4.0, VT));
6566 // FADD -> FMA combines:
6567 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6568 DAG.getTarget().Options.UnsafeFPMath) &&
6569 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6570 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6572 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6573 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6574 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6575 N0.getOperand(0), N0.getOperand(1), N1);
6577 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6578 // Note: Commutes FADD operands.
6579 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6580 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6581 N1.getOperand(0), N1.getOperand(1), N0);
6587 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6588 SDValue N0 = N->getOperand(0);
6589 SDValue N1 = N->getOperand(1);
6590 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6591 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6592 EVT VT = N->getValueType(0);
6596 if (VT.isVector()) {
6597 SDValue FoldedVOp = SimplifyVBinOp(N);
6598 if (FoldedVOp.getNode()) return FoldedVOp;
6601 // fold (fsub c1, c2) -> c1-c2
6603 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6604 // fold (fsub A, 0) -> A
6605 if (DAG.getTarget().Options.UnsafeFPMath &&
6606 N1CFP && N1CFP->getValueAPF().isZero())
6608 // fold (fsub 0, B) -> -B
6609 if (DAG.getTarget().Options.UnsafeFPMath &&
6610 N0CFP && N0CFP->getValueAPF().isZero()) {
6611 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6612 return GetNegatedExpression(N1, DAG, LegalOperations);
6613 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6614 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6616 // fold (fsub A, (fneg B)) -> (fadd A, B)
6617 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6618 return DAG.getNode(ISD::FADD, dl, VT, N0,
6619 GetNegatedExpression(N1, DAG, LegalOperations));
6621 // If 'unsafe math' is enabled, fold
6622 // (fsub x, x) -> 0.0 &
6623 // (fsub x, (fadd x, y)) -> (fneg y) &
6624 // (fsub x, (fadd y, x)) -> (fneg y)
6625 if (DAG.getTarget().Options.UnsafeFPMath) {
6627 return DAG.getConstantFP(0.0f, VT);
6629 if (N1.getOpcode() == ISD::FADD) {
6630 SDValue N10 = N1->getOperand(0);
6631 SDValue N11 = N1->getOperand(1);
6633 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6634 &DAG.getTarget().Options))
6635 return GetNegatedExpression(N11, DAG, LegalOperations);
6637 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6638 &DAG.getTarget().Options))
6639 return GetNegatedExpression(N10, DAG, LegalOperations);
6643 // FSUB -> FMA combines:
6644 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6645 DAG.getTarget().Options.UnsafeFPMath) &&
6646 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6647 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6649 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6650 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6651 return DAG.getNode(ISD::FMA, dl, VT,
6652 N0.getOperand(0), N0.getOperand(1),
6653 DAG.getNode(ISD::FNEG, dl, VT, N1));
6655 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6656 // Note: Commutes FSUB operands.
6657 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6658 return DAG.getNode(ISD::FMA, dl, VT,
6659 DAG.getNode(ISD::FNEG, dl, VT,
6661 N1.getOperand(1), N0);
6663 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6664 if (N0.getOpcode() == ISD::FNEG &&
6665 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6666 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6667 SDValue N00 = N0.getOperand(0).getOperand(0);
6668 SDValue N01 = N0.getOperand(0).getOperand(1);
6669 return DAG.getNode(ISD::FMA, dl, VT,
6670 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6671 DAG.getNode(ISD::FNEG, dl, VT, N1));
6678 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6679 SDValue N0 = N->getOperand(0);
6680 SDValue N1 = N->getOperand(1);
6681 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6682 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6683 EVT VT = N->getValueType(0);
6684 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6687 if (VT.isVector()) {
6688 SDValue FoldedVOp = SimplifyVBinOp(N);
6689 if (FoldedVOp.getNode()) return FoldedVOp;
6692 // fold (fmul c1, c2) -> c1*c2
6694 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6695 // canonicalize constant to RHS
6696 if (N0CFP && !N1CFP)
6697 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6698 // fold (fmul A, 0) -> 0
6699 if (DAG.getTarget().Options.UnsafeFPMath &&
6700 N1CFP && N1CFP->getValueAPF().isZero())
6702 // fold (fmul A, 0) -> 0, vector edition.
6703 if (DAG.getTarget().Options.UnsafeFPMath &&
6704 ISD::isBuildVectorAllZeros(N1.getNode()))
6706 // fold (fmul A, 1.0) -> A
6707 if (N1CFP && N1CFP->isExactlyValue(1.0))
6709 // fold (fmul X, 2.0) -> (fadd X, X)
6710 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6711 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6712 // fold (fmul X, -1.0) -> (fneg X)
6713 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6714 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6715 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6717 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6718 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6719 &DAG.getTarget().Options)) {
6720 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6721 &DAG.getTarget().Options)) {
6722 // Both can be negated for free, check to see if at least one is cheaper
6724 if (LHSNeg == 2 || RHSNeg == 2)
6725 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6726 GetNegatedExpression(N0, DAG, LegalOperations),
6727 GetNegatedExpression(N1, DAG, LegalOperations));
6731 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6732 if (DAG.getTarget().Options.UnsafeFPMath &&
6733 N1CFP && N0.getOpcode() == ISD::FMUL &&
6734 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6735 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6736 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6737 N0.getOperand(1), N1));
6742 SDValue DAGCombiner::visitFMA(SDNode *N) {
6743 SDValue N0 = N->getOperand(0);
6744 SDValue N1 = N->getOperand(1);
6745 SDValue N2 = N->getOperand(2);
6746 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6747 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6748 EVT VT = N->getValueType(0);
6751 if (DAG.getTarget().Options.UnsafeFPMath) {
6752 if (N0CFP && N0CFP->isZero())
6754 if (N1CFP && N1CFP->isZero())
6757 if (N0CFP && N0CFP->isExactlyValue(1.0))
6758 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6759 if (N1CFP && N1CFP->isExactlyValue(1.0))
6760 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6762 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6763 if (N0CFP && !N1CFP)
6764 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6766 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6767 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6768 N2.getOpcode() == ISD::FMUL &&
6769 N0 == N2.getOperand(0) &&
6770 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6771 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6772 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6776 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6777 if (DAG.getTarget().Options.UnsafeFPMath &&
6778 N0.getOpcode() == ISD::FMUL && N1CFP &&
6779 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6780 return DAG.getNode(ISD::FMA, dl, VT,
6782 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6786 // (fma x, 1, y) -> (fadd x, y)
6787 // (fma x, -1, y) -> (fadd (fneg x), y)
6789 if (N1CFP->isExactlyValue(1.0))
6790 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6792 if (N1CFP->isExactlyValue(-1.0) &&
6793 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6794 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6795 AddToWorkList(RHSNeg.getNode());
6796 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6800 // (fma x, c, x) -> (fmul x, (c+1))
6801 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6802 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6803 DAG.getNode(ISD::FADD, dl, VT,
6804 N1, DAG.getConstantFP(1.0, VT)));
6806 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6807 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6808 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6809 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6810 DAG.getNode(ISD::FADD, dl, VT,
6811 N1, DAG.getConstantFP(-1.0, VT)));
6817 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6818 SDValue N0 = N->getOperand(0);
6819 SDValue N1 = N->getOperand(1);
6820 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6821 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6822 EVT VT = N->getValueType(0);
6823 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6826 if (VT.isVector()) {
6827 SDValue FoldedVOp = SimplifyVBinOp(N);
6828 if (FoldedVOp.getNode()) return FoldedVOp;
6831 // fold (fdiv c1, c2) -> c1/c2
6833 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6835 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6836 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6837 // Compute the reciprocal 1.0 / c2.
6838 APFloat N1APF = N1CFP->getValueAPF();
6839 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6840 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6841 // Only do the transform if the reciprocal is a legal fp immediate that
6842 // isn't too nasty (eg NaN, denormal, ...).
6843 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6844 (!LegalOperations ||
6845 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6846 // backend)... we should handle this gracefully after Legalize.
6847 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6848 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6849 TLI.isFPImmLegal(Recip, VT)))
6850 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6851 DAG.getConstantFP(Recip, VT));
6854 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6855 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6856 &DAG.getTarget().Options)) {
6857 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6858 &DAG.getTarget().Options)) {
6859 // Both can be negated for free, check to see if at least one is cheaper
6861 if (LHSNeg == 2 || RHSNeg == 2)
6862 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6863 GetNegatedExpression(N0, DAG, LegalOperations),
6864 GetNegatedExpression(N1, DAG, LegalOperations));
6871 SDValue DAGCombiner::visitFREM(SDNode *N) {
6872 SDValue N0 = N->getOperand(0);
6873 SDValue N1 = N->getOperand(1);
6874 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6875 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6876 EVT VT = N->getValueType(0);
6878 // fold (frem c1, c2) -> fmod(c1,c2)
6880 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6885 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6886 SDValue N0 = N->getOperand(0);
6887 SDValue N1 = N->getOperand(1);
6888 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6889 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6890 EVT VT = N->getValueType(0);
6892 if (N0CFP && N1CFP) // Constant fold
6893 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6896 const APFloat& V = N1CFP->getValueAPF();
6897 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6898 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6899 if (!V.isNegative()) {
6900 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6901 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6903 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6904 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6905 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6909 // copysign(fabs(x), y) -> copysign(x, y)
6910 // copysign(fneg(x), y) -> copysign(x, y)
6911 // copysign(copysign(x,z), y) -> copysign(x, y)
6912 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6913 N0.getOpcode() == ISD::FCOPYSIGN)
6914 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6915 N0.getOperand(0), N1);
6917 // copysign(x, abs(y)) -> abs(x)
6918 if (N1.getOpcode() == ISD::FABS)
6919 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6921 // copysign(x, copysign(y,z)) -> copysign(x, z)
6922 if (N1.getOpcode() == ISD::FCOPYSIGN)
6923 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6924 N0, N1.getOperand(1));
6926 // copysign(x, fp_extend(y)) -> copysign(x, y)
6927 // copysign(x, fp_round(y)) -> copysign(x, y)
6928 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6929 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6930 N0, N1.getOperand(0));
6935 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6936 SDValue N0 = N->getOperand(0);
6937 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6938 EVT VT = N->getValueType(0);
6939 EVT OpVT = N0.getValueType();
6941 // fold (sint_to_fp c1) -> c1fp
6943 // ...but only if the target supports immediate floating-point values
6944 (!LegalOperations ||
6945 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6946 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6948 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6949 // but UINT_TO_FP is legal on this target, try to convert.
6950 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6951 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6952 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6953 if (DAG.SignBitIsZero(N0))
6954 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6957 // The next optimizations are desirable only if SELECT_CC can be lowered.
6958 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6959 // having to say they don't support SELECT_CC on every type the DAG knows
6960 // about, since there is no way to mark an opcode illegal at all value types
6961 // (See also visitSELECT)
6962 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6963 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6964 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6966 (!LegalOperations ||
6967 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6969 { N0.getOperand(0), N0.getOperand(1),
6970 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6972 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
6975 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6976 // (select_cc x, y, 1.0, 0.0,, cc)
6977 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6978 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6979 (!LegalOperations ||
6980 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6982 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6983 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6984 N0.getOperand(0).getOperand(2) };
6985 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
6992 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6993 SDValue N0 = N->getOperand(0);
6994 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6995 EVT VT = N->getValueType(0);
6996 EVT OpVT = N0.getValueType();
6998 // fold (uint_to_fp c1) -> c1fp
7000 // ...but only if the target supports immediate floating-point values
7001 (!LegalOperations ||
7002 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7003 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7005 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7006 // but SINT_TO_FP is legal on this target, try to convert.
7007 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7008 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7009 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7010 if (DAG.SignBitIsZero(N0))
7011 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7014 // The next optimizations are desirable only if SELECT_CC can be lowered.
7015 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7016 // having to say they don't support SELECT_CC on every type the DAG knows
7017 // about, since there is no way to mark an opcode illegal at all value types
7018 // (See also visitSELECT)
7019 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7020 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7022 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7023 (!LegalOperations ||
7024 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7026 { N0.getOperand(0), N0.getOperand(1),
7027 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7029 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7036 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7037 SDValue N0 = N->getOperand(0);
7038 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7039 EVT VT = N->getValueType(0);
7041 // fold (fp_to_sint c1fp) -> c1
7043 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7048 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7049 SDValue N0 = N->getOperand(0);
7050 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7051 EVT VT = N->getValueType(0);
7053 // fold (fp_to_uint c1fp) -> c1
7055 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7060 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7061 SDValue N0 = N->getOperand(0);
7062 SDValue N1 = N->getOperand(1);
7063 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7064 EVT VT = N->getValueType(0);
7066 // fold (fp_round c1fp) -> c1fp
7068 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7070 // fold (fp_round (fp_extend x)) -> x
7071 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7072 return N0.getOperand(0);
7074 // fold (fp_round (fp_round x)) -> (fp_round x)
7075 if (N0.getOpcode() == ISD::FP_ROUND) {
7076 // This is a value preserving truncation if both round's are.
7077 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7078 N0.getNode()->getConstantOperandVal(1) == 1;
7079 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7080 DAG.getIntPtrConstant(IsTrunc));
7083 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7084 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7085 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7086 N0.getOperand(0), N1);
7087 AddToWorkList(Tmp.getNode());
7088 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7089 Tmp, N0.getOperand(1));
7095 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7096 SDValue N0 = N->getOperand(0);
7097 EVT VT = N->getValueType(0);
7098 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7099 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7101 // fold (fp_round_inreg c1fp) -> c1fp
7102 if (N0CFP && isTypeLegal(EVT)) {
7103 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7104 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7110 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7111 SDValue N0 = N->getOperand(0);
7112 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7113 EVT VT = N->getValueType(0);
7115 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7116 if (N->hasOneUse() &&
7117 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7120 // fold (fp_extend c1fp) -> c1fp
7122 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7124 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7126 if (N0.getOpcode() == ISD::FP_ROUND
7127 && N0.getNode()->getConstantOperandVal(1) == 1) {
7128 SDValue In = N0.getOperand(0);
7129 if (In.getValueType() == VT) return In;
7130 if (VT.bitsLT(In.getValueType()))
7131 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7132 In, N0.getOperand(1));
7133 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7136 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7137 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7138 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7139 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7140 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7141 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7143 LN0->getBasePtr(), N0.getValueType(),
7144 LN0->getMemOperand());
7145 CombineTo(N, ExtLoad);
7146 CombineTo(N0.getNode(),
7147 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7148 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7149 ExtLoad.getValue(1));
7150 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7156 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7157 SDValue N0 = N->getOperand(0);
7158 EVT VT = N->getValueType(0);
7160 if (VT.isVector()) {
7161 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7162 if (FoldedVOp.getNode()) return FoldedVOp;
7165 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7166 &DAG.getTarget().Options))
7167 return GetNegatedExpression(N0, DAG, LegalOperations);
7169 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7170 // constant pool values.
7171 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7173 N0.getNode()->hasOneUse() &&
7174 N0.getOperand(0).getValueType().isInteger()) {
7175 SDValue Int = N0.getOperand(0);
7176 EVT IntVT = Int.getValueType();
7177 if (IntVT.isInteger() && !IntVT.isVector()) {
7178 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7179 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7180 AddToWorkList(Int.getNode());
7181 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7186 // (fneg (fmul c, x)) -> (fmul -c, x)
7187 if (N0.getOpcode() == ISD::FMUL) {
7188 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7190 APFloat CVal = CFP1->getValueAPF();
7192 if (Level >= AfterLegalizeDAG &&
7193 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7194 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7196 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7197 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7204 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7205 SDValue N0 = N->getOperand(0);
7206 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7207 EVT VT = N->getValueType(0);
7209 // fold (fceil c1) -> fceil(c1)
7211 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7216 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7217 SDValue N0 = N->getOperand(0);
7218 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7219 EVT VT = N->getValueType(0);
7221 // fold (ftrunc c1) -> ftrunc(c1)
7223 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7228 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7229 SDValue N0 = N->getOperand(0);
7230 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7231 EVT VT = N->getValueType(0);
7233 // fold (ffloor c1) -> ffloor(c1)
7235 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7240 SDValue DAGCombiner::visitFABS(SDNode *N) {
7241 SDValue N0 = N->getOperand(0);
7242 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7243 EVT VT = N->getValueType(0);
7245 if (VT.isVector()) {
7246 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7247 if (FoldedVOp.getNode()) return FoldedVOp;
7250 // fold (fabs c1) -> fabs(c1)
7252 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7253 // fold (fabs (fabs x)) -> (fabs x)
7254 if (N0.getOpcode() == ISD::FABS)
7255 return N->getOperand(0);
7256 // fold (fabs (fneg x)) -> (fabs x)
7257 // fold (fabs (fcopysign x, y)) -> (fabs x)
7258 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7259 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7261 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7262 // constant pool values.
7263 if (!TLI.isFAbsFree(VT) &&
7264 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7265 N0.getOperand(0).getValueType().isInteger() &&
7266 !N0.getOperand(0).getValueType().isVector()) {
7267 SDValue Int = N0.getOperand(0);
7268 EVT IntVT = Int.getValueType();
7269 if (IntVT.isInteger() && !IntVT.isVector()) {
7270 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7271 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7272 AddToWorkList(Int.getNode());
7273 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7274 N->getValueType(0), Int);
7281 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7282 SDValue Chain = N->getOperand(0);
7283 SDValue N1 = N->getOperand(1);
7284 SDValue N2 = N->getOperand(2);
7286 // If N is a constant we could fold this into a fallthrough or unconditional
7287 // branch. However that doesn't happen very often in normal code, because
7288 // Instcombine/SimplifyCFG should have handled the available opportunities.
7289 // If we did this folding here, it would be necessary to update the
7290 // MachineBasicBlock CFG, which is awkward.
7292 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7294 if (N1.getOpcode() == ISD::SETCC &&
7295 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7296 N1.getOperand(0).getValueType())) {
7297 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7298 Chain, N1.getOperand(2),
7299 N1.getOperand(0), N1.getOperand(1), N2);
7302 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7303 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7304 (N1.getOperand(0).hasOneUse() &&
7305 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7306 SDNode *Trunc = nullptr;
7307 if (N1.getOpcode() == ISD::TRUNCATE) {
7308 // Look pass the truncate.
7309 Trunc = N1.getNode();
7310 N1 = N1.getOperand(0);
7313 // Match this pattern so that we can generate simpler code:
7316 // %b = and i32 %a, 2
7317 // %c = srl i32 %b, 1
7318 // brcond i32 %c ...
7323 // %b = and i32 %a, 2
7324 // %c = setcc eq %b, 0
7327 // This applies only when the AND constant value has one bit set and the
7328 // SRL constant is equal to the log2 of the AND constant. The back-end is
7329 // smart enough to convert the result into a TEST/JMP sequence.
7330 SDValue Op0 = N1.getOperand(0);
7331 SDValue Op1 = N1.getOperand(1);
7333 if (Op0.getOpcode() == ISD::AND &&
7334 Op1.getOpcode() == ISD::Constant) {
7335 SDValue AndOp1 = Op0.getOperand(1);
7337 if (AndOp1.getOpcode() == ISD::Constant) {
7338 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7340 if (AndConst.isPowerOf2() &&
7341 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7343 DAG.getSetCC(SDLoc(N),
7344 getSetCCResultType(Op0.getValueType()),
7345 Op0, DAG.getConstant(0, Op0.getValueType()),
7348 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7349 MVT::Other, Chain, SetCC, N2);
7350 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7351 // will convert it back to (X & C1) >> C2.
7352 CombineTo(N, NewBRCond, false);
7353 // Truncate is dead.
7355 removeFromWorkList(Trunc);
7356 DAG.DeleteNode(Trunc);
7358 // Replace the uses of SRL with SETCC
7359 WorkListRemover DeadNodes(*this);
7360 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7361 removeFromWorkList(N1.getNode());
7362 DAG.DeleteNode(N1.getNode());
7363 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7369 // Restore N1 if the above transformation doesn't match.
7370 N1 = N->getOperand(1);
7373 // Transform br(xor(x, y)) -> br(x != y)
7374 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7375 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7376 SDNode *TheXor = N1.getNode();
7377 SDValue Op0 = TheXor->getOperand(0);
7378 SDValue Op1 = TheXor->getOperand(1);
7379 if (Op0.getOpcode() == Op1.getOpcode()) {
7380 // Avoid missing important xor optimizations.
7381 SDValue Tmp = visitXOR(TheXor);
7382 if (Tmp.getNode()) {
7383 if (Tmp.getNode() != TheXor) {
7384 DEBUG(dbgs() << "\nReplacing.8 ";
7386 dbgs() << "\nWith: ";
7387 Tmp.getNode()->dump(&DAG);
7389 WorkListRemover DeadNodes(*this);
7390 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7391 removeFromWorkList(TheXor);
7392 DAG.DeleteNode(TheXor);
7393 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7394 MVT::Other, Chain, Tmp, N2);
7397 // visitXOR has changed XOR's operands or replaced the XOR completely,
7399 return SDValue(N, 0);
7403 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7405 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7406 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7407 Op0.getOpcode() == ISD::XOR) {
7408 TheXor = Op0.getNode();
7412 EVT SetCCVT = N1.getValueType();
7414 SetCCVT = getSetCCResultType(SetCCVT);
7415 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7418 Equal ? ISD::SETEQ : ISD::SETNE);
7419 // Replace the uses of XOR with SETCC
7420 WorkListRemover DeadNodes(*this);
7421 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7422 removeFromWorkList(N1.getNode());
7423 DAG.DeleteNode(N1.getNode());
7424 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7425 MVT::Other, Chain, SetCC, N2);
7432 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7434 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7435 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7436 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7438 // If N is a constant we could fold this into a fallthrough or unconditional
7439 // branch. However that doesn't happen very often in normal code, because
7440 // Instcombine/SimplifyCFG should have handled the available opportunities.
7441 // If we did this folding here, it would be necessary to update the
7442 // MachineBasicBlock CFG, which is awkward.
7444 // Use SimplifySetCC to simplify SETCC's.
7445 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7446 CondLHS, CondRHS, CC->get(), SDLoc(N),
7448 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7450 // fold to a simpler setcc
7451 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7452 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7453 N->getOperand(0), Simp.getOperand(2),
7454 Simp.getOperand(0), Simp.getOperand(1),
7460 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7461 /// uses N as its base pointer and that N may be folded in the load / store
7462 /// addressing mode.
7463 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7465 const TargetLowering &TLI) {
7467 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7468 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7470 VT = Use->getValueType(0);
7471 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7472 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7474 VT = ST->getValue().getValueType();
7478 TargetLowering::AddrMode AM;
7479 if (N->getOpcode() == ISD::ADD) {
7480 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7483 AM.BaseOffs = Offset->getSExtValue();
7487 } else if (N->getOpcode() == ISD::SUB) {
7488 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7491 AM.BaseOffs = -Offset->getSExtValue();
7498 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7501 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7502 /// pre-indexed load / store when the base pointer is an add or subtract
7503 /// and it has other uses besides the load / store. After the
7504 /// transformation, the new indexed load / store has effectively folded
7505 /// the add / subtract in and all of its other uses are redirected to the
7506 /// new load / store.
7507 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7508 if (Level < AfterLegalizeDAG)
7514 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7515 if (LD->isIndexed())
7517 VT = LD->getMemoryVT();
7518 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7519 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7521 Ptr = LD->getBasePtr();
7522 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7523 if (ST->isIndexed())
7525 VT = ST->getMemoryVT();
7526 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7527 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7529 Ptr = ST->getBasePtr();
7535 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7536 // out. There is no reason to make this a preinc/predec.
7537 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7538 Ptr.getNode()->hasOneUse())
7541 // Ask the target to do addressing mode selection.
7544 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7545 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7548 // Backends without true r+i pre-indexed forms may need to pass a
7549 // constant base with a variable offset so that constant coercion
7550 // will work with the patterns in canonical form.
7551 bool Swapped = false;
7552 if (isa<ConstantSDNode>(BasePtr)) {
7553 std::swap(BasePtr, Offset);
7557 // Don't create a indexed load / store with zero offset.
7558 if (isa<ConstantSDNode>(Offset) &&
7559 cast<ConstantSDNode>(Offset)->isNullValue())
7562 // Try turning it into a pre-indexed load / store except when:
7563 // 1) The new base ptr is a frame index.
7564 // 2) If N is a store and the new base ptr is either the same as or is a
7565 // predecessor of the value being stored.
7566 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7567 // that would create a cycle.
7568 // 4) All uses are load / store ops that use it as old base ptr.
7570 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7571 // (plus the implicit offset) to a register to preinc anyway.
7572 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7577 SDValue Val = cast<StoreSDNode>(N)->getValue();
7578 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7582 // If the offset is a constant, there may be other adds of constants that
7583 // can be folded with this one. We should do this to avoid having to keep
7584 // a copy of the original base pointer.
7585 SmallVector<SDNode *, 16> OtherUses;
7586 if (isa<ConstantSDNode>(Offset))
7587 for (SDNode *Use : BasePtr.getNode()->uses()) {
7588 if (Use == Ptr.getNode())
7591 if (Use->isPredecessorOf(N))
7594 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7599 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7600 if (Op1.getNode() == BasePtr.getNode())
7601 std::swap(Op0, Op1);
7602 assert(Op0.getNode() == BasePtr.getNode() &&
7603 "Use of ADD/SUB but not an operand");
7605 if (!isa<ConstantSDNode>(Op1)) {
7610 // FIXME: In some cases, we can be smarter about this.
7611 if (Op1.getValueType() != Offset.getValueType()) {
7616 OtherUses.push_back(Use);
7620 std::swap(BasePtr, Offset);
7622 // Now check for #3 and #4.
7623 bool RealUse = false;
7625 // Caches for hasPredecessorHelper
7626 SmallPtrSet<const SDNode *, 32> Visited;
7627 SmallVector<const SDNode *, 16> Worklist;
7629 for (SDNode *Use : Ptr.getNode()->uses()) {
7632 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7635 // If Ptr may be folded in addressing mode of other use, then it's
7636 // not profitable to do this transformation.
7637 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7646 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7647 BasePtr, Offset, AM);
7649 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7650 BasePtr, Offset, AM);
7653 DEBUG(dbgs() << "\nReplacing.4 ";
7655 dbgs() << "\nWith: ";
7656 Result.getNode()->dump(&DAG);
7658 WorkListRemover DeadNodes(*this);
7660 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7661 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7663 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7666 // Finally, since the node is now dead, remove it from the graph.
7670 std::swap(BasePtr, Offset);
7672 // Replace other uses of BasePtr that can be updated to use Ptr
7673 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7674 unsigned OffsetIdx = 1;
7675 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7677 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7678 BasePtr.getNode() && "Expected BasePtr operand");
7680 // We need to replace ptr0 in the following expression:
7681 // x0 * offset0 + y0 * ptr0 = t0
7683 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7685 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7686 // indexed load/store and the expresion that needs to be re-written.
7688 // Therefore, we have:
7689 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7691 ConstantSDNode *CN =
7692 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7694 APInt Offset0 = CN->getAPIntValue();
7695 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7697 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7698 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7699 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7700 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7702 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7704 APInt CNV = Offset0;
7705 if (X0 < 0) CNV = -CNV;
7706 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7707 else CNV = CNV - Offset1;
7709 // We can now generate the new expression.
7710 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7711 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7713 SDValue NewUse = DAG.getNode(Opcode,
7714 SDLoc(OtherUses[i]),
7715 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7716 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7717 removeFromWorkList(OtherUses[i]);
7718 DAG.DeleteNode(OtherUses[i]);
7721 // Replace the uses of Ptr with uses of the updated base value.
7722 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7723 removeFromWorkList(Ptr.getNode());
7724 DAG.DeleteNode(Ptr.getNode());
7729 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7730 /// add / sub of the base pointer node into a post-indexed load / store.
7731 /// The transformation folded the add / subtract into the new indexed
7732 /// load / store effectively and all of its uses are redirected to the
7733 /// new load / store.
7734 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7735 if (Level < AfterLegalizeDAG)
7741 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7742 if (LD->isIndexed())
7744 VT = LD->getMemoryVT();
7745 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7746 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7748 Ptr = LD->getBasePtr();
7749 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7750 if (ST->isIndexed())
7752 VT = ST->getMemoryVT();
7753 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7754 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7756 Ptr = ST->getBasePtr();
7762 if (Ptr.getNode()->hasOneUse())
7765 for (SDNode *Op : Ptr.getNode()->uses()) {
7767 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7772 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7773 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7774 // Don't create a indexed load / store with zero offset.
7775 if (isa<ConstantSDNode>(Offset) &&
7776 cast<ConstantSDNode>(Offset)->isNullValue())
7779 // Try turning it into a post-indexed load / store except when
7780 // 1) All uses are load / store ops that use it as base ptr (and
7781 // it may be folded as addressing mmode).
7782 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7783 // nor a successor of N. Otherwise, if Op is folded that would
7786 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7790 bool TryNext = false;
7791 for (SDNode *Use : BasePtr.getNode()->uses()) {
7792 if (Use == Ptr.getNode())
7795 // If all the uses are load / store addresses, then don't do the
7797 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7798 bool RealUse = false;
7799 for (SDNode *UseUse : Use->uses()) {
7800 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7815 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7816 SDValue Result = isLoad
7817 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7818 BasePtr, Offset, AM)
7819 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7820 BasePtr, Offset, AM);
7823 DEBUG(dbgs() << "\nReplacing.5 ";
7825 dbgs() << "\nWith: ";
7826 Result.getNode()->dump(&DAG);
7828 WorkListRemover DeadNodes(*this);
7830 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7831 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7833 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7836 // Finally, since the node is now dead, remove it from the graph.
7839 // Replace the uses of Use with uses of the updated base value.
7840 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7841 Result.getValue(isLoad ? 1 : 0));
7842 removeFromWorkList(Op);
7852 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
7853 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
7854 ISD::MemIndexedMode AM = LD->getAddressingMode();
7855 assert(AM != ISD::UNINDEXED);
7856 SDValue BP = LD->getOperand(1);
7857 SDValue Inc = LD->getOperand(2);
7859 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
7860 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
7863 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7864 LoadSDNode *LD = cast<LoadSDNode>(N);
7865 SDValue Chain = LD->getChain();
7866 SDValue Ptr = LD->getBasePtr();
7868 // If load is not volatile and there are no uses of the loaded value (and
7869 // the updated indexed value in case of indexed loads), change uses of the
7870 // chain value into uses of the chain input (i.e. delete the dead load).
7871 if (!LD->isVolatile()) {
7872 if (N->getValueType(1) == MVT::Other) {
7874 if (!N->hasAnyUseOfValue(0)) {
7875 // It's not safe to use the two value CombineTo variant here. e.g.
7876 // v1, chain2 = load chain1, loc
7877 // v2, chain3 = load chain2, loc
7879 // Now we replace use of chain2 with chain1. This makes the second load
7880 // isomorphic to the one we are deleting, and thus makes this load live.
7881 DEBUG(dbgs() << "\nReplacing.6 ";
7883 dbgs() << "\nWith chain: ";
7884 Chain.getNode()->dump(&DAG);
7886 WorkListRemover DeadNodes(*this);
7887 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7889 if (N->use_empty()) {
7890 removeFromWorkList(N);
7894 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7898 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7899 if (!N->hasAnyUseOfValue(0)) {
7900 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7902 if (N->hasAnyUseOfValue(1)) {
7903 Index = SplitIndexingFromLoad(LD);
7904 // Try to fold the base pointer arithmetic into subsequent loads and
7906 AddUsersToWorkList(N);
7908 Index = DAG.getUNDEF(N->getValueType(1));
7909 DEBUG(dbgs() << "\nReplacing.7 ";
7911 dbgs() << "\nWith: ";
7912 Undef.getNode()->dump(&DAG);
7913 dbgs() << " and 2 other values\n");
7914 WorkListRemover DeadNodes(*this);
7915 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7916 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
7917 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7918 removeFromWorkList(N);
7920 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7925 // If this load is directly stored, replace the load value with the stored
7927 // TODO: Handle store large -> read small portion.
7928 // TODO: Handle TRUNCSTORE/LOADEXT
7929 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7930 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7931 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7932 if (PrevST->getBasePtr() == Ptr &&
7933 PrevST->getValue().getValueType() == N->getValueType(0))
7934 return CombineTo(N, Chain.getOperand(1), Chain);
7938 // Try to infer better alignment information than the load already has.
7939 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7940 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7941 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7943 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7944 LD->getValueType(0),
7945 Chain, Ptr, LD->getPointerInfo(),
7947 LD->isVolatile(), LD->isNonTemporal(), Align,
7949 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7954 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7955 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7957 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7958 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7961 if (UseAA && LD->isUnindexed()) {
7962 // Walk up chain skipping non-aliasing memory nodes.
7963 SDValue BetterChain = FindBetterChain(N, Chain);
7965 // If there is a better chain.
7966 if (Chain != BetterChain) {
7969 // Replace the chain to void dependency.
7970 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7971 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7972 BetterChain, Ptr, LD->getMemOperand());
7974 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7975 LD->getValueType(0),
7976 BetterChain, Ptr, LD->getMemoryVT(),
7977 LD->getMemOperand());
7980 // Create token factor to keep old chain connected.
7981 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7982 MVT::Other, Chain, ReplLoad.getValue(1));
7984 // Make sure the new and old chains are cleaned up.
7985 AddToWorkList(Token.getNode());
7987 // Replace uses with load result and token factor. Don't add users
7989 return CombineTo(N, ReplLoad.getValue(0), Token, false);
7993 // Try transforming N to an indexed load.
7994 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7995 return SDValue(N, 0);
7997 // Try to slice up N to more direct loads if the slices are mapped to
7998 // different register banks or pairing can take place.
8000 return SDValue(N, 0);
8006 /// \brief Helper structure used to slice a load in smaller loads.
8007 /// Basically a slice is obtained from the following sequence:
8008 /// Origin = load Ty1, Base
8009 /// Shift = srl Ty1 Origin, CstTy Amount
8010 /// Inst = trunc Shift to Ty2
8012 /// Then, it will be rewriten into:
8013 /// Slice = load SliceTy, Base + SliceOffset
8014 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8016 /// SliceTy is deduced from the number of bits that are actually used to
8018 struct LoadedSlice {
8019 /// \brief Helper structure used to compute the cost of a slice.
8021 /// Are we optimizing for code size.
8026 unsigned CrossRegisterBanksCopies;
8030 Cost(bool ForCodeSize = false)
8031 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8032 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8034 /// \brief Get the cost of one isolated slice.
8035 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8036 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8037 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8038 EVT TruncType = LS.Inst->getValueType(0);
8039 EVT LoadedType = LS.getLoadedType();
8040 if (TruncType != LoadedType &&
8041 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8045 /// \brief Account for slicing gain in the current cost.
8046 /// Slicing provide a few gains like removing a shift or a
8047 /// truncate. This method allows to grow the cost of the original
8048 /// load with the gain from this slice.
8049 void addSliceGain(const LoadedSlice &LS) {
8050 // Each slice saves a truncate.
8051 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8052 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8053 LS.Inst->getOperand(0).getValueType()))
8055 // If there is a shift amount, this slice gets rid of it.
8058 // If this slice can merge a cross register bank copy, account for it.
8059 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8060 ++CrossRegisterBanksCopies;
8063 Cost &operator+=(const Cost &RHS) {
8065 Truncates += RHS.Truncates;
8066 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8072 bool operator==(const Cost &RHS) const {
8073 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8074 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8075 ZExts == RHS.ZExts && Shift == RHS.Shift;
8078 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8080 bool operator<(const Cost &RHS) const {
8081 // Assume cross register banks copies are as expensive as loads.
8082 // FIXME: Do we want some more target hooks?
8083 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8084 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8085 // Unless we are optimizing for code size, consider the
8086 // expensive operation first.
8087 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8088 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8089 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8090 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8093 bool operator>(const Cost &RHS) const { return RHS < *this; }
8095 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8097 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8099 // The last instruction that represent the slice. This should be a
8100 // truncate instruction.
8102 // The original load instruction.
8104 // The right shift amount in bits from the original load.
8106 // The DAG from which Origin came from.
8107 // This is used to get some contextual information about legal types, etc.
8110 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8111 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8112 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8114 LoadedSlice(const LoadedSlice &LS)
8115 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8117 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8118 /// \return Result is \p BitWidth and has used bits set to 1 and
8119 /// not used bits set to 0.
8120 APInt getUsedBits() const {
8121 // Reproduce the trunc(lshr) sequence:
8122 // - Start from the truncated value.
8123 // - Zero extend to the desired bit width.
8125 assert(Origin && "No original load to compare against.");
8126 unsigned BitWidth = Origin->getValueSizeInBits(0);
8127 assert(Inst && "This slice is not bound to an instruction");
8128 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8129 "Extracted slice is bigger than the whole type!");
8130 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8131 UsedBits.setAllBits();
8132 UsedBits = UsedBits.zext(BitWidth);
8137 /// \brief Get the size of the slice to be loaded in bytes.
8138 unsigned getLoadedSize() const {
8139 unsigned SliceSize = getUsedBits().countPopulation();
8140 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8141 return SliceSize / 8;
8144 /// \brief Get the type that will be loaded for this slice.
8145 /// Note: This may not be the final type for the slice.
8146 EVT getLoadedType() const {
8147 assert(DAG && "Missing context");
8148 LLVMContext &Ctxt = *DAG->getContext();
8149 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8152 /// \brief Get the alignment of the load used for this slice.
8153 unsigned getAlignment() const {
8154 unsigned Alignment = Origin->getAlignment();
8155 unsigned Offset = getOffsetFromBase();
8157 Alignment = MinAlign(Alignment, Alignment + Offset);
8161 /// \brief Check if this slice can be rewritten with legal operations.
8162 bool isLegal() const {
8163 // An invalid slice is not legal.
8164 if (!Origin || !Inst || !DAG)
8167 // Offsets are for indexed load only, we do not handle that.
8168 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8171 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8173 // Check that the type is legal.
8174 EVT SliceType = getLoadedType();
8175 if (!TLI.isTypeLegal(SliceType))
8178 // Check that the load is legal for this type.
8179 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8182 // Check that the offset can be computed.
8183 // 1. Check its type.
8184 EVT PtrType = Origin->getBasePtr().getValueType();
8185 if (PtrType == MVT::Untyped || PtrType.isExtended())
8188 // 2. Check that it fits in the immediate.
8189 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8192 // 3. Check that the computation is legal.
8193 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8196 // Check that the zext is legal if it needs one.
8197 EVT TruncateType = Inst->getValueType(0);
8198 if (TruncateType != SliceType &&
8199 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8205 /// \brief Get the offset in bytes of this slice in the original chunk of
8207 /// \pre DAG != nullptr.
8208 uint64_t getOffsetFromBase() const {
8209 assert(DAG && "Missing context.");
8211 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8212 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8213 uint64_t Offset = Shift / 8;
8214 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8215 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8216 "The size of the original loaded type is not a multiple of a"
8218 // If Offset is bigger than TySizeInBytes, it means we are loading all
8219 // zeros. This should have been optimized before in the process.
8220 assert(TySizeInBytes > Offset &&
8221 "Invalid shift amount for given loaded size");
8223 Offset = TySizeInBytes - Offset - getLoadedSize();
8227 /// \brief Generate the sequence of instructions to load the slice
8228 /// represented by this object and redirect the uses of this slice to
8229 /// this new sequence of instructions.
8230 /// \pre this->Inst && this->Origin are valid Instructions and this
8231 /// object passed the legal check: LoadedSlice::isLegal returned true.
8232 /// \return The last instruction of the sequence used to load the slice.
8233 SDValue loadSlice() const {
8234 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8235 const SDValue &OldBaseAddr = Origin->getBasePtr();
8236 SDValue BaseAddr = OldBaseAddr;
8237 // Get the offset in that chunk of bytes w.r.t. the endianess.
8238 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8239 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8241 // BaseAddr = BaseAddr + Offset.
8242 EVT ArithType = BaseAddr.getValueType();
8243 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8244 DAG->getConstant(Offset, ArithType));
8247 // Create the type of the loaded slice according to its size.
8248 EVT SliceType = getLoadedType();
8250 // Create the load for the slice.
8251 SDValue LastInst = DAG->getLoad(
8252 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8253 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8254 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8255 // If the final type is not the same as the loaded type, this means that
8256 // we have to pad with zero. Create a zero extend for that.
8257 EVT FinalType = Inst->getValueType(0);
8258 if (SliceType != FinalType)
8260 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8264 /// \brief Check if this slice can be merged with an expensive cross register
8265 /// bank copy. E.g.,
8267 /// f = bitcast i32 i to float
8268 bool canMergeExpensiveCrossRegisterBankCopy() const {
8269 if (!Inst || !Inst->hasOneUse())
8271 SDNode *Use = *Inst->use_begin();
8272 if (Use->getOpcode() != ISD::BITCAST)
8274 assert(DAG && "Missing context");
8275 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8276 EVT ResVT = Use->getValueType(0);
8277 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8278 const TargetRegisterClass *ArgRC =
8279 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8280 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8283 // At this point, we know that we perform a cross-register-bank copy.
8284 // Check if it is expensive.
8285 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8286 // Assume bitcasts are cheap, unless both register classes do not
8287 // explicitly share a common sub class.
8288 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8291 // Check if it will be merged with the load.
8292 // 1. Check the alignment constraint.
8293 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8294 ResVT.getTypeForEVT(*DAG->getContext()));
8296 if (RequiredAlignment > getAlignment())
8299 // 2. Check that the load is a legal operation for that type.
8300 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8303 // 3. Check that we do not have a zext in the way.
8304 if (Inst->getValueType(0) != getLoadedType())
8312 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8313 /// \p UsedBits looks like 0..0 1..1 0..0.
8314 static bool areUsedBitsDense(const APInt &UsedBits) {
8315 // If all the bits are one, this is dense!
8316 if (UsedBits.isAllOnesValue())
8319 // Get rid of the unused bits on the right.
8320 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8321 // Get rid of the unused bits on the left.
8322 if (NarrowedUsedBits.countLeadingZeros())
8323 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8324 // Check that the chunk of bits is completely used.
8325 return NarrowedUsedBits.isAllOnesValue();
8328 /// \brief Check whether or not \p First and \p Second are next to each other
8329 /// in memory. This means that there is no hole between the bits loaded
8330 /// by \p First and the bits loaded by \p Second.
8331 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8332 const LoadedSlice &Second) {
8333 assert(First.Origin == Second.Origin && First.Origin &&
8334 "Unable to match different memory origins.");
8335 APInt UsedBits = First.getUsedBits();
8336 assert((UsedBits & Second.getUsedBits()) == 0 &&
8337 "Slices are not supposed to overlap.");
8338 UsedBits |= Second.getUsedBits();
8339 return areUsedBitsDense(UsedBits);
8342 /// \brief Adjust the \p GlobalLSCost according to the target
8343 /// paring capabilities and the layout of the slices.
8344 /// \pre \p GlobalLSCost should account for at least as many loads as
8345 /// there is in the slices in \p LoadedSlices.
8346 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8347 LoadedSlice::Cost &GlobalLSCost) {
8348 unsigned NumberOfSlices = LoadedSlices.size();
8349 // If there is less than 2 elements, no pairing is possible.
8350 if (NumberOfSlices < 2)
8353 // Sort the slices so that elements that are likely to be next to each
8354 // other in memory are next to each other in the list.
8355 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8356 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8357 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8358 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8360 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8361 // First (resp. Second) is the first (resp. Second) potentially candidate
8362 // to be placed in a paired load.
8363 const LoadedSlice *First = nullptr;
8364 const LoadedSlice *Second = nullptr;
8365 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8366 // Set the beginning of the pair.
8369 Second = &LoadedSlices[CurrSlice];
8371 // If First is NULL, it means we start a new pair.
8372 // Get to the next slice.
8376 EVT LoadedType = First->getLoadedType();
8378 // If the types of the slices are different, we cannot pair them.
8379 if (LoadedType != Second->getLoadedType())
8382 // Check if the target supplies paired loads for this type.
8383 unsigned RequiredAlignment = 0;
8384 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8385 // move to the next pair, this type is hopeless.
8389 // Check if we meet the alignment requirement.
8390 if (RequiredAlignment > First->getAlignment())
8393 // Check that both loads are next to each other in memory.
8394 if (!areSlicesNextToEachOther(*First, *Second))
8397 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8398 --GlobalLSCost.Loads;
8399 // Move to the next pair.
8404 /// \brief Check the profitability of all involved LoadedSlice.
8405 /// Currently, it is considered profitable if there is exactly two
8406 /// involved slices (1) which are (2) next to each other in memory, and
8407 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8409 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8410 /// the elements themselves.
8412 /// FIXME: When the cost model will be mature enough, we can relax
8413 /// constraints (1) and (2).
8414 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8415 const APInt &UsedBits, bool ForCodeSize) {
8416 unsigned NumberOfSlices = LoadedSlices.size();
8417 if (StressLoadSlicing)
8418 return NumberOfSlices > 1;
8421 if (NumberOfSlices != 2)
8425 if (!areUsedBitsDense(UsedBits))
8429 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8430 // The original code has one big load.
8432 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8433 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8434 // Accumulate the cost of all the slices.
8435 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8436 GlobalSlicingCost += SliceCost;
8438 // Account as cost in the original configuration the gain obtained
8439 // with the current slices.
8440 OrigCost.addSliceGain(LS);
8443 // If the target supports paired load, adjust the cost accordingly.
8444 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8445 return OrigCost > GlobalSlicingCost;
8448 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8449 /// operations, split it in the various pieces being extracted.
8451 /// This sort of thing is introduced by SROA.
8452 /// This slicing takes care not to insert overlapping loads.
8453 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8454 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8455 if (Level < AfterLegalizeDAG)
8458 LoadSDNode *LD = cast<LoadSDNode>(N);
8459 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8460 !LD->getValueType(0).isInteger())
8463 // Keep track of already used bits to detect overlapping values.
8464 // In that case, we will just abort the transformation.
8465 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8467 SmallVector<LoadedSlice, 4> LoadedSlices;
8469 // Check if this load is used as several smaller chunks of bits.
8470 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8471 // of computation for each trunc.
8472 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8473 UI != UIEnd; ++UI) {
8474 // Skip the uses of the chain.
8475 if (UI.getUse().getResNo() != 0)
8481 // Check if this is a trunc(lshr).
8482 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8483 isa<ConstantSDNode>(User->getOperand(1))) {
8484 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8485 User = *User->use_begin();
8488 // At this point, User is a Truncate, iff we encountered, trunc or
8490 if (User->getOpcode() != ISD::TRUNCATE)
8493 // The width of the type must be a power of 2 and greater than 8-bits.
8494 // Otherwise the load cannot be represented in LLVM IR.
8495 // Moreover, if we shifted with a non-8-bits multiple, the slice
8496 // will be across several bytes. We do not support that.
8497 unsigned Width = User->getValueSizeInBits(0);
8498 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8501 // Build the slice for this chain of computations.
8502 LoadedSlice LS(User, LD, Shift, &DAG);
8503 APInt CurrentUsedBits = LS.getUsedBits();
8505 // Check if this slice overlaps with another.
8506 if ((CurrentUsedBits & UsedBits) != 0)
8508 // Update the bits used globally.
8509 UsedBits |= CurrentUsedBits;
8511 // Check if the new slice would be legal.
8515 // Record the slice.
8516 LoadedSlices.push_back(LS);
8519 // Abort slicing if it does not seem to be profitable.
8520 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8525 // Rewrite each chain to use an independent load.
8526 // By construction, each chain can be represented by a unique load.
8528 // Prepare the argument for the new token factor for all the slices.
8529 SmallVector<SDValue, 8> ArgChains;
8530 for (SmallVectorImpl<LoadedSlice>::const_iterator
8531 LSIt = LoadedSlices.begin(),
8532 LSItEnd = LoadedSlices.end();
8533 LSIt != LSItEnd; ++LSIt) {
8534 SDValue SliceInst = LSIt->loadSlice();
8535 CombineTo(LSIt->Inst, SliceInst, true);
8536 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8537 SliceInst = SliceInst.getOperand(0);
8538 assert(SliceInst->getOpcode() == ISD::LOAD &&
8539 "It takes more than a zext to get to the loaded slice!!");
8540 ArgChains.push_back(SliceInst.getValue(1));
8543 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8545 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8549 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8550 /// load is having specific bytes cleared out. If so, return the byte size
8551 /// being masked out and the shift amount.
8552 static std::pair<unsigned, unsigned>
8553 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8554 std::pair<unsigned, unsigned> Result(0, 0);
8556 // Check for the structure we're looking for.
8557 if (V->getOpcode() != ISD::AND ||
8558 !isa<ConstantSDNode>(V->getOperand(1)) ||
8559 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8562 // Check the chain and pointer.
8563 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8564 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8566 // The store should be chained directly to the load or be an operand of a
8568 if (LD == Chain.getNode())
8570 else if (Chain->getOpcode() != ISD::TokenFactor)
8571 return Result; // Fail.
8574 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8575 if (Chain->getOperand(i).getNode() == LD) {
8579 if (!isOk) return Result;
8582 // This only handles simple types.
8583 if (V.getValueType() != MVT::i16 &&
8584 V.getValueType() != MVT::i32 &&
8585 V.getValueType() != MVT::i64)
8588 // Check the constant mask. Invert it so that the bits being masked out are
8589 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8590 // follow the sign bit for uniformity.
8591 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8592 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8593 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8594 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8595 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8596 if (NotMaskLZ == 64) return Result; // All zero mask.
8598 // See if we have a continuous run of bits. If so, we have 0*1+0*
8599 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8602 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8603 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8604 NotMaskLZ -= 64-V.getValueSizeInBits();
8606 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8607 switch (MaskedBytes) {
8611 default: return Result; // All one mask, or 5-byte mask.
8614 // Verify that the first bit starts at a multiple of mask so that the access
8615 // is aligned the same as the access width.
8616 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8618 Result.first = MaskedBytes;
8619 Result.second = NotMaskTZ/8;
8624 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8625 /// provides a value as specified by MaskInfo. If so, replace the specified
8626 /// store with a narrower store of truncated IVal.
8628 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8629 SDValue IVal, StoreSDNode *St,
8631 unsigned NumBytes = MaskInfo.first;
8632 unsigned ByteShift = MaskInfo.second;
8633 SelectionDAG &DAG = DC->getDAG();
8635 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8636 // that uses this. If not, this is not a replacement.
8637 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8638 ByteShift*8, (ByteShift+NumBytes)*8);
8639 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8641 // Check that it is legal on the target to do this. It is legal if the new
8642 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8644 MVT VT = MVT::getIntegerVT(NumBytes*8);
8645 if (!DC->isTypeLegal(VT))
8648 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8649 // shifted by ByteShift and truncated down to NumBytes.
8651 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8652 DAG.getConstant(ByteShift*8,
8653 DC->getShiftAmountTy(IVal.getValueType())));
8655 // Figure out the offset for the store and the alignment of the access.
8657 unsigned NewAlign = St->getAlignment();
8659 if (DAG.getTargetLoweringInfo().isLittleEndian())
8660 StOffset = ByteShift;
8662 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8664 SDValue Ptr = St->getBasePtr();
8666 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8667 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8668 NewAlign = MinAlign(NewAlign, StOffset);
8671 // Truncate down to the new size.
8672 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8675 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8676 St->getPointerInfo().getWithOffset(StOffset),
8677 false, false, NewAlign).getNode();
8681 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8682 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8683 /// of the loaded bits, try narrowing the load and store if it would end up
8684 /// being a win for performance or code size.
8685 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8686 StoreSDNode *ST = cast<StoreSDNode>(N);
8687 if (ST->isVolatile())
8690 SDValue Chain = ST->getChain();
8691 SDValue Value = ST->getValue();
8692 SDValue Ptr = ST->getBasePtr();
8693 EVT VT = Value.getValueType();
8695 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8698 unsigned Opc = Value.getOpcode();
8700 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8701 // is a byte mask indicating a consecutive number of bytes, check to see if
8702 // Y is known to provide just those bytes. If so, we try to replace the
8703 // load + replace + store sequence with a single (narrower) store, which makes
8705 if (Opc == ISD::OR) {
8706 std::pair<unsigned, unsigned> MaskedLoad;
8707 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8708 if (MaskedLoad.first)
8709 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8710 Value.getOperand(1), ST,this))
8711 return SDValue(NewST, 0);
8713 // Or is commutative, so try swapping X and Y.
8714 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8715 if (MaskedLoad.first)
8716 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8717 Value.getOperand(0), ST,this))
8718 return SDValue(NewST, 0);
8721 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8722 Value.getOperand(1).getOpcode() != ISD::Constant)
8725 SDValue N0 = Value.getOperand(0);
8726 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8727 Chain == SDValue(N0.getNode(), 1)) {
8728 LoadSDNode *LD = cast<LoadSDNode>(N0);
8729 if (LD->getBasePtr() != Ptr ||
8730 LD->getPointerInfo().getAddrSpace() !=
8731 ST->getPointerInfo().getAddrSpace())
8734 // Find the type to narrow it the load / op / store to.
8735 SDValue N1 = Value.getOperand(1);
8736 unsigned BitWidth = N1.getValueSizeInBits();
8737 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8738 if (Opc == ISD::AND)
8739 Imm ^= APInt::getAllOnesValue(BitWidth);
8740 if (Imm == 0 || Imm.isAllOnesValue())
8742 unsigned ShAmt = Imm.countTrailingZeros();
8743 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8744 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8745 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8746 while (NewBW < BitWidth &&
8747 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8748 TLI.isNarrowingProfitable(VT, NewVT))) {
8749 NewBW = NextPowerOf2(NewBW);
8750 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8752 if (NewBW >= BitWidth)
8755 // If the lsb changed does not start at the type bitwidth boundary,
8756 // start at the previous one.
8758 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8759 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8760 std::min(BitWidth, ShAmt + NewBW));
8761 if ((Imm & Mask) == Imm) {
8762 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8763 if (Opc == ISD::AND)
8764 NewImm ^= APInt::getAllOnesValue(NewBW);
8765 uint64_t PtrOff = ShAmt / 8;
8766 // For big endian targets, we need to adjust the offset to the pointer to
8767 // load the correct bytes.
8768 if (TLI.isBigEndian())
8769 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8771 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8772 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8773 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8776 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8777 Ptr.getValueType(), Ptr,
8778 DAG.getConstant(PtrOff, Ptr.getValueType()));
8779 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8780 LD->getChain(), NewPtr,
8781 LD->getPointerInfo().getWithOffset(PtrOff),
8782 LD->isVolatile(), LD->isNonTemporal(),
8783 LD->isInvariant(), NewAlign,
8785 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8786 DAG.getConstant(NewImm, NewVT));
8787 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8789 ST->getPointerInfo().getWithOffset(PtrOff),
8790 false, false, NewAlign);
8792 AddToWorkList(NewPtr.getNode());
8793 AddToWorkList(NewLD.getNode());
8794 AddToWorkList(NewVal.getNode());
8795 WorkListRemover DeadNodes(*this);
8796 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8805 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8806 /// if the load value isn't used by any other operations, then consider
8807 /// transforming the pair to integer load / store operations if the target
8808 /// deems the transformation profitable.
8809 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8810 StoreSDNode *ST = cast<StoreSDNode>(N);
8811 SDValue Chain = ST->getChain();
8812 SDValue Value = ST->getValue();
8813 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8814 Value.hasOneUse() &&
8815 Chain == SDValue(Value.getNode(), 1)) {
8816 LoadSDNode *LD = cast<LoadSDNode>(Value);
8817 EVT VT = LD->getMemoryVT();
8818 if (!VT.isFloatingPoint() ||
8819 VT != ST->getMemoryVT() ||
8820 LD->isNonTemporal() ||
8821 ST->isNonTemporal() ||
8822 LD->getPointerInfo().getAddrSpace() != 0 ||
8823 ST->getPointerInfo().getAddrSpace() != 0)
8826 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8827 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8828 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8829 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8830 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8833 unsigned LDAlign = LD->getAlignment();
8834 unsigned STAlign = ST->getAlignment();
8835 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8836 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8837 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8840 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8841 LD->getChain(), LD->getBasePtr(),
8842 LD->getPointerInfo(),
8843 false, false, false, LDAlign);
8845 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8846 NewLD, ST->getBasePtr(),
8847 ST->getPointerInfo(),
8848 false, false, STAlign);
8850 AddToWorkList(NewLD.getNode());
8851 AddToWorkList(NewST.getNode());
8852 WorkListRemover DeadNodes(*this);
8853 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8861 /// Helper struct to parse and store a memory address as base + index + offset.
8862 /// We ignore sign extensions when it is safe to do so.
8863 /// The following two expressions are not equivalent. To differentiate we need
8864 /// to store whether there was a sign extension involved in the index
8866 /// (load (i64 add (i64 copyfromreg %c)
8867 /// (i64 signextend (add (i8 load %index)
8871 /// (load (i64 add (i64 copyfromreg %c)
8872 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8874 struct BaseIndexOffset {
8878 bool IsIndexSignExt;
8880 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8882 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8883 bool IsIndexSignExt) :
8884 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8886 bool equalBaseIndex(const BaseIndexOffset &Other) {
8887 return Other.Base == Base && Other.Index == Index &&
8888 Other.IsIndexSignExt == IsIndexSignExt;
8891 /// Parses tree in Ptr for base, index, offset addresses.
8892 static BaseIndexOffset match(SDValue Ptr) {
8893 bool IsIndexSignExt = false;
8895 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8896 // instruction, then it could be just the BASE or everything else we don't
8897 // know how to handle. Just use Ptr as BASE and give up.
8898 if (Ptr->getOpcode() != ISD::ADD)
8899 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8901 // We know that we have at least an ADD instruction. Try to pattern match
8902 // the simple case of BASE + OFFSET.
8903 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8904 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8905 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8909 // Inside a loop the current BASE pointer is calculated using an ADD and a
8910 // MUL instruction. In this case Ptr is the actual BASE pointer.
8911 // (i64 add (i64 %array_ptr)
8912 // (i64 mul (i64 %induction_var)
8913 // (i64 %element_size)))
8914 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8915 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8917 // Look at Base + Index + Offset cases.
8918 SDValue Base = Ptr->getOperand(0);
8919 SDValue IndexOffset = Ptr->getOperand(1);
8921 // Skip signextends.
8922 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8923 IndexOffset = IndexOffset->getOperand(0);
8924 IsIndexSignExt = true;
8927 // Either the case of Base + Index (no offset) or something else.
8928 if (IndexOffset->getOpcode() != ISD::ADD)
8929 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8931 // Now we have the case of Base + Index + offset.
8932 SDValue Index = IndexOffset->getOperand(0);
8933 SDValue Offset = IndexOffset->getOperand(1);
8935 if (!isa<ConstantSDNode>(Offset))
8936 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8938 // Ignore signextends.
8939 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8940 Index = Index->getOperand(0);
8941 IsIndexSignExt = true;
8942 } else IsIndexSignExt = false;
8944 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8945 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8949 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8950 /// is located in a sequence of memory operations connected by a chain.
8952 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8953 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8954 // Ptr to the mem node.
8955 LSBaseSDNode *MemNode;
8956 // Offset from the base ptr.
8957 int64_t OffsetFromBase;
8958 // What is the sequence number of this mem node.
8959 // Lowest mem operand in the DAG starts at zero.
8960 unsigned SequenceNum;
8963 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8964 EVT MemVT = St->getMemoryVT();
8965 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8966 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8967 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8969 // Don't merge vectors into wider inputs.
8970 if (MemVT.isVector() || !MemVT.isSimple())
8973 // Perform an early exit check. Do not bother looking at stored values that
8974 // are not constants or loads.
8975 SDValue StoredVal = St->getValue();
8976 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8977 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8981 // Only look at ends of store sequences.
8982 SDValue Chain = SDValue(St, 1);
8983 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8986 // This holds the base pointer, index, and the offset in bytes from the base
8988 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8990 // We must have a base and an offset.
8991 if (!BasePtr.Base.getNode())
8994 // Do not handle stores to undef base pointers.
8995 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8998 // Save the LoadSDNodes that we find in the chain.
8999 // We need to make sure that these nodes do not interfere with
9000 // any of the store nodes.
9001 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9003 // Save the StoreSDNodes that we find in the chain.
9004 SmallVector<MemOpLink, 8> StoreNodes;
9006 // Walk up the chain and look for nodes with offsets from the same
9007 // base pointer. Stop when reaching an instruction with a different kind
9008 // or instruction which has a different base pointer.
9010 StoreSDNode *Index = St;
9012 // If the chain has more than one use, then we can't reorder the mem ops.
9013 if (Index != St && !SDValue(Index, 1)->hasOneUse())
9016 // Find the base pointer and offset for this memory node.
9017 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9019 // Check that the base pointer is the same as the original one.
9020 if (!Ptr.equalBaseIndex(BasePtr))
9023 // Check that the alignment is the same.
9024 if (Index->getAlignment() != St->getAlignment())
9027 // The memory operands must not be volatile.
9028 if (Index->isVolatile() || Index->isIndexed())
9032 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9033 if (St->isTruncatingStore())
9036 // The stored memory type must be the same.
9037 if (Index->getMemoryVT() != MemVT)
9040 // We do not allow unaligned stores because we want to prevent overriding
9042 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9045 // We found a potential memory operand to merge.
9046 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9048 // Find the next memory operand in the chain. If the next operand in the
9049 // chain is a store then move up and continue the scan with the next
9050 // memory operand. If the next operand is a load save it and use alias
9051 // information to check if it interferes with anything.
9052 SDNode *NextInChain = Index->getChain().getNode();
9054 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9055 // We found a store node. Use it for the next iteration.
9058 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9059 if (Ldn->isVolatile()) {
9064 // Save the load node for later. Continue the scan.
9065 AliasLoadNodes.push_back(Ldn);
9066 NextInChain = Ldn->getChain().getNode();
9075 // Check if there is anything to merge.
9076 if (StoreNodes.size() < 2)
9079 // Sort the memory operands according to their distance from the base pointer.
9080 std::sort(StoreNodes.begin(), StoreNodes.end(),
9081 [](MemOpLink LHS, MemOpLink RHS) {
9082 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9083 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9084 LHS.SequenceNum > RHS.SequenceNum);
9087 // Scan the memory operations on the chain and find the first non-consecutive
9088 // store memory address.
9089 unsigned LastConsecutiveStore = 0;
9090 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9091 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9093 // Check that the addresses are consecutive starting from the second
9094 // element in the list of stores.
9096 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9097 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9102 // Check if this store interferes with any of the loads that we found.
9103 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9104 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9108 // We found a load that alias with this store. Stop the sequence.
9112 // Mark this node as useful.
9113 LastConsecutiveStore = i;
9116 // The node with the lowest store address.
9117 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9119 // Store the constants into memory as one consecutive store.
9121 unsigned LastLegalType = 0;
9122 unsigned LastLegalVectorType = 0;
9123 bool NonZero = false;
9124 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9125 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9126 SDValue StoredVal = St->getValue();
9128 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9129 NonZero |= !C->isNullValue();
9130 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9131 NonZero |= !C->getConstantFPValue()->isNullValue();
9137 // Find a legal type for the constant store.
9138 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9139 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9140 if (TLI.isTypeLegal(StoreTy))
9141 LastLegalType = i+1;
9142 // Or check whether a truncstore is legal.
9143 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9144 TargetLowering::TypePromoteInteger) {
9145 EVT LegalizedStoredValueTy =
9146 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9147 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9148 LastLegalType = i+1;
9151 // Find a legal type for the vector store.
9152 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9153 if (TLI.isTypeLegal(Ty))
9154 LastLegalVectorType = i + 1;
9157 // We only use vectors if the constant is known to be zero and the
9158 // function is not marked with the noimplicitfloat attribute.
9159 if (NonZero || NoVectors)
9160 LastLegalVectorType = 0;
9162 // Check if we found a legal integer type to store.
9163 if (LastLegalType == 0 && LastLegalVectorType == 0)
9166 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9167 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9169 // Make sure we have something to merge.
9173 unsigned EarliestNodeUsed = 0;
9174 for (unsigned i=0; i < NumElem; ++i) {
9175 // Find a chain for the new wide-store operand. Notice that some
9176 // of the store nodes that we found may not be selected for inclusion
9177 // in the wide store. The chain we use needs to be the chain of the
9178 // earliest store node which is *used* and replaced by the wide store.
9179 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9180 EarliestNodeUsed = i;
9183 // The earliest Node in the DAG.
9184 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9185 SDLoc DL(StoreNodes[0].MemNode);
9189 // Find a legal type for the vector store.
9190 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9191 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9192 StoredVal = DAG.getConstant(0, Ty);
9194 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9195 APInt StoreInt(StoreBW, 0);
9197 // Construct a single integer constant which is made of the smaller
9199 bool IsLE = TLI.isLittleEndian();
9200 for (unsigned i = 0; i < NumElem ; ++i) {
9201 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9202 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9203 SDValue Val = St->getValue();
9204 StoreInt<<=ElementSizeBytes*8;
9205 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9206 StoreInt|=C->getAPIntValue().zext(StoreBW);
9207 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9208 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9210 assert(false && "Invalid constant element type");
9214 // Create the new Load and Store operations.
9215 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9216 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9219 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9220 FirstInChain->getBasePtr(),
9221 FirstInChain->getPointerInfo(),
9223 FirstInChain->getAlignment());
9225 // Replace the first store with the new store
9226 CombineTo(EarliestOp, NewStore);
9227 // Erase all other stores.
9228 for (unsigned i = 0; i < NumElem ; ++i) {
9229 if (StoreNodes[i].MemNode == EarliestOp)
9231 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9232 // ReplaceAllUsesWith will replace all uses that existed when it was
9233 // called, but graph optimizations may cause new ones to appear. For
9234 // example, the case in pr14333 looks like
9236 // St's chain -> St -> another store -> X
9238 // And the only difference from St to the other store is the chain.
9239 // When we change it's chain to be St's chain they become identical,
9240 // get CSEed and the net result is that X is now a use of St.
9241 // Since we know that St is redundant, just iterate.
9242 while (!St->use_empty())
9243 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9244 removeFromWorkList(St);
9251 // Below we handle the case of multiple consecutive stores that
9252 // come from multiple consecutive loads. We merge them into a single
9253 // wide load and a single wide store.
9255 // Look for load nodes which are used by the stored values.
9256 SmallVector<MemOpLink, 8> LoadNodes;
9258 // Find acceptable loads. Loads need to have the same chain (token factor),
9259 // must not be zext, volatile, indexed, and they must be consecutive.
9260 BaseIndexOffset LdBasePtr;
9261 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9262 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9263 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9266 // Loads must only have one use.
9267 if (!Ld->hasNUsesOfValue(1, 0))
9270 // Check that the alignment is the same as the stores.
9271 if (Ld->getAlignment() != St->getAlignment())
9274 // The memory operands must not be volatile.
9275 if (Ld->isVolatile() || Ld->isIndexed())
9278 // We do not accept ext loads.
9279 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9282 // The stored memory type must be the same.
9283 if (Ld->getMemoryVT() != MemVT)
9286 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9287 // If this is not the first ptr that we check.
9288 if (LdBasePtr.Base.getNode()) {
9289 // The base ptr must be the same.
9290 if (!LdPtr.equalBaseIndex(LdBasePtr))
9293 // Check that all other base pointers are the same as this one.
9297 // We found a potential memory operand to merge.
9298 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9301 if (LoadNodes.size() < 2)
9304 // Scan the memory operations on the chain and find the first non-consecutive
9305 // load memory address. These variables hold the index in the store node
9307 unsigned LastConsecutiveLoad = 0;
9308 // This variable refers to the size and not index in the array.
9309 unsigned LastLegalVectorType = 0;
9310 unsigned LastLegalIntegerType = 0;
9311 StartAddress = LoadNodes[0].OffsetFromBase;
9312 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9313 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9314 // All loads much share the same chain.
9315 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9318 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9319 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9321 LastConsecutiveLoad = i;
9323 // Find a legal type for the vector store.
9324 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9325 if (TLI.isTypeLegal(StoreTy))
9326 LastLegalVectorType = i + 1;
9328 // Find a legal type for the integer store.
9329 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9330 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9331 if (TLI.isTypeLegal(StoreTy))
9332 LastLegalIntegerType = i + 1;
9333 // Or check whether a truncstore and extload is legal.
9334 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9335 TargetLowering::TypePromoteInteger) {
9336 EVT LegalizedStoredValueTy =
9337 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9338 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9339 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9340 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9341 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9342 LastLegalIntegerType = i+1;
9346 // Only use vector types if the vector type is larger than the integer type.
9347 // If they are the same, use integers.
9348 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9349 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9351 // We add +1 here because the LastXXX variables refer to location while
9352 // the NumElem refers to array/index size.
9353 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9354 NumElem = std::min(LastLegalType, NumElem);
9359 // The earliest Node in the DAG.
9360 unsigned EarliestNodeUsed = 0;
9361 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9362 for (unsigned i=1; i<NumElem; ++i) {
9363 // Find a chain for the new wide-store operand. Notice that some
9364 // of the store nodes that we found may not be selected for inclusion
9365 // in the wide store. The chain we use needs to be the chain of the
9366 // earliest store node which is *used* and replaced by the wide store.
9367 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9368 EarliestNodeUsed = i;
9371 // Find if it is better to use vectors or integers to load and store
9375 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9377 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9378 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9381 SDLoc LoadDL(LoadNodes[0].MemNode);
9382 SDLoc StoreDL(StoreNodes[0].MemNode);
9384 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9385 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9386 FirstLoad->getChain(),
9387 FirstLoad->getBasePtr(),
9388 FirstLoad->getPointerInfo(),
9389 false, false, false,
9390 FirstLoad->getAlignment());
9392 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9393 FirstInChain->getBasePtr(),
9394 FirstInChain->getPointerInfo(), false, false,
9395 FirstInChain->getAlignment());
9397 // Replace one of the loads with the new load.
9398 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9399 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9400 SDValue(NewLoad.getNode(), 1));
9402 // Remove the rest of the load chains.
9403 for (unsigned i = 1; i < NumElem ; ++i) {
9404 // Replace all chain users of the old load nodes with the chain of the new
9406 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9407 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9410 // Replace the first store with the new store.
9411 CombineTo(EarliestOp, NewStore);
9412 // Erase all other stores.
9413 for (unsigned i = 0; i < NumElem ; ++i) {
9414 // Remove all Store nodes.
9415 if (StoreNodes[i].MemNode == EarliestOp)
9417 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9418 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9419 removeFromWorkList(St);
9426 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9427 StoreSDNode *ST = cast<StoreSDNode>(N);
9428 SDValue Chain = ST->getChain();
9429 SDValue Value = ST->getValue();
9430 SDValue Ptr = ST->getBasePtr();
9432 // If this is a store of a bit convert, store the input value if the
9433 // resultant store does not need a higher alignment than the original.
9434 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9435 ST->isUnindexed()) {
9436 unsigned OrigAlign = ST->getAlignment();
9437 EVT SVT = Value.getOperand(0).getValueType();
9438 unsigned Align = TLI.getDataLayout()->
9439 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9440 if (Align <= OrigAlign &&
9441 ((!LegalOperations && !ST->isVolatile()) ||
9442 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9443 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9444 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9445 ST->isNonTemporal(), OrigAlign,
9449 // Turn 'store undef, Ptr' -> nothing.
9450 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9453 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9454 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9455 // NOTE: If the original store is volatile, this transform must not increase
9456 // the number of stores. For example, on x86-32 an f64 can be stored in one
9457 // processor operation but an i64 (which is not legal) requires two. So the
9458 // transform should not be done in this case.
9459 if (Value.getOpcode() != ISD::TargetConstantFP) {
9461 switch (CFP->getSimpleValueType(0).SimpleTy) {
9462 default: llvm_unreachable("Unknown FP type");
9463 case MVT::f16: // We don't do this for these yet.
9469 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9470 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9471 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9472 bitcastToAPInt().getZExtValue(), MVT::i32);
9473 return DAG.getStore(Chain, SDLoc(N), Tmp,
9474 Ptr, ST->getMemOperand());
9478 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9479 !ST->isVolatile()) ||
9480 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9481 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9482 getZExtValue(), MVT::i64);
9483 return DAG.getStore(Chain, SDLoc(N), Tmp,
9484 Ptr, ST->getMemOperand());
9487 if (!ST->isVolatile() &&
9488 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9489 // Many FP stores are not made apparent until after legalize, e.g. for
9490 // argument passing. Since this is so common, custom legalize the
9491 // 64-bit integer store into two 32-bit stores.
9492 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9493 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9494 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9495 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9497 unsigned Alignment = ST->getAlignment();
9498 bool isVolatile = ST->isVolatile();
9499 bool isNonTemporal = ST->isNonTemporal();
9500 const MDNode *TBAAInfo = ST->getTBAAInfo();
9502 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9503 Ptr, ST->getPointerInfo(),
9504 isVolatile, isNonTemporal,
9505 ST->getAlignment(), TBAAInfo);
9506 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9507 DAG.getConstant(4, Ptr.getValueType()));
9508 Alignment = MinAlign(Alignment, 4U);
9509 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9510 Ptr, ST->getPointerInfo().getWithOffset(4),
9511 isVolatile, isNonTemporal,
9512 Alignment, TBAAInfo);
9513 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9522 // Try to infer better alignment information than the store already has.
9523 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9524 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9525 if (Align > ST->getAlignment())
9526 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9527 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9528 ST->isVolatile(), ST->isNonTemporal(), Align,
9533 // Try transforming a pair floating point load / store ops to integer
9534 // load / store ops.
9535 SDValue NewST = TransformFPLoadStorePair(N);
9536 if (NewST.getNode())
9539 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9540 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9542 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9543 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9546 if (UseAA && ST->isUnindexed()) {
9547 // Walk up chain skipping non-aliasing memory nodes.
9548 SDValue BetterChain = FindBetterChain(N, Chain);
9550 // If there is a better chain.
9551 if (Chain != BetterChain) {
9554 // Replace the chain to avoid dependency.
9555 if (ST->isTruncatingStore()) {
9556 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9557 ST->getMemoryVT(), ST->getMemOperand());
9559 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9560 ST->getMemOperand());
9563 // Create token to keep both nodes around.
9564 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9565 MVT::Other, Chain, ReplStore);
9567 // Make sure the new and old chains are cleaned up.
9568 AddToWorkList(Token.getNode());
9570 // Don't add users to work list.
9571 return CombineTo(N, Token, false);
9575 // Try transforming N to an indexed store.
9576 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9577 return SDValue(N, 0);
9579 // FIXME: is there such a thing as a truncating indexed store?
9580 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9581 Value.getValueType().isInteger()) {
9582 // See if we can simplify the input to this truncstore with knowledge that
9583 // only the low bits are being used. For example:
9584 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9586 GetDemandedBits(Value,
9587 APInt::getLowBitsSet(
9588 Value.getValueType().getScalarType().getSizeInBits(),
9589 ST->getMemoryVT().getScalarType().getSizeInBits()));
9590 AddToWorkList(Value.getNode());
9591 if (Shorter.getNode())
9592 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9593 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9595 // Otherwise, see if we can simplify the operation with
9596 // SimplifyDemandedBits, which only works if the value has a single use.
9597 if (SimplifyDemandedBits(Value,
9598 APInt::getLowBitsSet(
9599 Value.getValueType().getScalarType().getSizeInBits(),
9600 ST->getMemoryVT().getScalarType().getSizeInBits())))
9601 return SDValue(N, 0);
9604 // If this is a load followed by a store to the same location, then the store
9606 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9607 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9608 ST->isUnindexed() && !ST->isVolatile() &&
9609 // There can't be any side effects between the load and store, such as
9611 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9612 // The store is dead, remove it.
9617 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9618 // truncating store. We can do this even if this is already a truncstore.
9619 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9620 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9621 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9622 ST->getMemoryVT())) {
9623 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9624 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9627 // Only perform this optimization before the types are legal, because we
9628 // don't want to perform this optimization on every DAGCombine invocation.
9630 bool EverChanged = false;
9633 // There can be multiple store sequences on the same chain.
9634 // Keep trying to merge store sequences until we are unable to do so
9635 // or until we merge the last store on the chain.
9636 bool Changed = MergeConsecutiveStores(ST);
9637 EverChanged |= Changed;
9638 if (!Changed) break;
9639 } while (ST->getOpcode() != ISD::DELETED_NODE);
9642 return SDValue(N, 0);
9645 return ReduceLoadOpStoreWidth(N);
9648 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9649 SDValue InVec = N->getOperand(0);
9650 SDValue InVal = N->getOperand(1);
9651 SDValue EltNo = N->getOperand(2);
9654 // If the inserted element is an UNDEF, just use the input vector.
9655 if (InVal.getOpcode() == ISD::UNDEF)
9658 EVT VT = InVec.getValueType();
9660 // If we can't generate a legal BUILD_VECTOR, exit
9661 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9664 // Check that we know which element is being inserted
9665 if (!isa<ConstantSDNode>(EltNo))
9667 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9669 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9670 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9672 SmallVector<SDValue, 8> Ops;
9673 // Do not combine these two vectors if the output vector will not replace
9674 // the input vector.
9675 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9676 Ops.append(InVec.getNode()->op_begin(),
9677 InVec.getNode()->op_end());
9678 } else if (InVec.getOpcode() == ISD::UNDEF) {
9679 unsigned NElts = VT.getVectorNumElements();
9680 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9685 // Insert the element
9686 if (Elt < Ops.size()) {
9687 // All the operands of BUILD_VECTOR must have the same type;
9688 // we enforce that here.
9689 EVT OpVT = Ops[0].getValueType();
9690 if (InVal.getValueType() != OpVT)
9691 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9692 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9693 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9697 // Return the new vector
9698 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9701 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9702 // (vextract (scalar_to_vector val, 0) -> val
9703 SDValue InVec = N->getOperand(0);
9704 EVT VT = InVec.getValueType();
9705 EVT NVT = N->getValueType(0);
9707 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9708 // Check if the result type doesn't match the inserted element type. A
9709 // SCALAR_TO_VECTOR may truncate the inserted element and the
9710 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9711 SDValue InOp = InVec.getOperand(0);
9712 if (InOp.getValueType() != NVT) {
9713 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9714 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9719 SDValue EltNo = N->getOperand(1);
9720 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9722 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9723 // We only perform this optimization before the op legalization phase because
9724 // we may introduce new vector instructions which are not backed by TD
9725 // patterns. For example on AVX, extracting elements from a wide vector
9726 // without using extract_subvector. However, if we can find an underlying
9727 // scalar value, then we can always use that.
9728 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9730 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9731 int NumElem = VT.getVectorNumElements();
9732 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9733 // Find the new index to extract from.
9734 int OrigElt = SVOp->getMaskElt(Elt);
9736 // Extracting an undef index is undef.
9738 return DAG.getUNDEF(NVT);
9740 // Select the right vector half to extract from.
9742 if (OrigElt < NumElem) {
9743 SVInVec = InVec->getOperand(0);
9745 SVInVec = InVec->getOperand(1);
9749 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9750 SDValue InOp = SVInVec.getOperand(OrigElt);
9751 if (InOp.getValueType() != NVT) {
9752 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9753 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9759 // FIXME: We should handle recursing on other vector shuffles and
9760 // scalar_to_vector here as well.
9762 if (!LegalOperations) {
9763 EVT IndexTy = TLI.getVectorIdxTy();
9764 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9765 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9769 // Perform only after legalization to ensure build_vector / vector_shuffle
9770 // optimizations have already been done.
9771 if (!LegalOperations) return SDValue();
9773 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9774 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9775 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9778 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9779 bool NewLoad = false;
9780 bool BCNumEltsChanged = false;
9781 EVT ExtVT = VT.getVectorElementType();
9784 // If the result of load has to be truncated, then it's not necessarily
9786 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9789 if (InVec.getOpcode() == ISD::BITCAST) {
9790 // Don't duplicate a load with other uses.
9791 if (!InVec.hasOneUse())
9794 EVT BCVT = InVec.getOperand(0).getValueType();
9795 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9797 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9798 BCNumEltsChanged = true;
9799 InVec = InVec.getOperand(0);
9800 ExtVT = BCVT.getVectorElementType();
9804 LoadSDNode *LN0 = nullptr;
9805 const ShuffleVectorSDNode *SVN = nullptr;
9806 if (ISD::isNormalLoad(InVec.getNode())) {
9807 LN0 = cast<LoadSDNode>(InVec);
9808 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9809 InVec.getOperand(0).getValueType() == ExtVT &&
9810 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9811 // Don't duplicate a load with other uses.
9812 if (!InVec.hasOneUse())
9815 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9816 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9817 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9819 // (load $addr+1*size)
9821 // Don't duplicate a load with other uses.
9822 if (!InVec.hasOneUse())
9825 // If the bit convert changed the number of elements, it is unsafe
9826 // to examine the mask.
9827 if (BCNumEltsChanged)
9830 // Select the input vector, guarding against out of range extract vector.
9831 unsigned NumElems = VT.getVectorNumElements();
9832 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9833 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9835 if (InVec.getOpcode() == ISD::BITCAST) {
9836 // Don't duplicate a load with other uses.
9837 if (!InVec.hasOneUse())
9840 InVec = InVec.getOperand(0);
9842 if (ISD::isNormalLoad(InVec.getNode())) {
9843 LN0 = cast<LoadSDNode>(InVec);
9844 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9848 // Make sure we found a non-volatile load and the extractelement is
9850 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9853 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9855 return DAG.getUNDEF(LVT);
9857 unsigned Align = LN0->getAlignment();
9859 // Check the resultant load doesn't need a higher alignment than the
9863 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9865 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9871 SDValue NewPtr = LN0->getBasePtr();
9872 unsigned PtrOff = 0;
9875 PtrOff = LVT.getSizeInBits() * Elt / 8;
9876 EVT PtrType = NewPtr.getValueType();
9877 if (TLI.isBigEndian())
9878 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9879 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9880 DAG.getConstant(PtrOff, PtrType));
9883 // The replacement we need to do here is a little tricky: we need to
9884 // replace an extractelement of a load with a load.
9885 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9886 // Note that this replacement assumes that the extractvalue is the only
9887 // use of the load; that's okay because we don't want to perform this
9888 // transformation in other cases anyway.
9891 if (NVT.bitsGT(LVT)) {
9892 // If the result type of vextract is wider than the load, then issue an
9893 // extending load instead.
9894 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9895 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9896 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9897 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9898 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9899 Align, LN0->getTBAAInfo());
9900 Chain = Load.getValue(1);
9902 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9903 LN0->getPointerInfo().getWithOffset(PtrOff),
9904 LN0->isVolatile(), LN0->isNonTemporal(),
9905 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9906 Chain = Load.getValue(1);
9907 if (NVT.bitsLT(LVT))
9908 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9910 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9912 WorkListRemover DeadNodes(*this);
9913 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9914 SDValue To[] = { Load, Chain };
9915 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9916 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9917 // worklist explicitly as well.
9918 AddToWorkList(Load.getNode());
9919 AddUsersToWorkList(Load.getNode()); // Add users too
9920 // Make sure to revisit this node to clean it up; it will usually be dead.
9922 return SDValue(N, 0);
9928 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9929 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9930 // We perform this optimization post type-legalization because
9931 // the type-legalizer often scalarizes integer-promoted vectors.
9932 // Performing this optimization before may create bit-casts which
9933 // will be type-legalized to complex code sequences.
9934 // We perform this optimization only before the operation legalizer because we
9935 // may introduce illegal operations.
9936 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9939 unsigned NumInScalars = N->getNumOperands();
9941 EVT VT = N->getValueType(0);
9943 // Check to see if this is a BUILD_VECTOR of a bunch of values
9944 // which come from any_extend or zero_extend nodes. If so, we can create
9945 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9946 // optimizations. We do not handle sign-extend because we can't fill the sign
9948 EVT SourceType = MVT::Other;
9949 bool AllAnyExt = true;
9951 for (unsigned i = 0; i != NumInScalars; ++i) {
9952 SDValue In = N->getOperand(i);
9953 // Ignore undef inputs.
9954 if (In.getOpcode() == ISD::UNDEF) continue;
9956 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9957 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9959 // Abort if the element is not an extension.
9960 if (!ZeroExt && !AnyExt) {
9961 SourceType = MVT::Other;
9965 // The input is a ZeroExt or AnyExt. Check the original type.
9966 EVT InTy = In.getOperand(0).getValueType();
9968 // Check that all of the widened source types are the same.
9969 if (SourceType == MVT::Other)
9972 else if (InTy != SourceType) {
9973 // Multiple income types. Abort.
9974 SourceType = MVT::Other;
9978 // Check if all of the extends are ANY_EXTENDs.
9979 AllAnyExt &= AnyExt;
9982 // In order to have valid types, all of the inputs must be extended from the
9983 // same source type and all of the inputs must be any or zero extend.
9984 // Scalar sizes must be a power of two.
9985 EVT OutScalarTy = VT.getScalarType();
9986 bool ValidTypes = SourceType != MVT::Other &&
9987 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9988 isPowerOf2_32(SourceType.getSizeInBits());
9990 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9991 // turn into a single shuffle instruction.
9995 bool isLE = TLI.isLittleEndian();
9996 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9997 assert(ElemRatio > 1 && "Invalid element size ratio");
9998 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9999 DAG.getConstant(0, SourceType);
10001 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10002 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10004 // Populate the new build_vector
10005 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10006 SDValue Cast = N->getOperand(i);
10007 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10008 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10009 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10011 if (Cast.getOpcode() == ISD::UNDEF)
10012 In = DAG.getUNDEF(SourceType);
10014 In = Cast->getOperand(0);
10015 unsigned Index = isLE ? (i * ElemRatio) :
10016 (i * ElemRatio + (ElemRatio - 1));
10018 assert(Index < Ops.size() && "Invalid index");
10022 // The type of the new BUILD_VECTOR node.
10023 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10024 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10025 "Invalid vector size");
10026 // Check if the new vector type is legal.
10027 if (!isTypeLegal(VecVT)) return SDValue();
10029 // Make the new BUILD_VECTOR.
10030 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10032 // The new BUILD_VECTOR node has the potential to be further optimized.
10033 AddToWorkList(BV.getNode());
10034 // Bitcast to the desired type.
10035 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10038 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10039 EVT VT = N->getValueType(0);
10041 unsigned NumInScalars = N->getNumOperands();
10044 EVT SrcVT = MVT::Other;
10045 unsigned Opcode = ISD::DELETED_NODE;
10046 unsigned NumDefs = 0;
10048 for (unsigned i = 0; i != NumInScalars; ++i) {
10049 SDValue In = N->getOperand(i);
10050 unsigned Opc = In.getOpcode();
10052 if (Opc == ISD::UNDEF)
10055 // If all scalar values are floats and converted from integers.
10056 if (Opcode == ISD::DELETED_NODE &&
10057 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10064 EVT InVT = In.getOperand(0).getValueType();
10066 // If all scalar values are typed differently, bail out. It's chosen to
10067 // simplify BUILD_VECTOR of integer types.
10068 if (SrcVT == MVT::Other)
10075 // If the vector has just one element defined, it's not worth to fold it into
10076 // a vectorized one.
10080 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10081 && "Should only handle conversion from integer to float.");
10082 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10084 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10086 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10089 SmallVector<SDValue, 8> Opnds;
10090 for (unsigned i = 0; i != NumInScalars; ++i) {
10091 SDValue In = N->getOperand(i);
10093 if (In.getOpcode() == ISD::UNDEF)
10094 Opnds.push_back(DAG.getUNDEF(SrcVT));
10096 Opnds.push_back(In.getOperand(0));
10098 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10099 AddToWorkList(BV.getNode());
10101 return DAG.getNode(Opcode, dl, VT, BV);
10104 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10105 unsigned NumInScalars = N->getNumOperands();
10107 EVT VT = N->getValueType(0);
10109 // A vector built entirely of undefs is undef.
10110 if (ISD::allOperandsUndef(N))
10111 return DAG.getUNDEF(VT);
10113 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10117 V = reduceBuildVecConvertToConvertBuildVec(N);
10121 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10122 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10123 // at most two distinct vectors, turn this into a shuffle node.
10125 // May only combine to shuffle after legalize if shuffle is legal.
10126 if (LegalOperations &&
10127 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10130 SDValue VecIn1, VecIn2;
10131 for (unsigned i = 0; i != NumInScalars; ++i) {
10132 // Ignore undef inputs.
10133 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10135 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10136 // constant index, bail out.
10137 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10138 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10139 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10143 // We allow up to two distinct input vectors.
10144 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10145 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10148 if (!VecIn1.getNode()) {
10149 VecIn1 = ExtractedFromVec;
10150 } else if (!VecIn2.getNode()) {
10151 VecIn2 = ExtractedFromVec;
10153 // Too many inputs.
10154 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10159 // If everything is good, we can make a shuffle operation.
10160 if (VecIn1.getNode()) {
10161 SmallVector<int, 8> Mask;
10162 for (unsigned i = 0; i != NumInScalars; ++i) {
10163 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10164 Mask.push_back(-1);
10168 // If extracting from the first vector, just use the index directly.
10169 SDValue Extract = N->getOperand(i);
10170 SDValue ExtVal = Extract.getOperand(1);
10171 if (Extract.getOperand(0) == VecIn1) {
10172 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10173 if (ExtIndex > VT.getVectorNumElements())
10176 Mask.push_back(ExtIndex);
10180 // Otherwise, use InIdx + VecSize
10181 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10182 Mask.push_back(Idx+NumInScalars);
10185 // We can't generate a shuffle node with mismatched input and output types.
10186 // Attempt to transform a single input vector to the correct type.
10187 if ((VT != VecIn1.getValueType())) {
10188 // We don't support shuffeling between TWO values of different types.
10189 if (VecIn2.getNode())
10192 // We only support widening of vectors which are half the size of the
10193 // output registers. For example XMM->YMM widening on X86 with AVX.
10194 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10197 // If the input vector type has a different base type to the output
10198 // vector type, bail out.
10199 if (VecIn1.getValueType().getVectorElementType() !=
10200 VT.getVectorElementType())
10203 // Widen the input vector by adding undef values.
10204 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10205 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10208 // If VecIn2 is unused then change it to undef.
10209 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10211 // Check that we were able to transform all incoming values to the same
10213 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10214 VecIn1.getValueType() != VT)
10217 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10218 if (!isTypeLegal(VT))
10221 // Return the new VECTOR_SHUFFLE node.
10225 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10231 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10232 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10233 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10234 // inputs come from at most two distinct vectors, turn this into a shuffle
10237 // If we only have one input vector, we don't need to do any concatenation.
10238 if (N->getNumOperands() == 1)
10239 return N->getOperand(0);
10241 // Check if all of the operands are undefs.
10242 EVT VT = N->getValueType(0);
10243 if (ISD::allOperandsUndef(N))
10244 return DAG.getUNDEF(VT);
10246 // Optimize concat_vectors where one of the vectors is undef.
10247 if (N->getNumOperands() == 2 &&
10248 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10249 SDValue In = N->getOperand(0);
10250 assert(In.getValueType().isVector() && "Must concat vectors");
10252 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10253 if (In->getOpcode() == ISD::BITCAST &&
10254 !In->getOperand(0)->getValueType(0).isVector()) {
10255 SDValue Scalar = In->getOperand(0);
10256 EVT SclTy = Scalar->getValueType(0);
10258 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10261 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10262 VT.getSizeInBits() / SclTy.getSizeInBits());
10263 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10266 SDLoc dl = SDLoc(N);
10267 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10268 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10272 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10273 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10274 if (N->getNumOperands() == 2 &&
10275 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10276 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10277 EVT VT = N->getValueType(0);
10278 SDValue N0 = N->getOperand(0);
10279 SDValue N1 = N->getOperand(1);
10280 SmallVector<SDValue, 8> Opnds;
10281 unsigned BuildVecNumElts = N0.getNumOperands();
10283 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10284 Opnds.push_back(N0.getOperand(i));
10285 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10286 Opnds.push_back(N1.getOperand(i));
10288 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10291 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10292 // nodes often generate nop CONCAT_VECTOR nodes.
10293 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10294 // place the incoming vectors at the exact same location.
10295 SDValue SingleSource = SDValue();
10296 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10298 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10299 SDValue Op = N->getOperand(i);
10301 if (Op.getOpcode() == ISD::UNDEF)
10304 // Check if this is the identity extract:
10305 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10308 // Find the single incoming vector for the extract_subvector.
10309 if (SingleSource.getNode()) {
10310 if (Op.getOperand(0) != SingleSource)
10313 SingleSource = Op.getOperand(0);
10315 // Check the source type is the same as the type of the result.
10316 // If not, this concat may extend the vector, so we can not
10317 // optimize it away.
10318 if (SingleSource.getValueType() != N->getValueType(0))
10322 unsigned IdentityIndex = i * PartNumElem;
10323 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10324 // The extract index must be constant.
10328 // Check that we are reading from the identity index.
10329 if (CS->getZExtValue() != IdentityIndex)
10333 if (SingleSource.getNode())
10334 return SingleSource;
10339 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10340 EVT NVT = N->getValueType(0);
10341 SDValue V = N->getOperand(0);
10343 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10345 // (extract_subvec (concat V1, V2, ...), i)
10348 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10350 if (V->getOperand(0).getValueType() != NVT)
10352 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10353 unsigned NumElems = NVT.getVectorNumElements();
10354 assert((Idx % NumElems) == 0 &&
10355 "IDX in concat is not a multiple of the result vector length.");
10356 return V->getOperand(Idx / NumElems);
10360 if (V->getOpcode() == ISD::BITCAST)
10361 V = V.getOperand(0);
10363 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10365 // Handle only simple case where vector being inserted and vector
10366 // being extracted are of same type, and are half size of larger vectors.
10367 EVT BigVT = V->getOperand(0).getValueType();
10368 EVT SmallVT = V->getOperand(1).getValueType();
10369 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10372 // Only handle cases where both indexes are constants with the same type.
10373 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10374 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10376 if (InsIdx && ExtIdx &&
10377 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10378 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10380 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10382 // indices are equal or bit offsets are equal => V1
10383 // otherwise => (extract_subvec V1, ExtIdx)
10384 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10385 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10386 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10387 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10388 DAG.getNode(ISD::BITCAST, dl,
10389 N->getOperand(0).getValueType(),
10390 V->getOperand(0)), N->getOperand(1));
10397 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10398 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10399 EVT VT = N->getValueType(0);
10400 unsigned NumElts = VT.getVectorNumElements();
10402 SDValue N0 = N->getOperand(0);
10403 SDValue N1 = N->getOperand(1);
10404 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10406 SmallVector<SDValue, 4> Ops;
10407 EVT ConcatVT = N0.getOperand(0).getValueType();
10408 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10409 unsigned NumConcats = NumElts / NumElemsPerConcat;
10411 // Look at every vector that's inserted. We're looking for exact
10412 // subvector-sized copies from a concatenated vector
10413 for (unsigned I = 0; I != NumConcats; ++I) {
10414 // Make sure we're dealing with a copy.
10415 unsigned Begin = I * NumElemsPerConcat;
10416 bool AllUndef = true, NoUndef = true;
10417 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10418 if (SVN->getMaskElt(J) >= 0)
10425 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10428 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10429 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10432 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10433 if (FirstElt < N0.getNumOperands())
10434 Ops.push_back(N0.getOperand(FirstElt));
10436 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10438 } else if (AllUndef) {
10439 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10440 } else { // Mixed with general masks and undefs, can't do optimization.
10445 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10448 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10449 EVT VT = N->getValueType(0);
10450 unsigned NumElts = VT.getVectorNumElements();
10452 SDValue N0 = N->getOperand(0);
10453 SDValue N1 = N->getOperand(1);
10455 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10457 // Canonicalize shuffle undef, undef -> undef
10458 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10459 return DAG.getUNDEF(VT);
10461 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10463 // Canonicalize shuffle v, v -> v, undef
10465 SmallVector<int, 8> NewMask;
10466 for (unsigned i = 0; i != NumElts; ++i) {
10467 int Idx = SVN->getMaskElt(i);
10468 if (Idx >= (int)NumElts) Idx -= NumElts;
10469 NewMask.push_back(Idx);
10471 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10475 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10476 if (N0.getOpcode() == ISD::UNDEF) {
10477 SmallVector<int, 8> NewMask;
10478 for (unsigned i = 0; i != NumElts; ++i) {
10479 int Idx = SVN->getMaskElt(i);
10481 if (Idx >= (int)NumElts)
10484 Idx = -1; // remove reference to lhs
10486 NewMask.push_back(Idx);
10488 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10492 // Remove references to rhs if it is undef
10493 if (N1.getOpcode() == ISD::UNDEF) {
10494 bool Changed = false;
10495 SmallVector<int, 8> NewMask;
10496 for (unsigned i = 0; i != NumElts; ++i) {
10497 int Idx = SVN->getMaskElt(i);
10498 if (Idx >= (int)NumElts) {
10502 NewMask.push_back(Idx);
10505 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10508 // If it is a splat, check if the argument vector is another splat or a
10509 // build_vector with all scalar elements the same.
10510 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10511 SDNode *V = N0.getNode();
10513 // If this is a bit convert that changes the element type of the vector but
10514 // not the number of vector elements, look through it. Be careful not to
10515 // look though conversions that change things like v4f32 to v2f64.
10516 if (V->getOpcode() == ISD::BITCAST) {
10517 SDValue ConvInput = V->getOperand(0);
10518 if (ConvInput.getValueType().isVector() &&
10519 ConvInput.getValueType().getVectorNumElements() == NumElts)
10520 V = ConvInput.getNode();
10523 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10524 assert(V->getNumOperands() == NumElts &&
10525 "BUILD_VECTOR has wrong number of operands");
10527 bool AllSame = true;
10528 for (unsigned i = 0; i != NumElts; ++i) {
10529 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10530 Base = V->getOperand(i);
10534 // Splat of <u, u, u, u>, return <u, u, u, u>
10535 if (!Base.getNode())
10537 for (unsigned i = 0; i != NumElts; ++i) {
10538 if (V->getOperand(i) != Base) {
10543 // Splat of <x, x, x, x>, return <x, x, x, x>
10549 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10550 Level < AfterLegalizeVectorOps &&
10551 (N1.getOpcode() == ISD::UNDEF ||
10552 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10553 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10554 SDValue V = partitionShuffleOfConcats(N, DAG);
10560 // If this shuffle node is simply a swizzle of another shuffle node,
10561 // and it reverses the swizzle of the previous shuffle then we can
10562 // optimize shuffle(shuffle(x, undef), undef) -> x.
10563 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10564 N1.getOpcode() == ISD::UNDEF) {
10566 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10568 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10569 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10572 // The incoming shuffle must be of the same type as the result of the
10573 // current shuffle.
10574 assert(OtherSV->getOperand(0).getValueType() == VT &&
10575 "Shuffle types don't match");
10577 for (unsigned i = 0; i != NumElts; ++i) {
10578 int Idx = SVN->getMaskElt(i);
10579 assert(Idx < (int)NumElts && "Index references undef operand");
10580 // Next, this index comes from the first value, which is the incoming
10581 // shuffle. Adopt the incoming index.
10583 Idx = OtherSV->getMaskElt(Idx);
10585 // The combined shuffle must map each index to itself.
10586 if (Idx >= 0 && (unsigned)Idx != i)
10590 return OtherSV->getOperand(0);
10596 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10597 SDValue N0 = N->getOperand(0);
10598 SDValue N2 = N->getOperand(2);
10600 // If the input vector is a concatenation, and the insert replaces
10601 // one of the halves, we can optimize into a single concat_vectors.
10602 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10603 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10604 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10605 EVT VT = N->getValueType(0);
10607 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10608 // (concat_vectors Z, Y)
10610 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10611 N->getOperand(1), N0.getOperand(1));
10613 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10614 // (concat_vectors X, Z)
10615 if (InsIdx == VT.getVectorNumElements()/2)
10616 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10617 N0.getOperand(0), N->getOperand(1));
10623 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10624 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10625 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10626 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10627 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10628 EVT VT = N->getValueType(0);
10630 SDValue LHS = N->getOperand(0);
10631 SDValue RHS = N->getOperand(1);
10632 if (N->getOpcode() == ISD::AND) {
10633 if (RHS.getOpcode() == ISD::BITCAST)
10634 RHS = RHS.getOperand(0);
10635 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10636 SmallVector<int, 8> Indices;
10637 unsigned NumElts = RHS.getNumOperands();
10638 for (unsigned i = 0; i != NumElts; ++i) {
10639 SDValue Elt = RHS.getOperand(i);
10640 if (!isa<ConstantSDNode>(Elt))
10643 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10644 Indices.push_back(i);
10645 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10646 Indices.push_back(NumElts);
10651 // Let's see if the target supports this vector_shuffle.
10652 EVT RVT = RHS.getValueType();
10653 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10656 // Return the new VECTOR_SHUFFLE node.
10657 EVT EltVT = RVT.getVectorElementType();
10658 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10659 DAG.getConstant(0, EltVT));
10660 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
10661 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10662 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10663 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10670 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10671 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10672 assert(N->getValueType(0).isVector() &&
10673 "SimplifyVBinOp only works on vectors!");
10675 SDValue LHS = N->getOperand(0);
10676 SDValue RHS = N->getOperand(1);
10677 SDValue Shuffle = XformToShuffleWithZero(N);
10678 if (Shuffle.getNode()) return Shuffle;
10680 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10682 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10683 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10684 // Check if both vectors are constants. If not bail out.
10685 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10686 cast<BuildVectorSDNode>(RHS)->isConstant()))
10689 SmallVector<SDValue, 8> Ops;
10690 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10691 SDValue LHSOp = LHS.getOperand(i);
10692 SDValue RHSOp = RHS.getOperand(i);
10694 // Can't fold divide by zero.
10695 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10696 N->getOpcode() == ISD::FDIV) {
10697 if ((RHSOp.getOpcode() == ISD::Constant &&
10698 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10699 (RHSOp.getOpcode() == ISD::ConstantFP &&
10700 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10704 EVT VT = LHSOp.getValueType();
10705 EVT RVT = RHSOp.getValueType();
10707 // Integer BUILD_VECTOR operands may have types larger than the element
10708 // size (e.g., when the element type is not legal). Prior to type
10709 // legalization, the types may not match between the two BUILD_VECTORS.
10710 // Truncate one of the operands to make them match.
10711 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10712 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10714 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10718 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10720 if (FoldOp.getOpcode() != ISD::UNDEF &&
10721 FoldOp.getOpcode() != ISD::Constant &&
10722 FoldOp.getOpcode() != ISD::ConstantFP)
10724 Ops.push_back(FoldOp);
10725 AddToWorkList(FoldOp.getNode());
10728 if (Ops.size() == LHS.getNumOperands())
10729 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
10735 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10736 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10737 assert(N->getValueType(0).isVector() &&
10738 "SimplifyVUnaryOp only works on vectors!");
10740 SDValue N0 = N->getOperand(0);
10742 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10745 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10746 SmallVector<SDValue, 8> Ops;
10747 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10748 SDValue Op = N0.getOperand(i);
10749 if (Op.getOpcode() != ISD::UNDEF &&
10750 Op.getOpcode() != ISD::ConstantFP)
10752 EVT EltVT = Op.getValueType();
10753 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10754 if (FoldOp.getOpcode() != ISD::UNDEF &&
10755 FoldOp.getOpcode() != ISD::ConstantFP)
10757 Ops.push_back(FoldOp);
10758 AddToWorkList(FoldOp.getNode());
10761 if (Ops.size() != N0.getNumOperands())
10764 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
10767 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10768 SDValue N1, SDValue N2){
10769 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10771 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10772 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10774 // If we got a simplified select_cc node back from SimplifySelectCC, then
10775 // break it down into a new SETCC node, and a new SELECT node, and then return
10776 // the SELECT node, since we were called with a SELECT node.
10777 if (SCC.getNode()) {
10778 // Check to see if we got a select_cc back (to turn into setcc/select).
10779 // Otherwise, just return whatever node we got back, like fabs.
10780 if (SCC.getOpcode() == ISD::SELECT_CC) {
10781 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10783 SCC.getOperand(0), SCC.getOperand(1),
10784 SCC.getOperand(4));
10785 AddToWorkList(SETCC.getNode());
10786 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10787 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10795 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10796 /// are the two values being selected between, see if we can simplify the
10797 /// select. Callers of this should assume that TheSelect is deleted if this
10798 /// returns true. As such, they should return the appropriate thing (e.g. the
10799 /// node) back to the top-level of the DAG combiner loop to avoid it being
10801 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10804 // Cannot simplify select with vector condition
10805 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10807 // If this is a select from two identical things, try to pull the operation
10808 // through the select.
10809 if (LHS.getOpcode() != RHS.getOpcode() ||
10810 !LHS.hasOneUse() || !RHS.hasOneUse())
10813 // If this is a load and the token chain is identical, replace the select
10814 // of two loads with a load through a select of the address to load from.
10815 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10816 // constants have been dropped into the constant pool.
10817 if (LHS.getOpcode() == ISD::LOAD) {
10818 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10819 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10821 // Token chains must be identical.
10822 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10823 // Do not let this transformation reduce the number of volatile loads.
10824 LLD->isVolatile() || RLD->isVolatile() ||
10825 // If this is an EXTLOAD, the VT's must match.
10826 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10827 // If this is an EXTLOAD, the kind of extension must match.
10828 (LLD->getExtensionType() != RLD->getExtensionType() &&
10829 // The only exception is if one of the extensions is anyext.
10830 LLD->getExtensionType() != ISD::EXTLOAD &&
10831 RLD->getExtensionType() != ISD::EXTLOAD) ||
10832 // FIXME: this discards src value information. This is
10833 // over-conservative. It would be beneficial to be able to remember
10834 // both potential memory locations. Since we are discarding
10835 // src value info, don't do the transformation if the memory
10836 // locations are not in the default address space.
10837 LLD->getPointerInfo().getAddrSpace() != 0 ||
10838 RLD->getPointerInfo().getAddrSpace() != 0 ||
10839 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10840 LLD->getBasePtr().getValueType()))
10843 // Check that the select condition doesn't reach either load. If so,
10844 // folding this will induce a cycle into the DAG. If not, this is safe to
10845 // xform, so create a select of the addresses.
10847 if (TheSelect->getOpcode() == ISD::SELECT) {
10848 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10849 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10850 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10852 // The loads must not depend on one another.
10853 if (LLD->isPredecessorOf(RLD) ||
10854 RLD->isPredecessorOf(LLD))
10856 Addr = DAG.getSelect(SDLoc(TheSelect),
10857 LLD->getBasePtr().getValueType(),
10858 TheSelect->getOperand(0), LLD->getBasePtr(),
10859 RLD->getBasePtr());
10860 } else { // Otherwise SELECT_CC
10861 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10862 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10864 if ((LLD->hasAnyUseOfValue(1) &&
10865 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10866 (RLD->hasAnyUseOfValue(1) &&
10867 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10870 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10871 LLD->getBasePtr().getValueType(),
10872 TheSelect->getOperand(0),
10873 TheSelect->getOperand(1),
10874 LLD->getBasePtr(), RLD->getBasePtr(),
10875 TheSelect->getOperand(4));
10879 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10880 Load = DAG.getLoad(TheSelect->getValueType(0),
10882 // FIXME: Discards pointer and TBAA info.
10883 LLD->getChain(), Addr, MachinePointerInfo(),
10884 LLD->isVolatile(), LLD->isNonTemporal(),
10885 LLD->isInvariant(), LLD->getAlignment());
10887 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10888 RLD->getExtensionType() : LLD->getExtensionType(),
10890 TheSelect->getValueType(0),
10891 // FIXME: Discards pointer and TBAA info.
10892 LLD->getChain(), Addr, MachinePointerInfo(),
10893 LLD->getMemoryVT(), LLD->isVolatile(),
10894 LLD->isNonTemporal(), LLD->getAlignment());
10897 // Users of the select now use the result of the load.
10898 CombineTo(TheSelect, Load);
10900 // Users of the old loads now use the new load's chain. We know the
10901 // old-load value is dead now.
10902 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10903 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10910 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10911 /// where 'cond' is the comparison specified by CC.
10912 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10913 SDValue N2, SDValue N3,
10914 ISD::CondCode CC, bool NotExtCompare) {
10915 // (x ? y : y) -> y.
10916 if (N2 == N3) return N2;
10918 EVT VT = N2.getValueType();
10919 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10920 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10921 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10923 // Determine if the condition we're dealing with is constant
10924 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10925 N0, N1, CC, DL, false);
10926 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10927 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10929 // fold select_cc true, x, y -> x
10930 if (SCCC && !SCCC->isNullValue())
10932 // fold select_cc false, x, y -> y
10933 if (SCCC && SCCC->isNullValue())
10936 // Check to see if we can simplify the select into an fabs node
10937 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10938 // Allow either -0.0 or 0.0
10939 if (CFP->getValueAPF().isZero()) {
10940 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10941 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10942 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10943 N2 == N3.getOperand(0))
10944 return DAG.getNode(ISD::FABS, DL, VT, N0);
10946 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10947 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10948 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10949 N2.getOperand(0) == N3)
10950 return DAG.getNode(ISD::FABS, DL, VT, N3);
10954 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10955 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10956 // in it. This is a win when the constant is not otherwise available because
10957 // it replaces two constant pool loads with one. We only do this if the FP
10958 // type is known to be legal, because if it isn't, then we are before legalize
10959 // types an we want the other legalization to happen first (e.g. to avoid
10960 // messing with soft float) and if the ConstantFP is not legal, because if
10961 // it is legal, we may not need to store the FP constant in a constant pool.
10962 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10963 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10964 if (TLI.isTypeLegal(N2.getValueType()) &&
10965 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10966 TargetLowering::Legal &&
10967 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
10968 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
10969 // If both constants have multiple uses, then we won't need to do an
10970 // extra load, they are likely around in registers for other users.
10971 (TV->hasOneUse() || FV->hasOneUse())) {
10972 Constant *Elts[] = {
10973 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10974 const_cast<ConstantFP*>(TV->getConstantFPValue())
10976 Type *FPTy = Elts[0]->getType();
10977 const DataLayout &TD = *TLI.getDataLayout();
10979 // Create a ConstantArray of the two constants.
10980 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10981 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10982 TD.getPrefTypeAlignment(FPTy));
10983 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10985 // Get the offsets to the 0 and 1 element of the array so that we can
10986 // select between them.
10987 SDValue Zero = DAG.getIntPtrConstant(0);
10988 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10989 SDValue One = DAG.getIntPtrConstant(EltSize);
10991 SDValue Cond = DAG.getSetCC(DL,
10992 getSetCCResultType(N0.getValueType()),
10994 AddToWorkList(Cond.getNode());
10995 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10997 AddToWorkList(CstOffset.getNode());
10998 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11000 AddToWorkList(CPIdx.getNode());
11001 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11002 MachinePointerInfo::getConstantPool(), false,
11003 false, false, Alignment);
11008 // Check to see if we can perform the "gzip trick", transforming
11009 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11010 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11011 (N1C->isNullValue() || // (a < 0) ? b : 0
11012 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11013 EVT XType = N0.getValueType();
11014 EVT AType = N2.getValueType();
11015 if (XType.bitsGE(AType)) {
11016 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11017 // single-bit constant.
11018 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11019 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11020 ShCtV = XType.getSizeInBits()-ShCtV-1;
11021 SDValue ShCt = DAG.getConstant(ShCtV,
11022 getShiftAmountTy(N0.getValueType()));
11023 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11025 AddToWorkList(Shift.getNode());
11027 if (XType.bitsGT(AType)) {
11028 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11029 AddToWorkList(Shift.getNode());
11032 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11035 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11037 DAG.getConstant(XType.getSizeInBits()-1,
11038 getShiftAmountTy(N0.getValueType())));
11039 AddToWorkList(Shift.getNode());
11041 if (XType.bitsGT(AType)) {
11042 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11043 AddToWorkList(Shift.getNode());
11046 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11050 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11051 // where y is has a single bit set.
11052 // A plaintext description would be, we can turn the SELECT_CC into an AND
11053 // when the condition can be materialized as an all-ones register. Any
11054 // single bit-test can be materialized as an all-ones register with
11055 // shift-left and shift-right-arith.
11056 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11057 N0->getValueType(0) == VT &&
11058 N1C && N1C->isNullValue() &&
11059 N2C && N2C->isNullValue()) {
11060 SDValue AndLHS = N0->getOperand(0);
11061 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11062 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11063 // Shift the tested bit over the sign bit.
11064 APInt AndMask = ConstAndRHS->getAPIntValue();
11066 DAG.getConstant(AndMask.countLeadingZeros(),
11067 getShiftAmountTy(AndLHS.getValueType()));
11068 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11070 // Now arithmetic right shift it all the way over, so the result is either
11071 // all-ones, or zero.
11073 DAG.getConstant(AndMask.getBitWidth()-1,
11074 getShiftAmountTy(Shl.getValueType()));
11075 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11077 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11081 // fold select C, 16, 0 -> shl C, 4
11082 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11083 TLI.getBooleanContents(N0.getValueType().isVector()) ==
11084 TargetLowering::ZeroOrOneBooleanContent) {
11086 // If the caller doesn't want us to simplify this into a zext of a compare,
11088 if (NotExtCompare && N2C->getAPIntValue() == 1)
11091 // Get a SetCC of the condition
11092 // NOTE: Don't create a SETCC if it's not legal on this target.
11093 if (!LegalOperations ||
11094 TLI.isOperationLegal(ISD::SETCC,
11095 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11097 // cast from setcc result type to select result type
11099 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11101 if (N2.getValueType().bitsLT(SCC.getValueType()))
11102 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11103 N2.getValueType());
11105 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11106 N2.getValueType(), SCC);
11108 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11109 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11110 N2.getValueType(), SCC);
11113 AddToWorkList(SCC.getNode());
11114 AddToWorkList(Temp.getNode());
11116 if (N2C->getAPIntValue() == 1)
11119 // shl setcc result by log2 n2c
11120 return DAG.getNode(
11121 ISD::SHL, DL, N2.getValueType(), Temp,
11122 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11123 getShiftAmountTy(Temp.getValueType())));
11127 // Check to see if this is the equivalent of setcc
11128 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11129 // otherwise, go ahead with the folds.
11130 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11131 EVT XType = N0.getValueType();
11132 if (!LegalOperations ||
11133 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11134 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11135 if (Res.getValueType() != VT)
11136 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11140 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11141 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11142 (!LegalOperations ||
11143 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11144 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11145 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11146 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11147 getShiftAmountTy(Ctlz.getValueType())));
11149 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11150 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11151 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11152 XType, DAG.getConstant(0, XType), N0);
11153 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11154 return DAG.getNode(ISD::SRL, DL, XType,
11155 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11156 DAG.getConstant(XType.getSizeInBits()-1,
11157 getShiftAmountTy(XType)));
11159 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11160 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11161 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11162 DAG.getConstant(XType.getSizeInBits()-1,
11163 getShiftAmountTy(N0.getValueType())));
11164 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11168 // Check to see if this is an integer abs.
11169 // select_cc setg[te] X, 0, X, -X ->
11170 // select_cc setgt X, -1, X, -X ->
11171 // select_cc setl[te] X, 0, -X, X ->
11172 // select_cc setlt X, 1, -X, X ->
11173 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11175 ConstantSDNode *SubC = nullptr;
11176 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11177 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11178 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11179 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11180 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11181 (N1C->isOne() && CC == ISD::SETLT)) &&
11182 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11183 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11185 EVT XType = N0.getValueType();
11186 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11187 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11189 DAG.getConstant(XType.getSizeInBits()-1,
11190 getShiftAmountTy(N0.getValueType())));
11191 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11193 AddToWorkList(Shift.getNode());
11194 AddToWorkList(Add.getNode());
11195 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11202 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11203 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11204 SDValue N1, ISD::CondCode Cond,
11205 SDLoc DL, bool foldBooleans) {
11206 TargetLowering::DAGCombinerInfo
11207 DagCombineInfo(DAG, Level, false, this);
11208 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11211 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11212 /// return a DAG expression to select that will generate the same value by
11213 /// multiplying by a magic number. See:
11214 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11215 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11216 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11220 // Avoid division by zero.
11221 if (!C->getAPIntValue())
11224 std::vector<SDNode*> Built;
11226 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11228 for (SDNode *N : Built)
11233 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11234 /// return a DAG expression to select that will generate the same value by
11235 /// multiplying by a magic number. See:
11236 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11237 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11238 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11242 // Avoid division by zero.
11243 if (!C->getAPIntValue())
11246 std::vector<SDNode*> Built;
11248 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11250 for (SDNode *N : Built)
11255 /// FindBaseOffset - Return true if base is a frame index, which is known not
11256 // to alias with anything but itself. Provides base object and offset as
11258 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11259 const GlobalValue *&GV, const void *&CV) {
11260 // Assume it is a primitive operation.
11261 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11263 // If it's an adding a simple constant then integrate the offset.
11264 if (Base.getOpcode() == ISD::ADD) {
11265 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11266 Base = Base.getOperand(0);
11267 Offset += C->getZExtValue();
11271 // Return the underlying GlobalValue, and update the Offset. Return false
11272 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11273 // by multiple nodes with different offsets.
11274 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11275 GV = G->getGlobal();
11276 Offset += G->getOffset();
11280 // Return the underlying Constant value, and update the Offset. Return false
11281 // for ConstantSDNodes since the same constant pool entry may be represented
11282 // by multiple nodes with different offsets.
11283 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11284 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11285 : (const void *)C->getConstVal();
11286 Offset += C->getOffset();
11289 // If it's any of the following then it can't alias with anything but itself.
11290 return isa<FrameIndexSDNode>(Base);
11293 /// isAlias - Return true if there is any possibility that the two addresses
11295 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11296 // If they are the same then they must be aliases.
11297 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11299 // If they are both volatile then they cannot be reordered.
11300 if (Op0->isVolatile() && Op1->isVolatile()) return true;
11302 // Gather base node and offset information.
11303 SDValue Base1, Base2;
11304 int64_t Offset1, Offset2;
11305 const GlobalValue *GV1, *GV2;
11306 const void *CV1, *CV2;
11307 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11308 Base1, Offset1, GV1, CV1);
11309 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11310 Base2, Offset2, GV2, CV2);
11312 // If they have a same base address then check to see if they overlap.
11313 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11314 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11315 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11317 // It is possible for different frame indices to alias each other, mostly
11318 // when tail call optimization reuses return address slots for arguments.
11319 // To catch this case, look up the actual index of frame indices to compute
11320 // the real alias relationship.
11321 if (isFrameIndex1 && isFrameIndex2) {
11322 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11323 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11324 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11325 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11326 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11329 // Otherwise, if we know what the bases are, and they aren't identical, then
11330 // we know they cannot alias.
11331 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11334 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11335 // compared to the size and offset of the access, we may be able to prove they
11336 // do not alias. This check is conservative for now to catch cases created by
11337 // splitting vector types.
11338 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11339 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11340 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11341 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11342 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11343 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11344 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11346 // There is no overlap between these relatively aligned accesses of similar
11347 // size, return no alias.
11348 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11349 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11353 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11354 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11356 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11357 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11361 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11362 // Use alias analysis information.
11363 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11364 Op1->getSrcValueOffset());
11365 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11366 Op0->getSrcValueOffset() - MinOffset;
11367 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11368 Op1->getSrcValueOffset() - MinOffset;
11369 AliasAnalysis::AliasResult AAResult =
11370 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11372 UseTBAA ? Op0->getTBAAInfo() : nullptr),
11373 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11375 UseTBAA ? Op1->getTBAAInfo() : nullptr));
11376 if (AAResult == AliasAnalysis::NoAlias)
11380 // Otherwise we have to assume they alias.
11384 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11385 /// looking for aliasing nodes and adding them to the Aliases vector.
11386 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11387 SmallVectorImpl<SDValue> &Aliases) {
11388 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11389 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11391 // Get alias information for node.
11392 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11395 Chains.push_back(OriginalChain);
11396 unsigned Depth = 0;
11398 // Look at each chain and determine if it is an alias. If so, add it to the
11399 // aliases list. If not, then continue up the chain looking for the next
11401 while (!Chains.empty()) {
11402 SDValue Chain = Chains.back();
11405 // For TokenFactor nodes, look at each operand and only continue up the
11406 // chain until we find two aliases. If we've seen two aliases, assume we'll
11407 // find more and revert to original chain since the xform is unlikely to be
11410 // FIXME: The depth check could be made to return the last non-aliasing
11411 // chain we found before we hit a tokenfactor rather than the original
11413 if (Depth > 6 || Aliases.size() == 2) {
11415 Aliases.push_back(OriginalChain);
11419 // Don't bother if we've been before.
11420 if (!Visited.insert(Chain.getNode()))
11423 switch (Chain.getOpcode()) {
11424 case ISD::EntryToken:
11425 // Entry token is ideal chain operand, but handled in FindBetterChain.
11430 // Get alias information for Chain.
11431 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11432 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11434 // If chain is alias then stop here.
11435 if (!(IsLoad && IsOpLoad) &&
11436 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11437 Aliases.push_back(Chain);
11439 // Look further up the chain.
11440 Chains.push_back(Chain.getOperand(0));
11446 case ISD::TokenFactor:
11447 // We have to check each of the operands of the token factor for "small"
11448 // token factors, so we queue them up. Adding the operands to the queue
11449 // (stack) in reverse order maintains the original order and increases the
11450 // likelihood that getNode will find a matching token factor (CSE.)
11451 if (Chain.getNumOperands() > 16) {
11452 Aliases.push_back(Chain);
11455 for (unsigned n = Chain.getNumOperands(); n;)
11456 Chains.push_back(Chain.getOperand(--n));
11461 // For all other instructions we will just have to take what we can get.
11462 Aliases.push_back(Chain);
11467 // We need to be careful here to also search for aliases through the
11468 // value operand of a store, etc. Consider the following situation:
11470 // L1 = load Token1, %52
11471 // S1 = store Token1, L1, %51
11472 // L2 = load Token1, %52+8
11473 // S2 = store Token1, L2, %51+8
11474 // Token2 = Token(S1, S2)
11475 // L3 = load Token2, %53
11476 // S3 = store Token2, L3, %52
11477 // L4 = load Token2, %53+8
11478 // S4 = store Token2, L4, %52+8
11479 // If we search for aliases of S3 (which loads address %52), and we look
11480 // only through the chain, then we'll miss the trivial dependence on L1
11481 // (which also loads from %52). We then might change all loads and
11482 // stores to use Token1 as their chain operand, which could result in
11483 // copying %53 into %52 before copying %52 into %51 (which should
11486 // The problem is, however, that searching for such data dependencies
11487 // can become expensive, and the cost is not directly related to the
11488 // chain depth. Instead, we'll rule out such configurations here by
11489 // insisting that we've visited all chain users (except for users
11490 // of the original chain, which is not necessary). When doing this,
11491 // we need to look through nodes we don't care about (otherwise, things
11492 // like register copies will interfere with trivial cases).
11494 SmallVector<const SDNode *, 16> Worklist;
11495 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11496 IE = Visited.end(); I != IE; ++I)
11497 if (*I != OriginalChain.getNode())
11498 Worklist.push_back(*I);
11500 while (!Worklist.empty()) {
11501 const SDNode *M = Worklist.pop_back_val();
11503 // We have already visited M, and want to make sure we've visited any uses
11504 // of M that we care about. For uses that we've not visisted, and don't
11505 // care about, queue them to the worklist.
11507 for (SDNode::use_iterator UI = M->use_begin(),
11508 UIE = M->use_end(); UI != UIE; ++UI)
11509 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11510 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11511 // We've not visited this use, and we care about it (it could have an
11512 // ordering dependency with the original node).
11514 Aliases.push_back(OriginalChain);
11518 // We've not visited this use, but we don't care about it. Mark it as
11519 // visited and enqueue it to the worklist.
11520 Worklist.push_back(*UI);
11525 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11526 /// for a better chain (aliasing node.)
11527 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11528 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11530 // Accumulate all the aliases to this node.
11531 GatherAllAliases(N, OldChain, Aliases);
11533 // If no operands then chain to entry token.
11534 if (Aliases.size() == 0)
11535 return DAG.getEntryNode();
11537 // If a single operand then chain to it. We don't need to revisit it.
11538 if (Aliases.size() == 1)
11541 // Construct a custom tailored token factor.
11542 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11545 // SelectionDAG::Combine - This is the entry point for the file.
11547 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11548 CodeGenOpt::Level OptLevel) {
11549 /// run - This is the main entry point to this class.
11551 DAGCombiner(*this, AA, OptLevel).Run(Level);