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/TargetLowering.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
41 STATISTIC(NodesCombined , "Number of dag nodes combined");
42 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
43 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
44 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
48 CombinerAA("combiner-alias-analysis", cl::Hidden,
49 cl::desc("Turn on alias analysis during testing"));
52 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
53 cl::desc("Include global information in alias analysis"));
55 //------------------------------ DAGCombiner ---------------------------------//
59 const TargetLowering &TLI;
61 CodeGenOpt::Level OptLevel;
65 // Worklist of all of the nodes that need to be simplified.
66 std::vector<SDNode*> WorkList;
68 // AA - Used for DAG load/store alias analysis.
71 /// AddUsersToWorkList - When an instruction is simplified, add all users of
72 /// the instruction to the work lists because they might get more simplified
75 void AddUsersToWorkList(SDNode *N) {
76 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
81 /// visit - call the node-specific routine that knows how to fold each
82 /// particular type of node.
83 SDValue visit(SDNode *N);
86 /// AddToWorkList - Add to the work list making sure it's instance is at the
87 /// the back (next to be processed.)
88 void AddToWorkList(SDNode *N) {
89 removeFromWorkList(N);
90 WorkList.push_back(N);
93 /// removeFromWorkList - remove all instances of N from the worklist.
95 void removeFromWorkList(SDNode *N) {
96 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
100 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
103 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
104 return CombineTo(N, &Res, 1, AddTo);
107 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
109 SDValue To[] = { Res0, Res1 };
110 return CombineTo(N, To, 2, AddTo);
113 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
117 /// SimplifyDemandedBits - Check the specified integer node value to see if
118 /// it can be simplified or if things it uses can be simplified by bit
119 /// propagation. If so, return true.
120 bool SimplifyDemandedBits(SDValue Op) {
121 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
122 APInt Demanded = APInt::getAllOnesValue(BitWidth);
123 return SimplifyDemandedBits(Op, Demanded);
126 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
128 bool CombineToPreIndexedLoadStore(SDNode *N);
129 bool CombineToPostIndexedLoadStore(SDNode *N);
131 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
132 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
133 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
134 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
135 SDValue PromoteIntBinOp(SDValue Op);
136 SDValue PromoteIntShiftOp(SDValue Op);
137 SDValue PromoteExtend(SDValue Op);
138 bool PromoteLoad(SDValue Op);
140 /// combine - call the node-specific routine that knows how to fold each
141 /// particular type of node. If that doesn't do anything, try the
142 /// target-specific DAG combines.
143 SDValue combine(SDNode *N);
145 // Visitation implementation - Implement dag node combining for different
146 // node types. The semantics are as follows:
148 // SDValue.getNode() == 0 - No change was made
149 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
150 // otherwise - N should be replaced by the returned Operand.
152 SDValue visitTokenFactor(SDNode *N);
153 SDValue visitMERGE_VALUES(SDNode *N);
154 SDValue visitADD(SDNode *N);
155 SDValue visitSUB(SDNode *N);
156 SDValue visitADDC(SDNode *N);
157 SDValue visitADDE(SDNode *N);
158 SDValue visitMUL(SDNode *N);
159 SDValue visitSDIV(SDNode *N);
160 SDValue visitUDIV(SDNode *N);
161 SDValue visitSREM(SDNode *N);
162 SDValue visitUREM(SDNode *N);
163 SDValue visitMULHU(SDNode *N);
164 SDValue visitMULHS(SDNode *N);
165 SDValue visitSMUL_LOHI(SDNode *N);
166 SDValue visitUMUL_LOHI(SDNode *N);
167 SDValue visitSDIVREM(SDNode *N);
168 SDValue visitUDIVREM(SDNode *N);
169 SDValue visitAND(SDNode *N);
170 SDValue visitOR(SDNode *N);
171 SDValue visitXOR(SDNode *N);
172 SDValue SimplifyVBinOp(SDNode *N);
173 SDValue visitSHL(SDNode *N);
174 SDValue visitSRA(SDNode *N);
175 SDValue visitSRL(SDNode *N);
176 SDValue visitCTLZ(SDNode *N);
177 SDValue visitCTTZ(SDNode *N);
178 SDValue visitCTPOP(SDNode *N);
179 SDValue visitSELECT(SDNode *N);
180 SDValue visitSELECT_CC(SDNode *N);
181 SDValue visitSETCC(SDNode *N);
182 SDValue visitSIGN_EXTEND(SDNode *N);
183 SDValue visitZERO_EXTEND(SDNode *N);
184 SDValue visitANY_EXTEND(SDNode *N);
185 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
186 SDValue visitTRUNCATE(SDNode *N);
187 SDValue visitBITCAST(SDNode *N);
188 SDValue visitBUILD_PAIR(SDNode *N);
189 SDValue visitFADD(SDNode *N);
190 SDValue visitFSUB(SDNode *N);
191 SDValue visitFMUL(SDNode *N);
192 SDValue visitFDIV(SDNode *N);
193 SDValue visitFREM(SDNode *N);
194 SDValue visitFCOPYSIGN(SDNode *N);
195 SDValue visitSINT_TO_FP(SDNode *N);
196 SDValue visitUINT_TO_FP(SDNode *N);
197 SDValue visitFP_TO_SINT(SDNode *N);
198 SDValue visitFP_TO_UINT(SDNode *N);
199 SDValue visitFP_ROUND(SDNode *N);
200 SDValue visitFP_ROUND_INREG(SDNode *N);
201 SDValue visitFP_EXTEND(SDNode *N);
202 SDValue visitFNEG(SDNode *N);
203 SDValue visitFABS(SDNode *N);
204 SDValue visitBRCOND(SDNode *N);
205 SDValue visitBR_CC(SDNode *N);
206 SDValue visitLOAD(SDNode *N);
207 SDValue visitSTORE(SDNode *N);
208 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
209 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
210 SDValue visitBUILD_VECTOR(SDNode *N);
211 SDValue visitCONCAT_VECTORS(SDNode *N);
212 SDValue visitVECTOR_SHUFFLE(SDNode *N);
213 SDValue visitMEMBARRIER(SDNode *N);
215 SDValue XformToShuffleWithZero(SDNode *N);
216 SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
218 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
220 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
221 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
222 SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
223 SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
224 SDValue N3, ISD::CondCode CC,
225 bool NotExtCompare = false);
226 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
227 DebugLoc DL, bool foldBooleans = true);
228 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
230 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
231 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
232 SDValue BuildSDIV(SDNode *N);
233 SDValue BuildUDIV(SDNode *N);
234 SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
235 SDValue ReduceLoadWidth(SDNode *N);
236 SDValue ReduceLoadOpStoreWidth(SDNode *N);
238 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
240 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
241 /// looking for aliasing nodes and adding them to the Aliases vector.
242 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
243 SmallVector<SDValue, 8> &Aliases);
245 /// isAlias - Return true if there is any possibility that the two addresses
247 bool isAlias(SDValue Ptr1, int64_t Size1,
248 const Value *SrcValue1, int SrcValueOffset1,
249 unsigned SrcValueAlign1,
250 const MDNode *TBAAInfo1,
251 SDValue Ptr2, int64_t Size2,
252 const Value *SrcValue2, int SrcValueOffset2,
253 unsigned SrcValueAlign2,
254 const MDNode *TBAAInfo2) const;
256 /// FindAliasInfo - Extracts the relevant alias information from the memory
257 /// node. Returns true if the operand was a load.
258 bool FindAliasInfo(SDNode *N,
259 SDValue &Ptr, int64_t &Size,
260 const Value *&SrcValue, int &SrcValueOffset,
261 unsigned &SrcValueAlignment,
262 const MDNode *&TBAAInfo) const;
264 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
265 /// looking for a better chain (aliasing node.)
266 SDValue FindBetterChain(SDNode *N, SDValue Chain);
269 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
270 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(Unrestricted),
271 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
273 /// Run - runs the dag combiner on all nodes in the work list
274 void Run(CombineLevel AtLevel);
276 SelectionDAG &getDAG() const { return DAG; }
278 /// getShiftAmountTy - Returns a type large enough to hold any valid
279 /// shift amount - before type legalization these can be huge.
280 EVT getShiftAmountTy() {
281 return LegalTypes ? TLI.getShiftAmountTy() : TLI.getPointerTy();
284 /// isTypeLegal - This method returns true if we are running before type
285 /// legalization or if the specified VT is legal.
286 bool isTypeLegal(const EVT &VT) {
287 if (!LegalTypes) return true;
288 return TLI.isTypeLegal(VT);
295 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
296 /// nodes from the worklist.
297 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
300 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
302 virtual void NodeDeleted(SDNode *N, SDNode *E) {
303 DC.removeFromWorkList(N);
306 virtual void NodeUpdated(SDNode *N) {
312 //===----------------------------------------------------------------------===//
313 // TargetLowering::DAGCombinerInfo implementation
314 //===----------------------------------------------------------------------===//
316 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
317 ((DAGCombiner*)DC)->AddToWorkList(N);
320 SDValue TargetLowering::DAGCombinerInfo::
321 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
322 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
325 SDValue TargetLowering::DAGCombinerInfo::
326 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
327 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
331 SDValue TargetLowering::DAGCombinerInfo::
332 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
333 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
336 void TargetLowering::DAGCombinerInfo::
337 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
338 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
341 //===----------------------------------------------------------------------===//
343 //===----------------------------------------------------------------------===//
345 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
346 /// specified expression for the same cost as the expression itself, or 2 if we
347 /// can compute the negated form more cheaply than the expression itself.
348 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
349 unsigned Depth = 0) {
350 // No compile time optimizations on this type.
351 if (Op.getValueType() == MVT::ppcf128)
354 // fneg is removable even if it has multiple uses.
355 if (Op.getOpcode() == ISD::FNEG) return 2;
357 // Don't allow anything with multiple uses.
358 if (!Op.hasOneUse()) return 0;
360 // Don't recurse exponentially.
361 if (Depth > 6) return 0;
363 switch (Op.getOpcode()) {
364 default: return false;
365 case ISD::ConstantFP:
366 // Don't invert constant FP values after legalize. The negated constant
367 // isn't necessarily legal.
368 return LegalOperations ? 0 : 1;
370 // FIXME: determine better conditions for this xform.
371 if (!UnsafeFPMath) return 0;
373 // fold (fsub (fadd A, B)) -> (fsub (fneg A), B)
374 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
376 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
377 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
379 // We can't turn -(A-B) into B-A when we honor signed zeros.
380 if (!UnsafeFPMath) return 0;
382 // fold (fneg (fsub A, B)) -> (fsub B, A)
387 if (HonorSignDependentRoundingFPMath()) return 0;
389 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
390 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
393 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
398 return isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1);
402 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
403 /// returns the newly negated expression.
404 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
405 bool LegalOperations, unsigned Depth = 0) {
406 // fneg is removable even if it has multiple uses.
407 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
409 // Don't allow anything with multiple uses.
410 assert(Op.hasOneUse() && "Unknown reuse!");
412 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
413 switch (Op.getOpcode()) {
414 default: llvm_unreachable("Unknown code");
415 case ISD::ConstantFP: {
416 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
418 return DAG.getConstantFP(V, Op.getValueType());
421 // FIXME: determine better conditions for this xform.
422 assert(UnsafeFPMath);
424 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
425 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
426 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
427 GetNegatedExpression(Op.getOperand(0), DAG,
428 LegalOperations, Depth+1),
430 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
431 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
432 GetNegatedExpression(Op.getOperand(1), DAG,
433 LegalOperations, Depth+1),
436 // We can't turn -(A-B) into B-A when we honor signed zeros.
437 assert(UnsafeFPMath);
439 // fold (fneg (fsub 0, B)) -> B
440 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
441 if (N0CFP->getValueAPF().isZero())
442 return Op.getOperand(1);
444 // fold (fneg (fsub A, B)) -> (fsub B, A)
445 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
446 Op.getOperand(1), Op.getOperand(0));
450 assert(!HonorSignDependentRoundingFPMath());
452 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
453 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
454 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
455 GetNegatedExpression(Op.getOperand(0), DAG,
456 LegalOperations, Depth+1),
459 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
460 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
462 GetNegatedExpression(Op.getOperand(1), DAG,
463 LegalOperations, Depth+1));
467 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
468 GetNegatedExpression(Op.getOperand(0), DAG,
469 LegalOperations, Depth+1));
471 return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
472 GetNegatedExpression(Op.getOperand(0), DAG,
473 LegalOperations, Depth+1),
479 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
480 // that selects between the values 1 and 0, making it equivalent to a setcc.
481 // Also, set the incoming LHS, RHS, and CC references to the appropriate
482 // nodes based on the type of node we are checking. This simplifies life a
483 // bit for the callers.
484 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
486 if (N.getOpcode() == ISD::SETCC) {
487 LHS = N.getOperand(0);
488 RHS = N.getOperand(1);
489 CC = N.getOperand(2);
492 if (N.getOpcode() == ISD::SELECT_CC &&
493 N.getOperand(2).getOpcode() == ISD::Constant &&
494 N.getOperand(3).getOpcode() == ISD::Constant &&
495 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
496 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
497 LHS = N.getOperand(0);
498 RHS = N.getOperand(1);
499 CC = N.getOperand(4);
505 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
506 // one use. If this is true, it allows the users to invert the operation for
507 // free when it is profitable to do so.
508 static bool isOneUseSetCC(SDValue N) {
510 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
515 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
516 SDValue N0, SDValue N1) {
517 EVT VT = N0.getValueType();
518 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
519 if (isa<ConstantSDNode>(N1)) {
520 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
522 DAG.FoldConstantArithmetic(Opc, VT,
523 cast<ConstantSDNode>(N0.getOperand(1)),
524 cast<ConstantSDNode>(N1));
525 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
526 } else if (N0.hasOneUse()) {
527 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
528 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
529 N0.getOperand(0), N1);
530 AddToWorkList(OpNode.getNode());
531 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
535 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
536 if (isa<ConstantSDNode>(N0)) {
537 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
539 DAG.FoldConstantArithmetic(Opc, VT,
540 cast<ConstantSDNode>(N1.getOperand(1)),
541 cast<ConstantSDNode>(N0));
542 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
543 } else if (N1.hasOneUse()) {
544 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
545 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
546 N1.getOperand(0), N0);
547 AddToWorkList(OpNode.getNode());
548 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
555 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
557 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
559 DEBUG(dbgs() << "\nReplacing.1 ";
561 dbgs() << "\nWith: ";
562 To[0].getNode()->dump(&DAG);
563 dbgs() << " and " << NumTo-1 << " other values\n";
564 for (unsigned i = 0, e = NumTo; i != e; ++i)
565 assert((!To[i].getNode() ||
566 N->getValueType(i) == To[i].getValueType()) &&
567 "Cannot combine value to value of different type!"));
568 WorkListRemover DeadNodes(*this);
569 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
572 // Push the new nodes and any users onto the worklist
573 for (unsigned i = 0, e = NumTo; i != e; ++i) {
574 if (To[i].getNode()) {
575 AddToWorkList(To[i].getNode());
576 AddUsersToWorkList(To[i].getNode());
581 // Finally, if the node is now dead, remove it from the graph. The node
582 // may not be dead if the replacement process recursively simplified to
583 // something else needing this node.
584 if (N->use_empty()) {
585 // Nodes can be reintroduced into the worklist. Make sure we do not
586 // process a node that has been replaced.
587 removeFromWorkList(N);
589 // Finally, since the node is now dead, remove it from the graph.
592 return SDValue(N, 0);
596 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
597 // Replace all uses. If any nodes become isomorphic to other nodes and
598 // are deleted, make sure to remove them from our worklist.
599 WorkListRemover DeadNodes(*this);
600 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
602 // Push the new node and any (possibly new) users onto the worklist.
603 AddToWorkList(TLO.New.getNode());
604 AddUsersToWorkList(TLO.New.getNode());
606 // Finally, if the node is now dead, remove it from the graph. The node
607 // may not be dead if the replacement process recursively simplified to
608 // something else needing this node.
609 if (TLO.Old.getNode()->use_empty()) {
610 removeFromWorkList(TLO.Old.getNode());
612 // If the operands of this node are only used by the node, they will now
613 // be dead. Make sure to visit them first to delete dead nodes early.
614 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
615 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
616 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
618 DAG.DeleteNode(TLO.Old.getNode());
622 /// SimplifyDemandedBits - Check the specified integer node value to see if
623 /// it can be simplified or if things it uses can be simplified by bit
624 /// propagation. If so, return true.
625 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
626 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
627 APInt KnownZero, KnownOne;
628 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
632 AddToWorkList(Op.getNode());
634 // Replace the old value with the new one.
636 DEBUG(dbgs() << "\nReplacing.2 ";
637 TLO.Old.getNode()->dump(&DAG);
638 dbgs() << "\nWith: ";
639 TLO.New.getNode()->dump(&DAG);
642 CommitTargetLoweringOpt(TLO);
646 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
647 DebugLoc dl = Load->getDebugLoc();
648 EVT VT = Load->getValueType(0);
649 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
651 DEBUG(dbgs() << "\nReplacing.9 ";
653 dbgs() << "\nWith: ";
654 Trunc.getNode()->dump(&DAG);
656 WorkListRemover DeadNodes(*this);
657 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc, &DeadNodes);
658 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1),
660 removeFromWorkList(Load);
661 DAG.DeleteNode(Load);
662 AddToWorkList(Trunc.getNode());
665 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
667 DebugLoc dl = Op.getDebugLoc();
668 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
669 EVT MemVT = LD->getMemoryVT();
670 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
671 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
673 : LD->getExtensionType();
675 return DAG.getExtLoad(ExtType, PVT, dl,
676 LD->getChain(), LD->getBasePtr(),
677 LD->getPointerInfo(),
678 MemVT, LD->isVolatile(),
679 LD->isNonTemporal(), LD->getAlignment());
682 unsigned Opc = Op.getOpcode();
685 case ISD::AssertSext:
686 return DAG.getNode(ISD::AssertSext, dl, PVT,
687 SExtPromoteOperand(Op.getOperand(0), PVT),
689 case ISD::AssertZext:
690 return DAG.getNode(ISD::AssertZext, dl, PVT,
691 ZExtPromoteOperand(Op.getOperand(0), PVT),
693 case ISD::Constant: {
695 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
696 return DAG.getNode(ExtOpc, dl, PVT, Op);
700 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
702 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
705 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
706 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
708 EVT OldVT = Op.getValueType();
709 DebugLoc dl = Op.getDebugLoc();
710 bool Replace = false;
711 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
712 if (NewOp.getNode() == 0)
714 AddToWorkList(NewOp.getNode());
717 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
718 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
719 DAG.getValueType(OldVT));
722 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
723 EVT OldVT = Op.getValueType();
724 DebugLoc dl = Op.getDebugLoc();
725 bool Replace = false;
726 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
727 if (NewOp.getNode() == 0)
729 AddToWorkList(NewOp.getNode());
732 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
733 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
736 /// PromoteIntBinOp - Promote the specified integer binary operation if the
737 /// target indicates it is beneficial. e.g. On x86, it's usually better to
738 /// promote i16 operations to i32 since i16 instructions are longer.
739 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
740 if (!LegalOperations)
743 EVT VT = Op.getValueType();
744 if (VT.isVector() || !VT.isInteger())
747 // If operation type is 'undesirable', e.g. i16 on x86, consider
749 unsigned Opc = Op.getOpcode();
750 if (TLI.isTypeDesirableForOp(Opc, VT))
754 // Consult target whether it is a good idea to promote this operation and
755 // what's the right type to promote it to.
756 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
757 assert(PVT != VT && "Don't know what type to promote to!");
759 bool Replace0 = false;
760 SDValue N0 = Op.getOperand(0);
761 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
762 if (NN0.getNode() == 0)
765 bool Replace1 = false;
766 SDValue N1 = Op.getOperand(1);
771 NN1 = PromoteOperand(N1, PVT, Replace1);
772 if (NN1.getNode() == 0)
776 AddToWorkList(NN0.getNode());
778 AddToWorkList(NN1.getNode());
781 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
783 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
785 DEBUG(dbgs() << "\nPromoting ";
786 Op.getNode()->dump(&DAG));
787 DebugLoc dl = Op.getDebugLoc();
788 return DAG.getNode(ISD::TRUNCATE, dl, VT,
789 DAG.getNode(Opc, dl, PVT, NN0, NN1));
794 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
795 /// target indicates it is beneficial. e.g. On x86, it's usually better to
796 /// promote i16 operations to i32 since i16 instructions are longer.
797 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
798 if (!LegalOperations)
801 EVT VT = Op.getValueType();
802 if (VT.isVector() || !VT.isInteger())
805 // If operation type is 'undesirable', e.g. i16 on x86, consider
807 unsigned Opc = Op.getOpcode();
808 if (TLI.isTypeDesirableForOp(Opc, VT))
812 // Consult target whether it is a good idea to promote this operation and
813 // what's the right type to promote it to.
814 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
815 assert(PVT != VT && "Don't know what type to promote to!");
817 bool Replace = false;
818 SDValue N0 = Op.getOperand(0);
820 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
821 else if (Opc == ISD::SRL)
822 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
824 N0 = PromoteOperand(N0, PVT, Replace);
825 if (N0.getNode() == 0)
828 AddToWorkList(N0.getNode());
830 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
832 DEBUG(dbgs() << "\nPromoting ";
833 Op.getNode()->dump(&DAG));
834 DebugLoc dl = Op.getDebugLoc();
835 return DAG.getNode(ISD::TRUNCATE, dl, VT,
836 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
841 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
842 if (!LegalOperations)
845 EVT VT = Op.getValueType();
846 if (VT.isVector() || !VT.isInteger())
849 // If operation type is 'undesirable', e.g. i16 on x86, consider
851 unsigned Opc = Op.getOpcode();
852 if (TLI.isTypeDesirableForOp(Opc, VT))
856 // Consult target whether it is a good idea to promote this operation and
857 // what's the right type to promote it to.
858 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
859 assert(PVT != VT && "Don't know what type to promote to!");
860 // fold (aext (aext x)) -> (aext x)
861 // fold (aext (zext x)) -> (zext x)
862 // fold (aext (sext x)) -> (sext x)
863 DEBUG(dbgs() << "\nPromoting ";
864 Op.getNode()->dump(&DAG));
865 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0));
870 bool DAGCombiner::PromoteLoad(SDValue Op) {
871 if (!LegalOperations)
874 EVT VT = Op.getValueType();
875 if (VT.isVector() || !VT.isInteger())
878 // If operation type is 'undesirable', e.g. i16 on x86, consider
880 unsigned Opc = Op.getOpcode();
881 if (TLI.isTypeDesirableForOp(Opc, VT))
885 // Consult target whether it is a good idea to promote this operation and
886 // what's the right type to promote it to.
887 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
888 assert(PVT != VT && "Don't know what type to promote to!");
890 DebugLoc dl = Op.getDebugLoc();
891 SDNode *N = Op.getNode();
892 LoadSDNode *LD = cast<LoadSDNode>(N);
893 EVT MemVT = LD->getMemoryVT();
894 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
895 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
897 : LD->getExtensionType();
898 SDValue NewLD = DAG.getExtLoad(ExtType, PVT, dl,
899 LD->getChain(), LD->getBasePtr(),
900 LD->getPointerInfo(),
901 MemVT, LD->isVolatile(),
902 LD->isNonTemporal(), LD->getAlignment());
903 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
905 DEBUG(dbgs() << "\nPromoting ";
908 Result.getNode()->dump(&DAG);
910 WorkListRemover DeadNodes(*this);
911 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result, &DeadNodes);
912 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1), &DeadNodes);
913 removeFromWorkList(N);
915 AddToWorkList(Result.getNode());
922 //===----------------------------------------------------------------------===//
923 // Main DAG Combiner implementation
924 //===----------------------------------------------------------------------===//
926 void DAGCombiner::Run(CombineLevel AtLevel) {
927 // set the instance variables, so that the various visit routines may use it.
929 LegalOperations = Level >= NoIllegalOperations;
930 LegalTypes = Level >= NoIllegalTypes;
932 // Add all the dag nodes to the worklist.
933 WorkList.reserve(DAG.allnodes_size());
934 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
935 E = DAG.allnodes_end(); I != E; ++I)
936 WorkList.push_back(I);
938 // Create a dummy node (which is not added to allnodes), that adds a reference
939 // to the root node, preventing it from being deleted, and tracking any
940 // changes of the root.
941 HandleSDNode Dummy(DAG.getRoot());
943 // The root of the dag may dangle to deleted nodes until the dag combiner is
944 // done. Set it to null to avoid confusion.
945 DAG.setRoot(SDValue());
947 // while the worklist isn't empty, inspect the node on the end of it and
948 // try and combine it.
949 while (!WorkList.empty()) {
950 SDNode *N = WorkList.back();
953 // If N has no uses, it is dead. Make sure to revisit all N's operands once
954 // N is deleted from the DAG, since they too may now be dead or may have a
955 // reduced number of uses, allowing other xforms.
956 if (N->use_empty() && N != &Dummy) {
957 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
958 AddToWorkList(N->getOperand(i).getNode());
964 SDValue RV = combine(N);
966 if (RV.getNode() == 0)
971 // If we get back the same node we passed in, rather than a new node or
972 // zero, we know that the node must have defined multiple values and
973 // CombineTo was used. Since CombineTo takes care of the worklist
974 // mechanics for us, we have no work to do in this case.
975 if (RV.getNode() == N)
978 assert(N->getOpcode() != ISD::DELETED_NODE &&
979 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
980 "Node was deleted but visit returned new node!");
982 DEBUG(dbgs() << "\nReplacing.3 ";
984 dbgs() << "\nWith: ";
985 RV.getNode()->dump(&DAG);
987 WorkListRemover DeadNodes(*this);
988 if (N->getNumValues() == RV.getNode()->getNumValues())
989 DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes);
991 assert(N->getValueType(0) == RV.getValueType() &&
992 N->getNumValues() == 1 && "Type mismatch");
994 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
997 // Push the new node and any users onto the worklist
998 AddToWorkList(RV.getNode());
999 AddUsersToWorkList(RV.getNode());
1001 // Add any uses of the old node to the worklist in case this node is the
1002 // last one that uses them. They may become dead after this node is
1004 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1005 AddToWorkList(N->getOperand(i).getNode());
1007 // Finally, if the node is now dead, remove it from the graph. The node
1008 // may not be dead if the replacement process recursively simplified to
1009 // something else needing this node.
1010 if (N->use_empty()) {
1011 // Nodes can be reintroduced into the worklist. Make sure we do not
1012 // process a node that has been replaced.
1013 removeFromWorkList(N);
1015 // Finally, since the node is now dead, remove it from the graph.
1020 // If the root changed (e.g. it was a dead load, update the root).
1021 DAG.setRoot(Dummy.getValue());
1024 SDValue DAGCombiner::visit(SDNode *N) {
1025 switch (N->getOpcode()) {
1027 case ISD::TokenFactor: return visitTokenFactor(N);
1028 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1029 case ISD::ADD: return visitADD(N);
1030 case ISD::SUB: return visitSUB(N);
1031 case ISD::ADDC: return visitADDC(N);
1032 case ISD::ADDE: return visitADDE(N);
1033 case ISD::MUL: return visitMUL(N);
1034 case ISD::SDIV: return visitSDIV(N);
1035 case ISD::UDIV: return visitUDIV(N);
1036 case ISD::SREM: return visitSREM(N);
1037 case ISD::UREM: return visitUREM(N);
1038 case ISD::MULHU: return visitMULHU(N);
1039 case ISD::MULHS: return visitMULHS(N);
1040 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1041 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1042 case ISD::SDIVREM: return visitSDIVREM(N);
1043 case ISD::UDIVREM: return visitUDIVREM(N);
1044 case ISD::AND: return visitAND(N);
1045 case ISD::OR: return visitOR(N);
1046 case ISD::XOR: return visitXOR(N);
1047 case ISD::SHL: return visitSHL(N);
1048 case ISD::SRA: return visitSRA(N);
1049 case ISD::SRL: return visitSRL(N);
1050 case ISD::CTLZ: return visitCTLZ(N);
1051 case ISD::CTTZ: return visitCTTZ(N);
1052 case ISD::CTPOP: return visitCTPOP(N);
1053 case ISD::SELECT: return visitSELECT(N);
1054 case ISD::SELECT_CC: return visitSELECT_CC(N);
1055 case ISD::SETCC: return visitSETCC(N);
1056 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1057 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1058 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1059 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1060 case ISD::TRUNCATE: return visitTRUNCATE(N);
1061 case ISD::BITCAST: return visitBITCAST(N);
1062 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1063 case ISD::FADD: return visitFADD(N);
1064 case ISD::FSUB: return visitFSUB(N);
1065 case ISD::FMUL: return visitFMUL(N);
1066 case ISD::FDIV: return visitFDIV(N);
1067 case ISD::FREM: return visitFREM(N);
1068 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1069 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1070 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1071 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1072 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1073 case ISD::FP_ROUND: return visitFP_ROUND(N);
1074 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1075 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1076 case ISD::FNEG: return visitFNEG(N);
1077 case ISD::FABS: return visitFABS(N);
1078 case ISD::BRCOND: return visitBRCOND(N);
1079 case ISD::BR_CC: return visitBR_CC(N);
1080 case ISD::LOAD: return visitLOAD(N);
1081 case ISD::STORE: return visitSTORE(N);
1082 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1083 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1084 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1085 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1086 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1087 case ISD::MEMBARRIER: return visitMEMBARRIER(N);
1092 SDValue DAGCombiner::combine(SDNode *N) {
1093 SDValue RV = visit(N);
1095 // If nothing happened, try a target-specific DAG combine.
1096 if (RV.getNode() == 0) {
1097 assert(N->getOpcode() != ISD::DELETED_NODE &&
1098 "Node was deleted but visit returned NULL!");
1100 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1101 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1103 // Expose the DAG combiner to the target combiner impls.
1104 TargetLowering::DAGCombinerInfo
1105 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
1107 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1111 // If nothing happened still, try promoting the operation.
1112 if (RV.getNode() == 0) {
1113 switch (N->getOpcode()) {
1121 RV = PromoteIntBinOp(SDValue(N, 0));
1126 RV = PromoteIntShiftOp(SDValue(N, 0));
1128 case ISD::SIGN_EXTEND:
1129 case ISD::ZERO_EXTEND:
1130 case ISD::ANY_EXTEND:
1131 RV = PromoteExtend(SDValue(N, 0));
1134 if (PromoteLoad(SDValue(N, 0)))
1140 // If N is a commutative binary node, try commuting it to enable more
1142 if (RV.getNode() == 0 &&
1143 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1144 N->getNumValues() == 1) {
1145 SDValue N0 = N->getOperand(0);
1146 SDValue N1 = N->getOperand(1);
1148 // Constant operands are canonicalized to RHS.
1149 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1150 SDValue Ops[] = { N1, N0 };
1151 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1154 return SDValue(CSENode, 0);
1161 /// getInputChainForNode - Given a node, return its input chain if it has one,
1162 /// otherwise return a null sd operand.
1163 static SDValue getInputChainForNode(SDNode *N) {
1164 if (unsigned NumOps = N->getNumOperands()) {
1165 if (N->getOperand(0).getValueType() == MVT::Other)
1166 return N->getOperand(0);
1167 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1168 return N->getOperand(NumOps-1);
1169 for (unsigned i = 1; i < NumOps-1; ++i)
1170 if (N->getOperand(i).getValueType() == MVT::Other)
1171 return N->getOperand(i);
1176 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1177 // If N has two operands, where one has an input chain equal to the other,
1178 // the 'other' chain is redundant.
1179 if (N->getNumOperands() == 2) {
1180 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1181 return N->getOperand(0);
1182 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1183 return N->getOperand(1);
1186 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1187 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1188 SmallPtrSet<SDNode*, 16> SeenOps;
1189 bool Changed = false; // If we should replace this token factor.
1191 // Start out with this token factor.
1194 // Iterate through token factors. The TFs grows when new token factors are
1196 for (unsigned i = 0; i < TFs.size(); ++i) {
1197 SDNode *TF = TFs[i];
1199 // Check each of the operands.
1200 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1201 SDValue Op = TF->getOperand(i);
1203 switch (Op.getOpcode()) {
1204 case ISD::EntryToken:
1205 // Entry tokens don't need to be added to the list. They are
1210 case ISD::TokenFactor:
1211 if (Op.hasOneUse() &&
1212 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1213 // Queue up for processing.
1214 TFs.push_back(Op.getNode());
1215 // Clean up in case the token factor is removed.
1216 AddToWorkList(Op.getNode());
1223 // Only add if it isn't already in the list.
1224 if (SeenOps.insert(Op.getNode()))
1235 // If we've change things around then replace token factor.
1238 // The entry token is the only possible outcome.
1239 Result = DAG.getEntryNode();
1241 // New and improved token factor.
1242 Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
1243 MVT::Other, &Ops[0], Ops.size());
1246 // Don't add users to work list.
1247 return CombineTo(N, Result, false);
1253 /// MERGE_VALUES can always be eliminated.
1254 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1255 WorkListRemover DeadNodes(*this);
1256 // Replacing results may cause a different MERGE_VALUES to suddenly
1257 // be CSE'd with N, and carry its uses with it. Iterate until no
1258 // uses remain, to ensure that the node can be safely deleted.
1260 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1261 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i),
1263 } while (!N->use_empty());
1264 removeFromWorkList(N);
1266 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1270 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
1271 SelectionDAG &DAG) {
1272 EVT VT = N0.getValueType();
1273 SDValue N00 = N0.getOperand(0);
1274 SDValue N01 = N0.getOperand(1);
1275 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1277 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1278 isa<ConstantSDNode>(N00.getOperand(1))) {
1279 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1280 N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
1281 DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
1282 N00.getOperand(0), N01),
1283 DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
1284 N00.getOperand(1), N01));
1285 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1291 SDValue DAGCombiner::visitADD(SDNode *N) {
1292 SDValue N0 = N->getOperand(0);
1293 SDValue N1 = N->getOperand(1);
1294 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1295 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1296 EVT VT = N0.getValueType();
1299 if (VT.isVector()) {
1300 SDValue FoldedVOp = SimplifyVBinOp(N);
1301 if (FoldedVOp.getNode()) return FoldedVOp;
1304 // fold (add x, undef) -> undef
1305 if (N0.getOpcode() == ISD::UNDEF)
1307 if (N1.getOpcode() == ISD::UNDEF)
1309 // fold (add c1, c2) -> c1+c2
1311 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1312 // canonicalize constant to RHS
1314 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
1315 // fold (add x, 0) -> x
1316 if (N1C && N1C->isNullValue())
1318 // fold (add Sym, c) -> Sym+c
1319 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1320 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1321 GA->getOpcode() == ISD::GlobalAddress)
1322 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1324 (uint64_t)N1C->getSExtValue());
1325 // fold ((c1-A)+c2) -> (c1+c2)-A
1326 if (N1C && N0.getOpcode() == ISD::SUB)
1327 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1328 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1329 DAG.getConstant(N1C->getAPIntValue()+
1330 N0C->getAPIntValue(), VT),
1333 SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1334 if (RADD.getNode() != 0)
1336 // fold ((0-A) + B) -> B-A
1337 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1338 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1339 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1340 // fold (A + (0-B)) -> A-B
1341 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1342 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1343 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1344 // fold (A+(B-A)) -> B
1345 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1346 return N1.getOperand(0);
1347 // fold ((B-A)+A) -> B
1348 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1349 return N0.getOperand(0);
1350 // fold (A+(B-(A+C))) to (B-C)
1351 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1352 N0 == N1.getOperand(1).getOperand(0))
1353 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1354 N1.getOperand(1).getOperand(1));
1355 // fold (A+(B-(C+A))) to (B-C)
1356 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1357 N0 == N1.getOperand(1).getOperand(1))
1358 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1359 N1.getOperand(1).getOperand(0));
1360 // fold (A+((B-A)+or-C)) to (B+or-C)
1361 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1362 N1.getOperand(0).getOpcode() == ISD::SUB &&
1363 N0 == N1.getOperand(0).getOperand(1))
1364 return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1365 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1367 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1368 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1369 SDValue N00 = N0.getOperand(0);
1370 SDValue N01 = N0.getOperand(1);
1371 SDValue N10 = N1.getOperand(0);
1372 SDValue N11 = N1.getOperand(1);
1374 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1375 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1376 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1377 DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1380 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1381 return SDValue(N, 0);
1383 // fold (a+b) -> (a|b) iff a and b share no bits.
1384 if (VT.isInteger() && !VT.isVector()) {
1385 APInt LHSZero, LHSOne;
1386 APInt RHSZero, RHSOne;
1387 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
1388 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1390 if (LHSZero.getBoolValue()) {
1391 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1393 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1394 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1395 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1396 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1397 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1401 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1402 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1403 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1404 if (Result.getNode()) return Result;
1406 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1407 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1408 if (Result.getNode()) return Result;
1411 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1412 if (N1.getOpcode() == ISD::SHL &&
1413 N1.getOperand(0).getOpcode() == ISD::SUB)
1414 if (ConstantSDNode *C =
1415 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1416 if (C->getAPIntValue() == 0)
1417 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
1418 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1419 N1.getOperand(0).getOperand(1),
1421 if (N0.getOpcode() == ISD::SHL &&
1422 N0.getOperand(0).getOpcode() == ISD::SUB)
1423 if (ConstantSDNode *C =
1424 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1425 if (C->getAPIntValue() == 0)
1426 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
1427 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1428 N0.getOperand(0).getOperand(1),
1431 if (N1.getOpcode() == ISD::AND) {
1432 SDValue AndOp0 = N1.getOperand(0);
1433 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1434 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1435 unsigned DestBits = VT.getScalarType().getSizeInBits();
1437 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1438 // and similar xforms where the inner op is either ~0 or 0.
1439 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1440 DebugLoc DL = N->getDebugLoc();
1441 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1445 // add (sext i1), X -> sub X, (zext i1)
1446 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1447 N0.getOperand(0).getValueType() == MVT::i1 &&
1448 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1449 DebugLoc DL = N->getDebugLoc();
1450 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1451 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1457 SDValue DAGCombiner::visitADDC(SDNode *N) {
1458 SDValue N0 = N->getOperand(0);
1459 SDValue N1 = N->getOperand(1);
1460 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1461 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1462 EVT VT = N0.getValueType();
1464 // If the flag result is dead, turn this into an ADD.
1465 if (N->hasNUsesOfValue(0, 1))
1466 return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0),
1467 DAG.getNode(ISD::CARRY_FALSE,
1468 N->getDebugLoc(), MVT::Glue));
1470 // canonicalize constant to RHS.
1472 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1474 // fold (addc x, 0) -> x + no carry out
1475 if (N1C && N1C->isNullValue())
1476 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1477 N->getDebugLoc(), MVT::Glue));
1479 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1480 APInt LHSZero, LHSOne;
1481 APInt RHSZero, RHSOne;
1482 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
1483 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1485 if (LHSZero.getBoolValue()) {
1486 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1488 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1489 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1490 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1491 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1492 return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1493 DAG.getNode(ISD::CARRY_FALSE,
1494 N->getDebugLoc(), MVT::Glue));
1500 SDValue DAGCombiner::visitADDE(SDNode *N) {
1501 SDValue N0 = N->getOperand(0);
1502 SDValue N1 = N->getOperand(1);
1503 SDValue CarryIn = N->getOperand(2);
1504 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1505 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1507 // canonicalize constant to RHS
1509 return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1512 // fold (adde x, y, false) -> (addc x, y)
1513 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1514 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1519 SDValue DAGCombiner::visitSUB(SDNode *N) {
1520 SDValue N0 = N->getOperand(0);
1521 SDValue N1 = N->getOperand(1);
1522 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1523 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1524 EVT VT = N0.getValueType();
1527 if (VT.isVector()) {
1528 SDValue FoldedVOp = SimplifyVBinOp(N);
1529 if (FoldedVOp.getNode()) return FoldedVOp;
1532 // fold (sub x, x) -> 0
1534 return DAG.getConstant(0, N->getValueType(0));
1535 // fold (sub c1, c2) -> c1-c2
1537 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1538 // fold (sub x, c) -> (add x, -c)
1540 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1541 DAG.getConstant(-N1C->getAPIntValue(), VT));
1542 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1543 if (N0C && N0C->isAllOnesValue())
1544 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
1545 // fold A-(A-B) -> B
1546 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1547 return N1.getOperand(1);
1548 // fold (A+B)-A -> B
1549 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1550 return N0.getOperand(1);
1551 // fold (A+B)-B -> A
1552 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1553 return N0.getOperand(0);
1554 // fold ((A+(B+or-C))-B) -> A+or-C
1555 if (N0.getOpcode() == ISD::ADD &&
1556 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1557 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1558 N0.getOperand(1).getOperand(0) == N1)
1559 return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1560 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1561 // fold ((A+(C+B))-B) -> A+C
1562 if (N0.getOpcode() == ISD::ADD &&
1563 N0.getOperand(1).getOpcode() == ISD::ADD &&
1564 N0.getOperand(1).getOperand(1) == N1)
1565 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1566 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1567 // fold ((A-(B-C))-C) -> A-B
1568 if (N0.getOpcode() == ISD::SUB &&
1569 N0.getOperand(1).getOpcode() == ISD::SUB &&
1570 N0.getOperand(1).getOperand(1) == N1)
1571 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1572 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1574 // If either operand of a sub is undef, the result is undef
1575 if (N0.getOpcode() == ISD::UNDEF)
1577 if (N1.getOpcode() == ISD::UNDEF)
1580 // If the relocation model supports it, consider symbol offsets.
1581 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1582 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1583 // fold (sub Sym, c) -> Sym-c
1584 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1585 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1587 (uint64_t)N1C->getSExtValue());
1588 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1589 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1590 if (GA->getGlobal() == GB->getGlobal())
1591 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1598 SDValue DAGCombiner::visitMUL(SDNode *N) {
1599 SDValue N0 = N->getOperand(0);
1600 SDValue N1 = N->getOperand(1);
1601 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1602 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1603 EVT VT = N0.getValueType();
1606 if (VT.isVector()) {
1607 SDValue FoldedVOp = SimplifyVBinOp(N);
1608 if (FoldedVOp.getNode()) return FoldedVOp;
1611 // fold (mul x, undef) -> 0
1612 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1613 return DAG.getConstant(0, VT);
1614 // fold (mul c1, c2) -> c1*c2
1616 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1617 // canonicalize constant to RHS
1619 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1620 // fold (mul x, 0) -> 0
1621 if (N1C && N1C->isNullValue())
1623 // fold (mul x, -1) -> 0-x
1624 if (N1C && N1C->isAllOnesValue())
1625 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1626 DAG.getConstant(0, VT), N0);
1627 // fold (mul x, (1 << c)) -> x << c
1628 if (N1C && N1C->getAPIntValue().isPowerOf2())
1629 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1630 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1631 getShiftAmountTy()));
1632 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1633 if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1634 unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1635 // FIXME: If the input is something that is easily negated (e.g. a
1636 // single-use add), we should put the negate there.
1637 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1638 DAG.getConstant(0, VT),
1639 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1640 DAG.getConstant(Log2Val, getShiftAmountTy())));
1642 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1643 if (N1C && N0.getOpcode() == ISD::SHL &&
1644 isa<ConstantSDNode>(N0.getOperand(1))) {
1645 SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1646 N1, N0.getOperand(1));
1647 AddToWorkList(C3.getNode());
1648 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1649 N0.getOperand(0), C3);
1652 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1655 SDValue Sh(0,0), Y(0,0);
1656 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1657 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1658 N0.getNode()->hasOneUse()) {
1660 } else if (N1.getOpcode() == ISD::SHL &&
1661 isa<ConstantSDNode>(N1.getOperand(1)) &&
1662 N1.getNode()->hasOneUse()) {
1667 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1668 Sh.getOperand(0), Y);
1669 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1670 Mul, Sh.getOperand(1));
1674 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1675 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1676 isa<ConstantSDNode>(N0.getOperand(1)))
1677 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1678 DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1679 N0.getOperand(0), N1),
1680 DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1681 N0.getOperand(1), N1));
1684 SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1685 if (RMUL.getNode() != 0)
1691 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1692 SDValue N0 = N->getOperand(0);
1693 SDValue N1 = N->getOperand(1);
1694 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1695 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1696 EVT VT = N->getValueType(0);
1699 if (VT.isVector()) {
1700 SDValue FoldedVOp = SimplifyVBinOp(N);
1701 if (FoldedVOp.getNode()) return FoldedVOp;
1704 // fold (sdiv c1, c2) -> c1/c2
1705 if (N0C && N1C && !N1C->isNullValue())
1706 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1707 // fold (sdiv X, 1) -> X
1708 if (N1C && N1C->getSExtValue() == 1LL)
1710 // fold (sdiv X, -1) -> 0-X
1711 if (N1C && N1C->isAllOnesValue())
1712 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1713 DAG.getConstant(0, VT), N0);
1714 // If we know the sign bits of both operands are zero, strength reduce to a
1715 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1716 if (!VT.isVector()) {
1717 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1718 return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1721 // fold (sdiv X, pow2) -> simple ops after legalize
1722 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1723 (isPowerOf2_64(N1C->getSExtValue()) ||
1724 isPowerOf2_64(-N1C->getSExtValue()))) {
1725 // If dividing by powers of two is cheap, then don't perform the following
1727 if (TLI.isPow2DivCheap())
1730 int64_t pow2 = N1C->getSExtValue();
1731 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1732 unsigned lg2 = Log2_64(abs2);
1734 // Splat the sign bit into the register
1735 SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1736 DAG.getConstant(VT.getSizeInBits()-1,
1737 getShiftAmountTy()));
1738 AddToWorkList(SGN.getNode());
1740 // Add (N0 < 0) ? abs2 - 1 : 0;
1741 SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1742 DAG.getConstant(VT.getSizeInBits() - lg2,
1743 getShiftAmountTy()));
1744 SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1745 AddToWorkList(SRL.getNode());
1746 AddToWorkList(ADD.getNode()); // Divide by pow2
1747 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1748 DAG.getConstant(lg2, getShiftAmountTy()));
1750 // If we're dividing by a positive value, we're done. Otherwise, we must
1751 // negate the result.
1755 AddToWorkList(SRA.getNode());
1756 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1757 DAG.getConstant(0, VT), SRA);
1760 // if integer divide is expensive and we satisfy the requirements, emit an
1761 // alternate sequence.
1762 if (N1C && (N1C->getSExtValue() < -1 || N1C->getSExtValue() > 1) &&
1763 !TLI.isIntDivCheap()) {
1764 SDValue Op = BuildSDIV(N);
1765 if (Op.getNode()) return Op;
1769 if (N0.getOpcode() == ISD::UNDEF)
1770 return DAG.getConstant(0, VT);
1771 // X / undef -> undef
1772 if (N1.getOpcode() == ISD::UNDEF)
1778 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1779 SDValue N0 = N->getOperand(0);
1780 SDValue N1 = N->getOperand(1);
1781 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1782 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1783 EVT VT = N->getValueType(0);
1786 if (VT.isVector()) {
1787 SDValue FoldedVOp = SimplifyVBinOp(N);
1788 if (FoldedVOp.getNode()) return FoldedVOp;
1791 // fold (udiv c1, c2) -> c1/c2
1792 if (N0C && N1C && !N1C->isNullValue())
1793 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1794 // fold (udiv x, (1 << c)) -> x >>u c
1795 if (N1C && N1C->getAPIntValue().isPowerOf2())
1796 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1797 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1798 getShiftAmountTy()));
1799 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1800 if (N1.getOpcode() == ISD::SHL) {
1801 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1802 if (SHC->getAPIntValue().isPowerOf2()) {
1803 EVT ADDVT = N1.getOperand(1).getValueType();
1804 SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1806 DAG.getConstant(SHC->getAPIntValue()
1809 AddToWorkList(Add.getNode());
1810 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1814 // fold (udiv x, c) -> alternate
1815 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1816 SDValue Op = BuildUDIV(N);
1817 if (Op.getNode()) return Op;
1821 if (N0.getOpcode() == ISD::UNDEF)
1822 return DAG.getConstant(0, VT);
1823 // X / undef -> undef
1824 if (N1.getOpcode() == ISD::UNDEF)
1830 SDValue DAGCombiner::visitSREM(SDNode *N) {
1831 SDValue N0 = N->getOperand(0);
1832 SDValue N1 = N->getOperand(1);
1833 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1834 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1835 EVT VT = N->getValueType(0);
1837 // fold (srem c1, c2) -> c1%c2
1838 if (N0C && N1C && !N1C->isNullValue())
1839 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1840 // If we know the sign bits of both operands are zero, strength reduce to a
1841 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1842 if (!VT.isVector()) {
1843 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1844 return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
1847 // If X/C can be simplified by the division-by-constant logic, lower
1848 // X%C to the equivalent of X-X/C*C.
1849 if (N1C && !N1C->isNullValue()) {
1850 SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
1851 AddToWorkList(Div.getNode());
1852 SDValue OptimizedDiv = combine(Div.getNode());
1853 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1854 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1856 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1857 AddToWorkList(Mul.getNode());
1863 if (N0.getOpcode() == ISD::UNDEF)
1864 return DAG.getConstant(0, VT);
1865 // X % undef -> undef
1866 if (N1.getOpcode() == ISD::UNDEF)
1872 SDValue DAGCombiner::visitUREM(SDNode *N) {
1873 SDValue N0 = N->getOperand(0);
1874 SDValue N1 = N->getOperand(1);
1875 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1876 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1877 EVT VT = N->getValueType(0);
1879 // fold (urem c1, c2) -> c1%c2
1880 if (N0C && N1C && !N1C->isNullValue())
1881 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
1882 // fold (urem x, pow2) -> (and x, pow2-1)
1883 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1884 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
1885 DAG.getConstant(N1C->getAPIntValue()-1,VT));
1886 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1887 if (N1.getOpcode() == ISD::SHL) {
1888 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1889 if (SHC->getAPIntValue().isPowerOf2()) {
1891 DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
1892 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1894 AddToWorkList(Add.getNode());
1895 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
1900 // If X/C can be simplified by the division-by-constant logic, lower
1901 // X%C to the equivalent of X-X/C*C.
1902 if (N1C && !N1C->isNullValue()) {
1903 SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
1904 AddToWorkList(Div.getNode());
1905 SDValue OptimizedDiv = combine(Div.getNode());
1906 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1907 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1909 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1910 AddToWorkList(Mul.getNode());
1916 if (N0.getOpcode() == ISD::UNDEF)
1917 return DAG.getConstant(0, VT);
1918 // X % undef -> undef
1919 if (N1.getOpcode() == ISD::UNDEF)
1925 SDValue DAGCombiner::visitMULHS(SDNode *N) {
1926 SDValue N0 = N->getOperand(0);
1927 SDValue N1 = N->getOperand(1);
1928 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1929 EVT VT = N->getValueType(0);
1930 DebugLoc DL = N->getDebugLoc();
1932 // fold (mulhs x, 0) -> 0
1933 if (N1C && N1C->isNullValue())
1935 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1936 if (N1C && N1C->getAPIntValue() == 1)
1937 return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
1938 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
1939 getShiftAmountTy()));
1940 // fold (mulhs x, undef) -> 0
1941 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1942 return DAG.getConstant(0, VT);
1944 // If the type twice as wide is legal, transform the mulhs to a wider multiply
1946 if (VT.isSimple() && !VT.isVector()) {
1947 MVT Simple = VT.getSimpleVT();
1948 unsigned SimpleSize = Simple.getSizeInBits();
1949 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
1950 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
1951 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
1952 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
1953 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
1954 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
1955 DAG.getConstant(SimpleSize, getShiftAmountTy()));
1956 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
1963 SDValue DAGCombiner::visitMULHU(SDNode *N) {
1964 SDValue N0 = N->getOperand(0);
1965 SDValue N1 = N->getOperand(1);
1966 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1967 EVT VT = N->getValueType(0);
1968 DebugLoc DL = N->getDebugLoc();
1970 // fold (mulhu x, 0) -> 0
1971 if (N1C && N1C->isNullValue())
1973 // fold (mulhu x, 1) -> 0
1974 if (N1C && N1C->getAPIntValue() == 1)
1975 return DAG.getConstant(0, N0.getValueType());
1976 // fold (mulhu x, undef) -> 0
1977 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1978 return DAG.getConstant(0, VT);
1980 // If the type twice as wide is legal, transform the mulhu to a wider multiply
1982 if (VT.isSimple() && !VT.isVector()) {
1983 MVT Simple = VT.getSimpleVT();
1984 unsigned SimpleSize = Simple.getSizeInBits();
1985 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
1986 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
1987 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
1988 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
1989 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
1990 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
1991 DAG.getConstant(SimpleSize, getShiftAmountTy()));
1992 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
1999 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2000 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2001 /// that are being performed. Return true if a simplification was made.
2003 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2005 // If the high half is not needed, just compute the low half.
2006 bool HiExists = N->hasAnyUseOfValue(1);
2008 (!LegalOperations ||
2009 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2010 SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2011 N->op_begin(), N->getNumOperands());
2012 return CombineTo(N, Res, Res);
2015 // If the low half is not needed, just compute the high half.
2016 bool LoExists = N->hasAnyUseOfValue(0);
2018 (!LegalOperations ||
2019 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2020 SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2021 N->op_begin(), N->getNumOperands());
2022 return CombineTo(N, Res, Res);
2025 // If both halves are used, return as it is.
2026 if (LoExists && HiExists)
2029 // If the two computed results can be simplified separately, separate them.
2031 SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2032 N->op_begin(), N->getNumOperands());
2033 AddToWorkList(Lo.getNode());
2034 SDValue LoOpt = combine(Lo.getNode());
2035 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2036 (!LegalOperations ||
2037 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2038 return CombineTo(N, LoOpt, LoOpt);
2042 SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2043 N->op_begin(), N->getNumOperands());
2044 AddToWorkList(Hi.getNode());
2045 SDValue HiOpt = combine(Hi.getNode());
2046 if (HiOpt.getNode() && HiOpt != Hi &&
2047 (!LegalOperations ||
2048 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2049 return CombineTo(N, HiOpt, HiOpt);
2055 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2056 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2057 if (Res.getNode()) return Res;
2059 EVT VT = N->getValueType(0);
2060 DebugLoc DL = N->getDebugLoc();
2062 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2064 if (VT.isSimple() && !VT.isVector()) {
2065 MVT Simple = VT.getSimpleVT();
2066 unsigned SimpleSize = Simple.getSizeInBits();
2067 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2068 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2069 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2070 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2071 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2072 // Compute the high part as N1.
2073 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2074 DAG.getConstant(SimpleSize, getShiftAmountTy()));
2075 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2076 // Compute the low part as N0.
2077 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2078 return CombineTo(N, Lo, Hi);
2085 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2086 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2087 if (Res.getNode()) return Res;
2089 EVT VT = N->getValueType(0);
2090 DebugLoc DL = N->getDebugLoc();
2092 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2094 if (VT.isSimple() && !VT.isVector()) {
2095 MVT Simple = VT.getSimpleVT();
2096 unsigned SimpleSize = Simple.getSizeInBits();
2097 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2098 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2099 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2100 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2101 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2102 // Compute the high part as N1.
2103 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2104 DAG.getConstant(SimpleSize, getShiftAmountTy()));
2105 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2106 // Compute the low part as N0.
2107 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2108 return CombineTo(N, Lo, Hi);
2115 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2116 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2117 if (Res.getNode()) return Res;
2122 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2123 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2124 if (Res.getNode()) return Res;
2129 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2130 /// two operands of the same opcode, try to simplify it.
2131 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2132 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2133 EVT VT = N0.getValueType();
2134 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2136 // Bail early if none of these transforms apply.
2137 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2139 // For each of OP in AND/OR/XOR:
2140 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2141 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2142 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2143 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2145 // do not sink logical op inside of a vector extend, since it may combine
2147 EVT Op0VT = N0.getOperand(0).getValueType();
2148 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2149 N0.getOpcode() == ISD::SIGN_EXTEND ||
2150 // Avoid infinite looping with PromoteIntBinOp.
2151 (N0.getOpcode() == ISD::ANY_EXTEND &&
2152 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2153 (N0.getOpcode() == ISD::TRUNCATE &&
2154 (!TLI.isZExtFree(VT, Op0VT) ||
2155 !TLI.isTruncateFree(Op0VT, VT)) &&
2156 TLI.isTypeLegal(Op0VT))) &&
2158 Op0VT == N1.getOperand(0).getValueType() &&
2159 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2160 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2161 N0.getOperand(0).getValueType(),
2162 N0.getOperand(0), N1.getOperand(0));
2163 AddToWorkList(ORNode.getNode());
2164 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
2167 // For each of OP in SHL/SRL/SRA/AND...
2168 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2169 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2170 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2171 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2172 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2173 N0.getOperand(1) == N1.getOperand(1)) {
2174 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2175 N0.getOperand(0).getValueType(),
2176 N0.getOperand(0), N1.getOperand(0));
2177 AddToWorkList(ORNode.getNode());
2178 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
2179 ORNode, N0.getOperand(1));
2185 SDValue DAGCombiner::visitAND(SDNode *N) {
2186 SDValue N0 = N->getOperand(0);
2187 SDValue N1 = N->getOperand(1);
2188 SDValue LL, LR, RL, RR, CC0, CC1;
2189 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2190 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2191 EVT VT = N1.getValueType();
2192 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2195 if (VT.isVector()) {
2196 SDValue FoldedVOp = SimplifyVBinOp(N);
2197 if (FoldedVOp.getNode()) return FoldedVOp;
2200 // fold (and x, undef) -> 0
2201 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2202 return DAG.getConstant(0, VT);
2203 // fold (and c1, c2) -> c1&c2
2205 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2206 // canonicalize constant to RHS
2208 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
2209 // fold (and x, -1) -> x
2210 if (N1C && N1C->isAllOnesValue())
2212 // if (and x, c) is known to be zero, return 0
2213 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2214 APInt::getAllOnesValue(BitWidth)))
2215 return DAG.getConstant(0, VT);
2217 SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
2218 if (RAND.getNode() != 0)
2220 // fold (and (or x, C), D) -> D if (C & D) == D
2221 if (N1C && N0.getOpcode() == ISD::OR)
2222 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2223 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2225 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2226 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2227 SDValue N0Op0 = N0.getOperand(0);
2228 APInt Mask = ~N1C->getAPIntValue();
2229 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2230 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2231 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
2232 N0.getValueType(), N0Op0);
2234 // Replace uses of the AND with uses of the Zero extend node.
2237 // We actually want to replace all uses of the any_extend with the
2238 // zero_extend, to avoid duplicating things. This will later cause this
2239 // AND to be folded.
2240 CombineTo(N0.getNode(), Zext);
2241 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2244 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2245 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2246 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2247 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2249 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2250 LL.getValueType().isInteger()) {
2251 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2252 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2253 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2254 LR.getValueType(), LL, RL);
2255 AddToWorkList(ORNode.getNode());
2256 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2258 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2259 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2260 SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
2261 LR.getValueType(), LL, RL);
2262 AddToWorkList(ANDNode.getNode());
2263 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2265 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2266 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2267 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2268 LR.getValueType(), LL, RL);
2269 AddToWorkList(ORNode.getNode());
2270 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2273 // canonicalize equivalent to ll == rl
2274 if (LL == RR && LR == RL) {
2275 Op1 = ISD::getSetCCSwappedOperands(Op1);
2278 if (LL == RL && LR == RR) {
2279 bool isInteger = LL.getValueType().isInteger();
2280 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2281 if (Result != ISD::SETCC_INVALID &&
2282 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2283 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2288 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2289 if (N0.getOpcode() == N1.getOpcode()) {
2290 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2291 if (Tmp.getNode()) return Tmp;
2294 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2295 // fold (and (sra)) -> (and (srl)) when possible.
2296 if (!VT.isVector() &&
2297 SimplifyDemandedBits(SDValue(N, 0)))
2298 return SDValue(N, 0);
2300 // fold (zext_inreg (extload x)) -> (zextload x)
2301 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2302 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2303 EVT MemVT = LN0->getMemoryVT();
2304 // If we zero all the possible extended bits, then we can turn this into
2305 // a zextload if we are running before legalize or the operation is legal.
2306 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2307 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2308 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2309 ((!LegalOperations && !LN0->isVolatile()) ||
2310 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2311 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getDebugLoc(),
2312 LN0->getChain(), LN0->getBasePtr(),
2313 LN0->getPointerInfo(), MemVT,
2314 LN0->isVolatile(), LN0->isNonTemporal(),
2315 LN0->getAlignment());
2317 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2318 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2321 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2322 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2324 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2325 EVT MemVT = LN0->getMemoryVT();
2326 // If we zero all the possible extended bits, then we can turn this into
2327 // a zextload if we are running before legalize or the operation is legal.
2328 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2329 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2330 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2331 ((!LegalOperations && !LN0->isVolatile()) ||
2332 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2333 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getDebugLoc(),
2335 LN0->getBasePtr(), LN0->getPointerInfo(),
2337 LN0->isVolatile(), LN0->isNonTemporal(),
2338 LN0->getAlignment());
2340 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2341 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2345 // fold (and (load x), 255) -> (zextload x, i8)
2346 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2347 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2348 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2349 (N0.getOpcode() == ISD::ANY_EXTEND &&
2350 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2351 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2352 LoadSDNode *LN0 = HasAnyExt
2353 ? cast<LoadSDNode>(N0.getOperand(0))
2354 : cast<LoadSDNode>(N0);
2355 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2356 LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
2357 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2358 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2359 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2360 EVT LoadedVT = LN0->getMemoryVT();
2362 if (ExtVT == LoadedVT &&
2363 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2364 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2367 DAG.getExtLoad(ISD::ZEXTLOAD, LoadResultTy, LN0->getDebugLoc(),
2368 LN0->getChain(), LN0->getBasePtr(),
2369 LN0->getPointerInfo(),
2370 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2371 LN0->getAlignment());
2373 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2374 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2377 // Do not change the width of a volatile load.
2378 // Do not generate loads of non-round integer types since these can
2379 // be expensive (and would be wrong if the type is not byte sized).
2380 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2381 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2382 EVT PtrType = LN0->getOperand(1).getValueType();
2384 unsigned Alignment = LN0->getAlignment();
2385 SDValue NewPtr = LN0->getBasePtr();
2387 // For big endian targets, we need to add an offset to the pointer
2388 // to load the correct bytes. For little endian systems, we merely
2389 // need to read fewer bytes from the same pointer.
2390 if (TLI.isBigEndian()) {
2391 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2392 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2393 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2394 NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
2395 NewPtr, DAG.getConstant(PtrOff, PtrType));
2396 Alignment = MinAlign(Alignment, PtrOff);
2399 AddToWorkList(NewPtr.getNode());
2401 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2403 DAG.getExtLoad(ISD::ZEXTLOAD, LoadResultTy, LN0->getDebugLoc(),
2404 LN0->getChain(), NewPtr,
2405 LN0->getPointerInfo(),
2406 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2409 CombineTo(LN0, Load, Load.getValue(1));
2410 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2419 SDValue DAGCombiner::visitOR(SDNode *N) {
2420 SDValue N0 = N->getOperand(0);
2421 SDValue N1 = N->getOperand(1);
2422 SDValue LL, LR, RL, RR, CC0, CC1;
2423 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2424 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2425 EVT VT = N1.getValueType();
2428 if (VT.isVector()) {
2429 SDValue FoldedVOp = SimplifyVBinOp(N);
2430 if (FoldedVOp.getNode()) return FoldedVOp;
2433 // fold (or x, undef) -> -1
2434 if (!LegalOperations &&
2435 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
2436 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
2437 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
2439 // fold (or c1, c2) -> c1|c2
2441 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
2442 // canonicalize constant to RHS
2444 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
2445 // fold (or x, 0) -> x
2446 if (N1C && N1C->isNullValue())
2448 // fold (or x, -1) -> -1
2449 if (N1C && N1C->isAllOnesValue())
2451 // fold (or x, c) -> c iff (x & ~c) == 0
2452 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
2455 SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
2456 if (ROR.getNode() != 0)
2458 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
2459 // iff (c1 & c2) == 0.
2460 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
2461 isa<ConstantSDNode>(N0.getOperand(1))) {
2462 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
2463 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
2464 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
2465 DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2466 N0.getOperand(0), N1),
2467 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
2469 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
2470 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2471 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2472 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2474 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2475 LL.getValueType().isInteger()) {
2476 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
2477 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
2478 if (cast<ConstantSDNode>(LR)->isNullValue() &&
2479 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
2480 SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
2481 LR.getValueType(), LL, RL);
2482 AddToWorkList(ORNode.getNode());
2483 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2485 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
2486 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
2487 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2488 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
2489 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
2490 LR.getValueType(), LL, RL);
2491 AddToWorkList(ANDNode.getNode());
2492 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2495 // canonicalize equivalent to ll == rl
2496 if (LL == RR && LR == RL) {
2497 Op1 = ISD::getSetCCSwappedOperands(Op1);
2500 if (LL == RL && LR == RR) {
2501 bool isInteger = LL.getValueType().isInteger();
2502 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
2503 if (Result != ISD::SETCC_INVALID &&
2504 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2505 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2510 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
2511 if (N0.getOpcode() == N1.getOpcode()) {
2512 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2513 if (Tmp.getNode()) return Tmp;
2516 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
2517 if (N0.getOpcode() == ISD::AND &&
2518 N1.getOpcode() == ISD::AND &&
2519 N0.getOperand(1).getOpcode() == ISD::Constant &&
2520 N1.getOperand(1).getOpcode() == ISD::Constant &&
2521 // Don't increase # computations.
2522 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
2523 // We can only do this xform if we know that bits from X that are set in C2
2524 // but not in C1 are already zero. Likewise for Y.
2525 const APInt &LHSMask =
2526 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2527 const APInt &RHSMask =
2528 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
2530 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
2531 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
2532 SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2533 N0.getOperand(0), N1.getOperand(0));
2534 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
2535 DAG.getConstant(LHSMask | RHSMask, VT));
2539 // See if this is some rotate idiom.
2540 if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
2541 return SDValue(Rot, 0);
2543 // Simplify the operands using demanded-bits information.
2544 if (!VT.isVector() &&
2545 SimplifyDemandedBits(SDValue(N, 0)))
2546 return SDValue(N, 0);
2551 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
2552 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
2553 if (Op.getOpcode() == ISD::AND) {
2554 if (isa<ConstantSDNode>(Op.getOperand(1))) {
2555 Mask = Op.getOperand(1);
2556 Op = Op.getOperand(0);
2562 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
2570 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
2571 // idioms for rotate, and if the target supports rotation instructions, generate
2573 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
2574 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
2575 EVT VT = LHS.getValueType();
2576 if (!TLI.isTypeLegal(VT)) return 0;
2578 // The target must have at least one rotate flavor.
2579 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
2580 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
2581 if (!HasROTL && !HasROTR) return 0;
2583 // Match "(X shl/srl V1) & V2" where V2 may not be present.
2584 SDValue LHSShift; // The shift.
2585 SDValue LHSMask; // AND value if any.
2586 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
2587 return 0; // Not part of a rotate.
2589 SDValue RHSShift; // The shift.
2590 SDValue RHSMask; // AND value if any.
2591 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
2592 return 0; // Not part of a rotate.
2594 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
2595 return 0; // Not shifting the same value.
2597 if (LHSShift.getOpcode() == RHSShift.getOpcode())
2598 return 0; // Shifts must disagree.
2600 // Canonicalize shl to left side in a shl/srl pair.
2601 if (RHSShift.getOpcode() == ISD::SHL) {
2602 std::swap(LHS, RHS);
2603 std::swap(LHSShift, RHSShift);
2604 std::swap(LHSMask , RHSMask );
2607 unsigned OpSizeInBits = VT.getSizeInBits();
2608 SDValue LHSShiftArg = LHSShift.getOperand(0);
2609 SDValue LHSShiftAmt = LHSShift.getOperand(1);
2610 SDValue RHSShiftAmt = RHSShift.getOperand(1);
2612 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
2613 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
2614 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2615 RHSShiftAmt.getOpcode() == ISD::Constant) {
2616 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
2617 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
2618 if ((LShVal + RShVal) != OpSizeInBits)
2623 Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
2625 Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
2627 // If there is an AND of either shifted operand, apply it to the result.
2628 if (LHSMask.getNode() || RHSMask.getNode()) {
2629 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2631 if (LHSMask.getNode()) {
2632 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2633 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2635 if (RHSMask.getNode()) {
2636 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2637 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2640 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
2643 return Rot.getNode();
2646 // If there is a mask here, and we have a variable shift, we can't be sure
2647 // that we're masking out the right stuff.
2648 if (LHSMask.getNode() || RHSMask.getNode())
2651 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2652 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2653 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2654 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2655 if (ConstantSDNode *SUBC =
2656 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2657 if (SUBC->getAPIntValue() == OpSizeInBits) {
2659 return DAG.getNode(ISD::ROTL, DL, VT,
2660 LHSShiftArg, LHSShiftAmt).getNode();
2662 return DAG.getNode(ISD::ROTR, DL, VT,
2663 LHSShiftArg, RHSShiftAmt).getNode();
2668 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2669 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2670 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2671 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2672 if (ConstantSDNode *SUBC =
2673 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2674 if (SUBC->getAPIntValue() == OpSizeInBits) {
2676 return DAG.getNode(ISD::ROTR, DL, VT,
2677 LHSShiftArg, RHSShiftAmt).getNode();
2679 return DAG.getNode(ISD::ROTL, DL, VT,
2680 LHSShiftArg, LHSShiftAmt).getNode();
2685 // Look for sign/zext/any-extended or truncate cases:
2686 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2687 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2688 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2689 || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
2690 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2691 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2692 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2693 || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
2694 SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
2695 SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
2696 if (RExtOp0.getOpcode() == ISD::SUB &&
2697 RExtOp0.getOperand(1) == LExtOp0) {
2698 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2700 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2701 // (rotr x, (sub 32, y))
2702 if (ConstantSDNode *SUBC =
2703 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2704 if (SUBC->getAPIntValue() == OpSizeInBits) {
2705 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
2707 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
2710 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2711 RExtOp0 == LExtOp0.getOperand(1)) {
2712 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2714 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2715 // (rotl x, (sub 32, y))
2716 if (ConstantSDNode *SUBC =
2717 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2718 if (SUBC->getAPIntValue() == OpSizeInBits) {
2719 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
2721 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
2730 SDValue DAGCombiner::visitXOR(SDNode *N) {
2731 SDValue N0 = N->getOperand(0);
2732 SDValue N1 = N->getOperand(1);
2733 SDValue LHS, RHS, CC;
2734 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2735 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2736 EVT VT = N0.getValueType();
2739 if (VT.isVector()) {
2740 SDValue FoldedVOp = SimplifyVBinOp(N);
2741 if (FoldedVOp.getNode()) return FoldedVOp;
2744 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2745 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2746 return DAG.getConstant(0, VT);
2747 // fold (xor x, undef) -> undef
2748 if (N0.getOpcode() == ISD::UNDEF)
2750 if (N1.getOpcode() == ISD::UNDEF)
2752 // fold (xor c1, c2) -> c1^c2
2754 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
2755 // canonicalize constant to RHS
2757 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
2758 // fold (xor x, 0) -> x
2759 if (N1C && N1C->isNullValue())
2762 SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
2763 if (RXOR.getNode() != 0)
2766 // fold !(x cc y) -> (x !cc y)
2767 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2768 bool isInt = LHS.getValueType().isInteger();
2769 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2772 if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
2773 switch (N0.getOpcode()) {
2775 llvm_unreachable("Unhandled SetCC Equivalent!");
2777 return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
2778 case ISD::SELECT_CC:
2779 return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
2780 N0.getOperand(3), NotCC);
2785 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2786 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2787 N0.getNode()->hasOneUse() &&
2788 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2789 SDValue V = N0.getOperand(0);
2790 V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
2791 DAG.getConstant(1, V.getValueType()));
2792 AddToWorkList(V.getNode());
2793 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
2796 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
2797 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2798 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2799 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2800 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2801 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2802 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2803 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2804 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2805 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2808 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
2809 if (N1C && N1C->isAllOnesValue() &&
2810 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2811 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2812 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2813 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2814 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2815 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2816 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2817 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2820 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
2821 if (N1C && N0.getOpcode() == ISD::XOR) {
2822 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2823 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2825 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
2826 DAG.getConstant(N1C->getAPIntValue() ^
2827 N00C->getAPIntValue(), VT));
2829 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
2830 DAG.getConstant(N1C->getAPIntValue() ^
2831 N01C->getAPIntValue(), VT));
2833 // fold (xor x, x) -> 0
2835 if (!VT.isVector()) {
2836 return DAG.getConstant(0, VT);
2837 } else if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)){
2838 // Produce a vector of zeros.
2839 SDValue El = DAG.getConstant(0, VT.getVectorElementType());
2840 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
2841 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
2842 &Ops[0], Ops.size());
2846 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2847 if (N0.getOpcode() == N1.getOpcode()) {
2848 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2849 if (Tmp.getNode()) return Tmp;
2852 // Simplify the expression using non-local knowledge.
2853 if (!VT.isVector() &&
2854 SimplifyDemandedBits(SDValue(N, 0)))
2855 return SDValue(N, 0);
2860 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2861 /// the shift amount is a constant.
2862 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2863 SDNode *LHS = N->getOperand(0).getNode();
2864 if (!LHS->hasOneUse()) return SDValue();
2866 // We want to pull some binops through shifts, so that we have (and (shift))
2867 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2868 // thing happens with address calculations, so it's important to canonicalize
2870 bool HighBitSet = false; // Can we transform this if the high bit is set?
2872 switch (LHS->getOpcode()) {
2873 default: return SDValue();
2876 HighBitSet = false; // We can only transform sra if the high bit is clear.
2879 HighBitSet = true; // We can only transform sra if the high bit is set.
2882 if (N->getOpcode() != ISD::SHL)
2883 return SDValue(); // only shl(add) not sr[al](add).
2884 HighBitSet = false; // We can only transform sra if the high bit is clear.
2888 // We require the RHS of the binop to be a constant as well.
2889 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2890 if (!BinOpCst) return SDValue();
2892 // FIXME: disable this unless the input to the binop is a shift by a constant.
2893 // If it is not a shift, it pessimizes some common cases like:
2895 // void foo(int *X, int i) { X[i & 1235] = 1; }
2896 // int bar(int *X, int i) { return X[i & 255]; }
2897 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
2898 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2899 BinOpLHSVal->getOpcode() != ISD::SRA &&
2900 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2901 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2904 EVT VT = N->getValueType(0);
2906 // If this is a signed shift right, and the high bit is modified by the
2907 // logical operation, do not perform the transformation. The highBitSet
2908 // boolean indicates the value of the high bit of the constant which would
2909 // cause it to be modified for this operation.
2910 if (N->getOpcode() == ISD::SRA) {
2911 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2912 if (BinOpRHSSignSet != HighBitSet)
2916 // Fold the constants, shifting the binop RHS by the shift amount.
2917 SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
2919 LHS->getOperand(1), N->getOperand(1));
2921 // Create the new shift.
2922 SDValue NewShift = DAG.getNode(N->getOpcode(),
2923 LHS->getOperand(0).getDebugLoc(),
2924 VT, LHS->getOperand(0), N->getOperand(1));
2926 // Create the new binop.
2927 return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
2930 SDValue DAGCombiner::visitSHL(SDNode *N) {
2931 SDValue N0 = N->getOperand(0);
2932 SDValue N1 = N->getOperand(1);
2933 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2934 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2935 EVT VT = N0.getValueType();
2936 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
2938 // fold (shl c1, c2) -> c1<<c2
2940 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
2941 // fold (shl 0, x) -> 0
2942 if (N0C && N0C->isNullValue())
2944 // fold (shl x, c >= size(x)) -> undef
2945 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2946 return DAG.getUNDEF(VT);
2947 // fold (shl x, 0) -> x
2948 if (N1C && N1C->isNullValue())
2950 // if (shl x, c) is known to be zero, return 0
2951 if (DAG.MaskedValueIsZero(SDValue(N, 0),
2952 APInt::getAllOnesValue(OpSizeInBits)))
2953 return DAG.getConstant(0, VT);
2954 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
2955 if (N1.getOpcode() == ISD::TRUNCATE &&
2956 N1.getOperand(0).getOpcode() == ISD::AND &&
2957 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2958 SDValue N101 = N1.getOperand(0).getOperand(1);
2959 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2960 EVT TruncVT = N1.getValueType();
2961 SDValue N100 = N1.getOperand(0).getOperand(0);
2962 APInt TruncC = N101C->getAPIntValue();
2963 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
2964 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
2965 DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
2966 DAG.getNode(ISD::TRUNCATE,
2969 DAG.getConstant(TruncC, TruncVT)));
2973 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2974 return SDValue(N, 0);
2976 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
2977 if (N1C && N0.getOpcode() == ISD::SHL &&
2978 N0.getOperand(1).getOpcode() == ISD::Constant) {
2979 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2980 uint64_t c2 = N1C->getZExtValue();
2981 if (c1 + c2 >= OpSizeInBits)
2982 return DAG.getConstant(0, VT);
2983 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
2984 DAG.getConstant(c1 + c2, N1.getValueType()));
2987 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
2988 // For this to be valid, the second form must not preserve any of the bits
2989 // that are shifted out by the inner shift in the first form. This means
2990 // the outer shift size must be >= the number of bits added by the ext.
2991 // As a corollary, we don't care what kind of ext it is.
2992 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
2993 N0.getOpcode() == ISD::ANY_EXTEND ||
2994 N0.getOpcode() == ISD::SIGN_EXTEND) &&
2995 N0.getOperand(0).getOpcode() == ISD::SHL &&
2996 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
2998 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
2999 uint64_t c2 = N1C->getZExtValue();
3000 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3001 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3002 if (c2 >= OpSizeInBits - InnerShiftSize) {
3003 if (c1 + c2 >= OpSizeInBits)
3004 return DAG.getConstant(0, VT);
3005 return DAG.getNode(ISD::SHL, N0->getDebugLoc(), VT,
3006 DAG.getNode(N0.getOpcode(), N0->getDebugLoc(), VT,
3007 N0.getOperand(0)->getOperand(0)),
3008 DAG.getConstant(c1 + c2, N1.getValueType()));
3012 // fold (shl (srl x, c1), c2) -> (shl (and x, (shl -1, c1)), (sub c2, c1)) or
3013 // (srl (and x, (shl -1, c1)), (sub c1, c2))
3014 if (N1C && N0.getOpcode() == ISD::SRL &&
3015 N0.getOperand(1).getOpcode() == ISD::Constant) {
3016 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3017 if (c1 < VT.getSizeInBits()) {
3018 uint64_t c2 = N1C->getZExtValue();
3019 SDValue HiBitsMask =
3020 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3021 VT.getSizeInBits() - c1),
3023 SDValue Mask = DAG.getNode(ISD::AND, N0.getDebugLoc(), VT,
3027 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, Mask,
3028 DAG.getConstant(c2-c1, N1.getValueType()));
3030 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Mask,
3031 DAG.getConstant(c1-c2, N1.getValueType()));
3034 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3035 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3036 SDValue HiBitsMask =
3037 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3038 VT.getSizeInBits() -
3039 N1C->getZExtValue()),
3041 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3046 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3047 if (NewSHL.getNode())
3054 SDValue DAGCombiner::visitSRA(SDNode *N) {
3055 SDValue N0 = N->getOperand(0);
3056 SDValue N1 = N->getOperand(1);
3057 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3058 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3059 EVT VT = N0.getValueType();
3060 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3062 // fold (sra c1, c2) -> (sra c1, c2)
3064 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3065 // fold (sra 0, x) -> 0
3066 if (N0C && N0C->isNullValue())
3068 // fold (sra -1, x) -> -1
3069 if (N0C && N0C->isAllOnesValue())
3071 // fold (sra x, (setge c, size(x))) -> undef
3072 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3073 return DAG.getUNDEF(VT);
3074 // fold (sra x, 0) -> x
3075 if (N1C && N1C->isNullValue())
3077 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3079 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3080 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3081 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3083 ExtVT = EVT::getVectorVT(*DAG.getContext(),
3084 ExtVT, VT.getVectorNumElements());
3085 if ((!LegalOperations ||
3086 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3087 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
3088 N0.getOperand(0), DAG.getValueType(ExtVT));
3091 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3092 if (N1C && N0.getOpcode() == ISD::SRA) {
3093 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3094 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3095 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3096 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
3097 DAG.getConstant(Sum, N1C->getValueType(0)));
3101 // fold (sra (shl X, m), (sub result_size, n))
3102 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3103 // result_size - n != m.
3104 // If truncate is free for the target sext(shl) is likely to result in better
3106 if (N0.getOpcode() == ISD::SHL) {
3107 // Get the two constanst of the shifts, CN0 = m, CN = n.
3108 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3110 // Determine what the truncate's result bitsize and type would be.
3112 EVT::getIntegerVT(*DAG.getContext(),
3113 OpSizeInBits - N1C->getZExtValue());
3114 // Determine the residual right-shift amount.
3115 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3117 // If the shift is not a no-op (in which case this should be just a sign
3118 // extend already), the truncated to type is legal, sign_extend is legal
3119 // on that type, and the truncate to that type is both legal and free,
3120 // perform the transform.
3121 if ((ShiftAmt > 0) &&
3122 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3123 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3124 TLI.isTruncateFree(VT, TruncVT)) {
3126 SDValue Amt = DAG.getConstant(ShiftAmt, getShiftAmountTy());
3127 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
3128 N0.getOperand(0), Amt);
3129 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
3131 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
3132 N->getValueType(0), Trunc);
3137 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3138 if (N1.getOpcode() == ISD::TRUNCATE &&
3139 N1.getOperand(0).getOpcode() == ISD::AND &&
3140 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3141 SDValue N101 = N1.getOperand(0).getOperand(1);
3142 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3143 EVT TruncVT = N1.getValueType();
3144 SDValue N100 = N1.getOperand(0).getOperand(0);
3145 APInt TruncC = N101C->getAPIntValue();
3146 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3147 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
3148 DAG.getNode(ISD::AND, N->getDebugLoc(),
3150 DAG.getNode(ISD::TRUNCATE,
3153 DAG.getConstant(TruncC, TruncVT)));
3157 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3158 // if c1 is equal to the number of bits the trunc removes
3159 if (N0.getOpcode() == ISD::TRUNCATE &&
3160 (N0.getOperand(0).getOpcode() == ISD::SRL ||
3161 N0.getOperand(0).getOpcode() == ISD::SRA) &&
3162 N0.getOperand(0).hasOneUse() &&
3163 N0.getOperand(0).getOperand(1).hasOneUse() &&
3164 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3165 EVT LargeVT = N0.getOperand(0).getValueType();
3166 ConstantSDNode *LargeShiftAmt =
3167 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3169 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3170 LargeShiftAmt->getZExtValue()) {
3172 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3173 getShiftAmountTy());
3174 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), LargeVT,
3175 N0.getOperand(0).getOperand(0), Amt);
3176 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, SRA);
3180 // Simplify, based on bits shifted out of the LHS.
3181 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3182 return SDValue(N, 0);
3185 // If the sign bit is known to be zero, switch this to a SRL.
3186 if (DAG.SignBitIsZero(N0))
3187 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
3190 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3191 if (NewSRA.getNode())
3198 SDValue DAGCombiner::visitSRL(SDNode *N) {
3199 SDValue N0 = N->getOperand(0);
3200 SDValue N1 = N->getOperand(1);
3201 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3202 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3203 EVT VT = N0.getValueType();
3204 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3206 // fold (srl c1, c2) -> c1 >>u c2
3208 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3209 // fold (srl 0, x) -> 0
3210 if (N0C && N0C->isNullValue())
3212 // fold (srl x, c >= size(x)) -> undef
3213 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3214 return DAG.getUNDEF(VT);
3215 // fold (srl x, 0) -> x
3216 if (N1C && N1C->isNullValue())
3218 // if (srl x, c) is known to be zero, return 0
3219 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3220 APInt::getAllOnesValue(OpSizeInBits)))
3221 return DAG.getConstant(0, VT);
3223 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3224 if (N1C && N0.getOpcode() == ISD::SRL &&
3225 N0.getOperand(1).getOpcode() == ISD::Constant) {
3226 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3227 uint64_t c2 = N1C->getZExtValue();
3228 if (c1 + c2 >= OpSizeInBits)
3229 return DAG.getConstant(0, VT);
3230 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3231 DAG.getConstant(c1 + c2, N1.getValueType()));
3234 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3235 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3236 N0.getOperand(0).getOpcode() == ISD::SRL &&
3237 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3239 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3240 uint64_t c2 = N1C->getZExtValue();
3241 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3242 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3243 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3244 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3245 if (c1 + OpSizeInBits == InnerShiftSize) {
3246 if (c1 + c2 >= InnerShiftSize)
3247 return DAG.getConstant(0, VT);
3248 return DAG.getNode(ISD::TRUNCATE, N0->getDebugLoc(), VT,
3249 DAG.getNode(ISD::SRL, N0->getDebugLoc(), InnerShiftVT,
3250 N0.getOperand(0)->getOperand(0),
3251 DAG.getConstant(c1 + c2, ShiftCountVT)));
3255 // fold (srl (shl x, c), c) -> (and x, cst2)
3256 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3257 N0.getValueSizeInBits() <= 64) {
3258 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3259 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3260 DAG.getConstant(~0ULL >> ShAmt, VT));
3264 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
3265 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3266 // Shifting in all undef bits?
3267 EVT SmallVT = N0.getOperand(0).getValueType();
3268 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3269 return DAG.getUNDEF(VT);
3271 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3272 SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
3273 N0.getOperand(0), N1);
3274 AddToWorkList(SmallShift.getNode());
3275 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
3279 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
3280 // bit, which is unmodified by sra.
3281 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
3282 if (N0.getOpcode() == ISD::SRA)
3283 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
3286 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
3287 if (N1C && N0.getOpcode() == ISD::CTLZ &&
3288 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
3289 APInt KnownZero, KnownOne;
3290 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
3291 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
3293 // If any of the input bits are KnownOne, then the input couldn't be all
3294 // zeros, thus the result of the srl will always be zero.
3295 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
3297 // If all of the bits input the to ctlz node are known to be zero, then
3298 // the result of the ctlz is "32" and the result of the shift is one.
3299 APInt UnknownBits = ~KnownZero & Mask;
3300 if (UnknownBits == 0) return DAG.getConstant(1, VT);
3302 // Otherwise, check to see if there is exactly one bit input to the ctlz.
3303 if ((UnknownBits & (UnknownBits - 1)) == 0) {
3304 // Okay, we know that only that the single bit specified by UnknownBits
3305 // could be set on input to the CTLZ node. If this bit is set, the SRL
3306 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
3307 // to an SRL/XOR pair, which is likely to simplify more.
3308 unsigned ShAmt = UnknownBits.countTrailingZeros();
3309 SDValue Op = N0.getOperand(0);
3312 Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
3313 DAG.getConstant(ShAmt, getShiftAmountTy()));
3314 AddToWorkList(Op.getNode());
3317 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3318 Op, DAG.getConstant(1, VT));
3322 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
3323 if (N1.getOpcode() == ISD::TRUNCATE &&
3324 N1.getOperand(0).getOpcode() == ISD::AND &&
3325 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3326 SDValue N101 = N1.getOperand(0).getOperand(1);
3327 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3328 EVT TruncVT = N1.getValueType();
3329 SDValue N100 = N1.getOperand(0).getOperand(0);
3330 APInt TruncC = N101C->getAPIntValue();
3331 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3332 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
3333 DAG.getNode(ISD::AND, N->getDebugLoc(),
3335 DAG.getNode(ISD::TRUNCATE,
3338 DAG.getConstant(TruncC, TruncVT)));
3342 // fold operands of srl based on knowledge that the low bits are not
3344 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3345 return SDValue(N, 0);
3348 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
3349 if (NewSRL.getNode())
3353 // Attempt to convert a srl of a load into a narrower zero-extending load.
3354 SDValue NarrowLoad = ReduceLoadWidth(N);
3355 if (NarrowLoad.getNode())
3358 // Here is a common situation. We want to optimize:
3361 // %b = and i32 %a, 2
3362 // %c = srl i32 %b, 1
3363 // brcond i32 %c ...
3369 // %c = setcc eq %b, 0
3372 // However when after the source operand of SRL is optimized into AND, the SRL
3373 // itself may not be optimized further. Look for it and add the BRCOND into
3375 if (N->hasOneUse()) {
3376 SDNode *Use = *N->use_begin();
3377 if (Use->getOpcode() == ISD::BRCOND)
3379 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
3380 // Also look pass the truncate.
3381 Use = *Use->use_begin();
3382 if (Use->getOpcode() == ISD::BRCOND)
3390 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
3391 SDValue N0 = N->getOperand(0);
3392 EVT VT = N->getValueType(0);
3394 // fold (ctlz c1) -> c2
3395 if (isa<ConstantSDNode>(N0))
3396 return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
3400 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
3401 SDValue N0 = N->getOperand(0);
3402 EVT VT = N->getValueType(0);
3404 // fold (cttz c1) -> c2
3405 if (isa<ConstantSDNode>(N0))
3406 return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
3410 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
3411 SDValue N0 = N->getOperand(0);
3412 EVT VT = N->getValueType(0);
3414 // fold (ctpop c1) -> c2
3415 if (isa<ConstantSDNode>(N0))
3416 return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
3420 SDValue DAGCombiner::visitSELECT(SDNode *N) {
3421 SDValue N0 = N->getOperand(0);
3422 SDValue N1 = N->getOperand(1);
3423 SDValue N2 = N->getOperand(2);
3424 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3425 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3426 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
3427 EVT VT = N->getValueType(0);
3428 EVT VT0 = N0.getValueType();
3430 // fold (select C, X, X) -> X
3433 // fold (select true, X, Y) -> X
3434 if (N0C && !N0C->isNullValue())
3436 // fold (select false, X, Y) -> Y
3437 if (N0C && N0C->isNullValue())
3439 // fold (select C, 1, X) -> (or C, X)
3440 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
3441 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3442 // fold (select C, 0, 1) -> (xor C, 1)
3443 if (VT.isInteger() &&
3446 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent)) &&
3447 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
3450 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
3451 N0, DAG.getConstant(1, VT0));
3452 XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
3453 N0, DAG.getConstant(1, VT0));
3454 AddToWorkList(XORNode.getNode());
3456 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
3457 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
3459 // fold (select C, 0, X) -> (and (not C), X)
3460 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
3461 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
3462 AddToWorkList(NOTNode.getNode());
3463 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
3465 // fold (select C, X, 1) -> (or (not C), X)
3466 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
3467 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
3468 AddToWorkList(NOTNode.getNode());
3469 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
3471 // fold (select C, X, 0) -> (and C, X)
3472 if (VT == MVT::i1 && N2C && N2C->isNullValue())
3473 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
3474 // fold (select X, X, Y) -> (or X, Y)
3475 // fold (select X, 1, Y) -> (or X, Y)
3476 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
3477 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3478 // fold (select X, Y, X) -> (and X, Y)
3479 // fold (select X, Y, 0) -> (and X, Y)
3480 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
3481 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
3483 // If we can fold this based on the true/false value, do so.
3484 if (SimplifySelectOps(N, N1, N2))
3485 return SDValue(N, 0); // Don't revisit N.
3487 // fold selects based on a setcc into other things, such as min/max/abs
3488 if (N0.getOpcode() == ISD::SETCC) {
3490 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
3491 // having to say they don't support SELECT_CC on every type the DAG knows
3492 // about, since there is no way to mark an opcode illegal at all value types
3493 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
3494 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
3495 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
3496 N0.getOperand(0), N0.getOperand(1),
3497 N1, N2, N0.getOperand(2));
3498 return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
3504 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
3505 SDValue N0 = N->getOperand(0);
3506 SDValue N1 = N->getOperand(1);
3507 SDValue N2 = N->getOperand(2);
3508 SDValue N3 = N->getOperand(3);
3509 SDValue N4 = N->getOperand(4);
3510 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
3512 // fold select_cc lhs, rhs, x, x, cc -> x
3516 // Determine if the condition we're dealing with is constant
3517 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
3518 N0, N1, CC, N->getDebugLoc(), false);
3519 if (SCC.getNode()) AddToWorkList(SCC.getNode());
3521 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
3522 if (!SCCC->isNullValue())
3523 return N2; // cond always true -> true val
3525 return N3; // cond always false -> false val
3528 // Fold to a simpler select_cc
3529 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
3530 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
3531 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
3534 // If we can fold this based on the true/false value, do so.
3535 if (SimplifySelectOps(N, N2, N3))
3536 return SDValue(N, 0); // Don't revisit N.
3538 // fold select_cc into other things, such as min/max/abs
3539 return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
3542 SDValue DAGCombiner::visitSETCC(SDNode *N) {
3543 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
3544 cast<CondCodeSDNode>(N->getOperand(2))->get(),
3548 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
3549 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
3550 // transformation. Returns true if extension are possible and the above
3551 // mentioned transformation is profitable.
3552 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
3554 SmallVector<SDNode*, 4> &ExtendNodes,
3555 const TargetLowering &TLI) {
3556 bool HasCopyToRegUses = false;
3557 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
3558 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
3559 UE = N0.getNode()->use_end();
3564 if (UI.getUse().getResNo() != N0.getResNo())
3566 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
3567 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
3568 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
3569 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
3570 // Sign bits will be lost after a zext.
3573 for (unsigned i = 0; i != 2; ++i) {
3574 SDValue UseOp = User->getOperand(i);
3577 if (!isa<ConstantSDNode>(UseOp))
3582 ExtendNodes.push_back(User);
3585 // If truncates aren't free and there are users we can't
3586 // extend, it isn't worthwhile.
3589 // Remember if this value is live-out.
3590 if (User->getOpcode() == ISD::CopyToReg)
3591 HasCopyToRegUses = true;
3594 if (HasCopyToRegUses) {
3595 bool BothLiveOut = false;
3596 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3598 SDUse &Use = UI.getUse();
3599 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
3605 // Both unextended and extended values are live out. There had better be
3606 // a good reason for the transformation.
3607 return ExtendNodes.size();
3612 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
3613 SDValue N0 = N->getOperand(0);
3614 EVT VT = N->getValueType(0);
3616 // fold (sext c1) -> c1
3617 if (isa<ConstantSDNode>(N0))
3618 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
3620 // fold (sext (sext x)) -> (sext x)
3621 // fold (sext (aext x)) -> (sext x)
3622 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3623 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
3626 if (N0.getOpcode() == ISD::TRUNCATE) {
3627 // fold (sext (truncate (load x))) -> (sext (smaller load x))
3628 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
3629 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3630 if (NarrowLoad.getNode()) {
3631 SDNode* oye = N0.getNode()->getOperand(0).getNode();
3632 if (NarrowLoad.getNode() != N0.getNode()) {
3633 CombineTo(N0.getNode(), NarrowLoad);
3634 // CombineTo deleted the truncate, if needed, but not what's under it.
3637 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3640 // See if the value being truncated is already sign extended. If so, just
3641 // eliminate the trunc/sext pair.
3642 SDValue Op = N0.getOperand(0);
3643 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
3644 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
3645 unsigned DestBits = VT.getScalarType().getSizeInBits();
3646 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
3648 if (OpBits == DestBits) {
3649 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
3650 // bits, it is already ready.
3651 if (NumSignBits > DestBits-MidBits)
3653 } else if (OpBits < DestBits) {
3654 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
3655 // bits, just sext from i32.
3656 if (NumSignBits > OpBits-MidBits)
3657 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
3659 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
3660 // bits, just truncate to i32.
3661 if (NumSignBits > OpBits-MidBits)
3662 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3665 // fold (sext (truncate x)) -> (sextinreg x).
3666 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
3667 N0.getValueType())) {
3668 if (OpBits < DestBits)
3669 Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
3670 else if (OpBits > DestBits)
3671 Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
3672 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
3673 DAG.getValueType(N0.getValueType()));
3677 // fold (sext (load x)) -> (sext (truncate (sextload x)))
3678 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3679 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3680 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
3681 bool DoXform = true;
3682 SmallVector<SDNode*, 4> SetCCs;
3683 if (!N0.hasOneUse())
3684 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
3686 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3687 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N->getDebugLoc(),
3689 LN0->getBasePtr(), LN0->getPointerInfo(),
3691 LN0->isVolatile(), LN0->isNonTemporal(),
3692 LN0->getAlignment());
3693 CombineTo(N, ExtLoad);
3694 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3695 N0.getValueType(), ExtLoad);
3696 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3698 // Extend SetCC uses if necessary.
3699 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3700 SDNode *SetCC = SetCCs[i];
3701 SmallVector<SDValue, 4> Ops;
3703 for (unsigned j = 0; j != 2; ++j) {
3704 SDValue SOp = SetCC->getOperand(j);
3706 Ops.push_back(ExtLoad);
3708 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND,
3709 N->getDebugLoc(), VT, SOp));
3712 Ops.push_back(SetCC->getOperand(2));
3713 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3714 SetCC->getValueType(0),
3715 &Ops[0], Ops.size()));
3718 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3722 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
3723 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
3724 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3725 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3726 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3727 EVT MemVT = LN0->getMemoryVT();
3728 if ((!LegalOperations && !LN0->isVolatile()) ||
3729 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
3730 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N->getDebugLoc(),
3732 LN0->getBasePtr(), LN0->getPointerInfo(),
3734 LN0->isVolatile(), LN0->isNonTemporal(),
3735 LN0->getAlignment());
3736 CombineTo(N, ExtLoad);
3737 CombineTo(N0.getNode(),
3738 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3739 N0.getValueType(), ExtLoad),
3740 ExtLoad.getValue(1));
3741 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3745 if (N0.getOpcode() == ISD::SETCC) {
3746 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
3747 // Only do this before legalize for now.
3748 if (VT.isVector() && !LegalOperations) {
3749 EVT N0VT = N0.getOperand(0).getValueType();
3750 // We know that the # elements of the results is the same as the
3751 // # elements of the compare (and the # elements of the compare result
3752 // for that matter). Check to see that they are the same size. If so,
3753 // we know that the element size of the sext'd result matches the
3754 // element size of the compare operands.
3755 if (VT.getSizeInBits() == N0VT.getSizeInBits())
3756 return DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
3758 cast<CondCodeSDNode>(N0.getOperand(2))->get());
3759 // If the desired elements are smaller or larger than the source
3760 // elements we can use a matching integer vector type and then
3761 // truncate/sign extend
3763 EVT MatchingElementType =
3764 EVT::getIntegerVT(*DAG.getContext(),
3765 N0VT.getScalarType().getSizeInBits());
3766 EVT MatchingVectorType =
3767 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
3768 N0VT.getVectorNumElements());
3770 DAG.getVSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
3772 cast<CondCodeSDNode>(N0.getOperand(2))->get());
3773 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
3777 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
3778 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
3780 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
3782 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3783 NegOne, DAG.getConstant(0, VT),
3784 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3785 if (SCC.getNode()) return SCC;
3786 if (!LegalOperations ||
3787 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT)))
3788 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
3789 DAG.getSetCC(N->getDebugLoc(),
3790 TLI.getSetCCResultType(VT),
3791 N0.getOperand(0), N0.getOperand(1),
3792 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
3793 NegOne, DAG.getConstant(0, VT));
3796 // fold (sext x) -> (zext x) if the sign bit is known zero.
3797 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
3798 DAG.SignBitIsZero(N0))
3799 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3804 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
3805 SDValue N0 = N->getOperand(0);
3806 EVT VT = N->getValueType(0);
3808 // fold (zext c1) -> c1
3809 if (isa<ConstantSDNode>(N0))
3810 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3811 // fold (zext (zext x)) -> (zext x)
3812 // fold (zext (aext x)) -> (zext x)
3813 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3814 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
3817 // fold (zext (truncate (load x))) -> (zext (smaller load x))
3818 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
3819 if (N0.getOpcode() == ISD::TRUNCATE) {
3820 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3821 if (NarrowLoad.getNode()) {
3822 SDNode* oye = N0.getNode()->getOperand(0).getNode();
3823 if (NarrowLoad.getNode() != N0.getNode()) {
3824 CombineTo(N0.getNode(), NarrowLoad);
3825 // CombineTo deleted the truncate, if needed, but not what's under it.
3828 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
3832 // fold (zext (truncate x)) -> (and x, mask)
3833 if (N0.getOpcode() == ISD::TRUNCATE &&
3834 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
3836 // fold (zext (truncate (load x))) -> (zext (smaller load x))
3837 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
3838 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3839 if (NarrowLoad.getNode()) {
3840 SDNode* oye = N0.getNode()->getOperand(0).getNode();
3841 if (NarrowLoad.getNode() != N0.getNode()) {
3842 CombineTo(N0.getNode(), NarrowLoad);
3843 // CombineTo deleted the truncate, if needed, but not what's under it.
3846 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3849 SDValue Op = N0.getOperand(0);
3850 if (Op.getValueType().bitsLT(VT)) {
3851 Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
3852 } else if (Op.getValueType().bitsGT(VT)) {
3853 Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3855 return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
3856 N0.getValueType().getScalarType());
3859 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
3860 // if either of the casts is not free.
3861 if (N0.getOpcode() == ISD::AND &&
3862 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3863 N0.getOperand(1).getOpcode() == ISD::Constant &&
3864 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
3865 N0.getValueType()) ||
3866 !TLI.isZExtFree(N0.getValueType(), VT))) {
3867 SDValue X = N0.getOperand(0).getOperand(0);
3868 if (X.getValueType().bitsLT(VT)) {
3869 X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
3870 } else if (X.getValueType().bitsGT(VT)) {
3871 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
3873 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3874 Mask = Mask.zext(VT.getSizeInBits());
3875 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3876 X, DAG.getConstant(Mask, VT));
3879 // fold (zext (load x)) -> (zext (truncate (zextload x)))
3880 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3881 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3882 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
3883 bool DoXform = true;
3884 SmallVector<SDNode*, 4> SetCCs;
3885 if (!N0.hasOneUse())
3886 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
3888 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3889 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N->getDebugLoc(),
3891 LN0->getBasePtr(), LN0->getPointerInfo(),
3893 LN0->isVolatile(), LN0->isNonTemporal(),
3894 LN0->getAlignment());
3895 CombineTo(N, ExtLoad);
3896 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3897 N0.getValueType(), ExtLoad);
3898 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3900 // Extend SetCC uses if necessary.
3901 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3902 SDNode *SetCC = SetCCs[i];
3903 SmallVector<SDValue, 4> Ops;
3905 for (unsigned j = 0; j != 2; ++j) {
3906 SDValue SOp = SetCC->getOperand(j);
3908 Ops.push_back(ExtLoad);
3910 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND,
3911 N->getDebugLoc(), VT, SOp));
3914 Ops.push_back(SetCC->getOperand(2));
3915 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3916 SetCC->getValueType(0),
3917 &Ops[0], Ops.size()));
3920 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3924 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
3925 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
3926 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3927 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3928 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3929 EVT MemVT = LN0->getMemoryVT();
3930 if ((!LegalOperations && !LN0->isVolatile()) ||
3931 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
3932 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N->getDebugLoc(),
3934 LN0->getBasePtr(), LN0->getPointerInfo(),
3936 LN0->isVolatile(), LN0->isNonTemporal(),
3937 LN0->getAlignment());
3938 CombineTo(N, ExtLoad);
3939 CombineTo(N0.getNode(),
3940 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
3942 ExtLoad.getValue(1));
3943 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3947 if (N0.getOpcode() == ISD::SETCC) {
3948 if (!LegalOperations && VT.isVector()) {
3949 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
3950 // Only do this before legalize for now.
3951 EVT N0VT = N0.getOperand(0).getValueType();
3952 EVT EltVT = VT.getVectorElementType();
3953 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
3954 DAG.getConstant(1, EltVT));
3955 if (VT.getSizeInBits() == N0VT.getSizeInBits()) {
3956 // We know that the # elements of the results is the same as the
3957 // # elements of the compare (and the # elements of the compare result
3958 // for that matter). Check to see that they are the same size. If so,
3959 // we know that the element size of the sext'd result matches the
3960 // element size of the compare operands.
3961 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3962 DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
3964 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
3965 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
3966 &OneOps[0], OneOps.size()));
3968 // If the desired elements are smaller or larger than the source
3969 // elements we can use a matching integer vector type and then
3970 // truncate/sign extend
3971 EVT MatchingElementType =
3972 EVT::getIntegerVT(*DAG.getContext(),
3973 N0VT.getScalarType().getSizeInBits());
3974 EVT MatchingVectorType =
3975 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
3976 N0VT.getVectorNumElements());
3978 DAG.getVSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
3980 cast<CondCodeSDNode>(N0.getOperand(2))->get());
3981 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3982 DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT),
3983 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
3984 &OneOps[0], OneOps.size()));
3988 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3990 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3991 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3992 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3993 if (SCC.getNode()) return SCC;
3996 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
3997 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
3998 isa<ConstantSDNode>(N0.getOperand(1)) &&
3999 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4001 if (N0.getOpcode() == ISD::SHL) {
4002 // If the original shl may be shifting out bits, do not perform this
4004 unsigned ShAmt = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4005 unsigned KnownZeroBits = N0.getOperand(0).getValueType().getSizeInBits() -
4006 N0.getOperand(0).getOperand(0).getValueType().getSizeInBits();
4007 if (ShAmt > KnownZeroBits)
4010 DebugLoc dl = N->getDebugLoc();
4011 return DAG.getNode(N0.getOpcode(), dl, VT,
4012 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0.getOperand(0)),
4013 DAG.getNode(ISD::ZERO_EXTEND, dl,
4014 N0.getOperand(1).getValueType(),
4021 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4022 SDValue N0 = N->getOperand(0);
4023 EVT VT = N->getValueType(0);
4025 // fold (aext c1) -> c1
4026 if (isa<ConstantSDNode>(N0))
4027 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
4028 // fold (aext (aext x)) -> (aext x)
4029 // fold (aext (zext x)) -> (zext x)
4030 // fold (aext (sext x)) -> (sext x)
4031 if (N0.getOpcode() == ISD::ANY_EXTEND ||
4032 N0.getOpcode() == ISD::ZERO_EXTEND ||
4033 N0.getOpcode() == ISD::SIGN_EXTEND)
4034 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
4036 // fold (aext (truncate (load x))) -> (aext (smaller load x))
4037 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
4038 if (N0.getOpcode() == ISD::TRUNCATE) {
4039 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4040 if (NarrowLoad.getNode()) {
4041 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4042 if (NarrowLoad.getNode() != N0.getNode()) {
4043 CombineTo(N0.getNode(), NarrowLoad);
4044 // CombineTo deleted the truncate, if needed, but not what's under it.
4047 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
4051 // fold (aext (truncate x))
4052 if (N0.getOpcode() == ISD::TRUNCATE) {
4053 SDValue TruncOp = N0.getOperand(0);
4054 if (TruncOp.getValueType() == VT)
4055 return TruncOp; // x iff x size == zext size.
4056 if (TruncOp.getValueType().bitsGT(VT))
4057 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
4058 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
4061 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
4062 // if the trunc is not free.
4063 if (N0.getOpcode() == ISD::AND &&
4064 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4065 N0.getOperand(1).getOpcode() == ISD::Constant &&
4066 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4067 N0.getValueType())) {
4068 SDValue X = N0.getOperand(0).getOperand(0);
4069 if (X.getValueType().bitsLT(VT)) {
4070 X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
4071 } else if (X.getValueType().bitsGT(VT)) {
4072 X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
4074 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4075 Mask = Mask.zext(VT.getSizeInBits());
4076 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4077 X, DAG.getConstant(Mask, VT));
4080 // fold (aext (load x)) -> (aext (truncate (extload x)))
4081 if (ISD::isNON_EXTLoad(N0.getNode()) &&
4082 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4083 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4084 bool DoXform = true;
4085 SmallVector<SDNode*, 4> SetCCs;
4086 if (!N0.hasOneUse())
4087 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
4089 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4090 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, N->getDebugLoc(),
4092 LN0->getBasePtr(), LN0->getPointerInfo(),
4094 LN0->isVolatile(), LN0->isNonTemporal(),
4095 LN0->getAlignment());
4096 CombineTo(N, ExtLoad);
4097 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4098 N0.getValueType(), ExtLoad);
4099 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4101 // Extend SetCC uses if necessary.
4102 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4103 SDNode *SetCC = SetCCs[i];
4104 SmallVector<SDValue, 4> Ops;
4106 for (unsigned j = 0; j != 2; ++j) {
4107 SDValue SOp = SetCC->getOperand(j);
4109 Ops.push_back(ExtLoad);
4111 Ops.push_back(DAG.getNode(ISD::ANY_EXTEND,
4112 N->getDebugLoc(), VT, SOp));
4115 Ops.push_back(SetCC->getOperand(2));
4116 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
4117 SetCC->getValueType(0),
4118 &Ops[0], Ops.size()));
4121 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4125 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
4126 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
4127 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
4128 if (N0.getOpcode() == ISD::LOAD &&
4129 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4131 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4132 EVT MemVT = LN0->getMemoryVT();
4133 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
4135 LN0->getChain(), LN0->getBasePtr(),
4136 LN0->getPointerInfo(), MemVT,
4137 LN0->isVolatile(), LN0->isNonTemporal(),
4138 LN0->getAlignment());
4139 CombineTo(N, ExtLoad);
4140 CombineTo(N0.getNode(),
4141 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4142 N0.getValueType(), ExtLoad),
4143 ExtLoad.getValue(1));
4144 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4147 if (N0.getOpcode() == ISD::SETCC) {
4148 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
4149 // Only do this before legalize for now.
4150 if (VT.isVector() && !LegalOperations) {
4151 EVT N0VT = N0.getOperand(0).getValueType();
4152 // We know that the # elements of the results is the same as the
4153 // # elements of the compare (and the # elements of the compare result
4154 // for that matter). Check to see that they are the same size. If so,
4155 // we know that the element size of the sext'd result matches the
4156 // element size of the compare operands.
4157 if (VT.getSizeInBits() == N0VT.getSizeInBits())
4158 return DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4160 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4161 // If the desired elements are smaller or larger than the source
4162 // elements we can use a matching integer vector type and then
4163 // truncate/sign extend
4165 EVT MatchingElementType =
4166 EVT::getIntegerVT(*DAG.getContext(),
4167 N0VT.getScalarType().getSizeInBits());
4168 EVT MatchingVectorType =
4169 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4170 N0VT.getVectorNumElements());
4172 DAG.getVSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4174 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4175 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4179 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4181 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4182 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4183 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4191 /// GetDemandedBits - See if the specified operand can be simplified with the
4192 /// knowledge that only the bits specified by Mask are used. If so, return the
4193 /// simpler operand, otherwise return a null SDValue.
4194 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
4195 switch (V.getOpcode()) {
4199 // If the LHS or RHS don't contribute bits to the or, drop them.
4200 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
4201 return V.getOperand(1);
4202 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
4203 return V.getOperand(0);
4206 // Only look at single-use SRLs.
4207 if (!V.getNode()->hasOneUse())
4209 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
4210 // See if we can recursively simplify the LHS.
4211 unsigned Amt = RHSC->getZExtValue();
4213 // Watch out for shift count overflow though.
4214 if (Amt >= Mask.getBitWidth()) break;
4215 APInt NewMask = Mask << Amt;
4216 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
4217 if (SimplifyLHS.getNode())
4218 return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
4219 SimplifyLHS, V.getOperand(1));
4225 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
4226 /// bits and then truncated to a narrower type and where N is a multiple
4227 /// of number of bits of the narrower type, transform it to a narrower load
4228 /// from address + N / num of bits of new type. If the result is to be
4229 /// extended, also fold the extension to form a extending load.
4230 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
4231 unsigned Opc = N->getOpcode();
4233 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
4234 SDValue N0 = N->getOperand(0);
4235 EVT VT = N->getValueType(0);
4238 // This transformation isn't valid for vector loads.
4242 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
4244 if (Opc == ISD::SIGN_EXTEND_INREG) {
4245 ExtType = ISD::SEXTLOAD;
4246 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4247 if (LegalOperations && !TLI.isLoadExtLegal(ISD::SEXTLOAD, ExtVT))
4249 } else if (Opc == ISD::SRL) {
4250 // Another special-case: SRL is basically zero-extending a narrower value.
4251 ExtType = ISD::ZEXTLOAD;
4253 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4254 if (!N01) return SDValue();
4255 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
4256 VT.getSizeInBits() - N01->getZExtValue());
4259 unsigned EVTBits = ExtVT.getSizeInBits();
4261 // Do not generate loads of non-round integer types since these can
4262 // be expensive (and would be wrong if the type is not byte sized).
4263 if (!ExtVT.isRound())
4267 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4268 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4269 ShAmt = N01->getZExtValue();
4270 // Is the shift amount a multiple of size of VT?
4271 if ((ShAmt & (EVTBits-1)) == 0) {
4272 N0 = N0.getOperand(0);
4273 // Is the load width a multiple of size of VT?
4274 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
4278 // At this point, we must have a load or else we can't do the transform.
4279 if (!isa<LoadSDNode>(N0)) return SDValue();
4281 // If the shift amount is larger than the input type then we're not
4282 // accessing any of the loaded bytes. If the load was a zextload/extload
4283 // then the result of the shift+trunc is zero/undef (handled elsewhere).
4284 // If the load was a sextload then the result is a splat of the sign bit
4285 // of the extended byte. This is not worth optimizing for.
4286 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
4291 // If the load is shifted left (and the result isn't shifted back right),
4292 // we can fold the truncate through the shift.
4293 unsigned ShLeftAmt = 0;
4294 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
4295 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
4296 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4297 ShLeftAmt = N01->getZExtValue();
4298 N0 = N0.getOperand(0);
4302 // If we haven't found a load, we can't narrow it. Don't transform one with
4303 // multiple uses, this would require adding a new load.
4304 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse() ||
4305 // Don't change the width of a volatile load.
4306 cast<LoadSDNode>(N0)->isVolatile())
4309 // Verify that we are actually reducing a load width here.
4310 if (cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() < EVTBits)
4313 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4314 EVT PtrType = N0.getOperand(1).getValueType();
4316 // For big endian targets, we need to adjust the offset to the pointer to
4317 // load the correct bytes.
4318 if (TLI.isBigEndian()) {
4319 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
4320 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
4321 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
4324 uint64_t PtrOff = ShAmt / 8;
4325 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
4326 SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
4327 PtrType, LN0->getBasePtr(),
4328 DAG.getConstant(PtrOff, PtrType));
4329 AddToWorkList(NewPtr.getNode());
4332 if (ExtType == ISD::NON_EXTLOAD)
4333 Load = DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
4334 LN0->getPointerInfo().getWithOffset(PtrOff),
4335 LN0->isVolatile(), LN0->isNonTemporal(), NewAlign);
4337 Load = DAG.getExtLoad(ExtType, VT, N0.getDebugLoc(), LN0->getChain(),NewPtr,
4338 LN0->getPointerInfo().getWithOffset(PtrOff),
4339 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
4342 // Replace the old load's chain with the new load's chain.
4343 WorkListRemover DeadNodes(*this);
4344 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
4347 // Shift the result left, if we've swallowed a left shift.
4348 SDValue Result = Load;
4349 if (ShLeftAmt != 0) {
4350 EVT ShImmTy = getShiftAmountTy();
4351 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
4353 Result = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT,
4354 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
4357 // Return the new loaded value.
4361 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
4362 SDValue N0 = N->getOperand(0);
4363 SDValue N1 = N->getOperand(1);
4364 EVT VT = N->getValueType(0);
4365 EVT EVT = cast<VTSDNode>(N1)->getVT();
4366 unsigned VTBits = VT.getScalarType().getSizeInBits();
4367 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
4369 // fold (sext_in_reg c1) -> c1
4370 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
4371 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
4373 // If the input is already sign extended, just drop the extension.
4374 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
4377 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
4378 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4379 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
4380 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
4381 N0.getOperand(0), N1);
4384 // fold (sext_in_reg (sext x)) -> (sext x)
4385 // fold (sext_in_reg (aext x)) -> (sext x)
4386 // if x is small enough.
4387 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
4388 SDValue N00 = N0.getOperand(0);
4389 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
4390 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
4391 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
4394 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
4395 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
4396 return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
4398 // fold operands of sext_in_reg based on knowledge that the top bits are not
4400 if (SimplifyDemandedBits(SDValue(N, 0)))
4401 return SDValue(N, 0);
4403 // fold (sext_in_reg (load x)) -> (smaller sextload x)
4404 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
4405 SDValue NarrowLoad = ReduceLoadWidth(N);
4406 if (NarrowLoad.getNode())
4409 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
4410 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
4411 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
4412 if (N0.getOpcode() == ISD::SRL) {
4413 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
4414 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
4415 // We can turn this into an SRA iff the input to the SRL is already sign
4417 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
4418 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
4419 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
4420 N0.getOperand(0), N0.getOperand(1));
4424 // fold (sext_inreg (extload x)) -> (sextload x)
4425 if (ISD::isEXTLoad(N0.getNode()) &&
4426 ISD::isUNINDEXEDLoad(N0.getNode()) &&
4427 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
4428 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4429 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
4430 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4431 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N->getDebugLoc(),
4433 LN0->getBasePtr(), LN0->getPointerInfo(),
4435 LN0->isVolatile(), LN0->isNonTemporal(),
4436 LN0->getAlignment());
4437 CombineTo(N, ExtLoad);
4438 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4439 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4441 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
4442 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4444 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
4445 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4446 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
4447 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4448 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N->getDebugLoc(),
4450 LN0->getBasePtr(), LN0->getPointerInfo(),
4452 LN0->isVolatile(), LN0->isNonTemporal(),
4453 LN0->getAlignment());
4454 CombineTo(N, ExtLoad);
4455 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4456 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4461 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
4462 SDValue N0 = N->getOperand(0);
4463 EVT VT = N->getValueType(0);
4466 if (N0.getValueType() == N->getValueType(0))
4468 // fold (truncate c1) -> c1
4469 if (isa<ConstantSDNode>(N0))
4470 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
4471 // fold (truncate (truncate x)) -> (truncate x)
4472 if (N0.getOpcode() == ISD::TRUNCATE)
4473 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4474 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
4475 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
4476 N0.getOpcode() == ISD::SIGN_EXTEND ||
4477 N0.getOpcode() == ISD::ANY_EXTEND) {
4478 if (N0.getOperand(0).getValueType().bitsLT(VT))
4479 // if the source is smaller than the dest, we still need an extend
4480 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4482 else if (N0.getOperand(0).getValueType().bitsGT(VT))
4483 // if the source is larger than the dest, than we just need the truncate
4484 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4486 // if the source and dest are the same type, we can drop both the extend
4487 // and the truncate.
4488 return N0.getOperand(0);
4491 // See if we can simplify the input to this truncate through knowledge that
4492 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
4495 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
4496 VT.getSizeInBits()));
4497 if (Shorter.getNode())
4498 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
4500 // fold (truncate (load x)) -> (smaller load x)
4501 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
4502 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
4503 SDValue Reduced = ReduceLoadWidth(N);
4504 if (Reduced.getNode())
4508 // Simplify the operands using demanded-bits information.
4509 if (!VT.isVector() &&
4510 SimplifyDemandedBits(SDValue(N, 0)))
4511 return SDValue(N, 0);
4516 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
4517 SDValue Elt = N->getOperand(i);
4518 if (Elt.getOpcode() != ISD::MERGE_VALUES)
4519 return Elt.getNode();
4520 return Elt.getOperand(Elt.getResNo()).getNode();
4523 /// CombineConsecutiveLoads - build_pair (load, load) -> load
4524 /// if load locations are consecutive.
4525 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
4526 assert(N->getOpcode() == ISD::BUILD_PAIR);
4528 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
4529 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
4530 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
4531 LD1->getPointerInfo().getAddrSpace() !=
4532 LD2->getPointerInfo().getAddrSpace())
4534 EVT LD1VT = LD1->getValueType(0);
4536 if (ISD::isNON_EXTLoad(LD2) &&
4538 // If both are volatile this would reduce the number of volatile loads.
4539 // If one is volatile it might be ok, but play conservative and bail out.
4540 !LD1->isVolatile() &&
4541 !LD2->isVolatile() &&
4542 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
4543 unsigned Align = LD1->getAlignment();
4544 unsigned NewAlign = TLI.getTargetData()->
4545 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
4547 if (NewAlign <= Align &&
4548 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
4549 return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
4550 LD1->getBasePtr(), LD1->getPointerInfo(),
4551 false, false, Align);
4557 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
4558 SDValue N0 = N->getOperand(0);
4559 EVT VT = N->getValueType(0);
4561 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
4562 // Only do this before legalize, since afterward the target may be depending
4563 // on the bitconvert.
4564 // First check to see if this is all constant.
4566 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
4568 bool isSimple = true;
4569 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
4570 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
4571 N0.getOperand(i).getOpcode() != ISD::Constant &&
4572 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
4577 EVT DestEltVT = N->getValueType(0).getVectorElementType();
4578 assert(!DestEltVT.isVector() &&
4579 "Element type of vector ValueType must not be vector!");
4581 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
4584 // If the input is a constant, let getNode fold it.
4585 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
4586 SDValue Res = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, N0);
4587 if (Res.getNode() != N) {
4588 if (!LegalOperations ||
4589 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
4592 // Folding it resulted in an illegal node, and it's too late to
4593 // do that. Clean up the old node and forego the transformation.
4594 // Ideally this won't happen very often, because instcombine
4595 // and the earlier dagcombine runs (where illegal nodes are
4596 // permitted) should have folded most of them already.
4597 DAG.DeleteNode(Res.getNode());
4601 // (conv (conv x, t1), t2) -> (conv x, t2)
4602 if (N0.getOpcode() == ISD::BITCAST)
4603 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT,
4606 // fold (conv (load x)) -> (load (conv*)x)
4607 // If the resultant load doesn't need a higher alignment than the original!
4608 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
4609 // Do not change the width of a volatile load.
4610 !cast<LoadSDNode>(N0)->isVolatile() &&
4611 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
4612 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4613 unsigned Align = TLI.getTargetData()->
4614 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
4615 unsigned OrigAlign = LN0->getAlignment();
4617 if (Align <= OrigAlign) {
4618 SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
4619 LN0->getBasePtr(), LN0->getPointerInfo(),
4620 LN0->isVolatile(), LN0->isNonTemporal(),
4623 CombineTo(N0.getNode(),
4624 DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
4625 N0.getValueType(), Load),
4631 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
4632 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
4633 // This often reduces constant pool loads.
4634 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
4635 N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
4636 SDValue NewConv = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), VT,
4638 AddToWorkList(NewConv.getNode());
4640 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
4641 if (N0.getOpcode() == ISD::FNEG)
4642 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
4643 NewConv, DAG.getConstant(SignBit, VT));
4644 assert(N0.getOpcode() == ISD::FABS);
4645 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4646 NewConv, DAG.getConstant(~SignBit, VT));
4649 // fold (bitconvert (fcopysign cst, x)) ->
4650 // (or (and (bitconvert x), sign), (and cst, (not sign)))
4651 // Note that we don't handle (copysign x, cst) because this can always be
4652 // folded to an fneg or fabs.
4653 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
4654 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
4655 VT.isInteger() && !VT.isVector()) {
4656 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
4657 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
4658 if (isTypeLegal(IntXVT)) {
4659 SDValue X = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
4660 IntXVT, N0.getOperand(1));
4661 AddToWorkList(X.getNode());
4663 // If X has a different width than the result/lhs, sext it or truncate it.
4664 unsigned VTWidth = VT.getSizeInBits();
4665 if (OrigXWidth < VTWidth) {
4666 X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
4667 AddToWorkList(X.getNode());
4668 } else if (OrigXWidth > VTWidth) {
4669 // To get the sign bit in the right place, we have to shift it right
4670 // before truncating.
4671 X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
4672 X.getValueType(), X,
4673 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
4674 AddToWorkList(X.getNode());
4675 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
4676 AddToWorkList(X.getNode());
4679 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
4680 X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
4681 X, DAG.getConstant(SignBit, VT));
4682 AddToWorkList(X.getNode());
4684 SDValue Cst = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
4685 VT, N0.getOperand(0));
4686 Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
4687 Cst, DAG.getConstant(~SignBit, VT));
4688 AddToWorkList(Cst.getNode());
4690 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
4694 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
4695 if (N0.getOpcode() == ISD::BUILD_PAIR) {
4696 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
4697 if (CombineLD.getNode())
4704 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
4705 EVT VT = N->getValueType(0);
4706 return CombineConsecutiveLoads(N, VT);
4709 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
4710 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
4711 /// destination element value type.
4712 SDValue DAGCombiner::
4713 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
4714 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
4716 // If this is already the right type, we're done.
4717 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
4719 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
4720 unsigned DstBitSize = DstEltVT.getSizeInBits();
4722 // If this is a conversion of N elements of one type to N elements of another
4723 // type, convert each element. This handles FP<->INT cases.
4724 if (SrcBitSize == DstBitSize) {
4725 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4726 BV->getValueType(0).getVectorNumElements());
4728 // Due to the FP element handling below calling this routine recursively,
4729 // we can end up with a scalar-to-vector node here.
4730 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
4731 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
4732 DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
4733 DstEltVT, BV->getOperand(0)));
4735 SmallVector<SDValue, 8> Ops;
4736 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4737 SDValue Op = BV->getOperand(i);
4738 // If the vector element type is not legal, the BUILD_VECTOR operands
4739 // are promoted and implicitly truncated. Make that explicit here.
4740 if (Op.getValueType() != SrcEltVT)
4741 Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
4742 Ops.push_back(DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
4744 AddToWorkList(Ops.back().getNode());
4746 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4747 &Ops[0], Ops.size());
4750 // Otherwise, we're growing or shrinking the elements. To avoid having to
4751 // handle annoying details of growing/shrinking FP values, we convert them to
4753 if (SrcEltVT.isFloatingPoint()) {
4754 // Convert the input float vector to a int vector where the elements are the
4756 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
4757 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
4758 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
4762 // Now we know the input is an integer vector. If the output is a FP type,
4763 // convert to integer first, then to FP of the right size.
4764 if (DstEltVT.isFloatingPoint()) {
4765 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
4766 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
4767 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
4769 // Next, convert to FP elements of the same size.
4770 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
4773 // Okay, we know the src/dst types are both integers of differing types.
4774 // Handling growing first.
4775 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
4776 if (SrcBitSize < DstBitSize) {
4777 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
4779 SmallVector<SDValue, 8> Ops;
4780 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
4781 i += NumInputsPerOutput) {
4782 bool isLE = TLI.isLittleEndian();
4783 APInt NewBits = APInt(DstBitSize, 0);
4784 bool EltIsUndef = true;
4785 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
4786 // Shift the previously computed bits over.
4787 NewBits <<= SrcBitSize;
4788 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
4789 if (Op.getOpcode() == ISD::UNDEF) continue;
4792 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
4793 zextOrTrunc(SrcBitSize).zext(DstBitSize);
4797 Ops.push_back(DAG.getUNDEF(DstEltVT));
4799 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
4802 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
4803 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4804 &Ops[0], Ops.size());
4807 // Finally, this must be the case where we are shrinking elements: each input
4808 // turns into multiple outputs.
4809 bool isS2V = ISD::isScalarToVector(BV);
4810 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
4811 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4812 NumOutputsPerInput*BV->getNumOperands());
4813 SmallVector<SDValue, 8> Ops;
4815 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4816 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
4817 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
4818 Ops.push_back(DAG.getUNDEF(DstEltVT));
4822 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
4823 getAPIntValue().zextOrTrunc(SrcBitSize);
4825 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
4826 APInt ThisVal = OpVal.trunc(DstBitSize);
4827 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
4828 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
4829 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
4830 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
4832 OpVal = OpVal.lshr(DstBitSize);
4835 // For big endian targets, swap the order of the pieces of each element.
4836 if (TLI.isBigEndian())
4837 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
4840 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4841 &Ops[0], Ops.size());
4844 SDValue DAGCombiner::visitFADD(SDNode *N) {
4845 SDValue N0 = N->getOperand(0);
4846 SDValue N1 = N->getOperand(1);
4847 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4848 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4849 EVT VT = N->getValueType(0);
4852 if (VT.isVector()) {
4853 SDValue FoldedVOp = SimplifyVBinOp(N);
4854 if (FoldedVOp.getNode()) return FoldedVOp;
4857 // fold (fadd c1, c2) -> (fadd c1, c2)
4858 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4859 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
4860 // canonicalize constant to RHS
4861 if (N0CFP && !N1CFP)
4862 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
4863 // fold (fadd A, 0) -> A
4864 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4866 // fold (fadd A, (fneg B)) -> (fsub A, B)
4867 if (isNegatibleForFree(N1, LegalOperations) == 2)
4868 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
4869 GetNegatedExpression(N1, DAG, LegalOperations));
4870 // fold (fadd (fneg A), B) -> (fsub B, A)
4871 if (isNegatibleForFree(N0, LegalOperations) == 2)
4872 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
4873 GetNegatedExpression(N0, DAG, LegalOperations));
4875 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
4876 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
4877 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4878 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
4879 DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
4880 N0.getOperand(1), N1));
4885 SDValue DAGCombiner::visitFSUB(SDNode *N) {
4886 SDValue N0 = N->getOperand(0);
4887 SDValue N1 = N->getOperand(1);
4888 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4889 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4890 EVT VT = N->getValueType(0);
4893 if (VT.isVector()) {
4894 SDValue FoldedVOp = SimplifyVBinOp(N);
4895 if (FoldedVOp.getNode()) return FoldedVOp;
4898 // fold (fsub c1, c2) -> c1-c2
4899 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4900 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
4901 // fold (fsub A, 0) -> A
4902 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4904 // fold (fsub 0, B) -> -B
4905 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
4906 if (isNegatibleForFree(N1, LegalOperations))
4907 return GetNegatedExpression(N1, DAG, LegalOperations);
4908 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4909 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1);
4911 // fold (fsub A, (fneg B)) -> (fadd A, B)
4912 if (isNegatibleForFree(N1, LegalOperations))
4913 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0,
4914 GetNegatedExpression(N1, DAG, LegalOperations));
4919 SDValue DAGCombiner::visitFMUL(SDNode *N) {
4920 SDValue N0 = N->getOperand(0);
4921 SDValue N1 = N->getOperand(1);
4922 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4923 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4924 EVT VT = N->getValueType(0);
4927 if (VT.isVector()) {
4928 SDValue FoldedVOp = SimplifyVBinOp(N);
4929 if (FoldedVOp.getNode()) return FoldedVOp;
4932 // fold (fmul c1, c2) -> c1*c2
4933 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4934 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
4935 // canonicalize constant to RHS
4936 if (N0CFP && !N1CFP)
4937 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
4938 // fold (fmul A, 0) -> 0
4939 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4941 // fold (fmul A, 0) -> 0, vector edition.
4942 if (UnsafeFPMath && ISD::isBuildVectorAllZeros(N1.getNode()))
4944 // fold (fmul X, 2.0) -> (fadd X, X)
4945 if (N1CFP && N1CFP->isExactlyValue(+2.0))
4946 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
4947 // fold (fmul X, -1.0) -> (fneg X)
4948 if (N1CFP && N1CFP->isExactlyValue(-1.0))
4949 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4950 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
4952 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
4953 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4954 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4955 // Both can be negated for free, check to see if at least one is cheaper
4957 if (LHSNeg == 2 || RHSNeg == 2)
4958 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4959 GetNegatedExpression(N0, DAG, LegalOperations),
4960 GetNegatedExpression(N1, DAG, LegalOperations));
4964 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
4965 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
4966 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4967 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
4968 DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4969 N0.getOperand(1), N1));
4974 SDValue DAGCombiner::visitFDIV(SDNode *N) {
4975 SDValue N0 = N->getOperand(0);
4976 SDValue N1 = N->getOperand(1);
4977 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4978 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4979 EVT VT = N->getValueType(0);
4982 if (VT.isVector()) {
4983 SDValue FoldedVOp = SimplifyVBinOp(N);
4984 if (FoldedVOp.getNode()) return FoldedVOp;
4987 // fold (fdiv c1, c2) -> c1/c2
4988 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4989 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
4992 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
4993 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4994 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4995 // Both can be negated for free, check to see if at least one is cheaper
4997 if (LHSNeg == 2 || RHSNeg == 2)
4998 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
4999 GetNegatedExpression(N0, DAG, LegalOperations),
5000 GetNegatedExpression(N1, DAG, LegalOperations));
5007 SDValue DAGCombiner::visitFREM(SDNode *N) {
5008 SDValue N0 = N->getOperand(0);
5009 SDValue N1 = N->getOperand(1);
5010 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5011 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5012 EVT VT = N->getValueType(0);
5014 // fold (frem c1, c2) -> fmod(c1,c2)
5015 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5016 return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
5021 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
5022 SDValue N0 = N->getOperand(0);
5023 SDValue N1 = N->getOperand(1);
5024 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5025 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5026 EVT VT = N->getValueType(0);
5028 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
5029 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
5032 const APFloat& V = N1CFP->getValueAPF();
5033 // copysign(x, c1) -> fabs(x) iff ispos(c1)
5034 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
5035 if (!V.isNegative()) {
5036 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
5037 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5039 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5040 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
5041 DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
5045 // copysign(fabs(x), y) -> copysign(x, y)
5046 // copysign(fneg(x), y) -> copysign(x, y)
5047 // copysign(copysign(x,z), y) -> copysign(x, y)
5048 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
5049 N0.getOpcode() == ISD::FCOPYSIGN)
5050 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5051 N0.getOperand(0), N1);
5053 // copysign(x, abs(y)) -> abs(x)
5054 if (N1.getOpcode() == ISD::FABS)
5055 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5057 // copysign(x, copysign(y,z)) -> copysign(x, z)
5058 if (N1.getOpcode() == ISD::FCOPYSIGN)
5059 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5060 N0, N1.getOperand(1));
5062 // copysign(x, fp_extend(y)) -> copysign(x, y)
5063 // copysign(x, fp_round(y)) -> copysign(x, y)
5064 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
5065 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5066 N0, N1.getOperand(0));
5071 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
5072 SDValue N0 = N->getOperand(0);
5073 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
5074 EVT VT = N->getValueType(0);
5075 EVT OpVT = N0.getValueType();
5077 // fold (sint_to_fp c1) -> c1fp
5078 if (N0C && OpVT != MVT::ppcf128)
5079 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
5081 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
5082 // but UINT_TO_FP is legal on this target, try to convert.
5083 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
5084 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
5085 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
5086 if (DAG.SignBitIsZero(N0))
5087 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
5093 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
5094 SDValue N0 = N->getOperand(0);
5095 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
5096 EVT VT = N->getValueType(0);
5097 EVT OpVT = N0.getValueType();
5099 // fold (uint_to_fp c1) -> c1fp
5100 if (N0C && OpVT != MVT::ppcf128)
5101 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
5103 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
5104 // but SINT_TO_FP is legal on this target, try to convert.
5105 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
5106 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
5107 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
5108 if (DAG.SignBitIsZero(N0))
5109 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
5115 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
5116 SDValue N0 = N->getOperand(0);
5117 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5118 EVT VT = N->getValueType(0);
5120 // fold (fp_to_sint c1fp) -> c1
5122 return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
5127 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
5128 SDValue N0 = N->getOperand(0);
5129 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5130 EVT VT = N->getValueType(0);
5132 // fold (fp_to_uint c1fp) -> c1
5133 if (N0CFP && VT != MVT::ppcf128)
5134 return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
5139 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
5140 SDValue N0 = N->getOperand(0);
5141 SDValue N1 = N->getOperand(1);
5142 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5143 EVT VT = N->getValueType(0);
5145 // fold (fp_round c1fp) -> c1fp
5146 if (N0CFP && N0.getValueType() != MVT::ppcf128)
5147 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
5149 // fold (fp_round (fp_extend x)) -> x
5150 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
5151 return N0.getOperand(0);
5153 // fold (fp_round (fp_round x)) -> (fp_round x)
5154 if (N0.getOpcode() == ISD::FP_ROUND) {
5155 // This is a value preserving truncation if both round's are.
5156 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
5157 N0.getNode()->getConstantOperandVal(1) == 1;
5158 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
5159 DAG.getIntPtrConstant(IsTrunc));
5162 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
5163 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
5164 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
5165 N0.getOperand(0), N1);
5166 AddToWorkList(Tmp.getNode());
5167 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5168 Tmp, N0.getOperand(1));
5174 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
5175 SDValue N0 = N->getOperand(0);
5176 EVT VT = N->getValueType(0);
5177 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5178 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5180 // fold (fp_round_inreg c1fp) -> c1fp
5181 if (N0CFP && isTypeLegal(EVT)) {
5182 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
5183 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
5189 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
5190 SDValue N0 = N->getOperand(0);
5191 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5192 EVT VT = N->getValueType(0);
5194 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
5195 if (N->hasOneUse() &&
5196 N->use_begin()->getOpcode() == ISD::FP_ROUND)
5199 // fold (fp_extend c1fp) -> c1fp
5200 if (N0CFP && VT != MVT::ppcf128)
5201 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
5203 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
5205 if (N0.getOpcode() == ISD::FP_ROUND
5206 && N0.getNode()->getConstantOperandVal(1) == 1) {
5207 SDValue In = N0.getOperand(0);
5208 if (In.getValueType() == VT) return In;
5209 if (VT.bitsLT(In.getValueType()))
5210 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
5211 In, N0.getOperand(1));
5212 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
5215 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
5216 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
5217 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5218 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5219 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5220 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, N->getDebugLoc(),
5222 LN0->getBasePtr(), LN0->getPointerInfo(),
5224 LN0->isVolatile(), LN0->isNonTemporal(),
5225 LN0->getAlignment());
5226 CombineTo(N, ExtLoad);
5227 CombineTo(N0.getNode(),
5228 DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
5229 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
5230 ExtLoad.getValue(1));
5231 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5237 SDValue DAGCombiner::visitFNEG(SDNode *N) {
5238 SDValue N0 = N->getOperand(0);
5239 EVT VT = N->getValueType(0);
5241 if (isNegatibleForFree(N0, LegalOperations))
5242 return GetNegatedExpression(N0, DAG, LegalOperations);
5244 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
5245 // constant pool values.
5246 if (N0.getOpcode() == ISD::BITCAST &&
5248 N0.getNode()->hasOneUse() &&
5249 N0.getOperand(0).getValueType().isInteger()) {
5250 SDValue Int = N0.getOperand(0);
5251 EVT IntVT = Int.getValueType();
5252 if (IntVT.isInteger() && !IntVT.isVector()) {
5253 Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
5254 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
5255 AddToWorkList(Int.getNode());
5256 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5264 SDValue DAGCombiner::visitFABS(SDNode *N) {
5265 SDValue N0 = N->getOperand(0);
5266 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5267 EVT VT = N->getValueType(0);
5269 // fold (fabs c1) -> fabs(c1)
5270 if (N0CFP && VT != MVT::ppcf128)
5271 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5272 // fold (fabs (fabs x)) -> (fabs x)
5273 if (N0.getOpcode() == ISD::FABS)
5274 return N->getOperand(0);
5275 // fold (fabs (fneg x)) -> (fabs x)
5276 // fold (fabs (fcopysign x, y)) -> (fabs x)
5277 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
5278 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
5280 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
5281 // constant pool values.
5282 if (N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
5283 N0.getOperand(0).getValueType().isInteger() &&
5284 !N0.getOperand(0).getValueType().isVector()) {
5285 SDValue Int = N0.getOperand(0);
5286 EVT IntVT = Int.getValueType();
5287 if (IntVT.isInteger() && !IntVT.isVector()) {
5288 Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
5289 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
5290 AddToWorkList(Int.getNode());
5291 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5292 N->getValueType(0), Int);
5299 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
5300 SDValue Chain = N->getOperand(0);
5301 SDValue N1 = N->getOperand(1);
5302 SDValue N2 = N->getOperand(2);
5304 // If N is a constant we could fold this into a fallthrough or unconditional
5305 // branch. However that doesn't happen very often in normal code, because
5306 // Instcombine/SimplifyCFG should have handled the available opportunities.
5307 // If we did this folding here, it would be necessary to update the
5308 // MachineBasicBlock CFG, which is awkward.
5310 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
5312 if (N1.getOpcode() == ISD::SETCC &&
5313 TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
5314 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
5315 Chain, N1.getOperand(2),
5316 N1.getOperand(0), N1.getOperand(1), N2);
5319 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
5320 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
5321 (N1.getOperand(0).hasOneUse() &&
5322 N1.getOperand(0).getOpcode() == ISD::SRL))) {
5324 if (N1.getOpcode() == ISD::TRUNCATE) {
5325 // Look pass the truncate.
5326 Trunc = N1.getNode();
5327 N1 = N1.getOperand(0);
5330 // Match this pattern so that we can generate simpler code:
5333 // %b = and i32 %a, 2
5334 // %c = srl i32 %b, 1
5335 // brcond i32 %c ...
5340 // %b = and i32 %a, 2
5341 // %c = setcc eq %b, 0
5344 // This applies only when the AND constant value has one bit set and the
5345 // SRL constant is equal to the log2 of the AND constant. The back-end is
5346 // smart enough to convert the result into a TEST/JMP sequence.
5347 SDValue Op0 = N1.getOperand(0);
5348 SDValue Op1 = N1.getOperand(1);
5350 if (Op0.getOpcode() == ISD::AND &&
5351 Op1.getOpcode() == ISD::Constant) {
5352 SDValue AndOp1 = Op0.getOperand(1);
5354 if (AndOp1.getOpcode() == ISD::Constant) {
5355 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
5357 if (AndConst.isPowerOf2() &&
5358 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
5360 DAG.getSetCC(N->getDebugLoc(),
5361 TLI.getSetCCResultType(Op0.getValueType()),
5362 Op0, DAG.getConstant(0, Op0.getValueType()),
5365 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5366 MVT::Other, Chain, SetCC, N2);
5367 // Don't add the new BRCond into the worklist or else SimplifySelectCC
5368 // will convert it back to (X & C1) >> C2.
5369 CombineTo(N, NewBRCond, false);
5370 // Truncate is dead.
5372 removeFromWorkList(Trunc);
5373 DAG.DeleteNode(Trunc);
5375 // Replace the uses of SRL with SETCC
5376 WorkListRemover DeadNodes(*this);
5377 DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes);
5378 removeFromWorkList(N1.getNode());
5379 DAG.DeleteNode(N1.getNode());
5380 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5386 // Restore N1 if the above transformation doesn't match.
5387 N1 = N->getOperand(1);
5390 // Transform br(xor(x, y)) -> br(x != y)
5391 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
5392 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
5393 SDNode *TheXor = N1.getNode();
5394 SDValue Op0 = TheXor->getOperand(0);
5395 SDValue Op1 = TheXor->getOperand(1);
5396 if (Op0.getOpcode() == Op1.getOpcode()) {
5397 // Avoid missing important xor optimizations.
5398 SDValue Tmp = visitXOR(TheXor);
5399 if (Tmp.getNode() && Tmp.getNode() != TheXor) {
5400 DEBUG(dbgs() << "\nReplacing.8 ";
5402 dbgs() << "\nWith: ";
5403 Tmp.getNode()->dump(&DAG);
5405 WorkListRemover DeadNodes(*this);
5406 DAG.ReplaceAllUsesOfValueWith(N1, Tmp, &DeadNodes);
5407 removeFromWorkList(TheXor);
5408 DAG.DeleteNode(TheXor);
5409 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5410 MVT::Other, Chain, Tmp, N2);
5414 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
5416 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
5417 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
5418 Op0.getOpcode() == ISD::XOR) {
5419 TheXor = Op0.getNode();
5423 EVT SetCCVT = N1.getValueType();
5425 SetCCVT = TLI.getSetCCResultType(SetCCVT);
5426 SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
5429 Equal ? ISD::SETEQ : ISD::SETNE);
5430 // Replace the uses of XOR with SETCC
5431 WorkListRemover DeadNodes(*this);
5432 DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes);
5433 removeFromWorkList(N1.getNode());
5434 DAG.DeleteNode(N1.getNode());
5435 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5436 MVT::Other, Chain, SetCC, N2);
5443 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
5445 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
5446 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
5447 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
5449 // If N is a constant we could fold this into a fallthrough or unconditional
5450 // branch. However that doesn't happen very often in normal code, because
5451 // Instcombine/SimplifyCFG should have handled the available opportunities.
5452 // If we did this folding here, it would be necessary to update the
5453 // MachineBasicBlock CFG, which is awkward.
5455 // Use SimplifySetCC to simplify SETCC's.
5456 SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
5457 CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
5459 if (Simp.getNode()) AddToWorkList(Simp.getNode());
5461 // fold to a simpler setcc
5462 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
5463 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
5464 N->getOperand(0), Simp.getOperand(2),
5465 Simp.getOperand(0), Simp.getOperand(1),
5471 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
5472 /// pre-indexed load / store when the base pointer is an add or subtract
5473 /// and it has other uses besides the load / store. After the
5474 /// transformation, the new indexed load / store has effectively folded
5475 /// the add / subtract in and all of its other uses are redirected to the
5476 /// new load / store.
5477 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
5478 if (!LegalOperations)
5484 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5485 if (LD->isIndexed())
5487 VT = LD->getMemoryVT();
5488 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
5489 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
5491 Ptr = LD->getBasePtr();
5492 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5493 if (ST->isIndexed())
5495 VT = ST->getMemoryVT();
5496 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
5497 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
5499 Ptr = ST->getBasePtr();
5505 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
5506 // out. There is no reason to make this a preinc/predec.
5507 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
5508 Ptr.getNode()->hasOneUse())
5511 // Ask the target to do addressing mode selection.
5514 ISD::MemIndexedMode AM = ISD::UNINDEXED;
5515 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
5517 // Don't create a indexed load / store with zero offset.
5518 if (isa<ConstantSDNode>(Offset) &&
5519 cast<ConstantSDNode>(Offset)->isNullValue())
5522 // Try turning it into a pre-indexed load / store except when:
5523 // 1) The new base ptr is a frame index.
5524 // 2) If N is a store and the new base ptr is either the same as or is a
5525 // predecessor of the value being stored.
5526 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
5527 // that would create a cycle.
5528 // 4) All uses are load / store ops that use it as old base ptr.
5530 // Check #1. Preinc'ing a frame index would require copying the stack pointer
5531 // (plus the implicit offset) to a register to preinc anyway.
5532 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
5537 SDValue Val = cast<StoreSDNode>(N)->getValue();
5538 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
5542 // Now check for #3 and #4.
5543 bool RealUse = false;
5544 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
5545 E = Ptr.getNode()->use_end(); I != E; ++I) {
5549 if (Use->isPredecessorOf(N))
5552 if (!((Use->getOpcode() == ISD::LOAD &&
5553 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
5554 (Use->getOpcode() == ISD::STORE &&
5555 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
5564 Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
5565 BasePtr, Offset, AM);
5567 Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
5568 BasePtr, Offset, AM);
5571 DEBUG(dbgs() << "\nReplacing.4 ";
5573 dbgs() << "\nWith: ";
5574 Result.getNode()->dump(&DAG);
5576 WorkListRemover DeadNodes(*this);
5578 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
5580 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
5583 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
5587 // Finally, since the node is now dead, remove it from the graph.
5590 // Replace the uses of Ptr with uses of the updated base value.
5591 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
5593 removeFromWorkList(Ptr.getNode());
5594 DAG.DeleteNode(Ptr.getNode());
5599 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
5600 /// add / sub of the base pointer node into a post-indexed load / store.
5601 /// The transformation folded the add / subtract into the new indexed
5602 /// load / store effectively and all of its uses are redirected to the
5603 /// new load / store.
5604 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
5605 if (!LegalOperations)
5611 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5612 if (LD->isIndexed())
5614 VT = LD->getMemoryVT();
5615 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
5616 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
5618 Ptr = LD->getBasePtr();
5619 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5620 if (ST->isIndexed())
5622 VT = ST->getMemoryVT();
5623 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
5624 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
5626 Ptr = ST->getBasePtr();
5632 if (Ptr.getNode()->hasOneUse())
5635 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
5636 E = Ptr.getNode()->use_end(); I != E; ++I) {
5639 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
5644 ISD::MemIndexedMode AM = ISD::UNINDEXED;
5645 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
5646 // Don't create a indexed load / store with zero offset.
5647 if (isa<ConstantSDNode>(Offset) &&
5648 cast<ConstantSDNode>(Offset)->isNullValue())
5651 // Try turning it into a post-indexed load / store except when
5652 // 1) All uses are load / store ops that use it as base ptr.
5653 // 2) Op must be independent of N, i.e. Op is neither a predecessor
5654 // nor a successor of N. Otherwise, if Op is folded that would
5657 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
5661 bool TryNext = false;
5662 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
5663 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
5665 if (Use == Ptr.getNode())
5668 // If all the uses are load / store addresses, then don't do the
5670 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
5671 bool RealUse = false;
5672 for (SDNode::use_iterator III = Use->use_begin(),
5673 EEE = Use->use_end(); III != EEE; ++III) {
5674 SDNode *UseUse = *III;
5675 if (!((UseUse->getOpcode() == ISD::LOAD &&
5676 cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) ||
5677 (UseUse->getOpcode() == ISD::STORE &&
5678 cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use)))
5693 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
5694 SDValue Result = isLoad
5695 ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
5696 BasePtr, Offset, AM)
5697 : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
5698 BasePtr, Offset, AM);
5701 DEBUG(dbgs() << "\nReplacing.5 ";
5703 dbgs() << "\nWith: ";
5704 Result.getNode()->dump(&DAG);
5706 WorkListRemover DeadNodes(*this);
5708 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
5710 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
5713 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
5717 // Finally, since the node is now dead, remove it from the graph.
5720 // Replace the uses of Use with uses of the updated base value.
5721 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
5722 Result.getValue(isLoad ? 1 : 0),
5724 removeFromWorkList(Op);
5734 SDValue DAGCombiner::visitLOAD(SDNode *N) {
5735 LoadSDNode *LD = cast<LoadSDNode>(N);
5736 SDValue Chain = LD->getChain();
5737 SDValue Ptr = LD->getBasePtr();
5739 // If load is not volatile and there are no uses of the loaded value (and
5740 // the updated indexed value in case of indexed loads), change uses of the
5741 // chain value into uses of the chain input (i.e. delete the dead load).
5742 if (!LD->isVolatile()) {
5743 if (N->getValueType(1) == MVT::Other) {
5745 if (N->hasNUsesOfValue(0, 0)) {
5746 // It's not safe to use the two value CombineTo variant here. e.g.
5747 // v1, chain2 = load chain1, loc
5748 // v2, chain3 = load chain2, loc
5750 // Now we replace use of chain2 with chain1. This makes the second load
5751 // isomorphic to the one we are deleting, and thus makes this load live.
5752 DEBUG(dbgs() << "\nReplacing.6 ";
5754 dbgs() << "\nWith chain: ";
5755 Chain.getNode()->dump(&DAG);
5757 WorkListRemover DeadNodes(*this);
5758 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes);
5760 if (N->use_empty()) {
5761 removeFromWorkList(N);
5765 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5769 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
5770 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
5771 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
5772 DEBUG(dbgs() << "\nReplacing.7 ";
5774 dbgs() << "\nWith: ";
5775 Undef.getNode()->dump(&DAG);
5776 dbgs() << " and 2 other values\n");
5777 WorkListRemover DeadNodes(*this);
5778 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes);
5779 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
5780 DAG.getUNDEF(N->getValueType(1)),
5782 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes);
5783 removeFromWorkList(N);
5785 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5790 // If this load is directly stored, replace the load value with the stored
5792 // TODO: Handle store large -> read small portion.
5793 // TODO: Handle TRUNCSTORE/LOADEXT
5794 if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
5795 !LD->isVolatile()) {
5796 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
5797 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
5798 if (PrevST->getBasePtr() == Ptr &&
5799 PrevST->getValue().getValueType() == N->getValueType(0))
5800 return CombineTo(N, Chain.getOperand(1), Chain);
5804 // Try to infer better alignment information than the load already has.
5805 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
5806 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
5807 if (Align > LD->getAlignment())
5808 return DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
5810 Chain, Ptr, LD->getPointerInfo(),
5812 LD->isVolatile(), LD->isNonTemporal(), Align);
5817 // Walk up chain skipping non-aliasing memory nodes.
5818 SDValue BetterChain = FindBetterChain(N, Chain);
5820 // If there is a better chain.
5821 if (Chain != BetterChain) {
5824 // Replace the chain to void dependency.
5825 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
5826 ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
5827 BetterChain, Ptr, LD->getPointerInfo(),
5828 LD->isVolatile(), LD->isNonTemporal(),
5829 LD->getAlignment());
5831 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
5833 BetterChain, Ptr, LD->getPointerInfo(),
5836 LD->isNonTemporal(),
5837 LD->getAlignment());
5840 // Create token factor to keep old chain connected.
5841 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
5842 MVT::Other, Chain, ReplLoad.getValue(1));
5844 // Make sure the new and old chains are cleaned up.
5845 AddToWorkList(Token.getNode());
5847 // Replace uses with load result and token factor. Don't add users
5849 return CombineTo(N, ReplLoad.getValue(0), Token, false);
5853 // Try transforming N to an indexed load.
5854 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
5855 return SDValue(N, 0);
5860 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
5861 /// load is having specific bytes cleared out. If so, return the byte size
5862 /// being masked out and the shift amount.
5863 static std::pair<unsigned, unsigned>
5864 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
5865 std::pair<unsigned, unsigned> Result(0, 0);
5867 // Check for the structure we're looking for.
5868 if (V->getOpcode() != ISD::AND ||
5869 !isa<ConstantSDNode>(V->getOperand(1)) ||
5870 !ISD::isNormalLoad(V->getOperand(0).getNode()))
5873 // Check the chain and pointer.
5874 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
5875 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
5877 // The store should be chained directly to the load or be an operand of a
5879 if (LD == Chain.getNode())
5881 else if (Chain->getOpcode() != ISD::TokenFactor)
5882 return Result; // Fail.
5885 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
5886 if (Chain->getOperand(i).getNode() == LD) {
5890 if (!isOk) return Result;
5893 // This only handles simple types.
5894 if (V.getValueType() != MVT::i16 &&
5895 V.getValueType() != MVT::i32 &&
5896 V.getValueType() != MVT::i64)
5899 // Check the constant mask. Invert it so that the bits being masked out are
5900 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
5901 // follow the sign bit for uniformity.
5902 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
5903 unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
5904 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
5905 unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
5906 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
5907 if (NotMaskLZ == 64) return Result; // All zero mask.
5909 // See if we have a continuous run of bits. If so, we have 0*1+0*
5910 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
5913 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
5914 if (V.getValueType() != MVT::i64 && NotMaskLZ)
5915 NotMaskLZ -= 64-V.getValueSizeInBits();
5917 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
5918 switch (MaskedBytes) {
5922 default: return Result; // All one mask, or 5-byte mask.
5925 // Verify that the first bit starts at a multiple of mask so that the access
5926 // is aligned the same as the access width.
5927 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
5929 Result.first = MaskedBytes;
5930 Result.second = NotMaskTZ/8;
5935 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
5936 /// provides a value as specified by MaskInfo. If so, replace the specified
5937 /// store with a narrower store of truncated IVal.
5939 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
5940 SDValue IVal, StoreSDNode *St,
5942 unsigned NumBytes = MaskInfo.first;
5943 unsigned ByteShift = MaskInfo.second;
5944 SelectionDAG &DAG = DC->getDAG();
5946 // Check to see if IVal is all zeros in the part being masked in by the 'or'
5947 // that uses this. If not, this is not a replacement.
5948 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
5949 ByteShift*8, (ByteShift+NumBytes)*8);
5950 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
5952 // Check that it is legal on the target to do this. It is legal if the new
5953 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
5955 MVT VT = MVT::getIntegerVT(NumBytes*8);
5956 if (!DC->isTypeLegal(VT))
5959 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
5960 // shifted by ByteShift and truncated down to NumBytes.
5962 IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
5963 DAG.getConstant(ByteShift*8, DC->getShiftAmountTy()));
5965 // Figure out the offset for the store and the alignment of the access.
5967 unsigned NewAlign = St->getAlignment();
5969 if (DAG.getTargetLoweringInfo().isLittleEndian())
5970 StOffset = ByteShift;
5972 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
5974 SDValue Ptr = St->getBasePtr();
5976 Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
5977 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
5978 NewAlign = MinAlign(NewAlign, StOffset);
5981 // Truncate down to the new size.
5982 IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
5985 return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr,
5986 St->getPointerInfo().getWithOffset(StOffset),
5987 false, false, NewAlign).getNode();
5991 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
5992 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
5993 /// of the loaded bits, try narrowing the load and store if it would end up
5994 /// being a win for performance or code size.
5995 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
5996 StoreSDNode *ST = cast<StoreSDNode>(N);
5997 if (ST->isVolatile())
6000 SDValue Chain = ST->getChain();
6001 SDValue Value = ST->getValue();
6002 SDValue Ptr = ST->getBasePtr();
6003 EVT VT = Value.getValueType();
6005 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
6008 unsigned Opc = Value.getOpcode();
6010 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
6011 // is a byte mask indicating a consecutive number of bytes, check to see if
6012 // Y is known to provide just those bytes. If so, we try to replace the
6013 // load + replace + store sequence with a single (narrower) store, which makes
6015 if (Opc == ISD::OR) {
6016 std::pair<unsigned, unsigned> MaskedLoad;
6017 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
6018 if (MaskedLoad.first)
6019 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
6020 Value.getOperand(1), ST,this))
6021 return SDValue(NewST, 0);
6023 // Or is commutative, so try swapping X and Y.
6024 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
6025 if (MaskedLoad.first)
6026 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
6027 Value.getOperand(0), ST,this))
6028 return SDValue(NewST, 0);
6031 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
6032 Value.getOperand(1).getOpcode() != ISD::Constant)
6035 SDValue N0 = Value.getOperand(0);
6036 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6037 Chain == SDValue(N0.getNode(), 1)) {
6038 LoadSDNode *LD = cast<LoadSDNode>(N0);
6039 if (LD->getBasePtr() != Ptr ||
6040 LD->getPointerInfo().getAddrSpace() !=
6041 ST->getPointerInfo().getAddrSpace())
6044 // Find the type to narrow it the load / op / store to.
6045 SDValue N1 = Value.getOperand(1);
6046 unsigned BitWidth = N1.getValueSizeInBits();
6047 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
6048 if (Opc == ISD::AND)
6049 Imm ^= APInt::getAllOnesValue(BitWidth);
6050 if (Imm == 0 || Imm.isAllOnesValue())
6052 unsigned ShAmt = Imm.countTrailingZeros();
6053 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
6054 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
6055 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
6056 while (NewBW < BitWidth &&
6057 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
6058 TLI.isNarrowingProfitable(VT, NewVT))) {
6059 NewBW = NextPowerOf2(NewBW);
6060 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
6062 if (NewBW >= BitWidth)
6065 // If the lsb changed does not start at the type bitwidth boundary,
6066 // start at the previous one.
6068 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
6069 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
6070 if ((Imm & Mask) == Imm) {
6071 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
6072 if (Opc == ISD::AND)
6073 NewImm ^= APInt::getAllOnesValue(NewBW);
6074 uint64_t PtrOff = ShAmt / 8;
6075 // For big endian targets, we need to adjust the offset to the pointer to
6076 // load the correct bytes.
6077 if (TLI.isBigEndian())
6078 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
6080 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
6081 const Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
6082 if (NewAlign < TLI.getTargetData()->getABITypeAlignment(NewVTTy))
6085 SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
6086 Ptr.getValueType(), Ptr,
6087 DAG.getConstant(PtrOff, Ptr.getValueType()));
6088 SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
6089 LD->getChain(), NewPtr,
6090 LD->getPointerInfo().getWithOffset(PtrOff),
6091 LD->isVolatile(), LD->isNonTemporal(),
6093 SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
6094 DAG.getConstant(NewImm, NewVT));
6095 SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
6097 ST->getPointerInfo().getWithOffset(PtrOff),
6098 false, false, NewAlign);
6100 AddToWorkList(NewPtr.getNode());
6101 AddToWorkList(NewLD.getNode());
6102 AddToWorkList(NewVal.getNode());
6103 WorkListRemover DeadNodes(*this);
6104 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1),
6114 SDValue DAGCombiner::visitSTORE(SDNode *N) {
6115 StoreSDNode *ST = cast<StoreSDNode>(N);
6116 SDValue Chain = ST->getChain();
6117 SDValue Value = ST->getValue();
6118 SDValue Ptr = ST->getBasePtr();
6120 // If this is a store of a bit convert, store the input value if the
6121 // resultant store does not need a higher alignment than the original.
6122 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
6123 ST->isUnindexed()) {
6124 unsigned OrigAlign = ST->getAlignment();
6125 EVT SVT = Value.getOperand(0).getValueType();
6126 unsigned Align = TLI.getTargetData()->
6127 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
6128 if (Align <= OrigAlign &&
6129 ((!LegalOperations && !ST->isVolatile()) ||
6130 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
6131 return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
6132 Ptr, ST->getPointerInfo(), ST->isVolatile(),
6133 ST->isNonTemporal(), OrigAlign);
6136 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
6137 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
6138 // NOTE: If the original store is volatile, this transform must not increase
6139 // the number of stores. For example, on x86-32 an f64 can be stored in one
6140 // processor operation but an i64 (which is not legal) requires two. So the
6141 // transform should not be done in this case.
6142 if (Value.getOpcode() != ISD::TargetConstantFP) {
6144 switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
6145 default: llvm_unreachable("Unknown FP type");
6146 case MVT::f80: // We don't do this for these yet.
6151 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
6152 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
6153 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
6154 bitcastToAPInt().getZExtValue(), MVT::i32);
6155 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
6156 Ptr, ST->getPointerInfo(), ST->isVolatile(),
6157 ST->isNonTemporal(), ST->getAlignment());
6161 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
6162 !ST->isVolatile()) ||
6163 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
6164 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
6165 getZExtValue(), MVT::i64);
6166 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
6167 Ptr, ST->getPointerInfo(), ST->isVolatile(),
6168 ST->isNonTemporal(), ST->getAlignment());
6169 } else if (!ST->isVolatile() &&
6170 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
6171 // Many FP stores are not made apparent until after legalize, e.g. for
6172 // argument passing. Since this is so common, custom legalize the
6173 // 64-bit integer store into two 32-bit stores.
6174 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
6175 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
6176 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
6177 if (TLI.isBigEndian()) std::swap(Lo, Hi);
6179 unsigned Alignment = ST->getAlignment();
6180 bool isVolatile = ST->isVolatile();
6181 bool isNonTemporal = ST->isNonTemporal();
6183 SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
6184 Ptr, ST->getPointerInfo(),
6185 isVolatile, isNonTemporal,
6186 ST->getAlignment());
6187 Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
6188 DAG.getConstant(4, Ptr.getValueType()));
6189 Alignment = MinAlign(Alignment, 4U);
6190 SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
6191 Ptr, ST->getPointerInfo().getWithOffset(4),
6192 isVolatile, isNonTemporal,
6194 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
6203 // Try to infer better alignment information than the store already has.
6204 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
6205 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
6206 if (Align > ST->getAlignment())
6207 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
6208 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6209 ST->isVolatile(), ST->isNonTemporal(), Align);
6214 // Walk up chain skipping non-aliasing memory nodes.
6215 SDValue BetterChain = FindBetterChain(N, Chain);
6217 // If there is a better chain.
6218 if (Chain != BetterChain) {
6221 // Replace the chain to avoid dependency.
6222 if (ST->isTruncatingStore()) {
6223 ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
6224 ST->getPointerInfo(),
6225 ST->getMemoryVT(), ST->isVolatile(),
6226 ST->isNonTemporal(), ST->getAlignment());
6228 ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
6229 ST->getPointerInfo(),
6230 ST->isVolatile(), ST->isNonTemporal(),
6231 ST->getAlignment());
6234 // Create token to keep both nodes around.
6235 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
6236 MVT::Other, Chain, ReplStore);
6238 // Make sure the new and old chains are cleaned up.
6239 AddToWorkList(Token.getNode());
6241 // Don't add users to work list.
6242 return CombineTo(N, Token, false);
6246 // Try transforming N to an indexed store.
6247 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
6248 return SDValue(N, 0);
6250 // FIXME: is there such a thing as a truncating indexed store?
6251 if (ST->isTruncatingStore() && ST->isUnindexed() &&
6252 Value.getValueType().isInteger()) {
6253 // See if we can simplify the input to this truncstore with knowledge that
6254 // only the low bits are being used. For example:
6255 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
6257 GetDemandedBits(Value,
6258 APInt::getLowBitsSet(Value.getValueSizeInBits(),
6259 ST->getMemoryVT().getSizeInBits()));
6260 AddToWorkList(Value.getNode());
6261 if (Shorter.getNode())
6262 return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
6263 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6264 ST->isVolatile(), ST->isNonTemporal(),
6265 ST->getAlignment());
6267 // Otherwise, see if we can simplify the operation with
6268 // SimplifyDemandedBits, which only works if the value has a single use.
6269 if (SimplifyDemandedBits(Value,
6270 APInt::getLowBitsSet(
6271 Value.getValueType().getScalarType().getSizeInBits(),
6272 ST->getMemoryVT().getScalarType().getSizeInBits())))
6273 return SDValue(N, 0);
6276 // If this is a load followed by a store to the same location, then the store
6278 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
6279 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
6280 ST->isUnindexed() && !ST->isVolatile() &&
6281 // There can't be any side effects between the load and store, such as
6283 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
6284 // The store is dead, remove it.
6289 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
6290 // truncating store. We can do this even if this is already a truncstore.
6291 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
6292 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
6293 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
6294 ST->getMemoryVT())) {
6295 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
6296 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6297 ST->isVolatile(), ST->isNonTemporal(),
6298 ST->getAlignment());
6301 return ReduceLoadOpStoreWidth(N);
6304 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
6305 SDValue InVec = N->getOperand(0);
6306 SDValue InVal = N->getOperand(1);
6307 SDValue EltNo = N->getOperand(2);
6309 // If the inserted element is an UNDEF, just use the input vector.
6310 if (InVal.getOpcode() == ISD::UNDEF)
6313 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
6314 // vector with the inserted element.
6315 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
6316 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6317 SmallVector<SDValue, 8> Ops(InVec.getNode()->op_begin(),
6318 InVec.getNode()->op_end());
6319 if (Elt < Ops.size())
6321 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6322 InVec.getValueType(), &Ops[0], Ops.size());
6324 // If the invec is an UNDEF and if EltNo is a constant, create a new
6325 // BUILD_VECTOR with undef elements and the inserted element.
6326 if (!LegalOperations && InVec.getOpcode() == ISD::UNDEF &&
6327 isa<ConstantSDNode>(EltNo)) {
6328 EVT VT = InVec.getValueType();
6329 EVT EltVT = VT.getVectorElementType();
6330 unsigned NElts = VT.getVectorNumElements();
6331 SmallVector<SDValue, 8> Ops(NElts, DAG.getUNDEF(EltVT));
6333 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6334 if (Elt < Ops.size())
6336 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6337 InVec.getValueType(), &Ops[0], Ops.size());
6342 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
6343 // (vextract (scalar_to_vector val, 0) -> val
6344 SDValue InVec = N->getOperand(0);
6346 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6347 // Check if the result type doesn't match the inserted element type. A
6348 // SCALAR_TO_VECTOR may truncate the inserted element and the
6349 // EXTRACT_VECTOR_ELT may widen the extracted vector.
6350 SDValue InOp = InVec.getOperand(0);
6351 EVT NVT = N->getValueType(0);
6352 if (InOp.getValueType() != NVT) {
6353 assert(InOp.getValueType().isInteger() && NVT.isInteger());
6354 return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
6359 // Perform only after legalization to ensure build_vector / vector_shuffle
6360 // optimizations have already been done.
6361 if (!LegalOperations) return SDValue();
6363 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
6364 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
6365 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
6366 SDValue EltNo = N->getOperand(1);
6368 if (isa<ConstantSDNode>(EltNo)) {
6369 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6370 bool NewLoad = false;
6371 bool BCNumEltsChanged = false;
6372 EVT VT = InVec.getValueType();
6373 EVT ExtVT = VT.getVectorElementType();
6376 if (InVec.getOpcode() == ISD::BITCAST) {
6377 EVT BCVT = InVec.getOperand(0).getValueType();
6378 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
6380 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
6381 BCNumEltsChanged = true;
6382 InVec = InVec.getOperand(0);
6383 ExtVT = BCVT.getVectorElementType();
6387 LoadSDNode *LN0 = NULL;
6388 const ShuffleVectorSDNode *SVN = NULL;
6389 if (ISD::isNormalLoad(InVec.getNode())) {
6390 LN0 = cast<LoadSDNode>(InVec);
6391 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6392 InVec.getOperand(0).getValueType() == ExtVT &&
6393 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
6394 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
6395 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
6396 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
6398 // (load $addr+1*size)
6400 // If the bit convert changed the number of elements, it is unsafe
6401 // to examine the mask.
6402 if (BCNumEltsChanged)
6405 // Select the input vector, guarding against out of range extract vector.
6406 unsigned NumElems = VT.getVectorNumElements();
6407 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
6408 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
6410 if (InVec.getOpcode() == ISD::BITCAST)
6411 InVec = InVec.getOperand(0);
6412 if (ISD::isNormalLoad(InVec.getNode())) {
6413 LN0 = cast<LoadSDNode>(InVec);
6414 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
6418 if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
6421 // If Idx was -1 above, Elt is going to be -1, so just return undef.
6423 return DAG.getUNDEF(LN0->getBasePtr().getValueType());
6425 unsigned Align = LN0->getAlignment();
6427 // Check the resultant load doesn't need a higher alignment than the
6431 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
6433 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
6439 SDValue NewPtr = LN0->getBasePtr();
6440 unsigned PtrOff = 0;
6443 PtrOff = LVT.getSizeInBits() * Elt / 8;
6444 EVT PtrType = NewPtr.getValueType();
6445 if (TLI.isBigEndian())
6446 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
6447 NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
6448 DAG.getConstant(PtrOff, PtrType));
6451 return DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
6452 LN0->getPointerInfo().getWithOffset(PtrOff),
6453 LN0->isVolatile(), LN0->isNonTemporal(), Align);
6459 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
6460 unsigned NumInScalars = N->getNumOperands();
6461 EVT VT = N->getValueType(0);
6463 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
6464 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
6465 // at most two distinct vectors, turn this into a shuffle node.
6466 SDValue VecIn1, VecIn2;
6467 for (unsigned i = 0; i != NumInScalars; ++i) {
6468 // Ignore undef inputs.
6469 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6471 // If this input is something other than a EXTRACT_VECTOR_ELT with a
6472 // constant index, bail out.
6473 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6474 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
6475 VecIn1 = VecIn2 = SDValue(0, 0);
6479 // If the input vector type disagrees with the result of the build_vector,
6480 // we can't make a shuffle.
6481 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
6482 if (ExtractedFromVec.getValueType() != VT) {
6483 VecIn1 = VecIn2 = SDValue(0, 0);
6487 // Otherwise, remember this. We allow up to two distinct input vectors.
6488 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
6491 if (VecIn1.getNode() == 0) {
6492 VecIn1 = ExtractedFromVec;
6493 } else if (VecIn2.getNode() == 0) {
6494 VecIn2 = ExtractedFromVec;
6497 VecIn1 = VecIn2 = SDValue(0, 0);
6502 // If everything is good, we can make a shuffle operation.
6503 if (VecIn1.getNode()) {
6504 SmallVector<int, 8> Mask;
6505 for (unsigned i = 0; i != NumInScalars; ++i) {
6506 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
6511 // If extracting from the first vector, just use the index directly.
6512 SDValue Extract = N->getOperand(i);
6513 SDValue ExtVal = Extract.getOperand(1);
6514 if (Extract.getOperand(0) == VecIn1) {
6515 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
6516 if (ExtIndex > VT.getVectorNumElements())
6519 Mask.push_back(ExtIndex);
6523 // Otherwise, use InIdx + VecSize
6524 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
6525 Mask.push_back(Idx+NumInScalars);
6528 // Add count and size info.
6529 if (!isTypeLegal(VT))
6532 // Return the new VECTOR_SHUFFLE node.
6535 Ops[1] = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6536 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
6542 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
6543 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
6544 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
6545 // inputs come from at most two distinct vectors, turn this into a shuffle
6548 // If we only have one input vector, we don't need to do any concatenation.
6549 if (N->getNumOperands() == 1)
6550 return N->getOperand(0);
6555 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
6556 EVT VT = N->getValueType(0);
6557 unsigned NumElts = VT.getVectorNumElements();
6559 SDValue N0 = N->getOperand(0);
6561 assert(N0.getValueType().getVectorNumElements() == NumElts &&
6562 "Vector shuffle must be normalized in DAG");
6564 // FIXME: implement canonicalizations from DAG.getVectorShuffle()
6566 // If it is a splat, check if the argument vector is another splat or a
6567 // build_vector with all scalar elements the same.
6568 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
6569 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
6570 SDNode *V = N0.getNode();
6572 // If this is a bit convert that changes the element type of the vector but
6573 // not the number of vector elements, look through it. Be careful not to
6574 // look though conversions that change things like v4f32 to v2f64.
6575 if (V->getOpcode() == ISD::BITCAST) {
6576 SDValue ConvInput = V->getOperand(0);
6577 if (ConvInput.getValueType().isVector() &&
6578 ConvInput.getValueType().getVectorNumElements() == NumElts)
6579 V = ConvInput.getNode();
6582 if (V->getOpcode() == ISD::BUILD_VECTOR) {
6583 assert(V->getNumOperands() == NumElts &&
6584 "BUILD_VECTOR has wrong number of operands");
6586 bool AllSame = true;
6587 for (unsigned i = 0; i != NumElts; ++i) {
6588 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
6589 Base = V->getOperand(i);
6593 // Splat of <u, u, u, u>, return <u, u, u, u>
6594 if (!Base.getNode())
6596 for (unsigned i = 0; i != NumElts; ++i) {
6597 if (V->getOperand(i) != Base) {
6602 // Splat of <x, x, x, x>, return <x, x, x, x>
6610 SDValue DAGCombiner::visitMEMBARRIER(SDNode* N) {
6611 if (!TLI.getShouldFoldAtomicFences())
6614 SDValue atomic = N->getOperand(0);
6615 switch (atomic.getOpcode()) {
6616 case ISD::ATOMIC_CMP_SWAP:
6617 case ISD::ATOMIC_SWAP:
6618 case ISD::ATOMIC_LOAD_ADD:
6619 case ISD::ATOMIC_LOAD_SUB:
6620 case ISD::ATOMIC_LOAD_AND:
6621 case ISD::ATOMIC_LOAD_OR:
6622 case ISD::ATOMIC_LOAD_XOR:
6623 case ISD::ATOMIC_LOAD_NAND:
6624 case ISD::ATOMIC_LOAD_MIN:
6625 case ISD::ATOMIC_LOAD_MAX:
6626 case ISD::ATOMIC_LOAD_UMIN:
6627 case ISD::ATOMIC_LOAD_UMAX:
6633 SDValue fence = atomic.getOperand(0);
6634 if (fence.getOpcode() != ISD::MEMBARRIER)
6637 switch (atomic.getOpcode()) {
6638 case ISD::ATOMIC_CMP_SWAP:
6639 return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
6640 fence.getOperand(0),
6641 atomic.getOperand(1), atomic.getOperand(2),
6642 atomic.getOperand(3)), atomic.getResNo());
6643 case ISD::ATOMIC_SWAP:
6644 case ISD::ATOMIC_LOAD_ADD:
6645 case ISD::ATOMIC_LOAD_SUB:
6646 case ISD::ATOMIC_LOAD_AND:
6647 case ISD::ATOMIC_LOAD_OR:
6648 case ISD::ATOMIC_LOAD_XOR:
6649 case ISD::ATOMIC_LOAD_NAND:
6650 case ISD::ATOMIC_LOAD_MIN:
6651 case ISD::ATOMIC_LOAD_MAX:
6652 case ISD::ATOMIC_LOAD_UMIN:
6653 case ISD::ATOMIC_LOAD_UMAX:
6654 return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
6655 fence.getOperand(0),
6656 atomic.getOperand(1), atomic.getOperand(2)),
6663 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
6664 /// an AND to a vector_shuffle with the destination vector and a zero vector.
6665 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
6666 /// vector_shuffle V, Zero, <0, 4, 2, 4>
6667 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
6668 EVT VT = N->getValueType(0);
6669 DebugLoc dl = N->getDebugLoc();
6670 SDValue LHS = N->getOperand(0);
6671 SDValue RHS = N->getOperand(1);
6672 if (N->getOpcode() == ISD::AND) {
6673 if (RHS.getOpcode() == ISD::BITCAST)
6674 RHS = RHS.getOperand(0);
6675 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
6676 SmallVector<int, 8> Indices;
6677 unsigned NumElts = RHS.getNumOperands();
6678 for (unsigned i = 0; i != NumElts; ++i) {
6679 SDValue Elt = RHS.getOperand(i);
6680 if (!isa<ConstantSDNode>(Elt))
6682 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
6683 Indices.push_back(i);
6684 else if (cast<ConstantSDNode>(Elt)->isNullValue())
6685 Indices.push_back(NumElts);
6690 // Let's see if the target supports this vector_shuffle.
6691 EVT RVT = RHS.getValueType();
6692 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
6695 // Return the new VECTOR_SHUFFLE node.
6696 EVT EltVT = RVT.getVectorElementType();
6697 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
6698 DAG.getConstant(0, EltVT));
6699 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6700 RVT, &ZeroOps[0], ZeroOps.size());
6701 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
6702 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
6703 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
6710 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
6711 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
6712 // After legalize, the target may be depending on adds and other
6713 // binary ops to provide legal ways to construct constants or other
6714 // things. Simplifying them may result in a loss of legality.
6715 if (LegalOperations) return SDValue();
6717 assert(N->getValueType(0).isVector() &&
6718 "SimplifyVBinOp only works on vectors!");
6720 SDValue LHS = N->getOperand(0);
6721 SDValue RHS = N->getOperand(1);
6722 SDValue Shuffle = XformToShuffleWithZero(N);
6723 if (Shuffle.getNode()) return Shuffle;
6725 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
6727 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
6728 RHS.getOpcode() == ISD::BUILD_VECTOR) {
6729 SmallVector<SDValue, 8> Ops;
6730 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
6731 SDValue LHSOp = LHS.getOperand(i);
6732 SDValue RHSOp = RHS.getOperand(i);
6733 // If these two elements can't be folded, bail out.
6734 if ((LHSOp.getOpcode() != ISD::UNDEF &&
6735 LHSOp.getOpcode() != ISD::Constant &&
6736 LHSOp.getOpcode() != ISD::ConstantFP) ||
6737 (RHSOp.getOpcode() != ISD::UNDEF &&
6738 RHSOp.getOpcode() != ISD::Constant &&
6739 RHSOp.getOpcode() != ISD::ConstantFP))
6742 // Can't fold divide by zero.
6743 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
6744 N->getOpcode() == ISD::FDIV) {
6745 if ((RHSOp.getOpcode() == ISD::Constant &&
6746 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
6747 (RHSOp.getOpcode() == ISD::ConstantFP &&
6748 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
6752 EVT VT = LHSOp.getValueType();
6753 assert(RHSOp.getValueType() == VT &&
6754 "SimplifyVBinOp with different BUILD_VECTOR element types");
6755 SDValue FoldOp = DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), VT,
6757 if (FoldOp.getOpcode() != ISD::UNDEF &&
6758 FoldOp.getOpcode() != ISD::Constant &&
6759 FoldOp.getOpcode() != ISD::ConstantFP)
6761 Ops.push_back(FoldOp);
6762 AddToWorkList(FoldOp.getNode());
6765 if (Ops.size() == LHS.getNumOperands())
6766 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6767 LHS.getValueType(), &Ops[0], Ops.size());
6773 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
6774 SDValue N1, SDValue N2){
6775 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
6777 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
6778 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6780 // If we got a simplified select_cc node back from SimplifySelectCC, then
6781 // break it down into a new SETCC node, and a new SELECT node, and then return
6782 // the SELECT node, since we were called with a SELECT node.
6783 if (SCC.getNode()) {
6784 // Check to see if we got a select_cc back (to turn into setcc/select).
6785 // Otherwise, just return whatever node we got back, like fabs.
6786 if (SCC.getOpcode() == ISD::SELECT_CC) {
6787 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
6789 SCC.getOperand(0), SCC.getOperand(1),
6791 AddToWorkList(SETCC.getNode());
6792 return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
6793 SCC.getOperand(2), SCC.getOperand(3), SETCC);
6801 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
6802 /// are the two values being selected between, see if we can simplify the
6803 /// select. Callers of this should assume that TheSelect is deleted if this
6804 /// returns true. As such, they should return the appropriate thing (e.g. the
6805 /// node) back to the top-level of the DAG combiner loop to avoid it being
6807 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
6810 // If this is a select from two identical things, try to pull the operation
6811 // through the select.
6812 if (LHS.getOpcode() != RHS.getOpcode() ||
6813 !LHS.hasOneUse() || !RHS.hasOneUse())
6816 // If this is a load and the token chain is identical, replace the select
6817 // of two loads with a load through a select of the address to load from.
6818 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
6819 // constants have been dropped into the constant pool.
6820 if (LHS.getOpcode() == ISD::LOAD) {
6821 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
6822 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
6824 // Token chains must be identical.
6825 if (LHS.getOperand(0) != RHS.getOperand(0) ||
6826 // Do not let this transformation reduce the number of volatile loads.
6827 LLD->isVolatile() || RLD->isVolatile() ||
6828 // If this is an EXTLOAD, the VT's must match.
6829 LLD->getMemoryVT() != RLD->getMemoryVT() ||
6830 // If this is an EXTLOAD, the kind of extension must match.
6831 (LLD->getExtensionType() != RLD->getExtensionType() &&
6832 // The only exception is if one of the extensions is anyext.
6833 LLD->getExtensionType() != ISD::EXTLOAD &&
6834 RLD->getExtensionType() != ISD::EXTLOAD) ||
6835 // FIXME: this discards src value information. This is
6836 // over-conservative. It would be beneficial to be able to remember
6837 // both potential memory locations. Since we are discarding
6838 // src value info, don't do the transformation if the memory
6839 // locations are not in the default address space.
6840 LLD->getPointerInfo().getAddrSpace() != 0 ||
6841 RLD->getPointerInfo().getAddrSpace() != 0)
6844 // Check that the select condition doesn't reach either load. If so,
6845 // folding this will induce a cycle into the DAG. If not, this is safe to
6846 // xform, so create a select of the addresses.
6848 if (TheSelect->getOpcode() == ISD::SELECT) {
6849 SDNode *CondNode = TheSelect->getOperand(0).getNode();
6850 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
6851 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
6853 Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
6854 LLD->getBasePtr().getValueType(),
6855 TheSelect->getOperand(0), LLD->getBasePtr(),
6857 } else { // Otherwise SELECT_CC
6858 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
6859 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
6861 if ((LLD->hasAnyUseOfValue(1) &&
6862 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
6863 (LLD->hasAnyUseOfValue(1) &&
6864 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))))
6867 Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
6868 LLD->getBasePtr().getValueType(),
6869 TheSelect->getOperand(0),
6870 TheSelect->getOperand(1),
6871 LLD->getBasePtr(), RLD->getBasePtr(),
6872 TheSelect->getOperand(4));
6876 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
6877 Load = DAG.getLoad(TheSelect->getValueType(0),
6878 TheSelect->getDebugLoc(),
6879 // FIXME: Discards pointer info.
6880 LLD->getChain(), Addr, MachinePointerInfo(),
6881 LLD->isVolatile(), LLD->isNonTemporal(),
6882 LLD->getAlignment());
6884 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
6885 RLD->getExtensionType() : LLD->getExtensionType(),
6886 TheSelect->getValueType(0),
6887 TheSelect->getDebugLoc(),
6888 // FIXME: Discards pointer info.
6889 LLD->getChain(), Addr, MachinePointerInfo(),
6890 LLD->getMemoryVT(), LLD->isVolatile(),
6891 LLD->isNonTemporal(), LLD->getAlignment());
6894 // Users of the select now use the result of the load.
6895 CombineTo(TheSelect, Load);
6897 // Users of the old loads now use the new load's chain. We know the
6898 // old-load value is dead now.
6899 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
6900 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
6907 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
6908 /// where 'cond' is the comparison specified by CC.
6909 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
6910 SDValue N2, SDValue N3,
6911 ISD::CondCode CC, bool NotExtCompare) {
6912 // (x ? y : y) -> y.
6913 if (N2 == N3) return N2;
6915 EVT VT = N2.getValueType();
6916 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
6917 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
6918 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
6920 // Determine if the condition we're dealing with is constant
6921 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
6922 N0, N1, CC, DL, false);
6923 if (SCC.getNode()) AddToWorkList(SCC.getNode());
6924 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
6926 // fold select_cc true, x, y -> x
6927 if (SCCC && !SCCC->isNullValue())
6929 // fold select_cc false, x, y -> y
6930 if (SCCC && SCCC->isNullValue())
6933 // Check to see if we can simplify the select into an fabs node
6934 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
6935 // Allow either -0.0 or 0.0
6936 if (CFP->getValueAPF().isZero()) {
6937 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
6938 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
6939 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
6940 N2 == N3.getOperand(0))
6941 return DAG.getNode(ISD::FABS, DL, VT, N0);
6943 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
6944 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
6945 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
6946 N2.getOperand(0) == N3)
6947 return DAG.getNode(ISD::FABS, DL, VT, N3);
6951 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
6952 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
6953 // in it. This is a win when the constant is not otherwise available because
6954 // it replaces two constant pool loads with one. We only do this if the FP
6955 // type is known to be legal, because if it isn't, then we are before legalize
6956 // types an we want the other legalization to happen first (e.g. to avoid
6957 // messing with soft float) and if the ConstantFP is not legal, because if
6958 // it is legal, we may not need to store the FP constant in a constant pool.
6959 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
6960 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
6961 if (TLI.isTypeLegal(N2.getValueType()) &&
6962 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
6963 TargetLowering::Legal) &&
6964 // If both constants have multiple uses, then we won't need to do an
6965 // extra load, they are likely around in registers for other users.
6966 (TV->hasOneUse() || FV->hasOneUse())) {
6967 Constant *Elts[] = {
6968 const_cast<ConstantFP*>(FV->getConstantFPValue()),
6969 const_cast<ConstantFP*>(TV->getConstantFPValue())
6971 const Type *FPTy = Elts[0]->getType();
6972 const TargetData &TD = *TLI.getTargetData();
6974 // Create a ConstantArray of the two constants.
6975 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts, 2);
6976 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
6977 TD.getPrefTypeAlignment(FPTy));
6978 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
6980 // Get the offsets to the 0 and 1 element of the array so that we can
6981 // select between them.
6982 SDValue Zero = DAG.getIntPtrConstant(0);
6983 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
6984 SDValue One = DAG.getIntPtrConstant(EltSize);
6986 SDValue Cond = DAG.getSetCC(DL,
6987 TLI.getSetCCResultType(N0.getValueType()),
6989 SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
6991 CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
6993 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
6994 MachinePointerInfo::getConstantPool(), false,
7000 // Check to see if we can perform the "gzip trick", transforming
7001 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
7002 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
7003 N0.getValueType().isInteger() &&
7004 N2.getValueType().isInteger() &&
7005 (N1C->isNullValue() || // (a < 0) ? b : 0
7006 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
7007 EVT XType = N0.getValueType();
7008 EVT AType = N2.getValueType();
7009 if (XType.bitsGE(AType)) {
7010 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
7011 // single-bit constant.
7012 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
7013 unsigned ShCtV = N2C->getAPIntValue().logBase2();
7014 ShCtV = XType.getSizeInBits()-ShCtV-1;
7015 SDValue ShCt = DAG.getConstant(ShCtV, getShiftAmountTy());
7016 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
7018 AddToWorkList(Shift.getNode());
7020 if (XType.bitsGT(AType)) {
7021 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
7022 AddToWorkList(Shift.getNode());
7025 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
7028 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
7030 DAG.getConstant(XType.getSizeInBits()-1,
7031 getShiftAmountTy()));
7032 AddToWorkList(Shift.getNode());
7034 if (XType.bitsGT(AType)) {
7035 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
7036 AddToWorkList(Shift.getNode());
7039 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
7043 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
7044 // where y is has a single bit set.
7045 // A plaintext description would be, we can turn the SELECT_CC into an AND
7046 // when the condition can be materialized as an all-ones register. Any
7047 // single bit-test can be materialized as an all-ones register with
7048 // shift-left and shift-right-arith.
7049 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
7050 N0->getValueType(0) == VT &&
7051 N1C && N1C->isNullValue() &&
7052 N2C && N2C->isNullValue()) {
7053 SDValue AndLHS = N0->getOperand(0);
7054 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7055 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
7056 // Shift the tested bit over the sign bit.
7057 APInt AndMask = ConstAndRHS->getAPIntValue();
7059 DAG.getConstant(AndMask.countLeadingZeros(), getShiftAmountTy());
7060 SDValue Shl = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, AndLHS, ShlAmt);
7062 // Now arithmetic right shift it all the way over, so the result is either
7063 // all-ones, or zero.
7065 DAG.getConstant(AndMask.getBitWidth()-1, getShiftAmountTy());
7066 SDValue Shr = DAG.getNode(ISD::SRA, N0.getDebugLoc(), VT, Shl, ShrAmt);
7068 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
7072 // fold select C, 16, 0 -> shl C, 4
7073 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
7074 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent) {
7076 // If the caller doesn't want us to simplify this into a zext of a compare,
7078 if (NotExtCompare && N2C->getAPIntValue() == 1)
7081 // Get a SetCC of the condition
7082 // FIXME: Should probably make sure that setcc is legal if we ever have a
7083 // target where it isn't.
7085 // cast from setcc result type to select result type
7087 SCC = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
7089 if (N2.getValueType().bitsLT(SCC.getValueType()))
7090 Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
7092 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
7093 N2.getValueType(), SCC);
7095 SCC = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
7096 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
7097 N2.getValueType(), SCC);
7100 AddToWorkList(SCC.getNode());
7101 AddToWorkList(Temp.getNode());
7103 if (N2C->getAPIntValue() == 1)
7106 // shl setcc result by log2 n2c
7107 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
7108 DAG.getConstant(N2C->getAPIntValue().logBase2(),
7109 getShiftAmountTy()));
7112 // Check to see if this is the equivalent of setcc
7113 // FIXME: Turn all of these into setcc if setcc if setcc is legal
7114 // otherwise, go ahead with the folds.
7115 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
7116 EVT XType = N0.getValueType();
7117 if (!LegalOperations ||
7118 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
7119 SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
7120 if (Res.getValueType() != VT)
7121 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
7125 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
7126 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
7127 (!LegalOperations ||
7128 TLI.isOperationLegal(ISD::CTLZ, XType))) {
7129 SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
7130 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
7131 DAG.getConstant(Log2_32(XType.getSizeInBits()),
7132 getShiftAmountTy()));
7134 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
7135 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
7136 SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
7137 XType, DAG.getConstant(0, XType), N0);
7138 SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
7139 return DAG.getNode(ISD::SRL, DL, XType,
7140 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
7141 DAG.getConstant(XType.getSizeInBits()-1,
7142 getShiftAmountTy()));
7144 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
7145 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
7146 SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
7147 DAG.getConstant(XType.getSizeInBits()-1,
7148 getShiftAmountTy()));
7149 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
7153 // Check to see if this is an integer abs.
7154 // select_cc setg[te] X, 0, X, -X ->
7155 // select_cc setgt X, -1, X, -X ->
7156 // select_cc setl[te] X, 0, -X, X ->
7157 // select_cc setlt X, 1, -X, X ->
7158 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
7160 ConstantSDNode *SubC = NULL;
7161 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
7162 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
7163 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
7164 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
7165 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
7166 (N1C->isOne() && CC == ISD::SETLT)) &&
7167 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
7168 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
7170 EVT XType = N0.getValueType();
7171 if (SubC && SubC->isNullValue() && XType.isInteger()) {
7172 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
7174 DAG.getConstant(XType.getSizeInBits()-1,
7175 getShiftAmountTy()));
7176 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
7178 AddToWorkList(Shift.getNode());
7179 AddToWorkList(Add.getNode());
7180 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
7187 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
7188 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
7189 SDValue N1, ISD::CondCode Cond,
7190 DebugLoc DL, bool foldBooleans) {
7191 TargetLowering::DAGCombinerInfo
7192 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
7193 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
7196 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
7197 /// return a DAG expression to select that will generate the same value by
7198 /// multiplying by a magic number. See:
7199 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
7200 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
7201 std::vector<SDNode*> Built;
7202 SDValue S = TLI.BuildSDIV(N, DAG, &Built);
7204 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
7210 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
7211 /// return a DAG expression to select that will generate the same value by
7212 /// multiplying by a magic number. See:
7213 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
7214 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
7215 std::vector<SDNode*> Built;
7216 SDValue S = TLI.BuildUDIV(N, DAG, &Built);
7218 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
7224 /// FindBaseOffset - Return true if base is a frame index, which is known not
7225 // to alias with anything but itself. Provides base object and offset as
7227 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
7228 const GlobalValue *&GV, void *&CV) {
7229 // Assume it is a primitive operation.
7230 Base = Ptr; Offset = 0; GV = 0; CV = 0;
7232 // If it's an adding a simple constant then integrate the offset.
7233 if (Base.getOpcode() == ISD::ADD) {
7234 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
7235 Base = Base.getOperand(0);
7236 Offset += C->getZExtValue();
7240 // Return the underlying GlobalValue, and update the Offset. Return false
7241 // for GlobalAddressSDNode since the same GlobalAddress may be represented
7242 // by multiple nodes with different offsets.
7243 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
7244 GV = G->getGlobal();
7245 Offset += G->getOffset();
7249 // Return the underlying Constant value, and update the Offset. Return false
7250 // for ConstantSDNodes since the same constant pool entry may be represented
7251 // by multiple nodes with different offsets.
7252 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
7253 CV = C->isMachineConstantPoolEntry() ? (void *)C->getMachineCPVal()
7254 : (void *)C->getConstVal();
7255 Offset += C->getOffset();
7258 // If it's any of the following then it can't alias with anything but itself.
7259 return isa<FrameIndexSDNode>(Base);
7262 /// isAlias - Return true if there is any possibility that the two addresses
7264 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
7265 const Value *SrcValue1, int SrcValueOffset1,
7266 unsigned SrcValueAlign1,
7267 const MDNode *TBAAInfo1,
7268 SDValue Ptr2, int64_t Size2,
7269 const Value *SrcValue2, int SrcValueOffset2,
7270 unsigned SrcValueAlign2,
7271 const MDNode *TBAAInfo2) const {
7272 // If they are the same then they must be aliases.
7273 if (Ptr1 == Ptr2) return true;
7275 // Gather base node and offset information.
7276 SDValue Base1, Base2;
7277 int64_t Offset1, Offset2;
7278 const GlobalValue *GV1, *GV2;
7280 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
7281 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
7283 // If they have a same base address then check to see if they overlap.
7284 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
7285 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
7287 // It is possible for different frame indices to alias each other, mostly
7288 // when tail call optimization reuses return address slots for arguments.
7289 // To catch this case, look up the actual index of frame indices to compute
7290 // the real alias relationship.
7291 if (isFrameIndex1 && isFrameIndex2) {
7292 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7293 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
7294 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
7295 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
7298 // Otherwise, if we know what the bases are, and they aren't identical, then
7299 // we know they cannot alias.
7300 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
7303 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
7304 // compared to the size and offset of the access, we may be able to prove they
7305 // do not alias. This check is conservative for now to catch cases created by
7306 // splitting vector types.
7307 if ((SrcValueAlign1 == SrcValueAlign2) &&
7308 (SrcValueOffset1 != SrcValueOffset2) &&
7309 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
7310 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
7311 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
7313 // There is no overlap between these relatively aligned accesses of similar
7314 // size, return no alias.
7315 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
7319 if (CombinerGlobalAA) {
7320 // Use alias analysis information.
7321 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
7322 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
7323 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
7324 AliasAnalysis::AliasResult AAResult =
7325 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
7326 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
7327 if (AAResult == AliasAnalysis::NoAlias)
7331 // Otherwise we have to assume they alias.
7335 /// FindAliasInfo - Extracts the relevant alias information from the memory
7336 /// node. Returns true if the operand was a load.
7337 bool DAGCombiner::FindAliasInfo(SDNode *N,
7338 SDValue &Ptr, int64_t &Size,
7339 const Value *&SrcValue,
7340 int &SrcValueOffset,
7341 unsigned &SrcValueAlign,
7342 const MDNode *&TBAAInfo) const {
7343 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7344 Ptr = LD->getBasePtr();
7345 Size = LD->getMemoryVT().getSizeInBits() >> 3;
7346 SrcValue = LD->getSrcValue();
7347 SrcValueOffset = LD->getSrcValueOffset();
7348 SrcValueAlign = LD->getOriginalAlignment();
7349 TBAAInfo = LD->getTBAAInfo();
7351 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7352 Ptr = ST->getBasePtr();
7353 Size = ST->getMemoryVT().getSizeInBits() >> 3;
7354 SrcValue = ST->getSrcValue();
7355 SrcValueOffset = ST->getSrcValueOffset();
7356 SrcValueAlign = ST->getOriginalAlignment();
7357 TBAAInfo = ST->getTBAAInfo();
7359 llvm_unreachable("FindAliasInfo expected a memory operand");
7365 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
7366 /// looking for aliasing nodes and adding them to the Aliases vector.
7367 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
7368 SmallVector<SDValue, 8> &Aliases) {
7369 SmallVector<SDValue, 8> Chains; // List of chains to visit.
7370 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
7372 // Get alias information for node.
7375 const Value *SrcValue;
7377 unsigned SrcValueAlign;
7378 const MDNode *SrcTBAAInfo;
7379 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
7380 SrcValueAlign, SrcTBAAInfo);
7383 Chains.push_back(OriginalChain);
7386 // Look at each chain and determine if it is an alias. If so, add it to the
7387 // aliases list. If not, then continue up the chain looking for the next
7389 while (!Chains.empty()) {
7390 SDValue Chain = Chains.back();
7393 // For TokenFactor nodes, look at each operand and only continue up the
7394 // chain until we find two aliases. If we've seen two aliases, assume we'll
7395 // find more and revert to original chain since the xform is unlikely to be
7398 // FIXME: The depth check could be made to return the last non-aliasing
7399 // chain we found before we hit a tokenfactor rather than the original
7401 if (Depth > 6 || Aliases.size() == 2) {
7403 Aliases.push_back(OriginalChain);
7407 // Don't bother if we've been before.
7408 if (!Visited.insert(Chain.getNode()))
7411 switch (Chain.getOpcode()) {
7412 case ISD::EntryToken:
7413 // Entry token is ideal chain operand, but handled in FindBetterChain.
7418 // Get alias information for Chain.
7421 const Value *OpSrcValue;
7422 int OpSrcValueOffset;
7423 unsigned OpSrcValueAlign;
7424 const MDNode *OpSrcTBAAInfo;
7425 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
7426 OpSrcValue, OpSrcValueOffset,
7430 // If chain is alias then stop here.
7431 if (!(IsLoad && IsOpLoad) &&
7432 isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
7434 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
7435 OpSrcValueAlign, OpSrcTBAAInfo)) {
7436 Aliases.push_back(Chain);
7438 // Look further up the chain.
7439 Chains.push_back(Chain.getOperand(0));
7445 case ISD::TokenFactor:
7446 // We have to check each of the operands of the token factor for "small"
7447 // token factors, so we queue them up. Adding the operands to the queue
7448 // (stack) in reverse order maintains the original order and increases the
7449 // likelihood that getNode will find a matching token factor (CSE.)
7450 if (Chain.getNumOperands() > 16) {
7451 Aliases.push_back(Chain);
7454 for (unsigned n = Chain.getNumOperands(); n;)
7455 Chains.push_back(Chain.getOperand(--n));
7460 // For all other instructions we will just have to take what we can get.
7461 Aliases.push_back(Chain);
7467 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
7468 /// for a better chain (aliasing node.)
7469 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
7470 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
7472 // Accumulate all the aliases to this node.
7473 GatherAllAliases(N, OldChain, Aliases);
7475 if (Aliases.size() == 0) {
7476 // If no operands then chain to entry token.
7477 return DAG.getEntryNode();
7478 } else if (Aliases.size() == 1) {
7479 // If a single operand then chain to it. We don't need to revisit it.
7483 // Construct a custom tailored token factor.
7484 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
7485 &Aliases[0], Aliases.size());
7488 // SelectionDAG::Combine - This is the entry point for the file.
7490 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
7491 CodeGenOpt::Level OptLevel) {
7492 /// run - This is the main entry point to this class.
7494 DAGCombiner(*this, AA, OptLevel).Run(Level);