blob: dae4e2102d6277c9cd5a17229490701dc2e53adf [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Nate Begeman and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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.
12//
13// FIXME: Missing folds
14// sdiv, udiv, srem, urem (X, const) where X is an integer can be expanded into
15// a sequence of multiplies, shifts, and adds. This should be controlled by
16// some kind of hint from the target that int div is expensive.
17// various folds of mulh[s,u] by constants such as -1, powers of 2, etc.
18//
19// FIXME: select C, pow2, pow2 -> something smart
20// FIXME: trunc(select X, Y, Z) -> select X, trunc(Y), trunc(Z)
21// FIXME: Dead stores -> nuke
22// FIXME: shr X, (and Y,31) -> shr X, Y (TRICKY!)
23// FIXME: mul (x, const) -> shifts + adds
24// FIXME: undef values
25// FIXME: divide by zero is currently left unfolded. do we want to turn this
26// into an undef?
27// FIXME: select ne (select cc, 1, 0), 0, true, false -> select cc, true, false
28//
29//===----------------------------------------------------------------------===//
30
31#define DEBUG_TYPE "dagcombine"
32#include "llvm/CodeGen/SelectionDAG.h"
33#include "llvm/Analysis/AliasAnalysis.h"
34#include "llvm/Target/TargetData.h"
35#include "llvm/Target/TargetLowering.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetOptions.h"
38#include "llvm/ADT/SmallPtrSet.h"
39#include "llvm/ADT/Statistic.h"
40#include "llvm/Support/Compiler.h"
41#include "llvm/Support/CommandLine.h"
42#include "llvm/Support/Debug.h"
43#include "llvm/Support/MathExtras.h"
44#include <algorithm>
45using namespace llvm;
46
47STATISTIC(NodesCombined , "Number of dag nodes combined");
48STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
49STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
50
51namespace {
52#ifndef NDEBUG
53 static cl::opt<bool>
54 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
55 cl::desc("Pop up a window to show dags before the first "
56 "dag combine pass"));
57 static cl::opt<bool>
58 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
59 cl::desc("Pop up a window to show dags before the second "
60 "dag combine pass"));
61#else
62 static const bool ViewDAGCombine1 = false;
63 static const bool ViewDAGCombine2 = false;
64#endif
65
66 static cl::opt<bool>
67 CombinerAA("combiner-alias-analysis", cl::Hidden,
68 cl::desc("Turn on alias analysis during testing"));
69
70 static cl::opt<bool>
71 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
72 cl::desc("Include global information in alias analysis"));
73
74//------------------------------ DAGCombiner ---------------------------------//
75
76 class VISIBILITY_HIDDEN DAGCombiner {
77 SelectionDAG &DAG;
78 TargetLowering &TLI;
79 bool AfterLegalize;
80
81 // Worklist of all of the nodes that need to be simplified.
82 std::vector<SDNode*> WorkList;
83
84 // AA - Used for DAG load/store alias analysis.
85 AliasAnalysis &AA;
86
87 /// AddUsersToWorkList - When an instruction is simplified, add all users of
88 /// the instruction to the work lists because they might get more simplified
89 /// now.
90 ///
91 void AddUsersToWorkList(SDNode *N) {
92 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
93 UI != UE; ++UI)
94 AddToWorkList(*UI);
95 }
96
97 /// removeFromWorkList - remove all instances of N from the worklist.
98 ///
99 void removeFromWorkList(SDNode *N) {
100 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
101 WorkList.end());
102 }
103
104 public:
105 /// AddToWorkList - Add to the work list making sure it's instance is at the
106 /// the back (next to be processed.)
107 void AddToWorkList(SDNode *N) {
108 removeFromWorkList(N);
109 WorkList.push_back(N);
110 }
111
112 SDOperand CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
113 bool AddTo = true) {
114 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
115 ++NodesCombined;
116 DOUT << "\nReplacing.1 "; DEBUG(N->dump(&DAG));
117 DOUT << "\nWith: "; DEBUG(To[0].Val->dump(&DAG));
118 DOUT << " and " << NumTo-1 << " other values\n";
119 std::vector<SDNode*> NowDead;
120 DAG.ReplaceAllUsesWith(N, To, &NowDead);
121
122 if (AddTo) {
123 // Push the new nodes and any users onto the worklist
124 for (unsigned i = 0, e = NumTo; i != e; ++i) {
125 AddToWorkList(To[i].Val);
126 AddUsersToWorkList(To[i].Val);
127 }
128 }
129
130 // Nodes can be reintroduced into the worklist. Make sure we do not
131 // process a node that has been replaced.
132 removeFromWorkList(N);
133 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
134 removeFromWorkList(NowDead[i]);
135
136 // Finally, since the node is now dead, remove it from the graph.
137 DAG.DeleteNode(N);
138 return SDOperand(N, 0);
139 }
140
141 SDOperand CombineTo(SDNode *N, SDOperand Res, bool AddTo = true) {
142 return CombineTo(N, &Res, 1, AddTo);
143 }
144
145 SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1,
146 bool AddTo = true) {
147 SDOperand To[] = { Res0, Res1 };
148 return CombineTo(N, To, 2, AddTo);
149 }
150 private:
151
152 /// SimplifyDemandedBits - Check the specified integer node value to see if
153 /// it can be simplified or if things it uses can be simplified by bit
154 /// propagation. If so, return true.
155 bool SimplifyDemandedBits(SDOperand Op) {
156 TargetLowering::TargetLoweringOpt TLO(DAG);
157 uint64_t KnownZero, KnownOne;
158 uint64_t Demanded = MVT::getIntVTBitMask(Op.getValueType());
159 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
160 return false;
161
162 // Revisit the node.
163 AddToWorkList(Op.Val);
164
165 // Replace the old value with the new one.
166 ++NodesCombined;
167 DOUT << "\nReplacing.2 "; DEBUG(TLO.Old.Val->dump(&DAG));
168 DOUT << "\nWith: "; DEBUG(TLO.New.Val->dump(&DAG));
169 DOUT << '\n';
170
171 std::vector<SDNode*> NowDead;
172 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, NowDead);
173
174 // Push the new node and any (possibly new) users onto the worklist.
175 AddToWorkList(TLO.New.Val);
176 AddUsersToWorkList(TLO.New.Val);
177
178 // Nodes can end up on the worklist more than once. Make sure we do
179 // not process a node that has been replaced.
180 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
181 removeFromWorkList(NowDead[i]);
182
183 // Finally, if the node is now dead, remove it from the graph. The node
184 // may not be dead if the replacement process recursively simplified to
185 // something else needing this node.
186 if (TLO.Old.Val->use_empty()) {
187 removeFromWorkList(TLO.Old.Val);
188
189 // If the operands of this node are only used by the node, they will now
190 // be dead. Make sure to visit them first to delete dead nodes early.
191 for (unsigned i = 0, e = TLO.Old.Val->getNumOperands(); i != e; ++i)
192 if (TLO.Old.Val->getOperand(i).Val->hasOneUse())
193 AddToWorkList(TLO.Old.Val->getOperand(i).Val);
194
195 DAG.DeleteNode(TLO.Old.Val);
196 }
197 return true;
198 }
199
200 bool CombineToPreIndexedLoadStore(SDNode *N);
201 bool CombineToPostIndexedLoadStore(SDNode *N);
202
203
204 /// visit - call the node-specific routine that knows how to fold each
205 /// particular type of node.
206 SDOperand visit(SDNode *N);
207
208 // Visitation implementation - Implement dag node combining for different
209 // node types. The semantics are as follows:
210 // Return Value:
211 // SDOperand.Val == 0 - No change was made
212 // SDOperand.Val == N - N was replaced, is dead, and is already handled.
213 // otherwise - N should be replaced by the returned Operand.
214 //
215 SDOperand visitTokenFactor(SDNode *N);
216 SDOperand visitADD(SDNode *N);
217 SDOperand visitSUB(SDNode *N);
218 SDOperand visitADDC(SDNode *N);
219 SDOperand visitADDE(SDNode *N);
220 SDOperand visitMUL(SDNode *N);
221 SDOperand visitSDIV(SDNode *N);
222 SDOperand visitUDIV(SDNode *N);
223 SDOperand visitSREM(SDNode *N);
224 SDOperand visitUREM(SDNode *N);
225 SDOperand visitMULHU(SDNode *N);
226 SDOperand visitMULHS(SDNode *N);
227 SDOperand visitAND(SDNode *N);
228 SDOperand visitOR(SDNode *N);
229 SDOperand visitXOR(SDNode *N);
230 SDOperand SimplifyVBinOp(SDNode *N);
231 SDOperand visitSHL(SDNode *N);
232 SDOperand visitSRA(SDNode *N);
233 SDOperand visitSRL(SDNode *N);
234 SDOperand visitCTLZ(SDNode *N);
235 SDOperand visitCTTZ(SDNode *N);
236 SDOperand visitCTPOP(SDNode *N);
237 SDOperand visitSELECT(SDNode *N);
238 SDOperand visitSELECT_CC(SDNode *N);
239 SDOperand visitSETCC(SDNode *N);
240 SDOperand visitSIGN_EXTEND(SDNode *N);
241 SDOperand visitZERO_EXTEND(SDNode *N);
242 SDOperand visitANY_EXTEND(SDNode *N);
243 SDOperand visitSIGN_EXTEND_INREG(SDNode *N);
244 SDOperand visitTRUNCATE(SDNode *N);
245 SDOperand visitBIT_CONVERT(SDNode *N);
246 SDOperand visitFADD(SDNode *N);
247 SDOperand visitFSUB(SDNode *N);
248 SDOperand visitFMUL(SDNode *N);
249 SDOperand visitFDIV(SDNode *N);
250 SDOperand visitFREM(SDNode *N);
251 SDOperand visitFCOPYSIGN(SDNode *N);
252 SDOperand visitSINT_TO_FP(SDNode *N);
253 SDOperand visitUINT_TO_FP(SDNode *N);
254 SDOperand visitFP_TO_SINT(SDNode *N);
255 SDOperand visitFP_TO_UINT(SDNode *N);
256 SDOperand visitFP_ROUND(SDNode *N);
257 SDOperand visitFP_ROUND_INREG(SDNode *N);
258 SDOperand visitFP_EXTEND(SDNode *N);
259 SDOperand visitFNEG(SDNode *N);
260 SDOperand visitFABS(SDNode *N);
261 SDOperand visitBRCOND(SDNode *N);
262 SDOperand visitBR_CC(SDNode *N);
263 SDOperand visitLOAD(SDNode *N);
264 SDOperand visitSTORE(SDNode *N);
265 SDOperand visitINSERT_VECTOR_ELT(SDNode *N);
266 SDOperand visitBUILD_VECTOR(SDNode *N);
267 SDOperand visitCONCAT_VECTORS(SDNode *N);
268 SDOperand visitVECTOR_SHUFFLE(SDNode *N);
269
270 SDOperand XformToShuffleWithZero(SDNode *N);
271 SDOperand ReassociateOps(unsigned Opc, SDOperand LHS, SDOperand RHS);
272
273 bool SimplifySelectOps(SDNode *SELECT, SDOperand LHS, SDOperand RHS);
274 SDOperand SimplifyBinOpWithSameOpcodeHands(SDNode *N);
275 SDOperand SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2);
276 SDOperand SimplifySelectCC(SDOperand N0, SDOperand N1, SDOperand N2,
277 SDOperand N3, ISD::CondCode CC,
278 bool NotExtCompare = false);
279 SDOperand SimplifySetCC(MVT::ValueType VT, SDOperand N0, SDOperand N1,
280 ISD::CondCode Cond, bool foldBooleans = true);
281 SDOperand ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, MVT::ValueType);
282 SDOperand BuildSDIV(SDNode *N);
283 SDOperand BuildUDIV(SDNode *N);
284 SDNode *MatchRotate(SDOperand LHS, SDOperand RHS);
285 SDOperand ReduceLoadWidth(SDNode *N);
286
287 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
288 /// looking for aliasing nodes and adding them to the Aliases vector.
289 void GatherAllAliases(SDNode *N, SDOperand OriginalChain,
290 SmallVector<SDOperand, 8> &Aliases);
291
292 /// isAlias - Return true if there is any possibility that the two addresses
293 /// overlap.
294 bool isAlias(SDOperand Ptr1, int64_t Size1,
295 const Value *SrcValue1, int SrcValueOffset1,
296 SDOperand Ptr2, int64_t Size2,
297 const Value *SrcValue2, int SrcValueOffset2);
298
299 /// FindAliasInfo - Extracts the relevant alias information from the memory
300 /// node. Returns true if the operand was a load.
301 bool FindAliasInfo(SDNode *N,
302 SDOperand &Ptr, int64_t &Size,
303 const Value *&SrcValue, int &SrcValueOffset);
304
305 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
306 /// looking for a better chain (aliasing node.)
307 SDOperand FindBetterChain(SDNode *N, SDOperand Chain);
308
309public:
310 DAGCombiner(SelectionDAG &D, AliasAnalysis &A)
311 : DAG(D),
312 TLI(D.getTargetLoweringInfo()),
313 AfterLegalize(false),
314 AA(A) {}
315
316 /// Run - runs the dag combiner on all nodes in the work list
317 void Run(bool RunningAfterLegalize);
318 };
319}
320
321//===----------------------------------------------------------------------===//
322// TargetLowering::DAGCombinerInfo implementation
323//===----------------------------------------------------------------------===//
324
325void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
326 ((DAGCombiner*)DC)->AddToWorkList(N);
327}
328
329SDOperand TargetLowering::DAGCombinerInfo::
330CombineTo(SDNode *N, const std::vector<SDOperand> &To) {
331 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
332}
333
334SDOperand TargetLowering::DAGCombinerInfo::
335CombineTo(SDNode *N, SDOperand Res) {
336 return ((DAGCombiner*)DC)->CombineTo(N, Res);
337}
338
339
340SDOperand TargetLowering::DAGCombinerInfo::
341CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
342 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
343}
344
345
346//===----------------------------------------------------------------------===//
347// Helper Functions
348//===----------------------------------------------------------------------===//
349
350/// isNegatibleForFree - Return 1 if we can compute the negated form of the
351/// specified expression for the same cost as the expression itself, or 2 if we
352/// can compute the negated form more cheaply than the expression itself.
353static char isNegatibleForFree(SDOperand Op, unsigned Depth = 0) {
354 // fneg is removable even if it has multiple uses.
355 if (Op.getOpcode() == ISD::FNEG) return 2;
356
357 // Don't allow anything with multiple uses.
358 if (!Op.hasOneUse()) return 0;
359
360 // Don't recurse exponentially.
361 if (Depth > 6) return 0;
362
363 switch (Op.getOpcode()) {
364 default: return false;
365 case ISD::ConstantFP:
366 return 1;
367 case ISD::FADD:
368 // FIXME: determine better conditions for this xform.
369 if (!UnsafeFPMath) return 0;
370
371 // -(A+B) -> -A - B
372 if (char V = isNegatibleForFree(Op.getOperand(0), Depth+1))
373 return V;
374 // -(A+B) -> -B - A
375 return isNegatibleForFree(Op.getOperand(1), Depth+1);
376 case ISD::FSUB:
377 // We can't turn -(A-B) into B-A when we honor signed zeros.
378 if (!UnsafeFPMath) return 0;
379
380 // -(A-B) -> B-A
381 return 1;
382
383 case ISD::FMUL:
384 case ISD::FDIV:
385 if (HonorSignDependentRoundingFPMath()) return 0;
386
387 // -(X*Y) -> (-X * Y) or (X*-Y)
388 if (char V = isNegatibleForFree(Op.getOperand(0), Depth+1))
389 return V;
390
391 return isNegatibleForFree(Op.getOperand(1), Depth+1);
392
393 case ISD::FP_EXTEND:
394 case ISD::FP_ROUND:
395 case ISD::FSIN:
396 return isNegatibleForFree(Op.getOperand(0), Depth+1);
397 }
398}
399
400/// GetNegatedExpression - If isNegatibleForFree returns true, this function
401/// returns the newly negated expression.
402static SDOperand GetNegatedExpression(SDOperand Op, SelectionDAG &DAG,
403 unsigned Depth = 0) {
404 // fneg is removable even if it has multiple uses.
405 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
406
407 // Don't allow anything with multiple uses.
408 assert(Op.hasOneUse() && "Unknown reuse!");
409
410 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
411 switch (Op.getOpcode()) {
412 default: assert(0 && "Unknown code");
Dale Johannesen7604c1b2007-08-31 23:34:27 +0000413 case ISD::ConstantFP: {
414 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
415 V.changeSign();
416 return DAG.getConstantFP(V, Op.getValueType());
417 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000418 case ISD::FADD:
419 // FIXME: determine better conditions for this xform.
420 assert(UnsafeFPMath);
421
422 // -(A+B) -> -A - B
423 if (isNegatibleForFree(Op.getOperand(0), Depth+1))
424 return DAG.getNode(ISD::FSUB, Op.getValueType(),
425 GetNegatedExpression(Op.getOperand(0), DAG, Depth+1),
426 Op.getOperand(1));
427 // -(A+B) -> -B - A
428 return DAG.getNode(ISD::FSUB, Op.getValueType(),
429 GetNegatedExpression(Op.getOperand(1), DAG, Depth+1),
430 Op.getOperand(0));
431 case ISD::FSUB:
432 // We can't turn -(A-B) into B-A when we honor signed zeros.
433 assert(UnsafeFPMath);
434
435 // -(0-B) -> B
436 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen7604c1b2007-08-31 23:34:27 +0000437 if (N0CFP->getValueAPF().isZero())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000438 return Op.getOperand(1);
439
440 // -(A-B) -> B-A
441 return DAG.getNode(ISD::FSUB, Op.getValueType(), Op.getOperand(1),
442 Op.getOperand(0));
443
444 case ISD::FMUL:
445 case ISD::FDIV:
446 assert(!HonorSignDependentRoundingFPMath());
447
448 // -(X*Y) -> -X * Y
449 if (isNegatibleForFree(Op.getOperand(0), Depth+1))
450 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
451 GetNegatedExpression(Op.getOperand(0), DAG, Depth+1),
452 Op.getOperand(1));
453
454 // -(X*Y) -> X * -Y
455 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
456 Op.getOperand(0),
457 GetNegatedExpression(Op.getOperand(1), DAG, Depth+1));
458
459 case ISD::FP_EXTEND:
460 case ISD::FP_ROUND:
461 case ISD::FSIN:
462 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
463 GetNegatedExpression(Op.getOperand(0), DAG, Depth+1));
464 }
465}
466
467
468// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
469// that selects between the values 1 and 0, making it equivalent to a setcc.
470// Also, set the incoming LHS, RHS, and CC references to the appropriate
471// nodes based on the type of node we are checking. This simplifies life a
472// bit for the callers.
473static bool isSetCCEquivalent(SDOperand N, SDOperand &LHS, SDOperand &RHS,
474 SDOperand &CC) {
475 if (N.getOpcode() == ISD::SETCC) {
476 LHS = N.getOperand(0);
477 RHS = N.getOperand(1);
478 CC = N.getOperand(2);
479 return true;
480 }
481 if (N.getOpcode() == ISD::SELECT_CC &&
482 N.getOperand(2).getOpcode() == ISD::Constant &&
483 N.getOperand(3).getOpcode() == ISD::Constant &&
484 cast<ConstantSDNode>(N.getOperand(2))->getValue() == 1 &&
485 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
486 LHS = N.getOperand(0);
487 RHS = N.getOperand(1);
488 CC = N.getOperand(4);
489 return true;
490 }
491 return false;
492}
493
494// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
495// one use. If this is true, it allows the users to invert the operation for
496// free when it is profitable to do so.
497static bool isOneUseSetCC(SDOperand N) {
498 SDOperand N0, N1, N2;
499 if (isSetCCEquivalent(N, N0, N1, N2) && N.Val->hasOneUse())
500 return true;
501 return false;
502}
503
504SDOperand DAGCombiner::ReassociateOps(unsigned Opc, SDOperand N0, SDOperand N1){
505 MVT::ValueType VT = N0.getValueType();
506 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
507 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
508 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
509 if (isa<ConstantSDNode>(N1)) {
510 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1);
511 AddToWorkList(OpNode.Val);
512 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0));
513 } else if (N0.hasOneUse()) {
514 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1);
515 AddToWorkList(OpNode.Val);
516 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(1));
517 }
518 }
519 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
520 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
521 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
522 if (isa<ConstantSDNode>(N0)) {
523 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0);
524 AddToWorkList(OpNode.Val);
525 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0));
526 } else if (N1.hasOneUse()) {
527 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0);
528 AddToWorkList(OpNode.Val);
529 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1));
530 }
531 }
532 return SDOperand();
533}
534
535//===----------------------------------------------------------------------===//
536// Main DAG Combiner implementation
537//===----------------------------------------------------------------------===//
538
539void DAGCombiner::Run(bool RunningAfterLegalize) {
540 // set the instance variable, so that the various visit routines may use it.
541 AfterLegalize = RunningAfterLegalize;
542
543 // Add all the dag nodes to the worklist.
544 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
545 E = DAG.allnodes_end(); I != E; ++I)
546 WorkList.push_back(I);
547
548 // Create a dummy node (which is not added to allnodes), that adds a reference
549 // to the root node, preventing it from being deleted, and tracking any
550 // changes of the root.
551 HandleSDNode Dummy(DAG.getRoot());
552
553 // The root of the dag may dangle to deleted nodes until the dag combiner is
554 // done. Set it to null to avoid confusion.
555 DAG.setRoot(SDOperand());
556
557 /// DagCombineInfo - Expose the DAG combiner to the target combiner impls.
558 TargetLowering::DAGCombinerInfo
559 DagCombineInfo(DAG, !RunningAfterLegalize, false, this);
560
561 // while the worklist isn't empty, inspect the node on the end of it and
562 // try and combine it.
563 while (!WorkList.empty()) {
564 SDNode *N = WorkList.back();
565 WorkList.pop_back();
566
567 // If N has no uses, it is dead. Make sure to revisit all N's operands once
568 // N is deleted from the DAG, since they too may now be dead or may have a
569 // reduced number of uses, allowing other xforms.
570 if (N->use_empty() && N != &Dummy) {
571 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
572 AddToWorkList(N->getOperand(i).Val);
573
574 DAG.DeleteNode(N);
575 continue;
576 }
577
578 SDOperand RV = visit(N);
579
580 // If nothing happened, try a target-specific DAG combine.
581 if (RV.Val == 0) {
582 assert(N->getOpcode() != ISD::DELETED_NODE &&
583 "Node was deleted but visit returned NULL!");
584 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
585 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode()))
586 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
587 }
588
589 if (RV.Val) {
590 ++NodesCombined;
591 // If we get back the same node we passed in, rather than a new node or
592 // zero, we know that the node must have defined multiple values and
593 // CombineTo was used. Since CombineTo takes care of the worklist
594 // mechanics for us, we have no work to do in this case.
595 if (RV.Val != N) {
596 assert(N->getOpcode() != ISD::DELETED_NODE &&
597 RV.Val->getOpcode() != ISD::DELETED_NODE &&
598 "Node was deleted but visit returned new node!");
599
600 DOUT << "\nReplacing.3 "; DEBUG(N->dump(&DAG));
601 DOUT << "\nWith: "; DEBUG(RV.Val->dump(&DAG));
602 DOUT << '\n';
603 std::vector<SDNode*> NowDead;
604 if (N->getNumValues() == RV.Val->getNumValues())
605 DAG.ReplaceAllUsesWith(N, RV.Val, &NowDead);
606 else {
607 assert(N->getValueType(0) == RV.getValueType() && "Type mismatch");
608 SDOperand OpV = RV;
609 DAG.ReplaceAllUsesWith(N, &OpV, &NowDead);
610 }
611
612 // Push the new node and any users onto the worklist
613 AddToWorkList(RV.Val);
614 AddUsersToWorkList(RV.Val);
615
616 // Nodes can be reintroduced into the worklist. Make sure we do not
617 // process a node that has been replaced.
618 removeFromWorkList(N);
619 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
620 removeFromWorkList(NowDead[i]);
621
622 // Finally, since the node is now dead, remove it from the graph.
623 DAG.DeleteNode(N);
624 }
625 }
626 }
627
628 // If the root changed (e.g. it was a dead load, update the root).
629 DAG.setRoot(Dummy.getValue());
630}
631
632SDOperand DAGCombiner::visit(SDNode *N) {
633 switch(N->getOpcode()) {
634 default: break;
635 case ISD::TokenFactor: return visitTokenFactor(N);
636 case ISD::ADD: return visitADD(N);
637 case ISD::SUB: return visitSUB(N);
638 case ISD::ADDC: return visitADDC(N);
639 case ISD::ADDE: return visitADDE(N);
640 case ISD::MUL: return visitMUL(N);
641 case ISD::SDIV: return visitSDIV(N);
642 case ISD::UDIV: return visitUDIV(N);
643 case ISD::SREM: return visitSREM(N);
644 case ISD::UREM: return visitUREM(N);
645 case ISD::MULHU: return visitMULHU(N);
646 case ISD::MULHS: return visitMULHS(N);
647 case ISD::AND: return visitAND(N);
648 case ISD::OR: return visitOR(N);
649 case ISD::XOR: return visitXOR(N);
650 case ISD::SHL: return visitSHL(N);
651 case ISD::SRA: return visitSRA(N);
652 case ISD::SRL: return visitSRL(N);
653 case ISD::CTLZ: return visitCTLZ(N);
654 case ISD::CTTZ: return visitCTTZ(N);
655 case ISD::CTPOP: return visitCTPOP(N);
656 case ISD::SELECT: return visitSELECT(N);
657 case ISD::SELECT_CC: return visitSELECT_CC(N);
658 case ISD::SETCC: return visitSETCC(N);
659 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
660 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
661 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
662 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
663 case ISD::TRUNCATE: return visitTRUNCATE(N);
664 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
665 case ISD::FADD: return visitFADD(N);
666 case ISD::FSUB: return visitFSUB(N);
667 case ISD::FMUL: return visitFMUL(N);
668 case ISD::FDIV: return visitFDIV(N);
669 case ISD::FREM: return visitFREM(N);
670 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
671 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
672 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
673 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
674 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
675 case ISD::FP_ROUND: return visitFP_ROUND(N);
676 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
677 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
678 case ISD::FNEG: return visitFNEG(N);
679 case ISD::FABS: return visitFABS(N);
680 case ISD::BRCOND: return visitBRCOND(N);
681 case ISD::BR_CC: return visitBR_CC(N);
682 case ISD::LOAD: return visitLOAD(N);
683 case ISD::STORE: return visitSTORE(N);
684 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
685 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
686 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
687 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
688 }
689 return SDOperand();
690}
691
692/// getInputChainForNode - Given a node, return its input chain if it has one,
693/// otherwise return a null sd operand.
694static SDOperand getInputChainForNode(SDNode *N) {
695 if (unsigned NumOps = N->getNumOperands()) {
696 if (N->getOperand(0).getValueType() == MVT::Other)
697 return N->getOperand(0);
698 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
699 return N->getOperand(NumOps-1);
700 for (unsigned i = 1; i < NumOps-1; ++i)
701 if (N->getOperand(i).getValueType() == MVT::Other)
702 return N->getOperand(i);
703 }
704 return SDOperand(0, 0);
705}
706
707SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
708 // If N has two operands, where one has an input chain equal to the other,
709 // the 'other' chain is redundant.
710 if (N->getNumOperands() == 2) {
711 if (getInputChainForNode(N->getOperand(0).Val) == N->getOperand(1))
712 return N->getOperand(0);
713 if (getInputChainForNode(N->getOperand(1).Val) == N->getOperand(0))
714 return N->getOperand(1);
715 }
716
717 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
718 SmallVector<SDOperand, 8> Ops; // Ops for replacing token factor.
719 SmallPtrSet<SDNode*, 16> SeenOps;
720 bool Changed = false; // If we should replace this token factor.
721
722 // Start out with this token factor.
723 TFs.push_back(N);
724
725 // Iterate through token factors. The TFs grows when new token factors are
726 // encountered.
727 for (unsigned i = 0; i < TFs.size(); ++i) {
728 SDNode *TF = TFs[i];
729
730 // Check each of the operands.
731 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
732 SDOperand Op = TF->getOperand(i);
733
734 switch (Op.getOpcode()) {
735 case ISD::EntryToken:
736 // Entry tokens don't need to be added to the list. They are
737 // rededundant.
738 Changed = true;
739 break;
740
741 case ISD::TokenFactor:
742 if ((CombinerAA || Op.hasOneUse()) &&
743 std::find(TFs.begin(), TFs.end(), Op.Val) == TFs.end()) {
744 // Queue up for processing.
745 TFs.push_back(Op.Val);
746 // Clean up in case the token factor is removed.
747 AddToWorkList(Op.Val);
748 Changed = true;
749 break;
750 }
751 // Fall thru
752
753 default:
754 // Only add if it isn't already in the list.
755 if (SeenOps.insert(Op.Val))
756 Ops.push_back(Op);
757 else
758 Changed = true;
759 break;
760 }
761 }
762 }
763
764 SDOperand Result;
765
766 // If we've change things around then replace token factor.
767 if (Changed) {
768 if (Ops.size() == 0) {
769 // The entry token is the only possible outcome.
770 Result = DAG.getEntryNode();
771 } else {
772 // New and improved token factor.
773 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
774 }
775
776 // Don't add users to work list.
777 return CombineTo(N, Result, false);
778 }
779
780 return Result;
781}
782
783static
784SDOperand combineShlAddConstant(SDOperand N0, SDOperand N1, SelectionDAG &DAG) {
785 MVT::ValueType VT = N0.getValueType();
786 SDOperand N00 = N0.getOperand(0);
787 SDOperand N01 = N0.getOperand(1);
788 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
789 if (N01C && N00.getOpcode() == ISD::ADD && N00.Val->hasOneUse() &&
790 isa<ConstantSDNode>(N00.getOperand(1))) {
791 N0 = DAG.getNode(ISD::ADD, VT,
792 DAG.getNode(ISD::SHL, VT, N00.getOperand(0), N01),
793 DAG.getNode(ISD::SHL, VT, N00.getOperand(1), N01));
794 return DAG.getNode(ISD::ADD, VT, N0, N1);
795 }
796 return SDOperand();
797}
798
799static
800SDOperand combineSelectAndUse(SDNode *N, SDOperand Slct, SDOperand OtherOp,
801 SelectionDAG &DAG) {
802 MVT::ValueType VT = N->getValueType(0);
803 unsigned Opc = N->getOpcode();
804 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
805 SDOperand LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
806 SDOperand RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
807 ISD::CondCode CC = ISD::SETCC_INVALID;
808 if (isSlctCC)
809 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
810 else {
811 SDOperand CCOp = Slct.getOperand(0);
812 if (CCOp.getOpcode() == ISD::SETCC)
813 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
814 }
815
816 bool DoXform = false;
817 bool InvCC = false;
818 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
819 "Bad input!");
820 if (LHS.getOpcode() == ISD::Constant &&
821 cast<ConstantSDNode>(LHS)->isNullValue())
822 DoXform = true;
823 else if (CC != ISD::SETCC_INVALID &&
824 RHS.getOpcode() == ISD::Constant &&
825 cast<ConstantSDNode>(RHS)->isNullValue()) {
826 std::swap(LHS, RHS);
827 bool isInt = MVT::isInteger(isSlctCC ? Slct.getOperand(0).getValueType()
828 : Slct.getOperand(0).getOperand(0).getValueType());
829 CC = ISD::getSetCCInverse(CC, isInt);
830 DoXform = true;
831 InvCC = true;
832 }
833
834 if (DoXform) {
835 SDOperand Result = DAG.getNode(Opc, VT, OtherOp, RHS);
836 if (isSlctCC)
837 return DAG.getSelectCC(OtherOp, Result,
838 Slct.getOperand(0), Slct.getOperand(1), CC);
839 SDOperand CCOp = Slct.getOperand(0);
840 if (InvCC)
841 CCOp = DAG.getSetCC(CCOp.getValueType(), CCOp.getOperand(0),
842 CCOp.getOperand(1), CC);
843 return DAG.getNode(ISD::SELECT, VT, CCOp, OtherOp, Result);
844 }
845 return SDOperand();
846}
847
848SDOperand DAGCombiner::visitADD(SDNode *N) {
849 SDOperand N0 = N->getOperand(0);
850 SDOperand N1 = N->getOperand(1);
851 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
852 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
853 MVT::ValueType VT = N0.getValueType();
854
855 // fold vector ops
856 if (MVT::isVector(VT)) {
857 SDOperand FoldedVOp = SimplifyVBinOp(N);
858 if (FoldedVOp.Val) return FoldedVOp;
859 }
860
861 // fold (add x, undef) -> undef
862 if (N0.getOpcode() == ISD::UNDEF)
863 return N0;
864 if (N1.getOpcode() == ISD::UNDEF)
865 return N1;
866 // fold (add c1, c2) -> c1+c2
867 if (N0C && N1C)
868 return DAG.getNode(ISD::ADD, VT, N0, N1);
869 // canonicalize constant to RHS
870 if (N0C && !N1C)
871 return DAG.getNode(ISD::ADD, VT, N1, N0);
872 // fold (add x, 0) -> x
873 if (N1C && N1C->isNullValue())
874 return N0;
875 // fold ((c1-A)+c2) -> (c1+c2)-A
876 if (N1C && N0.getOpcode() == ISD::SUB)
877 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
878 return DAG.getNode(ISD::SUB, VT,
879 DAG.getConstant(N1C->getValue()+N0C->getValue(), VT),
880 N0.getOperand(1));
881 // reassociate add
882 SDOperand RADD = ReassociateOps(ISD::ADD, N0, N1);
883 if (RADD.Val != 0)
884 return RADD;
885 // fold ((0-A) + B) -> B-A
886 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
887 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
888 return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
889 // fold (A + (0-B)) -> A-B
890 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
891 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
892 return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
893 // fold (A+(B-A)) -> B
894 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
895 return N1.getOperand(0);
896
897 if (!MVT::isVector(VT) && SimplifyDemandedBits(SDOperand(N, 0)))
898 return SDOperand(N, 0);
899
900 // fold (a+b) -> (a|b) iff a and b share no bits.
901 if (MVT::isInteger(VT) && !MVT::isVector(VT)) {
902 uint64_t LHSZero, LHSOne;
903 uint64_t RHSZero, RHSOne;
904 uint64_t Mask = MVT::getIntVTBitMask(VT);
905 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
906 if (LHSZero) {
907 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
908
909 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
910 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
911 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
912 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
913 return DAG.getNode(ISD::OR, VT, N0, N1);
914 }
915 }
916
917 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
918 if (N0.getOpcode() == ISD::SHL && N0.Val->hasOneUse()) {
919 SDOperand Result = combineShlAddConstant(N0, N1, DAG);
920 if (Result.Val) return Result;
921 }
922 if (N1.getOpcode() == ISD::SHL && N1.Val->hasOneUse()) {
923 SDOperand Result = combineShlAddConstant(N1, N0, DAG);
924 if (Result.Val) return Result;
925 }
926
927 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
928 if (N0.getOpcode() == ISD::SELECT && N0.Val->hasOneUse()) {
929 SDOperand Result = combineSelectAndUse(N, N0, N1, DAG);
930 if (Result.Val) return Result;
931 }
932 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
933 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
934 if (Result.Val) return Result;
935 }
936
937 return SDOperand();
938}
939
940SDOperand DAGCombiner::visitADDC(SDNode *N) {
941 SDOperand N0 = N->getOperand(0);
942 SDOperand N1 = N->getOperand(1);
943 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
944 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
945 MVT::ValueType VT = N0.getValueType();
946
947 // If the flag result is dead, turn this into an ADD.
948 if (N->hasNUsesOfValue(0, 1))
949 return CombineTo(N, DAG.getNode(ISD::ADD, VT, N1, N0),
950 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
951
952 // canonicalize constant to RHS.
953 if (N0C && !N1C) {
954 SDOperand Ops[] = { N1, N0 };
955 return DAG.getNode(ISD::ADDC, N->getVTList(), Ops, 2);
956 }
957
958 // fold (addc x, 0) -> x + no carry out
959 if (N1C && N1C->isNullValue())
960 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
961
962 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
963 uint64_t LHSZero, LHSOne;
964 uint64_t RHSZero, RHSOne;
965 uint64_t Mask = MVT::getIntVTBitMask(VT);
966 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
967 if (LHSZero) {
968 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
969
970 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
971 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
972 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
973 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
974 return CombineTo(N, DAG.getNode(ISD::OR, VT, N0, N1),
975 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
976 }
977
978 return SDOperand();
979}
980
981SDOperand DAGCombiner::visitADDE(SDNode *N) {
982 SDOperand N0 = N->getOperand(0);
983 SDOperand N1 = N->getOperand(1);
984 SDOperand CarryIn = N->getOperand(2);
985 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
986 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
987 //MVT::ValueType VT = N0.getValueType();
988
989 // canonicalize constant to RHS
990 if (N0C && !N1C) {
991 SDOperand Ops[] = { N1, N0, CarryIn };
992 return DAG.getNode(ISD::ADDE, N->getVTList(), Ops, 3);
993 }
994
995 // fold (adde x, y, false) -> (addc x, y)
996 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) {
997 SDOperand Ops[] = { N1, N0 };
998 return DAG.getNode(ISD::ADDC, N->getVTList(), Ops, 2);
999 }
1000
1001 return SDOperand();
1002}
1003
1004
1005
1006SDOperand DAGCombiner::visitSUB(SDNode *N) {
1007 SDOperand N0 = N->getOperand(0);
1008 SDOperand N1 = N->getOperand(1);
1009 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1010 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1011 MVT::ValueType VT = N0.getValueType();
1012
1013 // fold vector ops
1014 if (MVT::isVector(VT)) {
1015 SDOperand FoldedVOp = SimplifyVBinOp(N);
1016 if (FoldedVOp.Val) return FoldedVOp;
1017 }
1018
1019 // fold (sub x, x) -> 0
1020 if (N0 == N1)
1021 return DAG.getConstant(0, N->getValueType(0));
1022 // fold (sub c1, c2) -> c1-c2
1023 if (N0C && N1C)
1024 return DAG.getNode(ISD::SUB, VT, N0, N1);
1025 // fold (sub x, c) -> (add x, -c)
1026 if (N1C)
1027 return DAG.getNode(ISD::ADD, VT, N0, DAG.getConstant(-N1C->getValue(), VT));
1028 // fold (A+B)-A -> B
1029 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1030 return N0.getOperand(1);
1031 // fold (A+B)-B -> A
1032 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1033 return N0.getOperand(0);
1034 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
1035 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1036 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1037 if (Result.Val) return Result;
1038 }
1039 // If either operand of a sub is undef, the result is undef
1040 if (N0.getOpcode() == ISD::UNDEF)
1041 return N0;
1042 if (N1.getOpcode() == ISD::UNDEF)
1043 return N1;
1044
1045 return SDOperand();
1046}
1047
1048SDOperand DAGCombiner::visitMUL(SDNode *N) {
1049 SDOperand N0 = N->getOperand(0);
1050 SDOperand N1 = N->getOperand(1);
1051 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1052 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1053 MVT::ValueType VT = N0.getValueType();
1054
1055 // fold vector ops
1056 if (MVT::isVector(VT)) {
1057 SDOperand FoldedVOp = SimplifyVBinOp(N);
1058 if (FoldedVOp.Val) return FoldedVOp;
1059 }
1060
1061 // fold (mul x, undef) -> 0
1062 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1063 return DAG.getConstant(0, VT);
1064 // fold (mul c1, c2) -> c1*c2
1065 if (N0C && N1C)
1066 return DAG.getNode(ISD::MUL, VT, N0, N1);
1067 // canonicalize constant to RHS
1068 if (N0C && !N1C)
1069 return DAG.getNode(ISD::MUL, VT, N1, N0);
1070 // fold (mul x, 0) -> 0
1071 if (N1C && N1C->isNullValue())
1072 return N1;
1073 // fold (mul x, -1) -> 0-x
1074 if (N1C && N1C->isAllOnesValue())
1075 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1076 // fold (mul x, (1 << c)) -> x << c
1077 if (N1C && isPowerOf2_64(N1C->getValue()))
1078 return DAG.getNode(ISD::SHL, VT, N0,
1079 DAG.getConstant(Log2_64(N1C->getValue()),
1080 TLI.getShiftAmountTy()));
1081 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1082 if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
1083 // FIXME: If the input is something that is easily negated (e.g. a
1084 // single-use add), we should put the negate there.
1085 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
1086 DAG.getNode(ISD::SHL, VT, N0,
1087 DAG.getConstant(Log2_64(-N1C->getSignExtended()),
1088 TLI.getShiftAmountTy())));
1089 }
1090
1091 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1092 if (N1C && N0.getOpcode() == ISD::SHL &&
1093 isa<ConstantSDNode>(N0.getOperand(1))) {
1094 SDOperand C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
1095 AddToWorkList(C3.Val);
1096 return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
1097 }
1098
1099 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1100 // use.
1101 {
1102 SDOperand Sh(0,0), Y(0,0);
1103 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1104 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1105 N0.Val->hasOneUse()) {
1106 Sh = N0; Y = N1;
1107 } else if (N1.getOpcode() == ISD::SHL &&
1108 isa<ConstantSDNode>(N1.getOperand(1)) && N1.Val->hasOneUse()) {
1109 Sh = N1; Y = N0;
1110 }
1111 if (Sh.Val) {
1112 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
1113 return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
1114 }
1115 }
1116 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1117 if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
1118 isa<ConstantSDNode>(N0.getOperand(1))) {
1119 return DAG.getNode(ISD::ADD, VT,
1120 DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
1121 DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
1122 }
1123
1124 // reassociate mul
1125 SDOperand RMUL = ReassociateOps(ISD::MUL, N0, N1);
1126 if (RMUL.Val != 0)
1127 return RMUL;
1128
1129 return SDOperand();
1130}
1131
1132SDOperand DAGCombiner::visitSDIV(SDNode *N) {
1133 SDOperand N0 = N->getOperand(0);
1134 SDOperand N1 = N->getOperand(1);
1135 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1136 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1137 MVT::ValueType VT = N->getValueType(0);
1138
1139 // fold vector ops
1140 if (MVT::isVector(VT)) {
1141 SDOperand FoldedVOp = SimplifyVBinOp(N);
1142 if (FoldedVOp.Val) return FoldedVOp;
1143 }
1144
1145 // fold (sdiv c1, c2) -> c1/c2
1146 if (N0C && N1C && !N1C->isNullValue())
1147 return DAG.getNode(ISD::SDIV, VT, N0, N1);
1148 // fold (sdiv X, 1) -> X
1149 if (N1C && N1C->getSignExtended() == 1LL)
1150 return N0;
1151 // fold (sdiv X, -1) -> 0-X
1152 if (N1C && N1C->isAllOnesValue())
1153 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1154 // If we know the sign bits of both operands are zero, strength reduce to a
1155 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1156 uint64_t SignBit = 1ULL << (MVT::getSizeInBits(VT)-1);
1157 if (DAG.MaskedValueIsZero(N1, SignBit) &&
1158 DAG.MaskedValueIsZero(N0, SignBit))
1159 return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
1160 // fold (sdiv X, pow2) -> simple ops after legalize
1161 if (N1C && N1C->getValue() && !TLI.isIntDivCheap() &&
1162 (isPowerOf2_64(N1C->getSignExtended()) ||
1163 isPowerOf2_64(-N1C->getSignExtended()))) {
1164 // If dividing by powers of two is cheap, then don't perform the following
1165 // fold.
1166 if (TLI.isPow2DivCheap())
1167 return SDOperand();
1168 int64_t pow2 = N1C->getSignExtended();
1169 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1170 unsigned lg2 = Log2_64(abs2);
1171 // Splat the sign bit into the register
1172 SDOperand SGN = DAG.getNode(ISD::SRA, VT, N0,
1173 DAG.getConstant(MVT::getSizeInBits(VT)-1,
1174 TLI.getShiftAmountTy()));
1175 AddToWorkList(SGN.Val);
1176 // Add (N0 < 0) ? abs2 - 1 : 0;
1177 SDOperand SRL = DAG.getNode(ISD::SRL, VT, SGN,
1178 DAG.getConstant(MVT::getSizeInBits(VT)-lg2,
1179 TLI.getShiftAmountTy()));
1180 SDOperand ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
1181 AddToWorkList(SRL.Val);
1182 AddToWorkList(ADD.Val); // Divide by pow2
1183 SDOperand SRA = DAG.getNode(ISD::SRA, VT, ADD,
1184 DAG.getConstant(lg2, TLI.getShiftAmountTy()));
1185 // If we're dividing by a positive value, we're done. Otherwise, we must
1186 // negate the result.
1187 if (pow2 > 0)
1188 return SRA;
1189 AddToWorkList(SRA.Val);
1190 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
1191 }
1192 // if integer divide is expensive and we satisfy the requirements, emit an
1193 // alternate sequence.
1194 if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) &&
1195 !TLI.isIntDivCheap()) {
1196 SDOperand Op = BuildSDIV(N);
1197 if (Op.Val) return Op;
1198 }
1199
1200 // undef / X -> 0
1201 if (N0.getOpcode() == ISD::UNDEF)
1202 return DAG.getConstant(0, VT);
1203 // X / undef -> undef
1204 if (N1.getOpcode() == ISD::UNDEF)
1205 return N1;
1206
1207 return SDOperand();
1208}
1209
1210SDOperand DAGCombiner::visitUDIV(SDNode *N) {
1211 SDOperand N0 = N->getOperand(0);
1212 SDOperand N1 = N->getOperand(1);
1213 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1214 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1215 MVT::ValueType VT = N->getValueType(0);
1216
1217 // fold vector ops
1218 if (MVT::isVector(VT)) {
1219 SDOperand FoldedVOp = SimplifyVBinOp(N);
1220 if (FoldedVOp.Val) return FoldedVOp;
1221 }
1222
1223 // fold (udiv c1, c2) -> c1/c2
1224 if (N0C && N1C && !N1C->isNullValue())
1225 return DAG.getNode(ISD::UDIV, VT, N0, N1);
1226 // fold (udiv x, (1 << c)) -> x >>u c
1227 if (N1C && isPowerOf2_64(N1C->getValue()))
1228 return DAG.getNode(ISD::SRL, VT, N0,
1229 DAG.getConstant(Log2_64(N1C->getValue()),
1230 TLI.getShiftAmountTy()));
1231 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1232 if (N1.getOpcode() == ISD::SHL) {
1233 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1234 if (isPowerOf2_64(SHC->getValue())) {
1235 MVT::ValueType ADDVT = N1.getOperand(1).getValueType();
1236 SDOperand Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
1237 DAG.getConstant(Log2_64(SHC->getValue()),
1238 ADDVT));
1239 AddToWorkList(Add.Val);
1240 return DAG.getNode(ISD::SRL, VT, N0, Add);
1241 }
1242 }
1243 }
1244 // fold (udiv x, c) -> alternate
1245 if (N1C && N1C->getValue() && !TLI.isIntDivCheap()) {
1246 SDOperand Op = BuildUDIV(N);
1247 if (Op.Val) return Op;
1248 }
1249
1250 // undef / X -> 0
1251 if (N0.getOpcode() == ISD::UNDEF)
1252 return DAG.getConstant(0, VT);
1253 // X / undef -> undef
1254 if (N1.getOpcode() == ISD::UNDEF)
1255 return N1;
1256
1257 return SDOperand();
1258}
1259
1260SDOperand DAGCombiner::visitSREM(SDNode *N) {
1261 SDOperand N0 = N->getOperand(0);
1262 SDOperand N1 = N->getOperand(1);
1263 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1264 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1265 MVT::ValueType VT = N->getValueType(0);
1266
1267 // fold (srem c1, c2) -> c1%c2
1268 if (N0C && N1C && !N1C->isNullValue())
1269 return DAG.getNode(ISD::SREM, VT, N0, N1);
1270 // If we know the sign bits of both operands are zero, strength reduce to a
1271 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1272 uint64_t SignBit = 1ULL << (MVT::getSizeInBits(VT)-1);
1273 if (DAG.MaskedValueIsZero(N1, SignBit) &&
1274 DAG.MaskedValueIsZero(N0, SignBit))
1275 return DAG.getNode(ISD::UREM, VT, N0, N1);
1276
1277 // Unconditionally lower X%C -> X-X/C*C. This allows the X/C logic to hack on
1278 // the remainder operation.
1279 if (N1C && !N1C->isNullValue()) {
1280 SDOperand Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
1281 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Div, N1);
1282 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1283 AddToWorkList(Div.Val);
1284 AddToWorkList(Mul.Val);
1285 return Sub;
1286 }
1287
1288 // undef % X -> 0
1289 if (N0.getOpcode() == ISD::UNDEF)
1290 return DAG.getConstant(0, VT);
1291 // X % undef -> undef
1292 if (N1.getOpcode() == ISD::UNDEF)
1293 return N1;
1294
1295 return SDOperand();
1296}
1297
1298SDOperand DAGCombiner::visitUREM(SDNode *N) {
1299 SDOperand N0 = N->getOperand(0);
1300 SDOperand N1 = N->getOperand(1);
1301 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1302 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1303 MVT::ValueType VT = N->getValueType(0);
1304
1305 // fold (urem c1, c2) -> c1%c2
1306 if (N0C && N1C && !N1C->isNullValue())
1307 return DAG.getNode(ISD::UREM, VT, N0, N1);
1308 // fold (urem x, pow2) -> (and x, pow2-1)
1309 if (N1C && !N1C->isNullValue() && isPowerOf2_64(N1C->getValue()))
1310 return DAG.getNode(ISD::AND, VT, N0, DAG.getConstant(N1C->getValue()-1,VT));
1311 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1312 if (N1.getOpcode() == ISD::SHL) {
1313 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1314 if (isPowerOf2_64(SHC->getValue())) {
1315 SDOperand Add = DAG.getNode(ISD::ADD, VT, N1,DAG.getConstant(~0ULL,VT));
1316 AddToWorkList(Add.Val);
1317 return DAG.getNode(ISD::AND, VT, N0, Add);
1318 }
1319 }
1320 }
1321
1322 // Unconditionally lower X%C -> X-X/C*C. This allows the X/C logic to hack on
1323 // the remainder operation.
1324 if (N1C && !N1C->isNullValue()) {
1325 SDOperand Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
1326 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Div, N1);
1327 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1328 AddToWorkList(Div.Val);
1329 AddToWorkList(Mul.Val);
1330 return Sub;
1331 }
1332
1333 // undef % X -> 0
1334 if (N0.getOpcode() == ISD::UNDEF)
1335 return DAG.getConstant(0, VT);
1336 // X % undef -> undef
1337 if (N1.getOpcode() == ISD::UNDEF)
1338 return N1;
1339
1340 return SDOperand();
1341}
1342
1343SDOperand DAGCombiner::visitMULHS(SDNode *N) {
1344 SDOperand N0 = N->getOperand(0);
1345 SDOperand N1 = N->getOperand(1);
1346 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1347 MVT::ValueType VT = N->getValueType(0);
1348
1349 // fold (mulhs x, 0) -> 0
1350 if (N1C && N1C->isNullValue())
1351 return N1;
1352 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1353 if (N1C && N1C->getValue() == 1)
1354 return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
1355 DAG.getConstant(MVT::getSizeInBits(N0.getValueType())-1,
1356 TLI.getShiftAmountTy()));
1357 // fold (mulhs x, undef) -> 0
1358 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1359 return DAG.getConstant(0, VT);
1360
1361 return SDOperand();
1362}
1363
1364SDOperand DAGCombiner::visitMULHU(SDNode *N) {
1365 SDOperand N0 = N->getOperand(0);
1366 SDOperand N1 = N->getOperand(1);
1367 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1368 MVT::ValueType VT = N->getValueType(0);
1369
1370 // fold (mulhu x, 0) -> 0
1371 if (N1C && N1C->isNullValue())
1372 return N1;
1373 // fold (mulhu x, 1) -> 0
1374 if (N1C && N1C->getValue() == 1)
1375 return DAG.getConstant(0, N0.getValueType());
1376 // fold (mulhu x, undef) -> 0
1377 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1378 return DAG.getConstant(0, VT);
1379
1380 return SDOperand();
1381}
1382
1383/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1384/// two operands of the same opcode, try to simplify it.
1385SDOperand DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1386 SDOperand N0 = N->getOperand(0), N1 = N->getOperand(1);
1387 MVT::ValueType VT = N0.getValueType();
1388 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1389
1390 // For each of OP in AND/OR/XOR:
1391 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1392 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1393 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1394 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1395 if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1396 N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
1397 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1398 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1399 N0.getOperand(0).getValueType(),
1400 N0.getOperand(0), N1.getOperand(0));
1401 AddToWorkList(ORNode.Val);
1402 return DAG.getNode(N0.getOpcode(), VT, ORNode);
1403 }
1404
1405 // For each of OP in SHL/SRL/SRA/AND...
1406 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1407 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1408 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1409 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1410 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1411 N0.getOperand(1) == N1.getOperand(1)) {
1412 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1413 N0.getOperand(0).getValueType(),
1414 N0.getOperand(0), N1.getOperand(0));
1415 AddToWorkList(ORNode.Val);
1416 return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
1417 }
1418
1419 return SDOperand();
1420}
1421
1422SDOperand DAGCombiner::visitAND(SDNode *N) {
1423 SDOperand N0 = N->getOperand(0);
1424 SDOperand N1 = N->getOperand(1);
1425 SDOperand LL, LR, RL, RR, CC0, CC1;
1426 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1427 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1428 MVT::ValueType VT = N1.getValueType();
1429
1430 // fold vector ops
1431 if (MVT::isVector(VT)) {
1432 SDOperand FoldedVOp = SimplifyVBinOp(N);
1433 if (FoldedVOp.Val) return FoldedVOp;
1434 }
1435
1436 // fold (and x, undef) -> 0
1437 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1438 return DAG.getConstant(0, VT);
1439 // fold (and c1, c2) -> c1&c2
1440 if (N0C && N1C)
1441 return DAG.getNode(ISD::AND, VT, N0, N1);
1442 // canonicalize constant to RHS
1443 if (N0C && !N1C)
1444 return DAG.getNode(ISD::AND, VT, N1, N0);
1445 // fold (and x, -1) -> x
1446 if (N1C && N1C->isAllOnesValue())
1447 return N0;
1448 // if (and x, c) is known to be zero, return 0
1449 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
1450 return DAG.getConstant(0, VT);
1451 // reassociate and
1452 SDOperand RAND = ReassociateOps(ISD::AND, N0, N1);
1453 if (RAND.Val != 0)
1454 return RAND;
1455 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1456 if (N1C && N0.getOpcode() == ISD::OR)
1457 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1458 if ((ORI->getValue() & N1C->getValue()) == N1C->getValue())
1459 return N1;
1460 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1461 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1462 unsigned InMask = MVT::getIntVTBitMask(N0.getOperand(0).getValueType());
1463 if (DAG.MaskedValueIsZero(N0.getOperand(0),
1464 ~N1C->getValue() & InMask)) {
1465 SDOperand Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
1466 N0.getOperand(0));
1467
1468 // Replace uses of the AND with uses of the Zero extend node.
1469 CombineTo(N, Zext);
1470
1471 // We actually want to replace all uses of the any_extend with the
1472 // zero_extend, to avoid duplicating things. This will later cause this
1473 // AND to be folded.
1474 CombineTo(N0.Val, Zext);
1475 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1476 }
1477 }
1478 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1479 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1480 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1481 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1482
1483 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1484 MVT::isInteger(LL.getValueType())) {
1485 // fold (X == 0) & (Y == 0) -> (X|Y == 0)
1486 if (cast<ConstantSDNode>(LR)->getValue() == 0 && Op1 == ISD::SETEQ) {
1487 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1488 AddToWorkList(ORNode.Val);
1489 return DAG.getSetCC(VT, ORNode, LR, Op1);
1490 }
1491 // fold (X == -1) & (Y == -1) -> (X&Y == -1)
1492 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1493 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1494 AddToWorkList(ANDNode.Val);
1495 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1496 }
1497 // fold (X > -1) & (Y > -1) -> (X|Y > -1)
1498 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1499 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1500 AddToWorkList(ORNode.Val);
1501 return DAG.getSetCC(VT, ORNode, LR, Op1);
1502 }
1503 }
1504 // canonicalize equivalent to ll == rl
1505 if (LL == RR && LR == RL) {
1506 Op1 = ISD::getSetCCSwappedOperands(Op1);
1507 std::swap(RL, RR);
1508 }
1509 if (LL == RL && LR == RR) {
1510 bool isInteger = MVT::isInteger(LL.getValueType());
1511 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1512 if (Result != ISD::SETCC_INVALID)
1513 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1514 }
1515 }
1516
1517 // Simplify: and (op x...), (op y...) -> (op (and x, y))
1518 if (N0.getOpcode() == N1.getOpcode()) {
1519 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1520 if (Tmp.Val) return Tmp;
1521 }
1522
1523 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1524 // fold (and (sra)) -> (and (srl)) when possible.
1525 if (!MVT::isVector(VT) &&
1526 SimplifyDemandedBits(SDOperand(N, 0)))
1527 return SDOperand(N, 0);
1528 // fold (zext_inreg (extload x)) -> (zextload x)
1529 if (ISD::isEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val)) {
1530 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1531 MVT::ValueType EVT = LN0->getLoadedVT();
1532 // If we zero all the possible extended bits, then we can turn this into
1533 // a zextload if we are running before legalize or the operation is legal.
1534 if (DAG.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
1535 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1536 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1537 LN0->getBasePtr(), LN0->getSrcValue(),
1538 LN0->getSrcValueOffset(), EVT,
1539 LN0->isVolatile(),
1540 LN0->getAlignment());
1541 AddToWorkList(N);
1542 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1543 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1544 }
1545 }
1546 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1547 if (ISD::isSEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
1548 N0.hasOneUse()) {
1549 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1550 MVT::ValueType EVT = LN0->getLoadedVT();
1551 // If we zero all the possible extended bits, then we can turn this into
1552 // a zextload if we are running before legalize or the operation is legal.
1553 if (DAG.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
1554 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1555 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1556 LN0->getBasePtr(), LN0->getSrcValue(),
1557 LN0->getSrcValueOffset(), EVT,
1558 LN0->isVolatile(),
1559 LN0->getAlignment());
1560 AddToWorkList(N);
1561 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1562 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1563 }
1564 }
1565
1566 // fold (and (load x), 255) -> (zextload x, i8)
1567 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1568 if (N1C && N0.getOpcode() == ISD::LOAD) {
1569 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1570 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
1571 LN0->getAddressingMode() == ISD::UNINDEXED &&
1572 N0.hasOneUse()) {
1573 MVT::ValueType EVT, LoadedVT;
1574 if (N1C->getValue() == 255)
1575 EVT = MVT::i8;
1576 else if (N1C->getValue() == 65535)
1577 EVT = MVT::i16;
1578 else if (N1C->getValue() == ~0U)
1579 EVT = MVT::i32;
1580 else
1581 EVT = MVT::Other;
1582
1583 LoadedVT = LN0->getLoadedVT();
1584 if (EVT != MVT::Other && LoadedVT > EVT &&
1585 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1586 MVT::ValueType PtrType = N0.getOperand(1).getValueType();
1587 // For big endian targets, we need to add an offset to the pointer to
1588 // load the correct bytes. For little endian systems, we merely need to
1589 // read fewer bytes from the same pointer.
1590 unsigned PtrOff =
1591 (MVT::getSizeInBits(LoadedVT) - MVT::getSizeInBits(EVT)) / 8;
1592 SDOperand NewPtr = LN0->getBasePtr();
1593 if (!TLI.isLittleEndian())
1594 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1595 DAG.getConstant(PtrOff, PtrType));
1596 AddToWorkList(NewPtr.Val);
1597 SDOperand Load =
1598 DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
1599 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
1600 LN0->isVolatile(), LN0->getAlignment());
1601 AddToWorkList(N);
1602 CombineTo(N0.Val, Load, Load.getValue(1));
1603 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1604 }
1605 }
1606 }
1607
1608 return SDOperand();
1609}
1610
1611SDOperand DAGCombiner::visitOR(SDNode *N) {
1612 SDOperand N0 = N->getOperand(0);
1613 SDOperand N1 = N->getOperand(1);
1614 SDOperand LL, LR, RL, RR, CC0, CC1;
1615 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1616 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1617 MVT::ValueType VT = N1.getValueType();
1618 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1619
1620 // fold vector ops
1621 if (MVT::isVector(VT)) {
1622 SDOperand FoldedVOp = SimplifyVBinOp(N);
1623 if (FoldedVOp.Val) return FoldedVOp;
1624 }
1625
1626 // fold (or x, undef) -> -1
1627 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1628 return DAG.getConstant(~0ULL, VT);
1629 // fold (or c1, c2) -> c1|c2
1630 if (N0C && N1C)
1631 return DAG.getNode(ISD::OR, VT, N0, N1);
1632 // canonicalize constant to RHS
1633 if (N0C && !N1C)
1634 return DAG.getNode(ISD::OR, VT, N1, N0);
1635 // fold (or x, 0) -> x
1636 if (N1C && N1C->isNullValue())
1637 return N0;
1638 // fold (or x, -1) -> -1
1639 if (N1C && N1C->isAllOnesValue())
1640 return N1;
1641 // fold (or x, c) -> c iff (x & ~c) == 0
1642 if (N1C &&
1643 DAG.MaskedValueIsZero(N0,~N1C->getValue() & (~0ULL>>(64-OpSizeInBits))))
1644 return N1;
1645 // reassociate or
1646 SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
1647 if (ROR.Val != 0)
1648 return ROR;
1649 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1650 if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1651 isa<ConstantSDNode>(N0.getOperand(1))) {
1652 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1653 return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1654 N1),
1655 DAG.getConstant(N1C->getValue() | C1->getValue(), VT));
1656 }
1657 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1658 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1659 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1660 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1661
1662 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1663 MVT::isInteger(LL.getValueType())) {
1664 // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1665 // fold (X < 0) | (Y < 0) -> (X|Y < 0)
1666 if (cast<ConstantSDNode>(LR)->getValue() == 0 &&
1667 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1668 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1669 AddToWorkList(ORNode.Val);
1670 return DAG.getSetCC(VT, ORNode, LR, Op1);
1671 }
1672 // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1673 // fold (X > -1) | (Y > -1) -> (X&Y > -1)
1674 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1675 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1676 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1677 AddToWorkList(ANDNode.Val);
1678 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1679 }
1680 }
1681 // canonicalize equivalent to ll == rl
1682 if (LL == RR && LR == RL) {
1683 Op1 = ISD::getSetCCSwappedOperands(Op1);
1684 std::swap(RL, RR);
1685 }
1686 if (LL == RL && LR == RR) {
1687 bool isInteger = MVT::isInteger(LL.getValueType());
1688 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1689 if (Result != ISD::SETCC_INVALID)
1690 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1691 }
1692 }
1693
1694 // Simplify: or (op x...), (op y...) -> (op (or x, y))
1695 if (N0.getOpcode() == N1.getOpcode()) {
1696 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1697 if (Tmp.Val) return Tmp;
1698 }
1699
1700 // (X & C1) | (Y & C2) -> (X|Y) & C3 if possible.
1701 if (N0.getOpcode() == ISD::AND &&
1702 N1.getOpcode() == ISD::AND &&
1703 N0.getOperand(1).getOpcode() == ISD::Constant &&
1704 N1.getOperand(1).getOpcode() == ISD::Constant &&
1705 // Don't increase # computations.
1706 (N0.Val->hasOneUse() || N1.Val->hasOneUse())) {
1707 // We can only do this xform if we know that bits from X that are set in C2
1708 // but not in C1 are already zero. Likewise for Y.
1709 uint64_t LHSMask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1710 uint64_t RHSMask = cast<ConstantSDNode>(N1.getOperand(1))->getValue();
1711
1712 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
1713 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
1714 SDOperand X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
1715 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
1716 }
1717 }
1718
1719
1720 // See if this is some rotate idiom.
1721 if (SDNode *Rot = MatchRotate(N0, N1))
1722 return SDOperand(Rot, 0);
1723
1724 return SDOperand();
1725}
1726
1727
1728/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
1729static bool MatchRotateHalf(SDOperand Op, SDOperand &Shift, SDOperand &Mask) {
1730 if (Op.getOpcode() == ISD::AND) {
1731 if (isa<ConstantSDNode>(Op.getOperand(1))) {
1732 Mask = Op.getOperand(1);
1733 Op = Op.getOperand(0);
1734 } else {
1735 return false;
1736 }
1737 }
1738
1739 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
1740 Shift = Op;
1741 return true;
1742 }
1743 return false;
1744}
1745
1746
1747// MatchRotate - Handle an 'or' of two operands. If this is one of the many
1748// idioms for rotate, and if the target supports rotation instructions, generate
1749// a rot[lr].
1750SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
1751 // Must be a legal type. Expanded an promoted things won't work with rotates.
1752 MVT::ValueType VT = LHS.getValueType();
1753 if (!TLI.isTypeLegal(VT)) return 0;
1754
1755 // The target must have at least one rotate flavor.
1756 bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
1757 bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
1758 if (!HasROTL && !HasROTR) return 0;
1759
1760 // Match "(X shl/srl V1) & V2" where V2 may not be present.
1761 SDOperand LHSShift; // The shift.
1762 SDOperand LHSMask; // AND value if any.
1763 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
1764 return 0; // Not part of a rotate.
1765
1766 SDOperand RHSShift; // The shift.
1767 SDOperand RHSMask; // AND value if any.
1768 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
1769 return 0; // Not part of a rotate.
1770
1771 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
1772 return 0; // Not shifting the same value.
1773
1774 if (LHSShift.getOpcode() == RHSShift.getOpcode())
1775 return 0; // Shifts must disagree.
1776
1777 // Canonicalize shl to left side in a shl/srl pair.
1778 if (RHSShift.getOpcode() == ISD::SHL) {
1779 std::swap(LHS, RHS);
1780 std::swap(LHSShift, RHSShift);
1781 std::swap(LHSMask , RHSMask );
1782 }
1783
1784 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1785 SDOperand LHSShiftArg = LHSShift.getOperand(0);
1786 SDOperand LHSShiftAmt = LHSShift.getOperand(1);
1787 SDOperand RHSShiftAmt = RHSShift.getOperand(1);
1788
1789 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
1790 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
1791 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
1792 RHSShiftAmt.getOpcode() == ISD::Constant) {
1793 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getValue();
1794 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getValue();
1795 if ((LShVal + RShVal) != OpSizeInBits)
1796 return 0;
1797
1798 SDOperand Rot;
1799 if (HasROTL)
1800 Rot = DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt);
1801 else
1802 Rot = DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt);
1803
1804 // If there is an AND of either shifted operand, apply it to the result.
1805 if (LHSMask.Val || RHSMask.Val) {
1806 uint64_t Mask = MVT::getIntVTBitMask(VT);
1807
1808 if (LHSMask.Val) {
1809 uint64_t RHSBits = (1ULL << LShVal)-1;
1810 Mask &= cast<ConstantSDNode>(LHSMask)->getValue() | RHSBits;
1811 }
1812 if (RHSMask.Val) {
1813 uint64_t LHSBits = ~((1ULL << (OpSizeInBits-RShVal))-1);
1814 Mask &= cast<ConstantSDNode>(RHSMask)->getValue() | LHSBits;
1815 }
1816
1817 Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
1818 }
1819
1820 return Rot.Val;
1821 }
1822
1823 // If there is a mask here, and we have a variable shift, we can't be sure
1824 // that we're masking out the right stuff.
1825 if (LHSMask.Val || RHSMask.Val)
1826 return 0;
1827
1828 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
1829 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
1830 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
1831 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
1832 if (ConstantSDNode *SUBC =
1833 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
1834 if (SUBC->getValue() == OpSizeInBits)
1835 if (HasROTL)
1836 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
1837 else
1838 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
1839 }
1840 }
1841
1842 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
1843 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
1844 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
1845 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
1846 if (ConstantSDNode *SUBC =
1847 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
1848 if (SUBC->getValue() == OpSizeInBits)
1849 if (HasROTL)
1850 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
1851 else
1852 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
1853 }
1854 }
1855
1856 // Look for sign/zext/any-extended cases:
1857 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
1858 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
1859 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND) &&
1860 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
1861 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
1862 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND)) {
1863 SDOperand LExtOp0 = LHSShiftAmt.getOperand(0);
1864 SDOperand RExtOp0 = RHSShiftAmt.getOperand(0);
1865 if (RExtOp0.getOpcode() == ISD::SUB &&
1866 RExtOp0.getOperand(1) == LExtOp0) {
1867 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
1868 // (rotr x, y)
1869 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
1870 // (rotl x, (sub 32, y))
1871 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
1872 if (SUBC->getValue() == OpSizeInBits) {
1873 if (HasROTL)
1874 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
1875 else
1876 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
1877 }
1878 }
1879 } else if (LExtOp0.getOpcode() == ISD::SUB &&
1880 RExtOp0 == LExtOp0.getOperand(1)) {
1881 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
1882 // (rotl x, y)
1883 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
1884 // (rotr x, (sub 32, y))
1885 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
1886 if (SUBC->getValue() == OpSizeInBits) {
1887 if (HasROTL)
1888 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, RHSShiftAmt).Val;
1889 else
1890 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
1891 }
1892 }
1893 }
1894 }
1895
1896 return 0;
1897}
1898
1899
1900SDOperand DAGCombiner::visitXOR(SDNode *N) {
1901 SDOperand N0 = N->getOperand(0);
1902 SDOperand N1 = N->getOperand(1);
1903 SDOperand LHS, RHS, CC;
1904 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1905 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1906 MVT::ValueType VT = N0.getValueType();
1907
1908 // fold vector ops
1909 if (MVT::isVector(VT)) {
1910 SDOperand FoldedVOp = SimplifyVBinOp(N);
1911 if (FoldedVOp.Val) return FoldedVOp;
1912 }
1913
1914 // fold (xor x, undef) -> undef
1915 if (N0.getOpcode() == ISD::UNDEF)
1916 return N0;
1917 if (N1.getOpcode() == ISD::UNDEF)
1918 return N1;
1919 // fold (xor c1, c2) -> c1^c2
1920 if (N0C && N1C)
1921 return DAG.getNode(ISD::XOR, VT, N0, N1);
1922 // canonicalize constant to RHS
1923 if (N0C && !N1C)
1924 return DAG.getNode(ISD::XOR, VT, N1, N0);
1925 // fold (xor x, 0) -> x
1926 if (N1C && N1C->isNullValue())
1927 return N0;
1928 // reassociate xor
1929 SDOperand RXOR = ReassociateOps(ISD::XOR, N0, N1);
1930 if (RXOR.Val != 0)
1931 return RXOR;
1932 // fold !(x cc y) -> (x !cc y)
1933 if (N1C && N1C->getValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
1934 bool isInt = MVT::isInteger(LHS.getValueType());
1935 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
1936 isInt);
1937 if (N0.getOpcode() == ISD::SETCC)
1938 return DAG.getSetCC(VT, LHS, RHS, NotCC);
1939 if (N0.getOpcode() == ISD::SELECT_CC)
1940 return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
1941 assert(0 && "Unhandled SetCC Equivalent!");
1942 abort();
1943 }
1944 // fold !(x or y) -> (!x and !y) iff x or y are setcc
1945 if (N1C && N1C->getValue() == 1 && VT == MVT::i1 &&
1946 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
1947 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
1948 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
1949 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
1950 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
1951 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
1952 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
1953 return DAG.getNode(NewOpcode, VT, LHS, RHS);
1954 }
1955 }
1956 // fold !(x or y) -> (!x and !y) iff x or y are constants
1957 if (N1C && N1C->isAllOnesValue() &&
1958 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
1959 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
1960 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
1961 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
1962 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
1963 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
1964 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
1965 return DAG.getNode(NewOpcode, VT, LHS, RHS);
1966 }
1967 }
1968 // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
1969 if (N1C && N0.getOpcode() == ISD::XOR) {
1970 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
1971 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1972 if (N00C)
1973 return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
1974 DAG.getConstant(N1C->getValue()^N00C->getValue(), VT));
1975 if (N01C)
1976 return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
1977 DAG.getConstant(N1C->getValue()^N01C->getValue(), VT));
1978 }
1979 // fold (xor x, x) -> 0
1980 if (N0 == N1) {
1981 if (!MVT::isVector(VT)) {
1982 return DAG.getConstant(0, VT);
1983 } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1984 // Produce a vector of zeros.
1985 SDOperand El = DAG.getConstant(0, MVT::getVectorElementType(VT));
1986 std::vector<SDOperand> Ops(MVT::getVectorNumElements(VT), El);
1987 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1988 }
1989 }
1990
1991 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
1992 if (N0.getOpcode() == N1.getOpcode()) {
1993 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1994 if (Tmp.Val) return Tmp;
1995 }
1996
1997 // Simplify the expression using non-local knowledge.
1998 if (!MVT::isVector(VT) &&
1999 SimplifyDemandedBits(SDOperand(N, 0)))
2000 return SDOperand(N, 0);
2001
2002 return SDOperand();
2003}
2004
2005SDOperand DAGCombiner::visitSHL(SDNode *N) {
2006 SDOperand N0 = N->getOperand(0);
2007 SDOperand N1 = N->getOperand(1);
2008 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2009 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2010 MVT::ValueType VT = N0.getValueType();
2011 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
2012
2013 // fold (shl c1, c2) -> c1<<c2
2014 if (N0C && N1C)
2015 return DAG.getNode(ISD::SHL, VT, N0, N1);
2016 // fold (shl 0, x) -> 0
2017 if (N0C && N0C->isNullValue())
2018 return N0;
2019 // fold (shl x, c >= size(x)) -> undef
2020 if (N1C && N1C->getValue() >= OpSizeInBits)
2021 return DAG.getNode(ISD::UNDEF, VT);
2022 // fold (shl x, 0) -> x
2023 if (N1C && N1C->isNullValue())
2024 return N0;
2025 // if (shl x, c) is known to be zero, return 0
2026 if (DAG.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
2027 return DAG.getConstant(0, VT);
2028 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2029 return SDOperand(N, 0);
2030 // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
2031 if (N1C && N0.getOpcode() == ISD::SHL &&
2032 N0.getOperand(1).getOpcode() == ISD::Constant) {
2033 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2034 uint64_t c2 = N1C->getValue();
2035 if (c1 + c2 > OpSizeInBits)
2036 return DAG.getConstant(0, VT);
2037 return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
2038 DAG.getConstant(c1 + c2, N1.getValueType()));
2039 }
2040 // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
2041 // (srl (and x, -1 << c1), c1-c2)
2042 if (N1C && N0.getOpcode() == ISD::SRL &&
2043 N0.getOperand(1).getOpcode() == ISD::Constant) {
2044 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2045 uint64_t c2 = N1C->getValue();
2046 SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2047 DAG.getConstant(~0ULL << c1, VT));
2048 if (c2 > c1)
2049 return DAG.getNode(ISD::SHL, VT, Mask,
2050 DAG.getConstant(c2-c1, N1.getValueType()));
2051 else
2052 return DAG.getNode(ISD::SRL, VT, Mask,
2053 DAG.getConstant(c1-c2, N1.getValueType()));
2054 }
2055 // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
2056 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
2057 return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2058 DAG.getConstant(~0ULL << N1C->getValue(), VT));
2059 return SDOperand();
2060}
2061
2062SDOperand DAGCombiner::visitSRA(SDNode *N) {
2063 SDOperand N0 = N->getOperand(0);
2064 SDOperand N1 = N->getOperand(1);
2065 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2066 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2067 MVT::ValueType VT = N0.getValueType();
2068
2069 // fold (sra c1, c2) -> c1>>c2
2070 if (N0C && N1C)
2071 return DAG.getNode(ISD::SRA, VT, N0, N1);
2072 // fold (sra 0, x) -> 0
2073 if (N0C && N0C->isNullValue())
2074 return N0;
2075 // fold (sra -1, x) -> -1
2076 if (N0C && N0C->isAllOnesValue())
2077 return N0;
2078 // fold (sra x, c >= size(x)) -> undef
2079 if (N1C && N1C->getValue() >= MVT::getSizeInBits(VT))
2080 return DAG.getNode(ISD::UNDEF, VT);
2081 // fold (sra x, 0) -> x
2082 if (N1C && N1C->isNullValue())
2083 return N0;
2084 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2085 // sext_inreg.
2086 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2087 unsigned LowBits = MVT::getSizeInBits(VT) - (unsigned)N1C->getValue();
2088 MVT::ValueType EVT;
2089 switch (LowBits) {
2090 default: EVT = MVT::Other; break;
2091 case 1: EVT = MVT::i1; break;
2092 case 8: EVT = MVT::i8; break;
2093 case 16: EVT = MVT::i16; break;
2094 case 32: EVT = MVT::i32; break;
2095 }
2096 if (EVT > MVT::Other && TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT))
2097 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
2098 DAG.getValueType(EVT));
2099 }
2100
2101 // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
2102 if (N1C && N0.getOpcode() == ISD::SRA) {
2103 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2104 unsigned Sum = N1C->getValue() + C1->getValue();
2105 if (Sum >= MVT::getSizeInBits(VT)) Sum = MVT::getSizeInBits(VT)-1;
2106 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
2107 DAG.getConstant(Sum, N1C->getValueType(0)));
2108 }
2109 }
2110
2111 // Simplify, based on bits shifted out of the LHS.
2112 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2113 return SDOperand(N, 0);
2114
2115
2116 // If the sign bit is known to be zero, switch this to a SRL.
2117 if (DAG.MaskedValueIsZero(N0, MVT::getIntVTSignBit(VT)))
2118 return DAG.getNode(ISD::SRL, VT, N0, N1);
2119 return SDOperand();
2120}
2121
2122SDOperand DAGCombiner::visitSRL(SDNode *N) {
2123 SDOperand N0 = N->getOperand(0);
2124 SDOperand N1 = N->getOperand(1);
2125 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2126 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2127 MVT::ValueType VT = N0.getValueType();
2128 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
2129
2130 // fold (srl c1, c2) -> c1 >>u c2
2131 if (N0C && N1C)
2132 return DAG.getNode(ISD::SRL, VT, N0, N1);
2133 // fold (srl 0, x) -> 0
2134 if (N0C && N0C->isNullValue())
2135 return N0;
2136 // fold (srl x, c >= size(x)) -> undef
2137 if (N1C && N1C->getValue() >= OpSizeInBits)
2138 return DAG.getNode(ISD::UNDEF, VT);
2139 // fold (srl x, 0) -> x
2140 if (N1C && N1C->isNullValue())
2141 return N0;
2142 // if (srl x, c) is known to be zero, return 0
2143 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0), ~0ULL >> (64-OpSizeInBits)))
2144 return DAG.getConstant(0, VT);
2145
2146 // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
2147 if (N1C && N0.getOpcode() == ISD::SRL &&
2148 N0.getOperand(1).getOpcode() == ISD::Constant) {
2149 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2150 uint64_t c2 = N1C->getValue();
2151 if (c1 + c2 > OpSizeInBits)
2152 return DAG.getConstant(0, VT);
2153 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
2154 DAG.getConstant(c1 + c2, N1.getValueType()));
2155 }
2156
2157 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2158 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2159 // Shifting in all undef bits?
2160 MVT::ValueType SmallVT = N0.getOperand(0).getValueType();
2161 if (N1C->getValue() >= MVT::getSizeInBits(SmallVT))
2162 return DAG.getNode(ISD::UNDEF, VT);
2163
2164 SDOperand SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
2165 AddToWorkList(SmallShift.Val);
2166 return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
2167 }
2168
2169 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
2170 // bit, which is unmodified by sra.
2171 if (N1C && N1C->getValue()+1 == MVT::getSizeInBits(VT)) {
2172 if (N0.getOpcode() == ISD::SRA)
2173 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1);
2174 }
2175
2176 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
2177 if (N1C && N0.getOpcode() == ISD::CTLZ &&
2178 N1C->getValue() == Log2_32(MVT::getSizeInBits(VT))) {
2179 uint64_t KnownZero, KnownOne, Mask = MVT::getIntVTBitMask(VT);
2180 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2181
2182 // If any of the input bits are KnownOne, then the input couldn't be all
2183 // zeros, thus the result of the srl will always be zero.
2184 if (KnownOne) return DAG.getConstant(0, VT);
2185
2186 // If all of the bits input the to ctlz node are known to be zero, then
2187 // the result of the ctlz is "32" and the result of the shift is one.
2188 uint64_t UnknownBits = ~KnownZero & Mask;
2189 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2190
2191 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2192 if ((UnknownBits & (UnknownBits-1)) == 0) {
2193 // Okay, we know that only that the single bit specified by UnknownBits
2194 // could be set on input to the CTLZ node. If this bit is set, the SRL
2195 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2196 // to an SRL,XOR pair, which is likely to simplify more.
2197 unsigned ShAmt = CountTrailingZeros_64(UnknownBits);
2198 SDOperand Op = N0.getOperand(0);
2199 if (ShAmt) {
2200 Op = DAG.getNode(ISD::SRL, VT, Op,
2201 DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
2202 AddToWorkList(Op.Val);
2203 }
2204 return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
2205 }
2206 }
2207
2208 // fold operands of srl based on knowledge that the low bits are not
2209 // demanded.
2210 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2211 return SDOperand(N, 0);
2212
2213 return SDOperand();
2214}
2215
2216SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
2217 SDOperand N0 = N->getOperand(0);
2218 MVT::ValueType VT = N->getValueType(0);
2219
2220 // fold (ctlz c1) -> c2
2221 if (isa<ConstantSDNode>(N0))
2222 return DAG.getNode(ISD::CTLZ, VT, N0);
2223 return SDOperand();
2224}
2225
2226SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
2227 SDOperand N0 = N->getOperand(0);
2228 MVT::ValueType VT = N->getValueType(0);
2229
2230 // fold (cttz c1) -> c2
2231 if (isa<ConstantSDNode>(N0))
2232 return DAG.getNode(ISD::CTTZ, VT, N0);
2233 return SDOperand();
2234}
2235
2236SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
2237 SDOperand N0 = N->getOperand(0);
2238 MVT::ValueType VT = N->getValueType(0);
2239
2240 // fold (ctpop c1) -> c2
2241 if (isa<ConstantSDNode>(N0))
2242 return DAG.getNode(ISD::CTPOP, VT, N0);
2243 return SDOperand();
2244}
2245
2246SDOperand DAGCombiner::visitSELECT(SDNode *N) {
2247 SDOperand N0 = N->getOperand(0);
2248 SDOperand N1 = N->getOperand(1);
2249 SDOperand N2 = N->getOperand(2);
2250 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2251 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2252 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2253 MVT::ValueType VT = N->getValueType(0);
Evan Chengff601dc2007-08-18 05:57:05 +00002254 MVT::ValueType VT0 = N0.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002255
2256 // fold select C, X, X -> X
2257 if (N1 == N2)
2258 return N1;
2259 // fold select true, X, Y -> X
2260 if (N0C && !N0C->isNullValue())
2261 return N1;
2262 // fold select false, X, Y -> Y
2263 if (N0C && N0C->isNullValue())
2264 return N2;
2265 // fold select C, 1, X -> C | X
2266 if (MVT::i1 == VT && N1C && N1C->getValue() == 1)
2267 return DAG.getNode(ISD::OR, VT, N0, N2);
Evan Chengff601dc2007-08-18 05:57:05 +00002268 // fold select C, 0, 1 -> ~C
2269 if (MVT::isInteger(VT) && MVT::isInteger(VT0) &&
2270 N1C && N2C && N1C->isNullValue() && N2C->getValue() == 1) {
2271 SDOperand XORNode = DAG.getNode(ISD::XOR, VT0, N0, DAG.getConstant(1, VT0));
2272 if (VT == VT0)
2273 return XORNode;
2274 AddToWorkList(XORNode.Val);
2275 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(VT0))
2276 return DAG.getNode(ISD::ZERO_EXTEND, VT, XORNode);
2277 return DAG.getNode(ISD::TRUNCATE, VT, XORNode);
2278 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002279 // fold select C, 0, X -> ~C & X
Evan Chengff601dc2007-08-18 05:57:05 +00002280 if (VT == VT0 && N1C && N1C->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002281 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2282 AddToWorkList(XORNode.Val);
2283 return DAG.getNode(ISD::AND, VT, XORNode, N2);
2284 }
2285 // fold select C, X, 1 -> ~C | X
Evan Chengff601dc2007-08-18 05:57:05 +00002286 if (VT == VT0 && N2C && N2C->getValue() == 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002287 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2288 AddToWorkList(XORNode.Val);
2289 return DAG.getNode(ISD::OR, VT, XORNode, N1);
2290 }
2291 // fold select C, X, 0 -> C & X
2292 // FIXME: this should check for C type == X type, not i1?
2293 if (MVT::i1 == VT && N2C && N2C->isNullValue())
2294 return DAG.getNode(ISD::AND, VT, N0, N1);
2295 // fold X ? X : Y --> X ? 1 : Y --> X | Y
2296 if (MVT::i1 == VT && N0 == N1)
2297 return DAG.getNode(ISD::OR, VT, N0, N2);
2298 // fold X ? Y : X --> X ? Y : 0 --> X & Y
2299 if (MVT::i1 == VT && N0 == N2)
2300 return DAG.getNode(ISD::AND, VT, N0, N1);
2301
2302 // If we can fold this based on the true/false value, do so.
2303 if (SimplifySelectOps(N, N1, N2))
2304 return SDOperand(N, 0); // Don't revisit N.
2305
2306 // fold selects based on a setcc into other things, such as min/max/abs
2307 if (N0.getOpcode() == ISD::SETCC)
2308 // FIXME:
2309 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2310 // having to say they don't support SELECT_CC on every type the DAG knows
2311 // about, since there is no way to mark an opcode illegal at all value types
2312 if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
2313 return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
2314 N1, N2, N0.getOperand(2));
2315 else
2316 return SimplifySelect(N0, N1, N2);
2317 return SDOperand();
2318}
2319
2320SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
2321 SDOperand N0 = N->getOperand(0);
2322 SDOperand N1 = N->getOperand(1);
2323 SDOperand N2 = N->getOperand(2);
2324 SDOperand N3 = N->getOperand(3);
2325 SDOperand N4 = N->getOperand(4);
2326 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2327
2328 // fold select_cc lhs, rhs, x, x, cc -> x
2329 if (N2 == N3)
2330 return N2;
2331
2332 // Determine if the condition we're dealing with is constant
2333 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
2334 if (SCC.Val) AddToWorkList(SCC.Val);
2335
2336 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val)) {
2337 if (SCCC->getValue())
2338 return N2; // cond always true -> true val
2339 else
2340 return N3; // cond always false -> false val
2341 }
2342
2343 // Fold to a simpler select_cc
2344 if (SCC.Val && SCC.getOpcode() == ISD::SETCC)
2345 return DAG.getNode(ISD::SELECT_CC, N2.getValueType(),
2346 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2347 SCC.getOperand(2));
2348
2349 // If we can fold this based on the true/false value, do so.
2350 if (SimplifySelectOps(N, N2, N3))
2351 return SDOperand(N, 0); // Don't revisit N.
2352
2353 // fold select_cc into other things, such as min/max/abs
2354 return SimplifySelectCC(N0, N1, N2, N3, CC);
2355}
2356
2357SDOperand DAGCombiner::visitSETCC(SDNode *N) {
2358 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2359 cast<CondCodeSDNode>(N->getOperand(2))->get());
2360}
2361
2362SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2363 SDOperand N0 = N->getOperand(0);
2364 MVT::ValueType VT = N->getValueType(0);
2365
2366 // fold (sext c1) -> c1
2367 if (isa<ConstantSDNode>(N0))
2368 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
2369
2370 // fold (sext (sext x)) -> (sext x)
2371 // fold (sext (aext x)) -> (sext x)
2372 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2373 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
2374
2375 // fold (sext (truncate (load x))) -> (sext (smaller load x))
2376 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
2377 if (N0.getOpcode() == ISD::TRUNCATE) {
2378 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2379 if (NarrowLoad.Val) {
2380 if (NarrowLoad.Val != N0.Val)
2381 CombineTo(N0.Val, NarrowLoad);
2382 return DAG.getNode(ISD::SIGN_EXTEND, VT, NarrowLoad);
2383 }
2384 }
2385
2386 // See if the value being truncated is already sign extended. If so, just
2387 // eliminate the trunc/sext pair.
2388 if (N0.getOpcode() == ISD::TRUNCATE) {
2389 SDOperand Op = N0.getOperand(0);
2390 unsigned OpBits = MVT::getSizeInBits(Op.getValueType());
2391 unsigned MidBits = MVT::getSizeInBits(N0.getValueType());
2392 unsigned DestBits = MVT::getSizeInBits(VT);
2393 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
2394
2395 if (OpBits == DestBits) {
2396 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
2397 // bits, it is already ready.
2398 if (NumSignBits > DestBits-MidBits)
2399 return Op;
2400 } else if (OpBits < DestBits) {
2401 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
2402 // bits, just sext from i32.
2403 if (NumSignBits > OpBits-MidBits)
2404 return DAG.getNode(ISD::SIGN_EXTEND, VT, Op);
2405 } else {
2406 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
2407 // bits, just truncate to i32.
2408 if (NumSignBits > OpBits-MidBits)
2409 return DAG.getNode(ISD::TRUNCATE, VT, Op);
2410 }
2411
2412 // fold (sext (truncate x)) -> (sextinreg x).
2413 if (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
2414 N0.getValueType())) {
2415 if (Op.getValueType() < VT)
2416 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2417 else if (Op.getValueType() > VT)
2418 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2419 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op,
2420 DAG.getValueType(N0.getValueType()));
2421 }
2422 }
2423
2424 // fold (sext (load x)) -> (sext (truncate (sextload x)))
2425 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2426 (!AfterLegalize||TLI.isLoadXLegal(ISD::SEXTLOAD, N0.getValueType()))){
2427 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2428 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2429 LN0->getBasePtr(), LN0->getSrcValue(),
2430 LN0->getSrcValueOffset(),
2431 N0.getValueType(),
2432 LN0->isVolatile(),
2433 LN0->getAlignment());
2434 CombineTo(N, ExtLoad);
2435 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2436 ExtLoad.getValue(1));
2437 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2438 }
2439
2440 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
2441 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
2442 if ((ISD::isSEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2443 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2444 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2445 MVT::ValueType EVT = LN0->getLoadedVT();
2446 if (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT)) {
2447 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2448 LN0->getBasePtr(), LN0->getSrcValue(),
2449 LN0->getSrcValueOffset(), EVT,
2450 LN0->isVolatile(),
2451 LN0->getAlignment());
2452 CombineTo(N, ExtLoad);
2453 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2454 ExtLoad.getValue(1));
2455 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2456 }
2457 }
2458
2459 // sext(setcc x,y,cc) -> select_cc x, y, -1, 0, cc
2460 if (N0.getOpcode() == ISD::SETCC) {
2461 SDOperand SCC =
2462 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2463 DAG.getConstant(~0ULL, VT), DAG.getConstant(0, VT),
2464 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2465 if (SCC.Val) return SCC;
2466 }
2467
2468 return SDOperand();
2469}
2470
2471SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
2472 SDOperand N0 = N->getOperand(0);
2473 MVT::ValueType VT = N->getValueType(0);
2474
2475 // fold (zext c1) -> c1
2476 if (isa<ConstantSDNode>(N0))
2477 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2478 // fold (zext (zext x)) -> (zext x)
2479 // fold (zext (aext x)) -> (zext x)
2480 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2481 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
2482
2483 // fold (zext (truncate (load x))) -> (zext (smaller load x))
2484 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
2485 if (N0.getOpcode() == ISD::TRUNCATE) {
2486 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2487 if (NarrowLoad.Val) {
2488 if (NarrowLoad.Val != N0.Val)
2489 CombineTo(N0.Val, NarrowLoad);
2490 return DAG.getNode(ISD::ZERO_EXTEND, VT, NarrowLoad);
2491 }
2492 }
2493
2494 // fold (zext (truncate x)) -> (and x, mask)
2495 if (N0.getOpcode() == ISD::TRUNCATE &&
2496 (!AfterLegalize || TLI.isOperationLegal(ISD::AND, VT))) {
2497 SDOperand Op = N0.getOperand(0);
2498 if (Op.getValueType() < VT) {
2499 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2500 } else if (Op.getValueType() > VT) {
2501 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2502 }
2503 return DAG.getZeroExtendInReg(Op, N0.getValueType());
2504 }
2505
2506 // fold (zext (and (trunc x), cst)) -> (and x, cst).
2507 if (N0.getOpcode() == ISD::AND &&
2508 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2509 N0.getOperand(1).getOpcode() == ISD::Constant) {
2510 SDOperand X = N0.getOperand(0).getOperand(0);
2511 if (X.getValueType() < VT) {
2512 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2513 } else if (X.getValueType() > VT) {
2514 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2515 }
2516 uint64_t Mask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2517 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2518 }
2519
2520 // fold (zext (load x)) -> (zext (truncate (zextload x)))
2521 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2522 (!AfterLegalize||TLI.isLoadXLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
2523 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2524 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2525 LN0->getBasePtr(), LN0->getSrcValue(),
2526 LN0->getSrcValueOffset(),
2527 N0.getValueType(),
2528 LN0->isVolatile(),
2529 LN0->getAlignment());
2530 CombineTo(N, ExtLoad);
2531 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2532 ExtLoad.getValue(1));
2533 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2534 }
2535
2536 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
2537 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
2538 if ((ISD::isZEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2539 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2540 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2541 MVT::ValueType EVT = LN0->getLoadedVT();
2542 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2543 LN0->getBasePtr(), LN0->getSrcValue(),
2544 LN0->getSrcValueOffset(), EVT,
2545 LN0->isVolatile(),
2546 LN0->getAlignment());
2547 CombineTo(N, ExtLoad);
2548 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2549 ExtLoad.getValue(1));
2550 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2551 }
2552
2553 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
2554 if (N0.getOpcode() == ISD::SETCC) {
2555 SDOperand SCC =
2556 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2557 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2558 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2559 if (SCC.Val) return SCC;
2560 }
2561
2562 return SDOperand();
2563}
2564
2565SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
2566 SDOperand N0 = N->getOperand(0);
2567 MVT::ValueType VT = N->getValueType(0);
2568
2569 // fold (aext c1) -> c1
2570 if (isa<ConstantSDNode>(N0))
2571 return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
2572 // fold (aext (aext x)) -> (aext x)
2573 // fold (aext (zext x)) -> (zext x)
2574 // fold (aext (sext x)) -> (sext x)
2575 if (N0.getOpcode() == ISD::ANY_EXTEND ||
2576 N0.getOpcode() == ISD::ZERO_EXTEND ||
2577 N0.getOpcode() == ISD::SIGN_EXTEND)
2578 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
2579
2580 // fold (aext (truncate (load x))) -> (aext (smaller load x))
2581 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
2582 if (N0.getOpcode() == ISD::TRUNCATE) {
2583 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2584 if (NarrowLoad.Val) {
2585 if (NarrowLoad.Val != N0.Val)
2586 CombineTo(N0.Val, NarrowLoad);
2587 return DAG.getNode(ISD::ANY_EXTEND, VT, NarrowLoad);
2588 }
2589 }
2590
2591 // fold (aext (truncate x))
2592 if (N0.getOpcode() == ISD::TRUNCATE) {
2593 SDOperand TruncOp = N0.getOperand(0);
2594 if (TruncOp.getValueType() == VT)
2595 return TruncOp; // x iff x size == zext size.
2596 if (TruncOp.getValueType() > VT)
2597 return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
2598 return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
2599 }
2600
2601 // fold (aext (and (trunc x), cst)) -> (and x, cst).
2602 if (N0.getOpcode() == ISD::AND &&
2603 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2604 N0.getOperand(1).getOpcode() == ISD::Constant) {
2605 SDOperand X = N0.getOperand(0).getOperand(0);
2606 if (X.getValueType() < VT) {
2607 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2608 } else if (X.getValueType() > VT) {
2609 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2610 }
2611 uint64_t Mask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2612 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2613 }
2614
2615 // fold (aext (load x)) -> (aext (truncate (extload x)))
2616 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2617 (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
2618 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2619 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
2620 LN0->getBasePtr(), LN0->getSrcValue(),
2621 LN0->getSrcValueOffset(),
2622 N0.getValueType(),
2623 LN0->isVolatile(),
2624 LN0->getAlignment());
2625 CombineTo(N, ExtLoad);
2626 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2627 ExtLoad.getValue(1));
2628 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2629 }
2630
2631 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
2632 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
2633 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
2634 if (N0.getOpcode() == ISD::LOAD &&
2635 !ISD::isNON_EXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
2636 N0.hasOneUse()) {
2637 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2638 MVT::ValueType EVT = LN0->getLoadedVT();
2639 SDOperand ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
2640 LN0->getChain(), LN0->getBasePtr(),
2641 LN0->getSrcValue(),
2642 LN0->getSrcValueOffset(), EVT,
2643 LN0->isVolatile(),
2644 LN0->getAlignment());
2645 CombineTo(N, ExtLoad);
2646 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2647 ExtLoad.getValue(1));
2648 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2649 }
2650
2651 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
2652 if (N0.getOpcode() == ISD::SETCC) {
2653 SDOperand SCC =
2654 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2655 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2656 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2657 if (SCC.Val)
2658 return SCC;
2659 }
2660
2661 return SDOperand();
2662}
2663
2664/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
2665/// bits and then truncated to a narrower type and where N is a multiple
2666/// of number of bits of the narrower type, transform it to a narrower load
2667/// from address + N / num of bits of new type. If the result is to be
2668/// extended, also fold the extension to form a extending load.
2669SDOperand DAGCombiner::ReduceLoadWidth(SDNode *N) {
2670 unsigned Opc = N->getOpcode();
2671 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2672 SDOperand N0 = N->getOperand(0);
2673 MVT::ValueType VT = N->getValueType(0);
2674 MVT::ValueType EVT = N->getValueType(0);
2675
2676 // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then
2677 // extended to VT.
2678 if (Opc == ISD::SIGN_EXTEND_INREG) {
2679 ExtType = ISD::SEXTLOAD;
2680 EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
2681 if (AfterLegalize && !TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))
2682 return SDOperand();
2683 }
2684
2685 unsigned EVTBits = MVT::getSizeInBits(EVT);
2686 unsigned ShAmt = 0;
2687 bool CombineSRL = false;
2688 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
2689 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2690 ShAmt = N01->getValue();
2691 // Is the shift amount a multiple of size of VT?
2692 if ((ShAmt & (EVTBits-1)) == 0) {
2693 N0 = N0.getOperand(0);
2694 if (MVT::getSizeInBits(N0.getValueType()) <= EVTBits)
2695 return SDOperand();
2696 CombineSRL = true;
2697 }
2698 }
2699 }
2700
2701 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2702 // Do not allow folding to i1 here. i1 is implicitly stored in memory in
2703 // zero extended form: by shrinking the load, we lose track of the fact
2704 // that it is already zero extended.
2705 // FIXME: This should be reevaluated.
2706 VT != MVT::i1) {
2707 assert(MVT::getSizeInBits(N0.getValueType()) > EVTBits &&
2708 "Cannot truncate to larger type!");
2709 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2710 MVT::ValueType PtrType = N0.getOperand(1).getValueType();
2711 // For big endian targets, we need to adjust the offset to the pointer to
2712 // load the correct bytes.
2713 if (!TLI.isLittleEndian())
2714 ShAmt = MVT::getSizeInBits(N0.getValueType()) - ShAmt - EVTBits;
2715 uint64_t PtrOff = ShAmt / 8;
2716 SDOperand NewPtr = DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
2717 DAG.getConstant(PtrOff, PtrType));
2718 AddToWorkList(NewPtr.Val);
2719 SDOperand Load = (ExtType == ISD::NON_EXTLOAD)
2720 ? DAG.getLoad(VT, LN0->getChain(), NewPtr,
2721 LN0->getSrcValue(), LN0->getSrcValueOffset(),
2722 LN0->isVolatile(), LN0->getAlignment())
2723 : DAG.getExtLoad(ExtType, VT, LN0->getChain(), NewPtr,
2724 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
2725 LN0->isVolatile(), LN0->getAlignment());
2726 AddToWorkList(N);
2727 if (CombineSRL) {
2728 std::vector<SDNode*> NowDead;
2729 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1), NowDead);
2730 CombineTo(N->getOperand(0).Val, Load);
2731 } else
2732 CombineTo(N0.Val, Load, Load.getValue(1));
2733 if (ShAmt) {
2734 if (Opc == ISD::SIGN_EXTEND_INREG)
2735 return DAG.getNode(Opc, VT, Load, N->getOperand(1));
2736 else
2737 return DAG.getNode(Opc, VT, Load);
2738 }
2739 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2740 }
2741
2742 return SDOperand();
2743}
2744
2745
2746SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
2747 SDOperand N0 = N->getOperand(0);
2748 SDOperand N1 = N->getOperand(1);
2749 MVT::ValueType VT = N->getValueType(0);
2750 MVT::ValueType EVT = cast<VTSDNode>(N1)->getVT();
2751 unsigned EVTBits = MVT::getSizeInBits(EVT);
2752
2753 // fold (sext_in_reg c1) -> c1
2754 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
2755 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
2756
2757 // If the input is already sign extended, just drop the extension.
2758 if (DAG.ComputeNumSignBits(N0) >= MVT::getSizeInBits(VT)-EVTBits+1)
2759 return N0;
2760
2761 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
2762 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2763 EVT < cast<VTSDNode>(N0.getOperand(1))->getVT()) {
2764 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
2765 }
2766
2767 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
2768 if (DAG.MaskedValueIsZero(N0, 1ULL << (EVTBits-1)))
2769 return DAG.getZeroExtendInReg(N0, EVT);
2770
2771 // fold operands of sext_in_reg based on knowledge that the top bits are not
2772 // demanded.
2773 if (SimplifyDemandedBits(SDOperand(N, 0)))
2774 return SDOperand(N, 0);
2775
2776 // fold (sext_in_reg (load x)) -> (smaller sextload x)
2777 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
2778 SDOperand NarrowLoad = ReduceLoadWidth(N);
2779 if (NarrowLoad.Val)
2780 return NarrowLoad;
2781
2782 // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
2783 // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
2784 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
2785 if (N0.getOpcode() == ISD::SRL) {
2786 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2787 if (ShAmt->getValue()+EVTBits <= MVT::getSizeInBits(VT)) {
2788 // We can turn this into an SRA iff the input to the SRL is already sign
2789 // extended enough.
2790 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
2791 if (MVT::getSizeInBits(VT)-(ShAmt->getValue()+EVTBits) < InSignBits)
2792 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
2793 }
2794 }
2795
2796 // fold (sext_inreg (extload x)) -> (sextload x)
2797 if (ISD::isEXTLoad(N0.Val) &&
2798 ISD::isUNINDEXEDLoad(N0.Val) &&
2799 EVT == cast<LoadSDNode>(N0)->getLoadedVT() &&
2800 (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
2801 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2802 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2803 LN0->getBasePtr(), LN0->getSrcValue(),
2804 LN0->getSrcValueOffset(), EVT,
2805 LN0->isVolatile(),
2806 LN0->getAlignment());
2807 CombineTo(N, ExtLoad);
2808 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
2809 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2810 }
2811 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
2812 if (ISD::isZEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
2813 N0.hasOneUse() &&
2814 EVT == cast<LoadSDNode>(N0)->getLoadedVT() &&
2815 (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
2816 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2817 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2818 LN0->getBasePtr(), LN0->getSrcValue(),
2819 LN0->getSrcValueOffset(), EVT,
2820 LN0->isVolatile(),
2821 LN0->getAlignment());
2822 CombineTo(N, ExtLoad);
2823 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
2824 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2825 }
2826 return SDOperand();
2827}
2828
2829SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
2830 SDOperand N0 = N->getOperand(0);
2831 MVT::ValueType VT = N->getValueType(0);
2832
2833 // noop truncate
2834 if (N0.getValueType() == N->getValueType(0))
2835 return N0;
2836 // fold (truncate c1) -> c1
2837 if (isa<ConstantSDNode>(N0))
2838 return DAG.getNode(ISD::TRUNCATE, VT, N0);
2839 // fold (truncate (truncate x)) -> (truncate x)
2840 if (N0.getOpcode() == ISD::TRUNCATE)
2841 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
2842 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
2843 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
2844 N0.getOpcode() == ISD::ANY_EXTEND) {
2845 if (N0.getOperand(0).getValueType() < VT)
2846 // if the source is smaller than the dest, we still need an extend
2847 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
2848 else if (N0.getOperand(0).getValueType() > VT)
2849 // if the source is larger than the dest, than we just need the truncate
2850 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
2851 else
2852 // if the source and dest are the same type, we can drop both the extend
2853 // and the truncate
2854 return N0.getOperand(0);
2855 }
2856
2857 // fold (truncate (load x)) -> (smaller load x)
2858 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
2859 return ReduceLoadWidth(N);
2860}
2861
2862SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
2863 SDOperand N0 = N->getOperand(0);
2864 MVT::ValueType VT = N->getValueType(0);
2865
2866 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
2867 // Only do this before legalize, since afterward the target may be depending
2868 // on the bitconvert.
2869 // First check to see if this is all constant.
2870 if (!AfterLegalize &&
2871 N0.getOpcode() == ISD::BUILD_VECTOR && N0.Val->hasOneUse() &&
2872 MVT::isVector(VT)) {
2873 bool isSimple = true;
2874 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
2875 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
2876 N0.getOperand(i).getOpcode() != ISD::Constant &&
2877 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
2878 isSimple = false;
2879 break;
2880 }
2881
2882 MVT::ValueType DestEltVT = MVT::getVectorElementType(N->getValueType(0));
2883 assert(!MVT::isVector(DestEltVT) &&
2884 "Element type of vector ValueType must not be vector!");
2885 if (isSimple) {
2886 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.Val, DestEltVT);
2887 }
2888 }
2889
2890 // If the input is a constant, let getNode() fold it.
2891 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
2892 SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
2893 if (Res.Val != N) return Res;
2894 }
2895
2896 if (N0.getOpcode() == ISD::BIT_CONVERT) // conv(conv(x,t1),t2) -> conv(x,t2)
2897 return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
2898
2899 // fold (conv (load x)) -> (load (conv*)x)
2900 // If the resultant load doesn't need a higher alignment than the original!
2901 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2902 ISD::isUNINDEXEDLoad(N0.Val) &&
2903 TLI.isOperationLegal(ISD::LOAD, VT)) {
2904 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2905 unsigned Align = TLI.getTargetMachine().getTargetData()->
2906 getABITypeAlignment(MVT::getTypeForValueType(VT));
2907 unsigned OrigAlign = LN0->getAlignment();
2908 if (Align <= OrigAlign) {
2909 SDOperand Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(),
2910 LN0->getSrcValue(), LN0->getSrcValueOffset(),
2911 LN0->isVolatile(), Align);
2912 AddToWorkList(N);
2913 CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
2914 Load.getValue(1));
2915 return Load;
2916 }
2917 }
2918
2919 return SDOperand();
2920}
2921
2922/// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
2923/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
2924/// destination element value type.
2925SDOperand DAGCombiner::
2926ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT::ValueType DstEltVT) {
2927 MVT::ValueType SrcEltVT = BV->getOperand(0).getValueType();
2928
2929 // If this is already the right type, we're done.
2930 if (SrcEltVT == DstEltVT) return SDOperand(BV, 0);
2931
2932 unsigned SrcBitSize = MVT::getSizeInBits(SrcEltVT);
2933 unsigned DstBitSize = MVT::getSizeInBits(DstEltVT);
2934
2935 // If this is a conversion of N elements of one type to N elements of another
2936 // type, convert each element. This handles FP<->INT cases.
2937 if (SrcBitSize == DstBitSize) {
2938 SmallVector<SDOperand, 8> Ops;
2939 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2940 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
2941 AddToWorkList(Ops.back().Val);
2942 }
2943 MVT::ValueType VT =
2944 MVT::getVectorType(DstEltVT,
2945 MVT::getVectorNumElements(BV->getValueType(0)));
2946 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
2947 }
2948
2949 // Otherwise, we're growing or shrinking the elements. To avoid having to
2950 // handle annoying details of growing/shrinking FP values, we convert them to
2951 // int first.
2952 if (MVT::isFloatingPoint(SrcEltVT)) {
2953 // Convert the input float vector to a int vector where the elements are the
2954 // same sizes.
2955 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
2956 MVT::ValueType IntVT = SrcEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
2957 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).Val;
2958 SrcEltVT = IntVT;
2959 }
2960
2961 // Now we know the input is an integer vector. If the output is a FP type,
2962 // convert to integer first, then to FP of the right size.
2963 if (MVT::isFloatingPoint(DstEltVT)) {
2964 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
2965 MVT::ValueType TmpVT = DstEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
2966 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).Val;
2967
2968 // Next, convert to FP elements of the same size.
2969 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
2970 }
2971
2972 // Okay, we know the src/dst types are both integers of differing types.
2973 // Handling growing first.
2974 assert(MVT::isInteger(SrcEltVT) && MVT::isInteger(DstEltVT));
2975 if (SrcBitSize < DstBitSize) {
2976 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
2977
2978 SmallVector<SDOperand, 8> Ops;
2979 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
2980 i += NumInputsPerOutput) {
2981 bool isLE = TLI.isLittleEndian();
2982 uint64_t NewBits = 0;
2983 bool EltIsUndef = true;
2984 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
2985 // Shift the previously computed bits over.
2986 NewBits <<= SrcBitSize;
2987 SDOperand Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
2988 if (Op.getOpcode() == ISD::UNDEF) continue;
2989 EltIsUndef = false;
2990
2991 NewBits |= cast<ConstantSDNode>(Op)->getValue();
2992 }
2993
2994 if (EltIsUndef)
2995 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
2996 else
2997 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
2998 }
2999
3000 MVT::ValueType VT = MVT::getVectorType(DstEltVT,
3001 Ops.size());
3002 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3003 }
3004
3005 // Finally, this must be the case where we are shrinking elements: each input
3006 // turns into multiple outputs.
3007 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
3008 SmallVector<SDOperand, 8> Ops;
3009 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3010 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
3011 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
3012 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3013 continue;
3014 }
3015 uint64_t OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getValue();
3016
3017 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
3018 unsigned ThisVal = OpVal & ((1ULL << DstBitSize)-1);
3019 OpVal >>= DstBitSize;
3020 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
3021 }
3022
3023 // For big endian targets, swap the order of the pieces of each element.
3024 if (!TLI.isLittleEndian())
3025 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
3026 }
3027 MVT::ValueType VT = MVT::getVectorType(DstEltVT, Ops.size());
3028 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3029}
3030
3031
3032
3033SDOperand DAGCombiner::visitFADD(SDNode *N) {
3034 SDOperand N0 = N->getOperand(0);
3035 SDOperand N1 = N->getOperand(1);
3036 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3037 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3038 MVT::ValueType VT = N->getValueType(0);
3039
3040 // fold vector ops
3041 if (MVT::isVector(VT)) {
3042 SDOperand FoldedVOp = SimplifyVBinOp(N);
3043 if (FoldedVOp.Val) return FoldedVOp;
3044 }
3045
3046 // fold (fadd c1, c2) -> c1+c2
3047 if (N0CFP && N1CFP)
3048 return DAG.getNode(ISD::FADD, VT, N0, N1);
3049 // canonicalize constant to RHS
3050 if (N0CFP && !N1CFP)
3051 return DAG.getNode(ISD::FADD, VT, N1, N0);
3052 // fold (A + (-B)) -> A-B
3053 if (isNegatibleForFree(N1) == 2)
3054 return DAG.getNode(ISD::FSUB, VT, N0, GetNegatedExpression(N1, DAG));
3055 // fold ((-A) + B) -> B-A
3056 if (isNegatibleForFree(N0) == 2)
3057 return DAG.getNode(ISD::FSUB, VT, N1, GetNegatedExpression(N0, DAG));
3058
3059 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
3060 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
3061 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3062 return DAG.getNode(ISD::FADD, VT, N0.getOperand(0),
3063 DAG.getNode(ISD::FADD, VT, N0.getOperand(1), N1));
3064
3065 return SDOperand();
3066}
3067
3068SDOperand DAGCombiner::visitFSUB(SDNode *N) {
3069 SDOperand N0 = N->getOperand(0);
3070 SDOperand N1 = N->getOperand(1);
3071 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3072 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3073 MVT::ValueType VT = N->getValueType(0);
3074
3075 // fold vector ops
3076 if (MVT::isVector(VT)) {
3077 SDOperand FoldedVOp = SimplifyVBinOp(N);
3078 if (FoldedVOp.Val) return FoldedVOp;
3079 }
3080
3081 // fold (fsub c1, c2) -> c1-c2
3082 if (N0CFP && N1CFP)
3083 return DAG.getNode(ISD::FSUB, VT, N0, N1);
3084 // fold (0-B) -> -B
Dale Johannesen7604c1b2007-08-31 23:34:27 +00003085 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003086 if (isNegatibleForFree(N1))
3087 return GetNegatedExpression(N1, DAG);
3088 return DAG.getNode(ISD::FNEG, VT, N1);
3089 }
3090 // fold (A-(-B)) -> A+B
3091 if (isNegatibleForFree(N1))
3092 return DAG.getNode(ISD::FADD, VT, N0, GetNegatedExpression(N1, DAG));
3093
3094 return SDOperand();
3095}
3096
3097SDOperand DAGCombiner::visitFMUL(SDNode *N) {
3098 SDOperand N0 = N->getOperand(0);
3099 SDOperand N1 = N->getOperand(1);
3100 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3101 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3102 MVT::ValueType VT = N->getValueType(0);
3103
3104 // fold vector ops
3105 if (MVT::isVector(VT)) {
3106 SDOperand FoldedVOp = SimplifyVBinOp(N);
3107 if (FoldedVOp.Val) return FoldedVOp;
3108 }
3109
3110 // fold (fmul c1, c2) -> c1*c2
3111 if (N0CFP && N1CFP)
3112 return DAG.getNode(ISD::FMUL, VT, N0, N1);
3113 // canonicalize constant to RHS
3114 if (N0CFP && !N1CFP)
3115 return DAG.getNode(ISD::FMUL, VT, N1, N0);
3116 // fold (fmul X, 2.0) -> (fadd X, X)
3117 if (N1CFP && N1CFP->isExactlyValue(+2.0))
3118 return DAG.getNode(ISD::FADD, VT, N0, N0);
3119 // fold (fmul X, -1.0) -> (fneg X)
3120 if (N1CFP && N1CFP->isExactlyValue(-1.0))
3121 return DAG.getNode(ISD::FNEG, VT, N0);
3122
3123 // -X * -Y -> X*Y
3124 if (char LHSNeg = isNegatibleForFree(N0)) {
3125 if (char RHSNeg = isNegatibleForFree(N1)) {
3126 // Both can be negated for free, check to see if at least one is cheaper
3127 // negated.
3128 if (LHSNeg == 2 || RHSNeg == 2)
3129 return DAG.getNode(ISD::FMUL, VT, GetNegatedExpression(N0, DAG),
3130 GetNegatedExpression(N1, DAG));
3131 }
3132 }
3133
3134 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
3135 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
3136 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3137 return DAG.getNode(ISD::FMUL, VT, N0.getOperand(0),
3138 DAG.getNode(ISD::FMUL, VT, N0.getOperand(1), N1));
3139
3140 return SDOperand();
3141}
3142
3143SDOperand DAGCombiner::visitFDIV(SDNode *N) {
3144 SDOperand N0 = N->getOperand(0);
3145 SDOperand N1 = N->getOperand(1);
3146 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3147 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3148 MVT::ValueType VT = N->getValueType(0);
3149
3150 // fold vector ops
3151 if (MVT::isVector(VT)) {
3152 SDOperand FoldedVOp = SimplifyVBinOp(N);
3153 if (FoldedVOp.Val) return FoldedVOp;
3154 }
3155
3156 // fold (fdiv c1, c2) -> c1/c2
3157 if (N0CFP && N1CFP)
3158 return DAG.getNode(ISD::FDIV, VT, N0, N1);
3159
3160
3161 // -X / -Y -> X*Y
3162 if (char LHSNeg = isNegatibleForFree(N0)) {
3163 if (char RHSNeg = isNegatibleForFree(N1)) {
3164 // Both can be negated for free, check to see if at least one is cheaper
3165 // negated.
3166 if (LHSNeg == 2 || RHSNeg == 2)
3167 return DAG.getNode(ISD::FDIV, VT, GetNegatedExpression(N0, DAG),
3168 GetNegatedExpression(N1, DAG));
3169 }
3170 }
3171
3172 return SDOperand();
3173}
3174
3175SDOperand DAGCombiner::visitFREM(SDNode *N) {
3176 SDOperand N0 = N->getOperand(0);
3177 SDOperand N1 = N->getOperand(1);
3178 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3179 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3180 MVT::ValueType VT = N->getValueType(0);
3181
3182 // fold (frem c1, c2) -> fmod(c1,c2)
3183 if (N0CFP && N1CFP)
3184 return DAG.getNode(ISD::FREM, VT, N0, N1);
3185
3186 return SDOperand();
3187}
3188
3189SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
3190 SDOperand N0 = N->getOperand(0);
3191 SDOperand N1 = N->getOperand(1);
3192 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3193 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3194 MVT::ValueType VT = N->getValueType(0);
3195
3196 if (N0CFP && N1CFP) // Constant fold
3197 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
3198
3199 if (N1CFP) {
Dale Johannesenc53301c2007-08-26 01:18:27 +00003200 const APFloat& V = N1CFP->getValueAPF();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003201 // copysign(x, c1) -> fabs(x) iff ispos(c1)
3202 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dale Johannesen7f2c1d12007-08-25 22:10:57 +00003203 if (!V.isNegative())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003204 return DAG.getNode(ISD::FABS, VT, N0);
3205 else
3206 return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
3207 }
3208
3209 // copysign(fabs(x), y) -> copysign(x, y)
3210 // copysign(fneg(x), y) -> copysign(x, y)
3211 // copysign(copysign(x,z), y) -> copysign(x, y)
3212 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
3213 N0.getOpcode() == ISD::FCOPYSIGN)
3214 return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
3215
3216 // copysign(x, abs(y)) -> abs(x)
3217 if (N1.getOpcode() == ISD::FABS)
3218 return DAG.getNode(ISD::FABS, VT, N0);
3219
3220 // copysign(x, copysign(y,z)) -> copysign(x, z)
3221 if (N1.getOpcode() == ISD::FCOPYSIGN)
3222 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
3223
3224 // copysign(x, fp_extend(y)) -> copysign(x, y)
3225 // copysign(x, fp_round(y)) -> copysign(x, y)
3226 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
3227 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
3228
3229 return SDOperand();
3230}
3231
3232
3233
3234SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
3235 SDOperand N0 = N->getOperand(0);
3236 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3237 MVT::ValueType VT = N->getValueType(0);
3238
3239 // fold (sint_to_fp c1) -> c1fp
3240 if (N0C)
3241 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
3242 return SDOperand();
3243}
3244
3245SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
3246 SDOperand N0 = N->getOperand(0);
3247 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3248 MVT::ValueType VT = N->getValueType(0);
3249
3250 // fold (uint_to_fp c1) -> c1fp
3251 if (N0C)
3252 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
3253 return SDOperand();
3254}
3255
3256SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
3257 SDOperand N0 = N->getOperand(0);
3258 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3259 MVT::ValueType VT = N->getValueType(0);
3260
3261 // fold (fp_to_sint c1fp) -> c1
3262 if (N0CFP)
3263 return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
3264 return SDOperand();
3265}
3266
3267SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
3268 SDOperand N0 = N->getOperand(0);
3269 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3270 MVT::ValueType VT = N->getValueType(0);
3271
3272 // fold (fp_to_uint c1fp) -> c1
3273 if (N0CFP)
3274 return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
3275 return SDOperand();
3276}
3277
3278SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
3279 SDOperand N0 = N->getOperand(0);
3280 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3281 MVT::ValueType VT = N->getValueType(0);
3282
3283 // fold (fp_round c1fp) -> c1fp
3284 if (N0CFP)
3285 return DAG.getNode(ISD::FP_ROUND, VT, N0);
3286
3287 // fold (fp_round (fp_extend x)) -> x
3288 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
3289 return N0.getOperand(0);
3290
3291 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
3292 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
3293 SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0));
3294 AddToWorkList(Tmp.Val);
3295 return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
3296 }
3297
3298 return SDOperand();
3299}
3300
3301SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
3302 SDOperand N0 = N->getOperand(0);
3303 MVT::ValueType VT = N->getValueType(0);
3304 MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3305 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3306
3307 // fold (fp_round_inreg c1fp) -> c1fp
3308 if (N0CFP) {
Dale Johannesen7604c1b2007-08-31 23:34:27 +00003309 SDOperand Round = DAG.getConstantFP(N0CFP->getValueAPF(), EVT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003310 return DAG.getNode(ISD::FP_EXTEND, VT, Round);
3311 }
3312 return SDOperand();
3313}
3314
3315SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
3316 SDOperand N0 = N->getOperand(0);
3317 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3318 MVT::ValueType VT = N->getValueType(0);
3319
3320 // fold (fp_extend c1fp) -> c1fp
3321 if (N0CFP)
3322 return DAG.getNode(ISD::FP_EXTEND, VT, N0);
3323
3324 // fold (fpext (load x)) -> (fpext (fpround (extload x)))
3325 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3326 (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3327 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3328 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3329 LN0->getBasePtr(), LN0->getSrcValue(),
3330 LN0->getSrcValueOffset(),
3331 N0.getValueType(),
3332 LN0->isVolatile(),
3333 LN0->getAlignment());
3334 CombineTo(N, ExtLoad);
3335 CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad),
3336 ExtLoad.getValue(1));
3337 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3338 }
3339
3340
3341 return SDOperand();
3342}
3343
3344SDOperand DAGCombiner::visitFNEG(SDNode *N) {
3345 SDOperand N0 = N->getOperand(0);
3346
3347 if (isNegatibleForFree(N0))
3348 return GetNegatedExpression(N0, DAG);
3349
3350 return SDOperand();
3351}
3352
3353SDOperand DAGCombiner::visitFABS(SDNode *N) {
3354 SDOperand N0 = N->getOperand(0);
3355 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3356 MVT::ValueType VT = N->getValueType(0);
3357
3358 // fold (fabs c1) -> fabs(c1)
3359 if (N0CFP)
3360 return DAG.getNode(ISD::FABS, VT, N0);
3361 // fold (fabs (fabs x)) -> (fabs x)
3362 if (N0.getOpcode() == ISD::FABS)
3363 return N->getOperand(0);
3364 // fold (fabs (fneg x)) -> (fabs x)
3365 // fold (fabs (fcopysign x, y)) -> (fabs x)
3366 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
3367 return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
3368
3369 return SDOperand();
3370}
3371
3372SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
3373 SDOperand Chain = N->getOperand(0);
3374 SDOperand N1 = N->getOperand(1);
3375 SDOperand N2 = N->getOperand(2);
3376 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3377
3378 // never taken branch, fold to chain
3379 if (N1C && N1C->isNullValue())
3380 return Chain;
3381 // unconditional branch
3382 if (N1C && N1C->getValue() == 1)
3383 return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
3384 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
3385 // on the target.
3386 if (N1.getOpcode() == ISD::SETCC &&
3387 TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
3388 return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
3389 N1.getOperand(0), N1.getOperand(1), N2);
3390 }
3391 return SDOperand();
3392}
3393
3394// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
3395//
3396SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
3397 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
3398 SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
3399
3400 // Use SimplifySetCC to simplify SETCC's.
3401 SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
3402 if (Simp.Val) AddToWorkList(Simp.Val);
3403
3404 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
3405
3406 // fold br_cc true, dest -> br dest (unconditional branch)
3407 if (SCCC && SCCC->getValue())
3408 return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
3409 N->getOperand(4));
3410 // fold br_cc false, dest -> unconditional fall through
3411 if (SCCC && SCCC->isNullValue())
3412 return N->getOperand(0);
3413
3414 // fold to a simpler setcc
3415 if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
3416 return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
3417 Simp.getOperand(2), Simp.getOperand(0),
3418 Simp.getOperand(1), N->getOperand(4));
3419 return SDOperand();
3420}
3421
3422
3423/// CombineToPreIndexedLoadStore - Try turning a load / store and a
3424/// pre-indexed load / store when the base pointer is a add or subtract
3425/// and it has other uses besides the load / store. After the
3426/// transformation, the new indexed load / store has effectively folded
3427/// the add / subtract in and all of its other uses are redirected to the
3428/// new load / store.
3429bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
3430 if (!AfterLegalize)
3431 return false;
3432
3433 bool isLoad = true;
3434 SDOperand Ptr;
3435 MVT::ValueType VT;
3436 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3437 if (LD->getAddressingMode() != ISD::UNINDEXED)
3438 return false;
3439 VT = LD->getLoadedVT();
3440 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
3441 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
3442 return false;
3443 Ptr = LD->getBasePtr();
3444 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
3445 if (ST->getAddressingMode() != ISD::UNINDEXED)
3446 return false;
3447 VT = ST->getStoredVT();
3448 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
3449 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
3450 return false;
3451 Ptr = ST->getBasePtr();
3452 isLoad = false;
3453 } else
3454 return false;
3455
3456 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
3457 // out. There is no reason to make this a preinc/predec.
3458 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
3459 Ptr.Val->hasOneUse())
3460 return false;
3461
3462 // Ask the target to do addressing mode selection.
3463 SDOperand BasePtr;
3464 SDOperand Offset;
3465 ISD::MemIndexedMode AM = ISD::UNINDEXED;
3466 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
3467 return false;
3468 // Don't create a indexed load / store with zero offset.
3469 if (isa<ConstantSDNode>(Offset) &&
3470 cast<ConstantSDNode>(Offset)->getValue() == 0)
3471 return false;
3472
3473 // Try turning it into a pre-indexed load / store except when:
3474 // 1) The new base ptr is a frame index.
3475 // 2) If N is a store and the new base ptr is either the same as or is a
3476 // predecessor of the value being stored.
3477 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
3478 // that would create a cycle.
3479 // 4) All uses are load / store ops that use it as old base ptr.
3480
3481 // Check #1. Preinc'ing a frame index would require copying the stack pointer
3482 // (plus the implicit offset) to a register to preinc anyway.
3483 if (isa<FrameIndexSDNode>(BasePtr))
3484 return false;
3485
3486 // Check #2.
3487 if (!isLoad) {
3488 SDOperand Val = cast<StoreSDNode>(N)->getValue();
3489 if (Val == BasePtr || BasePtr.Val->isPredecessor(Val.Val))
3490 return false;
3491 }
3492
3493 // Now check for #3 and #4.
3494 bool RealUse = false;
3495 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
3496 E = Ptr.Val->use_end(); I != E; ++I) {
3497 SDNode *Use = *I;
3498 if (Use == N)
3499 continue;
3500 if (Use->isPredecessor(N))
3501 return false;
3502
3503 if (!((Use->getOpcode() == ISD::LOAD &&
3504 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
3505 (Use->getOpcode() == ISD::STORE) &&
3506 cast<StoreSDNode>(Use)->getBasePtr() == Ptr))
3507 RealUse = true;
3508 }
3509 if (!RealUse)
3510 return false;
3511
3512 SDOperand Result;
3513 if (isLoad)
3514 Result = DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM);
3515 else
3516 Result = DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
3517 ++PreIndexedNodes;
3518 ++NodesCombined;
3519 DOUT << "\nReplacing.4 "; DEBUG(N->dump(&DAG));
3520 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
3521 DOUT << '\n';
3522 std::vector<SDNode*> NowDead;
3523 if (isLoad) {
3524 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
3525 NowDead);
3526 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
3527 NowDead);
3528 } else {
3529 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
3530 NowDead);
3531 }
3532
3533 // Nodes can end up on the worklist more than once. Make sure we do
3534 // not process a node that has been replaced.
3535 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
3536 removeFromWorkList(NowDead[i]);
3537 // Finally, since the node is now dead, remove it from the graph.
3538 DAG.DeleteNode(N);
3539
3540 // Replace the uses of Ptr with uses of the updated base value.
3541 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
3542 NowDead);
3543 removeFromWorkList(Ptr.Val);
3544 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
3545 removeFromWorkList(NowDead[i]);
3546 DAG.DeleteNode(Ptr.Val);
3547
3548 return true;
3549}
3550
3551/// CombineToPostIndexedLoadStore - Try combine a load / store with a
3552/// add / sub of the base pointer node into a post-indexed load / store.
3553/// The transformation folded the add / subtract into the new indexed
3554/// load / store effectively and all of its uses are redirected to the
3555/// new load / store.
3556bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
3557 if (!AfterLegalize)
3558 return false;
3559
3560 bool isLoad = true;
3561 SDOperand Ptr;
3562 MVT::ValueType VT;
3563 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3564 if (LD->getAddressingMode() != ISD::UNINDEXED)
3565 return false;
3566 VT = LD->getLoadedVT();
3567 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
3568 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
3569 return false;
3570 Ptr = LD->getBasePtr();
3571 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
3572 if (ST->getAddressingMode() != ISD::UNINDEXED)
3573 return false;
3574 VT = ST->getStoredVT();
3575 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
3576 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
3577 return false;
3578 Ptr = ST->getBasePtr();
3579 isLoad = false;
3580 } else
3581 return false;
3582
3583 if (Ptr.Val->hasOneUse())
3584 return false;
3585
3586 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
3587 E = Ptr.Val->use_end(); I != E; ++I) {
3588 SDNode *Op = *I;
3589 if (Op == N ||
3590 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
3591 continue;
3592
3593 SDOperand BasePtr;
3594 SDOperand Offset;
3595 ISD::MemIndexedMode AM = ISD::UNINDEXED;
3596 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
3597 if (Ptr == Offset)
3598 std::swap(BasePtr, Offset);
3599 if (Ptr != BasePtr)
3600 continue;
3601 // Don't create a indexed load / store with zero offset.
3602 if (isa<ConstantSDNode>(Offset) &&
3603 cast<ConstantSDNode>(Offset)->getValue() == 0)
3604 continue;
3605
3606 // Try turning it into a post-indexed load / store except when
3607 // 1) All uses are load / store ops that use it as base ptr.
3608 // 2) Op must be independent of N, i.e. Op is neither a predecessor
3609 // nor a successor of N. Otherwise, if Op is folded that would
3610 // create a cycle.
3611
3612 // Check for #1.
3613 bool TryNext = false;
3614 for (SDNode::use_iterator II = BasePtr.Val->use_begin(),
3615 EE = BasePtr.Val->use_end(); II != EE; ++II) {
3616 SDNode *Use = *II;
3617 if (Use == Ptr.Val)
3618 continue;
3619
3620 // If all the uses are load / store addresses, then don't do the
3621 // transformation.
3622 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
3623 bool RealUse = false;
3624 for (SDNode::use_iterator III = Use->use_begin(),
3625 EEE = Use->use_end(); III != EEE; ++III) {
3626 SDNode *UseUse = *III;
3627 if (!((UseUse->getOpcode() == ISD::LOAD &&
3628 cast<LoadSDNode>(UseUse)->getBasePtr().Val == Use) ||
3629 (UseUse->getOpcode() == ISD::STORE) &&
3630 cast<StoreSDNode>(UseUse)->getBasePtr().Val == Use))
3631 RealUse = true;
3632 }
3633
3634 if (!RealUse) {
3635 TryNext = true;
3636 break;
3637 }
3638 }
3639 }
3640 if (TryNext)
3641 continue;
3642
3643 // Check for #2
3644 if (!Op->isPredecessor(N) && !N->isPredecessor(Op)) {
3645 SDOperand Result = isLoad
3646 ? DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM)
3647 : DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
3648 ++PostIndexedNodes;
3649 ++NodesCombined;
3650 DOUT << "\nReplacing.5 "; DEBUG(N->dump(&DAG));
3651 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
3652 DOUT << '\n';
3653 std::vector<SDNode*> NowDead;
3654 if (isLoad) {
3655 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
3656 NowDead);
3657 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
3658 NowDead);
3659 } else {
3660 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
3661 NowDead);
3662 }
3663
3664 // Nodes can end up on the worklist more than once. Make sure we do
3665 // not process a node that has been replaced.
3666 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
3667 removeFromWorkList(NowDead[i]);
3668 // Finally, since the node is now dead, remove it from the graph.
3669 DAG.DeleteNode(N);
3670
3671 // Replace the uses of Use with uses of the updated base value.
3672 DAG.ReplaceAllUsesOfValueWith(SDOperand(Op, 0),
3673 Result.getValue(isLoad ? 1 : 0),
3674 NowDead);
3675 removeFromWorkList(Op);
3676 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
3677 removeFromWorkList(NowDead[i]);
3678 DAG.DeleteNode(Op);
3679
3680 return true;
3681 }
3682 }
3683 }
3684 return false;
3685}
3686
3687
3688SDOperand DAGCombiner::visitLOAD(SDNode *N) {
3689 LoadSDNode *LD = cast<LoadSDNode>(N);
3690 SDOperand Chain = LD->getChain();
3691 SDOperand Ptr = LD->getBasePtr();
3692
3693 // If load is not volatile and there are no uses of the loaded value (and
3694 // the updated indexed value in case of indexed loads), change uses of the
3695 // chain value into uses of the chain input (i.e. delete the dead load).
3696 if (!LD->isVolatile()) {
3697 if (N->getValueType(1) == MVT::Other) {
3698 // Unindexed loads.
3699 if (N->hasNUsesOfValue(0, 0))
3700 return CombineTo(N, DAG.getNode(ISD::UNDEF, N->getValueType(0)), Chain);
3701 } else {
3702 // Indexed loads.
3703 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
3704 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
3705 SDOperand Undef0 = DAG.getNode(ISD::UNDEF, N->getValueType(0));
3706 SDOperand Undef1 = DAG.getNode(ISD::UNDEF, N->getValueType(1));
3707 SDOperand To[] = { Undef0, Undef1, Chain };
3708 return CombineTo(N, To, 3);
3709 }
3710 }
3711 }
3712
3713 // If this load is directly stored, replace the load value with the stored
3714 // value.
3715 // TODO: Handle store large -> read small portion.
3716 // TODO: Handle TRUNCSTORE/LOADEXT
3717 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
3718 if (ISD::isNON_TRUNCStore(Chain.Val)) {
3719 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
3720 if (PrevST->getBasePtr() == Ptr &&
3721 PrevST->getValue().getValueType() == N->getValueType(0))
3722 return CombineTo(N, Chain.getOperand(1), Chain);
3723 }
3724 }
3725
3726 if (CombinerAA) {
3727 // Walk up chain skipping non-aliasing memory nodes.
3728 SDOperand BetterChain = FindBetterChain(N, Chain);
3729
3730 // If there is a better chain.
3731 if (Chain != BetterChain) {
3732 SDOperand ReplLoad;
3733
3734 // Replace the chain to void dependency.
3735 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
3736 ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
3737 LD->getSrcValue(), LD->getSrcValueOffset(),
3738 LD->isVolatile(), LD->getAlignment());
3739 } else {
3740 ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
3741 LD->getValueType(0),
3742 BetterChain, Ptr, LD->getSrcValue(),
3743 LD->getSrcValueOffset(),
3744 LD->getLoadedVT(),
3745 LD->isVolatile(),
3746 LD->getAlignment());
3747 }
3748
3749 // Create token factor to keep old chain connected.
3750 SDOperand Token = DAG.getNode(ISD::TokenFactor, MVT::Other,
3751 Chain, ReplLoad.getValue(1));
3752
3753 // Replace uses with load result and token factor. Don't add users
3754 // to work list.
3755 return CombineTo(N, ReplLoad.getValue(0), Token, false);
3756 }
3757 }
3758
3759 // Try transforming N to an indexed load.
3760 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
3761 return SDOperand(N, 0);
3762
3763 return SDOperand();
3764}
3765
3766SDOperand DAGCombiner::visitSTORE(SDNode *N) {
3767 StoreSDNode *ST = cast<StoreSDNode>(N);
3768 SDOperand Chain = ST->getChain();
3769 SDOperand Value = ST->getValue();
3770 SDOperand Ptr = ST->getBasePtr();
3771
3772 // If this is a store of a bit convert, store the input value if the
3773 // resultant store does not need a higher alignment than the original.
3774 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
3775 ST->getAddressingMode() == ISD::UNINDEXED) {
3776 unsigned Align = ST->getAlignment();
3777 MVT::ValueType SVT = Value.getOperand(0).getValueType();
3778 unsigned OrigAlign = TLI.getTargetMachine().getTargetData()->
3779 getABITypeAlignment(MVT::getTypeForValueType(SVT));
3780 if (Align <= OrigAlign && TLI.isOperationLegal(ISD::STORE, SVT))
3781 return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
3782 ST->getSrcValueOffset(), ST->isVolatile(), Align);
3783 }
3784
3785 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
3786 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
3787 if (Value.getOpcode() != ISD::TargetConstantFP) {
3788 SDOperand Tmp;
3789 switch (CFP->getValueType(0)) {
3790 default: assert(0 && "Unknown FP type");
3791 case MVT::f32:
3792 if (!AfterLegalize || TLI.isTypeLegal(MVT::i32)) {
Dale Johannesen7f2c1d12007-08-25 22:10:57 +00003793 Tmp = DAG.getConstant(FloatToBits(CFP->getValueAPF().convertToFloat()), MVT::i32);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003794 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
3795 ST->getSrcValueOffset(), ST->isVolatile(),
3796 ST->getAlignment());
3797 }
3798 break;
3799 case MVT::f64:
3800 if (!AfterLegalize || TLI.isTypeLegal(MVT::i64)) {
Dale Johannesen7f2c1d12007-08-25 22:10:57 +00003801 Tmp = DAG.getConstant(DoubleToBits(CFP->getValueAPF().convertToDouble()), MVT::i64);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003802 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
3803 ST->getSrcValueOffset(), ST->isVolatile(),
3804 ST->getAlignment());
3805 } else if (TLI.isTypeLegal(MVT::i32)) {
3806 // Many FP stores are not make apparent until after legalize, e.g. for
3807 // argument passing. Since this is so common, custom legalize the
3808 // 64-bit integer store into two 32-bit stores.
Dale Johannesen7f2c1d12007-08-25 22:10:57 +00003809 uint64_t Val = DoubleToBits(CFP->getValueAPF().convertToDouble());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003810 SDOperand Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
3811 SDOperand Hi = DAG.getConstant(Val >> 32, MVT::i32);
3812 if (!TLI.isLittleEndian()) std::swap(Lo, Hi);
3813
3814 int SVOffset = ST->getSrcValueOffset();
3815 unsigned Alignment = ST->getAlignment();
3816 bool isVolatile = ST->isVolatile();
3817
3818 SDOperand St0 = DAG.getStore(Chain, Lo, Ptr, ST->getSrcValue(),
3819 ST->getSrcValueOffset(),
3820 isVolatile, ST->getAlignment());
3821 Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
3822 DAG.getConstant(4, Ptr.getValueType()));
3823 SVOffset += 4;
3824 if (Alignment > 4)
3825 Alignment = 4;
3826 SDOperand St1 = DAG.getStore(Chain, Hi, Ptr, ST->getSrcValue(),
3827 SVOffset, isVolatile, Alignment);
3828 return DAG.getNode(ISD::TokenFactor, MVT::Other, St0, St1);
3829 }
3830 break;
3831 }
3832 }
3833 }
3834
3835 if (CombinerAA) {
3836 // Walk up chain skipping non-aliasing memory nodes.
3837 SDOperand BetterChain = FindBetterChain(N, Chain);
3838
3839 // If there is a better chain.
3840 if (Chain != BetterChain) {
3841 // Replace the chain to avoid dependency.
3842 SDOperand ReplStore;
3843 if (ST->isTruncatingStore()) {
3844 ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
3845 ST->getSrcValue(), ST->getSrcValueOffset(), ST->getStoredVT(),
3846 ST->isVolatile(), ST->getAlignment());
3847 } else {
3848 ReplStore = DAG.getStore(BetterChain, Value, Ptr,
3849 ST->getSrcValue(), ST->getSrcValueOffset(),
3850 ST->isVolatile(), ST->getAlignment());
3851 }
3852
3853 // Create token to keep both nodes around.
3854 SDOperand Token =
3855 DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore);
3856
3857 // Don't add users to work list.
3858 return CombineTo(N, Token, false);
3859 }
3860 }
3861
3862 // Try transforming N to an indexed store.
3863 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
3864 return SDOperand(N, 0);
3865
3866 return SDOperand();
3867}
3868
3869SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
3870 SDOperand InVec = N->getOperand(0);
3871 SDOperand InVal = N->getOperand(1);
3872 SDOperand EltNo = N->getOperand(2);
3873
3874 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
3875 // vector with the inserted element.
3876 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
3877 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
3878 SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
3879 if (Elt < Ops.size())
3880 Ops[Elt] = InVal;
3881 return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
3882 &Ops[0], Ops.size());
3883 }
3884
3885 return SDOperand();
3886}
3887
3888SDOperand DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
3889 unsigned NumInScalars = N->getNumOperands();
3890 MVT::ValueType VT = N->getValueType(0);
3891 unsigned NumElts = MVT::getVectorNumElements(VT);
3892 MVT::ValueType EltType = MVT::getVectorElementType(VT);
3893
3894 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
3895 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
3896 // at most two distinct vectors, turn this into a shuffle node.
3897 SDOperand VecIn1, VecIn2;
3898 for (unsigned i = 0; i != NumInScalars; ++i) {
3899 // Ignore undef inputs.
3900 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
3901
3902 // If this input is something other than a EXTRACT_VECTOR_ELT with a
3903 // constant index, bail out.
3904 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
3905 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
3906 VecIn1 = VecIn2 = SDOperand(0, 0);
3907 break;
3908 }
3909
3910 // If the input vector type disagrees with the result of the build_vector,
3911 // we can't make a shuffle.
3912 SDOperand ExtractedFromVec = N->getOperand(i).getOperand(0);
3913 if (ExtractedFromVec.getValueType() != VT) {
3914 VecIn1 = VecIn2 = SDOperand(0, 0);
3915 break;
3916 }
3917
3918 // Otherwise, remember this. We allow up to two distinct input vectors.
3919 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
3920 continue;
3921
3922 if (VecIn1.Val == 0) {
3923 VecIn1 = ExtractedFromVec;
3924 } else if (VecIn2.Val == 0) {
3925 VecIn2 = ExtractedFromVec;
3926 } else {
3927 // Too many inputs.
3928 VecIn1 = VecIn2 = SDOperand(0, 0);
3929 break;
3930 }
3931 }
3932
3933 // If everything is good, we can make a shuffle operation.
3934 if (VecIn1.Val) {
3935 SmallVector<SDOperand, 8> BuildVecIndices;
3936 for (unsigned i = 0; i != NumInScalars; ++i) {
3937 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
3938 BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, TLI.getPointerTy()));
3939 continue;
3940 }
3941
3942 SDOperand Extract = N->getOperand(i);
3943
3944 // If extracting from the first vector, just use the index directly.
3945 if (Extract.getOperand(0) == VecIn1) {
3946 BuildVecIndices.push_back(Extract.getOperand(1));
3947 continue;
3948 }
3949
3950 // Otherwise, use InIdx + VecSize
3951 unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue();
3952 BuildVecIndices.push_back(DAG.getConstant(Idx+NumInScalars,
3953 TLI.getPointerTy()));
3954 }
3955
3956 // Add count and size info.
3957 MVT::ValueType BuildVecVT =
3958 MVT::getVectorType(TLI.getPointerTy(), NumElts);
3959
3960 // Return the new VECTOR_SHUFFLE node.
3961 SDOperand Ops[5];
3962 Ops[0] = VecIn1;
3963 if (VecIn2.Val) {
3964 Ops[1] = VecIn2;
3965 } else {
3966 // Use an undef build_vector as input for the second operand.
3967 std::vector<SDOperand> UnOps(NumInScalars,
3968 DAG.getNode(ISD::UNDEF,
3969 EltType));
3970 Ops[1] = DAG.getNode(ISD::BUILD_VECTOR, VT,
3971 &UnOps[0], UnOps.size());
3972 AddToWorkList(Ops[1].Val);
3973 }
3974 Ops[2] = DAG.getNode(ISD::BUILD_VECTOR, BuildVecVT,
3975 &BuildVecIndices[0], BuildVecIndices.size());
3976 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Ops, 3);
3977 }
3978
3979 return SDOperand();
3980}
3981
3982SDOperand DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
3983 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
3984 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
3985 // inputs come from at most two distinct vectors, turn this into a shuffle
3986 // node.
3987
3988 // If we only have one input vector, we don't need to do any concatenation.
3989 if (N->getNumOperands() == 1) {
3990 return N->getOperand(0);
3991 }
3992
3993 return SDOperand();
3994}
3995
3996SDOperand DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
3997 SDOperand ShufMask = N->getOperand(2);
3998 unsigned NumElts = ShufMask.getNumOperands();
3999
4000 // If the shuffle mask is an identity operation on the LHS, return the LHS.
4001 bool isIdentity = true;
4002 for (unsigned i = 0; i != NumElts; ++i) {
4003 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4004 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
4005 isIdentity = false;
4006 break;
4007 }
4008 }
4009 if (isIdentity) return N->getOperand(0);
4010
4011 // If the shuffle mask is an identity operation on the RHS, return the RHS.
4012 isIdentity = true;
4013 for (unsigned i = 0; i != NumElts; ++i) {
4014 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4015 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
4016 isIdentity = false;
4017 break;
4018 }
4019 }
4020 if (isIdentity) return N->getOperand(1);
4021
4022 // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
4023 // needed at all.
4024 bool isUnary = true;
4025 bool isSplat = true;
4026 int VecNum = -1;
4027 unsigned BaseIdx = 0;
4028 for (unsigned i = 0; i != NumElts; ++i)
4029 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
4030 unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
4031 int V = (Idx < NumElts) ? 0 : 1;
4032 if (VecNum == -1) {
4033 VecNum = V;
4034 BaseIdx = Idx;
4035 } else {
4036 if (BaseIdx != Idx)
4037 isSplat = false;
4038 if (VecNum != V) {
4039 isUnary = false;
4040 break;
4041 }
4042 }
4043 }
4044
4045 SDOperand N0 = N->getOperand(0);
4046 SDOperand N1 = N->getOperand(1);
4047 // Normalize unary shuffle so the RHS is undef.
4048 if (isUnary && VecNum == 1)
4049 std::swap(N0, N1);
4050
4051 // If it is a splat, check if the argument vector is a build_vector with
4052 // all scalar elements the same.
4053 if (isSplat) {
4054 SDNode *V = N0.Val;
4055
4056 // If this is a bit convert that changes the element type of the vector but
4057 // not the number of vector elements, look through it. Be careful not to
4058 // look though conversions that change things like v4f32 to v2f64.
4059 if (V->getOpcode() == ISD::BIT_CONVERT) {
4060 SDOperand ConvInput = V->getOperand(0);
4061 if (MVT::getVectorNumElements(ConvInput.getValueType()) == NumElts)
4062 V = ConvInput.Val;
4063 }
4064
4065 if (V->getOpcode() == ISD::BUILD_VECTOR) {
4066 unsigned NumElems = V->getNumOperands();
4067 if (NumElems > BaseIdx) {
4068 SDOperand Base;
4069 bool AllSame = true;
4070 for (unsigned i = 0; i != NumElems; ++i) {
4071 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
4072 Base = V->getOperand(i);
4073 break;
4074 }
4075 }
4076 // Splat of <u, u, u, u>, return <u, u, u, u>
4077 if (!Base.Val)
4078 return N0;
4079 for (unsigned i = 0; i != NumElems; ++i) {
4080 if (V->getOperand(i).getOpcode() != ISD::UNDEF &&
4081 V->getOperand(i) != Base) {
4082 AllSame = false;
4083 break;
4084 }
4085 }
4086 // Splat of <x, x, x, x>, return <x, x, x, x>
4087 if (AllSame)
4088 return N0;
4089 }
4090 }
4091 }
4092
4093 // If it is a unary or the LHS and the RHS are the same node, turn the RHS
4094 // into an undef.
4095 if (isUnary || N0 == N1) {
4096 // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
4097 // first operand.
4098 SmallVector<SDOperand, 8> MappedOps;
4099 for (unsigned i = 0; i != NumElts; ++i) {
4100 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
4101 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
4102 MappedOps.push_back(ShufMask.getOperand(i));
4103 } else {
4104 unsigned NewIdx =
4105 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
4106 MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
4107 }
4108 }
4109 ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
4110 &MappedOps[0], MappedOps.size());
4111 AddToWorkList(ShufMask.Val);
4112 return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
4113 N0,
4114 DAG.getNode(ISD::UNDEF, N->getValueType(0)),
4115 ShufMask);
4116 }
4117
4118 return SDOperand();
4119}
4120
4121/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
4122/// an AND to a vector_shuffle with the destination vector and a zero vector.
4123/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
4124/// vector_shuffle V, Zero, <0, 4, 2, 4>
4125SDOperand DAGCombiner::XformToShuffleWithZero(SDNode *N) {
4126 SDOperand LHS = N->getOperand(0);
4127 SDOperand RHS = N->getOperand(1);
4128 if (N->getOpcode() == ISD::AND) {
4129 if (RHS.getOpcode() == ISD::BIT_CONVERT)
4130 RHS = RHS.getOperand(0);
4131 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
4132 std::vector<SDOperand> IdxOps;
4133 unsigned NumOps = RHS.getNumOperands();
4134 unsigned NumElts = NumOps;
4135 MVT::ValueType EVT = MVT::getVectorElementType(RHS.getValueType());
4136 for (unsigned i = 0; i != NumElts; ++i) {
4137 SDOperand Elt = RHS.getOperand(i);
4138 if (!isa<ConstantSDNode>(Elt))
4139 return SDOperand();
4140 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
4141 IdxOps.push_back(DAG.getConstant(i, EVT));
4142 else if (cast<ConstantSDNode>(Elt)->isNullValue())
4143 IdxOps.push_back(DAG.getConstant(NumElts, EVT));
4144 else
4145 return SDOperand();
4146 }
4147
4148 // Let's see if the target supports this vector_shuffle.
4149 if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG))
4150 return SDOperand();
4151
4152 // Return the new VECTOR_SHUFFLE node.
4153 MVT::ValueType VT = MVT::getVectorType(EVT, NumElts);
4154 std::vector<SDOperand> Ops;
4155 LHS = DAG.getNode(ISD::BIT_CONVERT, VT, LHS);
4156 Ops.push_back(LHS);
4157 AddToWorkList(LHS.Val);
4158 std::vector<SDOperand> ZeroOps(NumElts, DAG.getConstant(0, EVT));
4159 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
4160 &ZeroOps[0], ZeroOps.size()));
4161 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
4162 &IdxOps[0], IdxOps.size()));
4163 SDOperand Result = DAG.getNode(ISD::VECTOR_SHUFFLE, VT,
4164 &Ops[0], Ops.size());
4165 if (VT != LHS.getValueType()) {
4166 Result = DAG.getNode(ISD::BIT_CONVERT, LHS.getValueType(), Result);
4167 }
4168 return Result;
4169 }
4170 }
4171 return SDOperand();
4172}
4173
4174/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
4175SDOperand DAGCombiner::SimplifyVBinOp(SDNode *N) {
4176 // After legalize, the target may be depending on adds and other
4177 // binary ops to provide legal ways to construct constants or other
4178 // things. Simplifying them may result in a loss of legality.
4179 if (AfterLegalize) return SDOperand();
4180
4181 MVT::ValueType VT = N->getValueType(0);
4182 assert(MVT::isVector(VT) && "SimplifyVBinOp only works on vectors!");
4183
4184 MVT::ValueType EltType = MVT::getVectorElementType(VT);
4185 SDOperand LHS = N->getOperand(0);
4186 SDOperand RHS = N->getOperand(1);
4187 SDOperand Shuffle = XformToShuffleWithZero(N);
4188 if (Shuffle.Val) return Shuffle;
4189
4190 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
4191 // this operation.
4192 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
4193 RHS.getOpcode() == ISD::BUILD_VECTOR) {
4194 SmallVector<SDOperand, 8> Ops;
4195 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
4196 SDOperand LHSOp = LHS.getOperand(i);
4197 SDOperand RHSOp = RHS.getOperand(i);
4198 // If these two elements can't be folded, bail out.
4199 if ((LHSOp.getOpcode() != ISD::UNDEF &&
4200 LHSOp.getOpcode() != ISD::Constant &&
4201 LHSOp.getOpcode() != ISD::ConstantFP) ||
4202 (RHSOp.getOpcode() != ISD::UNDEF &&
4203 RHSOp.getOpcode() != ISD::Constant &&
4204 RHSOp.getOpcode() != ISD::ConstantFP))
4205 break;
4206 // Can't fold divide by zero.
4207 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
4208 N->getOpcode() == ISD::FDIV) {
4209 if ((RHSOp.getOpcode() == ISD::Constant &&
4210 cast<ConstantSDNode>(RHSOp.Val)->isNullValue()) ||
4211 (RHSOp.getOpcode() == ISD::ConstantFP &&
Dale Johannesen7604c1b2007-08-31 23:34:27 +00004212 cast<ConstantFPSDNode>(RHSOp.Val)->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004213 break;
4214 }
4215 Ops.push_back(DAG.getNode(N->getOpcode(), EltType, LHSOp, RHSOp));
4216 AddToWorkList(Ops.back().Val);
4217 assert((Ops.back().getOpcode() == ISD::UNDEF ||
4218 Ops.back().getOpcode() == ISD::Constant ||
4219 Ops.back().getOpcode() == ISD::ConstantFP) &&
4220 "Scalar binop didn't fold!");
4221 }
4222
4223 if (Ops.size() == LHS.getNumOperands()) {
4224 MVT::ValueType VT = LHS.getValueType();
4225 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
4226 }
4227 }
4228
4229 return SDOperand();
4230}
4231
4232SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
4233 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
4234
4235 SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
4236 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4237 // If we got a simplified select_cc node back from SimplifySelectCC, then
4238 // break it down into a new SETCC node, and a new SELECT node, and then return
4239 // the SELECT node, since we were called with a SELECT node.
4240 if (SCC.Val) {
4241 // Check to see if we got a select_cc back (to turn into setcc/select).
4242 // Otherwise, just return whatever node we got back, like fabs.
4243 if (SCC.getOpcode() == ISD::SELECT_CC) {
4244 SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
4245 SCC.getOperand(0), SCC.getOperand(1),
4246 SCC.getOperand(4));
4247 AddToWorkList(SETCC.Val);
4248 return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
4249 SCC.getOperand(3), SETCC);
4250 }
4251 return SCC;
4252 }
4253 return SDOperand();
4254}
4255
4256/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
4257/// are the two values being selected between, see if we can simplify the
4258/// select. Callers of this should assume that TheSelect is deleted if this
4259/// returns true. As such, they should return the appropriate thing (e.g. the
4260/// node) back to the top-level of the DAG combiner loop to avoid it being
4261/// looked at.
4262///
4263bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
4264 SDOperand RHS) {
4265
4266 // If this is a select from two identical things, try to pull the operation
4267 // through the select.
4268 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
4269 // If this is a load and the token chain is identical, replace the select
4270 // of two loads with a load through a select of the address to load from.
4271 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
4272 // constants have been dropped into the constant pool.
4273 if (LHS.getOpcode() == ISD::LOAD &&
4274 // Token chains must be identical.
4275 LHS.getOperand(0) == RHS.getOperand(0)) {
4276 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
4277 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
4278
4279 // If this is an EXTLOAD, the VT's must match.
4280 if (LLD->getLoadedVT() == RLD->getLoadedVT()) {
4281 // FIXME: this conflates two src values, discarding one. This is not
4282 // the right thing to do, but nothing uses srcvalues now. When they do,
4283 // turn SrcValue into a list of locations.
4284 SDOperand Addr;
4285 if (TheSelect->getOpcode() == ISD::SELECT) {
4286 // Check that the condition doesn't reach either load. If so, folding
4287 // this will induce a cycle into the DAG.
4288 if (!LLD->isPredecessor(TheSelect->getOperand(0).Val) &&
4289 !RLD->isPredecessor(TheSelect->getOperand(0).Val)) {
4290 Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
4291 TheSelect->getOperand(0), LLD->getBasePtr(),
4292 RLD->getBasePtr());
4293 }
4294 } else {
4295 // Check that the condition doesn't reach either load. If so, folding
4296 // this will induce a cycle into the DAG.
4297 if (!LLD->isPredecessor(TheSelect->getOperand(0).Val) &&
4298 !RLD->isPredecessor(TheSelect->getOperand(0).Val) &&
4299 !LLD->isPredecessor(TheSelect->getOperand(1).Val) &&
4300 !RLD->isPredecessor(TheSelect->getOperand(1).Val)) {
4301 Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
4302 TheSelect->getOperand(0),
4303 TheSelect->getOperand(1),
4304 LLD->getBasePtr(), RLD->getBasePtr(),
4305 TheSelect->getOperand(4));
4306 }
4307 }
4308
4309 if (Addr.Val) {
4310 SDOperand Load;
4311 if (LLD->getExtensionType() == ISD::NON_EXTLOAD)
4312 Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(),
4313 Addr,LLD->getSrcValue(),
4314 LLD->getSrcValueOffset(),
4315 LLD->isVolatile(),
4316 LLD->getAlignment());
4317 else {
4318 Load = DAG.getExtLoad(LLD->getExtensionType(),
4319 TheSelect->getValueType(0),
4320 LLD->getChain(), Addr, LLD->getSrcValue(),
4321 LLD->getSrcValueOffset(),
4322 LLD->getLoadedVT(),
4323 LLD->isVolatile(),
4324 LLD->getAlignment());
4325 }
4326 // Users of the select now use the result of the load.
4327 CombineTo(TheSelect, Load);
4328
4329 // Users of the old loads now use the new load's chain. We know the
4330 // old-load value is dead now.
4331 CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
4332 CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
4333 return true;
4334 }
4335 }
4336 }
4337 }
4338
4339 return false;
4340}
4341
4342SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
4343 SDOperand N2, SDOperand N3,
4344 ISD::CondCode CC, bool NotExtCompare) {
4345
4346 MVT::ValueType VT = N2.getValueType();
4347 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
4348 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
4349 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
4350
4351 // Determine if the condition we're dealing with is constant
4352 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
4353 if (SCC.Val) AddToWorkList(SCC.Val);
4354 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
4355
4356 // fold select_cc true, x, y -> x
4357 if (SCCC && SCCC->getValue())
4358 return N2;
4359 // fold select_cc false, x, y -> y
4360 if (SCCC && SCCC->getValue() == 0)
4361 return N3;
4362
4363 // Check to see if we can simplify the select into an fabs node
4364 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
4365 // Allow either -0.0 or 0.0
Dale Johannesen7f2c1d12007-08-25 22:10:57 +00004366 if (CFP->getValueAPF().isZero()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004367 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
4368 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
4369 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
4370 N2 == N3.getOperand(0))
4371 return DAG.getNode(ISD::FABS, VT, N0);
4372
4373 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
4374 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
4375 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
4376 N2.getOperand(0) == N3)
4377 return DAG.getNode(ISD::FABS, VT, N3);
4378 }
4379 }
4380
4381 // Check to see if we can perform the "gzip trick", transforming
4382 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
4383 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
4384 MVT::isInteger(N0.getValueType()) &&
4385 MVT::isInteger(N2.getValueType()) &&
4386 (N1C->isNullValue() || // (a < 0) ? b : 0
4387 (N1C->getValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
4388 MVT::ValueType XType = N0.getValueType();
4389 MVT::ValueType AType = N2.getValueType();
4390 if (XType >= AType) {
4391 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
4392 // single-bit constant.
4393 if (N2C && ((N2C->getValue() & (N2C->getValue()-1)) == 0)) {
4394 unsigned ShCtV = Log2_64(N2C->getValue());
4395 ShCtV = MVT::getSizeInBits(XType)-ShCtV-1;
4396 SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
4397 SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
4398 AddToWorkList(Shift.Val);
4399 if (XType > AType) {
4400 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
4401 AddToWorkList(Shift.Val);
4402 }
4403 return DAG.getNode(ISD::AND, AType, Shift, N2);
4404 }
4405 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
4406 DAG.getConstant(MVT::getSizeInBits(XType)-1,
4407 TLI.getShiftAmountTy()));
4408 AddToWorkList(Shift.Val);
4409 if (XType > AType) {
4410 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
4411 AddToWorkList(Shift.Val);
4412 }
4413 return DAG.getNode(ISD::AND, AType, Shift, N2);
4414 }
4415 }
4416
4417 // fold select C, 16, 0 -> shl C, 4
4418 if (N2C && N3C && N3C->isNullValue() && isPowerOf2_64(N2C->getValue()) &&
4419 TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
4420
4421 // If the caller doesn't want us to simplify this into a zext of a compare,
4422 // don't do it.
4423 if (NotExtCompare && N2C->getValue() == 1)
4424 return SDOperand();
4425
4426 // Get a SetCC of the condition
4427 // FIXME: Should probably make sure that setcc is legal if we ever have a
4428 // target where it isn't.
4429 SDOperand Temp, SCC;
4430 // cast from setcc result type to select result type
4431 if (AfterLegalize) {
4432 SCC = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
4433 if (N2.getValueType() < SCC.getValueType())
4434 Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
4435 else
4436 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
4437 } else {
4438 SCC = DAG.getSetCC(MVT::i1, N0, N1, CC);
4439 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
4440 }
4441 AddToWorkList(SCC.Val);
4442 AddToWorkList(Temp.Val);
4443
4444 if (N2C->getValue() == 1)
4445 return Temp;
4446 // shl setcc result by log2 n2c
4447 return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
4448 DAG.getConstant(Log2_64(N2C->getValue()),
4449 TLI.getShiftAmountTy()));
4450 }
4451
4452 // Check to see if this is the equivalent of setcc
4453 // FIXME: Turn all of these into setcc if setcc if setcc is legal
4454 // otherwise, go ahead with the folds.
4455 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getValue() == 1ULL)) {
4456 MVT::ValueType XType = N0.getValueType();
4457 if (TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultTy())) {
4458 SDOperand Res = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
4459 if (Res.getValueType() != VT)
4460 Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
4461 return Res;
4462 }
4463
4464 // seteq X, 0 -> srl (ctlz X, log2(size(X)))
4465 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
4466 TLI.isOperationLegal(ISD::CTLZ, XType)) {
4467 SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
4468 return DAG.getNode(ISD::SRL, XType, Ctlz,
4469 DAG.getConstant(Log2_32(MVT::getSizeInBits(XType)),
4470 TLI.getShiftAmountTy()));
4471 }
4472 // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
4473 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
4474 SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
4475 N0);
4476 SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0,
4477 DAG.getConstant(~0ULL, XType));
4478 return DAG.getNode(ISD::SRL, XType,
4479 DAG.getNode(ISD::AND, XType, NegN0, NotN0),
4480 DAG.getConstant(MVT::getSizeInBits(XType)-1,
4481 TLI.getShiftAmountTy()));
4482 }
4483 // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
4484 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
4485 SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
4486 DAG.getConstant(MVT::getSizeInBits(XType)-1,
4487 TLI.getShiftAmountTy()));
4488 return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
4489 }
4490 }
4491
4492 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
4493 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4494 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
4495 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
4496 N2.getOperand(0) == N1 && MVT::isInteger(N0.getValueType())) {
4497 MVT::ValueType XType = N0.getValueType();
4498 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
4499 DAG.getConstant(MVT::getSizeInBits(XType)-1,
4500 TLI.getShiftAmountTy()));
4501 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
4502 AddToWorkList(Shift.Val);
4503 AddToWorkList(Add.Val);
4504 return DAG.getNode(ISD::XOR, XType, Add, Shift);
4505 }
4506 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
4507 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4508 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
4509 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
4510 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
4511 MVT::ValueType XType = N0.getValueType();
4512 if (SubC->isNullValue() && MVT::isInteger(XType)) {
4513 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
4514 DAG.getConstant(MVT::getSizeInBits(XType)-1,
4515 TLI.getShiftAmountTy()));
4516 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
4517 AddToWorkList(Shift.Val);
4518 AddToWorkList(Add.Val);
4519 return DAG.getNode(ISD::XOR, XType, Add, Shift);
4520 }
4521 }
4522 }
4523
4524 return SDOperand();
4525}
4526
4527/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
4528SDOperand DAGCombiner::SimplifySetCC(MVT::ValueType VT, SDOperand N0,
4529 SDOperand N1, ISD::CondCode Cond,
4530 bool foldBooleans) {
4531 TargetLowering::DAGCombinerInfo
4532 DagCombineInfo(DAG, !AfterLegalize, false, this);
4533 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo);
4534}
4535
4536/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
4537/// return a DAG expression to select that will generate the same value by
4538/// multiplying by a magic number. See:
4539/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
4540SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
4541 std::vector<SDNode*> Built;
4542 SDOperand S = TLI.BuildSDIV(N, DAG, &Built);
4543
4544 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
4545 ii != ee; ++ii)
4546 AddToWorkList(*ii);
4547 return S;
4548}
4549
4550/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
4551/// return a DAG expression to select that will generate the same value by
4552/// multiplying by a magic number. See:
4553/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
4554SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
4555 std::vector<SDNode*> Built;
4556 SDOperand S = TLI.BuildUDIV(N, DAG, &Built);
4557
4558 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
4559 ii != ee; ++ii)
4560 AddToWorkList(*ii);
4561 return S;
4562}
4563
4564/// FindBaseOffset - Return true if base is known not to alias with anything
4565/// but itself. Provides base object and offset as results.
4566static bool FindBaseOffset(SDOperand Ptr, SDOperand &Base, int64_t &Offset) {
4567 // Assume it is a primitive operation.
4568 Base = Ptr; Offset = 0;
4569
4570 // If it's an adding a simple constant then integrate the offset.
4571 if (Base.getOpcode() == ISD::ADD) {
4572 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
4573 Base = Base.getOperand(0);
4574 Offset += C->getValue();
4575 }
4576 }
4577
4578 // If it's any of the following then it can't alias with anything but itself.
4579 return isa<FrameIndexSDNode>(Base) ||
4580 isa<ConstantPoolSDNode>(Base) ||
4581 isa<GlobalAddressSDNode>(Base);
4582}
4583
4584/// isAlias - Return true if there is any possibility that the two addresses
4585/// overlap.
4586bool DAGCombiner::isAlias(SDOperand Ptr1, int64_t Size1,
4587 const Value *SrcValue1, int SrcValueOffset1,
4588 SDOperand Ptr2, int64_t Size2,
4589 const Value *SrcValue2, int SrcValueOffset2)
4590{
4591 // If they are the same then they must be aliases.
4592 if (Ptr1 == Ptr2) return true;
4593
4594 // Gather base node and offset information.
4595 SDOperand Base1, Base2;
4596 int64_t Offset1, Offset2;
4597 bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
4598 bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
4599
4600 // If they have a same base address then...
4601 if (Base1 == Base2) {
4602 // Check to see if the addresses overlap.
4603 return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
4604 }
4605
4606 // If we know both bases then they can't alias.
4607 if (KnownBase1 && KnownBase2) return false;
4608
4609 if (CombinerGlobalAA) {
4610 // Use alias analysis information.
Dan Gohmane142c2e2007-08-27 16:32:11 +00004611 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
4612 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
4613 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004614 AliasAnalysis::AliasResult AAResult =
4615 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
4616 if (AAResult == AliasAnalysis::NoAlias)
4617 return false;
4618 }
4619
4620 // Otherwise we have to assume they alias.
4621 return true;
4622}
4623
4624/// FindAliasInfo - Extracts the relevant alias information from the memory
4625/// node. Returns true if the operand was a load.
4626bool DAGCombiner::FindAliasInfo(SDNode *N,
4627 SDOperand &Ptr, int64_t &Size,
4628 const Value *&SrcValue, int &SrcValueOffset) {
4629 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4630 Ptr = LD->getBasePtr();
4631 Size = MVT::getSizeInBits(LD->getLoadedVT()) >> 3;
4632 SrcValue = LD->getSrcValue();
4633 SrcValueOffset = LD->getSrcValueOffset();
4634 return true;
4635 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4636 Ptr = ST->getBasePtr();
4637 Size = MVT::getSizeInBits(ST->getStoredVT()) >> 3;
4638 SrcValue = ST->getSrcValue();
4639 SrcValueOffset = ST->getSrcValueOffset();
4640 } else {
4641 assert(0 && "FindAliasInfo expected a memory operand");
4642 }
4643
4644 return false;
4645}
4646
4647/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
4648/// looking for aliasing nodes and adding them to the Aliases vector.
4649void DAGCombiner::GatherAllAliases(SDNode *N, SDOperand OriginalChain,
4650 SmallVector<SDOperand, 8> &Aliases) {
4651 SmallVector<SDOperand, 8> Chains; // List of chains to visit.
4652 std::set<SDNode *> Visited; // Visited node set.
4653
4654 // Get alias information for node.
4655 SDOperand Ptr;
4656 int64_t Size;
4657 const Value *SrcValue;
4658 int SrcValueOffset;
4659 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
4660
4661 // Starting off.
4662 Chains.push_back(OriginalChain);
4663
4664 // Look at each chain and determine if it is an alias. If so, add it to the
4665 // aliases list. If not, then continue up the chain looking for the next
4666 // candidate.
4667 while (!Chains.empty()) {
4668 SDOperand Chain = Chains.back();
4669 Chains.pop_back();
4670
4671 // Don't bother if we've been before.
4672 if (Visited.find(Chain.Val) != Visited.end()) continue;
4673 Visited.insert(Chain.Val);
4674
4675 switch (Chain.getOpcode()) {
4676 case ISD::EntryToken:
4677 // Entry token is ideal chain operand, but handled in FindBetterChain.
4678 break;
4679
4680 case ISD::LOAD:
4681 case ISD::STORE: {
4682 // Get alias information for Chain.
4683 SDOperand OpPtr;
4684 int64_t OpSize;
4685 const Value *OpSrcValue;
4686 int OpSrcValueOffset;
4687 bool IsOpLoad = FindAliasInfo(Chain.Val, OpPtr, OpSize,
4688 OpSrcValue, OpSrcValueOffset);
4689
4690 // If chain is alias then stop here.
4691 if (!(IsLoad && IsOpLoad) &&
4692 isAlias(Ptr, Size, SrcValue, SrcValueOffset,
4693 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
4694 Aliases.push_back(Chain);
4695 } else {
4696 // Look further up the chain.
4697 Chains.push_back(Chain.getOperand(0));
4698 // Clean up old chain.
4699 AddToWorkList(Chain.Val);
4700 }
4701 break;
4702 }
4703
4704 case ISD::TokenFactor:
4705 // We have to check each of the operands of the token factor, so we queue
4706 // then up. Adding the operands to the queue (stack) in reverse order
4707 // maintains the original order and increases the likelihood that getNode
4708 // will find a matching token factor (CSE.)
4709 for (unsigned n = Chain.getNumOperands(); n;)
4710 Chains.push_back(Chain.getOperand(--n));
4711 // Eliminate the token factor if we can.
4712 AddToWorkList(Chain.Val);
4713 break;
4714
4715 default:
4716 // For all other instructions we will just have to take what we can get.
4717 Aliases.push_back(Chain);
4718 break;
4719 }
4720 }
4721}
4722
4723/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
4724/// for a better chain (aliasing node.)
4725SDOperand DAGCombiner::FindBetterChain(SDNode *N, SDOperand OldChain) {
4726 SmallVector<SDOperand, 8> Aliases; // Ops for replacing token factor.
4727
4728 // Accumulate all the aliases to this node.
4729 GatherAllAliases(N, OldChain, Aliases);
4730
4731 if (Aliases.size() == 0) {
4732 // If no operands then chain to entry token.
4733 return DAG.getEntryNode();
4734 } else if (Aliases.size() == 1) {
4735 // If a single operand then chain to it. We don't need to revisit it.
4736 return Aliases[0];
4737 }
4738
4739 // Construct a custom tailored token factor.
4740 SDOperand NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4741 &Aliases[0], Aliases.size());
4742
4743 // Make sure the old chain gets cleaned up.
4744 if (NewChain != OldChain) AddToWorkList(OldChain.Val);
4745
4746 return NewChain;
4747}
4748
4749// SelectionDAG::Combine - This is the entry point for the file.
4750//
4751void SelectionDAG::Combine(bool RunningAfterLegalize, AliasAnalysis &AA) {
4752 if (!RunningAfterLegalize && ViewDAGCombine1)
4753 viewGraph();
4754 if (RunningAfterLegalize && ViewDAGCombine2)
4755 viewGraph();
4756 /// run - This is the main entry point to this class.
4757 ///
4758 DAGCombiner(*this, AA).Run(RunningAfterLegalize);
4759}