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 #define DEBUG_TYPE "dagcombine"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/PseudoSourceValue.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetFrameInfo.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
42 STATISTIC(NodesCombined , "Number of dag nodes combined");
43 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
44 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
45 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
49 CombinerAA("combiner-alias-analysis", cl::Hidden,
50 cl::desc("Turn on alias analysis during testing"));
53 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
54 cl::desc("Include global information in alias analysis"));
56 //------------------------------ DAGCombiner ---------------------------------//
60 const TargetLowering &TLI;
62 CodeGenOpt::Level OptLevel;
66 // Worklist of all of the nodes that need to be simplified.
67 std::vector<SDNode*> WorkList;
69 // AA - Used for DAG load/store alias analysis.
72 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
76 void AddUsersToWorkList(SDNode *N) {
77 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
82 /// visit - call the node-specific routine that knows how to fold each
83 /// particular type of node.
84 SDValue visit(SDNode *N);
87 /// AddToWorkList - Add to the work list making sure it's instance is at the
88 /// the back (next to be processed.)
89 void AddToWorkList(SDNode *N) {
90 removeFromWorkList(N);
91 WorkList.push_back(N);
94 /// removeFromWorkList - remove all instances of N from the worklist.
96 void removeFromWorkList(SDNode *N) {
97 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
101 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
104 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
105 return CombineTo(N, &Res, 1, AddTo);
108 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
110 SDValue To[] = { Res0, Res1 };
111 return CombineTo(N, To, 2, AddTo);
114 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
118 /// SimplifyDemandedBits - Check the specified integer node value to see if
119 /// it can be simplified or if things it uses can be simplified by bit
120 /// propagation. If so, return true.
121 bool SimplifyDemandedBits(SDValue Op) {
122 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
123 APInt Demanded = APInt::getAllOnesValue(BitWidth);
124 return SimplifyDemandedBits(Op, Demanded);
127 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
129 bool CombineToPreIndexedLoadStore(SDNode *N);
130 bool CombineToPostIndexedLoadStore(SDNode *N);
133 /// combine - call the node-specific routine that knows how to fold each
134 /// particular type of node. If that doesn't do anything, try the
135 /// target-specific DAG combines.
136 SDValue combine(SDNode *N);
138 // Visitation implementation - Implement dag node combining for different
139 // node types. The semantics are as follows:
141 // SDValue.getNode() == 0 - No change was made
142 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
143 // otherwise - N should be replaced by the returned Operand.
145 SDValue visitTokenFactor(SDNode *N);
146 SDValue visitMERGE_VALUES(SDNode *N);
147 SDValue visitADD(SDNode *N);
148 SDValue visitSUB(SDNode *N);
149 SDValue visitADDC(SDNode *N);
150 SDValue visitADDE(SDNode *N);
151 SDValue visitMUL(SDNode *N);
152 SDValue visitSDIV(SDNode *N);
153 SDValue visitUDIV(SDNode *N);
154 SDValue visitSREM(SDNode *N);
155 SDValue visitUREM(SDNode *N);
156 SDValue visitMULHU(SDNode *N);
157 SDValue visitMULHS(SDNode *N);
158 SDValue visitSMUL_LOHI(SDNode *N);
159 SDValue visitUMUL_LOHI(SDNode *N);
160 SDValue visitSDIVREM(SDNode *N);
161 SDValue visitUDIVREM(SDNode *N);
162 SDValue visitAND(SDNode *N);
163 SDValue visitOR(SDNode *N);
164 SDValue visitXOR(SDNode *N);
165 SDValue SimplifyVBinOp(SDNode *N);
166 SDValue visitSHL(SDNode *N);
167 SDValue visitSRA(SDNode *N);
168 SDValue visitSRL(SDNode *N);
169 SDValue visitCTLZ(SDNode *N);
170 SDValue visitCTTZ(SDNode *N);
171 SDValue visitCTPOP(SDNode *N);
172 SDValue visitSELECT(SDNode *N);
173 SDValue visitSELECT_CC(SDNode *N);
174 SDValue visitSETCC(SDNode *N);
175 SDValue visitSIGN_EXTEND(SDNode *N);
176 SDValue visitZERO_EXTEND(SDNode *N);
177 SDValue visitANY_EXTEND(SDNode *N);
178 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
179 SDValue visitTRUNCATE(SDNode *N);
180 SDValue visitBIT_CONVERT(SDNode *N);
181 SDValue visitBUILD_PAIR(SDNode *N);
182 SDValue visitFADD(SDNode *N);
183 SDValue visitFSUB(SDNode *N);
184 SDValue visitFMUL(SDNode *N);
185 SDValue visitFDIV(SDNode *N);
186 SDValue visitFREM(SDNode *N);
187 SDValue visitFCOPYSIGN(SDNode *N);
188 SDValue visitSINT_TO_FP(SDNode *N);
189 SDValue visitUINT_TO_FP(SDNode *N);
190 SDValue visitFP_TO_SINT(SDNode *N);
191 SDValue visitFP_TO_UINT(SDNode *N);
192 SDValue visitFP_ROUND(SDNode *N);
193 SDValue visitFP_ROUND_INREG(SDNode *N);
194 SDValue visitFP_EXTEND(SDNode *N);
195 SDValue visitFNEG(SDNode *N);
196 SDValue visitFABS(SDNode *N);
197 SDValue visitBRCOND(SDNode *N);
198 SDValue visitBR_CC(SDNode *N);
199 SDValue visitLOAD(SDNode *N);
200 SDValue visitSTORE(SDNode *N);
201 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
202 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
203 SDValue visitBUILD_VECTOR(SDNode *N);
204 SDValue visitCONCAT_VECTORS(SDNode *N);
205 SDValue visitVECTOR_SHUFFLE(SDNode *N);
207 SDValue XformToShuffleWithZero(SDNode *N);
208 SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
210 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
212 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
213 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
214 SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
215 SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
216 SDValue N3, ISD::CondCode CC,
217 bool NotExtCompare = false);
218 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
219 DebugLoc DL, bool foldBooleans = true);
220 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
222 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
223 SDValue ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, EVT);
224 SDValue BuildSDIV(SDNode *N);
225 SDValue BuildUDIV(SDNode *N);
226 SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
227 SDValue ReduceLoadWidth(SDNode *N);
228 SDValue ReduceLoadOpStoreWidth(SDNode *N);
230 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
232 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
233 /// looking for aliasing nodes and adding them to the Aliases vector.
234 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
235 SmallVector<SDValue, 8> &Aliases);
237 /// isAlias - Return true if there is any possibility that the two addresses
239 bool isAlias(SDValue Ptr1, int64_t Size1,
240 const Value *SrcValue1, int SrcValueOffset1,
241 unsigned SrcValueAlign1,
242 SDValue Ptr2, int64_t Size2,
243 const Value *SrcValue2, int SrcValueOffset2,
244 unsigned SrcValueAlign2) const;
246 /// FindAliasInfo - Extracts the relevant alias information from the memory
247 /// node. Returns true if the operand was a load.
248 bool FindAliasInfo(SDNode *N,
249 SDValue &Ptr, int64_t &Size,
250 const Value *&SrcValue, int &SrcValueOffset,
251 unsigned &SrcValueAlignment) const;
253 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
254 /// looking for a better chain (aliasing node.)
255 SDValue FindBetterChain(SDNode *N, SDValue Chain);
257 /// getShiftAmountTy - Returns a type large enough to hold any valid
258 /// shift amount - before type legalization these can be huge.
259 EVT getShiftAmountTy() {
260 return LegalTypes ? TLI.getShiftAmountTy() : TLI.getPointerTy();
264 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
266 TLI(D.getTargetLoweringInfo()),
269 LegalOperations(false),
273 /// Run - runs the dag combiner on all nodes in the work list
274 void Run(CombineLevel AtLevel);
280 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
281 /// nodes from the worklist.
282 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
285 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
287 virtual void NodeDeleted(SDNode *N, SDNode *E) {
288 DC.removeFromWorkList(N);
291 virtual void NodeUpdated(SDNode *N) {
297 //===----------------------------------------------------------------------===//
298 // TargetLowering::DAGCombinerInfo implementation
299 //===----------------------------------------------------------------------===//
301 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
302 ((DAGCombiner*)DC)->AddToWorkList(N);
305 SDValue TargetLowering::DAGCombinerInfo::
306 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
307 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
310 SDValue TargetLowering::DAGCombinerInfo::
311 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
312 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
316 SDValue TargetLowering::DAGCombinerInfo::
317 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
318 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
321 void TargetLowering::DAGCombinerInfo::
322 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
323 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
326 //===----------------------------------------------------------------------===//
328 //===----------------------------------------------------------------------===//
330 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
331 /// specified expression for the same cost as the expression itself, or 2 if we
332 /// can compute the negated form more cheaply than the expression itself.
333 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
334 unsigned Depth = 0) {
335 // No compile time optimizations on this type.
336 if (Op.getValueType() == MVT::ppcf128)
339 // fneg is removable even if it has multiple uses.
340 if (Op.getOpcode() == ISD::FNEG) return 2;
342 // Don't allow anything with multiple uses.
343 if (!Op.hasOneUse()) return 0;
345 // Don't recurse exponentially.
346 if (Depth > 6) return 0;
348 switch (Op.getOpcode()) {
349 default: return false;
350 case ISD::ConstantFP:
351 // Don't invert constant FP values after legalize. The negated constant
352 // isn't necessarily legal.
353 return LegalOperations ? 0 : 1;
355 // FIXME: determine better conditions for this xform.
356 if (!UnsafeFPMath) return 0;
358 // fold (fsub (fadd A, B)) -> (fsub (fneg A), B)
359 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
361 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
362 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
364 // We can't turn -(A-B) into B-A when we honor signed zeros.
365 if (!UnsafeFPMath) return 0;
367 // fold (fneg (fsub A, B)) -> (fsub B, A)
372 if (HonorSignDependentRoundingFPMath()) return 0;
374 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
375 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
378 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
383 return isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1);
387 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
388 /// returns the newly negated expression.
389 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
390 bool LegalOperations, unsigned Depth = 0) {
391 // fneg is removable even if it has multiple uses.
392 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
394 // Don't allow anything with multiple uses.
395 assert(Op.hasOneUse() && "Unknown reuse!");
397 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
398 switch (Op.getOpcode()) {
399 default: llvm_unreachable("Unknown code");
400 case ISD::ConstantFP: {
401 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
403 return DAG.getConstantFP(V, Op.getValueType());
406 // FIXME: determine better conditions for this xform.
407 assert(UnsafeFPMath);
409 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
410 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
411 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
412 GetNegatedExpression(Op.getOperand(0), DAG,
413 LegalOperations, Depth+1),
415 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
416 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
417 GetNegatedExpression(Op.getOperand(1), DAG,
418 LegalOperations, Depth+1),
421 // We can't turn -(A-B) into B-A when we honor signed zeros.
422 assert(UnsafeFPMath);
424 // fold (fneg (fsub 0, B)) -> B
425 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
426 if (N0CFP->getValueAPF().isZero())
427 return Op.getOperand(1);
429 // fold (fneg (fsub A, B)) -> (fsub B, A)
430 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
431 Op.getOperand(1), Op.getOperand(0));
435 assert(!HonorSignDependentRoundingFPMath());
437 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
438 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
439 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
440 GetNegatedExpression(Op.getOperand(0), DAG,
441 LegalOperations, Depth+1),
444 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
445 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
447 GetNegatedExpression(Op.getOperand(1), DAG,
448 LegalOperations, Depth+1));
452 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
453 GetNegatedExpression(Op.getOperand(0), DAG,
454 LegalOperations, Depth+1));
456 return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
457 GetNegatedExpression(Op.getOperand(0), DAG,
458 LegalOperations, Depth+1),
464 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
465 // that selects between the values 1 and 0, making it equivalent to a setcc.
466 // Also, set the incoming LHS, RHS, and CC references to the appropriate
467 // nodes based on the type of node we are checking. This simplifies life a
468 // bit for the callers.
469 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
471 if (N.getOpcode() == ISD::SETCC) {
472 LHS = N.getOperand(0);
473 RHS = N.getOperand(1);
474 CC = N.getOperand(2);
477 if (N.getOpcode() == ISD::SELECT_CC &&
478 N.getOperand(2).getOpcode() == ISD::Constant &&
479 N.getOperand(3).getOpcode() == ISD::Constant &&
480 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
481 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
482 LHS = N.getOperand(0);
483 RHS = N.getOperand(1);
484 CC = N.getOperand(4);
490 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
491 // one use. If this is true, it allows the users to invert the operation for
492 // free when it is profitable to do so.
493 static bool isOneUseSetCC(SDValue N) {
495 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
500 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
501 SDValue N0, SDValue N1) {
502 EVT VT = N0.getValueType();
503 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
504 if (isa<ConstantSDNode>(N1)) {
505 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
507 DAG.FoldConstantArithmetic(Opc, VT,
508 cast<ConstantSDNode>(N0.getOperand(1)),
509 cast<ConstantSDNode>(N1));
510 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
511 } else if (N0.hasOneUse()) {
512 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
513 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
514 N0.getOperand(0), N1);
515 AddToWorkList(OpNode.getNode());
516 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
520 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
521 if (isa<ConstantSDNode>(N0)) {
522 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
524 DAG.FoldConstantArithmetic(Opc, VT,
525 cast<ConstantSDNode>(N1.getOperand(1)),
526 cast<ConstantSDNode>(N0));
527 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
528 } else if (N1.hasOneUse()) {
529 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
530 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
531 N1.getOperand(0), N0);
532 AddToWorkList(OpNode.getNode());
533 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
540 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
542 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
544 DEBUG(dbgs() << "\nReplacing.1 ";
546 dbgs() << "\nWith: ";
547 To[0].getNode()->dump(&DAG);
548 dbgs() << " and " << NumTo-1 << " other values\n";
549 for (unsigned i = 0, e = NumTo; i != e; ++i)
550 assert((!To[i].getNode() ||
551 N->getValueType(i) == To[i].getValueType()) &&
552 "Cannot combine value to value of different type!"));
553 WorkListRemover DeadNodes(*this);
554 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
557 // Push the new nodes and any users onto the worklist
558 for (unsigned i = 0, e = NumTo; i != e; ++i) {
559 if (To[i].getNode()) {
560 AddToWorkList(To[i].getNode());
561 AddUsersToWorkList(To[i].getNode());
566 // Finally, if the node is now dead, remove it from the graph. The node
567 // may not be dead if the replacement process recursively simplified to
568 // something else needing this node.
569 if (N->use_empty()) {
570 // Nodes can be reintroduced into the worklist. Make sure we do not
571 // process a node that has been replaced.
572 removeFromWorkList(N);
574 // Finally, since the node is now dead, remove it from the graph.
577 return SDValue(N, 0);
581 DAGCombiner::CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &
583 // Replace all uses. If any nodes become isomorphic to other nodes and
584 // are deleted, make sure to remove them from our worklist.
585 WorkListRemover DeadNodes(*this);
586 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
588 // Push the new node and any (possibly new) users onto the worklist.
589 AddToWorkList(TLO.New.getNode());
590 AddUsersToWorkList(TLO.New.getNode());
592 // Finally, if the node is now dead, remove it from the graph. The node
593 // may not be dead if the replacement process recursively simplified to
594 // something else needing this node.
595 if (TLO.Old.getNode()->use_empty()) {
596 removeFromWorkList(TLO.Old.getNode());
598 // If the operands of this node are only used by the node, they will now
599 // be dead. Make sure to visit them first to delete dead nodes early.
600 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
601 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
602 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
604 DAG.DeleteNode(TLO.Old.getNode());
608 /// SimplifyDemandedBits - Check the specified integer node value to see if
609 /// it can be simplified or if things it uses can be simplified by bit
610 /// propagation. If so, return true.
611 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
612 TargetLowering::TargetLoweringOpt TLO(DAG);
613 APInt KnownZero, KnownOne;
614 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
618 AddToWorkList(Op.getNode());
620 // Replace the old value with the new one.
622 DEBUG(dbgs() << "\nReplacing.2 ";
623 TLO.Old.getNode()->dump(&DAG);
624 dbgs() << "\nWith: ";
625 TLO.New.getNode()->dump(&DAG);
628 CommitTargetLoweringOpt(TLO);
632 //===----------------------------------------------------------------------===//
633 // Main DAG Combiner implementation
634 //===----------------------------------------------------------------------===//
636 void DAGCombiner::Run(CombineLevel AtLevel) {
637 // set the instance variables, so that the various visit routines may use it.
639 LegalOperations = Level >= NoIllegalOperations;
640 LegalTypes = Level >= NoIllegalTypes;
642 // Add all the dag nodes to the worklist.
643 WorkList.reserve(DAG.allnodes_size());
644 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
645 E = DAG.allnodes_end(); I != E; ++I)
646 WorkList.push_back(I);
648 // Create a dummy node (which is not added to allnodes), that adds a reference
649 // to the root node, preventing it from being deleted, and tracking any
650 // changes of the root.
651 HandleSDNode Dummy(DAG.getRoot());
653 // The root of the dag may dangle to deleted nodes until the dag combiner is
654 // done. Set it to null to avoid confusion.
655 DAG.setRoot(SDValue());
657 // while the worklist isn't empty, inspect the node on the end of it and
658 // try and combine it.
659 while (!WorkList.empty()) {
660 SDNode *N = WorkList.back();
663 // If N has no uses, it is dead. Make sure to revisit all N's operands once
664 // N is deleted from the DAG, since they too may now be dead or may have a
665 // reduced number of uses, allowing other xforms.
666 if (N->use_empty() && N != &Dummy) {
667 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
668 AddToWorkList(N->getOperand(i).getNode());
674 SDValue RV = combine(N);
676 if (RV.getNode() == 0)
681 // If we get back the same node we passed in, rather than a new node or
682 // zero, we know that the node must have defined multiple values and
683 // CombineTo was used. Since CombineTo takes care of the worklist
684 // mechanics for us, we have no work to do in this case.
685 if (RV.getNode() == N)
688 assert(N->getOpcode() != ISD::DELETED_NODE &&
689 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
690 "Node was deleted but visit returned new node!");
692 DEBUG(dbgs() << "\nReplacing.3 ";
694 dbgs() << "\nWith: ";
695 RV.getNode()->dump(&DAG);
697 WorkListRemover DeadNodes(*this);
698 if (N->getNumValues() == RV.getNode()->getNumValues())
699 DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes);
701 assert(N->getValueType(0) == RV.getValueType() &&
702 N->getNumValues() == 1 && "Type mismatch");
704 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
707 // Push the new node and any users onto the worklist
708 AddToWorkList(RV.getNode());
709 AddUsersToWorkList(RV.getNode());
711 // Add any uses of the old node to the worklist in case this node is the
712 // last one that uses them. They may become dead after this node is
714 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
715 AddToWorkList(N->getOperand(i).getNode());
717 // Finally, if the node is now dead, remove it from the graph. The node
718 // may not be dead if the replacement process recursively simplified to
719 // something else needing this node.
720 if (N->use_empty()) {
721 // Nodes can be reintroduced into the worklist. Make sure we do not
722 // process a node that has been replaced.
723 removeFromWorkList(N);
725 // Finally, since the node is now dead, remove it from the graph.
730 // If the root changed (e.g. it was a dead load, update the root).
731 DAG.setRoot(Dummy.getValue());
734 SDValue DAGCombiner::visit(SDNode *N) {
735 switch(N->getOpcode()) {
737 case ISD::TokenFactor: return visitTokenFactor(N);
738 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
739 case ISD::ADD: return visitADD(N);
740 case ISD::SUB: return visitSUB(N);
741 case ISD::ADDC: return visitADDC(N);
742 case ISD::ADDE: return visitADDE(N);
743 case ISD::MUL: return visitMUL(N);
744 case ISD::SDIV: return visitSDIV(N);
745 case ISD::UDIV: return visitUDIV(N);
746 case ISD::SREM: return visitSREM(N);
747 case ISD::UREM: return visitUREM(N);
748 case ISD::MULHU: return visitMULHU(N);
749 case ISD::MULHS: return visitMULHS(N);
750 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
751 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
752 case ISD::SDIVREM: return visitSDIVREM(N);
753 case ISD::UDIVREM: return visitUDIVREM(N);
754 case ISD::AND: return visitAND(N);
755 case ISD::OR: return visitOR(N);
756 case ISD::XOR: return visitXOR(N);
757 case ISD::SHL: return visitSHL(N);
758 case ISD::SRA: return visitSRA(N);
759 case ISD::SRL: return visitSRL(N);
760 case ISD::CTLZ: return visitCTLZ(N);
761 case ISD::CTTZ: return visitCTTZ(N);
762 case ISD::CTPOP: return visitCTPOP(N);
763 case ISD::SELECT: return visitSELECT(N);
764 case ISD::SELECT_CC: return visitSELECT_CC(N);
765 case ISD::SETCC: return visitSETCC(N);
766 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
767 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
768 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
769 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
770 case ISD::TRUNCATE: return visitTRUNCATE(N);
771 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
772 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
773 case ISD::FADD: return visitFADD(N);
774 case ISD::FSUB: return visitFSUB(N);
775 case ISD::FMUL: return visitFMUL(N);
776 case ISD::FDIV: return visitFDIV(N);
777 case ISD::FREM: return visitFREM(N);
778 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
779 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
780 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
781 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
782 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
783 case ISD::FP_ROUND: return visitFP_ROUND(N);
784 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
785 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
786 case ISD::FNEG: return visitFNEG(N);
787 case ISD::FABS: return visitFABS(N);
788 case ISD::BRCOND: return visitBRCOND(N);
789 case ISD::BR_CC: return visitBR_CC(N);
790 case ISD::LOAD: return visitLOAD(N);
791 case ISD::STORE: return visitSTORE(N);
792 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
793 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
794 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
795 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
796 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
801 SDValue DAGCombiner::combine(SDNode *N) {
802 SDValue RV = visit(N);
804 // If nothing happened, try a target-specific DAG combine.
805 if (RV.getNode() == 0) {
806 assert(N->getOpcode() != ISD::DELETED_NODE &&
807 "Node was deleted but visit returned NULL!");
809 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
810 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
812 // Expose the DAG combiner to the target combiner impls.
813 TargetLowering::DAGCombinerInfo
814 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
816 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
820 // If N is a commutative binary node, try commuting it to enable more
822 if (RV.getNode() == 0 &&
823 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
824 N->getNumValues() == 1) {
825 SDValue N0 = N->getOperand(0);
826 SDValue N1 = N->getOperand(1);
828 // Constant operands are canonicalized to RHS.
829 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
830 SDValue Ops[] = { N1, N0 };
831 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
834 return SDValue(CSENode, 0);
841 /// getInputChainForNode - Given a node, return its input chain if it has one,
842 /// otherwise return a null sd operand.
843 static SDValue getInputChainForNode(SDNode *N) {
844 if (unsigned NumOps = N->getNumOperands()) {
845 if (N->getOperand(0).getValueType() == MVT::Other)
846 return N->getOperand(0);
847 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
848 return N->getOperand(NumOps-1);
849 for (unsigned i = 1; i < NumOps-1; ++i)
850 if (N->getOperand(i).getValueType() == MVT::Other)
851 return N->getOperand(i);
856 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
857 // If N has two operands, where one has an input chain equal to the other,
858 // the 'other' chain is redundant.
859 if (N->getNumOperands() == 2) {
860 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
861 return N->getOperand(0);
862 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
863 return N->getOperand(1);
866 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
867 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
868 SmallPtrSet<SDNode*, 16> SeenOps;
869 bool Changed = false; // If we should replace this token factor.
871 // Start out with this token factor.
874 // Iterate through token factors. The TFs grows when new token factors are
876 for (unsigned i = 0; i < TFs.size(); ++i) {
879 // Check each of the operands.
880 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
881 SDValue Op = TF->getOperand(i);
883 switch (Op.getOpcode()) {
884 case ISD::EntryToken:
885 // Entry tokens don't need to be added to the list. They are
890 case ISD::TokenFactor:
891 if (Op.hasOneUse() &&
892 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
893 // Queue up for processing.
894 TFs.push_back(Op.getNode());
895 // Clean up in case the token factor is removed.
896 AddToWorkList(Op.getNode());
903 // Only add if it isn't already in the list.
904 if (SeenOps.insert(Op.getNode()))
915 // If we've change things around then replace token factor.
918 // The entry token is the only possible outcome.
919 Result = DAG.getEntryNode();
921 // New and improved token factor.
922 Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
923 MVT::Other, &Ops[0], Ops.size());
926 // Don't add users to work list.
927 return CombineTo(N, Result, false);
933 /// MERGE_VALUES can always be eliminated.
934 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
935 WorkListRemover DeadNodes(*this);
936 // Replacing results may cause a different MERGE_VALUES to suddenly
937 // be CSE'd with N, and carry its uses with it. Iterate until no
938 // uses remain, to ensure that the node can be safely deleted.
940 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
941 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i),
943 } while (!N->use_empty());
944 removeFromWorkList(N);
946 return SDValue(N, 0); // Return N so it doesn't get rechecked!
950 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
952 EVT VT = N0.getValueType();
953 SDValue N00 = N0.getOperand(0);
954 SDValue N01 = N0.getOperand(1);
955 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
957 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
958 isa<ConstantSDNode>(N00.getOperand(1))) {
959 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
960 N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
961 DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
962 N00.getOperand(0), N01),
963 DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
964 N00.getOperand(1), N01));
965 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
971 SDValue DAGCombiner::visitADD(SDNode *N) {
972 SDValue N0 = N->getOperand(0);
973 SDValue N1 = N->getOperand(1);
974 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
975 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
976 EVT VT = N0.getValueType();
980 SDValue FoldedVOp = SimplifyVBinOp(N);
981 if (FoldedVOp.getNode()) return FoldedVOp;
984 // fold (add x, undef) -> undef
985 if (N0.getOpcode() == ISD::UNDEF)
987 if (N1.getOpcode() == ISD::UNDEF)
989 // fold (add c1, c2) -> c1+c2
991 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
992 // canonicalize constant to RHS
994 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
995 // fold (add x, 0) -> x
996 if (N1C && N1C->isNullValue())
998 // fold (add Sym, c) -> Sym+c
999 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1000 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1001 GA->getOpcode() == ISD::GlobalAddress)
1002 return DAG.getGlobalAddress(GA->getGlobal(), VT,
1004 (uint64_t)N1C->getSExtValue());
1005 // fold ((c1-A)+c2) -> (c1+c2)-A
1006 if (N1C && N0.getOpcode() == ISD::SUB)
1007 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1008 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1009 DAG.getConstant(N1C->getAPIntValue()+
1010 N0C->getAPIntValue(), VT),
1013 SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1014 if (RADD.getNode() != 0)
1016 // fold ((0-A) + B) -> B-A
1017 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1018 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1019 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1020 // fold (A + (0-B)) -> A-B
1021 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1022 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1023 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1024 // fold (A+(B-A)) -> B
1025 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1026 return N1.getOperand(0);
1027 // fold ((B-A)+A) -> B
1028 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1029 return N0.getOperand(0);
1030 // fold (A+(B-(A+C))) to (B-C)
1031 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1032 N0 == N1.getOperand(1).getOperand(0))
1033 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1034 N1.getOperand(1).getOperand(1));
1035 // fold (A+(B-(C+A))) to (B-C)
1036 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1037 N0 == N1.getOperand(1).getOperand(1))
1038 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1039 N1.getOperand(1).getOperand(0));
1040 // fold (A+((B-A)+or-C)) to (B+or-C)
1041 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1042 N1.getOperand(0).getOpcode() == ISD::SUB &&
1043 N0 == N1.getOperand(0).getOperand(1))
1044 return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1045 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1047 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1048 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1049 SDValue N00 = N0.getOperand(0);
1050 SDValue N01 = N0.getOperand(1);
1051 SDValue N10 = N1.getOperand(0);
1052 SDValue N11 = N1.getOperand(1);
1054 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1055 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1056 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1057 DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1060 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1061 return SDValue(N, 0);
1063 // fold (a+b) -> (a|b) iff a and b share no bits.
1064 if (VT.isInteger() && !VT.isVector()) {
1065 APInt LHSZero, LHSOne;
1066 APInt RHSZero, RHSOne;
1067 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1068 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1070 if (LHSZero.getBoolValue()) {
1071 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1073 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1074 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1075 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1076 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1077 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1081 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1082 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1083 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1084 if (Result.getNode()) return Result;
1086 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1087 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1088 if (Result.getNode()) return Result;
1091 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1092 if (N1.getOpcode() == ISD::SHL &&
1093 N1.getOperand(0).getOpcode() == ISD::SUB)
1094 if (ConstantSDNode *C =
1095 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1096 if (C->getAPIntValue() == 0)
1097 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
1098 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1099 N1.getOperand(0).getOperand(1),
1101 if (N0.getOpcode() == ISD::SHL &&
1102 N0.getOperand(0).getOpcode() == ISD::SUB)
1103 if (ConstantSDNode *C =
1104 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1105 if (C->getAPIntValue() == 0)
1106 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
1107 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1108 N0.getOperand(0).getOperand(1),
1114 SDValue DAGCombiner::visitADDC(SDNode *N) {
1115 SDValue N0 = N->getOperand(0);
1116 SDValue N1 = N->getOperand(1);
1117 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1118 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1119 EVT VT = N0.getValueType();
1121 // If the flag result is dead, turn this into an ADD.
1122 if (N->hasNUsesOfValue(0, 1))
1123 return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0),
1124 DAG.getNode(ISD::CARRY_FALSE,
1125 N->getDebugLoc(), MVT::Flag));
1127 // canonicalize constant to RHS.
1129 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1131 // fold (addc x, 0) -> x + no carry out
1132 if (N1C && N1C->isNullValue())
1133 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1134 N->getDebugLoc(), MVT::Flag));
1136 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1137 APInt LHSZero, LHSOne;
1138 APInt RHSZero, RHSOne;
1139 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1140 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1142 if (LHSZero.getBoolValue()) {
1143 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1145 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1146 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1147 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1148 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1149 return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1150 DAG.getNode(ISD::CARRY_FALSE,
1151 N->getDebugLoc(), MVT::Flag));
1157 SDValue DAGCombiner::visitADDE(SDNode *N) {
1158 SDValue N0 = N->getOperand(0);
1159 SDValue N1 = N->getOperand(1);
1160 SDValue CarryIn = N->getOperand(2);
1161 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1162 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1164 // canonicalize constant to RHS
1166 return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1169 // fold (adde x, y, false) -> (addc x, y)
1170 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1171 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1176 SDValue DAGCombiner::visitSUB(SDNode *N) {
1177 SDValue N0 = N->getOperand(0);
1178 SDValue N1 = N->getOperand(1);
1179 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1180 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1181 EVT VT = N0.getValueType();
1184 if (VT.isVector()) {
1185 SDValue FoldedVOp = SimplifyVBinOp(N);
1186 if (FoldedVOp.getNode()) return FoldedVOp;
1189 // fold (sub x, x) -> 0
1191 return DAG.getConstant(0, N->getValueType(0));
1192 // fold (sub c1, c2) -> c1-c2
1194 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1195 // fold (sub x, c) -> (add x, -c)
1197 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1198 DAG.getConstant(-N1C->getAPIntValue(), VT));
1199 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1200 if (N0C && N0C->isAllOnesValue())
1201 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
1202 // fold (A+B)-A -> B
1203 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1204 return N0.getOperand(1);
1205 // fold (A+B)-B -> A
1206 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1207 return N0.getOperand(0);
1208 // fold ((A+(B+or-C))-B) -> A+or-C
1209 if (N0.getOpcode() == ISD::ADD &&
1210 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1211 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1212 N0.getOperand(1).getOperand(0) == N1)
1213 return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1214 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1215 // fold ((A+(C+B))-B) -> A+C
1216 if (N0.getOpcode() == ISD::ADD &&
1217 N0.getOperand(1).getOpcode() == ISD::ADD &&
1218 N0.getOperand(1).getOperand(1) == N1)
1219 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1220 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1221 // fold ((A-(B-C))-C) -> A-B
1222 if (N0.getOpcode() == ISD::SUB &&
1223 N0.getOperand(1).getOpcode() == ISD::SUB &&
1224 N0.getOperand(1).getOperand(1) == N1)
1225 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1226 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1228 // If either operand of a sub is undef, the result is undef
1229 if (N0.getOpcode() == ISD::UNDEF)
1231 if (N1.getOpcode() == ISD::UNDEF)
1234 // If the relocation model supports it, consider symbol offsets.
1235 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1236 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1237 // fold (sub Sym, c) -> Sym-c
1238 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1239 return DAG.getGlobalAddress(GA->getGlobal(), VT,
1241 (uint64_t)N1C->getSExtValue());
1242 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1243 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1244 if (GA->getGlobal() == GB->getGlobal())
1245 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1252 SDValue DAGCombiner::visitMUL(SDNode *N) {
1253 SDValue N0 = N->getOperand(0);
1254 SDValue N1 = N->getOperand(1);
1255 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1256 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1257 EVT VT = N0.getValueType();
1260 if (VT.isVector()) {
1261 SDValue FoldedVOp = SimplifyVBinOp(N);
1262 if (FoldedVOp.getNode()) return FoldedVOp;
1265 // fold (mul x, undef) -> 0
1266 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1267 return DAG.getConstant(0, VT);
1268 // fold (mul c1, c2) -> c1*c2
1270 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1271 // canonicalize constant to RHS
1273 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1274 // fold (mul x, 0) -> 0
1275 if (N1C && N1C->isNullValue())
1277 // fold (mul x, -1) -> 0-x
1278 if (N1C && N1C->isAllOnesValue())
1279 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1280 DAG.getConstant(0, VT), N0);
1281 // fold (mul x, (1 << c)) -> x << c
1282 if (N1C && N1C->getAPIntValue().isPowerOf2())
1283 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1284 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1285 getShiftAmountTy()));
1286 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1287 if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1288 unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1289 // FIXME: If the input is something that is easily negated (e.g. a
1290 // single-use add), we should put the negate there.
1291 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1292 DAG.getConstant(0, VT),
1293 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1294 DAG.getConstant(Log2Val, getShiftAmountTy())));
1296 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1297 if (N1C && N0.getOpcode() == ISD::SHL &&
1298 isa<ConstantSDNode>(N0.getOperand(1))) {
1299 SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1300 N1, N0.getOperand(1));
1301 AddToWorkList(C3.getNode());
1302 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1303 N0.getOperand(0), C3);
1306 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1309 SDValue Sh(0,0), Y(0,0);
1310 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1311 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1312 N0.getNode()->hasOneUse()) {
1314 } else if (N1.getOpcode() == ISD::SHL &&
1315 isa<ConstantSDNode>(N1.getOperand(1)) &&
1316 N1.getNode()->hasOneUse()) {
1321 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1322 Sh.getOperand(0), Y);
1323 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1324 Mul, Sh.getOperand(1));
1328 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1329 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1330 isa<ConstantSDNode>(N0.getOperand(1)))
1331 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1332 DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1333 N0.getOperand(0), N1),
1334 DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1335 N0.getOperand(1), N1));
1338 SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1339 if (RMUL.getNode() != 0)
1345 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1346 SDValue N0 = N->getOperand(0);
1347 SDValue N1 = N->getOperand(1);
1348 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1349 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1350 EVT VT = N->getValueType(0);
1353 if (VT.isVector()) {
1354 SDValue FoldedVOp = SimplifyVBinOp(N);
1355 if (FoldedVOp.getNode()) return FoldedVOp;
1358 // fold (sdiv c1, c2) -> c1/c2
1359 if (N0C && N1C && !N1C->isNullValue())
1360 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1361 // fold (sdiv X, 1) -> X
1362 if (N1C && N1C->getSExtValue() == 1LL)
1364 // fold (sdiv X, -1) -> 0-X
1365 if (N1C && N1C->isAllOnesValue())
1366 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1367 DAG.getConstant(0, VT), N0);
1368 // If we know the sign bits of both operands are zero, strength reduce to a
1369 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1370 if (!VT.isVector()) {
1371 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1372 return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1375 // fold (sdiv X, pow2) -> simple ops after legalize
1376 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1377 (isPowerOf2_64(N1C->getSExtValue()) ||
1378 isPowerOf2_64(-N1C->getSExtValue()))) {
1379 // If dividing by powers of two is cheap, then don't perform the following
1381 if (TLI.isPow2DivCheap())
1384 int64_t pow2 = N1C->getSExtValue();
1385 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1386 unsigned lg2 = Log2_64(abs2);
1388 // Splat the sign bit into the register
1389 SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1390 DAG.getConstant(VT.getSizeInBits()-1,
1391 getShiftAmountTy()));
1392 AddToWorkList(SGN.getNode());
1394 // Add (N0 < 0) ? abs2 - 1 : 0;
1395 SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1396 DAG.getConstant(VT.getSizeInBits() - lg2,
1397 getShiftAmountTy()));
1398 SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1399 AddToWorkList(SRL.getNode());
1400 AddToWorkList(ADD.getNode()); // Divide by pow2
1401 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1402 DAG.getConstant(lg2, getShiftAmountTy()));
1404 // If we're dividing by a positive value, we're done. Otherwise, we must
1405 // negate the result.
1409 AddToWorkList(SRA.getNode());
1410 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1411 DAG.getConstant(0, VT), SRA);
1414 // if integer divide is expensive and we satisfy the requirements, emit an
1415 // alternate sequence.
1416 if (N1C && (N1C->getSExtValue() < -1 || N1C->getSExtValue() > 1) &&
1417 !TLI.isIntDivCheap()) {
1418 SDValue Op = BuildSDIV(N);
1419 if (Op.getNode()) return Op;
1423 if (N0.getOpcode() == ISD::UNDEF)
1424 return DAG.getConstant(0, VT);
1425 // X / undef -> undef
1426 if (N1.getOpcode() == ISD::UNDEF)
1432 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1433 SDValue N0 = N->getOperand(0);
1434 SDValue N1 = N->getOperand(1);
1435 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1436 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1437 EVT VT = N->getValueType(0);
1440 if (VT.isVector()) {
1441 SDValue FoldedVOp = SimplifyVBinOp(N);
1442 if (FoldedVOp.getNode()) return FoldedVOp;
1445 // fold (udiv c1, c2) -> c1/c2
1446 if (N0C && N1C && !N1C->isNullValue())
1447 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1448 // fold (udiv x, (1 << c)) -> x >>u c
1449 if (N1C && N1C->getAPIntValue().isPowerOf2())
1450 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1451 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1452 getShiftAmountTy()));
1453 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1454 if (N1.getOpcode() == ISD::SHL) {
1455 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1456 if (SHC->getAPIntValue().isPowerOf2()) {
1457 EVT ADDVT = N1.getOperand(1).getValueType();
1458 SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1460 DAG.getConstant(SHC->getAPIntValue()
1463 AddToWorkList(Add.getNode());
1464 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1468 // fold (udiv x, c) -> alternate
1469 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1470 SDValue Op = BuildUDIV(N);
1471 if (Op.getNode()) return Op;
1475 if (N0.getOpcode() == ISD::UNDEF)
1476 return DAG.getConstant(0, VT);
1477 // X / undef -> undef
1478 if (N1.getOpcode() == ISD::UNDEF)
1484 SDValue DAGCombiner::visitSREM(SDNode *N) {
1485 SDValue N0 = N->getOperand(0);
1486 SDValue N1 = N->getOperand(1);
1487 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1488 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1489 EVT VT = N->getValueType(0);
1491 // fold (srem c1, c2) -> c1%c2
1492 if (N0C && N1C && !N1C->isNullValue())
1493 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1494 // If we know the sign bits of both operands are zero, strength reduce to a
1495 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1496 if (!VT.isVector()) {
1497 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1498 return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
1501 // If X/C can be simplified by the division-by-constant logic, lower
1502 // X%C to the equivalent of X-X/C*C.
1503 if (N1C && !N1C->isNullValue()) {
1504 SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
1505 AddToWorkList(Div.getNode());
1506 SDValue OptimizedDiv = combine(Div.getNode());
1507 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1508 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1510 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1511 AddToWorkList(Mul.getNode());
1517 if (N0.getOpcode() == ISD::UNDEF)
1518 return DAG.getConstant(0, VT);
1519 // X % undef -> undef
1520 if (N1.getOpcode() == ISD::UNDEF)
1526 SDValue DAGCombiner::visitUREM(SDNode *N) {
1527 SDValue N0 = N->getOperand(0);
1528 SDValue N1 = N->getOperand(1);
1529 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1530 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1531 EVT VT = N->getValueType(0);
1533 // fold (urem c1, c2) -> c1%c2
1534 if (N0C && N1C && !N1C->isNullValue())
1535 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
1536 // fold (urem x, pow2) -> (and x, pow2-1)
1537 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1538 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
1539 DAG.getConstant(N1C->getAPIntValue()-1,VT));
1540 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1541 if (N1.getOpcode() == ISD::SHL) {
1542 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1543 if (SHC->getAPIntValue().isPowerOf2()) {
1545 DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
1546 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1548 AddToWorkList(Add.getNode());
1549 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
1554 // If X/C can be simplified by the division-by-constant logic, lower
1555 // X%C to the equivalent of X-X/C*C.
1556 if (N1C && !N1C->isNullValue()) {
1557 SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
1558 AddToWorkList(Div.getNode());
1559 SDValue OptimizedDiv = combine(Div.getNode());
1560 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1561 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1563 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1564 AddToWorkList(Mul.getNode());
1570 if (N0.getOpcode() == ISD::UNDEF)
1571 return DAG.getConstant(0, VT);
1572 // X % undef -> undef
1573 if (N1.getOpcode() == ISD::UNDEF)
1579 SDValue DAGCombiner::visitMULHS(SDNode *N) {
1580 SDValue N0 = N->getOperand(0);
1581 SDValue N1 = N->getOperand(1);
1582 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1583 EVT VT = N->getValueType(0);
1585 // fold (mulhs x, 0) -> 0
1586 if (N1C && N1C->isNullValue())
1588 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1589 if (N1C && N1C->getAPIntValue() == 1)
1590 return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
1591 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
1592 getShiftAmountTy()));
1593 // fold (mulhs x, undef) -> 0
1594 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1595 return DAG.getConstant(0, VT);
1600 SDValue DAGCombiner::visitMULHU(SDNode *N) {
1601 SDValue N0 = N->getOperand(0);
1602 SDValue N1 = N->getOperand(1);
1603 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1604 EVT VT = N->getValueType(0);
1606 // fold (mulhu x, 0) -> 0
1607 if (N1C && N1C->isNullValue())
1609 // fold (mulhu x, 1) -> 0
1610 if (N1C && N1C->getAPIntValue() == 1)
1611 return DAG.getConstant(0, N0.getValueType());
1612 // fold (mulhu x, undef) -> 0
1613 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1614 return DAG.getConstant(0, VT);
1619 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1620 /// compute two values. LoOp and HiOp give the opcodes for the two computations
1621 /// that are being performed. Return true if a simplification was made.
1623 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1625 // If the high half is not needed, just compute the low half.
1626 bool HiExists = N->hasAnyUseOfValue(1);
1628 (!LegalOperations ||
1629 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
1630 SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
1631 N->op_begin(), N->getNumOperands());
1632 return CombineTo(N, Res, Res);
1635 // If the low half is not needed, just compute the high half.
1636 bool LoExists = N->hasAnyUseOfValue(0);
1638 (!LegalOperations ||
1639 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
1640 SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
1641 N->op_begin(), N->getNumOperands());
1642 return CombineTo(N, Res, Res);
1645 // If both halves are used, return as it is.
1646 if (LoExists && HiExists)
1649 // If the two computed results can be simplified separately, separate them.
1651 SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
1652 N->op_begin(), N->getNumOperands());
1653 AddToWorkList(Lo.getNode());
1654 SDValue LoOpt = combine(Lo.getNode());
1655 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
1656 (!LegalOperations ||
1657 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
1658 return CombineTo(N, LoOpt, LoOpt);
1662 SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
1663 N->op_begin(), N->getNumOperands());
1664 AddToWorkList(Hi.getNode());
1665 SDValue HiOpt = combine(Hi.getNode());
1666 if (HiOpt.getNode() && HiOpt != Hi &&
1667 (!LegalOperations ||
1668 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
1669 return CombineTo(N, HiOpt, HiOpt);
1675 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
1676 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
1677 if (Res.getNode()) return Res;
1682 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
1683 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
1684 if (Res.getNode()) return Res;
1689 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
1690 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
1691 if (Res.getNode()) return Res;
1696 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
1697 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
1698 if (Res.getNode()) return Res;
1703 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1704 /// two operands of the same opcode, try to simplify it.
1705 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1706 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
1707 EVT VT = N0.getValueType();
1708 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1710 // Bail early if none of these transforms apply.
1711 if (N0.getNode()->getNumOperands() == 0) return SDValue();
1713 // For each of OP in AND/OR/XOR:
1714 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1715 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1716 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1717 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1719 // do not sink logical op inside of a vector extend, since it may combine
1721 EVT Op0VT = N0.getOperand(0).getValueType();
1722 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
1723 N0.getOpcode() == ISD::ANY_EXTEND ||
1724 N0.getOpcode() == ISD::SIGN_EXTEND ||
1725 (N0.getOpcode() == ISD::TRUNCATE && TLI.isTypeLegal(Op0VT))) &&
1727 Op0VT == N1.getOperand(0).getValueType() &&
1728 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
1729 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
1730 N0.getOperand(0).getValueType(),
1731 N0.getOperand(0), N1.getOperand(0));
1732 AddToWorkList(ORNode.getNode());
1733 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
1736 // For each of OP in SHL/SRL/SRA/AND...
1737 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1738 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1739 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1740 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1741 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1742 N0.getOperand(1) == N1.getOperand(1)) {
1743 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
1744 N0.getOperand(0).getValueType(),
1745 N0.getOperand(0), N1.getOperand(0));
1746 AddToWorkList(ORNode.getNode());
1747 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
1748 ORNode, N0.getOperand(1));
1754 SDValue DAGCombiner::visitAND(SDNode *N) {
1755 SDValue N0 = N->getOperand(0);
1756 SDValue N1 = N->getOperand(1);
1757 SDValue LL, LR, RL, RR, CC0, CC1;
1758 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1759 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1760 EVT VT = N1.getValueType();
1761 unsigned BitWidth = VT.getSizeInBits();
1764 if (VT.isVector()) {
1765 SDValue FoldedVOp = SimplifyVBinOp(N);
1766 if (FoldedVOp.getNode()) return FoldedVOp;
1769 // fold (and x, undef) -> 0
1770 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1771 return DAG.getConstant(0, VT);
1772 // fold (and c1, c2) -> c1&c2
1774 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
1775 // canonicalize constant to RHS
1777 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
1778 // fold (and x, -1) -> x
1779 if (N1C && N1C->isAllOnesValue())
1781 // if (and x, c) is known to be zero, return 0
1782 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
1783 APInt::getAllOnesValue(BitWidth)))
1784 return DAG.getConstant(0, VT);
1786 SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
1787 if (RAND.getNode() != 0)
1789 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1790 if (N1C && N0.getOpcode() == ISD::OR)
1791 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1792 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
1794 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1795 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1796 SDValue N0Op0 = N0.getOperand(0);
1797 APInt Mask = ~N1C->getAPIntValue();
1798 Mask.trunc(N0Op0.getValueSizeInBits());
1799 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
1800 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
1801 N0.getValueType(), N0Op0);
1803 // Replace uses of the AND with uses of the Zero extend node.
1806 // We actually want to replace all uses of the any_extend with the
1807 // zero_extend, to avoid duplicating things. This will later cause this
1808 // AND to be folded.
1809 CombineTo(N0.getNode(), Zext);
1810 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1813 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1814 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1815 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1816 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1818 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1819 LL.getValueType().isInteger()) {
1820 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
1821 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
1822 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
1823 LR.getValueType(), LL, RL);
1824 AddToWorkList(ORNode.getNode());
1825 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
1827 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
1828 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1829 SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
1830 LR.getValueType(), LL, RL);
1831 AddToWorkList(ANDNode.getNode());
1832 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
1834 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
1835 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1836 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
1837 LR.getValueType(), LL, RL);
1838 AddToWorkList(ORNode.getNode());
1839 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
1842 // canonicalize equivalent to ll == rl
1843 if (LL == RR && LR == RL) {
1844 Op1 = ISD::getSetCCSwappedOperands(Op1);
1847 if (LL == RL && LR == RR) {
1848 bool isInteger = LL.getValueType().isInteger();
1849 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1850 if (Result != ISD::SETCC_INVALID &&
1851 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
1852 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
1857 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
1858 if (N0.getOpcode() == N1.getOpcode()) {
1859 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1860 if (Tmp.getNode()) return Tmp;
1863 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1864 // fold (and (sra)) -> (and (srl)) when possible.
1865 if (!VT.isVector() &&
1866 SimplifyDemandedBits(SDValue(N, 0)))
1867 return SDValue(N, 0);
1869 // fold (zext_inreg (extload x)) -> (zextload x)
1870 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
1871 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1872 EVT MemVT = LN0->getMemoryVT();
1873 // If we zero all the possible extended bits, then we can turn this into
1874 // a zextload if we are running before legalize or the operation is legal.
1875 unsigned BitWidth = N1.getValueSizeInBits();
1876 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1877 BitWidth - MemVT.getSizeInBits())) &&
1878 ((!LegalOperations && !LN0->isVolatile()) ||
1879 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
1880 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
1881 LN0->getChain(), LN0->getBasePtr(),
1883 LN0->getSrcValueOffset(), MemVT,
1884 LN0->isVolatile(), LN0->getAlignment());
1886 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
1887 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1890 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1891 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
1893 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1894 EVT MemVT = LN0->getMemoryVT();
1895 // If we zero all the possible extended bits, then we can turn this into
1896 // a zextload if we are running before legalize or the operation is legal.
1897 unsigned BitWidth = N1.getValueSizeInBits();
1898 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1899 BitWidth - MemVT.getSizeInBits())) &&
1900 ((!LegalOperations && !LN0->isVolatile()) ||
1901 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
1902 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
1904 LN0->getBasePtr(), LN0->getSrcValue(),
1905 LN0->getSrcValueOffset(), MemVT,
1906 LN0->isVolatile(), LN0->getAlignment());
1908 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
1909 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1913 // fold (and (load x), 255) -> (zextload x, i8)
1914 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1915 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
1916 if (N1C && (N0.getOpcode() == ISD::LOAD ||
1917 (N0.getOpcode() == ISD::ANY_EXTEND &&
1918 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
1919 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
1920 LoadSDNode *LN0 = HasAnyExt
1921 ? cast<LoadSDNode>(N0.getOperand(0))
1922 : cast<LoadSDNode>(N0);
1923 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
1924 LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
1925 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
1926 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
1927 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
1928 EVT LoadedVT = LN0->getMemoryVT();
1930 if (ExtVT == LoadedVT &&
1931 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
1932 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
1935 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
1936 LN0->getChain(), LN0->getBasePtr(),
1937 LN0->getSrcValue(), LN0->getSrcValueOffset(),
1938 ExtVT, LN0->isVolatile(), LN0->getAlignment());
1940 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
1941 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1944 // Do not change the width of a volatile load.
1945 // Do not generate loads of non-round integer types since these can
1946 // be expensive (and would be wrong if the type is not byte sized).
1947 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
1948 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
1949 EVT PtrType = LN0->getOperand(1).getValueType();
1951 unsigned Alignment = LN0->getAlignment();
1952 SDValue NewPtr = LN0->getBasePtr();
1954 // For big endian targets, we need to add an offset to the pointer
1955 // to load the correct bytes. For little endian systems, we merely
1956 // need to read fewer bytes from the same pointer.
1957 if (TLI.isBigEndian()) {
1958 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
1959 unsigned EVTStoreBytes = ExtVT.getStoreSize();
1960 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
1961 NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
1962 NewPtr, DAG.getConstant(PtrOff, PtrType));
1963 Alignment = MinAlign(Alignment, PtrOff);
1966 AddToWorkList(NewPtr.getNode());
1968 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
1970 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
1971 LN0->getChain(), NewPtr,
1972 LN0->getSrcValue(), LN0->getSrcValueOffset(),
1973 ExtVT, LN0->isVolatile(), Alignment);
1975 CombineTo(LN0, Load, Load.getValue(1));
1976 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1985 SDValue DAGCombiner::visitOR(SDNode *N) {
1986 SDValue N0 = N->getOperand(0);
1987 SDValue N1 = N->getOperand(1);
1988 SDValue LL, LR, RL, RR, CC0, CC1;
1989 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1990 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1991 EVT VT = N1.getValueType();
1994 if (VT.isVector()) {
1995 SDValue FoldedVOp = SimplifyVBinOp(N);
1996 if (FoldedVOp.getNode()) return FoldedVOp;
1999 // fold (or x, undef) -> -1
2000 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) {
2001 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
2002 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
2004 // fold (or c1, c2) -> c1|c2
2006 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
2007 // canonicalize constant to RHS
2009 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
2010 // fold (or x, 0) -> x
2011 if (N1C && N1C->isNullValue())
2013 // fold (or x, -1) -> -1
2014 if (N1C && N1C->isAllOnesValue())
2016 // fold (or x, c) -> c iff (x & ~c) == 0
2017 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
2020 SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
2021 if (ROR.getNode() != 0)
2023 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
2024 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
2025 isa<ConstantSDNode>(N0.getOperand(1))) {
2026 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
2027 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
2028 DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2029 N0.getOperand(0), N1),
2030 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
2032 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
2033 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2034 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2035 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2037 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2038 LL.getValueType().isInteger()) {
2039 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
2040 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
2041 if (cast<ConstantSDNode>(LR)->isNullValue() &&
2042 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
2043 SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
2044 LR.getValueType(), LL, RL);
2045 AddToWorkList(ORNode.getNode());
2046 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2048 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
2049 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
2050 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2051 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
2052 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
2053 LR.getValueType(), LL, RL);
2054 AddToWorkList(ANDNode.getNode());
2055 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2058 // canonicalize equivalent to ll == rl
2059 if (LL == RR && LR == RL) {
2060 Op1 = ISD::getSetCCSwappedOperands(Op1);
2063 if (LL == RL && LR == RR) {
2064 bool isInteger = LL.getValueType().isInteger();
2065 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
2066 if (Result != ISD::SETCC_INVALID &&
2067 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2068 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2073 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
2074 if (N0.getOpcode() == N1.getOpcode()) {
2075 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2076 if (Tmp.getNode()) return Tmp;
2079 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
2080 if (N0.getOpcode() == ISD::AND &&
2081 N1.getOpcode() == ISD::AND &&
2082 N0.getOperand(1).getOpcode() == ISD::Constant &&
2083 N1.getOperand(1).getOpcode() == ISD::Constant &&
2084 // Don't increase # computations.
2085 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
2086 // We can only do this xform if we know that bits from X that are set in C2
2087 // but not in C1 are already zero. Likewise for Y.
2088 const APInt &LHSMask =
2089 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2090 const APInt &RHSMask =
2091 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
2093 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
2094 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
2095 SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2096 N0.getOperand(0), N1.getOperand(0));
2097 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
2098 DAG.getConstant(LHSMask | RHSMask, VT));
2102 // See if this is some rotate idiom.
2103 if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
2104 return SDValue(Rot, 0);
2109 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
2110 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
2111 if (Op.getOpcode() == ISD::AND) {
2112 if (isa<ConstantSDNode>(Op.getOperand(1))) {
2113 Mask = Op.getOperand(1);
2114 Op = Op.getOperand(0);
2120 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
2128 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
2129 // idioms for rotate, and if the target supports rotation instructions, generate
2131 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
2132 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
2133 EVT VT = LHS.getValueType();
2134 if (!TLI.isTypeLegal(VT)) return 0;
2136 // The target must have at least one rotate flavor.
2137 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
2138 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
2139 if (!HasROTL && !HasROTR) return 0;
2141 // Match "(X shl/srl V1) & V2" where V2 may not be present.
2142 SDValue LHSShift; // The shift.
2143 SDValue LHSMask; // AND value if any.
2144 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
2145 return 0; // Not part of a rotate.
2147 SDValue RHSShift; // The shift.
2148 SDValue RHSMask; // AND value if any.
2149 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
2150 return 0; // Not part of a rotate.
2152 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
2153 return 0; // Not shifting the same value.
2155 if (LHSShift.getOpcode() == RHSShift.getOpcode())
2156 return 0; // Shifts must disagree.
2158 // Canonicalize shl to left side in a shl/srl pair.
2159 if (RHSShift.getOpcode() == ISD::SHL) {
2160 std::swap(LHS, RHS);
2161 std::swap(LHSShift, RHSShift);
2162 std::swap(LHSMask , RHSMask );
2165 unsigned OpSizeInBits = VT.getSizeInBits();
2166 SDValue LHSShiftArg = LHSShift.getOperand(0);
2167 SDValue LHSShiftAmt = LHSShift.getOperand(1);
2168 SDValue RHSShiftAmt = RHSShift.getOperand(1);
2170 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
2171 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
2172 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2173 RHSShiftAmt.getOpcode() == ISD::Constant) {
2174 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
2175 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
2176 if ((LShVal + RShVal) != OpSizeInBits)
2181 Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
2183 Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
2185 // If there is an AND of either shifted operand, apply it to the result.
2186 if (LHSMask.getNode() || RHSMask.getNode()) {
2187 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2189 if (LHSMask.getNode()) {
2190 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2191 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2193 if (RHSMask.getNode()) {
2194 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2195 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2198 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
2201 return Rot.getNode();
2204 // If there is a mask here, and we have a variable shift, we can't be sure
2205 // that we're masking out the right stuff.
2206 if (LHSMask.getNode() || RHSMask.getNode())
2209 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2210 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2211 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2212 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2213 if (ConstantSDNode *SUBC =
2214 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2215 if (SUBC->getAPIntValue() == OpSizeInBits) {
2217 return DAG.getNode(ISD::ROTL, DL, VT,
2218 LHSShiftArg, LHSShiftAmt).getNode();
2220 return DAG.getNode(ISD::ROTR, DL, VT,
2221 LHSShiftArg, RHSShiftAmt).getNode();
2226 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2227 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2228 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2229 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2230 if (ConstantSDNode *SUBC =
2231 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2232 if (SUBC->getAPIntValue() == OpSizeInBits) {
2234 return DAG.getNode(ISD::ROTR, DL, VT,
2235 LHSShiftArg, RHSShiftAmt).getNode();
2237 return DAG.getNode(ISD::ROTL, DL, VT,
2238 LHSShiftArg, LHSShiftAmt).getNode();
2243 // Look for sign/zext/any-extended or truncate cases:
2244 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2245 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2246 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2247 || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
2248 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2249 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2250 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2251 || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
2252 SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
2253 SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
2254 if (RExtOp0.getOpcode() == ISD::SUB &&
2255 RExtOp0.getOperand(1) == LExtOp0) {
2256 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2258 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2259 // (rotr x, (sub 32, y))
2260 if (ConstantSDNode *SUBC =
2261 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2262 if (SUBC->getAPIntValue() == OpSizeInBits) {
2263 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
2265 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
2268 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2269 RExtOp0 == LExtOp0.getOperand(1)) {
2270 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2272 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2273 // (rotl x, (sub 32, y))
2274 if (ConstantSDNode *SUBC =
2275 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2276 if (SUBC->getAPIntValue() == OpSizeInBits) {
2277 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
2279 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
2288 SDValue DAGCombiner::visitXOR(SDNode *N) {
2289 SDValue N0 = N->getOperand(0);
2290 SDValue N1 = N->getOperand(1);
2291 SDValue LHS, RHS, CC;
2292 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2293 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2294 EVT VT = N0.getValueType();
2297 if (VT.isVector()) {
2298 SDValue FoldedVOp = SimplifyVBinOp(N);
2299 if (FoldedVOp.getNode()) return FoldedVOp;
2302 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2303 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2304 return DAG.getConstant(0, VT);
2305 // fold (xor x, undef) -> undef
2306 if (N0.getOpcode() == ISD::UNDEF)
2308 if (N1.getOpcode() == ISD::UNDEF)
2310 // fold (xor c1, c2) -> c1^c2
2312 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
2313 // canonicalize constant to RHS
2315 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
2316 // fold (xor x, 0) -> x
2317 if (N1C && N1C->isNullValue())
2320 SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
2321 if (RXOR.getNode() != 0)
2324 // fold !(x cc y) -> (x !cc y)
2325 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2326 bool isInt = LHS.getValueType().isInteger();
2327 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2330 if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
2331 switch (N0.getOpcode()) {
2333 llvm_unreachable("Unhandled SetCC Equivalent!");
2335 return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
2336 case ISD::SELECT_CC:
2337 return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
2338 N0.getOperand(3), NotCC);
2343 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2344 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2345 N0.getNode()->hasOneUse() &&
2346 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2347 SDValue V = N0.getOperand(0);
2348 V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
2349 DAG.getConstant(1, V.getValueType()));
2350 AddToWorkList(V.getNode());
2351 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
2354 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
2355 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2356 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2357 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2358 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2359 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2360 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2361 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2362 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2363 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2366 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
2367 if (N1C && N1C->isAllOnesValue() &&
2368 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2369 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2370 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2371 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2372 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2373 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2374 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2375 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2378 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
2379 if (N1C && N0.getOpcode() == ISD::XOR) {
2380 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2381 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2383 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
2384 DAG.getConstant(N1C->getAPIntValue() ^
2385 N00C->getAPIntValue(), VT));
2387 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
2388 DAG.getConstant(N1C->getAPIntValue() ^
2389 N01C->getAPIntValue(), VT));
2391 // fold (xor x, x) -> 0
2393 if (!VT.isVector()) {
2394 return DAG.getConstant(0, VT);
2395 } else if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)){
2396 // Produce a vector of zeros.
2397 SDValue El = DAG.getConstant(0, VT.getVectorElementType());
2398 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
2399 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
2400 &Ops[0], Ops.size());
2404 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2405 if (N0.getOpcode() == N1.getOpcode()) {
2406 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2407 if (Tmp.getNode()) return Tmp;
2410 // Simplify the expression using non-local knowledge.
2411 if (!VT.isVector() &&
2412 SimplifyDemandedBits(SDValue(N, 0)))
2413 return SDValue(N, 0);
2418 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2419 /// the shift amount is a constant.
2420 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2421 SDNode *LHS = N->getOperand(0).getNode();
2422 if (!LHS->hasOneUse()) return SDValue();
2424 // We want to pull some binops through shifts, so that we have (and (shift))
2425 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2426 // thing happens with address calculations, so it's important to canonicalize
2428 bool HighBitSet = false; // Can we transform this if the high bit is set?
2430 switch (LHS->getOpcode()) {
2431 default: return SDValue();
2434 HighBitSet = false; // We can only transform sra if the high bit is clear.
2437 HighBitSet = true; // We can only transform sra if the high bit is set.
2440 if (N->getOpcode() != ISD::SHL)
2441 return SDValue(); // only shl(add) not sr[al](add).
2442 HighBitSet = false; // We can only transform sra if the high bit is clear.
2446 // We require the RHS of the binop to be a constant as well.
2447 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2448 if (!BinOpCst) return SDValue();
2450 // FIXME: disable this unless the input to the binop is a shift by a constant.
2451 // If it is not a shift, it pessimizes some common cases like:
2453 // void foo(int *X, int i) { X[i & 1235] = 1; }
2454 // int bar(int *X, int i) { return X[i & 255]; }
2455 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
2456 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2457 BinOpLHSVal->getOpcode() != ISD::SRA &&
2458 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2459 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2462 EVT VT = N->getValueType(0);
2464 // If this is a signed shift right, and the high bit is modified by the
2465 // logical operation, do not perform the transformation. The highBitSet
2466 // boolean indicates the value of the high bit of the constant which would
2467 // cause it to be modified for this operation.
2468 if (N->getOpcode() == ISD::SRA) {
2469 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2470 if (BinOpRHSSignSet != HighBitSet)
2474 // Fold the constants, shifting the binop RHS by the shift amount.
2475 SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
2477 LHS->getOperand(1), N->getOperand(1));
2479 // Create the new shift.
2480 SDValue NewShift = DAG.getNode(N->getOpcode(), LHS->getOperand(0).getDebugLoc(),
2481 VT, LHS->getOperand(0), N->getOperand(1));
2483 // Create the new binop.
2484 return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
2487 SDValue DAGCombiner::visitSHL(SDNode *N) {
2488 SDValue N0 = N->getOperand(0);
2489 SDValue N1 = N->getOperand(1);
2490 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2491 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2492 EVT VT = N0.getValueType();
2493 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
2495 // fold (shl c1, c2) -> c1<<c2
2497 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
2498 // fold (shl 0, x) -> 0
2499 if (N0C && N0C->isNullValue())
2501 // fold (shl x, c >= size(x)) -> undef
2502 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2503 return DAG.getUNDEF(VT);
2504 // fold (shl x, 0) -> x
2505 if (N1C && N1C->isNullValue())
2507 // if (shl x, c) is known to be zero, return 0
2508 if (DAG.MaskedValueIsZero(SDValue(N, 0),
2509 APInt::getAllOnesValue(OpSizeInBits)))
2510 return DAG.getConstant(0, VT);
2511 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
2512 if (N1.getOpcode() == ISD::TRUNCATE &&
2513 N1.getOperand(0).getOpcode() == ISD::AND &&
2514 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2515 SDValue N101 = N1.getOperand(0).getOperand(1);
2516 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2517 EVT TruncVT = N1.getValueType();
2518 SDValue N100 = N1.getOperand(0).getOperand(0);
2519 APInt TruncC = N101C->getAPIntValue();
2520 TruncC.trunc(TruncVT.getSizeInBits());
2521 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
2522 DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
2523 DAG.getNode(ISD::TRUNCATE,
2526 DAG.getConstant(TruncC, TruncVT)));
2530 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2531 return SDValue(N, 0);
2533 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
2534 if (N1C && N0.getOpcode() == ISD::SHL &&
2535 N0.getOperand(1).getOpcode() == ISD::Constant) {
2536 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2537 uint64_t c2 = N1C->getZExtValue();
2538 if (c1 + c2 > OpSizeInBits)
2539 return DAG.getConstant(0, VT);
2540 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
2541 DAG.getConstant(c1 + c2, N1.getValueType()));
2543 // fold (shl (srl x, c1), c2) -> (shl (and x, (shl -1, c1)), (sub c2, c1)) or
2544 // (srl (and x, (shl -1, c1)), (sub c1, c2))
2545 if (N1C && N0.getOpcode() == ISD::SRL &&
2546 N0.getOperand(1).getOpcode() == ISD::Constant) {
2547 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2548 if (c1 < VT.getSizeInBits()) {
2549 uint64_t c2 = N1C->getZExtValue();
2550 SDValue HiBitsMask =
2551 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
2552 VT.getSizeInBits() - c1),
2554 SDValue Mask = DAG.getNode(ISD::AND, N0.getDebugLoc(), VT,
2558 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, Mask,
2559 DAG.getConstant(c2-c1, N1.getValueType()));
2561 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Mask,
2562 DAG.getConstant(c1-c2, N1.getValueType()));
2565 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
2566 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
2567 SDValue HiBitsMask =
2568 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
2569 VT.getSizeInBits() -
2570 N1C->getZExtValue()),
2572 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
2576 return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
2579 SDValue DAGCombiner::visitSRA(SDNode *N) {
2580 SDValue N0 = N->getOperand(0);
2581 SDValue N1 = N->getOperand(1);
2582 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2583 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2584 EVT VT = N0.getValueType();
2585 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
2587 // fold (sra c1, c2) -> (sra c1, c2)
2589 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
2590 // fold (sra 0, x) -> 0
2591 if (N0C && N0C->isNullValue())
2593 // fold (sra -1, x) -> -1
2594 if (N0C && N0C->isAllOnesValue())
2596 // fold (sra x, (setge c, size(x))) -> undef
2597 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2598 return DAG.getUNDEF(VT);
2599 // fold (sra x, 0) -> x
2600 if (N1C && N1C->isNullValue())
2602 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2604 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2605 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
2606 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
2608 ExtVT = EVT::getVectorVT(*DAG.getContext(),
2609 ExtVT, VT.getVectorNumElements());
2610 if ((!LegalOperations ||
2611 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
2612 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
2613 N0.getOperand(0), DAG.getValueType(ExtVT));
2616 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
2617 if (N1C && N0.getOpcode() == ISD::SRA) {
2618 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2619 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
2620 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
2621 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
2622 DAG.getConstant(Sum, N1C->getValueType(0)));
2626 // fold (sra (shl X, m), (sub result_size, n))
2627 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
2628 // result_size - n != m.
2629 // If truncate is free for the target sext(shl) is likely to result in better
2631 if (N0.getOpcode() == ISD::SHL) {
2632 // Get the two constanst of the shifts, CN0 = m, CN = n.
2633 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2635 // Determine what the truncate's result bitsize and type would be.
2637 EVT::getIntegerVT(*DAG.getContext(), OpSizeInBits - N1C->getZExtValue());
2638 // Determine the residual right-shift amount.
2639 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
2641 // If the shift is not a no-op (in which case this should be just a sign
2642 // extend already), the truncated to type is legal, sign_extend is legal
2643 // on that type, and the the truncate to that type is both legal and free,
2644 // perform the transform.
2645 if ((ShiftAmt > 0) &&
2646 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
2647 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
2648 TLI.isTruncateFree(VT, TruncVT)) {
2650 SDValue Amt = DAG.getConstant(ShiftAmt, getShiftAmountTy());
2651 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
2652 N0.getOperand(0), Amt);
2653 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
2655 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
2656 N->getValueType(0), Trunc);
2661 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
2662 if (N1.getOpcode() == ISD::TRUNCATE &&
2663 N1.getOperand(0).getOpcode() == ISD::AND &&
2664 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2665 SDValue N101 = N1.getOperand(0).getOperand(1);
2666 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2667 EVT TruncVT = N1.getValueType();
2668 SDValue N100 = N1.getOperand(0).getOperand(0);
2669 APInt TruncC = N101C->getAPIntValue();
2670 TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
2671 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
2672 DAG.getNode(ISD::AND, N->getDebugLoc(),
2674 DAG.getNode(ISD::TRUNCATE,
2677 DAG.getConstant(TruncC, TruncVT)));
2681 // Simplify, based on bits shifted out of the LHS.
2682 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2683 return SDValue(N, 0);
2686 // If the sign bit is known to be zero, switch this to a SRL.
2687 if (DAG.SignBitIsZero(N0))
2688 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
2690 return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
2693 SDValue DAGCombiner::visitSRL(SDNode *N) {
2694 SDValue N0 = N->getOperand(0);
2695 SDValue N1 = N->getOperand(1);
2696 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2697 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2698 EVT VT = N0.getValueType();
2699 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
2701 // fold (srl c1, c2) -> c1 >>u c2
2703 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
2704 // fold (srl 0, x) -> 0
2705 if (N0C && N0C->isNullValue())
2707 // fold (srl x, c >= size(x)) -> undef
2708 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2709 return DAG.getUNDEF(VT);
2710 // fold (srl x, 0) -> x
2711 if (N1C && N1C->isNullValue())
2713 // if (srl x, c) is known to be zero, return 0
2714 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2715 APInt::getAllOnesValue(OpSizeInBits)))
2716 return DAG.getConstant(0, VT);
2718 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
2719 if (N1C && N0.getOpcode() == ISD::SRL &&
2720 N0.getOperand(1).getOpcode() == ISD::Constant) {
2721 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2722 uint64_t c2 = N1C->getZExtValue();
2723 if (c1 + c2 > OpSizeInBits)
2724 return DAG.getConstant(0, VT);
2725 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
2726 DAG.getConstant(c1 + c2, N1.getValueType()));
2729 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2730 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2731 // Shifting in all undef bits?
2732 EVT SmallVT = N0.getOperand(0).getValueType();
2733 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
2734 return DAG.getUNDEF(VT);
2736 SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
2737 N0.getOperand(0), N1);
2738 AddToWorkList(SmallShift.getNode());
2739 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
2742 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
2743 // bit, which is unmodified by sra.
2744 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
2745 if (N0.getOpcode() == ISD::SRA)
2746 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
2749 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
2750 if (N1C && N0.getOpcode() == ISD::CTLZ &&
2751 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
2752 APInt KnownZero, KnownOne;
2753 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
2754 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2756 // If any of the input bits are KnownOne, then the input couldn't be all
2757 // zeros, thus the result of the srl will always be zero.
2758 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
2760 // If all of the bits input the to ctlz node are known to be zero, then
2761 // the result of the ctlz is "32" and the result of the shift is one.
2762 APInt UnknownBits = ~KnownZero & Mask;
2763 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2765 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2766 if ((UnknownBits & (UnknownBits - 1)) == 0) {
2767 // Okay, we know that only that the single bit specified by UnknownBits
2768 // could be set on input to the CTLZ node. If this bit is set, the SRL
2769 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2770 // to an SRL/XOR pair, which is likely to simplify more.
2771 unsigned ShAmt = UnknownBits.countTrailingZeros();
2772 SDValue Op = N0.getOperand(0);
2775 Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
2776 DAG.getConstant(ShAmt, getShiftAmountTy()));
2777 AddToWorkList(Op.getNode());
2780 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
2781 Op, DAG.getConstant(1, VT));
2785 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
2786 if (N1.getOpcode() == ISD::TRUNCATE &&
2787 N1.getOperand(0).getOpcode() == ISD::AND &&
2788 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2789 SDValue N101 = N1.getOperand(0).getOperand(1);
2790 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2791 EVT TruncVT = N1.getValueType();
2792 SDValue N100 = N1.getOperand(0).getOperand(0);
2793 APInt TruncC = N101C->getAPIntValue();
2794 TruncC.trunc(TruncVT.getSizeInBits());
2795 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
2796 DAG.getNode(ISD::AND, N->getDebugLoc(),
2798 DAG.getNode(ISD::TRUNCATE,
2801 DAG.getConstant(TruncC, TruncVT)));
2805 // fold operands of srl based on knowledge that the low bits are not
2807 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2808 return SDValue(N, 0);
2811 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
2812 if (NewSRL.getNode())
2816 // Here is a common situation. We want to optimize:
2819 // %b = and i32 %a, 2
2820 // %c = srl i32 %b, 1
2821 // brcond i32 %c ...
2827 // %c = setcc eq %b, 0
2830 // However when after the source operand of SRL is optimized into AND, the SRL
2831 // itself may not be optimized further. Look for it and add the BRCOND into
2833 if (N->hasOneUse()) {
2834 SDNode *Use = *N->use_begin();
2835 if (Use->getOpcode() == ISD::BRCOND)
2837 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
2838 // Also look pass the truncate.
2839 Use = *Use->use_begin();
2840 if (Use->getOpcode() == ISD::BRCOND)
2848 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
2849 SDValue N0 = N->getOperand(0);
2850 EVT VT = N->getValueType(0);
2852 // fold (ctlz c1) -> c2
2853 if (isa<ConstantSDNode>(N0))
2854 return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
2858 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
2859 SDValue N0 = N->getOperand(0);
2860 EVT VT = N->getValueType(0);
2862 // fold (cttz c1) -> c2
2863 if (isa<ConstantSDNode>(N0))
2864 return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
2868 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
2869 SDValue N0 = N->getOperand(0);
2870 EVT VT = N->getValueType(0);
2872 // fold (ctpop c1) -> c2
2873 if (isa<ConstantSDNode>(N0))
2874 return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
2878 SDValue DAGCombiner::visitSELECT(SDNode *N) {
2879 SDValue N0 = N->getOperand(0);
2880 SDValue N1 = N->getOperand(1);
2881 SDValue N2 = N->getOperand(2);
2882 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2883 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2884 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2885 EVT VT = N->getValueType(0);
2886 EVT VT0 = N0.getValueType();
2888 // fold (select C, X, X) -> X
2891 // fold (select true, X, Y) -> X
2892 if (N0C && !N0C->isNullValue())
2894 // fold (select false, X, Y) -> Y
2895 if (N0C && N0C->isNullValue())
2897 // fold (select C, 1, X) -> (or C, X)
2898 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
2899 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
2900 // fold (select C, 0, 1) -> (xor C, 1)
2901 if (VT.isInteger() &&
2904 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent)) &&
2905 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
2908 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
2909 N0, DAG.getConstant(1, VT0));
2910 XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
2911 N0, DAG.getConstant(1, VT0));
2912 AddToWorkList(XORNode.getNode());
2914 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
2915 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
2917 // fold (select C, 0, X) -> (and (not C), X)
2918 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
2919 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
2920 AddToWorkList(NOTNode.getNode());
2921 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
2923 // fold (select C, X, 1) -> (or (not C), X)
2924 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
2925 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
2926 AddToWorkList(NOTNode.getNode());
2927 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
2929 // fold (select C, X, 0) -> (and C, X)
2930 if (VT == MVT::i1 && N2C && N2C->isNullValue())
2931 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
2932 // fold (select X, X, Y) -> (or X, Y)
2933 // fold (select X, 1, Y) -> (or X, Y)
2934 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
2935 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
2936 // fold (select X, Y, X) -> (and X, Y)
2937 // fold (select X, Y, 0) -> (and X, Y)
2938 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
2939 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
2941 // If we can fold this based on the true/false value, do so.
2942 if (SimplifySelectOps(N, N1, N2))
2943 return SDValue(N, 0); // Don't revisit N.
2945 // fold selects based on a setcc into other things, such as min/max/abs
2946 if (N0.getOpcode() == ISD::SETCC) {
2948 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2949 // having to say they don't support SELECT_CC on every type the DAG knows
2950 // about, since there is no way to mark an opcode illegal at all value types
2951 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
2952 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
2953 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
2954 N0.getOperand(0), N0.getOperand(1),
2955 N1, N2, N0.getOperand(2));
2956 return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
2962 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
2963 SDValue N0 = N->getOperand(0);
2964 SDValue N1 = N->getOperand(1);
2965 SDValue N2 = N->getOperand(2);
2966 SDValue N3 = N->getOperand(3);
2967 SDValue N4 = N->getOperand(4);
2968 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2970 // fold select_cc lhs, rhs, x, x, cc -> x
2974 // Determine if the condition we're dealing with is constant
2975 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
2976 N0, N1, CC, N->getDebugLoc(), false);
2977 if (SCC.getNode()) AddToWorkList(SCC.getNode());
2979 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
2980 if (!SCCC->isNullValue())
2981 return N2; // cond always true -> true val
2983 return N3; // cond always false -> false val
2986 // Fold to a simpler select_cc
2987 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
2988 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
2989 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2992 // If we can fold this based on the true/false value, do so.
2993 if (SimplifySelectOps(N, N2, N3))
2994 return SDValue(N, 0); // Don't revisit N.
2996 // fold select_cc into other things, such as min/max/abs
2997 return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
3000 SDValue DAGCombiner::visitSETCC(SDNode *N) {
3001 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
3002 cast<CondCodeSDNode>(N->getOperand(2))->get(),
3006 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
3007 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
3008 // transformation. Returns true if extension are possible and the above
3009 // mentioned transformation is profitable.
3010 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
3012 SmallVector<SDNode*, 4> &ExtendNodes,
3013 const TargetLowering &TLI) {
3014 bool HasCopyToRegUses = false;
3015 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
3016 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
3017 UE = N0.getNode()->use_end();
3022 if (UI.getUse().getResNo() != N0.getResNo())
3024 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
3025 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
3026 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
3027 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
3028 // Sign bits will be lost after a zext.
3031 for (unsigned i = 0; i != 2; ++i) {
3032 SDValue UseOp = User->getOperand(i);
3035 if (!isa<ConstantSDNode>(UseOp))
3040 ExtendNodes.push_back(User);
3043 // If truncates aren't free and there are users we can't
3044 // extend, it isn't worthwhile.
3047 // Remember if this value is live-out.
3048 if (User->getOpcode() == ISD::CopyToReg)
3049 HasCopyToRegUses = true;
3052 if (HasCopyToRegUses) {
3053 bool BothLiveOut = false;
3054 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3056 SDUse &Use = UI.getUse();
3057 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
3063 // Both unextended and extended values are live out. There had better be
3064 // good a reason for the transformation.
3065 return ExtendNodes.size();
3070 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
3071 SDValue N0 = N->getOperand(0);
3072 EVT VT = N->getValueType(0);
3074 // fold (sext c1) -> c1
3075 if (isa<ConstantSDNode>(N0))
3076 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
3078 // fold (sext (sext x)) -> (sext x)
3079 // fold (sext (aext x)) -> (sext x)
3080 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3081 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
3084 if (N0.getOpcode() == ISD::TRUNCATE) {
3085 // fold (sext (truncate (load x))) -> (sext (smaller load x))
3086 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
3087 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3088 if (NarrowLoad.getNode()) {
3089 if (NarrowLoad.getNode() != N0.getNode())
3090 CombineTo(N0.getNode(), NarrowLoad);
3091 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3094 // See if the value being truncated is already sign extended. If so, just
3095 // eliminate the trunc/sext pair.
3096 SDValue Op = N0.getOperand(0);
3097 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
3098 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
3099 unsigned DestBits = VT.getScalarType().getSizeInBits();
3100 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
3102 if (OpBits == DestBits) {
3103 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
3104 // bits, it is already ready.
3105 if (NumSignBits > DestBits-MidBits)
3107 } else if (OpBits < DestBits) {
3108 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
3109 // bits, just sext from i32.
3110 if (NumSignBits > OpBits-MidBits)
3111 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
3113 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
3114 // bits, just truncate to i32.
3115 if (NumSignBits > OpBits-MidBits)
3116 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3119 // fold (sext (truncate x)) -> (sextinreg x).
3120 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
3121 N0.getValueType())) {
3122 if (OpBits < DestBits)
3123 Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
3124 else if (OpBits > DestBits)
3125 Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
3126 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
3127 DAG.getValueType(N0.getValueType()));
3131 // fold (sext (load x)) -> (sext (truncate (sextload x)))
3132 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3133 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3134 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
3135 bool DoXform = true;
3136 SmallVector<SDNode*, 4> SetCCs;
3137 if (!N0.hasOneUse())
3138 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
3140 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3141 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3143 LN0->getBasePtr(), LN0->getSrcValue(),
3144 LN0->getSrcValueOffset(),
3146 LN0->isVolatile(), LN0->getAlignment());
3147 CombineTo(N, ExtLoad);
3148 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3149 N0.getValueType(), ExtLoad);
3150 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3152 // Extend SetCC uses if necessary.
3153 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3154 SDNode *SetCC = SetCCs[i];
3155 SmallVector<SDValue, 4> Ops;
3157 for (unsigned j = 0; j != 2; ++j) {
3158 SDValue SOp = SetCC->getOperand(j);
3160 Ops.push_back(ExtLoad);
3162 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND,
3163 N->getDebugLoc(), VT, SOp));
3166 Ops.push_back(SetCC->getOperand(2));
3167 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3168 SetCC->getValueType(0),
3169 &Ops[0], Ops.size()));
3172 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3176 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
3177 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
3178 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3179 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3180 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3181 EVT MemVT = LN0->getMemoryVT();
3182 if ((!LegalOperations && !LN0->isVolatile()) ||
3183 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
3184 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3186 LN0->getBasePtr(), LN0->getSrcValue(),
3187 LN0->getSrcValueOffset(), MemVT,
3188 LN0->isVolatile(), LN0->getAlignment());
3189 CombineTo(N, ExtLoad);
3190 CombineTo(N0.getNode(),
3191 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3192 N0.getValueType(), ExtLoad),
3193 ExtLoad.getValue(1));
3194 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3198 if (N0.getOpcode() == ISD::SETCC) {
3199 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
3200 if (VT.isVector() &&
3201 // We know that the # elements of the results is the same as the
3202 // # elements of the compare (and the # elements of the compare result
3203 // for that matter). Check to see that they are the same size. If so,
3204 // we know that the element size of the sext'd result matches the
3205 // element size of the compare operands.
3206 VT.getSizeInBits() == N0.getOperand(0).getValueType().getSizeInBits() &&
3208 // Only do this before legalize for now.
3210 return DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
3212 cast<CondCodeSDNode>(N0.getOperand(2))->get());
3215 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
3217 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
3219 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3220 NegOne, DAG.getConstant(0, VT),
3221 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3222 if (SCC.getNode()) return SCC;
3223 if (!LegalOperations ||
3224 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT)))
3225 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
3226 DAG.getSetCC(N->getDebugLoc(),
3227 TLI.getSetCCResultType(VT),
3228 N0.getOperand(0), N0.getOperand(1),
3229 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
3230 NegOne, DAG.getConstant(0, VT));
3235 // fold (sext x) -> (zext x) if the sign bit is known zero.
3236 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
3237 DAG.SignBitIsZero(N0))
3238 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3243 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
3244 SDValue N0 = N->getOperand(0);
3245 EVT VT = N->getValueType(0);
3247 // fold (zext c1) -> c1
3248 if (isa<ConstantSDNode>(N0))
3249 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3250 // fold (zext (zext x)) -> (zext x)
3251 // fold (zext (aext x)) -> (zext x)
3252 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3253 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
3256 // fold (zext (truncate (load x))) -> (zext (smaller load x))
3257 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
3258 if (N0.getOpcode() == ISD::TRUNCATE) {
3259 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3260 if (NarrowLoad.getNode()) {
3261 if (NarrowLoad.getNode() != N0.getNode())
3262 CombineTo(N0.getNode(), NarrowLoad);
3263 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
3267 // fold (zext (truncate x)) -> (and x, mask)
3268 if (N0.getOpcode() == ISD::TRUNCATE &&
3269 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) &&
3270 (!TLI.isTruncateFree(N0.getOperand(0).getValueType(),
3271 N0.getValueType()) ||
3272 !TLI.isZExtFree(N0.getValueType(), VT))) {
3273 SDValue Op = N0.getOperand(0);
3274 if (Op.getValueType().bitsLT(VT)) {
3275 Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
3276 } else if (Op.getValueType().bitsGT(VT)) {
3277 Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3279 return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
3280 N0.getValueType().getScalarType());
3283 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
3284 // if either of the casts is not free.
3285 if (N0.getOpcode() == ISD::AND &&
3286 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3287 N0.getOperand(1).getOpcode() == ISD::Constant &&
3288 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
3289 N0.getValueType()) ||
3290 !TLI.isZExtFree(N0.getValueType(), VT))) {
3291 SDValue X = N0.getOperand(0).getOperand(0);
3292 if (X.getValueType().bitsLT(VT)) {
3293 X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
3294 } else if (X.getValueType().bitsGT(VT)) {
3295 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
3297 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3298 Mask.zext(VT.getSizeInBits());
3299 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3300 X, DAG.getConstant(Mask, VT));
3303 // fold (zext (load x)) -> (zext (truncate (zextload x)))
3304 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3305 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3306 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
3307 bool DoXform = true;
3308 SmallVector<SDNode*, 4> SetCCs;
3309 if (!N0.hasOneUse())
3310 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
3312 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3313 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
3315 LN0->getBasePtr(), LN0->getSrcValue(),
3316 LN0->getSrcValueOffset(),
3318 LN0->isVolatile(), LN0->getAlignment());
3319 CombineTo(N, ExtLoad);
3320 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3321 N0.getValueType(), ExtLoad);
3322 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3324 // Extend SetCC uses if necessary.
3325 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3326 SDNode *SetCC = SetCCs[i];
3327 SmallVector<SDValue, 4> Ops;
3329 for (unsigned j = 0; j != 2; ++j) {
3330 SDValue SOp = SetCC->getOperand(j);
3332 Ops.push_back(ExtLoad);
3334 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND,
3335 N->getDebugLoc(), VT, SOp));
3338 Ops.push_back(SetCC->getOperand(2));
3339 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3340 SetCC->getValueType(0),
3341 &Ops[0], Ops.size()));
3344 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3348 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
3349 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
3350 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3351 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3352 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3353 EVT MemVT = LN0->getMemoryVT();
3354 if ((!LegalOperations && !LN0->isVolatile()) ||
3355 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
3356 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
3358 LN0->getBasePtr(), LN0->getSrcValue(),
3359 LN0->getSrcValueOffset(), MemVT,
3360 LN0->isVolatile(), LN0->getAlignment());
3361 CombineTo(N, ExtLoad);
3362 CombineTo(N0.getNode(),
3363 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
3365 ExtLoad.getValue(1));
3366 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3370 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3371 if (N0.getOpcode() == ISD::SETCC) {
3373 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3374 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3375 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3376 if (SCC.getNode()) return SCC;
3379 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
3380 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
3381 isa<ConstantSDNode>(N0.getOperand(1)) &&
3382 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
3384 if (N0.getOpcode() == ISD::SHL) {
3385 // If the original shl may be shifting out bits, do not perform this
3387 unsigned ShAmt = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3388 unsigned KnownZeroBits = N0.getOperand(0).getValueType().getSizeInBits() -
3389 N0.getOperand(0).getOperand(0).getValueType().getSizeInBits();
3390 if (ShAmt > KnownZeroBits)
3393 DebugLoc dl = N->getDebugLoc();
3394 return DAG.getNode(N0.getOpcode(), dl, VT,
3395 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0.getOperand(0)),
3396 DAG.getNode(ISD::ZERO_EXTEND, dl,
3397 N0.getOperand(1).getValueType(),
3404 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
3405 SDValue N0 = N->getOperand(0);
3406 EVT VT = N->getValueType(0);
3408 // fold (aext c1) -> c1
3409 if (isa<ConstantSDNode>(N0))
3410 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
3411 // fold (aext (aext x)) -> (aext x)
3412 // fold (aext (zext x)) -> (zext x)
3413 // fold (aext (sext x)) -> (sext x)
3414 if (N0.getOpcode() == ISD::ANY_EXTEND ||
3415 N0.getOpcode() == ISD::ZERO_EXTEND ||
3416 N0.getOpcode() == ISD::SIGN_EXTEND)
3417 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
3419 // fold (aext (truncate (load x))) -> (aext (smaller load x))
3420 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
3421 if (N0.getOpcode() == ISD::TRUNCATE) {
3422 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3423 if (NarrowLoad.getNode()) {
3424 if (NarrowLoad.getNode() != N0.getNode())
3425 CombineTo(N0.getNode(), NarrowLoad);
3426 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
3430 // fold (aext (truncate x))
3431 if (N0.getOpcode() == ISD::TRUNCATE) {
3432 SDValue TruncOp = N0.getOperand(0);
3433 if (TruncOp.getValueType() == VT)
3434 return TruncOp; // x iff x size == zext size.
3435 if (TruncOp.getValueType().bitsGT(VT))
3436 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
3437 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
3440 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
3441 // if the trunc is not free.
3442 if (N0.getOpcode() == ISD::AND &&
3443 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3444 N0.getOperand(1).getOpcode() == ISD::Constant &&
3445 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
3446 N0.getValueType())) {
3447 SDValue X = N0.getOperand(0).getOperand(0);
3448 if (X.getValueType().bitsLT(VT)) {
3449 X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
3450 } else if (X.getValueType().bitsGT(VT)) {
3451 X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
3453 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3454 Mask.zext(VT.getSizeInBits());
3455 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3456 X, DAG.getConstant(Mask, VT));
3459 // fold (aext (load x)) -> (aext (truncate (extload x)))
3460 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3461 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3462 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
3463 bool DoXform = true;
3464 SmallVector<SDNode*, 4> SetCCs;
3465 if (!N0.hasOneUse())
3466 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
3468 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3469 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
3471 LN0->getBasePtr(), LN0->getSrcValue(),
3472 LN0->getSrcValueOffset(),
3474 LN0->isVolatile(), LN0->getAlignment());
3475 CombineTo(N, ExtLoad);
3476 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3477 N0.getValueType(), ExtLoad);
3478 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3480 // Extend SetCC uses if necessary.
3481 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3482 SDNode *SetCC = SetCCs[i];
3483 SmallVector<SDValue, 4> Ops;
3485 for (unsigned j = 0; j != 2; ++j) {
3486 SDValue SOp = SetCC->getOperand(j);
3488 Ops.push_back(ExtLoad);
3490 Ops.push_back(DAG.getNode(ISD::ANY_EXTEND,
3491 N->getDebugLoc(), VT, SOp));
3494 Ops.push_back(SetCC->getOperand(2));
3495 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3496 SetCC->getValueType(0),
3497 &Ops[0], Ops.size()));
3500 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3504 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
3505 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
3506 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
3507 if (N0.getOpcode() == ISD::LOAD &&
3508 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3510 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3511 EVT MemVT = LN0->getMemoryVT();
3512 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
3513 VT, LN0->getChain(), LN0->getBasePtr(),
3515 LN0->getSrcValueOffset(), MemVT,
3516 LN0->isVolatile(), LN0->getAlignment());
3517 CombineTo(N, ExtLoad);
3518 CombineTo(N0.getNode(),
3519 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3520 N0.getValueType(), ExtLoad),
3521 ExtLoad.getValue(1));
3522 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3525 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3526 if (N0.getOpcode() == ISD::SETCC) {
3528 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3529 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3530 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3538 /// GetDemandedBits - See if the specified operand can be simplified with the
3539 /// knowledge that only the bits specified by Mask are used. If so, return the
3540 /// simpler operand, otherwise return a null SDValue.
3541 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
3542 switch (V.getOpcode()) {
3546 // If the LHS or RHS don't contribute bits to the or, drop them.
3547 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3548 return V.getOperand(1);
3549 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3550 return V.getOperand(0);
3553 // Only look at single-use SRLs.
3554 if (!V.getNode()->hasOneUse())
3556 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3557 // See if we can recursively simplify the LHS.
3558 unsigned Amt = RHSC->getZExtValue();
3560 // Watch out for shift count overflow though.
3561 if (Amt >= Mask.getBitWidth()) break;
3562 APInt NewMask = Mask << Amt;
3563 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
3564 if (SimplifyLHS.getNode())
3565 return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
3566 SimplifyLHS, V.getOperand(1));
3572 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3573 /// bits and then truncated to a narrower type and where N is a multiple
3574 /// of number of bits of the narrower type, transform it to a narrower load
3575 /// from address + N / num of bits of new type. If the result is to be
3576 /// extended, also fold the extension to form a extending load.
3577 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
3578 unsigned Opc = N->getOpcode();
3579 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3580 SDValue N0 = N->getOperand(0);
3581 EVT VT = N->getValueType(0);
3584 // This transformation isn't valid for vector loads.
3588 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
3590 if (Opc == ISD::SIGN_EXTEND_INREG) {
3591 ExtType = ISD::SEXTLOAD;
3592 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3593 if (LegalOperations && !TLI.isLoadExtLegal(ISD::SEXTLOAD, ExtVT))
3597 unsigned EVTBits = ExtVT.getSizeInBits();
3599 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse() && ExtVT.isRound()) {
3600 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3601 ShAmt = N01->getZExtValue();
3602 // Is the shift amount a multiple of size of VT?
3603 if ((ShAmt & (EVTBits-1)) == 0) {
3604 N0 = N0.getOperand(0);
3605 // Is the load width a multiple of size of VT?
3606 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
3612 // Do not generate loads of non-round integer types since these can
3613 // be expensive (and would be wrong if the type is not byte sized).
3614 if (isa<LoadSDNode>(N0) && N0.hasOneUse() && ExtVT.isRound() &&
3615 cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() > EVTBits &&
3616 // Do not change the width of a volatile load.
3617 !cast<LoadSDNode>(N0)->isVolatile()) {
3618 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3619 EVT PtrType = N0.getOperand(1).getValueType();
3621 // For big endian targets, we need to adjust the offset to the pointer to
3622 // load the correct bytes.
3623 if (TLI.isBigEndian()) {
3624 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
3625 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
3626 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3629 uint64_t PtrOff = ShAmt / 8;
3630 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
3631 SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
3632 PtrType, LN0->getBasePtr(),
3633 DAG.getConstant(PtrOff, PtrType));
3634 AddToWorkList(NewPtr.getNode());
3636 SDValue Load = (ExtType == ISD::NON_EXTLOAD)
3637 ? DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
3638 LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
3639 LN0->isVolatile(), NewAlign)
3640 : DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(), NewPtr,
3641 LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
3642 ExtVT, LN0->isVolatile(), NewAlign);
3644 // Replace the old load's chain with the new load's chain.
3645 WorkListRemover DeadNodes(*this);
3646 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3649 // Return the new loaded value.
3656 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
3657 SDValue N0 = N->getOperand(0);
3658 SDValue N1 = N->getOperand(1);
3659 EVT VT = N->getValueType(0);
3660 EVT EVT = cast<VTSDNode>(N1)->getVT();
3661 unsigned VTBits = VT.getScalarType().getSizeInBits();
3662 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
3664 // fold (sext_in_reg c1) -> c1
3665 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
3666 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
3668 // If the input is already sign extended, just drop the extension.
3669 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
3672 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
3673 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3674 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
3675 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
3676 N0.getOperand(0), N1);
3679 // fold (sext_in_reg (sext x)) -> (sext x)
3680 // fold (sext_in_reg (aext x)) -> (sext x)
3681 // if x is small enough.
3682 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
3683 SDValue N00 = N0.getOperand(0);
3684 if (N00.getValueType().getScalarType().getSizeInBits() < EVTBits)
3685 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
3688 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
3689 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
3690 return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
3692 // fold operands of sext_in_reg based on knowledge that the top bits are not
3694 if (SimplifyDemandedBits(SDValue(N, 0)))
3695 return SDValue(N, 0);
3697 // fold (sext_in_reg (load x)) -> (smaller sextload x)
3698 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
3699 SDValue NarrowLoad = ReduceLoadWidth(N);
3700 if (NarrowLoad.getNode())
3703 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
3704 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
3705 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
3706 if (N0.getOpcode() == ISD::SRL) {
3707 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3708 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
3709 // We can turn this into an SRA iff the input to the SRL is already sign
3711 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
3712 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
3713 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
3714 N0.getOperand(0), N0.getOperand(1));
3718 // fold (sext_inreg (extload x)) -> (sextload x)
3719 if (ISD::isEXTLoad(N0.getNode()) &&
3720 ISD::isUNINDEXEDLoad(N0.getNode()) &&
3721 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3722 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3723 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
3724 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3725 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3727 LN0->getBasePtr(), LN0->getSrcValue(),
3728 LN0->getSrcValueOffset(), EVT,
3729 LN0->isVolatile(), LN0->getAlignment());
3730 CombineTo(N, ExtLoad);
3731 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3732 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3734 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
3735 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3737 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3738 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3739 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
3740 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3741 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3743 LN0->getBasePtr(), LN0->getSrcValue(),
3744 LN0->getSrcValueOffset(), EVT,
3745 LN0->isVolatile(), LN0->getAlignment());
3746 CombineTo(N, ExtLoad);
3747 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3748 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3753 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
3754 SDValue N0 = N->getOperand(0);
3755 EVT VT = N->getValueType(0);
3758 if (N0.getValueType() == N->getValueType(0))
3760 // fold (truncate c1) -> c1
3761 if (isa<ConstantSDNode>(N0))
3762 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
3763 // fold (truncate (truncate x)) -> (truncate x)
3764 if (N0.getOpcode() == ISD::TRUNCATE)
3765 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
3766 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
3767 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
3768 N0.getOpcode() == ISD::ANY_EXTEND) {
3769 if (N0.getOperand(0).getValueType().bitsLT(VT))
3770 // if the source is smaller than the dest, we still need an extend
3771 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
3773 else if (N0.getOperand(0).getValueType().bitsGT(VT))
3774 // if the source is larger than the dest, than we just need the truncate
3775 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
3777 // if the source and dest are the same type, we can drop both the extend
3778 // and the truncate.
3779 return N0.getOperand(0);
3782 // See if we can simplify the input to this truncate through knowledge that
3783 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
3786 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
3787 VT.getSizeInBits()));
3788 if (Shorter.getNode())
3789 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
3791 // fold (truncate (load x)) -> (smaller load x)
3792 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
3793 return ReduceLoadWidth(N);
3796 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
3797 SDValue Elt = N->getOperand(i);
3798 if (Elt.getOpcode() != ISD::MERGE_VALUES)
3799 return Elt.getNode();
3800 return Elt.getOperand(Elt.getResNo()).getNode();
3803 /// CombineConsecutiveLoads - build_pair (load, load) -> load
3804 /// if load locations are consecutive.
3805 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
3806 assert(N->getOpcode() == ISD::BUILD_PAIR);
3808 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
3809 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
3810 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse())
3812 EVT LD1VT = LD1->getValueType(0);
3814 if (ISD::isNON_EXTLoad(LD2) &&
3816 // If both are volatile this would reduce the number of volatile loads.
3817 // If one is volatile it might be ok, but play conservative and bail out.
3818 !LD1->isVolatile() &&
3819 !LD2->isVolatile() &&
3820 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
3821 unsigned Align = LD1->getAlignment();
3822 unsigned NewAlign = TLI.getTargetData()->
3823 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
3825 if (NewAlign <= Align &&
3826 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
3827 return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
3828 LD1->getBasePtr(), LD1->getSrcValue(),
3829 LD1->getSrcValueOffset(), false, Align);
3835 SDValue DAGCombiner::visitBIT_CONVERT(SDNode *N) {
3836 SDValue N0 = N->getOperand(0);
3837 EVT VT = N->getValueType(0);
3839 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
3840 // Only do this before legalize, since afterward the target may be depending
3841 // on the bitconvert.
3842 // First check to see if this is all constant.
3844 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
3846 bool isSimple = true;
3847 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
3848 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
3849 N0.getOperand(i).getOpcode() != ISD::Constant &&
3850 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
3855 EVT DestEltVT = N->getValueType(0).getVectorElementType();
3856 assert(!DestEltVT.isVector() &&
3857 "Element type of vector ValueType must not be vector!");
3859 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.getNode(), DestEltVT);
3862 // If the input is a constant, let getNode fold it.
3863 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
3864 SDValue Res = DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, N0);
3865 if (Res.getNode() != N) {
3866 if (!LegalOperations ||
3867 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
3870 // Folding it resulted in an illegal node, and it's too late to
3871 // do that. Clean up the old node and forego the transformation.
3872 // Ideally this won't happen very often, because instcombine
3873 // and the earlier dagcombine runs (where illegal nodes are
3874 // permitted) should have folded most of them already.
3875 DAG.DeleteNode(Res.getNode());
3879 // (conv (conv x, t1), t2) -> (conv x, t2)
3880 if (N0.getOpcode() == ISD::BIT_CONVERT)
3881 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT,
3884 // fold (conv (load x)) -> (load (conv*)x)
3885 // If the resultant load doesn't need a higher alignment than the original!
3886 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
3887 // Do not change the width of a volatile load.
3888 !cast<LoadSDNode>(N0)->isVolatile() &&
3889 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
3890 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3891 unsigned Align = TLI.getTargetData()->
3892 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
3893 unsigned OrigAlign = LN0->getAlignment();
3895 if (Align <= OrigAlign) {
3896 SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
3898 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3899 LN0->isVolatile(), OrigAlign);
3901 CombineTo(N0.getNode(),
3902 DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
3903 N0.getValueType(), Load),
3909 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
3910 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
3911 // This often reduces constant pool loads.
3912 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
3913 N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
3914 SDValue NewConv = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(), VT,
3916 AddToWorkList(NewConv.getNode());
3918 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3919 if (N0.getOpcode() == ISD::FNEG)
3920 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3921 NewConv, DAG.getConstant(SignBit, VT));
3922 assert(N0.getOpcode() == ISD::FABS);
3923 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3924 NewConv, DAG.getConstant(~SignBit, VT));
3927 // fold (bitconvert (fcopysign cst, x)) ->
3928 // (or (and (bitconvert x), sign), (and cst, (not sign)))
3929 // Note that we don't handle (copysign x, cst) because this can always be
3930 // folded to an fneg or fabs.
3931 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
3932 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
3933 VT.isInteger() && !VT.isVector()) {
3934 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
3935 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
3936 if (TLI.isTypeLegal(IntXVT) || !LegalTypes) {
3937 SDValue X = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
3938 IntXVT, N0.getOperand(1));
3939 AddToWorkList(X.getNode());
3941 // If X has a different width than the result/lhs, sext it or truncate it.
3942 unsigned VTWidth = VT.getSizeInBits();
3943 if (OrigXWidth < VTWidth) {
3944 X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
3945 AddToWorkList(X.getNode());
3946 } else if (OrigXWidth > VTWidth) {
3947 // To get the sign bit in the right place, we have to shift it right
3948 // before truncating.
3949 X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
3950 X.getValueType(), X,
3951 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
3952 AddToWorkList(X.getNode());
3953 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
3954 AddToWorkList(X.getNode());
3957 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3958 X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
3959 X, DAG.getConstant(SignBit, VT));
3960 AddToWorkList(X.getNode());
3962 SDValue Cst = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
3963 VT, N0.getOperand(0));
3964 Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
3965 Cst, DAG.getConstant(~SignBit, VT));
3966 AddToWorkList(Cst.getNode());
3968 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
3972 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
3973 if (N0.getOpcode() == ISD::BUILD_PAIR) {
3974 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
3975 if (CombineLD.getNode())
3982 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
3983 EVT VT = N->getValueType(0);
3984 return CombineConsecutiveLoads(N, VT);
3987 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
3988 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
3989 /// destination element value type.
3990 SDValue DAGCombiner::
3991 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
3992 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
3994 // If this is already the right type, we're done.
3995 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
3997 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
3998 unsigned DstBitSize = DstEltVT.getSizeInBits();
4000 // If this is a conversion of N elements of one type to N elements of another
4001 // type, convert each element. This handles FP<->INT cases.
4002 if (SrcBitSize == DstBitSize) {
4003 SmallVector<SDValue, 8> Ops;
4004 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4005 SDValue Op = BV->getOperand(i);
4006 // If the vector element type is not legal, the BUILD_VECTOR operands
4007 // are promoted and implicitly truncated. Make that explicit here.
4008 if (Op.getValueType() != SrcEltVT)
4009 Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
4010 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, BV->getDebugLoc(),
4012 AddToWorkList(Ops.back().getNode());
4014 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4015 BV->getValueType(0).getVectorNumElements());
4016 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4017 &Ops[0], Ops.size());
4020 // Otherwise, we're growing or shrinking the elements. To avoid having to
4021 // handle annoying details of growing/shrinking FP values, we convert them to
4023 if (SrcEltVT.isFloatingPoint()) {
4024 // Convert the input float vector to a int vector where the elements are the
4026 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
4027 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
4028 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).getNode();
4032 // Now we know the input is an integer vector. If the output is a FP type,
4033 // convert to integer first, then to FP of the right size.
4034 if (DstEltVT.isFloatingPoint()) {
4035 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
4036 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
4037 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).getNode();
4039 // Next, convert to FP elements of the same size.
4040 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
4043 // Okay, we know the src/dst types are both integers of differing types.
4044 // Handling growing first.
4045 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
4046 if (SrcBitSize < DstBitSize) {
4047 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
4049 SmallVector<SDValue, 8> Ops;
4050 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
4051 i += NumInputsPerOutput) {
4052 bool isLE = TLI.isLittleEndian();
4053 APInt NewBits = APInt(DstBitSize, 0);
4054 bool EltIsUndef = true;
4055 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
4056 // Shift the previously computed bits over.
4057 NewBits <<= SrcBitSize;
4058 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
4059 if (Op.getOpcode() == ISD::UNDEF) continue;
4062 NewBits |= (APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).
4063 zextOrTrunc(SrcBitSize).zext(DstBitSize));
4067 Ops.push_back(DAG.getUNDEF(DstEltVT));
4069 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
4072 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
4073 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4074 &Ops[0], Ops.size());
4077 // Finally, this must be the case where we are shrinking elements: each input
4078 // turns into multiple outputs.
4079 bool isS2V = ISD::isScalarToVector(BV);
4080 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
4081 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4082 NumOutputsPerInput*BV->getNumOperands());
4083 SmallVector<SDValue, 8> Ops;
4085 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4086 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
4087 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
4088 Ops.push_back(DAG.getUNDEF(DstEltVT));
4092 APInt OpVal = APInt(cast<ConstantSDNode>(BV->getOperand(i))->
4093 getAPIntValue()).zextOrTrunc(SrcBitSize);
4095 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
4096 APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
4097 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
4098 if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
4099 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
4100 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
4102 OpVal = OpVal.lshr(DstBitSize);
4105 // For big endian targets, swap the order of the pieces of each element.
4106 if (TLI.isBigEndian())
4107 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
4110 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4111 &Ops[0], Ops.size());
4114 SDValue DAGCombiner::visitFADD(SDNode *N) {
4115 SDValue N0 = N->getOperand(0);
4116 SDValue N1 = N->getOperand(1);
4117 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4118 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4119 EVT VT = N->getValueType(0);
4122 if (VT.isVector()) {
4123 SDValue FoldedVOp = SimplifyVBinOp(N);
4124 if (FoldedVOp.getNode()) return FoldedVOp;
4127 // fold (fadd c1, c2) -> (fadd c1, c2)
4128 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4129 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
4130 // canonicalize constant to RHS
4131 if (N0CFP && !N1CFP)
4132 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
4133 // fold (fadd A, 0) -> A
4134 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4136 // fold (fadd A, (fneg B)) -> (fsub A, B)
4137 if (isNegatibleForFree(N1, LegalOperations) == 2)
4138 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
4139 GetNegatedExpression(N1, DAG, LegalOperations));
4140 // fold (fadd (fneg A), B) -> (fsub B, A)
4141 if (isNegatibleForFree(N0, LegalOperations) == 2)
4142 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
4143 GetNegatedExpression(N0, DAG, LegalOperations));
4145 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
4146 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
4147 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4148 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
4149 DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
4150 N0.getOperand(1), N1));
4155 SDValue DAGCombiner::visitFSUB(SDNode *N) {
4156 SDValue N0 = N->getOperand(0);
4157 SDValue N1 = N->getOperand(1);
4158 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4159 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4160 EVT VT = N->getValueType(0);
4163 if (VT.isVector()) {
4164 SDValue FoldedVOp = SimplifyVBinOp(N);
4165 if (FoldedVOp.getNode()) return FoldedVOp;
4168 // fold (fsub c1, c2) -> c1-c2
4169 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4170 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
4171 // fold (fsub A, 0) -> A
4172 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4174 // fold (fsub 0, B) -> -B
4175 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
4176 if (isNegatibleForFree(N1, LegalOperations))
4177 return GetNegatedExpression(N1, DAG, LegalOperations);
4178 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4179 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1);
4181 // fold (fsub A, (fneg B)) -> (fadd A, B)
4182 if (isNegatibleForFree(N1, LegalOperations))
4183 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0,
4184 GetNegatedExpression(N1, DAG, LegalOperations));
4189 SDValue DAGCombiner::visitFMUL(SDNode *N) {
4190 SDValue N0 = N->getOperand(0);
4191 SDValue N1 = N->getOperand(1);
4192 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4193 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4194 EVT VT = N->getValueType(0);
4197 if (VT.isVector()) {
4198 SDValue FoldedVOp = SimplifyVBinOp(N);
4199 if (FoldedVOp.getNode()) return FoldedVOp;
4202 // fold (fmul c1, c2) -> c1*c2
4203 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4204 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
4205 // canonicalize constant to RHS
4206 if (N0CFP && !N1CFP)
4207 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
4208 // fold (fmul A, 0) -> 0
4209 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4211 // fold (fmul A, 0) -> 0, vector edition.
4212 if (UnsafeFPMath && ISD::isBuildVectorAllZeros(N1.getNode()))
4214 // fold (fmul X, 2.0) -> (fadd X, X)
4215 if (N1CFP && N1CFP->isExactlyValue(+2.0))
4216 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
4217 // fold (fmul X, -1.0) -> (fneg X)
4218 if (N1CFP && N1CFP->isExactlyValue(-1.0))
4219 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4220 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
4222 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
4223 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4224 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4225 // Both can be negated for free, check to see if at least one is cheaper
4227 if (LHSNeg == 2 || RHSNeg == 2)
4228 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4229 GetNegatedExpression(N0, DAG, LegalOperations),
4230 GetNegatedExpression(N1, DAG, LegalOperations));
4234 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
4235 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
4236 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4237 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
4238 DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4239 N0.getOperand(1), N1));
4244 SDValue DAGCombiner::visitFDIV(SDNode *N) {
4245 SDValue N0 = N->getOperand(0);
4246 SDValue N1 = N->getOperand(1);
4247 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4248 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4249 EVT VT = N->getValueType(0);
4252 if (VT.isVector()) {
4253 SDValue FoldedVOp = SimplifyVBinOp(N);
4254 if (FoldedVOp.getNode()) return FoldedVOp;
4257 // fold (fdiv c1, c2) -> c1/c2
4258 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4259 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
4262 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
4263 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4264 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4265 // Both can be negated for free, check to see if at least one is cheaper
4267 if (LHSNeg == 2 || RHSNeg == 2)
4268 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
4269 GetNegatedExpression(N0, DAG, LegalOperations),
4270 GetNegatedExpression(N1, DAG, LegalOperations));
4277 SDValue DAGCombiner::visitFREM(SDNode *N) {
4278 SDValue N0 = N->getOperand(0);
4279 SDValue N1 = N->getOperand(1);
4280 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4281 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4282 EVT VT = N->getValueType(0);
4284 // fold (frem c1, c2) -> fmod(c1,c2)
4285 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4286 return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
4291 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
4292 SDValue N0 = N->getOperand(0);
4293 SDValue N1 = N->getOperand(1);
4294 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4295 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4296 EVT VT = N->getValueType(0);
4298 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
4299 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
4302 const APFloat& V = N1CFP->getValueAPF();
4303 // copysign(x, c1) -> fabs(x) iff ispos(c1)
4304 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
4305 if (!V.isNegative()) {
4306 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
4307 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4309 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4310 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
4311 DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
4315 // copysign(fabs(x), y) -> copysign(x, y)
4316 // copysign(fneg(x), y) -> copysign(x, y)
4317 // copysign(copysign(x,z), y) -> copysign(x, y)
4318 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
4319 N0.getOpcode() == ISD::FCOPYSIGN)
4320 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4321 N0.getOperand(0), N1);
4323 // copysign(x, abs(y)) -> abs(x)
4324 if (N1.getOpcode() == ISD::FABS)
4325 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4327 // copysign(x, copysign(y,z)) -> copysign(x, z)
4328 if (N1.getOpcode() == ISD::FCOPYSIGN)
4329 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4330 N0, N1.getOperand(1));
4332 // copysign(x, fp_extend(y)) -> copysign(x, y)
4333 // copysign(x, fp_round(y)) -> copysign(x, y)
4334 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
4335 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4336 N0, N1.getOperand(0));
4341 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
4342 SDValue N0 = N->getOperand(0);
4343 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4344 EVT VT = N->getValueType(0);
4345 EVT OpVT = N0.getValueType();
4347 // fold (sint_to_fp c1) -> c1fp
4348 if (N0C && OpVT != MVT::ppcf128)
4349 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
4351 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
4352 // but UINT_TO_FP is legal on this target, try to convert.
4353 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
4354 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
4355 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
4356 if (DAG.SignBitIsZero(N0))
4357 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
4363 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
4364 SDValue N0 = N->getOperand(0);
4365 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4366 EVT VT = N->getValueType(0);
4367 EVT OpVT = N0.getValueType();
4369 // fold (uint_to_fp c1) -> c1fp
4370 if (N0C && OpVT != MVT::ppcf128)
4371 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
4373 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
4374 // but SINT_TO_FP is legal on this target, try to convert.
4375 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
4376 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
4377 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
4378 if (DAG.SignBitIsZero(N0))
4379 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
4385 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
4386 SDValue N0 = N->getOperand(0);
4387 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4388 EVT VT = N->getValueType(0);
4390 // fold (fp_to_sint c1fp) -> c1
4392 return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
4397 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
4398 SDValue N0 = N->getOperand(0);
4399 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4400 EVT VT = N->getValueType(0);
4402 // fold (fp_to_uint c1fp) -> c1
4403 if (N0CFP && VT != MVT::ppcf128)
4404 return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
4409 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
4410 SDValue N0 = N->getOperand(0);
4411 SDValue N1 = N->getOperand(1);
4412 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4413 EVT VT = N->getValueType(0);
4415 // fold (fp_round c1fp) -> c1fp
4416 if (N0CFP && N0.getValueType() != MVT::ppcf128)
4417 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
4419 // fold (fp_round (fp_extend x)) -> x
4420 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
4421 return N0.getOperand(0);
4423 // fold (fp_round (fp_round x)) -> (fp_round x)
4424 if (N0.getOpcode() == ISD::FP_ROUND) {
4425 // This is a value preserving truncation if both round's are.
4426 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
4427 N0.getNode()->getConstantOperandVal(1) == 1;
4428 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
4429 DAG.getIntPtrConstant(IsTrunc));
4432 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
4433 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
4434 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
4435 N0.getOperand(0), N1);
4436 AddToWorkList(Tmp.getNode());
4437 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4438 Tmp, N0.getOperand(1));
4444 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
4445 SDValue N0 = N->getOperand(0);
4446 EVT VT = N->getValueType(0);
4447 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4448 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4450 // fold (fp_round_inreg c1fp) -> c1fp
4451 if (N0CFP && (TLI.isTypeLegal(EVT) || !LegalTypes)) {
4452 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
4453 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
4459 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
4460 SDValue N0 = N->getOperand(0);
4461 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4462 EVT VT = N->getValueType(0);
4464 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
4465 if (N->hasOneUse() &&
4466 N->use_begin()->getOpcode() == ISD::FP_ROUND)
4469 // fold (fp_extend c1fp) -> c1fp
4470 if (N0CFP && VT != MVT::ppcf128)
4471 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
4473 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
4475 if (N0.getOpcode() == ISD::FP_ROUND
4476 && N0.getNode()->getConstantOperandVal(1) == 1) {
4477 SDValue In = N0.getOperand(0);
4478 if (In.getValueType() == VT) return In;
4479 if (VT.bitsLT(In.getValueType()))
4480 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
4481 In, N0.getOperand(1));
4482 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
4485 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
4486 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
4487 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4488 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4489 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4490 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
4492 LN0->getBasePtr(), LN0->getSrcValue(),
4493 LN0->getSrcValueOffset(),
4495 LN0->isVolatile(), LN0->getAlignment());
4496 CombineTo(N, ExtLoad);
4497 CombineTo(N0.getNode(),
4498 DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
4499 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
4500 ExtLoad.getValue(1));
4501 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4507 SDValue DAGCombiner::visitFNEG(SDNode *N) {
4508 SDValue N0 = N->getOperand(0);
4509 EVT VT = N->getValueType(0);
4511 if (isNegatibleForFree(N0, LegalOperations))
4512 return GetNegatedExpression(N0, DAG, LegalOperations);
4514 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
4515 // constant pool values.
4516 if (N0.getOpcode() == ISD::BIT_CONVERT &&
4518 N0.getNode()->hasOneUse() &&
4519 N0.getOperand(0).getValueType().isInteger()) {
4520 SDValue Int = N0.getOperand(0);
4521 EVT IntVT = Int.getValueType();
4522 if (IntVT.isInteger() && !IntVT.isVector()) {
4523 Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
4524 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
4525 AddToWorkList(Int.getNode());
4526 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
4534 SDValue DAGCombiner::visitFABS(SDNode *N) {
4535 SDValue N0 = N->getOperand(0);
4536 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4537 EVT VT = N->getValueType(0);
4539 // fold (fabs c1) -> fabs(c1)
4540 if (N0CFP && VT != MVT::ppcf128)
4541 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4542 // fold (fabs (fabs x)) -> (fabs x)
4543 if (N0.getOpcode() == ISD::FABS)
4544 return N->getOperand(0);
4545 // fold (fabs (fneg x)) -> (fabs x)
4546 // fold (fabs (fcopysign x, y)) -> (fabs x)
4547 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
4548 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
4550 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
4551 // constant pool values.
4552 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() &&
4553 N0.getOperand(0).getValueType().isInteger() &&
4554 !N0.getOperand(0).getValueType().isVector()) {
4555 SDValue Int = N0.getOperand(0);
4556 EVT IntVT = Int.getValueType();
4557 if (IntVT.isInteger() && !IntVT.isVector()) {
4558 Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
4559 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
4560 AddToWorkList(Int.getNode());
4561 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
4562 N->getValueType(0), Int);
4569 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
4570 SDValue Chain = N->getOperand(0);
4571 SDValue N1 = N->getOperand(1);
4572 SDValue N2 = N->getOperand(2);
4574 // If N is a constant we could fold this into a fallthrough or unconditional
4575 // branch. However that doesn't happen very often in normal code, because
4576 // Instcombine/SimplifyCFG should have handled the available opportunities.
4577 // If we did this folding here, it would be necessary to update the
4578 // MachineBasicBlock CFG, which is awkward.
4580 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
4582 if (N1.getOpcode() == ISD::SETCC &&
4583 TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
4584 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
4585 Chain, N1.getOperand(2),
4586 N1.getOperand(0), N1.getOperand(1), N2);
4590 if (N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) {
4591 // Look pass truncate.
4592 Trunc = N1.getNode();
4593 N1 = N1.getOperand(0);
4596 if (N1.hasOneUse() && N1.getOpcode() == ISD::SRL) {
4597 // Match this pattern so that we can generate simpler code:
4600 // %b = and i32 %a, 2
4601 // %c = srl i32 %b, 1
4602 // brcond i32 %c ...
4607 // %b = and i32 %a, 2
4608 // %c = setcc eq %b, 0
4611 // This applies only when the AND constant value has one bit set and the
4612 // SRL constant is equal to the log2 of the AND constant. The back-end is
4613 // smart enough to convert the result into a TEST/JMP sequence.
4614 SDValue Op0 = N1.getOperand(0);
4615 SDValue Op1 = N1.getOperand(1);
4617 if (Op0.getOpcode() == ISD::AND &&
4618 Op1.getOpcode() == ISD::Constant) {
4619 SDValue AndOp1 = Op0.getOperand(1);
4621 if (AndOp1.getOpcode() == ISD::Constant) {
4622 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
4624 if (AndConst.isPowerOf2() &&
4625 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
4627 DAG.getSetCC(N->getDebugLoc(),
4628 TLI.getSetCCResultType(Op0.getValueType()),
4629 Op0, DAG.getConstant(0, Op0.getValueType()),
4632 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
4633 MVT::Other, Chain, SetCC, N2);
4634 // Don't add the new BRCond into the worklist or else SimplifySelectCC
4635 // will convert it back to (X & C1) >> C2.
4636 CombineTo(N, NewBRCond, false);
4637 // Truncate is dead.
4639 removeFromWorkList(Trunc);
4640 DAG.DeleteNode(Trunc);
4642 // Replace the uses of SRL with SETCC
4643 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
4644 removeFromWorkList(N1.getNode());
4645 DAG.DeleteNode(N1.getNode());
4646 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4655 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
4657 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
4658 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
4659 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
4661 // If N is a constant we could fold this into a fallthrough or unconditional
4662 // branch. However that doesn't happen very often in normal code, because
4663 // Instcombine/SimplifyCFG should have handled the available opportunities.
4664 // If we did this folding here, it would be necessary to update the
4665 // MachineBasicBlock CFG, which is awkward.
4667 // Use SimplifySetCC to simplify SETCC's.
4668 SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
4669 CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
4671 if (Simp.getNode()) AddToWorkList(Simp.getNode());
4673 // fold to a simpler setcc
4674 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
4675 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
4676 N->getOperand(0), Simp.getOperand(2),
4677 Simp.getOperand(0), Simp.getOperand(1),
4683 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
4684 /// pre-indexed load / store when the base pointer is an add or subtract
4685 /// and it has other uses besides the load / store. After the
4686 /// transformation, the new indexed load / store has effectively folded
4687 /// the add / subtract in and all of its other uses are redirected to the
4688 /// new load / store.
4689 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
4690 if (!LegalOperations)
4696 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4697 if (LD->isIndexed())
4699 VT = LD->getMemoryVT();
4700 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
4701 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
4703 Ptr = LD->getBasePtr();
4704 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4705 if (ST->isIndexed())
4707 VT = ST->getMemoryVT();
4708 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
4709 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
4711 Ptr = ST->getBasePtr();
4717 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
4718 // out. There is no reason to make this a preinc/predec.
4719 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
4720 Ptr.getNode()->hasOneUse())
4723 // Ask the target to do addressing mode selection.
4726 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4727 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
4729 // Don't create a indexed load / store with zero offset.
4730 if (isa<ConstantSDNode>(Offset) &&
4731 cast<ConstantSDNode>(Offset)->isNullValue())
4734 // Try turning it into a pre-indexed load / store except when:
4735 // 1) The new base ptr is a frame index.
4736 // 2) If N is a store and the new base ptr is either the same as or is a
4737 // predecessor of the value being stored.
4738 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
4739 // that would create a cycle.
4740 // 4) All uses are load / store ops that use it as old base ptr.
4742 // Check #1. Preinc'ing a frame index would require copying the stack pointer
4743 // (plus the implicit offset) to a register to preinc anyway.
4744 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
4749 SDValue Val = cast<StoreSDNode>(N)->getValue();
4750 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
4754 // Now check for #3 and #4.
4755 bool RealUse = false;
4756 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
4757 E = Ptr.getNode()->use_end(); I != E; ++I) {
4761 if (Use->isPredecessorOf(N))
4764 if (!((Use->getOpcode() == ISD::LOAD &&
4765 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
4766 (Use->getOpcode() == ISD::STORE &&
4767 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
4776 Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
4777 BasePtr, Offset, AM);
4779 Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
4780 BasePtr, Offset, AM);
4783 DEBUG(dbgs() << "\nReplacing.4 ";
4785 dbgs() << "\nWith: ";
4786 Result.getNode()->dump(&DAG);
4788 WorkListRemover DeadNodes(*this);
4790 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
4792 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
4795 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
4799 // Finally, since the node is now dead, remove it from the graph.
4802 // Replace the uses of Ptr with uses of the updated base value.
4803 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
4805 removeFromWorkList(Ptr.getNode());
4806 DAG.DeleteNode(Ptr.getNode());
4811 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
4812 /// add / sub of the base pointer node into a post-indexed load / store.
4813 /// The transformation folded the add / subtract into the new indexed
4814 /// load / store effectively and all of its uses are redirected to the
4815 /// new load / store.
4816 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
4817 if (!LegalOperations)
4823 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4824 if (LD->isIndexed())
4826 VT = LD->getMemoryVT();
4827 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
4828 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
4830 Ptr = LD->getBasePtr();
4831 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4832 if (ST->isIndexed())
4834 VT = ST->getMemoryVT();
4835 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
4836 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
4838 Ptr = ST->getBasePtr();
4844 if (Ptr.getNode()->hasOneUse())
4847 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
4848 E = Ptr.getNode()->use_end(); I != E; ++I) {
4851 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
4856 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4857 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
4858 if (Ptr == Offset && Op->getOpcode() == ISD::ADD)
4859 std::swap(BasePtr, Offset);
4862 // Don't create a indexed load / store with zero offset.
4863 if (isa<ConstantSDNode>(Offset) &&
4864 cast<ConstantSDNode>(Offset)->isNullValue())
4867 // Try turning it into a post-indexed load / store except when
4868 // 1) All uses are load / store ops that use it as base ptr.
4869 // 2) Op must be independent of N, i.e. Op is neither a predecessor
4870 // nor a successor of N. Otherwise, if Op is folded that would
4873 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
4877 bool TryNext = false;
4878 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
4879 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
4881 if (Use == Ptr.getNode())
4884 // If all the uses are load / store addresses, then don't do the
4886 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
4887 bool RealUse = false;
4888 for (SDNode::use_iterator III = Use->use_begin(),
4889 EEE = Use->use_end(); III != EEE; ++III) {
4890 SDNode *UseUse = *III;
4891 if (!((UseUse->getOpcode() == ISD::LOAD &&
4892 cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) ||
4893 (UseUse->getOpcode() == ISD::STORE &&
4894 cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use)))
4909 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
4910 SDValue Result = isLoad
4911 ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
4912 BasePtr, Offset, AM)
4913 : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
4914 BasePtr, Offset, AM);
4917 DEBUG(dbgs() << "\nReplacing.5 ";
4919 dbgs() << "\nWith: ";
4920 Result.getNode()->dump(&DAG);
4922 WorkListRemover DeadNodes(*this);
4924 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
4926 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
4929 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
4933 // Finally, since the node is now dead, remove it from the graph.
4936 // Replace the uses of Use with uses of the updated base value.
4937 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
4938 Result.getValue(isLoad ? 1 : 0),
4940 removeFromWorkList(Op);
4950 SDValue DAGCombiner::visitLOAD(SDNode *N) {
4951 LoadSDNode *LD = cast<LoadSDNode>(N);
4952 SDValue Chain = LD->getChain();
4953 SDValue Ptr = LD->getBasePtr();
4955 // Try to infer better alignment information than the load already has.
4956 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
4957 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
4958 if (Align > LD->getAlignment())
4959 return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
4960 LD->getValueType(0),
4961 Chain, Ptr, LD->getSrcValue(),
4962 LD->getSrcValueOffset(), LD->getMemoryVT(),
4963 LD->isVolatile(), Align);
4967 // If load is not volatile and there are no uses of the loaded value (and
4968 // the updated indexed value in case of indexed loads), change uses of the
4969 // chain value into uses of the chain input (i.e. delete the dead load).
4970 if (!LD->isVolatile()) {
4971 if (N->getValueType(1) == MVT::Other) {
4973 if (N->hasNUsesOfValue(0, 0)) {
4974 // It's not safe to use the two value CombineTo variant here. e.g.
4975 // v1, chain2 = load chain1, loc
4976 // v2, chain3 = load chain2, loc
4978 // Now we replace use of chain2 with chain1. This makes the second load
4979 // isomorphic to the one we are deleting, and thus makes this load live.
4980 DEBUG(dbgs() << "\nReplacing.6 ";
4982 dbgs() << "\nWith chain: ";
4983 Chain.getNode()->dump(&DAG);
4985 WorkListRemover DeadNodes(*this);
4986 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes);
4988 if (N->use_empty()) {
4989 removeFromWorkList(N);
4993 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4997 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
4998 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
4999 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
5000 DEBUG(dbgs() << "\nReplacing.6 ";
5002 dbgs() << "\nWith: ";
5003 Undef.getNode()->dump(&DAG);
5004 dbgs() << " and 2 other values\n");
5005 WorkListRemover DeadNodes(*this);
5006 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes);
5007 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
5008 DAG.getUNDEF(N->getValueType(1)),
5010 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes);
5011 removeFromWorkList(N);
5013 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5018 // If this load is directly stored, replace the load value with the stored
5020 // TODO: Handle store large -> read small portion.
5021 // TODO: Handle TRUNCSTORE/LOADEXT
5022 if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
5023 !LD->isVolatile()) {
5024 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
5025 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
5026 if (PrevST->getBasePtr() == Ptr &&
5027 PrevST->getValue().getValueType() == N->getValueType(0))
5028 return CombineTo(N, Chain.getOperand(1), Chain);
5033 // Walk up chain skipping non-aliasing memory nodes.
5034 SDValue BetterChain = FindBetterChain(N, Chain);
5036 // If there is a better chain.
5037 if (Chain != BetterChain) {
5040 // Replace the chain to void dependency.
5041 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
5042 ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
5044 LD->getSrcValue(), LD->getSrcValueOffset(),
5045 LD->isVolatile(), LD->getAlignment());
5047 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
5048 LD->getValueType(0),
5049 BetterChain, Ptr, LD->getSrcValue(),
5050 LD->getSrcValueOffset(),
5053 LD->getAlignment());
5056 // Create token factor to keep old chain connected.
5057 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
5058 MVT::Other, Chain, ReplLoad.getValue(1));
5060 // Make sure the new and old chains are cleaned up.
5061 AddToWorkList(Token.getNode());
5063 // Replace uses with load result and token factor. Don't add users
5065 return CombineTo(N, ReplLoad.getValue(0), Token, false);
5069 // Try transforming N to an indexed load.
5070 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
5071 return SDValue(N, 0);
5077 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
5078 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
5079 /// of the loaded bits, try narrowing the load and store if it would end up
5080 /// being a win for performance or code size.
5081 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
5082 StoreSDNode *ST = cast<StoreSDNode>(N);
5083 if (ST->isVolatile())
5086 SDValue Chain = ST->getChain();
5087 SDValue Value = ST->getValue();
5088 SDValue Ptr = ST->getBasePtr();
5089 EVT VT = Value.getValueType();
5091 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
5094 unsigned Opc = Value.getOpcode();
5095 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
5096 Value.getOperand(1).getOpcode() != ISD::Constant)
5099 SDValue N0 = Value.getOperand(0);
5100 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
5101 LoadSDNode *LD = cast<LoadSDNode>(N0);
5102 if (LD->getBasePtr() != Ptr)
5105 // Find the type to narrow it the load / op / store to.
5106 SDValue N1 = Value.getOperand(1);
5107 unsigned BitWidth = N1.getValueSizeInBits();
5108 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
5109 if (Opc == ISD::AND)
5110 Imm ^= APInt::getAllOnesValue(BitWidth);
5111 if (Imm == 0 || Imm.isAllOnesValue())
5113 unsigned ShAmt = Imm.countTrailingZeros();
5114 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
5115 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
5116 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
5117 while (NewBW < BitWidth &&
5118 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
5119 TLI.isNarrowingProfitable(VT, NewVT))) {
5120 NewBW = NextPowerOf2(NewBW);
5121 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
5123 if (NewBW >= BitWidth)
5126 // If the lsb changed does not start at the type bitwidth boundary,
5127 // start at the previous one.
5129 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
5130 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
5131 if ((Imm & Mask) == Imm) {
5132 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
5133 if (Opc == ISD::AND)
5134 NewImm ^= APInt::getAllOnesValue(NewBW);
5135 uint64_t PtrOff = ShAmt / 8;
5136 // For big endian targets, we need to adjust the offset to the pointer to
5137 // load the correct bytes.
5138 if (TLI.isBigEndian())
5139 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
5141 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
5143 TLI.getTargetData()->getABITypeAlignment(NewVT.getTypeForEVT(*DAG.getContext())))
5146 SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
5147 Ptr.getValueType(), Ptr,
5148 DAG.getConstant(PtrOff, Ptr.getValueType()));
5149 SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
5150 LD->getChain(), NewPtr,
5151 LD->getSrcValue(), LD->getSrcValueOffset(),
5152 LD->isVolatile(), NewAlign);
5153 SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
5154 DAG.getConstant(NewImm, NewVT));
5155 SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
5157 ST->getSrcValue(), ST->getSrcValueOffset(),
5160 AddToWorkList(NewPtr.getNode());
5161 AddToWorkList(NewLD.getNode());
5162 AddToWorkList(NewVal.getNode());
5163 WorkListRemover DeadNodes(*this);
5164 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1),
5174 SDValue DAGCombiner::visitSTORE(SDNode *N) {
5175 StoreSDNode *ST = cast<StoreSDNode>(N);
5176 SDValue Chain = ST->getChain();
5177 SDValue Value = ST->getValue();
5178 SDValue Ptr = ST->getBasePtr();
5180 // Try to infer better alignment information than the store already has.
5181 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
5182 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
5183 if (Align > ST->getAlignment())
5184 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
5185 Ptr, ST->getSrcValue(),
5186 ST->getSrcValueOffset(), ST->getMemoryVT(),
5187 ST->isVolatile(), Align);
5191 // If this is a store of a bit convert, store the input value if the
5192 // resultant store does not need a higher alignment than the original.
5193 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
5194 ST->isUnindexed()) {
5195 unsigned OrigAlign = ST->getAlignment();
5196 EVT SVT = Value.getOperand(0).getValueType();
5197 unsigned Align = TLI.getTargetData()->
5198 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
5199 if (Align <= OrigAlign &&
5200 ((!LegalOperations && !ST->isVolatile()) ||
5201 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
5202 return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
5203 Ptr, ST->getSrcValue(),
5204 ST->getSrcValueOffset(), ST->isVolatile(), OrigAlign);
5207 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
5208 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
5209 // NOTE: If the original store is volatile, this transform must not increase
5210 // the number of stores. For example, on x86-32 an f64 can be stored in one
5211 // processor operation but an i64 (which is not legal) requires two. So the
5212 // transform should not be done in this case.
5213 if (Value.getOpcode() != ISD::TargetConstantFP) {
5215 switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
5216 default: llvm_unreachable("Unknown FP type");
5217 case MVT::f80: // We don't do this for these yet.
5222 if (((TLI.isTypeLegal(MVT::i32) || !LegalTypes) && !LegalOperations &&
5223 !ST->isVolatile()) ||
5224 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
5225 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
5226 bitcastToAPInt().getZExtValue(), MVT::i32);
5227 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
5228 Ptr, ST->getSrcValue(),
5229 ST->getSrcValueOffset(), ST->isVolatile(),
5230 ST->getAlignment());
5234 if (((TLI.isTypeLegal(MVT::i64) || !LegalTypes) && !LegalOperations &&
5235 !ST->isVolatile()) ||
5236 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
5237 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
5238 getZExtValue(), MVT::i64);
5239 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
5240 Ptr, ST->getSrcValue(),
5241 ST->getSrcValueOffset(), ST->isVolatile(),
5242 ST->getAlignment());
5243 } else if (!ST->isVolatile() &&
5244 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
5245 // Many FP stores are not made apparent until after legalize, e.g. for
5246 // argument passing. Since this is so common, custom legalize the
5247 // 64-bit integer store into two 32-bit stores.
5248 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
5249 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
5250 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
5251 if (TLI.isBigEndian()) std::swap(Lo, Hi);
5253 int SVOffset = ST->getSrcValueOffset();
5254 unsigned Alignment = ST->getAlignment();
5255 bool isVolatile = ST->isVolatile();
5257 SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
5258 Ptr, ST->getSrcValue(),
5259 ST->getSrcValueOffset(),
5260 isVolatile, ST->getAlignment());
5261 Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
5262 DAG.getConstant(4, Ptr.getValueType()));
5264 Alignment = MinAlign(Alignment, 4U);
5265 SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
5266 Ptr, ST->getSrcValue(),
5267 SVOffset, isVolatile, Alignment);
5268 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
5278 // Walk up chain skipping non-aliasing memory nodes.
5279 SDValue BetterChain = FindBetterChain(N, Chain);
5281 // If there is a better chain.
5282 if (Chain != BetterChain) {
5285 // Replace the chain to avoid dependency.
5286 if (ST->isTruncatingStore()) {
5287 ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
5288 ST->getSrcValue(),ST->getSrcValueOffset(),
5290 ST->isVolatile(), ST->getAlignment());
5292 ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
5293 ST->getSrcValue(), ST->getSrcValueOffset(),
5294 ST->isVolatile(), ST->getAlignment());
5297 // Create token to keep both nodes around.
5298 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
5299 MVT::Other, Chain, ReplStore);
5301 // Make sure the new and old chains are cleaned up.
5302 AddToWorkList(Token.getNode());
5304 // Don't add users to work list.
5305 return CombineTo(N, Token, false);
5309 // Try transforming N to an indexed store.
5310 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
5311 return SDValue(N, 0);
5313 // FIXME: is there such a thing as a truncating indexed store?
5314 if (ST->isTruncatingStore() && ST->isUnindexed() &&
5315 Value.getValueType().isInteger()) {
5316 // See if we can simplify the input to this truncstore with knowledge that
5317 // only the low bits are being used. For example:
5318 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
5320 GetDemandedBits(Value,
5321 APInt::getLowBitsSet(Value.getValueSizeInBits(),
5322 ST->getMemoryVT().getSizeInBits()));
5323 AddToWorkList(Value.getNode());
5324 if (Shorter.getNode())
5325 return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
5326 Ptr, ST->getSrcValue(),
5327 ST->getSrcValueOffset(), ST->getMemoryVT(),
5328 ST->isVolatile(), ST->getAlignment());
5330 // Otherwise, see if we can simplify the operation with
5331 // SimplifyDemandedBits, which only works if the value has a single use.
5332 if (SimplifyDemandedBits(Value,
5333 APInt::getLowBitsSet(
5334 Value.getValueType().getScalarType().getSizeInBits(),
5335 ST->getMemoryVT().getSizeInBits())))
5336 return SDValue(N, 0);
5339 // If this is a load followed by a store to the same location, then the store
5341 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
5342 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
5343 ST->isUnindexed() && !ST->isVolatile() &&
5344 // There can't be any side effects between the load and store, such as
5346 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
5347 // The store is dead, remove it.
5352 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
5353 // truncating store. We can do this even if this is already a truncstore.
5354 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
5355 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
5356 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
5357 ST->getMemoryVT())) {
5358 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
5359 Ptr, ST->getSrcValue(),
5360 ST->getSrcValueOffset(), ST->getMemoryVT(),
5361 ST->isVolatile(), ST->getAlignment());
5364 return ReduceLoadOpStoreWidth(N);
5367 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
5368 SDValue InVec = N->getOperand(0);
5369 SDValue InVal = N->getOperand(1);
5370 SDValue EltNo = N->getOperand(2);
5372 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
5373 // vector with the inserted element.
5374 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
5375 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5376 SmallVector<SDValue, 8> Ops(InVec.getNode()->op_begin(),
5377 InVec.getNode()->op_end());
5378 if (Elt < Ops.size())
5380 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5381 InVec.getValueType(), &Ops[0], Ops.size());
5383 // If the invec is an UNDEF and if EltNo is a constant, create a new
5384 // BUILD_VECTOR with undef elements and the inserted element.
5385 if (!LegalOperations && InVec.getOpcode() == ISD::UNDEF &&
5386 isa<ConstantSDNode>(EltNo)) {
5387 EVT VT = InVec.getValueType();
5388 EVT EltVT = VT.getVectorElementType();
5389 unsigned NElts = VT.getVectorNumElements();
5390 SmallVector<SDValue, 8> Ops(NElts, DAG.getUNDEF(EltVT));
5392 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5393 if (Elt < Ops.size())
5395 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5396 InVec.getValueType(), &Ops[0], Ops.size());
5401 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
5402 // (vextract (scalar_to_vector val, 0) -> val
5403 SDValue InVec = N->getOperand(0);
5405 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5406 // Check if the result type doesn't match the inserted element type. A
5407 // SCALAR_TO_VECTOR may truncate the inserted element and the
5408 // EXTRACT_VECTOR_ELT may widen the extracted vector.
5409 EVT EltVT = InVec.getValueType().getVectorElementType();
5410 SDValue InOp = InVec.getOperand(0);
5411 EVT NVT = N->getValueType(0);
5412 if (InOp.getValueType() != NVT) {
5413 assert(InOp.getValueType().isInteger() && NVT.isInteger());
5414 return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
5419 // Perform only after legalization to ensure build_vector / vector_shuffle
5420 // optimizations have already been done.
5421 if (!LegalOperations) return SDValue();
5423 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
5424 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
5425 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
5426 SDValue EltNo = N->getOperand(1);
5428 if (isa<ConstantSDNode>(EltNo)) {
5429 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5430 bool NewLoad = false;
5431 bool BCNumEltsChanged = false;
5432 EVT VT = InVec.getValueType();
5433 EVT ExtVT = VT.getVectorElementType();
5436 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
5437 EVT BCVT = InVec.getOperand(0).getValueType();
5438 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
5440 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
5441 BCNumEltsChanged = true;
5442 InVec = InVec.getOperand(0);
5443 ExtVT = BCVT.getVectorElementType();
5447 LoadSDNode *LN0 = NULL;
5448 const ShuffleVectorSDNode *SVN = NULL;
5449 if (ISD::isNormalLoad(InVec.getNode())) {
5450 LN0 = cast<LoadSDNode>(InVec);
5451 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5452 InVec.getOperand(0).getValueType() == ExtVT &&
5453 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
5454 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
5455 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
5456 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
5458 // (load $addr+1*size)
5460 // If the bit convert changed the number of elements, it is unsafe
5461 // to examine the mask.
5462 if (BCNumEltsChanged)
5465 // Select the input vector, guarding against out of range extract vector.
5466 unsigned NumElems = VT.getVectorNumElements();
5467 int Idx = (Elt > NumElems) ? -1 : SVN->getMaskElt(Elt);
5468 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
5470 if (InVec.getOpcode() == ISD::BIT_CONVERT)
5471 InVec = InVec.getOperand(0);
5472 if (ISD::isNormalLoad(InVec.getNode())) {
5473 LN0 = cast<LoadSDNode>(InVec);
5474 Elt = (Idx < (int)NumElems) ? Idx : Idx - NumElems;
5478 if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
5481 unsigned Align = LN0->getAlignment();
5483 // Check the resultant load doesn't need a higher alignment than the
5486 TLI.getTargetData()->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
5488 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
5494 SDValue NewPtr = LN0->getBasePtr();
5496 unsigned PtrOff = LVT.getSizeInBits() * Elt / 8;
5497 EVT PtrType = NewPtr.getValueType();
5498 if (TLI.isBigEndian())
5499 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
5500 NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
5501 DAG.getConstant(PtrOff, PtrType));
5504 return DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
5505 LN0->getSrcValue(), LN0->getSrcValueOffset(),
5506 LN0->isVolatile(), Align);
5512 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
5513 unsigned NumInScalars = N->getNumOperands();
5514 EVT VT = N->getValueType(0);
5516 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
5517 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
5518 // at most two distinct vectors, turn this into a shuffle node.
5519 SDValue VecIn1, VecIn2;
5520 for (unsigned i = 0; i != NumInScalars; ++i) {
5521 // Ignore undef inputs.
5522 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
5524 // If this input is something other than a EXTRACT_VECTOR_ELT with a
5525 // constant index, bail out.
5526 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5527 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
5528 VecIn1 = VecIn2 = SDValue(0, 0);
5532 // If the input vector type disagrees with the result of the build_vector,
5533 // we can't make a shuffle.
5534 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
5535 if (ExtractedFromVec.getValueType() != VT) {
5536 VecIn1 = VecIn2 = SDValue(0, 0);
5540 // Otherwise, remember this. We allow up to two distinct input vectors.
5541 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
5544 if (VecIn1.getNode() == 0) {
5545 VecIn1 = ExtractedFromVec;
5546 } else if (VecIn2.getNode() == 0) {
5547 VecIn2 = ExtractedFromVec;
5550 VecIn1 = VecIn2 = SDValue(0, 0);
5555 // If everything is good, we can make a shuffle operation.
5556 if (VecIn1.getNode()) {
5557 SmallVector<int, 8> Mask;
5558 for (unsigned i = 0; i != NumInScalars; ++i) {
5559 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
5564 // If extracting from the first vector, just use the index directly.
5565 SDValue Extract = N->getOperand(i);
5566 SDValue ExtVal = Extract.getOperand(1);
5567 if (Extract.getOperand(0) == VecIn1) {
5568 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
5569 if (ExtIndex > VT.getVectorNumElements())
5572 Mask.push_back(ExtIndex);
5576 // Otherwise, use InIdx + VecSize
5577 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
5578 Mask.push_back(Idx+NumInScalars);
5581 // Add count and size info.
5582 if (!TLI.isTypeLegal(VT) && LegalTypes)
5585 // Return the new VECTOR_SHUFFLE node.
5588 Ops[1] = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5589 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
5595 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
5596 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
5597 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
5598 // inputs come from at most two distinct vectors, turn this into a shuffle
5601 // If we only have one input vector, we don't need to do any concatenation.
5602 if (N->getNumOperands() == 1)
5603 return N->getOperand(0);
5608 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
5611 EVT VT = N->getValueType(0);
5612 unsigned NumElts = VT.getVectorNumElements();
5614 SDValue N0 = N->getOperand(0);
5616 assert(N0.getValueType().getVectorNumElements() == NumElts &&
5617 "Vector shuffle must be normalized in DAG");
5619 // FIXME: implement canonicalizations from DAG.getVectorShuffle()
5621 // If it is a splat, check if the argument vector is a build_vector with
5622 // all scalar elements the same.
5623 if (cast<ShuffleVectorSDNode>(N)->isSplat()) {
5624 SDNode *V = N0.getNode();
5627 // If this is a bit convert that changes the element type of the vector but
5628 // not the number of vector elements, look through it. Be careful not to
5629 // look though conversions that change things like v4f32 to v2f64.
5630 if (V->getOpcode() == ISD::BIT_CONVERT) {
5631 SDValue ConvInput = V->getOperand(0);
5632 if (ConvInput.getValueType().isVector() &&
5633 ConvInput.getValueType().getVectorNumElements() == NumElts)
5634 V = ConvInput.getNode();
5637 if (V->getOpcode() == ISD::BUILD_VECTOR) {
5638 unsigned NumElems = V->getNumOperands();
5639 unsigned BaseIdx = cast<ShuffleVectorSDNode>(N)->getSplatIndex();
5640 if (NumElems > BaseIdx) {
5642 bool AllSame = true;
5643 for (unsigned i = 0; i != NumElems; ++i) {
5644 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
5645 Base = V->getOperand(i);
5649 // Splat of <u, u, u, u>, return <u, u, u, u>
5650 if (!Base.getNode())
5652 for (unsigned i = 0; i != NumElems; ++i) {
5653 if (V->getOperand(i) != Base) {
5658 // Splat of <x, x, x, x>, return <x, x, x, x>
5667 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
5668 /// an AND to a vector_shuffle with the destination vector and a zero vector.
5669 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
5670 /// vector_shuffle V, Zero, <0, 4, 2, 4>
5671 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
5672 EVT VT = N->getValueType(0);
5673 DebugLoc dl = N->getDebugLoc();
5674 SDValue LHS = N->getOperand(0);
5675 SDValue RHS = N->getOperand(1);
5676 if (N->getOpcode() == ISD::AND) {
5677 if (RHS.getOpcode() == ISD::BIT_CONVERT)
5678 RHS = RHS.getOperand(0);
5679 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
5680 SmallVector<int, 8> Indices;
5681 unsigned NumElts = RHS.getNumOperands();
5682 for (unsigned i = 0; i != NumElts; ++i) {
5683 SDValue Elt = RHS.getOperand(i);
5684 if (!isa<ConstantSDNode>(Elt))
5686 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
5687 Indices.push_back(i);
5688 else if (cast<ConstantSDNode>(Elt)->isNullValue())
5689 Indices.push_back(NumElts);
5694 // Let's see if the target supports this vector_shuffle.
5695 EVT RVT = RHS.getValueType();
5696 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
5699 // Return the new VECTOR_SHUFFLE node.
5700 EVT EltVT = RVT.getVectorElementType();
5701 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
5702 DAG.getConstant(0, EltVT));
5703 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5704 RVT, &ZeroOps[0], ZeroOps.size());
5705 LHS = DAG.getNode(ISD::BIT_CONVERT, dl, RVT, LHS);
5706 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
5707 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuf);
5714 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
5715 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
5716 // After legalize, the target may be depending on adds and other
5717 // binary ops to provide legal ways to construct constants or other
5718 // things. Simplifying them may result in a loss of legality.
5719 if (LegalOperations) return SDValue();
5721 EVT VT = N->getValueType(0);
5722 assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
5724 EVT EltType = VT.getVectorElementType();
5725 SDValue LHS = N->getOperand(0);
5726 SDValue RHS = N->getOperand(1);
5727 SDValue Shuffle = XformToShuffleWithZero(N);
5728 if (Shuffle.getNode()) return Shuffle;
5730 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
5732 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
5733 RHS.getOpcode() == ISD::BUILD_VECTOR) {
5734 SmallVector<SDValue, 8> Ops;
5735 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
5736 SDValue LHSOp = LHS.getOperand(i);
5737 SDValue RHSOp = RHS.getOperand(i);
5738 // If these two elements can't be folded, bail out.
5739 if ((LHSOp.getOpcode() != ISD::UNDEF &&
5740 LHSOp.getOpcode() != ISD::Constant &&
5741 LHSOp.getOpcode() != ISD::ConstantFP) ||
5742 (RHSOp.getOpcode() != ISD::UNDEF &&
5743 RHSOp.getOpcode() != ISD::Constant &&
5744 RHSOp.getOpcode() != ISD::ConstantFP))
5747 // Can't fold divide by zero.
5748 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
5749 N->getOpcode() == ISD::FDIV) {
5750 if ((RHSOp.getOpcode() == ISD::Constant &&
5751 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
5752 (RHSOp.getOpcode() == ISD::ConstantFP &&
5753 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
5757 Ops.push_back(DAG.getNode(N->getOpcode(), LHS.getDebugLoc(),
5758 EltType, LHSOp, RHSOp));
5759 AddToWorkList(Ops.back().getNode());
5760 assert((Ops.back().getOpcode() == ISD::UNDEF ||
5761 Ops.back().getOpcode() == ISD::Constant ||
5762 Ops.back().getOpcode() == ISD::ConstantFP) &&
5763 "Scalar binop didn't fold!");
5766 if (Ops.size() == LHS.getNumOperands()) {
5767 EVT VT = LHS.getValueType();
5768 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
5769 &Ops[0], Ops.size());
5776 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
5777 SDValue N1, SDValue N2){
5778 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
5780 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
5781 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5783 // If we got a simplified select_cc node back from SimplifySelectCC, then
5784 // break it down into a new SETCC node, and a new SELECT node, and then return
5785 // the SELECT node, since we were called with a SELECT node.
5786 if (SCC.getNode()) {
5787 // Check to see if we got a select_cc back (to turn into setcc/select).
5788 // Otherwise, just return whatever node we got back, like fabs.
5789 if (SCC.getOpcode() == ISD::SELECT_CC) {
5790 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
5792 SCC.getOperand(0), SCC.getOperand(1),
5794 AddToWorkList(SETCC.getNode());
5795 return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
5796 SCC.getOperand(2), SCC.getOperand(3), SETCC);
5804 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
5805 /// are the two values being selected between, see if we can simplify the
5806 /// select. Callers of this should assume that TheSelect is deleted if this
5807 /// returns true. As such, they should return the appropriate thing (e.g. the
5808 /// node) back to the top-level of the DAG combiner loop to avoid it being
5810 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
5813 // If this is a select from two identical things, try to pull the operation
5814 // through the select.
5815 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
5816 // If this is a load and the token chain is identical, replace the select
5817 // of two loads with a load through a select of the address to load from.
5818 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
5819 // constants have been dropped into the constant pool.
5820 if (LHS.getOpcode() == ISD::LOAD &&
5821 // Do not let this transformation reduce the number of volatile loads.
5822 !cast<LoadSDNode>(LHS)->isVolatile() &&
5823 !cast<LoadSDNode>(RHS)->isVolatile() &&
5824 // Token chains must be identical.
5825 LHS.getOperand(0) == RHS.getOperand(0)) {
5826 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
5827 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
5829 // If this is an EXTLOAD, the VT's must match.
5830 if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
5831 // FIXME: this discards src value information. This is
5832 // over-conservative. It would be beneficial to be able to remember
5833 // both potential memory locations. Since we are discarding
5834 // src value info, don't do the transformation if the memory
5835 // locations are not in the default address space.
5836 unsigned LLDAddrSpace = 0, RLDAddrSpace = 0;
5837 if (const Value *LLDVal = LLD->getMemOperand()->getValue()) {
5838 if (const PointerType *PT = dyn_cast<PointerType>(LLDVal->getType()))
5839 LLDAddrSpace = PT->getAddressSpace();
5841 if (const Value *RLDVal = RLD->getMemOperand()->getValue()) {
5842 if (const PointerType *PT = dyn_cast<PointerType>(RLDVal->getType()))
5843 RLDAddrSpace = PT->getAddressSpace();
5846 if (LLDAddrSpace == 0 && RLDAddrSpace == 0) {
5847 if (TheSelect->getOpcode() == ISD::SELECT) {
5848 // Check that the condition doesn't reach either load. If so, folding
5849 // this will induce a cycle into the DAG.
5850 if ((!LLD->hasAnyUseOfValue(1) ||
5851 !LLD->isPredecessorOf(TheSelect->getOperand(0).getNode())) &&
5852 (!RLD->hasAnyUseOfValue(1) ||
5853 !RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()))) {
5854 Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
5855 LLD->getBasePtr().getValueType(),
5856 TheSelect->getOperand(0), LLD->getBasePtr(),
5860 // Check that the condition doesn't reach either load. If so, folding
5861 // this will induce a cycle into the DAG.
5862 if ((!LLD->hasAnyUseOfValue(1) ||
5863 (!LLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
5864 !LLD->isPredecessorOf(TheSelect->getOperand(1).getNode()))) &&
5865 (!RLD->hasAnyUseOfValue(1) ||
5866 (!RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
5867 !RLD->isPredecessorOf(TheSelect->getOperand(1).getNode())))) {
5868 Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
5869 LLD->getBasePtr().getValueType(),
5870 TheSelect->getOperand(0),
5871 TheSelect->getOperand(1),
5872 LLD->getBasePtr(), RLD->getBasePtr(),
5873 TheSelect->getOperand(4));
5878 if (Addr.getNode()) {
5880 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
5881 Load = DAG.getLoad(TheSelect->getValueType(0),
5882 TheSelect->getDebugLoc(),
5886 LLD->getAlignment());
5888 Load = DAG.getExtLoad(LLD->getExtensionType(),
5889 TheSelect->getDebugLoc(),
5890 TheSelect->getValueType(0),
5891 LLD->getChain(), Addr, 0, 0,
5894 LLD->getAlignment());
5897 // Users of the select now use the result of the load.
5898 CombineTo(TheSelect, Load);
5900 // Users of the old loads now use the new load's chain. We know the
5901 // old-load value is dead now.
5902 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
5903 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
5913 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
5914 /// where 'cond' is the comparison specified by CC.
5915 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
5916 SDValue N2, SDValue N3,
5917 ISD::CondCode CC, bool NotExtCompare) {
5918 // (x ? y : y) -> y.
5919 if (N2 == N3) return N2;
5921 EVT VT = N2.getValueType();
5922 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
5923 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
5924 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
5926 // Determine if the condition we're dealing with is constant
5927 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
5928 N0, N1, CC, DL, false);
5929 if (SCC.getNode()) AddToWorkList(SCC.getNode());
5930 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
5932 // fold select_cc true, x, y -> x
5933 if (SCCC && !SCCC->isNullValue())
5935 // fold select_cc false, x, y -> y
5936 if (SCCC && SCCC->isNullValue())
5939 // Check to see if we can simplify the select into an fabs node
5940 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
5941 // Allow either -0.0 or 0.0
5942 if (CFP->getValueAPF().isZero()) {
5943 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
5944 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
5945 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
5946 N2 == N3.getOperand(0))
5947 return DAG.getNode(ISD::FABS, DL, VT, N0);
5949 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
5950 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
5951 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
5952 N2.getOperand(0) == N3)
5953 return DAG.getNode(ISD::FABS, DL, VT, N3);
5957 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
5958 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
5959 // in it. This is a win when the constant is not otherwise available because
5960 // it replaces two constant pool loads with one. We only do this if the FP
5961 // type is known to be legal, because if it isn't, then we are before legalize
5962 // types an we want the other legalization to happen first (e.g. to avoid
5963 // messing with soft float) and if the ConstantFP is not legal, because if
5964 // it is legal, we may not need to store the FP constant in a constant pool.
5965 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
5966 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
5967 if (TLI.isTypeLegal(N2.getValueType()) &&
5968 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
5969 TargetLowering::Legal) &&
5970 // If both constants have multiple uses, then we won't need to do an
5971 // extra load, they are likely around in registers for other users.
5972 (TV->hasOneUse() || FV->hasOneUse())) {
5973 Constant *Elts[] = {
5974 const_cast<ConstantFP*>(FV->getConstantFPValue()),
5975 const_cast<ConstantFP*>(TV->getConstantFPValue())
5977 const Type *FPTy = Elts[0]->getType();
5978 const TargetData &TD = *TLI.getTargetData();
5980 // Create a ConstantArray of the two constants.
5981 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts, 2);
5982 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
5983 TD.getPrefTypeAlignment(FPTy));
5984 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
5986 // Get the offsets to the 0 and 1 element of the array so that we can
5987 // select between them.
5988 SDValue Zero = DAG.getIntPtrConstant(0);
5989 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
5990 SDValue One = DAG.getIntPtrConstant(EltSize);
5992 SDValue Cond = DAG.getSetCC(DL,
5993 TLI.getSetCCResultType(N0.getValueType()),
5995 SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
5997 CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
5999 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
6000 PseudoSourceValue::getConstantPool(), 0, false,
6006 // Check to see if we can perform the "gzip trick", transforming
6007 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
6008 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
6009 N0.getValueType().isInteger() &&
6010 N2.getValueType().isInteger() &&
6011 (N1C->isNullValue() || // (a < 0) ? b : 0
6012 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
6013 EVT XType = N0.getValueType();
6014 EVT AType = N2.getValueType();
6015 if (XType.bitsGE(AType)) {
6016 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
6017 // single-bit constant.
6018 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
6019 unsigned ShCtV = N2C->getAPIntValue().logBase2();
6020 ShCtV = XType.getSizeInBits()-ShCtV-1;
6021 SDValue ShCt = DAG.getConstant(ShCtV, getShiftAmountTy());
6022 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
6024 AddToWorkList(Shift.getNode());
6026 if (XType.bitsGT(AType)) {
6027 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
6028 AddToWorkList(Shift.getNode());
6031 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
6034 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
6036 DAG.getConstant(XType.getSizeInBits()-1,
6037 getShiftAmountTy()));
6038 AddToWorkList(Shift.getNode());
6040 if (XType.bitsGT(AType)) {
6041 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
6042 AddToWorkList(Shift.getNode());
6045 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
6049 // fold select C, 16, 0 -> shl C, 4
6050 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
6051 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent) {
6053 // If the caller doesn't want us to simplify this into a zext of a compare,
6055 if (NotExtCompare && N2C->getAPIntValue() == 1)
6058 // Get a SetCC of the condition
6059 // FIXME: Should probably make sure that setcc is legal if we ever have a
6060 // target where it isn't.
6062 // cast from setcc result type to select result type
6064 SCC = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
6066 if (N2.getValueType().bitsLT(SCC.getValueType()))
6067 Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
6069 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
6070 N2.getValueType(), SCC);
6072 SCC = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
6073 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
6074 N2.getValueType(), SCC);
6077 AddToWorkList(SCC.getNode());
6078 AddToWorkList(Temp.getNode());
6080 if (N2C->getAPIntValue() == 1)
6083 // shl setcc result by log2 n2c
6084 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
6085 DAG.getConstant(N2C->getAPIntValue().logBase2(),
6086 getShiftAmountTy()));
6089 // Check to see if this is the equivalent of setcc
6090 // FIXME: Turn all of these into setcc if setcc if setcc is legal
6091 // otherwise, go ahead with the folds.
6092 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
6093 EVT XType = N0.getValueType();
6094 if (!LegalOperations ||
6095 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
6096 SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
6097 if (Res.getValueType() != VT)
6098 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
6102 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
6103 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
6104 (!LegalOperations ||
6105 TLI.isOperationLegal(ISD::CTLZ, XType))) {
6106 SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
6107 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
6108 DAG.getConstant(Log2_32(XType.getSizeInBits()),
6109 getShiftAmountTy()));
6111 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
6112 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
6113 SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
6114 XType, DAG.getConstant(0, XType), N0);
6115 SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
6116 return DAG.getNode(ISD::SRL, DL, XType,
6117 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
6118 DAG.getConstant(XType.getSizeInBits()-1,
6119 getShiftAmountTy()));
6121 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
6122 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
6123 SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
6124 DAG.getConstant(XType.getSizeInBits()-1,
6125 getShiftAmountTy()));
6126 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
6130 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
6131 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6132 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
6133 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
6134 N2.getOperand(0) == N1 && N0.getValueType().isInteger()) {
6135 EVT XType = N0.getValueType();
6136 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType, N0,
6137 DAG.getConstant(XType.getSizeInBits()-1,
6138 getShiftAmountTy()));
6139 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(), XType,
6141 AddToWorkList(Shift.getNode());
6142 AddToWorkList(Add.getNode());
6143 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
6145 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
6146 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6147 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
6148 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
6149 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
6150 EVT XType = N0.getValueType();
6151 if (SubC->isNullValue() && XType.isInteger()) {
6152 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
6154 DAG.getConstant(XType.getSizeInBits()-1,
6155 getShiftAmountTy()));
6156 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
6158 AddToWorkList(Shift.getNode());
6159 AddToWorkList(Add.getNode());
6160 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
6168 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
6169 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
6170 SDValue N1, ISD::CondCode Cond,
6171 DebugLoc DL, bool foldBooleans) {
6172 TargetLowering::DAGCombinerInfo
6173 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
6174 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
6177 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
6178 /// return a DAG expression to select that will generate the same value by
6179 /// multiplying by a magic number. See:
6180 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
6181 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
6182 std::vector<SDNode*> Built;
6183 SDValue S = TLI.BuildSDIV(N, DAG, &Built);
6185 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
6191 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
6192 /// return a DAG expression to select that will generate the same value by
6193 /// multiplying by a magic number. See:
6194 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
6195 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
6196 std::vector<SDNode*> Built;
6197 SDValue S = TLI.BuildUDIV(N, DAG, &Built);
6199 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
6205 /// FindBaseOffset - Return true if base is a frame index, which is known not
6206 // to alias with anything but itself. Provides base object and offset as results.
6207 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
6208 GlobalValue *&GV, void *&CV) {
6209 // Assume it is a primitive operation.
6210 Base = Ptr; Offset = 0; GV = 0; CV = 0;
6212 // If it's an adding a simple constant then integrate the offset.
6213 if (Base.getOpcode() == ISD::ADD) {
6214 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
6215 Base = Base.getOperand(0);
6216 Offset += C->getZExtValue();
6220 // Return the underlying GlobalValue, and update the Offset. Return false
6221 // for GlobalAddressSDNode since the same GlobalAddress may be represented
6222 // by multiple nodes with different offsets.
6223 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
6224 GV = G->getGlobal();
6225 Offset += G->getOffset();
6229 // Return the underlying Constant value, and update the Offset. Return false
6230 // for ConstantSDNodes since the same constant pool entry may be represented
6231 // by multiple nodes with different offsets.
6232 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
6233 CV = C->isMachineConstantPoolEntry() ? (void *)C->getMachineCPVal()
6234 : (void *)C->getConstVal();
6235 Offset += C->getOffset();
6238 // If it's any of the following then it can't alias with anything but itself.
6239 return isa<FrameIndexSDNode>(Base);
6242 /// isAlias - Return true if there is any possibility that the two addresses
6244 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
6245 const Value *SrcValue1, int SrcValueOffset1,
6246 unsigned SrcValueAlign1,
6247 SDValue Ptr2, int64_t Size2,
6248 const Value *SrcValue2, int SrcValueOffset2,
6249 unsigned SrcValueAlign2) const {
6250 // If they are the same then they must be aliases.
6251 if (Ptr1 == Ptr2) return true;
6253 // Gather base node and offset information.
6254 SDValue Base1, Base2;
6255 int64_t Offset1, Offset2;
6256 GlobalValue *GV1, *GV2;
6258 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
6259 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
6261 // If they have a same base address then check to see if they overlap.
6262 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
6263 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
6265 // If we know what the bases are, and they aren't identical, then we know they
6267 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
6270 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
6271 // compared to the size and offset of the access, we may be able to prove they
6272 // do not alias. This check is conservative for now to catch cases created by
6273 // splitting vector types.
6274 if ((SrcValueAlign1 == SrcValueAlign2) &&
6275 (SrcValueOffset1 != SrcValueOffset2) &&
6276 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
6277 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
6278 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
6280 // There is no overlap between these relatively aligned accesses of similar
6281 // size, return no alias.
6282 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
6286 if (CombinerGlobalAA) {
6287 // Use alias analysis information.
6288 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
6289 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
6290 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
6291 AliasAnalysis::AliasResult AAResult =
6292 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
6293 if (AAResult == AliasAnalysis::NoAlias)
6297 // Otherwise we have to assume they alias.
6301 /// FindAliasInfo - Extracts the relevant alias information from the memory
6302 /// node. Returns true if the operand was a load.
6303 bool DAGCombiner::FindAliasInfo(SDNode *N,
6304 SDValue &Ptr, int64_t &Size,
6305 const Value *&SrcValue,
6306 int &SrcValueOffset,
6307 unsigned &SrcValueAlign) const {
6308 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
6309 Ptr = LD->getBasePtr();
6310 Size = LD->getMemoryVT().getSizeInBits() >> 3;
6311 SrcValue = LD->getSrcValue();
6312 SrcValueOffset = LD->getSrcValueOffset();
6313 SrcValueAlign = LD->getOriginalAlignment();
6315 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
6316 Ptr = ST->getBasePtr();
6317 Size = ST->getMemoryVT().getSizeInBits() >> 3;
6318 SrcValue = ST->getSrcValue();
6319 SrcValueOffset = ST->getSrcValueOffset();
6320 SrcValueAlign = ST->getOriginalAlignment();
6322 llvm_unreachable("FindAliasInfo expected a memory operand");
6328 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
6329 /// looking for aliasing nodes and adding them to the Aliases vector.
6330 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
6331 SmallVector<SDValue, 8> &Aliases) {
6332 SmallVector<SDValue, 8> Chains; // List of chains to visit.
6333 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
6335 // Get alias information for node.
6338 const Value *SrcValue;
6340 unsigned SrcValueAlign;
6341 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
6345 Chains.push_back(OriginalChain);
6348 // Look at each chain and determine if it is an alias. If so, add it to the
6349 // aliases list. If not, then continue up the chain looking for the next
6351 while (!Chains.empty()) {
6352 SDValue Chain = Chains.back();
6355 // For TokenFactor nodes, look at each operand and only continue up the
6356 // chain until we find two aliases. If we've seen two aliases, assume we'll
6357 // find more and revert to original chain since the xform is unlikely to be
6360 // FIXME: The depth check could be made to return the last non-aliasing
6361 // chain we found before we hit a tokenfactor rather than the original
6363 if (Depth > 6 || Aliases.size() == 2) {
6365 Aliases.push_back(OriginalChain);
6369 // Don't bother if we've been before.
6370 if (!Visited.insert(Chain.getNode()))
6373 switch (Chain.getOpcode()) {
6374 case ISD::EntryToken:
6375 // Entry token is ideal chain operand, but handled in FindBetterChain.
6380 // Get alias information for Chain.
6383 const Value *OpSrcValue;
6384 int OpSrcValueOffset;
6385 unsigned OpSrcValueAlign;
6386 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
6387 OpSrcValue, OpSrcValueOffset,
6390 // If chain is alias then stop here.
6391 if (!(IsLoad && IsOpLoad) &&
6392 isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
6393 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
6395 Aliases.push_back(Chain);
6397 // Look further up the chain.
6398 Chains.push_back(Chain.getOperand(0));
6404 case ISD::TokenFactor:
6405 // We have to check each of the operands of the token factor for "small"
6406 // token factors, so we queue them up. Adding the operands to the queue
6407 // (stack) in reverse order maintains the original order and increases the
6408 // likelihood that getNode will find a matching token factor (CSE.)
6409 if (Chain.getNumOperands() > 16) {
6410 Aliases.push_back(Chain);
6413 for (unsigned n = Chain.getNumOperands(); n;)
6414 Chains.push_back(Chain.getOperand(--n));
6419 // For all other instructions we will just have to take what we can get.
6420 Aliases.push_back(Chain);
6426 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
6427 /// for a better chain (aliasing node.)
6428 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
6429 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
6431 // Accumulate all the aliases to this node.
6432 GatherAllAliases(N, OldChain, Aliases);
6434 if (Aliases.size() == 0) {
6435 // If no operands then chain to entry token.
6436 return DAG.getEntryNode();
6437 } else if (Aliases.size() == 1) {
6438 // If a single operand then chain to it. We don't need to revisit it.
6442 // Construct a custom tailored token factor.
6443 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
6444 &Aliases[0], Aliases.size());
6447 // SelectionDAG::Combine - This is the entry point for the file.
6449 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
6450 CodeGenOpt::Level OptLevel) {
6451 /// run - This is the main entry point to this class.
6453 DAGCombiner(*this, AA, OptLevel).Run(Level);