blob: 817b62588dbeddb76cbd21ab15e1710a89d7cc23 [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//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "dagcombine"
16#include "llvm/CodeGen/SelectionDAG.h"
Chris Lattner4e137af2008-01-25 07:20:16 +000017#include "llvm/CodeGen/MachineFunction.h"
18#include "llvm/CodeGen/MachineFrameInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000019#include "llvm/Analysis/AliasAnalysis.h"
20#include "llvm/Target/TargetData.h"
Chris Lattner1e3362f2008-01-26 19:45:50 +000021#include "llvm/Target/TargetFrameInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000022#include "llvm/Target/TargetLowering.h"
23#include "llvm/Target/TargetMachine.h"
24#include "llvm/Target/TargetOptions.h"
25#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/Support/Compiler.h"
28#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/Support/MathExtras.h"
31#include <algorithm>
Dan Gohmand408d392008-05-23 20:40:06 +000032#include <set>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033using namespace llvm;
34
35STATISTIC(NodesCombined , "Number of dag nodes combined");
36STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
37STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
38
39namespace {
40#ifndef NDEBUG
41 static cl::opt<bool>
42 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
43 cl::desc("Pop up a window to show dags before the first "
44 "dag combine pass"));
45 static cl::opt<bool>
46 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
47 cl::desc("Pop up a window to show dags before the second "
48 "dag combine pass"));
49#else
50 static const bool ViewDAGCombine1 = false;
51 static const bool ViewDAGCombine2 = false;
52#endif
53
54 static cl::opt<bool>
55 CombinerAA("combiner-alias-analysis", cl::Hidden,
56 cl::desc("Turn on alias analysis during testing"));
57
58 static cl::opt<bool>
59 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
60 cl::desc("Include global information in alias analysis"));
61
62//------------------------------ DAGCombiner ---------------------------------//
63
64 class VISIBILITY_HIDDEN DAGCombiner {
65 SelectionDAG &DAG;
66 TargetLowering &TLI;
67 bool AfterLegalize;
68
69 // Worklist of all of the nodes that need to be simplified.
70 std::vector<SDNode*> WorkList;
71
72 // AA - Used for DAG load/store alias analysis.
73 AliasAnalysis &AA;
74
75 /// AddUsersToWorkList - When an instruction is simplified, add all users of
76 /// the instruction to the work lists because they might get more simplified
77 /// now.
78 ///
79 void AddUsersToWorkList(SDNode *N) {
80 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
81 UI != UE; ++UI)
Roman Levenstein05650fd2008-04-07 10:06:32 +000082 AddToWorkList(UI->getUser());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083 }
84
Dan Gohman6c89ea72007-10-08 17:57:15 +000085 /// visit - call the node-specific routine that knows how to fold each
86 /// particular type of node.
87 SDOperand visit(SDNode *N);
88
Dan Gohmanf17a25c2007-07-18 16:29:46 +000089 public:
90 /// AddToWorkList - Add to the work list making sure it's instance is at the
91 /// the back (next to be processed.)
92 void AddToWorkList(SDNode *N) {
93 removeFromWorkList(N);
94 WorkList.push_back(N);
95 }
96
Chris Lattner7bcb18f2008-02-03 06:49:24 +000097 /// 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());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000102 }
103
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000104 SDOperand CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
105 bool AddTo = true);
106
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107 SDOperand CombineTo(SDNode *N, SDOperand Res, bool AddTo = true) {
108 return CombineTo(N, &Res, 1, AddTo);
109 }
110
111 SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1,
112 bool AddTo = true) {
113 SDOperand To[] = { Res0, Res1 };
114 return CombineTo(N, To, 2, AddTo);
115 }
Chris Lattner5872a362008-01-17 07:00:52 +0000116
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000117 private:
118
119 /// SimplifyDemandedBits - Check the specified integer node value to see if
120 /// it can be simplified or if things it uses can be simplified by bit
121 /// propagation. If so, return true.
Dan Gohman11607792008-02-27 00:25:32 +0000122 bool SimplifyDemandedBits(SDOperand Op) {
123 APInt Demanded = APInt::getAllOnesValue(Op.getValueSizeInBits());
124 return SimplifyDemandedBits(Op, Demanded);
125 }
126
127 bool SimplifyDemandedBits(SDOperand Op, const APInt &Demanded);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000128
129 bool CombineToPreIndexedLoadStore(SDNode *N);
130 bool CombineToPostIndexedLoadStore(SDNode *N);
131
132
Dan Gohman6c89ea72007-10-08 17:57:15 +0000133 /// combine - call the node-specific routine that knows how to fold each
134 /// particular type of node. If that doesn't do anything, try the
135 /// target-specific DAG combines.
136 SDOperand combine(SDNode *N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000137
138 // Visitation implementation - Implement dag node combining for different
139 // node types. The semantics are as follows:
140 // Return Value:
141 // SDOperand.Val == 0 - No change was made
142 // SDOperand.Val == N - N was replaced, is dead, and is already handled.
143 // otherwise - N should be replaced by the returned Operand.
144 //
145 SDOperand visitTokenFactor(SDNode *N);
Chris Lattnerf32fa7f2008-02-13 07:25:05 +0000146 SDOperand visitMERGE_VALUES(SDNode *N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000147 SDOperand visitADD(SDNode *N);
148 SDOperand visitSUB(SDNode *N);
149 SDOperand visitADDC(SDNode *N);
150 SDOperand visitADDE(SDNode *N);
151 SDOperand visitMUL(SDNode *N);
152 SDOperand visitSDIV(SDNode *N);
153 SDOperand visitUDIV(SDNode *N);
154 SDOperand visitSREM(SDNode *N);
155 SDOperand visitUREM(SDNode *N);
156 SDOperand visitMULHU(SDNode *N);
157 SDOperand visitMULHS(SDNode *N);
Dan Gohman6c89ea72007-10-08 17:57:15 +0000158 SDOperand visitSMUL_LOHI(SDNode *N);
159 SDOperand visitUMUL_LOHI(SDNode *N);
160 SDOperand visitSDIVREM(SDNode *N);
161 SDOperand visitUDIVREM(SDNode *N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000162 SDOperand visitAND(SDNode *N);
163 SDOperand visitOR(SDNode *N);
164 SDOperand visitXOR(SDNode *N);
165 SDOperand SimplifyVBinOp(SDNode *N);
166 SDOperand visitSHL(SDNode *N);
167 SDOperand visitSRA(SDNode *N);
168 SDOperand visitSRL(SDNode *N);
169 SDOperand visitCTLZ(SDNode *N);
170 SDOperand visitCTTZ(SDNode *N);
171 SDOperand visitCTPOP(SDNode *N);
172 SDOperand visitSELECT(SDNode *N);
173 SDOperand visitSELECT_CC(SDNode *N);
174 SDOperand visitSETCC(SDNode *N);
175 SDOperand visitSIGN_EXTEND(SDNode *N);
176 SDOperand visitZERO_EXTEND(SDNode *N);
177 SDOperand visitANY_EXTEND(SDNode *N);
178 SDOperand visitSIGN_EXTEND_INREG(SDNode *N);
179 SDOperand visitTRUNCATE(SDNode *N);
180 SDOperand visitBIT_CONVERT(SDNode *N);
Evan Chengb6290462008-05-12 23:04:07 +0000181 SDOperand visitBUILD_PAIR(SDNode *N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000182 SDOperand visitFADD(SDNode *N);
183 SDOperand visitFSUB(SDNode *N);
184 SDOperand visitFMUL(SDNode *N);
185 SDOperand visitFDIV(SDNode *N);
186 SDOperand visitFREM(SDNode *N);
187 SDOperand visitFCOPYSIGN(SDNode *N);
188 SDOperand visitSINT_TO_FP(SDNode *N);
189 SDOperand visitUINT_TO_FP(SDNode *N);
190 SDOperand visitFP_TO_SINT(SDNode *N);
191 SDOperand visitFP_TO_UINT(SDNode *N);
192 SDOperand visitFP_ROUND(SDNode *N);
193 SDOperand visitFP_ROUND_INREG(SDNode *N);
194 SDOperand visitFP_EXTEND(SDNode *N);
195 SDOperand visitFNEG(SDNode *N);
196 SDOperand visitFABS(SDNode *N);
197 SDOperand visitBRCOND(SDNode *N);
198 SDOperand visitBR_CC(SDNode *N);
199 SDOperand visitLOAD(SDNode *N);
200 SDOperand visitSTORE(SDNode *N);
201 SDOperand visitINSERT_VECTOR_ELT(SDNode *N);
Evan Chengd7ba7ed2007-10-06 08:19:55 +0000202 SDOperand visitEXTRACT_VECTOR_ELT(SDNode *N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000203 SDOperand visitBUILD_VECTOR(SDNode *N);
204 SDOperand visitCONCAT_VECTORS(SDNode *N);
205 SDOperand visitVECTOR_SHUFFLE(SDNode *N);
206
207 SDOperand XformToShuffleWithZero(SDNode *N);
208 SDOperand ReassociateOps(unsigned Opc, SDOperand LHS, SDOperand RHS);
209
Chris Lattner91ed3c32007-12-06 07:33:36 +0000210 SDOperand visitShiftByConstant(SDNode *N, unsigned Amt);
211
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000212 bool SimplifySelectOps(SDNode *SELECT, SDOperand LHS, SDOperand RHS);
213 SDOperand SimplifyBinOpWithSameOpcodeHands(SDNode *N);
214 SDOperand SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2);
215 SDOperand SimplifySelectCC(SDOperand N0, SDOperand N1, SDOperand N2,
216 SDOperand N3, ISD::CondCode CC,
217 bool NotExtCompare = false);
Duncan Sands92c43912008-06-06 12:08:01 +0000218 SDOperand SimplifySetCC(MVT VT, SDOperand N0, SDOperand N1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219 ISD::CondCode Cond, bool foldBooleans = true);
Chris Lattner4a7c8452008-01-26 01:09:19 +0000220 SDOperand SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
221 unsigned HiOp);
Duncan Sands92c43912008-06-06 12:08:01 +0000222 SDOperand CombineConsecutiveLoads(SDNode *N, MVT VT);
223 SDOperand ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, MVT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000224 SDOperand BuildSDIV(SDNode *N);
225 SDOperand BuildUDIV(SDNode *N);
226 SDNode *MatchRotate(SDOperand LHS, SDOperand RHS);
227 SDOperand ReduceLoadWidth(SDNode *N);
228
Dan Gohman07961cd2008-02-25 21:11:39 +0000229 SDOperand GetDemandedBits(SDOperand V, const APInt &Mask);
Chris Lattnere8671c52007-10-13 06:35:54 +0000230
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
232 /// looking for aliasing nodes and adding them to the Aliases vector.
233 void GatherAllAliases(SDNode *N, SDOperand OriginalChain,
234 SmallVector<SDOperand, 8> &Aliases);
235
236 /// isAlias - Return true if there is any possibility that the two addresses
237 /// overlap.
238 bool isAlias(SDOperand Ptr1, int64_t Size1,
239 const Value *SrcValue1, int SrcValueOffset1,
240 SDOperand Ptr2, int64_t Size2,
241 const Value *SrcValue2, int SrcValueOffset2);
242
243 /// FindAliasInfo - Extracts the relevant alias information from the memory
244 /// node. Returns true if the operand was a load.
245 bool FindAliasInfo(SDNode *N,
246 SDOperand &Ptr, int64_t &Size,
247 const Value *&SrcValue, int &SrcValueOffset);
248
249 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
250 /// looking for a better chain (aliasing node.)
251 SDOperand FindBetterChain(SDNode *N, SDOperand Chain);
252
253public:
254 DAGCombiner(SelectionDAG &D, AliasAnalysis &A)
255 : DAG(D),
256 TLI(D.getTargetLoweringInfo()),
257 AfterLegalize(false),
258 AA(A) {}
259
260 /// Run - runs the dag combiner on all nodes in the work list
261 void Run(bool RunningAfterLegalize);
262 };
263}
264
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000265
266namespace {
267/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
268/// nodes from the worklist.
269class VISIBILITY_HIDDEN WorkListRemover :
270 public SelectionDAG::DAGUpdateListener {
271 DAGCombiner &DC;
272public:
Dan Gohmana789bff2008-02-20 16:44:09 +0000273 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000274
Duncan Sands3866b1c2008-06-11 11:42:12 +0000275 virtual void NodeDeleted(SDNode *N, SDNode *E) {
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000276 DC.removeFromWorkList(N);
277 }
278
279 virtual void NodeUpdated(SDNode *N) {
280 // Ignore updates.
281 }
282};
283}
284
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000285//===----------------------------------------------------------------------===//
286// TargetLowering::DAGCombinerInfo implementation
287//===----------------------------------------------------------------------===//
288
289void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
290 ((DAGCombiner*)DC)->AddToWorkList(N);
291}
292
293SDOperand TargetLowering::DAGCombinerInfo::
294CombineTo(SDNode *N, const std::vector<SDOperand> &To) {
295 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
296}
297
298SDOperand TargetLowering::DAGCombinerInfo::
299CombineTo(SDNode *N, SDOperand Res) {
300 return ((DAGCombiner*)DC)->CombineTo(N, Res);
301}
302
303
304SDOperand TargetLowering::DAGCombinerInfo::
305CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
306 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
307}
308
309
310//===----------------------------------------------------------------------===//
311// Helper Functions
312//===----------------------------------------------------------------------===//
313
314/// isNegatibleForFree - Return 1 if we can compute the negated form of the
315/// specified expression for the same cost as the expression itself, or 2 if we
316/// can compute the negated form more cheaply than the expression itself.
Chris Lattnere0992b82008-02-26 07:04:54 +0000317static char isNegatibleForFree(SDOperand Op, bool AfterLegalize,
318 unsigned Depth = 0) {
Dale Johannesenb89072e2007-10-16 23:38:29 +0000319 // No compile time optimizations on this type.
320 if (Op.getValueType() == MVT::ppcf128)
321 return 0;
322
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000323 // fneg is removable even if it has multiple uses.
324 if (Op.getOpcode() == ISD::FNEG) return 2;
325
326 // Don't allow anything with multiple uses.
327 if (!Op.hasOneUse()) return 0;
328
329 // Don't recurse exponentially.
330 if (Depth > 6) return 0;
331
332 switch (Op.getOpcode()) {
333 default: return false;
334 case ISD::ConstantFP:
Chris Lattnere0992b82008-02-26 07:04:54 +0000335 // Don't invert constant FP values after legalize. The negated constant
336 // isn't necessarily legal.
337 return AfterLegalize ? 0 : 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000338 case ISD::FADD:
339 // FIXME: determine better conditions for this xform.
340 if (!UnsafeFPMath) return 0;
341
342 // -(A+B) -> -A - B
Chris Lattnere0992b82008-02-26 07:04:54 +0000343 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344 return V;
345 // -(A+B) -> -B - A
Chris Lattnere0992b82008-02-26 07:04:54 +0000346 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000347 case ISD::FSUB:
348 // We can't turn -(A-B) into B-A when we honor signed zeros.
349 if (!UnsafeFPMath) return 0;
350
351 // -(A-B) -> B-A
352 return 1;
353
354 case ISD::FMUL:
355 case ISD::FDIV:
356 if (HonorSignDependentRoundingFPMath()) return 0;
357
358 // -(X*Y) -> (-X * Y) or (X*-Y)
Chris Lattnere0992b82008-02-26 07:04:54 +0000359 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000360 return V;
361
Chris Lattnere0992b82008-02-26 07:04:54 +0000362 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000363
364 case ISD::FP_EXTEND:
365 case ISD::FP_ROUND:
366 case ISD::FSIN:
Chris Lattnere0992b82008-02-26 07:04:54 +0000367 return isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000368 }
369}
370
371/// GetNegatedExpression - If isNegatibleForFree returns true, this function
372/// returns the newly negated expression.
373static SDOperand GetNegatedExpression(SDOperand Op, SelectionDAG &DAG,
Chris Lattnere0992b82008-02-26 07:04:54 +0000374 bool AfterLegalize, unsigned Depth = 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000375 // fneg is removable even if it has multiple uses.
376 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
377
378 // Don't allow anything with multiple uses.
379 assert(Op.hasOneUse() && "Unknown reuse!");
380
381 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
382 switch (Op.getOpcode()) {
383 default: assert(0 && "Unknown code");
Dale Johannesen7604c1b2007-08-31 23:34:27 +0000384 case ISD::ConstantFP: {
385 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
386 V.changeSign();
387 return DAG.getConstantFP(V, Op.getValueType());
388 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000389 case ISD::FADD:
390 // FIXME: determine better conditions for this xform.
391 assert(UnsafeFPMath);
392
393 // -(A+B) -> -A - B
Chris Lattnere0992b82008-02-26 07:04:54 +0000394 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000395 return DAG.getNode(ISD::FSUB, Op.getValueType(),
Chris Lattnere0992b82008-02-26 07:04:54 +0000396 GetNegatedExpression(Op.getOperand(0), DAG,
397 AfterLegalize, Depth+1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000398 Op.getOperand(1));
399 // -(A+B) -> -B - A
400 return DAG.getNode(ISD::FSUB, Op.getValueType(),
Chris Lattnere0992b82008-02-26 07:04:54 +0000401 GetNegatedExpression(Op.getOperand(1), DAG,
402 AfterLegalize, Depth+1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000403 Op.getOperand(0));
404 case ISD::FSUB:
405 // We can't turn -(A-B) into B-A when we honor signed zeros.
406 assert(UnsafeFPMath);
407
408 // -(0-B) -> B
409 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen7604c1b2007-08-31 23:34:27 +0000410 if (N0CFP->getValueAPF().isZero())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000411 return Op.getOperand(1);
412
413 // -(A-B) -> B-A
414 return DAG.getNode(ISD::FSUB, Op.getValueType(), Op.getOperand(1),
415 Op.getOperand(0));
416
417 case ISD::FMUL:
418 case ISD::FDIV:
419 assert(!HonorSignDependentRoundingFPMath());
420
421 // -(X*Y) -> -X * Y
Chris Lattner46360032008-02-26 17:09:59 +0000422 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000423 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
Chris Lattnere0992b82008-02-26 07:04:54 +0000424 GetNegatedExpression(Op.getOperand(0), DAG,
425 AfterLegalize, Depth+1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000426 Op.getOperand(1));
427
428 // -(X*Y) -> X * -Y
429 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
430 Op.getOperand(0),
Chris Lattnere0992b82008-02-26 07:04:54 +0000431 GetNegatedExpression(Op.getOperand(1), DAG,
432 AfterLegalize, Depth+1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000433
434 case ISD::FP_EXTEND:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000435 case ISD::FSIN:
436 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
Chris Lattnere0992b82008-02-26 07:04:54 +0000437 GetNegatedExpression(Op.getOperand(0), DAG,
438 AfterLegalize, Depth+1));
Chris Lattner5872a362008-01-17 07:00:52 +0000439 case ISD::FP_ROUND:
440 return DAG.getNode(ISD::FP_ROUND, Op.getValueType(),
Chris Lattnere0992b82008-02-26 07:04:54 +0000441 GetNegatedExpression(Op.getOperand(0), DAG,
442 AfterLegalize, Depth+1),
Chris Lattner5872a362008-01-17 07:00:52 +0000443 Op.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000444 }
445}
446
447
448// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
449// that selects between the values 1 and 0, making it equivalent to a setcc.
450// Also, set the incoming LHS, RHS, and CC references to the appropriate
451// nodes based on the type of node we are checking. This simplifies life a
452// bit for the callers.
453static bool isSetCCEquivalent(SDOperand N, SDOperand &LHS, SDOperand &RHS,
454 SDOperand &CC) {
455 if (N.getOpcode() == ISD::SETCC) {
456 LHS = N.getOperand(0);
457 RHS = N.getOperand(1);
458 CC = N.getOperand(2);
459 return true;
460 }
461 if (N.getOpcode() == ISD::SELECT_CC &&
462 N.getOperand(2).getOpcode() == ISD::Constant &&
463 N.getOperand(3).getOpcode() == ISD::Constant &&
Dan Gohman9d24dc72008-03-13 22:13:53 +0000464 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000465 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
466 LHS = N.getOperand(0);
467 RHS = N.getOperand(1);
468 CC = N.getOperand(4);
469 return true;
470 }
471 return false;
472}
473
474// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
475// one use. If this is true, it allows the users to invert the operation for
476// free when it is profitable to do so.
477static bool isOneUseSetCC(SDOperand N) {
478 SDOperand N0, N1, N2;
479 if (isSetCCEquivalent(N, N0, N1, N2) && N.Val->hasOneUse())
480 return true;
481 return false;
482}
483
484SDOperand DAGCombiner::ReassociateOps(unsigned Opc, SDOperand N0, SDOperand N1){
Duncan Sands92c43912008-06-06 12:08:01 +0000485 MVT VT = N0.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000486 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
487 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
488 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
489 if (isa<ConstantSDNode>(N1)) {
490 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1);
491 AddToWorkList(OpNode.Val);
492 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0));
493 } else if (N0.hasOneUse()) {
494 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1);
495 AddToWorkList(OpNode.Val);
496 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(1));
497 }
498 }
499 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
500 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
501 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
502 if (isa<ConstantSDNode>(N0)) {
503 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0);
504 AddToWorkList(OpNode.Val);
505 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0));
506 } else if (N1.hasOneUse()) {
507 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0);
508 AddToWorkList(OpNode.Val);
509 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1));
510 }
511 }
512 return SDOperand();
513}
514
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000515SDOperand DAGCombiner::CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
516 bool AddTo) {
517 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
518 ++NodesCombined;
519 DOUT << "\nReplacing.1 "; DEBUG(N->dump(&DAG));
520 DOUT << "\nWith: "; DEBUG(To[0].Val->dump(&DAG));
521 DOUT << " and " << NumTo-1 << " other values\n";
522 WorkListRemover DeadNodes(*this);
523 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
524
525 if (AddTo) {
526 // Push the new nodes and any users onto the worklist
527 for (unsigned i = 0, e = NumTo; i != e; ++i) {
528 AddToWorkList(To[i].Val);
529 AddUsersToWorkList(To[i].Val);
530 }
531 }
532
533 // Nodes can be reintroduced into the worklist. Make sure we do not
534 // process a node that has been replaced.
535 removeFromWorkList(N);
536
537 // Finally, since the node is now dead, remove it from the graph.
538 DAG.DeleteNode(N);
539 return SDOperand(N, 0);
540}
541
542/// SimplifyDemandedBits - Check the specified integer node value to see if
543/// it can be simplified or if things it uses can be simplified by bit
544/// propagation. If so, return true.
Dan Gohman11607792008-02-27 00:25:32 +0000545bool DAGCombiner::SimplifyDemandedBits(SDOperand Op, const APInt &Demanded) {
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000546 TargetLowering::TargetLoweringOpt TLO(DAG, AfterLegalize);
Dan Gohman11607792008-02-27 00:25:32 +0000547 APInt KnownZero, KnownOne;
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000548 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
549 return false;
550
551 // Revisit the node.
552 AddToWorkList(Op.Val);
553
554 // Replace the old value with the new one.
555 ++NodesCombined;
556 DOUT << "\nReplacing.2 "; DEBUG(TLO.Old.Val->dump(&DAG));
557 DOUT << "\nWith: "; DEBUG(TLO.New.Val->dump(&DAG));
558 DOUT << '\n';
559
560 // Replace all uses. If any nodes become isomorphic to other nodes and
561 // are deleted, make sure to remove them from our worklist.
562 WorkListRemover DeadNodes(*this);
563 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
564
565 // Push the new node and any (possibly new) users onto the worklist.
566 AddToWorkList(TLO.New.Val);
567 AddUsersToWorkList(TLO.New.Val);
568
569 // Finally, if the node is now dead, remove it from the graph. The node
570 // may not be dead if the replacement process recursively simplified to
571 // something else needing this node.
572 if (TLO.Old.Val->use_empty()) {
573 removeFromWorkList(TLO.Old.Val);
574
575 // If the operands of this node are only used by the node, they will now
576 // be dead. Make sure to visit them first to delete dead nodes early.
577 for (unsigned i = 0, e = TLO.Old.Val->getNumOperands(); i != e; ++i)
578 if (TLO.Old.Val->getOperand(i).Val->hasOneUse())
579 AddToWorkList(TLO.Old.Val->getOperand(i).Val);
580
581 DAG.DeleteNode(TLO.Old.Val);
582 }
583 return true;
584}
585
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000586//===----------------------------------------------------------------------===//
587// Main DAG Combiner implementation
588//===----------------------------------------------------------------------===//
589
590void DAGCombiner::Run(bool RunningAfterLegalize) {
591 // set the instance variable, so that the various visit routines may use it.
592 AfterLegalize = RunningAfterLegalize;
593
594 // Add all the dag nodes to the worklist.
595 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
596 E = DAG.allnodes_end(); I != E; ++I)
597 WorkList.push_back(I);
598
599 // Create a dummy node (which is not added to allnodes), that adds a reference
600 // to the root node, preventing it from being deleted, and tracking any
601 // changes of the root.
602 HandleSDNode Dummy(DAG.getRoot());
603
604 // The root of the dag may dangle to deleted nodes until the dag combiner is
605 // done. Set it to null to avoid confusion.
606 DAG.setRoot(SDOperand());
607
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000608 // while the worklist isn't empty, inspect the node on the end of it and
609 // try and combine it.
610 while (!WorkList.empty()) {
611 SDNode *N = WorkList.back();
612 WorkList.pop_back();
613
614 // If N has no uses, it is dead. Make sure to revisit all N's operands once
615 // N is deleted from the DAG, since they too may now be dead or may have a
616 // reduced number of uses, allowing other xforms.
617 if (N->use_empty() && N != &Dummy) {
618 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
619 AddToWorkList(N->getOperand(i).Val);
620
621 DAG.DeleteNode(N);
622 continue;
623 }
624
Dan Gohman6c89ea72007-10-08 17:57:15 +0000625 SDOperand RV = combine(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626
Chris Lattner20e53902008-01-25 23:34:24 +0000627 if (RV.Val == 0)
628 continue;
629
630 ++NodesCombined;
Chris Lattner4a7c8452008-01-26 01:09:19 +0000631
Chris Lattner20e53902008-01-25 23:34:24 +0000632 // If we get back the same node we passed in, rather than a new node or
633 // zero, we know that the node must have defined multiple values and
634 // CombineTo was used. Since CombineTo takes care of the worklist
635 // mechanics for us, we have no work to do in this case.
636 if (RV.Val == N)
637 continue;
638
639 assert(N->getOpcode() != ISD::DELETED_NODE &&
640 RV.Val->getOpcode() != ISD::DELETED_NODE &&
641 "Node was deleted but visit returned new node!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000642
Chris Lattner20e53902008-01-25 23:34:24 +0000643 DOUT << "\nReplacing.3 "; DEBUG(N->dump(&DAG));
644 DOUT << "\nWith: "; DEBUG(RV.Val->dump(&DAG));
645 DOUT << '\n';
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000646 WorkListRemover DeadNodes(*this);
Chris Lattner20e53902008-01-25 23:34:24 +0000647 if (N->getNumValues() == RV.Val->getNumValues())
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000648 DAG.ReplaceAllUsesWith(N, RV.Val, &DeadNodes);
Chris Lattner20e53902008-01-25 23:34:24 +0000649 else {
Chris Lattner4a7c8452008-01-26 01:09:19 +0000650 assert(N->getValueType(0) == RV.getValueType() &&
651 N->getNumValues() == 1 && "Type mismatch");
Chris Lattner20e53902008-01-25 23:34:24 +0000652 SDOperand OpV = RV;
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000653 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000654 }
Chris Lattner20e53902008-01-25 23:34:24 +0000655
656 // Push the new node and any users onto the worklist
657 AddToWorkList(RV.Val);
658 AddUsersToWorkList(RV.Val);
659
660 // Add any uses of the old node to the worklist in case this node is the
661 // last one that uses them. They may become dead after this node is
662 // deleted.
663 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
664 AddToWorkList(N->getOperand(i).Val);
665
666 // Nodes can be reintroduced into the worklist. Make sure we do not
667 // process a node that has been replaced.
668 removeFromWorkList(N);
Chris Lattner20e53902008-01-25 23:34:24 +0000669
670 // Finally, since the node is now dead, remove it from the graph.
671 DAG.DeleteNode(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000672 }
673
674 // If the root changed (e.g. it was a dead load, update the root).
675 DAG.setRoot(Dummy.getValue());
676}
677
678SDOperand DAGCombiner::visit(SDNode *N) {
679 switch(N->getOpcode()) {
680 default: break;
681 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattnerf32fa7f2008-02-13 07:25:05 +0000682 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000683 case ISD::ADD: return visitADD(N);
684 case ISD::SUB: return visitSUB(N);
685 case ISD::ADDC: return visitADDC(N);
686 case ISD::ADDE: return visitADDE(N);
687 case ISD::MUL: return visitMUL(N);
688 case ISD::SDIV: return visitSDIV(N);
689 case ISD::UDIV: return visitUDIV(N);
690 case ISD::SREM: return visitSREM(N);
691 case ISD::UREM: return visitUREM(N);
692 case ISD::MULHU: return visitMULHU(N);
693 case ISD::MULHS: return visitMULHS(N);
Dan Gohman6c89ea72007-10-08 17:57:15 +0000694 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
695 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
696 case ISD::SDIVREM: return visitSDIVREM(N);
697 case ISD::UDIVREM: return visitUDIVREM(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000698 case ISD::AND: return visitAND(N);
699 case ISD::OR: return visitOR(N);
700 case ISD::XOR: return visitXOR(N);
701 case ISD::SHL: return visitSHL(N);
702 case ISD::SRA: return visitSRA(N);
703 case ISD::SRL: return visitSRL(N);
704 case ISD::CTLZ: return visitCTLZ(N);
705 case ISD::CTTZ: return visitCTTZ(N);
706 case ISD::CTPOP: return visitCTPOP(N);
707 case ISD::SELECT: return visitSELECT(N);
708 case ISD::SELECT_CC: return visitSELECT_CC(N);
709 case ISD::SETCC: return visitSETCC(N);
710 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
711 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
712 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
713 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
714 case ISD::TRUNCATE: return visitTRUNCATE(N);
715 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
Evan Chengb6290462008-05-12 23:04:07 +0000716 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000717 case ISD::FADD: return visitFADD(N);
718 case ISD::FSUB: return visitFSUB(N);
719 case ISD::FMUL: return visitFMUL(N);
720 case ISD::FDIV: return visitFDIV(N);
721 case ISD::FREM: return visitFREM(N);
722 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
723 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
724 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
725 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
726 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
727 case ISD::FP_ROUND: return visitFP_ROUND(N);
728 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
729 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
730 case ISD::FNEG: return visitFNEG(N);
731 case ISD::FABS: return visitFABS(N);
732 case ISD::BRCOND: return visitBRCOND(N);
733 case ISD::BR_CC: return visitBR_CC(N);
734 case ISD::LOAD: return visitLOAD(N);
735 case ISD::STORE: return visitSTORE(N);
736 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Chengd7ba7ed2007-10-06 08:19:55 +0000737 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000738 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
739 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
740 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
741 }
742 return SDOperand();
743}
744
Dan Gohman6c89ea72007-10-08 17:57:15 +0000745SDOperand DAGCombiner::combine(SDNode *N) {
746
747 SDOperand RV = visit(N);
748
749 // If nothing happened, try a target-specific DAG combine.
750 if (RV.Val == 0) {
751 assert(N->getOpcode() != ISD::DELETED_NODE &&
752 "Node was deleted but visit returned NULL!");
753
754 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
755 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
756
757 // Expose the DAG combiner to the target combiner impls.
758 TargetLowering::DAGCombinerInfo
759 DagCombineInfo(DAG, !AfterLegalize, false, this);
760
761 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
762 }
763 }
764
Evan Chengd1113582008-03-22 01:55:50 +0000765 // If N is a commutative binary node, try commuting it to enable more
766 // sdisel CSE.
767 if (RV.Val == 0 &&
768 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
769 N->getNumValues() == 1) {
770 SDOperand N0 = N->getOperand(0);
771 SDOperand N1 = N->getOperand(1);
772 // Constant operands are canonicalized to RHS.
773 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
774 SDOperand Ops[] = { N1, N0 };
775 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
776 Ops, 2);
Evan Chenge40b51c2008-03-24 23:55:16 +0000777 if (CSENode)
Evan Chengd1113582008-03-22 01:55:50 +0000778 return SDOperand(CSENode, 0);
779 }
780 }
781
Dan Gohman6c89ea72007-10-08 17:57:15 +0000782 return RV;
783}
784
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000785/// getInputChainForNode - Given a node, return its input chain if it has one,
786/// otherwise return a null sd operand.
787static SDOperand getInputChainForNode(SDNode *N) {
788 if (unsigned NumOps = N->getNumOperands()) {
789 if (N->getOperand(0).getValueType() == MVT::Other)
790 return N->getOperand(0);
791 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
792 return N->getOperand(NumOps-1);
793 for (unsigned i = 1; i < NumOps-1; ++i)
794 if (N->getOperand(i).getValueType() == MVT::Other)
795 return N->getOperand(i);
796 }
797 return SDOperand(0, 0);
798}
799
800SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
801 // If N has two operands, where one has an input chain equal to the other,
802 // the 'other' chain is redundant.
803 if (N->getNumOperands() == 2) {
804 if (getInputChainForNode(N->getOperand(0).Val) == N->getOperand(1))
805 return N->getOperand(0);
806 if (getInputChainForNode(N->getOperand(1).Val) == N->getOperand(0))
807 return N->getOperand(1);
808 }
809
810 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
811 SmallVector<SDOperand, 8> Ops; // Ops for replacing token factor.
812 SmallPtrSet<SDNode*, 16> SeenOps;
813 bool Changed = false; // If we should replace this token factor.
814
815 // Start out with this token factor.
816 TFs.push_back(N);
817
818 // Iterate through token factors. The TFs grows when new token factors are
819 // encountered.
820 for (unsigned i = 0; i < TFs.size(); ++i) {
821 SDNode *TF = TFs[i];
822
823 // Check each of the operands.
824 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
825 SDOperand Op = TF->getOperand(i);
826
827 switch (Op.getOpcode()) {
828 case ISD::EntryToken:
829 // Entry tokens don't need to be added to the list. They are
830 // rededundant.
831 Changed = true;
832 break;
833
834 case ISD::TokenFactor:
835 if ((CombinerAA || Op.hasOneUse()) &&
836 std::find(TFs.begin(), TFs.end(), Op.Val) == TFs.end()) {
837 // Queue up for processing.
838 TFs.push_back(Op.Val);
839 // Clean up in case the token factor is removed.
840 AddToWorkList(Op.Val);
841 Changed = true;
842 break;
843 }
844 // Fall thru
845
846 default:
847 // Only add if it isn't already in the list.
848 if (SeenOps.insert(Op.Val))
849 Ops.push_back(Op);
850 else
851 Changed = true;
852 break;
853 }
854 }
855 }
856
857 SDOperand Result;
858
859 // If we've change things around then replace token factor.
860 if (Changed) {
Dan Gohman301f4052008-01-29 13:02:09 +0000861 if (Ops.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000862 // The entry token is the only possible outcome.
863 Result = DAG.getEntryNode();
864 } else {
865 // New and improved token factor.
866 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
867 }
868
869 // Don't add users to work list.
870 return CombineTo(N, Result, false);
871 }
872
873 return Result;
874}
875
Chris Lattnerf32fa7f2008-02-13 07:25:05 +0000876/// MERGE_VALUES can always be eliminated.
877SDOperand DAGCombiner::visitMERGE_VALUES(SDNode *N) {
878 WorkListRemover DeadNodes(*this);
879 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
880 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, i), N->getOperand(i),
881 &DeadNodes);
882 removeFromWorkList(N);
883 DAG.DeleteNode(N);
884 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
885}
886
887
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000888static
889SDOperand combineShlAddConstant(SDOperand N0, SDOperand N1, SelectionDAG &DAG) {
Duncan Sands92c43912008-06-06 12:08:01 +0000890 MVT VT = N0.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000891 SDOperand N00 = N0.getOperand(0);
892 SDOperand N01 = N0.getOperand(1);
893 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
894 if (N01C && N00.getOpcode() == ISD::ADD && N00.Val->hasOneUse() &&
895 isa<ConstantSDNode>(N00.getOperand(1))) {
896 N0 = DAG.getNode(ISD::ADD, VT,
897 DAG.getNode(ISD::SHL, VT, N00.getOperand(0), N01),
898 DAG.getNode(ISD::SHL, VT, N00.getOperand(1), N01));
899 return DAG.getNode(ISD::ADD, VT, N0, N1);
900 }
901 return SDOperand();
902}
903
904static
905SDOperand combineSelectAndUse(SDNode *N, SDOperand Slct, SDOperand OtherOp,
906 SelectionDAG &DAG) {
Duncan Sands92c43912008-06-06 12:08:01 +0000907 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000908 unsigned Opc = N->getOpcode();
909 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
910 SDOperand LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
911 SDOperand RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
912 ISD::CondCode CC = ISD::SETCC_INVALID;
913 if (isSlctCC)
914 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
915 else {
916 SDOperand CCOp = Slct.getOperand(0);
917 if (CCOp.getOpcode() == ISD::SETCC)
918 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
919 }
920
921 bool DoXform = false;
922 bool InvCC = false;
923 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
924 "Bad input!");
925 if (LHS.getOpcode() == ISD::Constant &&
926 cast<ConstantSDNode>(LHS)->isNullValue())
927 DoXform = true;
928 else if (CC != ISD::SETCC_INVALID &&
929 RHS.getOpcode() == ISD::Constant &&
930 cast<ConstantSDNode>(RHS)->isNullValue()) {
931 std::swap(LHS, RHS);
Chris Lattner667f9c12008-01-17 07:20:38 +0000932 SDOperand Op0 = Slct.getOperand(0);
Duncan Sands92c43912008-06-06 12:08:01 +0000933 bool isInt = (isSlctCC ? Op0.getValueType() :
934 Op0.getOperand(0).getValueType()).isInteger();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000935 CC = ISD::getSetCCInverse(CC, isInt);
936 DoXform = true;
937 InvCC = true;
938 }
939
940 if (DoXform) {
941 SDOperand Result = DAG.getNode(Opc, VT, OtherOp, RHS);
942 if (isSlctCC)
943 return DAG.getSelectCC(OtherOp, Result,
944 Slct.getOperand(0), Slct.getOperand(1), CC);
945 SDOperand CCOp = Slct.getOperand(0);
946 if (InvCC)
947 CCOp = DAG.getSetCC(CCOp.getValueType(), CCOp.getOperand(0),
948 CCOp.getOperand(1), CC);
949 return DAG.getNode(ISD::SELECT, VT, CCOp, OtherOp, Result);
950 }
951 return SDOperand();
952}
953
954SDOperand DAGCombiner::visitADD(SDNode *N) {
955 SDOperand N0 = N->getOperand(0);
956 SDOperand N1 = N->getOperand(1);
957 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
958 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Duncan Sands92c43912008-06-06 12:08:01 +0000959 MVT VT = N0.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000960
961 // fold vector ops
Duncan Sands92c43912008-06-06 12:08:01 +0000962 if (VT.isVector()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000963 SDOperand FoldedVOp = SimplifyVBinOp(N);
964 if (FoldedVOp.Val) return FoldedVOp;
965 }
966
967 // fold (add x, undef) -> undef
968 if (N0.getOpcode() == ISD::UNDEF)
969 return N0;
970 if (N1.getOpcode() == ISD::UNDEF)
971 return N1;
972 // fold (add c1, c2) -> c1+c2
973 if (N0C && N1C)
Dan Gohman9d24dc72008-03-13 22:13:53 +0000974 return DAG.getConstant(N0C->getAPIntValue() + N1C->getAPIntValue(), VT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000975 // canonicalize constant to RHS
976 if (N0C && !N1C)
977 return DAG.getNode(ISD::ADD, VT, N1, N0);
978 // fold (add x, 0) -> x
979 if (N1C && N1C->isNullValue())
980 return N0;
981 // fold ((c1-A)+c2) -> (c1+c2)-A
982 if (N1C && N0.getOpcode() == ISD::SUB)
983 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
984 return DAG.getNode(ISD::SUB, VT,
Dan Gohman9d24dc72008-03-13 22:13:53 +0000985 DAG.getConstant(N1C->getAPIntValue()+
986 N0C->getAPIntValue(), VT),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000987 N0.getOperand(1));
988 // reassociate add
989 SDOperand RADD = ReassociateOps(ISD::ADD, N0, N1);
990 if (RADD.Val != 0)
991 return RADD;
992 // fold ((0-A) + B) -> B-A
993 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
994 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
995 return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
996 // fold (A + (0-B)) -> A-B
997 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
998 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
999 return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
1000 // fold (A+(B-A)) -> B
1001 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1002 return N1.getOperand(0);
1003
Duncan Sands92c43912008-06-06 12:08:01 +00001004 if (!VT.isVector() && SimplifyDemandedBits(SDOperand(N, 0)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001005 return SDOperand(N, 0);
1006
1007 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands92c43912008-06-06 12:08:01 +00001008 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmanbea075f2008-02-20 16:33:30 +00001009 APInt LHSZero, LHSOne;
1010 APInt RHSZero, RHSOne;
Duncan Sands92c43912008-06-06 12:08:01 +00001011 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001012 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
Dan Gohmanbea075f2008-02-20 16:33:30 +00001013 if (LHSZero.getBoolValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001014 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1015
1016 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1017 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1018 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1019 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1020 return DAG.getNode(ISD::OR, VT, N0, N1);
1021 }
1022 }
1023
1024 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1025 if (N0.getOpcode() == ISD::SHL && N0.Val->hasOneUse()) {
1026 SDOperand Result = combineShlAddConstant(N0, N1, DAG);
1027 if (Result.Val) return Result;
1028 }
1029 if (N1.getOpcode() == ISD::SHL && N1.Val->hasOneUse()) {
1030 SDOperand Result = combineShlAddConstant(N1, N0, DAG);
1031 if (Result.Val) return Result;
1032 }
1033
1034 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
1035 if (N0.getOpcode() == ISD::SELECT && N0.Val->hasOneUse()) {
1036 SDOperand Result = combineSelectAndUse(N, N0, N1, DAG);
1037 if (Result.Val) return Result;
1038 }
1039 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1040 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1041 if (Result.Val) return Result;
1042 }
1043
1044 return SDOperand();
1045}
1046
1047SDOperand DAGCombiner::visitADDC(SDNode *N) {
1048 SDOperand N0 = N->getOperand(0);
1049 SDOperand N1 = N->getOperand(1);
1050 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1051 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Duncan Sands92c43912008-06-06 12:08:01 +00001052 MVT VT = N0.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001053
1054 // If the flag result is dead, turn this into an ADD.
1055 if (N->hasNUsesOfValue(0, 1))
1056 return CombineTo(N, DAG.getNode(ISD::ADD, VT, N1, N0),
1057 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1058
1059 // canonicalize constant to RHS.
1060 if (N0C && !N1C) {
Dan Gohman6d4bb112008-06-21 22:06:07 +00001061 return DAG.getNode(ISD::ADDC, N->getVTList(), N1, N0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001062 }
1063
1064 // fold (addc x, 0) -> x + no carry out
1065 if (N1C && N1C->isNullValue())
1066 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1067
1068 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmanbea075f2008-02-20 16:33:30 +00001069 APInt LHSZero, LHSOne;
1070 APInt RHSZero, RHSOne;
Duncan Sands92c43912008-06-06 12:08:01 +00001071 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001072 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
Dan Gohmanbea075f2008-02-20 16:33:30 +00001073 if (LHSZero.getBoolValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001074 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1075
1076 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1077 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1078 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1079 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1080 return CombineTo(N, DAG.getNode(ISD::OR, VT, N0, N1),
1081 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1082 }
1083
1084 return SDOperand();
1085}
1086
1087SDOperand DAGCombiner::visitADDE(SDNode *N) {
1088 SDOperand N0 = N->getOperand(0);
1089 SDOperand N1 = N->getOperand(1);
1090 SDOperand CarryIn = N->getOperand(2);
1091 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1092 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Duncan Sands92c43912008-06-06 12:08:01 +00001093 //MVT VT = N0.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001094
1095 // canonicalize constant to RHS
1096 if (N0C && !N1C) {
Dan Gohman6d4bb112008-06-21 22:06:07 +00001097 return DAG.getNode(ISD::ADDE, N->getVTList(), N1, N0, CarryIn);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001098 }
1099
1100 // fold (adde x, y, false) -> (addc x, y)
1101 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) {
Dan Gohman6d4bb112008-06-21 22:06:07 +00001102 return DAG.getNode(ISD::ADDC, N->getVTList(), N1, N0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001103 }
1104
1105 return SDOperand();
1106}
1107
1108
1109
1110SDOperand DAGCombiner::visitSUB(SDNode *N) {
1111 SDOperand N0 = N->getOperand(0);
1112 SDOperand N1 = N->getOperand(1);
1113 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1114 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
Duncan Sands92c43912008-06-06 12:08:01 +00001115 MVT VT = N0.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001116
1117 // fold vector ops
Duncan Sands92c43912008-06-06 12:08:01 +00001118 if (VT.isVector()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001119 SDOperand FoldedVOp = SimplifyVBinOp(N);
1120 if (FoldedVOp.Val) return FoldedVOp;
1121 }
1122
1123 // fold (sub x, x) -> 0
Evan Chenga15896e2008-03-12 07:02:50 +00001124 if (N0 == N1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001125 return DAG.getConstant(0, N->getValueType(0));
1126 // fold (sub c1, c2) -> c1-c2
1127 if (N0C && N1C)
1128 return DAG.getNode(ISD::SUB, VT, N0, N1);
1129 // fold (sub x, c) -> (add x, -c)
1130 if (N1C)
Dan Gohman9d24dc72008-03-13 22:13:53 +00001131 return DAG.getNode(ISD::ADD, VT, N0,
1132 DAG.getConstant(-N1C->getAPIntValue(), VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001133 // fold (A+B)-A -> B
1134 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1135 return N0.getOperand(1);
1136 // fold (A+B)-B -> A
1137 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1138 return N0.getOperand(0);
1139 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
1140 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1141 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1142 if (Result.Val) return Result;
1143 }
1144 // If either operand of a sub is undef, the result is undef
1145 if (N0.getOpcode() == ISD::UNDEF)
1146 return N0;
1147 if (N1.getOpcode() == ISD::UNDEF)
1148 return N1;
1149
1150 return SDOperand();
1151}
1152
1153SDOperand DAGCombiner::visitMUL(SDNode *N) {
1154 SDOperand N0 = N->getOperand(0);
1155 SDOperand N1 = N->getOperand(1);
1156 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1157 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Duncan Sands92c43912008-06-06 12:08:01 +00001158 MVT VT = N0.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001159
1160 // fold vector ops
Duncan Sands92c43912008-06-06 12:08:01 +00001161 if (VT.isVector()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001162 SDOperand FoldedVOp = SimplifyVBinOp(N);
1163 if (FoldedVOp.Val) return FoldedVOp;
1164 }
1165
1166 // fold (mul x, undef) -> 0
1167 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1168 return DAG.getConstant(0, VT);
1169 // fold (mul c1, c2) -> c1*c2
1170 if (N0C && N1C)
1171 return DAG.getNode(ISD::MUL, VT, N0, N1);
1172 // canonicalize constant to RHS
1173 if (N0C && !N1C)
1174 return DAG.getNode(ISD::MUL, VT, N1, N0);
1175 // fold (mul x, 0) -> 0
1176 if (N1C && N1C->isNullValue())
1177 return N1;
1178 // fold (mul x, -1) -> 0-x
1179 if (N1C && N1C->isAllOnesValue())
1180 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1181 // fold (mul x, (1 << c)) -> x << c
Dan Gohman9d24dc72008-03-13 22:13:53 +00001182 if (N1C && N1C->getAPIntValue().isPowerOf2())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001183 return DAG.getNode(ISD::SHL, VT, N0,
Dan Gohman9d24dc72008-03-13 22:13:53 +00001184 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001185 TLI.getShiftAmountTy()));
1186 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1187 if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
1188 // FIXME: If the input is something that is easily negated (e.g. a
1189 // single-use add), we should put the negate there.
1190 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
1191 DAG.getNode(ISD::SHL, VT, N0,
1192 DAG.getConstant(Log2_64(-N1C->getSignExtended()),
1193 TLI.getShiftAmountTy())));
1194 }
1195
1196 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1197 if (N1C && N0.getOpcode() == ISD::SHL &&
1198 isa<ConstantSDNode>(N0.getOperand(1))) {
1199 SDOperand C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
1200 AddToWorkList(C3.Val);
1201 return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
1202 }
1203
1204 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1205 // use.
1206 {
1207 SDOperand Sh(0,0), Y(0,0);
1208 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1209 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1210 N0.Val->hasOneUse()) {
1211 Sh = N0; Y = N1;
1212 } else if (N1.getOpcode() == ISD::SHL &&
1213 isa<ConstantSDNode>(N1.getOperand(1)) && N1.Val->hasOneUse()) {
1214 Sh = N1; Y = N0;
1215 }
1216 if (Sh.Val) {
1217 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
1218 return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
1219 }
1220 }
1221 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1222 if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
1223 isa<ConstantSDNode>(N0.getOperand(1))) {
1224 return DAG.getNode(ISD::ADD, VT,
1225 DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
1226 DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
1227 }
1228
1229 // reassociate mul
1230 SDOperand RMUL = ReassociateOps(ISD::MUL, N0, N1);
1231 if (RMUL.Val != 0)
1232 return RMUL;
1233
1234 return SDOperand();
1235}
1236
1237SDOperand DAGCombiner::visitSDIV(SDNode *N) {
1238 SDOperand N0 = N->getOperand(0);
1239 SDOperand N1 = N->getOperand(1);
1240 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1241 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
Duncan Sands92c43912008-06-06 12:08:01 +00001242 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001243
1244 // fold vector ops
Duncan Sands92c43912008-06-06 12:08:01 +00001245 if (VT.isVector()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001246 SDOperand FoldedVOp = SimplifyVBinOp(N);
1247 if (FoldedVOp.Val) return FoldedVOp;
1248 }
1249
1250 // fold (sdiv c1, c2) -> c1/c2
1251 if (N0C && N1C && !N1C->isNullValue())
1252 return DAG.getNode(ISD::SDIV, VT, N0, N1);
1253 // fold (sdiv X, 1) -> X
1254 if (N1C && N1C->getSignExtended() == 1LL)
1255 return N0;
1256 // fold (sdiv X, -1) -> 0-X
1257 if (N1C && N1C->isAllOnesValue())
1258 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1259 // If we know the sign bits of both operands are zero, strength reduce to a
1260 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands92c43912008-06-06 12:08:01 +00001261 if (!VT.isVector()) {
Dan Gohman07961cd2008-02-25 21:11:39 +00001262 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Chris Lattner336672f2008-01-27 23:32:17 +00001263 return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
1264 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001265 // fold (sdiv X, pow2) -> simple ops after legalize
Dan Gohman9d24dc72008-03-13 22:13:53 +00001266 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001267 (isPowerOf2_64(N1C->getSignExtended()) ||
1268 isPowerOf2_64(-N1C->getSignExtended()))) {
1269 // If dividing by powers of two is cheap, then don't perform the following
1270 // fold.
1271 if (TLI.isPow2DivCheap())
1272 return SDOperand();
1273 int64_t pow2 = N1C->getSignExtended();
1274 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1275 unsigned lg2 = Log2_64(abs2);
1276 // Splat the sign bit into the register
1277 SDOperand SGN = DAG.getNode(ISD::SRA, VT, N0,
Duncan Sands92c43912008-06-06 12:08:01 +00001278 DAG.getConstant(VT.getSizeInBits()-1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001279 TLI.getShiftAmountTy()));
1280 AddToWorkList(SGN.Val);
1281 // Add (N0 < 0) ? abs2 - 1 : 0;
1282 SDOperand SRL = DAG.getNode(ISD::SRL, VT, SGN,
Duncan Sands92c43912008-06-06 12:08:01 +00001283 DAG.getConstant(VT.getSizeInBits()-lg2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001284 TLI.getShiftAmountTy()));
1285 SDOperand ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
1286 AddToWorkList(SRL.Val);
1287 AddToWorkList(ADD.Val); // Divide by pow2
1288 SDOperand SRA = DAG.getNode(ISD::SRA, VT, ADD,
1289 DAG.getConstant(lg2, TLI.getShiftAmountTy()));
1290 // If we're dividing by a positive value, we're done. Otherwise, we must
1291 // negate the result.
1292 if (pow2 > 0)
1293 return SRA;
1294 AddToWorkList(SRA.Val);
1295 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
1296 }
1297 // if integer divide is expensive and we satisfy the requirements, emit an
1298 // alternate sequence.
1299 if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) &&
1300 !TLI.isIntDivCheap()) {
1301 SDOperand Op = BuildSDIV(N);
1302 if (Op.Val) return Op;
1303 }
1304
1305 // undef / X -> 0
1306 if (N0.getOpcode() == ISD::UNDEF)
1307 return DAG.getConstant(0, VT);
1308 // X / undef -> undef
1309 if (N1.getOpcode() == ISD::UNDEF)
1310 return N1;
1311
1312 return SDOperand();
1313}
1314
1315SDOperand DAGCombiner::visitUDIV(SDNode *N) {
1316 SDOperand N0 = N->getOperand(0);
1317 SDOperand N1 = N->getOperand(1);
1318 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1319 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
Duncan Sands92c43912008-06-06 12:08:01 +00001320 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001321
1322 // fold vector ops
Duncan Sands92c43912008-06-06 12:08:01 +00001323 if (VT.isVector()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001324 SDOperand FoldedVOp = SimplifyVBinOp(N);
1325 if (FoldedVOp.Val) return FoldedVOp;
1326 }
1327
1328 // fold (udiv c1, c2) -> c1/c2
1329 if (N0C && N1C && !N1C->isNullValue())
1330 return DAG.getNode(ISD::UDIV, VT, N0, N1);
1331 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohman9d24dc72008-03-13 22:13:53 +00001332 if (N1C && N1C->getAPIntValue().isPowerOf2())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001333 return DAG.getNode(ISD::SRL, VT, N0,
Dan Gohman9d24dc72008-03-13 22:13:53 +00001334 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001335 TLI.getShiftAmountTy()));
1336 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1337 if (N1.getOpcode() == ISD::SHL) {
1338 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohman9d24dc72008-03-13 22:13:53 +00001339 if (SHC->getAPIntValue().isPowerOf2()) {
Duncan Sands92c43912008-06-06 12:08:01 +00001340 MVT ADDVT = N1.getOperand(1).getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001341 SDOperand Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
Dan Gohman9d24dc72008-03-13 22:13:53 +00001342 DAG.getConstant(SHC->getAPIntValue()
1343 .logBase2(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001344 ADDVT));
1345 AddToWorkList(Add.Val);
1346 return DAG.getNode(ISD::SRL, VT, N0, Add);
1347 }
1348 }
1349 }
1350 // fold (udiv x, c) -> alternate
Dan Gohman9d24dc72008-03-13 22:13:53 +00001351 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001352 SDOperand Op = BuildUDIV(N);
1353 if (Op.Val) return Op;
1354 }
1355
1356 // undef / X -> 0
1357 if (N0.getOpcode() == ISD::UNDEF)
1358 return DAG.getConstant(0, VT);
1359 // X / undef -> undef
1360 if (N1.getOpcode() == ISD::UNDEF)
1361 return N1;
1362
1363 return SDOperand();
1364}
1365
1366SDOperand DAGCombiner::visitSREM(SDNode *N) {
1367 SDOperand N0 = N->getOperand(0);
1368 SDOperand N1 = N->getOperand(1);
1369 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1370 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Duncan Sands92c43912008-06-06 12:08:01 +00001371 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001372
1373 // fold (srem c1, c2) -> c1%c2
1374 if (N0C && N1C && !N1C->isNullValue())
1375 return DAG.getNode(ISD::SREM, VT, N0, N1);
1376 // If we know the sign bits of both operands are zero, strength reduce to a
1377 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands92c43912008-06-06 12:08:01 +00001378 if (!VT.isVector()) {
Dan Gohman07961cd2008-02-25 21:11:39 +00001379 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Chris Lattnerce602f52008-01-27 23:21:58 +00001380 return DAG.getNode(ISD::UREM, VT, N0, N1);
1381 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001382
Dan Gohmanfdb31f12007-11-26 23:46:11 +00001383 // If X/C can be simplified by the division-by-constant logic, lower
1384 // X%C to the equivalent of X-X/C*C.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001385 if (N1C && !N1C->isNullValue()) {
1386 SDOperand Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
Chris Lattner4a7c8452008-01-26 01:09:19 +00001387 AddToWorkList(Div.Val);
Dan Gohmanfdb31f12007-11-26 23:46:11 +00001388 SDOperand OptimizedDiv = combine(Div.Val);
1389 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1390 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1391 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1392 AddToWorkList(Mul.Val);
1393 return Sub;
1394 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001395 }
1396
1397 // undef % X -> 0
1398 if (N0.getOpcode() == ISD::UNDEF)
1399 return DAG.getConstant(0, VT);
1400 // X % undef -> undef
1401 if (N1.getOpcode() == ISD::UNDEF)
1402 return N1;
1403
1404 return SDOperand();
1405}
1406
1407SDOperand DAGCombiner::visitUREM(SDNode *N) {
1408 SDOperand N0 = N->getOperand(0);
1409 SDOperand N1 = N->getOperand(1);
1410 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1411 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Duncan Sands92c43912008-06-06 12:08:01 +00001412 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001413
1414 // fold (urem c1, c2) -> c1%c2
1415 if (N0C && N1C && !N1C->isNullValue())
1416 return DAG.getNode(ISD::UREM, VT, N0, N1);
1417 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohman9d24dc72008-03-13 22:13:53 +00001418 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1419 return DAG.getNode(ISD::AND, VT, N0,
1420 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001421 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1422 if (N1.getOpcode() == ISD::SHL) {
1423 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohman9d24dc72008-03-13 22:13:53 +00001424 if (SHC->getAPIntValue().isPowerOf2()) {
1425 SDOperand Add =
1426 DAG.getNode(ISD::ADD, VT, N1,
Duncan Sands92c43912008-06-06 12:08:01 +00001427 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohman9d24dc72008-03-13 22:13:53 +00001428 VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001429 AddToWorkList(Add.Val);
1430 return DAG.getNode(ISD::AND, VT, N0, Add);
1431 }
1432 }
1433 }
1434
Dan Gohmanfdb31f12007-11-26 23:46:11 +00001435 // If X/C can be simplified by the division-by-constant logic, lower
1436 // X%C to the equivalent of X-X/C*C.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001437 if (N1C && !N1C->isNullValue()) {
1438 SDOperand Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
Dan Gohmanfdb31f12007-11-26 23:46:11 +00001439 SDOperand OptimizedDiv = combine(Div.Val);
1440 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1441 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1442 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1443 AddToWorkList(Mul.Val);
1444 return Sub;
1445 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001446 }
1447
1448 // undef % X -> 0
1449 if (N0.getOpcode() == ISD::UNDEF)
1450 return DAG.getConstant(0, VT);
1451 // X % undef -> undef
1452 if (N1.getOpcode() == ISD::UNDEF)
1453 return N1;
1454
1455 return SDOperand();
1456}
1457
1458SDOperand DAGCombiner::visitMULHS(SDNode *N) {
1459 SDOperand N0 = N->getOperand(0);
1460 SDOperand N1 = N->getOperand(1);
1461 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Duncan Sands92c43912008-06-06 12:08:01 +00001462 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001463
1464 // fold (mulhs x, 0) -> 0
1465 if (N1C && N1C->isNullValue())
1466 return N1;
1467 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohman9d24dc72008-03-13 22:13:53 +00001468 if (N1C && N1C->getAPIntValue() == 1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001469 return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
Duncan Sands92c43912008-06-06 12:08:01 +00001470 DAG.getConstant(N0.getValueType().getSizeInBits()-1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001471 TLI.getShiftAmountTy()));
1472 // fold (mulhs x, undef) -> 0
1473 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1474 return DAG.getConstant(0, VT);
1475
1476 return SDOperand();
1477}
1478
1479SDOperand DAGCombiner::visitMULHU(SDNode *N) {
1480 SDOperand N0 = N->getOperand(0);
1481 SDOperand N1 = N->getOperand(1);
1482 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Duncan Sands92c43912008-06-06 12:08:01 +00001483 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001484
1485 // fold (mulhu x, 0) -> 0
1486 if (N1C && N1C->isNullValue())
1487 return N1;
1488 // fold (mulhu x, 1) -> 0
Dan Gohman9d24dc72008-03-13 22:13:53 +00001489 if (N1C && N1C->getAPIntValue() == 1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001490 return DAG.getConstant(0, N0.getValueType());
1491 // fold (mulhu x, undef) -> 0
1492 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1493 return DAG.getConstant(0, VT);
1494
1495 return SDOperand();
1496}
1497
Dan Gohman6c89ea72007-10-08 17:57:15 +00001498/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1499/// compute two values. LoOp and HiOp give the opcodes for the two computations
1500/// that are being performed. Return true if a simplification was made.
1501///
Chris Lattner4a7c8452008-01-26 01:09:19 +00001502SDOperand DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1503 unsigned HiOp) {
Dan Gohman6c89ea72007-10-08 17:57:15 +00001504 // If the high half is not needed, just compute the low half.
Evan Chengddfa8c72007-11-08 09:25:29 +00001505 bool HiExists = N->hasAnyUseOfValue(1);
1506 if (!HiExists &&
Dan Gohman6c89ea72007-10-08 17:57:15 +00001507 (!AfterLegalize ||
1508 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
Chris Lattner4a7c8452008-01-26 01:09:19 +00001509 SDOperand Res = DAG.getNode(LoOp, N->getValueType(0), N->op_begin(),
1510 N->getNumOperands());
1511 return CombineTo(N, Res, Res);
Dan Gohman6c89ea72007-10-08 17:57:15 +00001512 }
1513
1514 // If the low half is not needed, just compute the high half.
Evan Chengddfa8c72007-11-08 09:25:29 +00001515 bool LoExists = N->hasAnyUseOfValue(0);
1516 if (!LoExists &&
Dan Gohman6c89ea72007-10-08 17:57:15 +00001517 (!AfterLegalize ||
1518 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Chris Lattner4a7c8452008-01-26 01:09:19 +00001519 SDOperand Res = DAG.getNode(HiOp, N->getValueType(1), N->op_begin(),
1520 N->getNumOperands());
1521 return CombineTo(N, Res, Res);
Dan Gohman6c89ea72007-10-08 17:57:15 +00001522 }
1523
Evan Chengddfa8c72007-11-08 09:25:29 +00001524 // If both halves are used, return as it is.
1525 if (LoExists && HiExists)
Chris Lattner4a7c8452008-01-26 01:09:19 +00001526 return SDOperand();
Evan Chengddfa8c72007-11-08 09:25:29 +00001527
1528 // If the two computed results can be simplified separately, separate them.
Evan Chengddfa8c72007-11-08 09:25:29 +00001529 if (LoExists) {
1530 SDOperand Lo = DAG.getNode(LoOp, N->getValueType(0),
1531 N->op_begin(), N->getNumOperands());
Chris Lattner4a7c8452008-01-26 01:09:19 +00001532 AddToWorkList(Lo.Val);
Evan Chengddfa8c72007-11-08 09:25:29 +00001533 SDOperand LoOpt = combine(Lo.Val);
Chris Lattner4a7c8452008-01-26 01:09:19 +00001534 if (LoOpt.Val && LoOpt.Val != Lo.Val &&
Duncan Sands2418bec2008-06-13 19:07:40 +00001535 (!AfterLegalize ||
1536 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner4a7c8452008-01-26 01:09:19 +00001537 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman6c89ea72007-10-08 17:57:15 +00001538 }
1539
Evan Chengddfa8c72007-11-08 09:25:29 +00001540 if (HiExists) {
1541 SDOperand Hi = DAG.getNode(HiOp, N->getValueType(1),
1542 N->op_begin(), N->getNumOperands());
Chris Lattner4a7c8452008-01-26 01:09:19 +00001543 AddToWorkList(Hi.Val);
Evan Chengddfa8c72007-11-08 09:25:29 +00001544 SDOperand HiOpt = combine(Hi.Val);
1545 if (HiOpt.Val && HiOpt != Hi &&
Duncan Sands2418bec2008-06-13 19:07:40 +00001546 (!AfterLegalize ||
1547 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner4a7c8452008-01-26 01:09:19 +00001548 return CombineTo(N, HiOpt, HiOpt);
Evan Chengddfa8c72007-11-08 09:25:29 +00001549 }
Chris Lattner4a7c8452008-01-26 01:09:19 +00001550 return SDOperand();
Dan Gohman6c89ea72007-10-08 17:57:15 +00001551}
1552
1553SDOperand DAGCombiner::visitSMUL_LOHI(SDNode *N) {
Chris Lattner4a7c8452008-01-26 01:09:19 +00001554 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
1555 if (Res.Val) return Res;
Dan Gohman6c89ea72007-10-08 17:57:15 +00001556
1557 return SDOperand();
1558}
1559
1560SDOperand DAGCombiner::visitUMUL_LOHI(SDNode *N) {
Chris Lattner4a7c8452008-01-26 01:09:19 +00001561 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
1562 if (Res.Val) return Res;
Dan Gohman6c89ea72007-10-08 17:57:15 +00001563
1564 return SDOperand();
1565}
1566
1567SDOperand DAGCombiner::visitSDIVREM(SDNode *N) {
Chris Lattner4a7c8452008-01-26 01:09:19 +00001568 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
1569 if (Res.Val) return Res;
Dan Gohman6c89ea72007-10-08 17:57:15 +00001570
1571 return SDOperand();
1572}
1573
1574SDOperand DAGCombiner::visitUDIVREM(SDNode *N) {
Chris Lattner4a7c8452008-01-26 01:09:19 +00001575 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
1576 if (Res.Val) return Res;
Dan Gohman6c89ea72007-10-08 17:57:15 +00001577
1578 return SDOperand();
1579}
1580
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001581/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1582/// two operands of the same opcode, try to simplify it.
1583SDOperand DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1584 SDOperand N0 = N->getOperand(0), N1 = N->getOperand(1);
Duncan Sands92c43912008-06-06 12:08:01 +00001585 MVT VT = N0.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001586 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1587
1588 // For each of OP in AND/OR/XOR:
1589 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1590 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1591 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1592 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1593 if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1594 N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
1595 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1596 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1597 N0.getOperand(0).getValueType(),
1598 N0.getOperand(0), N1.getOperand(0));
1599 AddToWorkList(ORNode.Val);
1600 return DAG.getNode(N0.getOpcode(), VT, ORNode);
1601 }
1602
1603 // For each of OP in SHL/SRL/SRA/AND...
1604 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1605 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1606 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1607 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1608 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1609 N0.getOperand(1) == N1.getOperand(1)) {
1610 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1611 N0.getOperand(0).getValueType(),
1612 N0.getOperand(0), N1.getOperand(0));
1613 AddToWorkList(ORNode.Val);
1614 return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
1615 }
1616
1617 return SDOperand();
1618}
1619
1620SDOperand DAGCombiner::visitAND(SDNode *N) {
1621 SDOperand N0 = N->getOperand(0);
1622 SDOperand N1 = N->getOperand(1);
1623 SDOperand LL, LR, RL, RR, CC0, CC1;
1624 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1625 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Duncan Sands92c43912008-06-06 12:08:01 +00001626 MVT VT = N1.getValueType();
1627 unsigned BitWidth = VT.getSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001628
1629 // fold vector ops
Duncan Sands92c43912008-06-06 12:08:01 +00001630 if (VT.isVector()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001631 SDOperand FoldedVOp = SimplifyVBinOp(N);
1632 if (FoldedVOp.Val) return FoldedVOp;
1633 }
1634
1635 // fold (and x, undef) -> 0
1636 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1637 return DAG.getConstant(0, VT);
1638 // fold (and c1, c2) -> c1&c2
1639 if (N0C && N1C)
1640 return DAG.getNode(ISD::AND, VT, N0, N1);
1641 // canonicalize constant to RHS
1642 if (N0C && !N1C)
1643 return DAG.getNode(ISD::AND, VT, N1, N0);
1644 // fold (and x, -1) -> x
1645 if (N1C && N1C->isAllOnesValue())
1646 return N0;
1647 // if (and x, c) is known to be zero, return 0
Dan Gohman07961cd2008-02-25 21:11:39 +00001648 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
1649 APInt::getAllOnesValue(BitWidth)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001650 return DAG.getConstant(0, VT);
1651 // reassociate and
1652 SDOperand RAND = ReassociateOps(ISD::AND, N0, N1);
1653 if (RAND.Val != 0)
1654 return RAND;
1655 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1656 if (N1C && N0.getOpcode() == ISD::OR)
1657 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman9d24dc72008-03-13 22:13:53 +00001658 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001659 return N1;
1660 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1661 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman07961cd2008-02-25 21:11:39 +00001662 SDOperand N0Op0 = N0.getOperand(0);
1663 APInt Mask = ~N1C->getAPIntValue();
1664 Mask.trunc(N0Op0.getValueSizeInBits());
1665 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001666 SDOperand Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
Dan Gohman07961cd2008-02-25 21:11:39 +00001667 N0Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001668
1669 // Replace uses of the AND with uses of the Zero extend node.
1670 CombineTo(N, Zext);
1671
1672 // We actually want to replace all uses of the any_extend with the
1673 // zero_extend, to avoid duplicating things. This will later cause this
1674 // AND to be folded.
1675 CombineTo(N0.Val, Zext);
1676 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1677 }
1678 }
1679 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1680 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1681 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1682 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1683
1684 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands92c43912008-06-06 12:08:01 +00001685 LL.getValueType().isInteger()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001686 // fold (X == 0) & (Y == 0) -> (X|Y == 0)
Dan Gohman9d24dc72008-03-13 22:13:53 +00001687 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001688 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1689 AddToWorkList(ORNode.Val);
1690 return DAG.getSetCC(VT, ORNode, LR, Op1);
1691 }
1692 // fold (X == -1) & (Y == -1) -> (X&Y == -1)
1693 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1694 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1695 AddToWorkList(ANDNode.Val);
1696 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1697 }
1698 // fold (X > -1) & (Y > -1) -> (X|Y > -1)
1699 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1700 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1701 AddToWorkList(ORNode.Val);
1702 return DAG.getSetCC(VT, ORNode, LR, Op1);
1703 }
1704 }
1705 // canonicalize equivalent to ll == rl
1706 if (LL == RR && LR == RL) {
1707 Op1 = ISD::getSetCCSwappedOperands(Op1);
1708 std::swap(RL, RR);
1709 }
1710 if (LL == RL && LR == RR) {
Duncan Sands92c43912008-06-06 12:08:01 +00001711 bool isInteger = LL.getValueType().isInteger();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001712 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1713 if (Result != ISD::SETCC_INVALID)
1714 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1715 }
1716 }
1717
1718 // Simplify: and (op x...), (op y...) -> (op (and x, y))
1719 if (N0.getOpcode() == N1.getOpcode()) {
1720 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1721 if (Tmp.Val) return Tmp;
1722 }
1723
1724 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1725 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands92c43912008-06-06 12:08:01 +00001726 if (!VT.isVector() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001727 SimplifyDemandedBits(SDOperand(N, 0)))
1728 return SDOperand(N, 0);
1729 // fold (zext_inreg (extload x)) -> (zextload x)
1730 if (ISD::isEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val)) {
1731 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Duncan Sands92c43912008-06-06 12:08:01 +00001732 MVT EVT = LN0->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001733 // If we zero all the possible extended bits, then we can turn this into
1734 // a zextload if we are running before legalize or the operation is legal.
Dan Gohman07961cd2008-02-25 21:11:39 +00001735 unsigned BitWidth = N1.getValueSizeInBits();
1736 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Duncan Sands92c43912008-06-06 12:08:01 +00001737 BitWidth - EVT.getSizeInBits())) &&
Duncan Sands2418bec2008-06-13 19:07:40 +00001738 ((!AfterLegalize && !LN0->isVolatile()) ||
1739 TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001740 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1741 LN0->getBasePtr(), LN0->getSrcValue(),
1742 LN0->getSrcValueOffset(), EVT,
1743 LN0->isVolatile(),
1744 LN0->getAlignment());
1745 AddToWorkList(N);
1746 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1747 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1748 }
1749 }
1750 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1751 if (ISD::isSEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
1752 N0.hasOneUse()) {
1753 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Duncan Sands92c43912008-06-06 12:08:01 +00001754 MVT EVT = LN0->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001755 // If we zero all the possible extended bits, then we can turn this into
1756 // a zextload if we are running before legalize or the operation is legal.
Dan Gohman07961cd2008-02-25 21:11:39 +00001757 unsigned BitWidth = N1.getValueSizeInBits();
1758 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Duncan Sands92c43912008-06-06 12:08:01 +00001759 BitWidth - EVT.getSizeInBits())) &&
Duncan Sands2418bec2008-06-13 19:07:40 +00001760 ((!AfterLegalize && !LN0->isVolatile()) ||
1761 TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001762 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1763 LN0->getBasePtr(), LN0->getSrcValue(),
1764 LN0->getSrcValueOffset(), EVT,
1765 LN0->isVolatile(),
1766 LN0->getAlignment());
1767 AddToWorkList(N);
1768 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1769 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1770 }
1771 }
1772
1773 // fold (and (load x), 255) -> (zextload x, i8)
1774 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1775 if (N1C && N0.getOpcode() == ISD::LOAD) {
1776 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1777 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Duncan Sands2418bec2008-06-13 19:07:40 +00001778 LN0->isUnindexed() && N0.hasOneUse() &&
1779 // Do not change the width of a volatile load.
1780 !LN0->isVolatile()) {
Duncan Sands6a437fb2008-06-09 11:32:28 +00001781 MVT EVT = MVT::Other;
1782 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
1783 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue()))
1784 EVT = MVT::getIntegerVT(ActiveBits);
1785
1786 MVT LoadedVT = LN0->getMemoryVT();
Duncan Sands3ea93352008-06-16 08:14:38 +00001787 // Do not generate loads of non-round integer types since these can
1788 // be expensive (and would be wrong if the type is not byte sized).
1789 if (EVT != MVT::Other && LoadedVT.bitsGT(EVT) && EVT.isRound() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001790 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
Duncan Sands92c43912008-06-06 12:08:01 +00001791 MVT PtrType = N0.getOperand(1).getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001792 // For big endian targets, we need to add an offset to the pointer to
1793 // load the correct bytes. For little endian systems, we merely need to
1794 // read fewer bytes from the same pointer.
Duncan Sands92c43912008-06-06 12:08:01 +00001795 unsigned LVTStoreBytes = LoadedVT.getStoreSizeInBits()/8;
1796 unsigned EVTStoreBytes = EVT.getStoreSizeInBits()/8;
Duncan Sands4f18d4f2007-11-09 08:57:19 +00001797 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Duncan Sandsa3691432007-10-28 12:59:45 +00001798 unsigned Alignment = LN0->getAlignment();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001799 SDOperand NewPtr = LN0->getBasePtr();
Duncan Sands9ff8fbf2008-02-11 10:37:04 +00001800 if (TLI.isBigEndian()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001801 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1802 DAG.getConstant(PtrOff, PtrType));
Duncan Sandsa3691432007-10-28 12:59:45 +00001803 Alignment = MinAlign(Alignment, PtrOff);
1804 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001805 AddToWorkList(NewPtr.Val);
1806 SDOperand Load =
1807 DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
1808 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
Duncan Sandsa3691432007-10-28 12:59:45 +00001809 LN0->isVolatile(), Alignment);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001810 AddToWorkList(N);
1811 CombineTo(N0.Val, Load, Load.getValue(1));
1812 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1813 }
1814 }
1815 }
1816
1817 return SDOperand();
1818}
1819
1820SDOperand DAGCombiner::visitOR(SDNode *N) {
1821 SDOperand N0 = N->getOperand(0);
1822 SDOperand N1 = N->getOperand(1);
1823 SDOperand LL, LR, RL, RR, CC0, CC1;
1824 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1825 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Duncan Sands92c43912008-06-06 12:08:01 +00001826 MVT VT = N1.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001827
1828 // fold vector ops
Duncan Sands92c43912008-06-06 12:08:01 +00001829 if (VT.isVector()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001830 SDOperand FoldedVOp = SimplifyVBinOp(N);
1831 if (FoldedVOp.Val) return FoldedVOp;
1832 }
1833
1834 // fold (or x, undef) -> -1
1835 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1836 return DAG.getConstant(~0ULL, VT);
1837 // fold (or c1, c2) -> c1|c2
1838 if (N0C && N1C)
1839 return DAG.getNode(ISD::OR, VT, N0, N1);
1840 // canonicalize constant to RHS
1841 if (N0C && !N1C)
1842 return DAG.getNode(ISD::OR, VT, N1, N0);
1843 // fold (or x, 0) -> x
1844 if (N1C && N1C->isNullValue())
1845 return N0;
1846 // fold (or x, -1) -> -1
1847 if (N1C && N1C->isAllOnesValue())
1848 return N1;
1849 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman07961cd2008-02-25 21:11:39 +00001850 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001851 return N1;
1852 // reassociate or
1853 SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
1854 if (ROR.Val != 0)
1855 return ROR;
1856 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1857 if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1858 isa<ConstantSDNode>(N0.getOperand(1))) {
1859 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1860 return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1861 N1),
Dan Gohman9d24dc72008-03-13 22:13:53 +00001862 DAG.getConstant(N1C->getAPIntValue() |
1863 C1->getAPIntValue(), VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001864 }
1865 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1866 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1867 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1868 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1869
1870 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands92c43912008-06-06 12:08:01 +00001871 LL.getValueType().isInteger()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001872 // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1873 // fold (X < 0) | (Y < 0) -> (X|Y < 0)
Dan Gohman9d24dc72008-03-13 22:13:53 +00001874 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001875 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1876 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1877 AddToWorkList(ORNode.Val);
1878 return DAG.getSetCC(VT, ORNode, LR, Op1);
1879 }
1880 // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1881 // fold (X > -1) | (Y > -1) -> (X&Y > -1)
1882 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1883 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1884 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1885 AddToWorkList(ANDNode.Val);
1886 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1887 }
1888 }
1889 // canonicalize equivalent to ll == rl
1890 if (LL == RR && LR == RL) {
1891 Op1 = ISD::getSetCCSwappedOperands(Op1);
1892 std::swap(RL, RR);
1893 }
1894 if (LL == RL && LR == RR) {
Duncan Sands92c43912008-06-06 12:08:01 +00001895 bool isInteger = LL.getValueType().isInteger();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001896 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1897 if (Result != ISD::SETCC_INVALID)
1898 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1899 }
1900 }
1901
1902 // Simplify: or (op x...), (op y...) -> (op (or x, y))
1903 if (N0.getOpcode() == N1.getOpcode()) {
1904 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1905 if (Tmp.Val) return Tmp;
1906 }
1907
1908 // (X & C1) | (Y & C2) -> (X|Y) & C3 if possible.
1909 if (N0.getOpcode() == ISD::AND &&
1910 N1.getOpcode() == ISD::AND &&
1911 N0.getOperand(1).getOpcode() == ISD::Constant &&
1912 N1.getOperand(1).getOpcode() == ISD::Constant &&
1913 // Don't increase # computations.
1914 (N0.Val->hasOneUse() || N1.Val->hasOneUse())) {
1915 // We can only do this xform if we know that bits from X that are set in C2
1916 // but not in C1 are already zero. Likewise for Y.
Dan Gohman07961cd2008-02-25 21:11:39 +00001917 const APInt &LHSMask =
1918 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1919 const APInt &RHSMask =
1920 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001921
1922 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
1923 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
1924 SDOperand X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
1925 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
1926 }
1927 }
1928
1929
1930 // See if this is some rotate idiom.
1931 if (SDNode *Rot = MatchRotate(N0, N1))
1932 return SDOperand(Rot, 0);
1933
1934 return SDOperand();
1935}
1936
1937
1938/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
1939static bool MatchRotateHalf(SDOperand Op, SDOperand &Shift, SDOperand &Mask) {
1940 if (Op.getOpcode() == ISD::AND) {
1941 if (isa<ConstantSDNode>(Op.getOperand(1))) {
1942 Mask = Op.getOperand(1);
1943 Op = Op.getOperand(0);
1944 } else {
1945 return false;
1946 }
1947 }
1948
1949 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
1950 Shift = Op;
1951 return true;
1952 }
1953 return false;
1954}
1955
1956
1957// MatchRotate - Handle an 'or' of two operands. If this is one of the many
1958// idioms for rotate, and if the target supports rotation instructions, generate
1959// a rot[lr].
1960SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
Duncan Sands2418bec2008-06-13 19:07:40 +00001961 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Duncan Sands92c43912008-06-06 12:08:01 +00001962 MVT VT = LHS.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001963 if (!TLI.isTypeLegal(VT)) return 0;
1964
1965 // The target must have at least one rotate flavor.
1966 bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
1967 bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
1968 if (!HasROTL && !HasROTR) return 0;
Duncan Sands2418bec2008-06-13 19:07:40 +00001969
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001970 // Match "(X shl/srl V1) & V2" where V2 may not be present.
1971 SDOperand LHSShift; // The shift.
1972 SDOperand LHSMask; // AND value if any.
1973 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
1974 return 0; // Not part of a rotate.
1975
1976 SDOperand RHSShift; // The shift.
1977 SDOperand RHSMask; // AND value if any.
1978 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
1979 return 0; // Not part of a rotate.
1980
1981 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
1982 return 0; // Not shifting the same value.
1983
1984 if (LHSShift.getOpcode() == RHSShift.getOpcode())
1985 return 0; // Shifts must disagree.
1986
1987 // Canonicalize shl to left side in a shl/srl pair.
1988 if (RHSShift.getOpcode() == ISD::SHL) {
1989 std::swap(LHS, RHS);
1990 std::swap(LHSShift, RHSShift);
1991 std::swap(LHSMask , RHSMask );
1992 }
1993
Duncan Sands92c43912008-06-06 12:08:01 +00001994 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001995 SDOperand LHSShiftArg = LHSShift.getOperand(0);
1996 SDOperand LHSShiftAmt = LHSShift.getOperand(1);
1997 SDOperand RHSShiftAmt = RHSShift.getOperand(1);
1998
1999 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
2000 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
2001 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2002 RHSShiftAmt.getOpcode() == ISD::Constant) {
2003 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getValue();
2004 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getValue();
2005 if ((LShVal + RShVal) != OpSizeInBits)
2006 return 0;
2007
2008 SDOperand Rot;
2009 if (HasROTL)
2010 Rot = DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt);
2011 else
2012 Rot = DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt);
2013
2014 // If there is an AND of either shifted operand, apply it to the result.
2015 if (LHSMask.Val || RHSMask.Val) {
Dan Gohmand047c3e2008-03-03 23:51:38 +00002016 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002017
2018 if (LHSMask.Val) {
Dan Gohmand047c3e2008-03-03 23:51:38 +00002019 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2020 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002021 }
2022 if (RHSMask.Val) {
Dan Gohmand047c3e2008-03-03 23:51:38 +00002023 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2024 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002025 }
2026
2027 Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
2028 }
2029
2030 return Rot.Val;
2031 }
2032
2033 // If there is a mask here, and we have a variable shift, we can't be sure
2034 // that we're masking out the right stuff.
2035 if (LHSMask.Val || RHSMask.Val)
2036 return 0;
2037
2038 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2039 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2040 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2041 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2042 if (ConstantSDNode *SUBC =
2043 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
Dan Gohman9d24dc72008-03-13 22:13:53 +00002044 if (SUBC->getAPIntValue() == OpSizeInBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002045 if (HasROTL)
2046 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2047 else
2048 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
Anton Korobeynikov53422f62008-02-20 11:10:28 +00002049 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002050 }
2051 }
2052
2053 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2054 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2055 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2056 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2057 if (ConstantSDNode *SUBC =
2058 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
Dan Gohman9d24dc72008-03-13 22:13:53 +00002059 if (SUBC->getAPIntValue() == OpSizeInBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002060 if (HasROTL)
2061 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2062 else
2063 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
Anton Korobeynikov53422f62008-02-20 11:10:28 +00002064 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002065 }
2066 }
2067
2068 // Look for sign/zext/any-extended cases:
2069 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2070 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2071 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND) &&
2072 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2073 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2074 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND)) {
2075 SDOperand LExtOp0 = LHSShiftAmt.getOperand(0);
2076 SDOperand RExtOp0 = RHSShiftAmt.getOperand(0);
2077 if (RExtOp0.getOpcode() == ISD::SUB &&
2078 RExtOp0.getOperand(1) == LExtOp0) {
2079 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2080 // (rotr x, y)
2081 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2082 // (rotl x, (sub 32, y))
2083 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
Dan Gohman9d24dc72008-03-13 22:13:53 +00002084 if (SUBC->getAPIntValue() == OpSizeInBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002085 if (HasROTL)
2086 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2087 else
2088 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2089 }
2090 }
2091 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2092 RExtOp0 == LExtOp0.getOperand(1)) {
2093 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2094 // (rotl x, y)
2095 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2096 // (rotr x, (sub 32, y))
2097 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
Dan Gohman9d24dc72008-03-13 22:13:53 +00002098 if (SUBC->getAPIntValue() == OpSizeInBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002099 if (HasROTL)
2100 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, RHSShiftAmt).Val;
2101 else
2102 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2103 }
2104 }
2105 }
2106 }
2107
2108 return 0;
2109}
2110
2111
2112SDOperand DAGCombiner::visitXOR(SDNode *N) {
2113 SDOperand N0 = N->getOperand(0);
2114 SDOperand N1 = N->getOperand(1);
2115 SDOperand LHS, RHS, CC;
2116 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2117 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Duncan Sands92c43912008-06-06 12:08:01 +00002118 MVT VT = N0.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002119
2120 // fold vector ops
Duncan Sands92c43912008-06-06 12:08:01 +00002121 if (VT.isVector()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002122 SDOperand FoldedVOp = SimplifyVBinOp(N);
2123 if (FoldedVOp.Val) return FoldedVOp;
2124 }
2125
Evan Cheng5d00cb42008-03-25 20:08:07 +00002126 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2127 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2128 return DAG.getConstant(0, VT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002129 // fold (xor x, undef) -> undef
2130 if (N0.getOpcode() == ISD::UNDEF)
2131 return N0;
2132 if (N1.getOpcode() == ISD::UNDEF)
2133 return N1;
2134 // fold (xor c1, c2) -> c1^c2
2135 if (N0C && N1C)
2136 return DAG.getNode(ISD::XOR, VT, N0, N1);
2137 // canonicalize constant to RHS
2138 if (N0C && !N1C)
2139 return DAG.getNode(ISD::XOR, VT, N1, N0);
2140 // fold (xor x, 0) -> x
2141 if (N1C && N1C->isNullValue())
2142 return N0;
2143 // reassociate xor
2144 SDOperand RXOR = ReassociateOps(ISD::XOR, N0, N1);
2145 if (RXOR.Val != 0)
2146 return RXOR;
2147 // fold !(x cc y) -> (x !cc y)
Dan Gohman9d24dc72008-03-13 22:13:53 +00002148 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands92c43912008-06-06 12:08:01 +00002149 bool isInt = LHS.getValueType().isInteger();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002150 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2151 isInt);
2152 if (N0.getOpcode() == ISD::SETCC)
2153 return DAG.getSetCC(VT, LHS, RHS, NotCC);
2154 if (N0.getOpcode() == ISD::SELECT_CC)
2155 return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
2156 assert(0 && "Unhandled SetCC Equivalent!");
2157 abort();
2158 }
Chris Lattnere27cd502007-09-10 21:39:07 +00002159 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohman9d24dc72008-03-13 22:13:53 +00002160 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Chris Lattnere27cd502007-09-10 21:39:07 +00002161 N0.Val->hasOneUse() && isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2162 SDOperand V = N0.getOperand(0);
2163 V = DAG.getNode(ISD::XOR, V.getValueType(), V,
Duncan Sandsbed21472007-10-10 09:54:50 +00002164 DAG.getConstant(1, V.getValueType()));
Chris Lattnere27cd502007-09-10 21:39:07 +00002165 AddToWorkList(V.Val);
2166 return DAG.getNode(ISD::ZERO_EXTEND, VT, V);
2167 }
2168
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002169 // fold !(x or y) -> (!x and !y) iff x or y are setcc
Dan Gohman9d24dc72008-03-13 22:13:53 +00002170 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002171 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2172 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2173 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2174 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2175 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2176 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2177 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2178 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2179 }
2180 }
2181 // fold !(x or y) -> (!x and !y) iff x or y are constants
2182 if (N1C && N1C->isAllOnesValue() &&
2183 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2184 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2185 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2186 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2187 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2188 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2189 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2190 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2191 }
2192 }
2193 // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
2194 if (N1C && N0.getOpcode() == ISD::XOR) {
2195 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2196 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2197 if (N00C)
2198 return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
Dan Gohman9d24dc72008-03-13 22:13:53 +00002199 DAG.getConstant(N1C->getAPIntValue()^
2200 N00C->getAPIntValue(), VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002201 if (N01C)
2202 return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
Dan Gohman9d24dc72008-03-13 22:13:53 +00002203 DAG.getConstant(N1C->getAPIntValue()^
2204 N01C->getAPIntValue(), VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002205 }
2206 // fold (xor x, x) -> 0
2207 if (N0 == N1) {
Duncan Sands92c43912008-06-06 12:08:01 +00002208 if (!VT.isVector()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002209 return DAG.getConstant(0, VT);
2210 } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
2211 // Produce a vector of zeros.
Duncan Sands92c43912008-06-06 12:08:01 +00002212 SDOperand El = DAG.getConstant(0, VT.getVectorElementType());
2213 std::vector<SDOperand> Ops(VT.getVectorNumElements(), El);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002214 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
2215 }
2216 }
2217
2218 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2219 if (N0.getOpcode() == N1.getOpcode()) {
2220 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2221 if (Tmp.Val) return Tmp;
2222 }
2223
2224 // Simplify the expression using non-local knowledge.
Duncan Sands92c43912008-06-06 12:08:01 +00002225 if (!VT.isVector() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002226 SimplifyDemandedBits(SDOperand(N, 0)))
2227 return SDOperand(N, 0);
2228
2229 return SDOperand();
2230}
2231
Chris Lattner91ed3c32007-12-06 07:33:36 +00002232/// visitShiftByConstant - Handle transforms common to the three shifts, when
2233/// the shift amount is a constant.
2234SDOperand DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2235 SDNode *LHS = N->getOperand(0).Val;
2236 if (!LHS->hasOneUse()) return SDOperand();
2237
2238 // We want to pull some binops through shifts, so that we have (and (shift))
2239 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2240 // thing happens with address calculations, so it's important to canonicalize
2241 // it.
2242 bool HighBitSet = false; // Can we transform this if the high bit is set?
2243
2244 switch (LHS->getOpcode()) {
2245 default: return SDOperand();
2246 case ISD::OR:
2247 case ISD::XOR:
2248 HighBitSet = false; // We can only transform sra if the high bit is clear.
2249 break;
2250 case ISD::AND:
2251 HighBitSet = true; // We can only transform sra if the high bit is set.
2252 break;
2253 case ISD::ADD:
2254 if (N->getOpcode() != ISD::SHL)
2255 return SDOperand(); // only shl(add) not sr[al](add).
2256 HighBitSet = false; // We can only transform sra if the high bit is clear.
2257 break;
2258 }
2259
2260 // We require the RHS of the binop to be a constant as well.
2261 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2262 if (!BinOpCst) return SDOperand();
2263
Chris Lattnerdcd19762007-12-06 07:47:55 +00002264
2265 // FIXME: disable this for unless the input to the binop is a shift by a
2266 // constant. If it is not a shift, it pessimizes some common cases like:
2267 //
2268 //void foo(int *X, int i) { X[i & 1235] = 1; }
2269 //int bar(int *X, int i) { return X[i & 255]; }
2270 SDNode *BinOpLHSVal = LHS->getOperand(0).Val;
2271 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2272 BinOpLHSVal->getOpcode() != ISD::SRA &&
2273 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2274 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2275 return SDOperand();
2276
Duncan Sands92c43912008-06-06 12:08:01 +00002277 MVT VT = N->getValueType(0);
Chris Lattner91ed3c32007-12-06 07:33:36 +00002278
2279 // If this is a signed shift right, and the high bit is modified
2280 // by the logical operation, do not perform the transformation.
2281 // The highBitSet boolean indicates the value of the high bit of
2282 // the constant which would cause it to be modified for this
2283 // operation.
2284 if (N->getOpcode() == ISD::SRA) {
Dan Gohmand047c3e2008-03-03 23:51:38 +00002285 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2286 if (BinOpRHSSignSet != HighBitSet)
Chris Lattner91ed3c32007-12-06 07:33:36 +00002287 return SDOperand();
2288 }
2289
2290 // Fold the constants, shifting the binop RHS by the shift amount.
2291 SDOperand NewRHS = DAG.getNode(N->getOpcode(), N->getValueType(0),
2292 LHS->getOperand(1), N->getOperand(1));
2293
2294 // Create the new shift.
2295 SDOperand NewShift = DAG.getNode(N->getOpcode(), VT, LHS->getOperand(0),
2296 N->getOperand(1));
2297
2298 // Create the new binop.
2299 return DAG.getNode(LHS->getOpcode(), VT, NewShift, NewRHS);
2300}
2301
2302
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002303SDOperand DAGCombiner::visitSHL(SDNode *N) {
2304 SDOperand N0 = N->getOperand(0);
2305 SDOperand N1 = N->getOperand(1);
2306 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2307 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Duncan Sands92c43912008-06-06 12:08:01 +00002308 MVT VT = N0.getValueType();
2309 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002310
2311 // fold (shl c1, c2) -> c1<<c2
2312 if (N0C && N1C)
2313 return DAG.getNode(ISD::SHL, VT, N0, N1);
2314 // fold (shl 0, x) -> 0
2315 if (N0C && N0C->isNullValue())
2316 return N0;
2317 // fold (shl x, c >= size(x)) -> undef
2318 if (N1C && N1C->getValue() >= OpSizeInBits)
2319 return DAG.getNode(ISD::UNDEF, VT);
2320 // fold (shl x, 0) -> x
2321 if (N1C && N1C->isNullValue())
2322 return N0;
2323 // if (shl x, c) is known to be zero, return 0
Dan Gohman07961cd2008-02-25 21:11:39 +00002324 if (DAG.MaskedValueIsZero(SDOperand(N, 0),
Duncan Sands92c43912008-06-06 12:08:01 +00002325 APInt::getAllOnesValue(VT.getSizeInBits())))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002326 return DAG.getConstant(0, VT);
2327 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2328 return SDOperand(N, 0);
2329 // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
2330 if (N1C && N0.getOpcode() == ISD::SHL &&
2331 N0.getOperand(1).getOpcode() == ISD::Constant) {
2332 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2333 uint64_t c2 = N1C->getValue();
2334 if (c1 + c2 > OpSizeInBits)
2335 return DAG.getConstant(0, VT);
2336 return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
2337 DAG.getConstant(c1 + c2, N1.getValueType()));
2338 }
2339 // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
2340 // (srl (and x, -1 << c1), c1-c2)
2341 if (N1C && N0.getOpcode() == ISD::SRL &&
2342 N0.getOperand(1).getOpcode() == ISD::Constant) {
2343 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2344 uint64_t c2 = N1C->getValue();
2345 SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2346 DAG.getConstant(~0ULL << c1, VT));
2347 if (c2 > c1)
2348 return DAG.getNode(ISD::SHL, VT, Mask,
2349 DAG.getConstant(c2-c1, N1.getValueType()));
2350 else
2351 return DAG.getNode(ISD::SRL, VT, Mask,
2352 DAG.getConstant(c1-c2, N1.getValueType()));
2353 }
2354 // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
2355 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
2356 return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2357 DAG.getConstant(~0ULL << N1C->getValue(), VT));
Chris Lattner91ed3c32007-12-06 07:33:36 +00002358
2359 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002360}
2361
2362SDOperand DAGCombiner::visitSRA(SDNode *N) {
2363 SDOperand N0 = N->getOperand(0);
2364 SDOperand N1 = N->getOperand(1);
2365 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2366 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Duncan Sands92c43912008-06-06 12:08:01 +00002367 MVT VT = N0.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002368
2369 // fold (sra c1, c2) -> c1>>c2
2370 if (N0C && N1C)
2371 return DAG.getNode(ISD::SRA, VT, N0, N1);
2372 // fold (sra 0, x) -> 0
2373 if (N0C && N0C->isNullValue())
2374 return N0;
2375 // fold (sra -1, x) -> -1
2376 if (N0C && N0C->isAllOnesValue())
2377 return N0;
2378 // fold (sra x, c >= size(x)) -> undef
Duncan Sands92c43912008-06-06 12:08:01 +00002379 if (N1C && N1C->getValue() >= VT.getSizeInBits())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002380 return DAG.getNode(ISD::UNDEF, VT);
2381 // fold (sra x, 0) -> x
2382 if (N1C && N1C->isNullValue())
2383 return N0;
2384 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2385 // sext_inreg.
2386 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Duncan Sands92c43912008-06-06 12:08:01 +00002387 unsigned LowBits = VT.getSizeInBits() - (unsigned)N1C->getValue();
Duncan Sands6a437fb2008-06-09 11:32:28 +00002388 MVT EVT = MVT::getIntegerVT(LowBits);
Duncan Sands2418bec2008-06-13 19:07:40 +00002389 if (EVT.isSimple() && // TODO: remove when apint codegen support lands.
2390 (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002391 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
2392 DAG.getValueType(EVT));
2393 }
Duncan Sands2418bec2008-06-13 19:07:40 +00002394
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002395 // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
2396 if (N1C && N0.getOpcode() == ISD::SRA) {
2397 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2398 unsigned Sum = N1C->getValue() + C1->getValue();
Duncan Sands92c43912008-06-06 12:08:01 +00002399 if (Sum >= VT.getSizeInBits()) Sum = VT.getSizeInBits()-1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002400 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
2401 DAG.getConstant(Sum, N1C->getValueType(0)));
2402 }
2403 }
Christopher Lambfc5c1642008-03-19 08:30:06 +00002404
2405 // fold sra (shl X, m), result_size - n
2406 // -> (sign_extend (trunc (shl X, result_size - n - m))) for
Christopher Lamb21e8a952008-03-20 04:31:39 +00002407 // result_size - n != m.
2408 // If truncate is free for the target sext(shl) is likely to result in better
2409 // code.
Christopher Lambfc5c1642008-03-19 08:30:06 +00002410 if (N0.getOpcode() == ISD::SHL) {
2411 // Get the two constanst of the shifts, CN0 = m, CN = n.
2412 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2413 if (N01C && N1C) {
Christopher Lamb21e8a952008-03-20 04:31:39 +00002414 // Determine what the truncate's result bitsize and type would be.
Duncan Sands92c43912008-06-06 12:08:01 +00002415 unsigned VTValSize = VT.getSizeInBits();
2416 MVT TruncVT =
2417 MVT::getIntegerVT(VTValSize - N1C->getValue());
Christopher Lamb21e8a952008-03-20 04:31:39 +00002418 // Determine the residual right-shift amount.
Christopher Lambfc5c1642008-03-19 08:30:06 +00002419 unsigned ShiftAmt = N1C->getValue() - N01C->getValue();
Duncan Sands2418bec2008-06-13 19:07:40 +00002420
Christopher Lamb21e8a952008-03-20 04:31:39 +00002421 // If the shift is not a no-op (in which case this should be just a sign
2422 // extend already), the truncated to type is legal, sign_extend is legal
2423 // on that type, and the the truncate to that type is both legal and free,
2424 // perform the transform.
2425 if (ShiftAmt &&
Christopher Lamb21e8a952008-03-20 04:31:39 +00002426 TLI.isOperationLegal(ISD::SIGN_EXTEND, TruncVT) &&
2427 TLI.isOperationLegal(ISD::TRUNCATE, VT) &&
Evan Chengca0e80f2008-03-20 02:18:41 +00002428 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb21e8a952008-03-20 04:31:39 +00002429
2430 SDOperand Amt = DAG.getConstant(ShiftAmt, TLI.getShiftAmountTy());
2431 SDOperand Shift = DAG.getNode(ISD::SRL, VT, N0.getOperand(0), Amt);
2432 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, TruncVT, Shift);
2433 return DAG.getNode(ISD::SIGN_EXTEND, N->getValueType(0), Trunc);
Christopher Lambfc5c1642008-03-19 08:30:06 +00002434 }
2435 }
2436 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002437
2438 // Simplify, based on bits shifted out of the LHS.
2439 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2440 return SDOperand(N, 0);
2441
2442
2443 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman07961cd2008-02-25 21:11:39 +00002444 if (DAG.SignBitIsZero(N0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002445 return DAG.getNode(ISD::SRL, VT, N0, N1);
Chris Lattner91ed3c32007-12-06 07:33:36 +00002446
2447 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002448}
2449
2450SDOperand DAGCombiner::visitSRL(SDNode *N) {
2451 SDOperand N0 = N->getOperand(0);
2452 SDOperand N1 = N->getOperand(1);
2453 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2454 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Duncan Sands92c43912008-06-06 12:08:01 +00002455 MVT VT = N0.getValueType();
2456 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002457
2458 // fold (srl c1, c2) -> c1 >>u c2
2459 if (N0C && N1C)
2460 return DAG.getNode(ISD::SRL, VT, N0, N1);
2461 // fold (srl 0, x) -> 0
2462 if (N0C && N0C->isNullValue())
2463 return N0;
2464 // fold (srl x, c >= size(x)) -> undef
2465 if (N1C && N1C->getValue() >= OpSizeInBits)
2466 return DAG.getNode(ISD::UNDEF, VT);
2467 // fold (srl x, 0) -> x
2468 if (N1C && N1C->isNullValue())
2469 return N0;
2470 // if (srl x, c) is known to be zero, return 0
Dan Gohman07961cd2008-02-25 21:11:39 +00002471 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
2472 APInt::getAllOnesValue(OpSizeInBits)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002473 return DAG.getConstant(0, VT);
2474
2475 // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
2476 if (N1C && N0.getOpcode() == ISD::SRL &&
2477 N0.getOperand(1).getOpcode() == ISD::Constant) {
2478 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2479 uint64_t c2 = N1C->getValue();
2480 if (c1 + c2 > OpSizeInBits)
2481 return DAG.getConstant(0, VT);
2482 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
2483 DAG.getConstant(c1 + c2, N1.getValueType()));
2484 }
2485
2486 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2487 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2488 // Shifting in all undef bits?
Duncan Sands92c43912008-06-06 12:08:01 +00002489 MVT SmallVT = N0.getOperand(0).getValueType();
2490 if (N1C->getValue() >= SmallVT.getSizeInBits())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002491 return DAG.getNode(ISD::UNDEF, VT);
2492
2493 SDOperand SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
2494 AddToWorkList(SmallShift.Val);
2495 return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
2496 }
2497
2498 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
2499 // bit, which is unmodified by sra.
Duncan Sands92c43912008-06-06 12:08:01 +00002500 if (N1C && N1C->getValue()+1 == VT.getSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002501 if (N0.getOpcode() == ISD::SRA)
2502 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1);
2503 }
2504
2505 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
2506 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Duncan Sands92c43912008-06-06 12:08:01 +00002507 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
Dan Gohmanbea075f2008-02-20 16:33:30 +00002508 APInt KnownZero, KnownOne;
Duncan Sands92c43912008-06-06 12:08:01 +00002509 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002510 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2511
2512 // If any of the input bits are KnownOne, then the input couldn't be all
2513 // zeros, thus the result of the srl will always be zero.
Dan Gohmanbea075f2008-02-20 16:33:30 +00002514 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002515
2516 // If all of the bits input the to ctlz node are known to be zero, then
2517 // the result of the ctlz is "32" and the result of the shift is one.
Dan Gohmanbea075f2008-02-20 16:33:30 +00002518 APInt UnknownBits = ~KnownZero & Mask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002519 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2520
2521 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2522 if ((UnknownBits & (UnknownBits-1)) == 0) {
2523 // Okay, we know that only that the single bit specified by UnknownBits
2524 // could be set on input to the CTLZ node. If this bit is set, the SRL
2525 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2526 // to an SRL,XOR pair, which is likely to simplify more.
Dan Gohmanbea075f2008-02-20 16:33:30 +00002527 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002528 SDOperand Op = N0.getOperand(0);
2529 if (ShAmt) {
2530 Op = DAG.getNode(ISD::SRL, VT, Op,
2531 DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
2532 AddToWorkList(Op.Val);
2533 }
2534 return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
2535 }
2536 }
2537
2538 // fold operands of srl based on knowledge that the low bits are not
2539 // demanded.
2540 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2541 return SDOperand(N, 0);
2542
Chris Lattner91ed3c32007-12-06 07:33:36 +00002543 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002544}
2545
2546SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
2547 SDOperand N0 = N->getOperand(0);
Duncan Sands92c43912008-06-06 12:08:01 +00002548 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002549
2550 // fold (ctlz c1) -> c2
2551 if (isa<ConstantSDNode>(N0))
2552 return DAG.getNode(ISD::CTLZ, VT, N0);
2553 return SDOperand();
2554}
2555
2556SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
2557 SDOperand N0 = N->getOperand(0);
Duncan Sands92c43912008-06-06 12:08:01 +00002558 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002559
2560 // fold (cttz c1) -> c2
2561 if (isa<ConstantSDNode>(N0))
2562 return DAG.getNode(ISD::CTTZ, VT, N0);
2563 return SDOperand();
2564}
2565
2566SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
2567 SDOperand N0 = N->getOperand(0);
Duncan Sands92c43912008-06-06 12:08:01 +00002568 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002569
2570 // fold (ctpop c1) -> c2
2571 if (isa<ConstantSDNode>(N0))
2572 return DAG.getNode(ISD::CTPOP, VT, N0);
2573 return SDOperand();
2574}
2575
2576SDOperand DAGCombiner::visitSELECT(SDNode *N) {
2577 SDOperand N0 = N->getOperand(0);
2578 SDOperand N1 = N->getOperand(1);
2579 SDOperand N2 = N->getOperand(2);
2580 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2581 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2582 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Duncan Sands92c43912008-06-06 12:08:01 +00002583 MVT VT = N->getValueType(0);
2584 MVT VT0 = N0.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002585
2586 // fold select C, X, X -> X
2587 if (N1 == N2)
2588 return N1;
2589 // fold select true, X, Y -> X
2590 if (N0C && !N0C->isNullValue())
2591 return N1;
2592 // fold select false, X, Y -> Y
2593 if (N0C && N0C->isNullValue())
2594 return N2;
2595 // fold select C, 1, X -> C | X
Duncan Sands92c43912008-06-06 12:08:01 +00002596 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002597 return DAG.getNode(ISD::OR, VT, N0, N2);
Evan Chengff601dc2007-08-18 05:57:05 +00002598 // fold select C, 0, 1 -> ~C
Duncan Sands92c43912008-06-06 12:08:01 +00002599 if (VT.isInteger() && VT0.isInteger() &&
Dan Gohman9d24dc72008-03-13 22:13:53 +00002600 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Evan Chengff601dc2007-08-18 05:57:05 +00002601 SDOperand XORNode = DAG.getNode(ISD::XOR, VT0, N0, DAG.getConstant(1, VT0));
2602 if (VT == VT0)
2603 return XORNode;
2604 AddToWorkList(XORNode.Val);
Duncan Sandsec142ee2008-06-08 20:54:56 +00002605 if (VT.bitsGT(VT0))
Evan Chengff601dc2007-08-18 05:57:05 +00002606 return DAG.getNode(ISD::ZERO_EXTEND, VT, XORNode);
2607 return DAG.getNode(ISD::TRUNCATE, VT, XORNode);
2608 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002609 // fold select C, 0, X -> ~C & X
Dale Johannesen53e0ad72007-12-06 17:53:31 +00002610 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
2611 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002612 AddToWorkList(XORNode.Val);
2613 return DAG.getNode(ISD::AND, VT, XORNode, N2);
2614 }
2615 // fold select C, X, 1 -> ~C | X
Dan Gohman9d24dc72008-03-13 22:13:53 +00002616 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Dale Johannesen53e0ad72007-12-06 17:53:31 +00002617 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002618 AddToWorkList(XORNode.Val);
2619 return DAG.getNode(ISD::OR, VT, XORNode, N1);
2620 }
2621 // fold select C, X, 0 -> C & X
2622 // FIXME: this should check for C type == X type, not i1?
Duncan Sands92c43912008-06-06 12:08:01 +00002623 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002624 return DAG.getNode(ISD::AND, VT, N0, N1);
2625 // fold X ? X : Y --> X ? 1 : Y --> X | Y
Duncan Sands92c43912008-06-06 12:08:01 +00002626 if (VT == MVT::i1 && N0 == N1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002627 return DAG.getNode(ISD::OR, VT, N0, N2);
2628 // fold X ? Y : X --> X ? Y : 0 --> X & Y
Duncan Sands92c43912008-06-06 12:08:01 +00002629 if (VT == MVT::i1 && N0 == N2)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002630 return DAG.getNode(ISD::AND, VT, N0, N1);
2631
2632 // If we can fold this based on the true/false value, do so.
2633 if (SimplifySelectOps(N, N1, N2))
2634 return SDOperand(N, 0); // Don't revisit N.
Duncan Sands2418bec2008-06-13 19:07:40 +00002635
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002636 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov53422f62008-02-20 11:10:28 +00002637 if (N0.getOpcode() == ISD::SETCC) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002638 // FIXME:
2639 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2640 // having to say they don't support SELECT_CC on every type the DAG knows
2641 // about, since there is no way to mark an opcode illegal at all value types
2642 if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
2643 return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
2644 N1, N2, N0.getOperand(2));
2645 else
2646 return SimplifySelect(N0, N1, N2);
Anton Korobeynikov53422f62008-02-20 11:10:28 +00002647 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002648 return SDOperand();
2649}
2650
2651SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
2652 SDOperand N0 = N->getOperand(0);
2653 SDOperand N1 = N->getOperand(1);
2654 SDOperand N2 = N->getOperand(2);
2655 SDOperand N3 = N->getOperand(3);
2656 SDOperand N4 = N->getOperand(4);
2657 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2658
2659 // fold select_cc lhs, rhs, x, x, cc -> x
2660 if (N2 == N3)
2661 return N2;
2662
2663 // Determine if the condition we're dealing with is constant
Scott Michel502151f2008-03-10 15:42:14 +00002664 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002665 if (SCC.Val) AddToWorkList(SCC.Val);
2666
2667 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val)) {
Dan Gohman9d24dc72008-03-13 22:13:53 +00002668 if (!SCCC->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002669 return N2; // cond always true -> true val
2670 else
2671 return N3; // cond always false -> false val
2672 }
2673
2674 // Fold to a simpler select_cc
2675 if (SCC.Val && SCC.getOpcode() == ISD::SETCC)
2676 return DAG.getNode(ISD::SELECT_CC, N2.getValueType(),
2677 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2678 SCC.getOperand(2));
2679
2680 // If we can fold this based on the true/false value, do so.
2681 if (SimplifySelectOps(N, N2, N3))
2682 return SDOperand(N, 0); // Don't revisit N.
2683
2684 // fold select_cc into other things, such as min/max/abs
2685 return SimplifySelectCC(N0, N1, N2, N3, CC);
2686}
2687
2688SDOperand DAGCombiner::visitSETCC(SDNode *N) {
2689 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2690 cast<CondCodeSDNode>(N->getOperand(2))->get());
2691}
2692
Evan Cheng9decb332007-10-29 19:58:20 +00002693// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
2694// "fold ({s|z}ext (load x)) -> ({s|z}ext (truncate ({s|z}extload x)))"
2695// transformation. Returns true if extension are possible and the above
2696// mentioned transformation is profitable.
2697static bool ExtendUsesToFormExtLoad(SDNode *N, SDOperand N0,
2698 unsigned ExtOpc,
2699 SmallVector<SDNode*, 4> &ExtendNodes,
2700 TargetLowering &TLI) {
2701 bool HasCopyToRegUses = false;
2702 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
2703 for (SDNode::use_iterator UI = N0.Val->use_begin(), UE = N0.Val->use_end();
2704 UI != UE; ++UI) {
Roman Levenstein05650fd2008-04-07 10:06:32 +00002705 SDNode *User = UI->getUser();
Evan Cheng9decb332007-10-29 19:58:20 +00002706 if (User == N)
2707 continue;
2708 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
2709 if (User->getOpcode() == ISD::SETCC) {
2710 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
2711 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
2712 // Sign bits will be lost after a zext.
2713 return false;
2714 bool Add = false;
2715 for (unsigned i = 0; i != 2; ++i) {
2716 SDOperand UseOp = User->getOperand(i);
2717 if (UseOp == N0)
2718 continue;
2719 if (!isa<ConstantSDNode>(UseOp))
2720 return false;
2721 Add = true;
2722 }
2723 if (Add)
2724 ExtendNodes.push_back(User);
2725 } else {
2726 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2727 SDOperand UseOp = User->getOperand(i);
2728 if (UseOp == N0) {
2729 // If truncate from extended type to original load type is free
2730 // on this target, then it's ok to extend a CopyToReg.
2731 if (isTruncFree && User->getOpcode() == ISD::CopyToReg)
2732 HasCopyToRegUses = true;
2733 else
2734 return false;
2735 }
2736 }
2737 }
2738 }
2739
2740 if (HasCopyToRegUses) {
2741 bool BothLiveOut = false;
2742 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
2743 UI != UE; ++UI) {
Roman Levenstein05650fd2008-04-07 10:06:32 +00002744 SDNode *User = UI->getUser();
Evan Cheng9decb332007-10-29 19:58:20 +00002745 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2746 SDOperand UseOp = User->getOperand(i);
2747 if (UseOp.Val == N && UseOp.ResNo == 0) {
2748 BothLiveOut = true;
2749 break;
2750 }
2751 }
2752 }
2753 if (BothLiveOut)
2754 // Both unextended and extended values are live out. There had better be
2755 // good a reason for the transformation.
2756 return ExtendNodes.size();
2757 }
2758 return true;
2759}
2760
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002761SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2762 SDOperand N0 = N->getOperand(0);
Duncan Sands92c43912008-06-06 12:08:01 +00002763 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002764
2765 // fold (sext c1) -> c1
2766 if (isa<ConstantSDNode>(N0))
2767 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
2768
2769 // fold (sext (sext x)) -> (sext x)
2770 // fold (sext (aext x)) -> (sext x)
2771 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2772 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
2773
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002774 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2e0e0cf2008-05-20 20:56:33 +00002775 // fold (sext (truncate (load x))) -> (sext (smaller load x))
2776 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002777 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2778 if (NarrowLoad.Val) {
2779 if (NarrowLoad.Val != N0.Val)
2780 CombineTo(N0.Val, NarrowLoad);
2781 return DAG.getNode(ISD::SIGN_EXTEND, VT, NarrowLoad);
2782 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002783
Dan Gohman2e0e0cf2008-05-20 20:56:33 +00002784 // See if the value being truncated is already sign extended. If so, just
2785 // eliminate the trunc/sext pair.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002786 SDOperand Op = N0.getOperand(0);
Duncan Sands92c43912008-06-06 12:08:01 +00002787 unsigned OpBits = Op.getValueType().getSizeInBits();
2788 unsigned MidBits = N0.getValueType().getSizeInBits();
2789 unsigned DestBits = VT.getSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002790 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
2791
2792 if (OpBits == DestBits) {
2793 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
2794 // bits, it is already ready.
2795 if (NumSignBits > DestBits-MidBits)
2796 return Op;
2797 } else if (OpBits < DestBits) {
2798 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
2799 // bits, just sext from i32.
2800 if (NumSignBits > OpBits-MidBits)
2801 return DAG.getNode(ISD::SIGN_EXTEND, VT, Op);
2802 } else {
2803 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
2804 // bits, just truncate to i32.
2805 if (NumSignBits > OpBits-MidBits)
2806 return DAG.getNode(ISD::TRUNCATE, VT, Op);
2807 }
2808
2809 // fold (sext (truncate x)) -> (sextinreg x).
2810 if (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
2811 N0.getValueType())) {
Duncan Sandsec142ee2008-06-08 20:54:56 +00002812 if (Op.getValueType().bitsLT(VT))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002813 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
Duncan Sandsec142ee2008-06-08 20:54:56 +00002814 else if (Op.getValueType().bitsGT(VT))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002815 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2816 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op,
2817 DAG.getValueType(N0.getValueType()));
2818 }
2819 }
2820
2821 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Evan Cheng9decb332007-10-29 19:58:20 +00002822 if (ISD::isNON_EXTLoad(N0.Val) &&
Duncan Sands2418bec2008-06-13 19:07:40 +00002823 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
2824 TLI.isLoadXLegal(ISD::SEXTLOAD, N0.getValueType()))) {
Evan Cheng9decb332007-10-29 19:58:20 +00002825 bool DoXform = true;
2826 SmallVector<SDNode*, 4> SetCCs;
2827 if (!N0.hasOneUse())
2828 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
2829 if (DoXform) {
2830 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2831 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2832 LN0->getBasePtr(), LN0->getSrcValue(),
2833 LN0->getSrcValueOffset(),
2834 N0.getValueType(),
2835 LN0->isVolatile(),
2836 LN0->getAlignment());
2837 CombineTo(N, ExtLoad);
2838 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2839 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2840 // Extend SetCC uses if necessary.
2841 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2842 SDNode *SetCC = SetCCs[i];
2843 SmallVector<SDOperand, 4> Ops;
2844 for (unsigned j = 0; j != 2; ++j) {
2845 SDOperand SOp = SetCC->getOperand(j);
2846 if (SOp == Trunc)
2847 Ops.push_back(ExtLoad);
2848 else
2849 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, VT, SOp));
2850 }
2851 Ops.push_back(SetCC->getOperand(2));
2852 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2853 &Ops[0], Ops.size()));
2854 }
2855 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2856 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002857 }
2858
2859 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
2860 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
2861 if ((ISD::isSEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2862 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2863 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Duncan Sands92c43912008-06-06 12:08:01 +00002864 MVT EVT = LN0->getMemoryVT();
Duncan Sands2418bec2008-06-13 19:07:40 +00002865 if ((!AfterLegalize && !LN0->isVolatile()) ||
2866 TLI.isLoadXLegal(ISD::SEXTLOAD, EVT)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002867 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2868 LN0->getBasePtr(), LN0->getSrcValue(),
2869 LN0->getSrcValueOffset(), EVT,
2870 LN0->isVolatile(),
2871 LN0->getAlignment());
2872 CombineTo(N, ExtLoad);
2873 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2874 ExtLoad.getValue(1));
2875 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2876 }
2877 }
2878
2879 // sext(setcc x,y,cc) -> select_cc x, y, -1, 0, cc
2880 if (N0.getOpcode() == ISD::SETCC) {
2881 SDOperand SCC =
2882 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2883 DAG.getConstant(~0ULL, VT), DAG.getConstant(0, VT),
2884 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2885 if (SCC.Val) return SCC;
2886 }
2887
Dan Gohman415e13a2008-04-28 16:58:24 +00002888 // fold (sext x) -> (zext x) if the sign bit is known zero.
Dan Gohman5b37f9d2008-04-28 18:47:17 +00002889 if ((!AfterLegalize || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
2890 DAG.SignBitIsZero(N0))
Dan Gohman415e13a2008-04-28 16:58:24 +00002891 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2892
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002893 return SDOperand();
2894}
2895
2896SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
2897 SDOperand N0 = N->getOperand(0);
Duncan Sands92c43912008-06-06 12:08:01 +00002898 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002899
2900 // fold (zext c1) -> c1
2901 if (isa<ConstantSDNode>(N0))
2902 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2903 // fold (zext (zext x)) -> (zext x)
2904 // fold (zext (aext x)) -> (zext x)
2905 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2906 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
2907
2908 // fold (zext (truncate (load x))) -> (zext (smaller load x))
2909 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
2910 if (N0.getOpcode() == ISD::TRUNCATE) {
2911 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2912 if (NarrowLoad.Val) {
2913 if (NarrowLoad.Val != N0.Val)
2914 CombineTo(N0.Val, NarrowLoad);
2915 return DAG.getNode(ISD::ZERO_EXTEND, VT, NarrowLoad);
2916 }
2917 }
2918
2919 // fold (zext (truncate x)) -> (and x, mask)
2920 if (N0.getOpcode() == ISD::TRUNCATE &&
2921 (!AfterLegalize || TLI.isOperationLegal(ISD::AND, VT))) {
2922 SDOperand Op = N0.getOperand(0);
Duncan Sandsec142ee2008-06-08 20:54:56 +00002923 if (Op.getValueType().bitsLT(VT)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002924 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
Duncan Sandsec142ee2008-06-08 20:54:56 +00002925 } else if (Op.getValueType().bitsGT(VT)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002926 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2927 }
2928 return DAG.getZeroExtendInReg(Op, N0.getValueType());
2929 }
2930
2931 // fold (zext (and (trunc x), cst)) -> (and x, cst).
2932 if (N0.getOpcode() == ISD::AND &&
2933 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2934 N0.getOperand(1).getOpcode() == ISD::Constant) {
2935 SDOperand X = N0.getOperand(0).getOperand(0);
Duncan Sandsec142ee2008-06-08 20:54:56 +00002936 if (X.getValueType().bitsLT(VT)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002937 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
Duncan Sandsec142ee2008-06-08 20:54:56 +00002938 } else if (X.getValueType().bitsGT(VT)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002939 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2940 }
Dan Gohmand047c3e2008-03-03 23:51:38 +00002941 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Duncan Sands92c43912008-06-06 12:08:01 +00002942 Mask.zext(VT.getSizeInBits());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002943 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2944 }
2945
2946 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Evan Cheng9decb332007-10-29 19:58:20 +00002947 if (ISD::isNON_EXTLoad(N0.Val) &&
Duncan Sands2418bec2008-06-13 19:07:40 +00002948 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
2949 TLI.isLoadXLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Cheng9decb332007-10-29 19:58:20 +00002950 bool DoXform = true;
2951 SmallVector<SDNode*, 4> SetCCs;
2952 if (!N0.hasOneUse())
2953 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
2954 if (DoXform) {
2955 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2956 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2957 LN0->getBasePtr(), LN0->getSrcValue(),
2958 LN0->getSrcValueOffset(),
2959 N0.getValueType(),
2960 LN0->isVolatile(),
2961 LN0->getAlignment());
2962 CombineTo(N, ExtLoad);
2963 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2964 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2965 // Extend SetCC uses if necessary.
2966 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2967 SDNode *SetCC = SetCCs[i];
2968 SmallVector<SDOperand, 4> Ops;
2969 for (unsigned j = 0; j != 2; ++j) {
2970 SDOperand SOp = SetCC->getOperand(j);
2971 if (SOp == Trunc)
2972 Ops.push_back(ExtLoad);
2973 else
Evan Cheng06aaf4c2007-10-30 20:11:21 +00002974 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND, VT, SOp));
Evan Cheng9decb332007-10-29 19:58:20 +00002975 }
2976 Ops.push_back(SetCC->getOperand(2));
2977 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2978 &Ops[0], Ops.size()));
2979 }
2980 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2981 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002982 }
2983
2984 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
2985 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
2986 if ((ISD::isZEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2987 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2988 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Duncan Sands92c43912008-06-06 12:08:01 +00002989 MVT EVT = LN0->getMemoryVT();
Duncan Sands2418bec2008-06-13 19:07:40 +00002990 if ((!AfterLegalize && !LN0->isVolatile()) ||
2991 TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT)) {
2992 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2993 LN0->getBasePtr(), LN0->getSrcValue(),
2994 LN0->getSrcValueOffset(), EVT,
2995 LN0->isVolatile(),
2996 LN0->getAlignment());
2997 CombineTo(N, ExtLoad);
2998 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2999 ExtLoad.getValue(1));
3000 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3001 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003002 }
3003
3004 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3005 if (N0.getOpcode() == ISD::SETCC) {
3006 SDOperand SCC =
3007 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3008 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3009 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3010 if (SCC.Val) return SCC;
3011 }
3012
3013 return SDOperand();
3014}
3015
3016SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
3017 SDOperand N0 = N->getOperand(0);
Duncan Sands92c43912008-06-06 12:08:01 +00003018 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003019
3020 // fold (aext c1) -> c1
3021 if (isa<ConstantSDNode>(N0))
3022 return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
3023 // fold (aext (aext x)) -> (aext x)
3024 // fold (aext (zext x)) -> (zext x)
3025 // fold (aext (sext x)) -> (sext x)
3026 if (N0.getOpcode() == ISD::ANY_EXTEND ||
3027 N0.getOpcode() == ISD::ZERO_EXTEND ||
3028 N0.getOpcode() == ISD::SIGN_EXTEND)
3029 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3030
3031 // fold (aext (truncate (load x))) -> (aext (smaller load x))
3032 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
3033 if (N0.getOpcode() == ISD::TRUNCATE) {
3034 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
3035 if (NarrowLoad.Val) {
3036 if (NarrowLoad.Val != N0.Val)
3037 CombineTo(N0.Val, NarrowLoad);
3038 return DAG.getNode(ISD::ANY_EXTEND, VT, NarrowLoad);
3039 }
3040 }
3041
3042 // fold (aext (truncate x))
3043 if (N0.getOpcode() == ISD::TRUNCATE) {
3044 SDOperand TruncOp = N0.getOperand(0);
3045 if (TruncOp.getValueType() == VT)
3046 return TruncOp; // x iff x size == zext size.
Duncan Sandsec142ee2008-06-08 20:54:56 +00003047 if (TruncOp.getValueType().bitsGT(VT))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003048 return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
3049 return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
3050 }
3051
3052 // fold (aext (and (trunc x), cst)) -> (and x, cst).
3053 if (N0.getOpcode() == ISD::AND &&
3054 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3055 N0.getOperand(1).getOpcode() == ISD::Constant) {
3056 SDOperand X = N0.getOperand(0).getOperand(0);
Duncan Sandsec142ee2008-06-08 20:54:56 +00003057 if (X.getValueType().bitsLT(VT)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003058 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
Duncan Sandsec142ee2008-06-08 20:54:56 +00003059 } else if (X.getValueType().bitsGT(VT)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003060 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3061 }
Dan Gohmand047c3e2008-03-03 23:51:38 +00003062 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Duncan Sands92c43912008-06-06 12:08:01 +00003063 Mask.zext(VT.getSizeInBits());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003064 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
3065 }
3066
3067 // fold (aext (load x)) -> (aext (truncate (extload x)))
3068 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
Duncan Sands2418bec2008-06-13 19:07:40 +00003069 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3070 TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003071 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3072 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3073 LN0->getBasePtr(), LN0->getSrcValue(),
3074 LN0->getSrcValueOffset(),
3075 N0.getValueType(),
3076 LN0->isVolatile(),
3077 LN0->getAlignment());
3078 CombineTo(N, ExtLoad);
3079 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3080 ExtLoad.getValue(1));
3081 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3082 }
3083
3084 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
3085 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
3086 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
3087 if (N0.getOpcode() == ISD::LOAD &&
3088 !ISD::isNON_EXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
3089 N0.hasOneUse()) {
3090 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Duncan Sands92c43912008-06-06 12:08:01 +00003091 MVT EVT = LN0->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003092 SDOperand ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
3093 LN0->getChain(), LN0->getBasePtr(),
3094 LN0->getSrcValue(),
3095 LN0->getSrcValueOffset(), EVT,
3096 LN0->isVolatile(),
3097 LN0->getAlignment());
3098 CombineTo(N, ExtLoad);
3099 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3100 ExtLoad.getValue(1));
3101 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3102 }
3103
3104 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3105 if (N0.getOpcode() == ISD::SETCC) {
3106 SDOperand SCC =
3107 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3108 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3109 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3110 if (SCC.Val)
3111 return SCC;
3112 }
3113
3114 return SDOperand();
3115}
3116
Chris Lattnere8671c52007-10-13 06:35:54 +00003117/// GetDemandedBits - See if the specified operand can be simplified with the
3118/// knowledge that only the bits specified by Mask are used. If so, return the
3119/// simpler operand, otherwise return a null SDOperand.
Dan Gohman07961cd2008-02-25 21:11:39 +00003120SDOperand DAGCombiner::GetDemandedBits(SDOperand V, const APInt &Mask) {
Chris Lattnere8671c52007-10-13 06:35:54 +00003121 switch (V.getOpcode()) {
3122 default: break;
3123 case ISD::OR:
3124 case ISD::XOR:
3125 // If the LHS or RHS don't contribute bits to the or, drop them.
3126 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3127 return V.getOperand(1);
3128 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3129 return V.getOperand(0);
3130 break;
Chris Lattnerb77ea552007-10-13 06:58:48 +00003131 case ISD::SRL:
3132 // Only look at single-use SRLs.
3133 if (!V.Val->hasOneUse())
3134 break;
3135 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3136 // See if we can recursively simplify the LHS.
3137 unsigned Amt = RHSC->getValue();
Dan Gohman07961cd2008-02-25 21:11:39 +00003138 APInt NewMask = Mask << Amt;
3139 SDOperand SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Chris Lattnerb77ea552007-10-13 06:58:48 +00003140 if (SimplifyLHS.Val) {
3141 return DAG.getNode(ISD::SRL, V.getValueType(),
3142 SimplifyLHS, V.getOperand(1));
3143 }
3144 }
Chris Lattnere8671c52007-10-13 06:35:54 +00003145 }
3146 return SDOperand();
3147}
3148
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003149/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3150/// bits and then truncated to a narrower type and where N is a multiple
3151/// of number of bits of the narrower type, transform it to a narrower load
3152/// from address + N / num of bits of new type. If the result is to be
3153/// extended, also fold the extension to form a extending load.
3154SDOperand DAGCombiner::ReduceLoadWidth(SDNode *N) {
3155 unsigned Opc = N->getOpcode();
3156 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3157 SDOperand N0 = N->getOperand(0);
Duncan Sands92c43912008-06-06 12:08:01 +00003158 MVT VT = N->getValueType(0);
3159 MVT EVT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003160
3161 // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then
3162 // extended to VT.
3163 if (Opc == ISD::SIGN_EXTEND_INREG) {
3164 ExtType = ISD::SEXTLOAD;
3165 EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3166 if (AfterLegalize && !TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))
3167 return SDOperand();
3168 }
3169
Duncan Sands92c43912008-06-06 12:08:01 +00003170 unsigned EVTBits = EVT.getSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003171 unsigned ShAmt = 0;
3172 bool CombineSRL = false;
3173 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3174 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3175 ShAmt = N01->getValue();
3176 // Is the shift amount a multiple of size of VT?
3177 if ((ShAmt & (EVTBits-1)) == 0) {
3178 N0 = N0.getOperand(0);
Duncan Sands92c43912008-06-06 12:08:01 +00003179 if (N0.getValueType().getSizeInBits() <= EVTBits)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003180 return SDOperand();
3181 CombineSRL = true;
3182 }
3183 }
3184 }
3185
Duncan Sands3ea93352008-06-16 08:14:38 +00003186 // Do not generate loads of non-round integer types since these can
3187 // be expensive (and would be wrong if the type is not byte sized).
3188 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() && VT.isRound() &&
Duncan Sands2418bec2008-06-13 19:07:40 +00003189 // Do not change the width of a volatile load.
3190 !cast<LoadSDNode>(N0)->isVolatile()) {
Duncan Sands92c43912008-06-06 12:08:01 +00003191 assert(N0.getValueType().getSizeInBits() > EVTBits &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003192 "Cannot truncate to larger type!");
3193 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Duncan Sands92c43912008-06-06 12:08:01 +00003194 MVT PtrType = N0.getOperand(1).getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003195 // For big endian targets, we need to adjust the offset to the pointer to
3196 // load the correct bytes.
Duncan Sands9ff8fbf2008-02-11 10:37:04 +00003197 if (TLI.isBigEndian()) {
Duncan Sands92c43912008-06-06 12:08:01 +00003198 unsigned LVTStoreBits = N0.getValueType().getStoreSizeInBits();
3199 unsigned EVTStoreBits = EVT.getStoreSizeInBits();
Duncan Sands4f18d4f2007-11-09 08:57:19 +00003200 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3201 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003202 uint64_t PtrOff = ShAmt / 8;
Duncan Sandsa3691432007-10-28 12:59:45 +00003203 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003204 SDOperand NewPtr = DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
3205 DAG.getConstant(PtrOff, PtrType));
3206 AddToWorkList(NewPtr.Val);
3207 SDOperand Load = (ExtType == ISD::NON_EXTLOAD)
3208 ? DAG.getLoad(VT, LN0->getChain(), NewPtr,
3209 LN0->getSrcValue(), LN0->getSrcValueOffset(),
Duncan Sandsa3691432007-10-28 12:59:45 +00003210 LN0->isVolatile(), NewAlign)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003211 : DAG.getExtLoad(ExtType, VT, LN0->getChain(), NewPtr,
3212 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
Duncan Sandsa3691432007-10-28 12:59:45 +00003213 LN0->isVolatile(), NewAlign);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003214 AddToWorkList(N);
3215 if (CombineSRL) {
Chris Lattner7bcb18f2008-02-03 06:49:24 +00003216 WorkListRemover DeadNodes(*this);
3217 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3218 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003219 CombineTo(N->getOperand(0).Val, Load);
3220 } else
3221 CombineTo(N0.Val, Load, Load.getValue(1));
3222 if (ShAmt) {
3223 if (Opc == ISD::SIGN_EXTEND_INREG)
3224 return DAG.getNode(Opc, VT, Load, N->getOperand(1));
3225 else
3226 return DAG.getNode(Opc, VT, Load);
3227 }
3228 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3229 }
3230
3231 return SDOperand();
3232}
3233
3234
3235SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
3236 SDOperand N0 = N->getOperand(0);
3237 SDOperand N1 = N->getOperand(1);
Duncan Sands92c43912008-06-06 12:08:01 +00003238 MVT VT = N->getValueType(0);
3239 MVT EVT = cast<VTSDNode>(N1)->getVT();
3240 unsigned VTBits = VT.getSizeInBits();
3241 unsigned EVTBits = EVT.getSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003242
3243 // fold (sext_in_reg c1) -> c1
3244 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
3245 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
3246
3247 // If the input is already sign extended, just drop the extension.
Duncan Sands92c43912008-06-06 12:08:01 +00003248 if (DAG.ComputeNumSignBits(N0) >= VT.getSizeInBits()-EVTBits+1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003249 return N0;
3250
3251 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
3252 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Duncan Sandsec142ee2008-06-08 20:54:56 +00003253 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003254 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
3255 }
3256
3257 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman07961cd2008-02-25 21:11:39 +00003258 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003259 return DAG.getZeroExtendInReg(N0, EVT);
3260
3261 // fold operands of sext_in_reg based on knowledge that the top bits are not
3262 // demanded.
3263 if (SimplifyDemandedBits(SDOperand(N, 0)))
3264 return SDOperand(N, 0);
3265
3266 // fold (sext_in_reg (load x)) -> (smaller sextload x)
3267 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
3268 SDOperand NarrowLoad = ReduceLoadWidth(N);
3269 if (NarrowLoad.Val)
3270 return NarrowLoad;
3271
3272 // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
3273 // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
3274 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
3275 if (N0.getOpcode() == ISD::SRL) {
3276 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Duncan Sands92c43912008-06-06 12:08:01 +00003277 if (ShAmt->getValue()+EVTBits <= VT.getSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003278 // We can turn this into an SRA iff the input to the SRL is already sign
3279 // extended enough.
3280 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Duncan Sands92c43912008-06-06 12:08:01 +00003281 if (VT.getSizeInBits()-(ShAmt->getValue()+EVTBits) < InSignBits)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003282 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
3283 }
3284 }
3285
3286 // fold (sext_inreg (extload x)) -> (sextload x)
3287 if (ISD::isEXTLoad(N0.Val) &&
3288 ISD::isUNINDEXEDLoad(N0.Val) &&
Dan Gohman9a4c92c2008-01-30 00:15:11 +00003289 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sands2418bec2008-06-13 19:07:40 +00003290 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3291 TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003292 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3293 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3294 LN0->getBasePtr(), LN0->getSrcValue(),
3295 LN0->getSrcValueOffset(), EVT,
3296 LN0->isVolatile(),
3297 LN0->getAlignment());
3298 CombineTo(N, ExtLoad);
3299 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3300 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3301 }
3302 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
3303 if (ISD::isZEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
3304 N0.hasOneUse() &&
Dan Gohman9a4c92c2008-01-30 00:15:11 +00003305 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sands2418bec2008-06-13 19:07:40 +00003306 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3307 TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003308 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3309 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3310 LN0->getBasePtr(), LN0->getSrcValue(),
3311 LN0->getSrcValueOffset(), EVT,
3312 LN0->isVolatile(),
3313 LN0->getAlignment());
3314 CombineTo(N, ExtLoad);
3315 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3316 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3317 }
3318 return SDOperand();
3319}
3320
3321SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
3322 SDOperand N0 = N->getOperand(0);
Duncan Sands92c43912008-06-06 12:08:01 +00003323 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003324
3325 // noop truncate
3326 if (N0.getValueType() == N->getValueType(0))
3327 return N0;
3328 // fold (truncate c1) -> c1
3329 if (isa<ConstantSDNode>(N0))
3330 return DAG.getNode(ISD::TRUNCATE, VT, N0);
3331 // fold (truncate (truncate x)) -> (truncate x)
3332 if (N0.getOpcode() == ISD::TRUNCATE)
3333 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3334 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
3335 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
3336 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sandsec142ee2008-06-08 20:54:56 +00003337 if (N0.getOperand(0).getValueType().bitsLT(VT))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003338 // if the source is smaller than the dest, we still need an extend
3339 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
Duncan Sandsec142ee2008-06-08 20:54:56 +00003340 else if (N0.getOperand(0).getValueType().bitsGT(VT))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003341 // if the source is larger than the dest, than we just need the truncate
3342 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3343 else
3344 // if the source and dest are the same type, we can drop both the extend
3345 // and the truncate
3346 return N0.getOperand(0);
3347 }
3348
Chris Lattnere8671c52007-10-13 06:35:54 +00003349 // See if we can simplify the input to this truncate through knowledge that
3350 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
3351 // -> trunc y
Dan Gohman07961cd2008-02-25 21:11:39 +00003352 SDOperand Shorter =
3353 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
Duncan Sands92c43912008-06-06 12:08:01 +00003354 VT.getSizeInBits()));
Chris Lattnere8671c52007-10-13 06:35:54 +00003355 if (Shorter.Val)
3356 return DAG.getNode(ISD::TRUNCATE, VT, Shorter);
3357
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003358 // fold (truncate (load x)) -> (smaller load x)
3359 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
3360 return ReduceLoadWidth(N);
3361}
3362
Evan Chengb6290462008-05-12 23:04:07 +00003363static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
3364 SDOperand Elt = N->getOperand(i);
3365 if (Elt.getOpcode() != ISD::MERGE_VALUES)
3366 return Elt.Val;
3367 return Elt.getOperand(Elt.ResNo).Val;
3368}
3369
3370/// CombineConsecutiveLoads - build_pair (load, load) -> load
3371/// if load locations are consecutive.
Duncan Sands92c43912008-06-06 12:08:01 +00003372SDOperand DAGCombiner::CombineConsecutiveLoads(SDNode *N, MVT VT) {
Evan Chengb6290462008-05-12 23:04:07 +00003373 assert(N->getOpcode() == ISD::BUILD_PAIR);
3374
3375 SDNode *LD1 = getBuildPairElt(N, 0);
3376 if (!ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse())
3377 return SDOperand();
Duncan Sands92c43912008-06-06 12:08:01 +00003378 MVT LD1VT = LD1->getValueType(0);
Evan Chengb6290462008-05-12 23:04:07 +00003379 SDNode *LD2 = getBuildPairElt(N, 1);
3380 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3381 if (ISD::isNON_EXTLoad(LD2) &&
3382 LD2->hasOneUse() &&
Duncan Sands2418bec2008-06-13 19:07:40 +00003383 // If both are volatile this would reduce the number of volatile loads.
3384 // If one is volatile it might be ok, but play conservative and bail out.
3385 !cast<LoadSDNode>(LD1)->isVolatile() &&
3386 !cast<LoadSDNode>(LD2)->isVolatile() &&
Duncan Sands92c43912008-06-06 12:08:01 +00003387 TLI.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1, MFI)) {
Evan Chengb6290462008-05-12 23:04:07 +00003388 LoadSDNode *LD = cast<LoadSDNode>(LD1);
3389 unsigned Align = LD->getAlignment();
3390 unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
Duncan Sands92c43912008-06-06 12:08:01 +00003391 getABITypeAlignment(VT.getTypeForMVT());
Duncan Sands2418bec2008-06-13 19:07:40 +00003392 if (NewAlign <= Align &&
3393 (!AfterLegalize || TLI.isOperationLegal(ISD::LOAD, VT)))
Evan Chengb6290462008-05-12 23:04:07 +00003394 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(),
3395 LD->getSrcValue(), LD->getSrcValueOffset(),
Duncan Sands2418bec2008-06-13 19:07:40 +00003396 false, Align);
Evan Chengb6290462008-05-12 23:04:07 +00003397 }
3398 return SDOperand();
3399}
3400
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003401SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
3402 SDOperand N0 = N->getOperand(0);
Duncan Sands92c43912008-06-06 12:08:01 +00003403 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003404
3405 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
3406 // Only do this before legalize, since afterward the target may be depending
3407 // on the bitconvert.
3408 // First check to see if this is all constant.
3409 if (!AfterLegalize &&
3410 N0.getOpcode() == ISD::BUILD_VECTOR && N0.Val->hasOneUse() &&
Duncan Sands92c43912008-06-06 12:08:01 +00003411 VT.isVector()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003412 bool isSimple = true;
3413 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
3414 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
3415 N0.getOperand(i).getOpcode() != ISD::Constant &&
3416 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
3417 isSimple = false;
3418 break;
3419 }
3420
Duncan Sands92c43912008-06-06 12:08:01 +00003421 MVT DestEltVT = N->getValueType(0).getVectorElementType();
3422 assert(!DestEltVT.isVector() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003423 "Element type of vector ValueType must not be vector!");
3424 if (isSimple) {
3425 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.Val, DestEltVT);
3426 }
3427 }
3428
3429 // If the input is a constant, let getNode() fold it.
3430 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
3431 SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3432 if (Res.Val != N) return Res;
3433 }
3434
3435 if (N0.getOpcode() == ISD::BIT_CONVERT) // conv(conv(x,t1),t2) -> conv(x,t2)
3436 return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3437
3438 // fold (conv (load x)) -> (load (conv*)x)
Evan Chengd7ba7ed2007-10-06 08:19:55 +00003439 // If the resultant load doesn't need a higher alignment than the original!
3440 if (ISD::isNormalLoad(N0.Val) && N0.hasOneUse() &&
Duncan Sands2418bec2008-06-13 19:07:40 +00003441 // Do not change the width of a volatile load.
3442 !cast<LoadSDNode>(N0)->isVolatile() &&
3443 (!AfterLegalize || TLI.isOperationLegal(ISD::LOAD, VT))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003444 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3445 unsigned Align = TLI.getTargetMachine().getTargetData()->
Duncan Sands92c43912008-06-06 12:08:01 +00003446 getABITypeAlignment(VT.getTypeForMVT());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003447 unsigned OrigAlign = LN0->getAlignment();
3448 if (Align <= OrigAlign) {
3449 SDOperand Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(),
3450 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3451 LN0->isVolatile(), Align);
3452 AddToWorkList(N);
3453 CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
3454 Load.getValue(1));
3455 return Load;
3456 }
3457 }
Duncan Sands2418bec2008-06-13 19:07:40 +00003458
Chris Lattneref26cbc2008-01-27 17:42:27 +00003459 // Fold bitconvert(fneg(x)) -> xor(bitconvert(x), signbit)
3460 // Fold bitconvert(fabs(x)) -> and(bitconvert(x), ~signbit)
3461 // This often reduces constant pool loads.
3462 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
Duncan Sands92c43912008-06-06 12:08:01 +00003463 N0.Val->hasOneUse() && VT.isInteger() && !VT.isVector()) {
Chris Lattneref26cbc2008-01-27 17:42:27 +00003464 SDOperand NewConv = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3465 AddToWorkList(NewConv.Val);
3466
Duncan Sands92c43912008-06-06 12:08:01 +00003467 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattneref26cbc2008-01-27 17:42:27 +00003468 if (N0.getOpcode() == ISD::FNEG)
3469 return DAG.getNode(ISD::XOR, VT, NewConv, DAG.getConstant(SignBit, VT));
3470 assert(N0.getOpcode() == ISD::FABS);
3471 return DAG.getNode(ISD::AND, VT, NewConv, DAG.getConstant(~SignBit, VT));
3472 }
3473
3474 // Fold bitconvert(fcopysign(cst, x)) -> bitconvert(x)&sign | cst&~sign'
3475 // Note that we don't handle copysign(x,cst) because this can always be folded
3476 // to an fneg or fabs.
3477 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse() &&
Chris Lattner336672f2008-01-27 23:32:17 +00003478 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands92c43912008-06-06 12:08:01 +00003479 VT.isInteger() && !VT.isVector()) {
3480 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
3481 SDOperand X = DAG.getNode(ISD::BIT_CONVERT,
3482 MVT::getIntegerVT(OrigXWidth),
Chris Lattneref26cbc2008-01-27 17:42:27 +00003483 N0.getOperand(1));
3484 AddToWorkList(X.Val);
3485
3486 // If X has a different width than the result/lhs, sext it or truncate it.
Duncan Sands92c43912008-06-06 12:08:01 +00003487 unsigned VTWidth = VT.getSizeInBits();
Chris Lattneref26cbc2008-01-27 17:42:27 +00003488 if (OrigXWidth < VTWidth) {
3489 X = DAG.getNode(ISD::SIGN_EXTEND, VT, X);
3490 AddToWorkList(X.Val);
3491 } else if (OrigXWidth > VTWidth) {
3492 // To get the sign bit in the right place, we have to shift it right
3493 // before truncating.
3494 X = DAG.getNode(ISD::SRL, X.getValueType(), X,
3495 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
3496 AddToWorkList(X.Val);
3497 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3498 AddToWorkList(X.Val);
3499 }
3500
Duncan Sands92c43912008-06-06 12:08:01 +00003501 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattneref26cbc2008-01-27 17:42:27 +00003502 X = DAG.getNode(ISD::AND, VT, X, DAG.getConstant(SignBit, VT));
3503 AddToWorkList(X.Val);
3504
3505 SDOperand Cst = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3506 Cst = DAG.getNode(ISD::AND, VT, Cst, DAG.getConstant(~SignBit, VT));
3507 AddToWorkList(Cst.Val);
3508
3509 return DAG.getNode(ISD::OR, VT, X, Cst);
3510 }
Evan Chengb6290462008-05-12 23:04:07 +00003511
3512 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
3513 if (N0.getOpcode() == ISD::BUILD_PAIR) {
3514 SDOperand CombineLD = CombineConsecutiveLoads(N0.Val, VT);
3515 if (CombineLD.Val)
3516 return CombineLD;
3517 }
Chris Lattneref26cbc2008-01-27 17:42:27 +00003518
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003519 return SDOperand();
3520}
3521
Evan Chengb6290462008-05-12 23:04:07 +00003522SDOperand DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Duncan Sands92c43912008-06-06 12:08:01 +00003523 MVT VT = N->getValueType(0);
Evan Chengb6290462008-05-12 23:04:07 +00003524 return CombineConsecutiveLoads(N, VT);
3525}
3526
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003527/// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
3528/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
3529/// destination element value type.
3530SDOperand DAGCombiner::
Duncan Sands92c43912008-06-06 12:08:01 +00003531ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT DstEltVT) {
3532 MVT SrcEltVT = BV->getOperand(0).getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003533
3534 // If this is already the right type, we're done.
3535 if (SrcEltVT == DstEltVT) return SDOperand(BV, 0);
3536
Duncan Sands92c43912008-06-06 12:08:01 +00003537 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
3538 unsigned DstBitSize = DstEltVT.getSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003539
3540 // If this is a conversion of N elements of one type to N elements of another
3541 // type, convert each element. This handles FP<->INT cases.
3542 if (SrcBitSize == DstBitSize) {
3543 SmallVector<SDOperand, 8> Ops;
3544 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3545 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
3546 AddToWorkList(Ops.back().Val);
3547 }
Duncan Sands92c43912008-06-06 12:08:01 +00003548 MVT VT = MVT::getVectorVT(DstEltVT,
3549 BV->getValueType(0).getVectorNumElements());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003550 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3551 }
3552
3553 // Otherwise, we're growing or shrinking the elements. To avoid having to
3554 // handle annoying details of growing/shrinking FP values, we convert them to
3555 // int first.
Duncan Sands92c43912008-06-06 12:08:01 +00003556 if (SrcEltVT.isFloatingPoint()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003557 // Convert the input float vector to a int vector where the elements are the
3558 // same sizes.
3559 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
Duncan Sands6a437fb2008-06-09 11:32:28 +00003560 MVT IntVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003561 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).Val;
3562 SrcEltVT = IntVT;
3563 }
3564
3565 // Now we know the input is an integer vector. If the output is a FP type,
3566 // convert to integer first, then to FP of the right size.
Duncan Sands92c43912008-06-06 12:08:01 +00003567 if (DstEltVT.isFloatingPoint()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003568 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
Duncan Sands6a437fb2008-06-09 11:32:28 +00003569 MVT TmpVT = MVT::getIntegerVT(DstEltVT.getSizeInBits());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003570 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).Val;
3571
3572 // Next, convert to FP elements of the same size.
3573 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
3574 }
3575
3576 // Okay, we know the src/dst types are both integers of differing types.
3577 // Handling growing first.
Duncan Sands92c43912008-06-06 12:08:01 +00003578 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003579 if (SrcBitSize < DstBitSize) {
3580 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
3581
3582 SmallVector<SDOperand, 8> Ops;
3583 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
3584 i += NumInputsPerOutput) {
3585 bool isLE = TLI.isLittleEndian();
Dan Gohmand047c3e2008-03-03 23:51:38 +00003586 APInt NewBits = APInt(DstBitSize, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003587 bool EltIsUndef = true;
3588 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
3589 // Shift the previously computed bits over.
3590 NewBits <<= SrcBitSize;
3591 SDOperand Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
3592 if (Op.getOpcode() == ISD::UNDEF) continue;
3593 EltIsUndef = false;
3594
Dan Gohmand047c3e2008-03-03 23:51:38 +00003595 NewBits |=
3596 APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).zext(DstBitSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003597 }
3598
3599 if (EltIsUndef)
3600 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3601 else
3602 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
3603 }
3604
Duncan Sands92c43912008-06-06 12:08:01 +00003605 MVT VT = MVT::getVectorVT(DstEltVT, Ops.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003606 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3607 }
3608
3609 // Finally, this must be the case where we are shrinking elements: each input
3610 // turns into multiple outputs.
Evan Chengd1045a62008-02-18 23:04:32 +00003611 bool isS2V = ISD::isScalarToVector(BV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003612 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Duncan Sands92c43912008-06-06 12:08:01 +00003613 MVT VT = MVT::getVectorVT(DstEltVT, NumOutputsPerInput*BV->getNumOperands());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003614 SmallVector<SDOperand, 8> Ops;
3615 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3616 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
3617 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
3618 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3619 continue;
3620 }
Dan Gohmand047c3e2008-03-03 23:51:38 +00003621 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getAPIntValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003622 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Dan Gohmand047c3e2008-03-03 23:51:38 +00003623 APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003624 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Dan Gohmand047c3e2008-03-03 23:51:38 +00003625 if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
Evan Chengd1045a62008-02-18 23:04:32 +00003626 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
3627 return DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Ops[0]);
Dan Gohmand047c3e2008-03-03 23:51:38 +00003628 OpVal = OpVal.lshr(DstBitSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003629 }
3630
3631 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands9ff8fbf2008-02-11 10:37:04 +00003632 if (TLI.isBigEndian())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003633 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
3634 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003635 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3636}
3637
3638
3639
3640SDOperand DAGCombiner::visitFADD(SDNode *N) {
3641 SDOperand N0 = N->getOperand(0);
3642 SDOperand N1 = N->getOperand(1);
3643 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3644 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Duncan Sands92c43912008-06-06 12:08:01 +00003645 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003646
3647 // fold vector ops
Duncan Sands92c43912008-06-06 12:08:01 +00003648 if (VT.isVector()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003649 SDOperand FoldedVOp = SimplifyVBinOp(N);
3650 if (FoldedVOp.Val) return FoldedVOp;
3651 }
3652
3653 // fold (fadd c1, c2) -> c1+c2
Dale Johannesenb89072e2007-10-16 23:38:29 +00003654 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003655 return DAG.getNode(ISD::FADD, VT, N0, N1);
3656 // canonicalize constant to RHS
3657 if (N0CFP && !N1CFP)
3658 return DAG.getNode(ISD::FADD, VT, N1, N0);
3659 // fold (A + (-B)) -> A-B
Chris Lattnere0992b82008-02-26 07:04:54 +00003660 if (isNegatibleForFree(N1, AfterLegalize) == 2)
3661 return DAG.getNode(ISD::FSUB, VT, N0,
3662 GetNegatedExpression(N1, DAG, AfterLegalize));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003663 // fold ((-A) + B) -> B-A
Chris Lattnere0992b82008-02-26 07:04:54 +00003664 if (isNegatibleForFree(N0, AfterLegalize) == 2)
3665 return DAG.getNode(ISD::FSUB, VT, N1,
3666 GetNegatedExpression(N0, DAG, AfterLegalize));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003667
3668 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
3669 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
3670 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3671 return DAG.getNode(ISD::FADD, VT, N0.getOperand(0),
3672 DAG.getNode(ISD::FADD, VT, N0.getOperand(1), N1));
3673
3674 return SDOperand();
3675}
3676
3677SDOperand DAGCombiner::visitFSUB(SDNode *N) {
3678 SDOperand N0 = N->getOperand(0);
3679 SDOperand N1 = N->getOperand(1);
3680 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3681 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Duncan Sands92c43912008-06-06 12:08:01 +00003682 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003683
3684 // fold vector ops
Duncan Sands92c43912008-06-06 12:08:01 +00003685 if (VT.isVector()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003686 SDOperand FoldedVOp = SimplifyVBinOp(N);
3687 if (FoldedVOp.Val) return FoldedVOp;
3688 }
3689
3690 // fold (fsub c1, c2) -> c1-c2
Dale Johannesenb89072e2007-10-16 23:38:29 +00003691 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003692 return DAG.getNode(ISD::FSUB, VT, N0, N1);
3693 // fold (0-B) -> -B
Dale Johannesen7604c1b2007-08-31 23:34:27 +00003694 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
Chris Lattnere0992b82008-02-26 07:04:54 +00003695 if (isNegatibleForFree(N1, AfterLegalize))
3696 return GetNegatedExpression(N1, DAG, AfterLegalize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003697 return DAG.getNode(ISD::FNEG, VT, N1);
3698 }
3699 // fold (A-(-B)) -> A+B
Chris Lattnere0992b82008-02-26 07:04:54 +00003700 if (isNegatibleForFree(N1, AfterLegalize))
3701 return DAG.getNode(ISD::FADD, VT, N0,
3702 GetNegatedExpression(N1, DAG, AfterLegalize));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003703
3704 return SDOperand();
3705}
3706
3707SDOperand DAGCombiner::visitFMUL(SDNode *N) {
3708 SDOperand N0 = N->getOperand(0);
3709 SDOperand N1 = N->getOperand(1);
3710 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3711 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Duncan Sands92c43912008-06-06 12:08:01 +00003712 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003713
3714 // fold vector ops
Duncan Sands92c43912008-06-06 12:08:01 +00003715 if (VT.isVector()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003716 SDOperand FoldedVOp = SimplifyVBinOp(N);
3717 if (FoldedVOp.Val) return FoldedVOp;
3718 }
3719
3720 // fold (fmul c1, c2) -> c1*c2
Dale Johannesenb89072e2007-10-16 23:38:29 +00003721 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003722 return DAG.getNode(ISD::FMUL, VT, N0, N1);
3723 // canonicalize constant to RHS
3724 if (N0CFP && !N1CFP)
3725 return DAG.getNode(ISD::FMUL, VT, N1, N0);
3726 // fold (fmul X, 2.0) -> (fadd X, X)
3727 if (N1CFP && N1CFP->isExactlyValue(+2.0))
3728 return DAG.getNode(ISD::FADD, VT, N0, N0);
3729 // fold (fmul X, -1.0) -> (fneg X)
3730 if (N1CFP && N1CFP->isExactlyValue(-1.0))
3731 return DAG.getNode(ISD::FNEG, VT, N0);
3732
3733 // -X * -Y -> X*Y
Chris Lattnere0992b82008-02-26 07:04:54 +00003734 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3735 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003736 // Both can be negated for free, check to see if at least one is cheaper
3737 // negated.
3738 if (LHSNeg == 2 || RHSNeg == 2)
Chris Lattnere0992b82008-02-26 07:04:54 +00003739 return DAG.getNode(ISD::FMUL, VT,
3740 GetNegatedExpression(N0, DAG, AfterLegalize),
3741 GetNegatedExpression(N1, DAG, AfterLegalize));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003742 }
3743 }
3744
3745 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
3746 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
3747 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3748 return DAG.getNode(ISD::FMUL, VT, N0.getOperand(0),
3749 DAG.getNode(ISD::FMUL, VT, N0.getOperand(1), N1));
3750
3751 return SDOperand();
3752}
3753
3754SDOperand DAGCombiner::visitFDIV(SDNode *N) {
3755 SDOperand N0 = N->getOperand(0);
3756 SDOperand N1 = N->getOperand(1);
3757 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3758 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Duncan Sands92c43912008-06-06 12:08:01 +00003759 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003760
3761 // fold vector ops
Duncan Sands92c43912008-06-06 12:08:01 +00003762 if (VT.isVector()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003763 SDOperand FoldedVOp = SimplifyVBinOp(N);
3764 if (FoldedVOp.Val) return FoldedVOp;
3765 }
3766
3767 // fold (fdiv c1, c2) -> c1/c2
Dale Johannesenb89072e2007-10-16 23:38:29 +00003768 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003769 return DAG.getNode(ISD::FDIV, VT, N0, N1);
3770
3771
3772 // -X / -Y -> X*Y
Chris Lattnere0992b82008-02-26 07:04:54 +00003773 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3774 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003775 // Both can be negated for free, check to see if at least one is cheaper
3776 // negated.
3777 if (LHSNeg == 2 || RHSNeg == 2)
Chris Lattnere0992b82008-02-26 07:04:54 +00003778 return DAG.getNode(ISD::FDIV, VT,
3779 GetNegatedExpression(N0, DAG, AfterLegalize),
3780 GetNegatedExpression(N1, DAG, AfterLegalize));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003781 }
3782 }
3783
3784 return SDOperand();
3785}
3786
3787SDOperand DAGCombiner::visitFREM(SDNode *N) {
3788 SDOperand N0 = N->getOperand(0);
3789 SDOperand N1 = N->getOperand(1);
3790 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3791 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Duncan Sands92c43912008-06-06 12:08:01 +00003792 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003793
3794 // fold (frem c1, c2) -> fmod(c1,c2)
Dale Johannesenb89072e2007-10-16 23:38:29 +00003795 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003796 return DAG.getNode(ISD::FREM, VT, N0, N1);
3797
3798 return SDOperand();
3799}
3800
3801SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
3802 SDOperand N0 = N->getOperand(0);
3803 SDOperand N1 = N->getOperand(1);
3804 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3805 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Duncan Sands92c43912008-06-06 12:08:01 +00003806 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003807
Dale Johannesenb89072e2007-10-16 23:38:29 +00003808 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003809 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
3810
3811 if (N1CFP) {
Dale Johannesenc53301c2007-08-26 01:18:27 +00003812 const APFloat& V = N1CFP->getValueAPF();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003813 // copysign(x, c1) -> fabs(x) iff ispos(c1)
3814 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dale Johannesen7f2c1d12007-08-25 22:10:57 +00003815 if (!V.isNegative())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003816 return DAG.getNode(ISD::FABS, VT, N0);
3817 else
3818 return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
3819 }
3820
3821 // copysign(fabs(x), y) -> copysign(x, y)
3822 // copysign(fneg(x), y) -> copysign(x, y)
3823 // copysign(copysign(x,z), y) -> copysign(x, y)
3824 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
3825 N0.getOpcode() == ISD::FCOPYSIGN)
3826 return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
3827
3828 // copysign(x, abs(y)) -> abs(x)
3829 if (N1.getOpcode() == ISD::FABS)
3830 return DAG.getNode(ISD::FABS, VT, N0);
3831
3832 // copysign(x, copysign(y,z)) -> copysign(x, z)
3833 if (N1.getOpcode() == ISD::FCOPYSIGN)
3834 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
3835
3836 // copysign(x, fp_extend(y)) -> copysign(x, y)
3837 // copysign(x, fp_round(y)) -> copysign(x, y)
3838 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
3839 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
3840
3841 return SDOperand();
3842}
3843
3844
3845
3846SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
3847 SDOperand N0 = N->getOperand(0);
3848 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Duncan Sands92c43912008-06-06 12:08:01 +00003849 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003850
3851 // fold (sint_to_fp c1) -> c1fp
Dale Johannesenb89072e2007-10-16 23:38:29 +00003852 if (N0C && N0.getValueType() != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003853 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
3854 return SDOperand();
3855}
3856
3857SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
3858 SDOperand N0 = N->getOperand(0);
3859 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Duncan Sands92c43912008-06-06 12:08:01 +00003860 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003861
3862 // fold (uint_to_fp c1) -> c1fp
Dale Johannesenb89072e2007-10-16 23:38:29 +00003863 if (N0C && N0.getValueType() != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003864 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
3865 return SDOperand();
3866}
3867
3868SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
3869 SDOperand N0 = N->getOperand(0);
3870 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Duncan Sands92c43912008-06-06 12:08:01 +00003871 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003872
3873 // fold (fp_to_sint c1fp) -> c1
3874 if (N0CFP)
3875 return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
3876 return SDOperand();
3877}
3878
3879SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
3880 SDOperand N0 = N->getOperand(0);
3881 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Duncan Sands92c43912008-06-06 12:08:01 +00003882 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003883
3884 // fold (fp_to_uint c1fp) -> c1
Dale Johannesenb89072e2007-10-16 23:38:29 +00003885 if (N0CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003886 return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
3887 return SDOperand();
3888}
3889
3890SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
3891 SDOperand N0 = N->getOperand(0);
Chris Lattner5872a362008-01-17 07:00:52 +00003892 SDOperand N1 = N->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003893 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Duncan Sands92c43912008-06-06 12:08:01 +00003894 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003895
3896 // fold (fp_round c1fp) -> c1fp
Dale Johannesenb89072e2007-10-16 23:38:29 +00003897 if (N0CFP && N0.getValueType() != MVT::ppcf128)
Chris Lattner5872a362008-01-17 07:00:52 +00003898 return DAG.getNode(ISD::FP_ROUND, VT, N0, N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003899
3900 // fold (fp_round (fp_extend x)) -> x
3901 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
3902 return N0.getOperand(0);
3903
Chris Lattner7afb8552008-01-24 06:45:35 +00003904 // fold (fp_round (fp_round x)) -> (fp_round x)
3905 if (N0.getOpcode() == ISD::FP_ROUND) {
3906 // This is a value preserving truncation if both round's are.
3907 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
3908 N0.Val->getConstantOperandVal(1) == 1;
3909 return DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0),
3910 DAG.getIntPtrConstant(IsTrunc));
3911 }
3912
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003913 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
3914 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
Chris Lattner5872a362008-01-17 07:00:52 +00003915 SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0), N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003916 AddToWorkList(Tmp.Val);
3917 return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
3918 }
3919
3920 return SDOperand();
3921}
3922
3923SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
3924 SDOperand N0 = N->getOperand(0);
Duncan Sands92c43912008-06-06 12:08:01 +00003925 MVT VT = N->getValueType(0);
3926 MVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003927 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3928
3929 // fold (fp_round_inreg c1fp) -> c1fp
3930 if (N0CFP) {
Dale Johannesen7604c1b2007-08-31 23:34:27 +00003931 SDOperand Round = DAG.getConstantFP(N0CFP->getValueAPF(), EVT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003932 return DAG.getNode(ISD::FP_EXTEND, VT, Round);
3933 }
3934 return SDOperand();
3935}
3936
3937SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
3938 SDOperand N0 = N->getOperand(0);
3939 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Duncan Sands92c43912008-06-06 12:08:01 +00003940 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003941
Chris Lattner6f981fc2007-12-29 06:55:23 +00003942 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Roman Levenstein98b8fcb2008-04-16 16:15:27 +00003943 if (N->hasOneUse() &&
3944 N->use_begin()->getSDOperand().getOpcode() == ISD::FP_ROUND)
Chris Lattner6f981fc2007-12-29 06:55:23 +00003945 return SDOperand();
Chris Lattner5872a362008-01-17 07:00:52 +00003946
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003947 // fold (fp_extend c1fp) -> c1fp
Dale Johannesenb89072e2007-10-16 23:38:29 +00003948 if (N0CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003949 return DAG.getNode(ISD::FP_EXTEND, VT, N0);
Chris Lattner5872a362008-01-17 07:00:52 +00003950
3951 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
3952 // value of X.
3953 if (N0.getOpcode() == ISD::FP_ROUND && N0.Val->getConstantOperandVal(1) == 1){
3954 SDOperand In = N0.getOperand(0);
3955 if (In.getValueType() == VT) return In;
Duncan Sandsec142ee2008-06-08 20:54:56 +00003956 if (VT.bitsLT(In.getValueType()))
Chris Lattner5872a362008-01-17 07:00:52 +00003957 return DAG.getNode(ISD::FP_ROUND, VT, In, N0.getOperand(1));
3958 return DAG.getNode(ISD::FP_EXTEND, VT, In);
3959 }
3960
3961 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Dale Johannesen2550e3a2007-10-19 20:29:00 +00003962 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
Duncan Sands2418bec2008-06-13 19:07:40 +00003963 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3964 TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003965 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3966 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3967 LN0->getBasePtr(), LN0->getSrcValue(),
3968 LN0->getSrcValueOffset(),
3969 N0.getValueType(),
3970 LN0->isVolatile(),
3971 LN0->getAlignment());
3972 CombineTo(N, ExtLoad);
Chris Lattner5872a362008-01-17 07:00:52 +00003973 CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad,
3974 DAG.getIntPtrConstant(1)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003975 ExtLoad.getValue(1));
3976 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3977 }
Duncan Sands2418bec2008-06-13 19:07:40 +00003978
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003979 return SDOperand();
3980}
3981
3982SDOperand DAGCombiner::visitFNEG(SDNode *N) {
3983 SDOperand N0 = N->getOperand(0);
3984
Chris Lattnere0992b82008-02-26 07:04:54 +00003985 if (isNegatibleForFree(N0, AfterLegalize))
3986 return GetNegatedExpression(N0, DAG, AfterLegalize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003987
Chris Lattneref26cbc2008-01-27 17:42:27 +00003988 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
3989 // constant pool values.
Chris Lattner336672f2008-01-27 23:32:17 +00003990 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
Duncan Sands92c43912008-06-06 12:08:01 +00003991 N0.getOperand(0).getValueType().isInteger() &&
3992 !N0.getOperand(0).getValueType().isVector()) {
Chris Lattneref26cbc2008-01-27 17:42:27 +00003993 SDOperand Int = N0.getOperand(0);
Duncan Sands92c43912008-06-06 12:08:01 +00003994 MVT IntVT = Int.getValueType();
3995 if (IntVT.isInteger() && !IntVT.isVector()) {
Chris Lattneref26cbc2008-01-27 17:42:27 +00003996 Int = DAG.getNode(ISD::XOR, IntVT, Int,
Duncan Sands92c43912008-06-06 12:08:01 +00003997 DAG.getConstant(IntVT.getIntegerVTSignBit(), IntVT));
Chris Lattneref26cbc2008-01-27 17:42:27 +00003998 AddToWorkList(Int.Val);
3999 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
4000 }
4001 }
4002
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004003 return SDOperand();
4004}
4005
4006SDOperand DAGCombiner::visitFABS(SDNode *N) {
4007 SDOperand N0 = N->getOperand(0);
4008 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Duncan Sands92c43912008-06-06 12:08:01 +00004009 MVT VT = N->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004010
4011 // fold (fabs c1) -> fabs(c1)
Dale Johannesenb89072e2007-10-16 23:38:29 +00004012 if (N0CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004013 return DAG.getNode(ISD::FABS, VT, N0);
4014 // fold (fabs (fabs x)) -> (fabs x)
4015 if (N0.getOpcode() == ISD::FABS)
4016 return N->getOperand(0);
4017 // fold (fabs (fneg x)) -> (fabs x)
4018 // fold (fabs (fcopysign x, y)) -> (fabs x)
4019 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
4020 return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
4021
Chris Lattneref26cbc2008-01-27 17:42:27 +00004022 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
4023 // constant pool values.
Chris Lattner336672f2008-01-27 23:32:17 +00004024 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
Duncan Sands92c43912008-06-06 12:08:01 +00004025 N0.getOperand(0).getValueType().isInteger() &&
4026 !N0.getOperand(0).getValueType().isVector()) {
Chris Lattneref26cbc2008-01-27 17:42:27 +00004027 SDOperand Int = N0.getOperand(0);
Duncan Sands92c43912008-06-06 12:08:01 +00004028 MVT IntVT = Int.getValueType();
4029 if (IntVT.isInteger() && !IntVT.isVector()) {
Chris Lattneref26cbc2008-01-27 17:42:27 +00004030 Int = DAG.getNode(ISD::AND, IntVT, Int,
Duncan Sands92c43912008-06-06 12:08:01 +00004031 DAG.getConstant(~IntVT.getIntegerVTSignBit(), IntVT));
Chris Lattneref26cbc2008-01-27 17:42:27 +00004032 AddToWorkList(Int.Val);
4033 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
4034 }
4035 }
4036
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004037 return SDOperand();
4038}
4039
4040SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
4041 SDOperand Chain = N->getOperand(0);
4042 SDOperand N1 = N->getOperand(1);
4043 SDOperand N2 = N->getOperand(2);
4044 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4045
4046 // never taken branch, fold to chain
4047 if (N1C && N1C->isNullValue())
4048 return Chain;
4049 // unconditional branch
Dan Gohman9d24dc72008-03-13 22:13:53 +00004050 if (N1C && N1C->getAPIntValue() == 1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004051 return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
4052 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
4053 // on the target.
4054 if (N1.getOpcode() == ISD::SETCC &&
4055 TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
4056 return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
4057 N1.getOperand(0), N1.getOperand(1), N2);
4058 }
4059 return SDOperand();
4060}
4061
4062// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
4063//
4064SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
4065 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
4066 SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
4067
Duncan Sands6a437fb2008-06-09 11:32:28 +00004068 // Use SimplifySetCC to simplify SETCC's.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004069 SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
4070 if (Simp.Val) AddToWorkList(Simp.Val);
4071
4072 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
4073
4074 // fold br_cc true, dest -> br dest (unconditional branch)
Dan Gohman9d24dc72008-03-13 22:13:53 +00004075 if (SCCC && !SCCC->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004076 return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
4077 N->getOperand(4));
4078 // fold br_cc false, dest -> unconditional fall through
4079 if (SCCC && SCCC->isNullValue())
4080 return N->getOperand(0);
4081
4082 // fold to a simpler setcc
4083 if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
4084 return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
4085 Simp.getOperand(2), Simp.getOperand(0),
4086 Simp.getOperand(1), N->getOperand(4));
4087 return SDOperand();
4088}
4089
4090
Duncan Sandsc218a5a2008-06-15 20:12:31 +00004091/// CombineToPreIndexedLoadStore - Try turning a load / store into a
4092/// pre-indexed load / store when the base pointer is an add or subtract
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004093/// and it has other uses besides the load / store. After the
4094/// transformation, the new indexed load / store has effectively folded
4095/// the add / subtract in and all of its other uses are redirected to the
4096/// new load / store.
4097bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
4098 if (!AfterLegalize)
4099 return false;
4100
4101 bool isLoad = true;
4102 SDOperand Ptr;
Duncan Sands92c43912008-06-06 12:08:01 +00004103 MVT VT;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004104 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner3bc08502008-01-17 19:59:44 +00004105 if (LD->isIndexed())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004106 return false;
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004107 VT = LD->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004108 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
4109 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
4110 return false;
4111 Ptr = LD->getBasePtr();
4112 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner3bc08502008-01-17 19:59:44 +00004113 if (ST->isIndexed())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004114 return false;
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004115 VT = ST->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004116 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
4117 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
4118 return false;
4119 Ptr = ST->getBasePtr();
4120 isLoad = false;
4121 } else
4122 return false;
4123
4124 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
4125 // out. There is no reason to make this a preinc/predec.
4126 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
4127 Ptr.Val->hasOneUse())
4128 return false;
4129
4130 // Ask the target to do addressing mode selection.
4131 SDOperand BasePtr;
4132 SDOperand Offset;
4133 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4134 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
4135 return false;
4136 // Don't create a indexed load / store with zero offset.
4137 if (isa<ConstantSDNode>(Offset) &&
Dan Gohman9d24dc72008-03-13 22:13:53 +00004138 cast<ConstantSDNode>(Offset)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004139 return false;
4140
4141 // Try turning it into a pre-indexed load / store except when:
4142 // 1) The new base ptr is a frame index.
4143 // 2) If N is a store and the new base ptr is either the same as or is a
4144 // predecessor of the value being stored.
4145 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
4146 // that would create a cycle.
4147 // 4) All uses are load / store ops that use it as old base ptr.
4148
4149 // Check #1. Preinc'ing a frame index would require copying the stack pointer
4150 // (plus the implicit offset) to a register to preinc anyway.
4151 if (isa<FrameIndexSDNode>(BasePtr))
4152 return false;
4153
4154 // Check #2.
4155 if (!isLoad) {
4156 SDOperand Val = cast<StoreSDNode>(N)->getValue();
Evan Chengd9387682008-03-04 00:41:45 +00004157 if (Val == BasePtr || BasePtr.Val->isPredecessorOf(Val.Val))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004158 return false;
4159 }
4160
4161 // Now check for #3 and #4.
4162 bool RealUse = false;
4163 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4164 E = Ptr.Val->use_end(); I != E; ++I) {
Roman Levenstein05650fd2008-04-07 10:06:32 +00004165 SDNode *Use = I->getUser();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004166 if (Use == N)
4167 continue;
Evan Chengd9387682008-03-04 00:41:45 +00004168 if (Use->isPredecessorOf(N))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004169 return false;
4170
4171 if (!((Use->getOpcode() == ISD::LOAD &&
4172 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
Anton Korobeynikov53422f62008-02-20 11:10:28 +00004173 (Use->getOpcode() == ISD::STORE &&
4174 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004175 RealUse = true;
4176 }
4177 if (!RealUse)
4178 return false;
4179
4180 SDOperand Result;
4181 if (isLoad)
4182 Result = DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM);
4183 else
4184 Result = DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4185 ++PreIndexedNodes;
4186 ++NodesCombined;
4187 DOUT << "\nReplacing.4 "; DEBUG(N->dump(&DAG));
4188 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4189 DOUT << '\n';
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004190 WorkListRemover DeadNodes(*this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004191 if (isLoad) {
4192 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004193 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004194 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004195 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004196 } else {
4197 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004198 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004199 }
4200
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004201 // Finally, since the node is now dead, remove it from the graph.
4202 DAG.DeleteNode(N);
4203
4204 // Replace the uses of Ptr with uses of the updated base value.
4205 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004206 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004207 removeFromWorkList(Ptr.Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004208 DAG.DeleteNode(Ptr.Val);
4209
4210 return true;
4211}
4212
Duncan Sandsc218a5a2008-06-15 20:12:31 +00004213/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004214/// add / sub of the base pointer node into a post-indexed load / store.
4215/// The transformation folded the add / subtract into the new indexed
4216/// load / store effectively and all of its uses are redirected to the
4217/// new load / store.
4218bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
4219 if (!AfterLegalize)
4220 return false;
4221
4222 bool isLoad = true;
4223 SDOperand Ptr;
Duncan Sands92c43912008-06-06 12:08:01 +00004224 MVT VT;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004225 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner3bc08502008-01-17 19:59:44 +00004226 if (LD->isIndexed())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004227 return false;
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004228 VT = LD->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004229 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
4230 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
4231 return false;
4232 Ptr = LD->getBasePtr();
4233 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner3bc08502008-01-17 19:59:44 +00004234 if (ST->isIndexed())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004235 return false;
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004236 VT = ST->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004237 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
4238 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
4239 return false;
4240 Ptr = ST->getBasePtr();
4241 isLoad = false;
4242 } else
4243 return false;
4244
4245 if (Ptr.Val->hasOneUse())
4246 return false;
4247
4248 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4249 E = Ptr.Val->use_end(); I != E; ++I) {
Roman Levenstein05650fd2008-04-07 10:06:32 +00004250 SDNode *Op = I->getUser();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004251 if (Op == N ||
4252 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
4253 continue;
4254
4255 SDOperand BasePtr;
4256 SDOperand Offset;
4257 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4258 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
4259 if (Ptr == Offset)
4260 std::swap(BasePtr, Offset);
4261 if (Ptr != BasePtr)
4262 continue;
4263 // Don't create a indexed load / store with zero offset.
4264 if (isa<ConstantSDNode>(Offset) &&
Dan Gohman9d24dc72008-03-13 22:13:53 +00004265 cast<ConstantSDNode>(Offset)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004266 continue;
4267
4268 // Try turning it into a post-indexed load / store except when
4269 // 1) All uses are load / store ops that use it as base ptr.
4270 // 2) Op must be independent of N, i.e. Op is neither a predecessor
4271 // nor a successor of N. Otherwise, if Op is folded that would
4272 // create a cycle.
4273
4274 // Check for #1.
4275 bool TryNext = false;
4276 for (SDNode::use_iterator II = BasePtr.Val->use_begin(),
4277 EE = BasePtr.Val->use_end(); II != EE; ++II) {
Roman Levenstein05650fd2008-04-07 10:06:32 +00004278 SDNode *Use = II->getUser();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004279 if (Use == Ptr.Val)
4280 continue;
4281
4282 // If all the uses are load / store addresses, then don't do the
4283 // transformation.
4284 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
4285 bool RealUse = false;
4286 for (SDNode::use_iterator III = Use->use_begin(),
4287 EEE = Use->use_end(); III != EEE; ++III) {
Roman Levenstein05650fd2008-04-07 10:06:32 +00004288 SDNode *UseUse = III->getUser();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004289 if (!((UseUse->getOpcode() == ISD::LOAD &&
4290 cast<LoadSDNode>(UseUse)->getBasePtr().Val == Use) ||
Anton Korobeynikov53422f62008-02-20 11:10:28 +00004291 (UseUse->getOpcode() == ISD::STORE &&
4292 cast<StoreSDNode>(UseUse)->getBasePtr().Val == Use)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004293 RealUse = true;
4294 }
4295
4296 if (!RealUse) {
4297 TryNext = true;
4298 break;
4299 }
4300 }
4301 }
4302 if (TryNext)
4303 continue;
4304
4305 // Check for #2
Evan Chengd9387682008-03-04 00:41:45 +00004306 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004307 SDOperand Result = isLoad
4308 ? DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM)
4309 : DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4310 ++PostIndexedNodes;
4311 ++NodesCombined;
4312 DOUT << "\nReplacing.5 "; DEBUG(N->dump(&DAG));
4313 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4314 DOUT << '\n';
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004315 WorkListRemover DeadNodes(*this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004316 if (isLoad) {
4317 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004318 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004319 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004320 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004321 } else {
4322 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004323 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004324 }
4325
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004326 // Finally, since the node is now dead, remove it from the graph.
4327 DAG.DeleteNode(N);
4328
4329 // Replace the uses of Use with uses of the updated base value.
4330 DAG.ReplaceAllUsesOfValueWith(SDOperand(Op, 0),
4331 Result.getValue(isLoad ? 1 : 0),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004332 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004333 removeFromWorkList(Op);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004334 DAG.DeleteNode(Op);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004335 return true;
4336 }
4337 }
4338 }
4339 return false;
4340}
4341
Chris Lattner4e137af2008-01-25 07:20:16 +00004342/// InferAlignment - If we can infer some alignment information from this
4343/// pointer, return it.
4344static unsigned InferAlignment(SDOperand Ptr, SelectionDAG &DAG) {
4345 // If this is a direct reference to a stack slot, use information about the
4346 // stack slot's alignment.
Chris Lattner1e3362f2008-01-26 19:45:50 +00004347 int FrameIdx = 1 << 31;
4348 int64_t FrameOffset = 0;
Chris Lattner4e137af2008-01-25 07:20:16 +00004349 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
Chris Lattner1e3362f2008-01-26 19:45:50 +00004350 FrameIdx = FI->getIndex();
4351 } else if (Ptr.getOpcode() == ISD::ADD &&
4352 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4353 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4354 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4355 FrameOffset = Ptr.getConstantOperandVal(1);
Chris Lattner4e137af2008-01-25 07:20:16 +00004356 }
Chris Lattner1e3362f2008-01-26 19:45:50 +00004357
4358 if (FrameIdx != (1 << 31)) {
4359 // FIXME: Handle FI+CST.
4360 const MachineFrameInfo &MFI = *DAG.getMachineFunction().getFrameInfo();
4361 if (MFI.isFixedObjectIndex(FrameIdx)) {
4362 int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx);
4363
4364 // The alignment of the frame index can be determined from its offset from
4365 // the incoming frame position. If the frame object is at offset 32 and
4366 // the stack is guaranteed to be 16-byte aligned, then we know that the
4367 // object is 16-byte aligned.
4368 unsigned StackAlign = DAG.getTarget().getFrameInfo()->getStackAlignment();
4369 unsigned Align = MinAlign(ObjectOffset, StackAlign);
4370
4371 // Finally, the frame object itself may have a known alignment. Factor
4372 // the alignment + offset into a new alignment. For example, if we know
4373 // the FI is 8 byte aligned, but the pointer is 4 off, we really have a
4374 // 4-byte alignment of the resultant pointer. Likewise align 4 + 4-byte
4375 // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
4376 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
4377 FrameOffset);
4378 return std::max(Align, FIInfoAlign);
4379 }
4380 }
Chris Lattner4e137af2008-01-25 07:20:16 +00004381
4382 return 0;
4383}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004384
4385SDOperand DAGCombiner::visitLOAD(SDNode *N) {
4386 LoadSDNode *LD = cast<LoadSDNode>(N);
4387 SDOperand Chain = LD->getChain();
4388 SDOperand Ptr = LD->getBasePtr();
Chris Lattner4e137af2008-01-25 07:20:16 +00004389
4390 // Try to infer better alignment information than the load already has.
4391 if (LD->isUnindexed()) {
4392 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4393 if (Align > LD->getAlignment())
4394 return DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
4395 Chain, Ptr, LD->getSrcValue(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004396 LD->getSrcValueOffset(), LD->getMemoryVT(),
Chris Lattner4e137af2008-01-25 07:20:16 +00004397 LD->isVolatile(), Align);
4398 }
4399 }
4400
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004401
4402 // If load is not volatile and there are no uses of the loaded value (and
4403 // the updated indexed value in case of indexed loads), change uses of the
4404 // chain value into uses of the chain input (i.e. delete the dead load).
4405 if (!LD->isVolatile()) {
4406 if (N->getValueType(1) == MVT::Other) {
4407 // Unindexed loads.
Evan Chenge8b886a2008-01-16 23:11:54 +00004408 if (N->hasNUsesOfValue(0, 0)) {
4409 // It's not safe to use the two value CombineTo variant here. e.g.
4410 // v1, chain2 = load chain1, loc
4411 // v2, chain3 = load chain2, loc
4412 // v3 = add v2, c
Chris Lattnerbb67c192008-01-24 07:57:06 +00004413 // Now we replace use of chain2 with chain1. This makes the second load
4414 // isomorphic to the one we are deleting, and thus makes this load live.
Evan Chenge8b886a2008-01-16 23:11:54 +00004415 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
Chris Lattnerbb67c192008-01-24 07:57:06 +00004416 DOUT << "\nWith chain: "; DEBUG(Chain.Val->dump(&DAG));
4417 DOUT << "\n";
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004418 WorkListRemover DeadNodes(*this);
4419 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Chain, &DeadNodes);
Chris Lattnerbb67c192008-01-24 07:57:06 +00004420 if (N->use_empty()) {
4421 removeFromWorkList(N);
4422 DAG.DeleteNode(N);
4423 }
Evan Chenge8b886a2008-01-16 23:11:54 +00004424 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
4425 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004426 } else {
4427 // Indexed loads.
4428 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
4429 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
Evan Chenge8b886a2008-01-16 23:11:54 +00004430 SDOperand Undef = DAG.getNode(ISD::UNDEF, N->getValueType(0));
4431 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4432 DOUT << "\nWith: "; DEBUG(Undef.Val->dump(&DAG));
4433 DOUT << " and 2 other values\n";
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004434 WorkListRemover DeadNodes(*this);
4435 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Undef, &DeadNodes);
Evan Chenge8b886a2008-01-16 23:11:54 +00004436 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1),
Chris Lattner667f9c12008-01-17 07:20:38 +00004437 DAG.getNode(ISD::UNDEF, N->getValueType(1)),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004438 &DeadNodes);
4439 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 2), Chain, &DeadNodes);
Evan Chenge8b886a2008-01-16 23:11:54 +00004440 removeFromWorkList(N);
Evan Chenge8b886a2008-01-16 23:11:54 +00004441 DAG.DeleteNode(N);
4442 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004443 }
4444 }
4445 }
4446
4447 // If this load is directly stored, replace the load value with the stored
4448 // value.
4449 // TODO: Handle store large -> read small portion.
4450 // TODO: Handle TRUNCSTORE/LOADEXT
Dan Gohman729b5ff2008-03-31 20:32:52 +00004451 if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
4452 !LD->isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004453 if (ISD::isNON_TRUNCStore(Chain.Val)) {
4454 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
4455 if (PrevST->getBasePtr() == Ptr &&
4456 PrevST->getValue().getValueType() == N->getValueType(0))
4457 return CombineTo(N, Chain.getOperand(1), Chain);
4458 }
4459 }
4460
4461 if (CombinerAA) {
4462 // Walk up chain skipping non-aliasing memory nodes.
4463 SDOperand BetterChain = FindBetterChain(N, Chain);
4464
4465 // If there is a better chain.
4466 if (Chain != BetterChain) {
4467 SDOperand ReplLoad;
4468
4469 // Replace the chain to void dependency.
4470 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4471 ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
Duncan Sandsa3691432007-10-28 12:59:45 +00004472 LD->getSrcValue(), LD->getSrcValueOffset(),
4473 LD->isVolatile(), LD->getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004474 } else {
4475 ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
4476 LD->getValueType(0),
4477 BetterChain, Ptr, LD->getSrcValue(),
4478 LD->getSrcValueOffset(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004479 LD->getMemoryVT(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004480 LD->isVolatile(),
4481 LD->getAlignment());
4482 }
4483
4484 // Create token factor to keep old chain connected.
4485 SDOperand Token = DAG.getNode(ISD::TokenFactor, MVT::Other,
4486 Chain, ReplLoad.getValue(1));
4487
4488 // Replace uses with load result and token factor. Don't add users
4489 // to work list.
4490 return CombineTo(N, ReplLoad.getValue(0), Token, false);
4491 }
4492 }
4493
4494 // Try transforming N to an indexed load.
4495 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4496 return SDOperand(N, 0);
4497
4498 return SDOperand();
4499}
4500
Chris Lattner2e023772008-01-08 23:08:06 +00004501
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004502SDOperand DAGCombiner::visitSTORE(SDNode *N) {
4503 StoreSDNode *ST = cast<StoreSDNode>(N);
4504 SDOperand Chain = ST->getChain();
4505 SDOperand Value = ST->getValue();
4506 SDOperand Ptr = ST->getBasePtr();
4507
Chris Lattner4e137af2008-01-25 07:20:16 +00004508 // Try to infer better alignment information than the store already has.
4509 if (ST->isUnindexed()) {
4510 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4511 if (Align > ST->getAlignment())
4512 return DAG.getTruncStore(Chain, Value, Ptr, ST->getSrcValue(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004513 ST->getSrcValueOffset(), ST->getMemoryVT(),
Chris Lattner4e137af2008-01-25 07:20:16 +00004514 ST->isVolatile(), Align);
4515 }
4516 }
Duncan Sands2418bec2008-06-13 19:07:40 +00004517
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004518 // If this is a store of a bit convert, store the input value if the
4519 // resultant store does not need a higher alignment than the original.
4520 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
Chris Lattner3bc08502008-01-17 19:59:44 +00004521 ST->isUnindexed()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004522 unsigned Align = ST->getAlignment();
Duncan Sands92c43912008-06-06 12:08:01 +00004523 MVT SVT = Value.getOperand(0).getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004524 unsigned OrigAlign = TLI.getTargetMachine().getTargetData()->
Duncan Sands92c43912008-06-06 12:08:01 +00004525 getABITypeAlignment(SVT.getTypeForMVT());
Duncan Sands2418bec2008-06-13 19:07:40 +00004526 if (Align <= OrigAlign &&
4527 ((!AfterLegalize && !ST->isVolatile()) ||
4528 TLI.isOperationLegal(ISD::STORE, SVT)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004529 return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4530 ST->getSrcValueOffset(), ST->isVolatile(), Align);
4531 }
Duncan Sands2418bec2008-06-13 19:07:40 +00004532
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004533 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
4534 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands2418bec2008-06-13 19:07:40 +00004535 // NOTE: If the original store is volatile, this transform must not increase
4536 // the number of stores. For example, on x86-32 an f64 can be stored in one
4537 // processor operation but an i64 (which is not legal) requires two. So the
4538 // transform should not be done in this case.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004539 if (Value.getOpcode() != ISD::TargetConstantFP) {
4540 SDOperand Tmp;
Duncan Sands92c43912008-06-06 12:08:01 +00004541 switch (CFP->getValueType(0).getSimpleVT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004542 default: assert(0 && "Unknown FP type");
Dale Johannesen1b4181d2007-09-18 18:36:59 +00004543 case MVT::f80: // We don't do this for these yet.
4544 case MVT::f128:
4545 case MVT::ppcf128:
4546 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004547 case MVT::f32:
Duncan Sands2418bec2008-06-13 19:07:40 +00004548 if ((!AfterLegalize && !ST->isVolatile()) ||
4549 TLI.isOperationLegal(ISD::STORE, MVT::i32)) {
Dale Johannesenfbd9cda2007-09-12 03:30:33 +00004550 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
4551 convertToAPInt().getZExtValue(), MVT::i32);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004552 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4553 ST->getSrcValueOffset(), ST->isVolatile(),
4554 ST->getAlignment());
4555 }
4556 break;
4557 case MVT::f64:
Duncan Sands2418bec2008-06-13 19:07:40 +00004558 if ((!AfterLegalize && !ST->isVolatile()) ||
4559 TLI.isOperationLegal(ISD::STORE, MVT::i64)) {
Dale Johannesenfbd9cda2007-09-12 03:30:33 +00004560 Tmp = DAG.getConstant(CFP->getValueAPF().convertToAPInt().
4561 getZExtValue(), MVT::i64);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004562 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4563 ST->getSrcValueOffset(), ST->isVolatile(),
4564 ST->getAlignment());
Duncan Sands2418bec2008-06-13 19:07:40 +00004565 } else if (!ST->isVolatile() &&
4566 TLI.isOperationLegal(ISD::STORE, MVT::i32)) {
Duncan Sandsa3691432007-10-28 12:59:45 +00004567 // Many FP stores are not made apparent until after legalize, e.g. for
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004568 // argument passing. Since this is so common, custom legalize the
4569 // 64-bit integer store into two 32-bit stores.
Dale Johannesenfbd9cda2007-09-12 03:30:33 +00004570 uint64_t Val = CFP->getValueAPF().convertToAPInt().getZExtValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004571 SDOperand Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
4572 SDOperand Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands9ff8fbf2008-02-11 10:37:04 +00004573 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004574
4575 int SVOffset = ST->getSrcValueOffset();
4576 unsigned Alignment = ST->getAlignment();
4577 bool isVolatile = ST->isVolatile();
4578
4579 SDOperand St0 = DAG.getStore(Chain, Lo, Ptr, ST->getSrcValue(),
4580 ST->getSrcValueOffset(),
4581 isVolatile, ST->getAlignment());
4582 Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4583 DAG.getConstant(4, Ptr.getValueType()));
4584 SVOffset += 4;
Duncan Sandsa3691432007-10-28 12:59:45 +00004585 Alignment = MinAlign(Alignment, 4U);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004586 SDOperand St1 = DAG.getStore(Chain, Hi, Ptr, ST->getSrcValue(),
4587 SVOffset, isVolatile, Alignment);
4588 return DAG.getNode(ISD::TokenFactor, MVT::Other, St0, St1);
4589 }
4590 break;
4591 }
4592 }
4593 }
4594
4595 if (CombinerAA) {
4596 // Walk up chain skipping non-aliasing memory nodes.
4597 SDOperand BetterChain = FindBetterChain(N, Chain);
4598
4599 // If there is a better chain.
4600 if (Chain != BetterChain) {
4601 // Replace the chain to avoid dependency.
4602 SDOperand ReplStore;
4603 if (ST->isTruncatingStore()) {
4604 ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
Chris Lattner667f9c12008-01-17 07:20:38 +00004605 ST->getSrcValue(),ST->getSrcValueOffset(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004606 ST->getMemoryVT(),
Chris Lattner667f9c12008-01-17 07:20:38 +00004607 ST->isVolatile(), ST->getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004608 } else {
4609 ReplStore = DAG.getStore(BetterChain, Value, Ptr,
Chris Lattner667f9c12008-01-17 07:20:38 +00004610 ST->getSrcValue(), ST->getSrcValueOffset(),
4611 ST->isVolatile(), ST->getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004612 }
4613
4614 // Create token to keep both nodes around.
4615 SDOperand Token =
4616 DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore);
4617
4618 // Don't add users to work list.
4619 return CombineTo(N, Token, false);
4620 }
4621 }
4622
4623 // Try transforming N to an indexed store.
4624 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4625 return SDOperand(N, 0);
4626
Chris Lattner447d8e82007-12-29 06:26:16 +00004627 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner3bc08502008-01-17 19:59:44 +00004628 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Duncan Sands92c43912008-06-06 12:08:01 +00004629 Value.getValueType().isInteger()) {
Chris Lattnere8671c52007-10-13 06:35:54 +00004630 // See if we can simplify the input to this truncstore with knowledge that
4631 // only the low bits are being used. For example:
4632 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
4633 SDOperand Shorter =
Dan Gohman07961cd2008-02-25 21:11:39 +00004634 GetDemandedBits(Value,
4635 APInt::getLowBitsSet(Value.getValueSizeInBits(),
Duncan Sands92c43912008-06-06 12:08:01 +00004636 ST->getMemoryVT().getSizeInBits()));
Chris Lattnere8671c52007-10-13 06:35:54 +00004637 AddToWorkList(Value.Val);
4638 if (Shorter.Val)
4639 return DAG.getTruncStore(Chain, Shorter, Ptr, ST->getSrcValue(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004640 ST->getSrcValueOffset(), ST->getMemoryVT(),
Chris Lattnere8671c52007-10-13 06:35:54 +00004641 ST->isVolatile(), ST->getAlignment());
Chris Lattnerb77ea552007-10-13 06:58:48 +00004642
4643 // Otherwise, see if we can simplify the operation with
4644 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohman11607792008-02-27 00:25:32 +00004645 if (SimplifyDemandedBits(Value,
4646 APInt::getLowBitsSet(
4647 Value.getValueSizeInBits(),
Duncan Sands92c43912008-06-06 12:08:01 +00004648 ST->getMemoryVT().getSizeInBits())))
Chris Lattnerb77ea552007-10-13 06:58:48 +00004649 return SDOperand(N, 0);
Chris Lattnere8671c52007-10-13 06:35:54 +00004650 }
4651
Chris Lattner447d8e82007-12-29 06:26:16 +00004652 // If this is a load followed by a store to the same location, then the store
4653 // is dead/noop.
4654 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004655 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner3bc08502008-01-17 19:59:44 +00004656 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner2e023772008-01-08 23:08:06 +00004657 // There can't be any side effects between the load and store, such as
4658 // a call or store.
Chris Lattner10d94f92008-01-16 05:49:24 +00004659 Chain.reachesChainWithoutSideEffects(SDOperand(Ld, 1))) {
Chris Lattner447d8e82007-12-29 06:26:16 +00004660 // The store is dead, remove it.
4661 return Chain;
4662 }
4663 }
Duncan Sands2418bec2008-06-13 19:07:40 +00004664
Chris Lattner3bc08502008-01-17 19:59:44 +00004665 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
4666 // truncating store. We can do this even if this is already a truncstore.
4667 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Duncan Sands2418bec2008-06-13 19:07:40 +00004668 && Value.Val->hasOneUse() && ST->isUnindexed() &&
Chris Lattner3bc08502008-01-17 19:59:44 +00004669 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004670 ST->getMemoryVT())) {
Chris Lattner3bc08502008-01-17 19:59:44 +00004671 return DAG.getTruncStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004672 ST->getSrcValueOffset(), ST->getMemoryVT(),
Chris Lattner3bc08502008-01-17 19:59:44 +00004673 ST->isVolatile(), ST->getAlignment());
4674 }
Duncan Sands2418bec2008-06-13 19:07:40 +00004675
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004676 return SDOperand();
4677}
4678
4679SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
4680 SDOperand InVec = N->getOperand(0);
4681 SDOperand InVal = N->getOperand(1);
4682 SDOperand EltNo = N->getOperand(2);
4683
4684 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
4685 // vector with the inserted element.
4686 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
4687 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4688 SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
4689 if (Elt < Ops.size())
4690 Ops[Elt] = InVal;
4691 return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
4692 &Ops[0], Ops.size());
4693 }
4694
4695 return SDOperand();
4696}
4697
Evan Chengd7ba7ed2007-10-06 08:19:55 +00004698SDOperand DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Evan Cheng411fc172008-05-13 08:35:03 +00004699 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
4700 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
4701 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
4702
4703 // Perform only after legalization to ensure build_vector / vector_shuffle
4704 // optimizations have already been done.
4705 if (!AfterLegalize) return SDOperand();
4706
Evan Chengd7ba7ed2007-10-06 08:19:55 +00004707 SDOperand InVec = N->getOperand(0);
4708 SDOperand EltNo = N->getOperand(1);
4709
Evan Chengd7ba7ed2007-10-06 08:19:55 +00004710 if (isa<ConstantSDNode>(EltNo)) {
4711 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4712 bool NewLoad = false;
Duncan Sands92c43912008-06-06 12:08:01 +00004713 MVT VT = InVec.getValueType();
4714 MVT EVT = VT.getVectorElementType();
4715 MVT LVT = EVT;
Evan Cheng411fc172008-05-13 08:35:03 +00004716 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
Duncan Sands92c43912008-06-06 12:08:01 +00004717 MVT BCVT = InVec.getOperand(0).getValueType();
Duncan Sandsec142ee2008-06-08 20:54:56 +00004718 if (!BCVT.isVector() || EVT.bitsGT(BCVT.getVectorElementType()))
Evan Cheng411fc172008-05-13 08:35:03 +00004719 return SDOperand();
4720 InVec = InVec.getOperand(0);
Duncan Sands92c43912008-06-06 12:08:01 +00004721 EVT = BCVT.getVectorElementType();
Evan Cheng411fc172008-05-13 08:35:03 +00004722 NewLoad = true;
4723 }
Evan Chengd7ba7ed2007-10-06 08:19:55 +00004724
Evan Cheng411fc172008-05-13 08:35:03 +00004725 LoadSDNode *LN0 = NULL;
4726 if (ISD::isNormalLoad(InVec.Val))
4727 LN0 = cast<LoadSDNode>(InVec);
4728 else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4729 InVec.getOperand(0).getValueType() == EVT &&
4730 ISD::isNormalLoad(InVec.getOperand(0).Val)) {
4731 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
4732 } else if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
4733 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
4734 // =>
4735 // (load $addr+1*size)
4736 unsigned Idx = cast<ConstantSDNode>(InVec.getOperand(2).
4737 getOperand(Elt))->getValue();
4738 unsigned NumElems = InVec.getOperand(2).getNumOperands();
4739 InVec = (Idx < NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
4740 if (InVec.getOpcode() == ISD::BIT_CONVERT)
4741 InVec = InVec.getOperand(0);
4742 if (ISD::isNormalLoad(InVec.Val)) {
4743 LN0 = cast<LoadSDNode>(InVec);
4744 Elt = (Idx < NumElems) ? Idx : Idx - NumElems;
Evan Chengd7ba7ed2007-10-06 08:19:55 +00004745 }
4746 }
Duncan Sandsc218a5a2008-06-15 20:12:31 +00004747 if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
Evan Cheng411fc172008-05-13 08:35:03 +00004748 return SDOperand();
4749
4750 unsigned Align = LN0->getAlignment();
4751 if (NewLoad) {
4752 // Check the resultant load doesn't need a higher alignment than the
4753 // original load.
4754 unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
Duncan Sands92c43912008-06-06 12:08:01 +00004755 getABITypeAlignment(LVT.getTypeForMVT());
Duncan Sands6ae1a0632008-06-14 17:48:34 +00004756 if (NewAlign > Align || !TLI.isOperationLegal(ISD::LOAD, LVT))
Evan Cheng411fc172008-05-13 08:35:03 +00004757 return SDOperand();
4758 Align = NewAlign;
4759 }
4760
4761 SDOperand NewPtr = LN0->getBasePtr();
4762 if (Elt) {
Duncan Sands92c43912008-06-06 12:08:01 +00004763 unsigned PtrOff = LVT.getSizeInBits() * Elt / 8;
4764 MVT PtrType = NewPtr.getValueType();
Evan Cheng411fc172008-05-13 08:35:03 +00004765 if (TLI.isBigEndian())
Duncan Sands92c43912008-06-06 12:08:01 +00004766 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
Evan Cheng411fc172008-05-13 08:35:03 +00004767 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
4768 DAG.getConstant(PtrOff, PtrType));
4769 }
4770 return DAG.getLoad(LVT, LN0->getChain(), NewPtr,
4771 LN0->getSrcValue(), LN0->getSrcValueOffset(),
4772 LN0->isVolatile(), Align);
Evan Chengd7ba7ed2007-10-06 08:19:55 +00004773 }
4774 return SDOperand();
4775}
4776
4777
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004778SDOperand DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
4779 unsigned NumInScalars = N->getNumOperands();
Duncan Sands92c43912008-06-06 12:08:01 +00004780 MVT VT = N->getValueType(0);
4781 unsigned NumElts = VT.getVectorNumElements();
4782 MVT EltType = VT.getVectorElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004783
4784 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
4785 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
4786 // at most two distinct vectors, turn this into a shuffle node.
4787 SDOperand VecIn1, VecIn2;
4788 for (unsigned i = 0; i != NumInScalars; ++i) {
4789 // Ignore undef inputs.
4790 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
4791
4792 // If this input is something other than a EXTRACT_VECTOR_ELT with a
4793 // constant index, bail out.
4794 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4795 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
4796 VecIn1 = VecIn2 = SDOperand(0, 0);
4797 break;
4798 }
4799
4800 // If the input vector type disagrees with the result of the build_vector,
4801 // we can't make a shuffle.
4802 SDOperand ExtractedFromVec = N->getOperand(i).getOperand(0);
4803 if (ExtractedFromVec.getValueType() != VT) {
4804 VecIn1 = VecIn2 = SDOperand(0, 0);
4805 break;
4806 }
4807
4808 // Otherwise, remember this. We allow up to two distinct input vectors.
4809 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
4810 continue;
4811
4812 if (VecIn1.Val == 0) {
4813 VecIn1 = ExtractedFromVec;
4814 } else if (VecIn2.Val == 0) {
4815 VecIn2 = ExtractedFromVec;
4816 } else {
4817 // Too many inputs.
4818 VecIn1 = VecIn2 = SDOperand(0, 0);
4819 break;
4820 }
4821 }
4822
4823 // If everything is good, we can make a shuffle operation.
4824 if (VecIn1.Val) {
4825 SmallVector<SDOperand, 8> BuildVecIndices;
4826 for (unsigned i = 0; i != NumInScalars; ++i) {
4827 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
4828 BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, TLI.getPointerTy()));
4829 continue;
4830 }
4831
4832 SDOperand Extract = N->getOperand(i);
4833
4834 // If extracting from the first vector, just use the index directly.
4835 if (Extract.getOperand(0) == VecIn1) {
4836 BuildVecIndices.push_back(Extract.getOperand(1));
4837 continue;
4838 }
4839
4840 // Otherwise, use InIdx + VecSize
4841 unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue();
Chris Lattner5872a362008-01-17 07:00:52 +00004842 BuildVecIndices.push_back(DAG.getIntPtrConstant(Idx+NumInScalars));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004843 }
4844
4845 // Add count and size info.
Duncan Sands92c43912008-06-06 12:08:01 +00004846 MVT BuildVecVT = MVT::getVectorVT(TLI.getPointerTy(), NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004847
4848 // Return the new VECTOR_SHUFFLE node.
4849 SDOperand Ops[5];
4850 Ops[0] = VecIn1;
4851 if (VecIn2.Val) {
4852 Ops[1] = VecIn2;
4853 } else {
4854 // Use an undef build_vector as input for the second operand.
4855 std::vector<SDOperand> UnOps(NumInScalars,
4856 DAG.getNode(ISD::UNDEF,
4857 EltType));
4858 Ops[1] = DAG.getNode(ISD::BUILD_VECTOR, VT,
4859 &UnOps[0], UnOps.size());
4860 AddToWorkList(Ops[1].Val);
4861 }
4862 Ops[2] = DAG.getNode(ISD::BUILD_VECTOR, BuildVecVT,
4863 &BuildVecIndices[0], BuildVecIndices.size());
4864 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Ops, 3);
4865 }
4866
4867 return SDOperand();
4868}
4869
4870SDOperand DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
4871 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
4872 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
4873 // inputs come from at most two distinct vectors, turn this into a shuffle
4874 // node.
4875
4876 // If we only have one input vector, we don't need to do any concatenation.
4877 if (N->getNumOperands() == 1) {
4878 return N->getOperand(0);
4879 }
4880
4881 return SDOperand();
4882}
4883
4884SDOperand DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
4885 SDOperand ShufMask = N->getOperand(2);
4886 unsigned NumElts = ShufMask.getNumOperands();
4887
4888 // If the shuffle mask is an identity operation on the LHS, return the LHS.
4889 bool isIdentity = true;
4890 for (unsigned i = 0; i != NumElts; ++i) {
4891 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4892 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
4893 isIdentity = false;
4894 break;
4895 }
4896 }
4897 if (isIdentity) return N->getOperand(0);
4898
4899 // If the shuffle mask is an identity operation on the RHS, return the RHS.
4900 isIdentity = true;
4901 for (unsigned i = 0; i != NumElts; ++i) {
4902 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4903 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
4904 isIdentity = false;
4905 break;
4906 }
4907 }
4908 if (isIdentity) return N->getOperand(1);
4909
4910 // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
4911 // needed at all.
4912 bool isUnary = true;
4913 bool isSplat = true;
4914 int VecNum = -1;
4915 unsigned BaseIdx = 0;
4916 for (unsigned i = 0; i != NumElts; ++i)
4917 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
4918 unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
4919 int V = (Idx < NumElts) ? 0 : 1;
4920 if (VecNum == -1) {
4921 VecNum = V;
4922 BaseIdx = Idx;
4923 } else {
4924 if (BaseIdx != Idx)
4925 isSplat = false;
4926 if (VecNum != V) {
4927 isUnary = false;
4928 break;
4929 }
4930 }
4931 }
4932
4933 SDOperand N0 = N->getOperand(0);
4934 SDOperand N1 = N->getOperand(1);
4935 // Normalize unary shuffle so the RHS is undef.
4936 if (isUnary && VecNum == 1)
4937 std::swap(N0, N1);
4938
4939 // If it is a splat, check if the argument vector is a build_vector with
4940 // all scalar elements the same.
4941 if (isSplat) {
4942 SDNode *V = N0.Val;
4943
4944 // If this is a bit convert that changes the element type of the vector but
4945 // not the number of vector elements, look through it. Be careful not to
4946 // look though conversions that change things like v4f32 to v2f64.
4947 if (V->getOpcode() == ISD::BIT_CONVERT) {
4948 SDOperand ConvInput = V->getOperand(0);
Duncan Sands92c43912008-06-06 12:08:01 +00004949 if (ConvInput.getValueType().getVectorNumElements() == NumElts)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004950 V = ConvInput.Val;
4951 }
4952
4953 if (V->getOpcode() == ISD::BUILD_VECTOR) {
4954 unsigned NumElems = V->getNumOperands();
4955 if (NumElems > BaseIdx) {
4956 SDOperand Base;
4957 bool AllSame = true;
4958 for (unsigned i = 0; i != NumElems; ++i) {
4959 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
4960 Base = V->getOperand(i);
4961 break;
4962 }
4963 }
4964 // Splat of <u, u, u, u>, return <u, u, u, u>
4965 if (!Base.Val)
4966 return N0;
4967 for (unsigned i = 0; i != NumElems; ++i) {
Evan Cheng8d68c2b2007-09-18 21:54:37 +00004968 if (V->getOperand(i) != Base) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004969 AllSame = false;
4970 break;
4971 }
4972 }
4973 // Splat of <x, x, x, x>, return <x, x, x, x>
4974 if (AllSame)
4975 return N0;
4976 }
4977 }
4978 }
4979
4980 // If it is a unary or the LHS and the RHS are the same node, turn the RHS
4981 // into an undef.
4982 if (isUnary || N0 == N1) {
4983 // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
4984 // first operand.
4985 SmallVector<SDOperand, 8> MappedOps;
4986 for (unsigned i = 0; i != NumElts; ++i) {
4987 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
4988 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
4989 MappedOps.push_back(ShufMask.getOperand(i));
4990 } else {
4991 unsigned NewIdx =
4992 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
4993 MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
4994 }
4995 }
4996 ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
4997 &MappedOps[0], MappedOps.size());
4998 AddToWorkList(ShufMask.Val);
4999 return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
5000 N0,
5001 DAG.getNode(ISD::UNDEF, N->getValueType(0)),
5002 ShufMask);
5003 }
5004
5005 return SDOperand();
5006}
5007
5008/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
5009/// an AND to a vector_shuffle with the destination vector and a zero vector.
5010/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
5011/// vector_shuffle V, Zero, <0, 4, 2, 4>
5012SDOperand DAGCombiner::XformToShuffleWithZero(SDNode *N) {
5013 SDOperand LHS = N->getOperand(0);
5014 SDOperand RHS = N->getOperand(1);
5015 if (N->getOpcode() == ISD::AND) {
5016 if (RHS.getOpcode() == ISD::BIT_CONVERT)
5017 RHS = RHS.getOperand(0);
5018 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
5019 std::vector<SDOperand> IdxOps;
5020 unsigned NumOps = RHS.getNumOperands();
5021 unsigned NumElts = NumOps;
Duncan Sands92c43912008-06-06 12:08:01 +00005022 MVT EVT = RHS.getValueType().getVectorElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005023 for (unsigned i = 0; i != NumElts; ++i) {
5024 SDOperand Elt = RHS.getOperand(i);
5025 if (!isa<ConstantSDNode>(Elt))
5026 return SDOperand();
5027 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
5028 IdxOps.push_back(DAG.getConstant(i, EVT));
5029 else if (cast<ConstantSDNode>(Elt)->isNullValue())
5030 IdxOps.push_back(DAG.getConstant(NumElts, EVT));
5031 else
5032 return SDOperand();
5033 }
5034
5035 // Let's see if the target supports this vector_shuffle.
5036 if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG))
5037 return SDOperand();
5038
5039 // Return the new VECTOR_SHUFFLE node.
Duncan Sands92c43912008-06-06 12:08:01 +00005040 MVT VT = MVT::getVectorVT(EVT, NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005041 std::vector<SDOperand> Ops;
5042 LHS = DAG.getNode(ISD::BIT_CONVERT, VT, LHS);
5043 Ops.push_back(LHS);
5044 AddToWorkList(LHS.Val);
5045 std::vector<SDOperand> ZeroOps(NumElts, DAG.getConstant(0, EVT));
5046 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
5047 &ZeroOps[0], ZeroOps.size()));
5048 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
5049 &IdxOps[0], IdxOps.size()));
5050 SDOperand Result = DAG.getNode(ISD::VECTOR_SHUFFLE, VT,
5051 &Ops[0], Ops.size());
5052 if (VT != LHS.getValueType()) {
5053 Result = DAG.getNode(ISD::BIT_CONVERT, LHS.getValueType(), Result);
5054 }
5055 return Result;
5056 }
5057 }
5058 return SDOperand();
5059}
5060
5061/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
5062SDOperand DAGCombiner::SimplifyVBinOp(SDNode *N) {
5063 // After legalize, the target may be depending on adds and other
5064 // binary ops to provide legal ways to construct constants or other
5065 // things. Simplifying them may result in a loss of legality.
5066 if (AfterLegalize) return SDOperand();
5067
Duncan Sands92c43912008-06-06 12:08:01 +00005068 MVT VT = N->getValueType(0);
5069 assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005070
Duncan Sands92c43912008-06-06 12:08:01 +00005071 MVT EltType = VT.getVectorElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005072 SDOperand LHS = N->getOperand(0);
5073 SDOperand RHS = N->getOperand(1);
5074 SDOperand Shuffle = XformToShuffleWithZero(N);
5075 if (Shuffle.Val) return Shuffle;
5076
5077 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
5078 // this operation.
5079 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
5080 RHS.getOpcode() == ISD::BUILD_VECTOR) {
5081 SmallVector<SDOperand, 8> Ops;
5082 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
5083 SDOperand LHSOp = LHS.getOperand(i);
5084 SDOperand RHSOp = RHS.getOperand(i);
5085 // If these two elements can't be folded, bail out.
5086 if ((LHSOp.getOpcode() != ISD::UNDEF &&
5087 LHSOp.getOpcode() != ISD::Constant &&
5088 LHSOp.getOpcode() != ISD::ConstantFP) ||
5089 (RHSOp.getOpcode() != ISD::UNDEF &&
5090 RHSOp.getOpcode() != ISD::Constant &&
5091 RHSOp.getOpcode() != ISD::ConstantFP))
5092 break;
5093 // Can't fold divide by zero.
5094 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
5095 N->getOpcode() == ISD::FDIV) {
5096 if ((RHSOp.getOpcode() == ISD::Constant &&
5097 cast<ConstantSDNode>(RHSOp.Val)->isNullValue()) ||
5098 (RHSOp.getOpcode() == ISD::ConstantFP &&
Dale Johannesen7604c1b2007-08-31 23:34:27 +00005099 cast<ConstantFPSDNode>(RHSOp.Val)->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005100 break;
5101 }
5102 Ops.push_back(DAG.getNode(N->getOpcode(), EltType, LHSOp, RHSOp));
5103 AddToWorkList(Ops.back().Val);
5104 assert((Ops.back().getOpcode() == ISD::UNDEF ||
5105 Ops.back().getOpcode() == ISD::Constant ||
5106 Ops.back().getOpcode() == ISD::ConstantFP) &&
5107 "Scalar binop didn't fold!");
5108 }
5109
5110 if (Ops.size() == LHS.getNumOperands()) {
Duncan Sands92c43912008-06-06 12:08:01 +00005111 MVT VT = LHS.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005112 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
5113 }
5114 }
5115
5116 return SDOperand();
5117}
5118
5119SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
5120 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
5121
5122 SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
5123 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5124 // If we got a simplified select_cc node back from SimplifySelectCC, then
5125 // break it down into a new SETCC node, and a new SELECT node, and then return
5126 // the SELECT node, since we were called with a SELECT node.
5127 if (SCC.Val) {
5128 // Check to see if we got a select_cc back (to turn into setcc/select).
5129 // Otherwise, just return whatever node we got back, like fabs.
5130 if (SCC.getOpcode() == ISD::SELECT_CC) {
5131 SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
5132 SCC.getOperand(0), SCC.getOperand(1),
5133 SCC.getOperand(4));
5134 AddToWorkList(SETCC.Val);
5135 return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
5136 SCC.getOperand(3), SETCC);
5137 }
5138 return SCC;
5139 }
5140 return SDOperand();
5141}
5142
5143/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
5144/// are the two values being selected between, see if we can simplify the
5145/// select. Callers of this should assume that TheSelect is deleted if this
5146/// returns true. As such, they should return the appropriate thing (e.g. the
5147/// node) back to the top-level of the DAG combiner loop to avoid it being
5148/// looked at.
5149///
5150bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
5151 SDOperand RHS) {
5152
5153 // If this is a select from two identical things, try to pull the operation
5154 // through the select.
5155 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
5156 // If this is a load and the token chain is identical, replace the select
5157 // of two loads with a load through a select of the address to load from.
5158 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
5159 // constants have been dropped into the constant pool.
5160 if (LHS.getOpcode() == ISD::LOAD &&
Duncan Sands2418bec2008-06-13 19:07:40 +00005161 // Do not let this transformation reduce the number of volatile loads.
5162 !cast<LoadSDNode>(LHS)->isVolatile() &&
5163 !cast<LoadSDNode>(RHS)->isVolatile() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005164 // Token chains must be identical.
5165 LHS.getOperand(0) == RHS.getOperand(0)) {
5166 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
5167 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
5168
5169 // If this is an EXTLOAD, the VT's must match.
Dan Gohman9a4c92c2008-01-30 00:15:11 +00005170 if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005171 // FIXME: this conflates two src values, discarding one. This is not
5172 // the right thing to do, but nothing uses srcvalues now. When they do,
5173 // turn SrcValue into a list of locations.
5174 SDOperand Addr;
5175 if (TheSelect->getOpcode() == ISD::SELECT) {
5176 // Check that the condition doesn't reach either load. If so, folding
5177 // this will induce a cycle into the DAG.
Evan Chengd9387682008-03-04 00:41:45 +00005178 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5179 !RLD->isPredecessorOf(TheSelect->getOperand(0).Val)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005180 Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
5181 TheSelect->getOperand(0), LLD->getBasePtr(),
5182 RLD->getBasePtr());
5183 }
5184 } else {
5185 // Check that the condition doesn't reach either load. If so, folding
5186 // this will induce a cycle into the DAG.
Evan Chengd9387682008-03-04 00:41:45 +00005187 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5188 !RLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5189 !LLD->isPredecessorOf(TheSelect->getOperand(1).Val) &&
5190 !RLD->isPredecessorOf(TheSelect->getOperand(1).Val)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005191 Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
5192 TheSelect->getOperand(0),
5193 TheSelect->getOperand(1),
5194 LLD->getBasePtr(), RLD->getBasePtr(),
5195 TheSelect->getOperand(4));
5196 }
5197 }
5198
5199 if (Addr.Val) {
5200 SDOperand Load;
5201 if (LLD->getExtensionType() == ISD::NON_EXTLOAD)
5202 Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(),
5203 Addr,LLD->getSrcValue(),
5204 LLD->getSrcValueOffset(),
5205 LLD->isVolatile(),
5206 LLD->getAlignment());
5207 else {
5208 Load = DAG.getExtLoad(LLD->getExtensionType(),
5209 TheSelect->getValueType(0),
5210 LLD->getChain(), Addr, LLD->getSrcValue(),
5211 LLD->getSrcValueOffset(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00005212 LLD->getMemoryVT(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005213 LLD->isVolatile(),
5214 LLD->getAlignment());
5215 }
5216 // Users of the select now use the result of the load.
5217 CombineTo(TheSelect, Load);
5218
5219 // Users of the old loads now use the new load's chain. We know the
5220 // old-load value is dead now.
5221 CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
5222 CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
5223 return true;
5224 }
5225 }
5226 }
5227 }
5228
5229 return false;
5230}
5231
5232SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
5233 SDOperand N2, SDOperand N3,
5234 ISD::CondCode CC, bool NotExtCompare) {
5235
Duncan Sands92c43912008-06-06 12:08:01 +00005236 MVT VT = N2.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005237 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
5238 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
5239 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
5240
5241 // Determine if the condition we're dealing with is constant
Scott Michel502151f2008-03-10 15:42:14 +00005242 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005243 if (SCC.Val) AddToWorkList(SCC.Val);
5244 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
5245
5246 // fold select_cc true, x, y -> x
Dan Gohman9d24dc72008-03-13 22:13:53 +00005247 if (SCCC && !SCCC->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005248 return N2;
5249 // fold select_cc false, x, y -> y
Dan Gohman9d24dc72008-03-13 22:13:53 +00005250 if (SCCC && SCCC->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005251 return N3;
5252
5253 // Check to see if we can simplify the select into an fabs node
5254 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
5255 // Allow either -0.0 or 0.0
Dale Johannesen7f2c1d12007-08-25 22:10:57 +00005256 if (CFP->getValueAPF().isZero()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005257 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
5258 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
5259 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
5260 N2 == N3.getOperand(0))
5261 return DAG.getNode(ISD::FABS, VT, N0);
5262
5263 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
5264 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
5265 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
5266 N2.getOperand(0) == N3)
5267 return DAG.getNode(ISD::FABS, VT, N3);
5268 }
5269 }
5270
5271 // Check to see if we can perform the "gzip trick", transforming
5272 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
5273 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Duncan Sands92c43912008-06-06 12:08:01 +00005274 N0.getValueType().isInteger() &&
5275 N2.getValueType().isInteger() &&
Dan Gohman9d24dc72008-03-13 22:13:53 +00005276 (N1C->isNullValue() || // (a < 0) ? b : 0
5277 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Duncan Sands92c43912008-06-06 12:08:01 +00005278 MVT XType = N0.getValueType();
5279 MVT AType = N2.getValueType();
Duncan Sandsec142ee2008-06-08 20:54:56 +00005280 if (XType.bitsGE(AType)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005281 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
5282 // single-bit constant.
Dan Gohman9d24dc72008-03-13 22:13:53 +00005283 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
5284 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands92c43912008-06-06 12:08:01 +00005285 ShCtV = XType.getSizeInBits()-ShCtV-1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005286 SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
5287 SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
5288 AddToWorkList(Shift.Val);
Duncan Sandsec142ee2008-06-08 20:54:56 +00005289 if (XType.bitsGT(AType)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005290 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5291 AddToWorkList(Shift.Val);
5292 }
5293 return DAG.getNode(ISD::AND, AType, Shift, N2);
5294 }
5295 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
Duncan Sands92c43912008-06-06 12:08:01 +00005296 DAG.getConstant(XType.getSizeInBits()-1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005297 TLI.getShiftAmountTy()));
5298 AddToWorkList(Shift.Val);
Duncan Sandsec142ee2008-06-08 20:54:56 +00005299 if (XType.bitsGT(AType)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005300 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5301 AddToWorkList(Shift.Val);
5302 }
5303 return DAG.getNode(ISD::AND, AType, Shift, N2);
5304 }
5305 }
5306
5307 // fold select C, 16, 0 -> shl C, 4
Dan Gohman9d24dc72008-03-13 22:13:53 +00005308 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005309 TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
5310
5311 // If the caller doesn't want us to simplify this into a zext of a compare,
5312 // don't do it.
Dan Gohman9d24dc72008-03-13 22:13:53 +00005313 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005314 return SDOperand();
5315
5316 // Get a SetCC of the condition
5317 // FIXME: Should probably make sure that setcc is legal if we ever have a
5318 // target where it isn't.
5319 SDOperand Temp, SCC;
5320 // cast from setcc result type to select result type
5321 if (AfterLegalize) {
Scott Michel502151f2008-03-10 15:42:14 +00005322 SCC = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
Duncan Sandsec142ee2008-06-08 20:54:56 +00005323 if (N2.getValueType().bitsLT(SCC.getValueType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005324 Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
5325 else
5326 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5327 } else {
5328 SCC = DAG.getSetCC(MVT::i1, N0, N1, CC);
5329 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5330 }
5331 AddToWorkList(SCC.Val);
5332 AddToWorkList(Temp.Val);
5333
Dan Gohman9d24dc72008-03-13 22:13:53 +00005334 if (N2C->getAPIntValue() == 1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005335 return Temp;
5336 // shl setcc result by log2 n2c
5337 return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
Dan Gohman9d24dc72008-03-13 22:13:53 +00005338 DAG.getConstant(N2C->getAPIntValue().logBase2(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005339 TLI.getShiftAmountTy()));
5340 }
5341
5342 // Check to see if this is the equivalent of setcc
5343 // FIXME: Turn all of these into setcc if setcc if setcc is legal
5344 // otherwise, go ahead with the folds.
Dan Gohman9d24dc72008-03-13 22:13:53 +00005345 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Duncan Sands92c43912008-06-06 12:08:01 +00005346 MVT XType = N0.getValueType();
Duncan Sands6ae1a0632008-06-14 17:48:34 +00005347 if (!AfterLegalize ||
5348 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(N0))) {
Scott Michel502151f2008-03-10 15:42:14 +00005349 SDOperand Res = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005350 if (Res.getValueType() != VT)
5351 Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
5352 return Res;
5353 }
5354
5355 // seteq X, 0 -> srl (ctlz X, log2(size(X)))
5356 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sands6ae1a0632008-06-14 17:48:34 +00005357 (!AfterLegalize ||
5358 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005359 SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
5360 return DAG.getNode(ISD::SRL, XType, Ctlz,
Duncan Sands92c43912008-06-06 12:08:01 +00005361 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005362 TLI.getShiftAmountTy()));
5363 }
5364 // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
5365 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
5366 SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
5367 N0);
5368 SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0,
5369 DAG.getConstant(~0ULL, XType));
5370 return DAG.getNode(ISD::SRL, XType,
5371 DAG.getNode(ISD::AND, XType, NegN0, NotN0),
Duncan Sands92c43912008-06-06 12:08:01 +00005372 DAG.getConstant(XType.getSizeInBits()-1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005373 TLI.getShiftAmountTy()));
5374 }
5375 // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
5376 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
5377 SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
Duncan Sands92c43912008-06-06 12:08:01 +00005378 DAG.getConstant(XType.getSizeInBits()-1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005379 TLI.getShiftAmountTy()));
5380 return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
5381 }
5382 }
5383
5384 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
5385 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5386 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
5387 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
Duncan Sands92c43912008-06-06 12:08:01 +00005388 N2.getOperand(0) == N1 && N0.getValueType().isInteger()) {
5389 MVT XType = N0.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005390 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
Duncan Sands92c43912008-06-06 12:08:01 +00005391 DAG.getConstant(XType.getSizeInBits()-1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005392 TLI.getShiftAmountTy()));
5393 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5394 AddToWorkList(Shift.Val);
5395 AddToWorkList(Add.Val);
5396 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5397 }
5398 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
5399 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5400 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
5401 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
5402 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
Duncan Sands92c43912008-06-06 12:08:01 +00005403 MVT XType = N0.getValueType();
5404 if (SubC->isNullValue() && XType.isInteger()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005405 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
Duncan Sands92c43912008-06-06 12:08:01 +00005406 DAG.getConstant(XType.getSizeInBits()-1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005407 TLI.getShiftAmountTy()));
5408 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5409 AddToWorkList(Shift.Val);
5410 AddToWorkList(Add.Val);
5411 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5412 }
5413 }
5414 }
5415
5416 return SDOperand();
5417}
5418
5419/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
Duncan Sands92c43912008-06-06 12:08:01 +00005420SDOperand DAGCombiner::SimplifySetCC(MVT VT, SDOperand N0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005421 SDOperand N1, ISD::CondCode Cond,
5422 bool foldBooleans) {
5423 TargetLowering::DAGCombinerInfo
5424 DagCombineInfo(DAG, !AfterLegalize, false, this);
5425 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo);
5426}
5427
5428/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
5429/// return a DAG expression to select that will generate the same value by
5430/// multiplying by a magic number. See:
5431/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5432SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
5433 std::vector<SDNode*> Built;
5434 SDOperand S = TLI.BuildSDIV(N, DAG, &Built);
5435
5436 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5437 ii != ee; ++ii)
5438 AddToWorkList(*ii);
5439 return S;
5440}
5441
5442/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
5443/// return a DAG expression to select that will generate the same value by
5444/// multiplying by a magic number. See:
5445/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5446SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
5447 std::vector<SDNode*> Built;
5448 SDOperand S = TLI.BuildUDIV(N, DAG, &Built);
5449
5450 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5451 ii != ee; ++ii)
5452 AddToWorkList(*ii);
5453 return S;
5454}
5455
5456/// FindBaseOffset - Return true if base is known not to alias with anything
5457/// but itself. Provides base object and offset as results.
5458static bool FindBaseOffset(SDOperand Ptr, SDOperand &Base, int64_t &Offset) {
5459 // Assume it is a primitive operation.
5460 Base = Ptr; Offset = 0;
5461
5462 // If it's an adding a simple constant then integrate the offset.
5463 if (Base.getOpcode() == ISD::ADD) {
5464 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
5465 Base = Base.getOperand(0);
5466 Offset += C->getValue();
5467 }
5468 }
5469
5470 // If it's any of the following then it can't alias with anything but itself.
5471 return isa<FrameIndexSDNode>(Base) ||
5472 isa<ConstantPoolSDNode>(Base) ||
5473 isa<GlobalAddressSDNode>(Base);
5474}
5475
5476/// isAlias - Return true if there is any possibility that the two addresses
5477/// overlap.
5478bool DAGCombiner::isAlias(SDOperand Ptr1, int64_t Size1,
5479 const Value *SrcValue1, int SrcValueOffset1,
5480 SDOperand Ptr2, int64_t Size2,
5481 const Value *SrcValue2, int SrcValueOffset2)
5482{
5483 // If they are the same then they must be aliases.
5484 if (Ptr1 == Ptr2) return true;
5485
5486 // Gather base node and offset information.
5487 SDOperand Base1, Base2;
5488 int64_t Offset1, Offset2;
5489 bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
5490 bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
5491
5492 // If they have a same base address then...
5493 if (Base1 == Base2) {
5494 // Check to see if the addresses overlap.
5495 return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
5496 }
5497
5498 // If we know both bases then they can't alias.
5499 if (KnownBase1 && KnownBase2) return false;
5500
5501 if (CombinerGlobalAA) {
5502 // Use alias analysis information.
Dan Gohmane142c2e2007-08-27 16:32:11 +00005503 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
5504 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
5505 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005506 AliasAnalysis::AliasResult AAResult =
5507 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
5508 if (AAResult == AliasAnalysis::NoAlias)
5509 return false;
5510 }
5511
5512 // Otherwise we have to assume they alias.
5513 return true;
5514}
5515
5516/// FindAliasInfo - Extracts the relevant alias information from the memory
5517/// node. Returns true if the operand was a load.
5518bool DAGCombiner::FindAliasInfo(SDNode *N,
5519 SDOperand &Ptr, int64_t &Size,
5520 const Value *&SrcValue, int &SrcValueOffset) {
5521 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5522 Ptr = LD->getBasePtr();
Duncan Sands92c43912008-06-06 12:08:01 +00005523 Size = LD->getMemoryVT().getSizeInBits() >> 3;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005524 SrcValue = LD->getSrcValue();
5525 SrcValueOffset = LD->getSrcValueOffset();
5526 return true;
5527 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5528 Ptr = ST->getBasePtr();
Duncan Sands92c43912008-06-06 12:08:01 +00005529 Size = ST->getMemoryVT().getSizeInBits() >> 3;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005530 SrcValue = ST->getSrcValue();
5531 SrcValueOffset = ST->getSrcValueOffset();
5532 } else {
5533 assert(0 && "FindAliasInfo expected a memory operand");
5534 }
5535
5536 return false;
5537}
5538
5539/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
5540/// looking for aliasing nodes and adding them to the Aliases vector.
5541void DAGCombiner::GatherAllAliases(SDNode *N, SDOperand OriginalChain,
5542 SmallVector<SDOperand, 8> &Aliases) {
5543 SmallVector<SDOperand, 8> Chains; // List of chains to visit.
5544 std::set<SDNode *> Visited; // Visited node set.
5545
5546 // Get alias information for node.
5547 SDOperand Ptr;
5548 int64_t Size;
5549 const Value *SrcValue;
5550 int SrcValueOffset;
5551 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
5552
5553 // Starting off.
5554 Chains.push_back(OriginalChain);
5555
5556 // Look at each chain and determine if it is an alias. If so, add it to the
5557 // aliases list. If not, then continue up the chain looking for the next
5558 // candidate.
5559 while (!Chains.empty()) {
5560 SDOperand Chain = Chains.back();
5561 Chains.pop_back();
5562
5563 // Don't bother if we've been before.
5564 if (Visited.find(Chain.Val) != Visited.end()) continue;
5565 Visited.insert(Chain.Val);
5566
5567 switch (Chain.getOpcode()) {
5568 case ISD::EntryToken:
5569 // Entry token is ideal chain operand, but handled in FindBetterChain.
5570 break;
5571
5572 case ISD::LOAD:
5573 case ISD::STORE: {
5574 // Get alias information for Chain.
5575 SDOperand OpPtr;
5576 int64_t OpSize;
5577 const Value *OpSrcValue;
5578 int OpSrcValueOffset;
5579 bool IsOpLoad = FindAliasInfo(Chain.Val, OpPtr, OpSize,
5580 OpSrcValue, OpSrcValueOffset);
5581
5582 // If chain is alias then stop here.
5583 if (!(IsLoad && IsOpLoad) &&
5584 isAlias(Ptr, Size, SrcValue, SrcValueOffset,
5585 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
5586 Aliases.push_back(Chain);
5587 } else {
5588 // Look further up the chain.
5589 Chains.push_back(Chain.getOperand(0));
5590 // Clean up old chain.
5591 AddToWorkList(Chain.Val);
5592 }
5593 break;
5594 }
5595
5596 case ISD::TokenFactor:
5597 // We have to check each of the operands of the token factor, so we queue
5598 // then up. Adding the operands to the queue (stack) in reverse order
5599 // maintains the original order and increases the likelihood that getNode
5600 // will find a matching token factor (CSE.)
5601 for (unsigned n = Chain.getNumOperands(); n;)
5602 Chains.push_back(Chain.getOperand(--n));
5603 // Eliminate the token factor if we can.
5604 AddToWorkList(Chain.Val);
5605 break;
5606
5607 default:
5608 // For all other instructions we will just have to take what we can get.
5609 Aliases.push_back(Chain);
5610 break;
5611 }
5612 }
5613}
5614
5615/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
5616/// for a better chain (aliasing node.)
5617SDOperand DAGCombiner::FindBetterChain(SDNode *N, SDOperand OldChain) {
5618 SmallVector<SDOperand, 8> Aliases; // Ops for replacing token factor.
5619
5620 // Accumulate all the aliases to this node.
5621 GatherAllAliases(N, OldChain, Aliases);
5622
5623 if (Aliases.size() == 0) {
5624 // If no operands then chain to entry token.
5625 return DAG.getEntryNode();
5626 } else if (Aliases.size() == 1) {
5627 // If a single operand then chain to it. We don't need to revisit it.
5628 return Aliases[0];
5629 }
5630
5631 // Construct a custom tailored token factor.
5632 SDOperand NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5633 &Aliases[0], Aliases.size());
5634
5635 // Make sure the old chain gets cleaned up.
5636 if (NewChain != OldChain) AddToWorkList(OldChain.Val);
5637
5638 return NewChain;
5639}
5640
5641// SelectionDAG::Combine - This is the entry point for the file.
5642//
5643void SelectionDAG::Combine(bool RunningAfterLegalize, AliasAnalysis &AA) {
5644 if (!RunningAfterLegalize && ViewDAGCombine1)
5645 viewGraph();
5646 if (RunningAfterLegalize && ViewDAGCombine2)
5647 viewGraph();
5648 /// run - This is the main entry point to this class.
5649 ///
5650 DAGCombiner(*this, AA).Run(RunningAfterLegalize);
5651}