blob: 684b2f66a59f1d3131c44d378225e9c75f05fbce [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>
32using namespace llvm;
33
34STATISTIC(NodesCombined , "Number of dag nodes combined");
35STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
36STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
37
38namespace {
39#ifndef NDEBUG
40 static cl::opt<bool>
41 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
42 cl::desc("Pop up a window to show dags before the first "
43 "dag combine pass"));
44 static cl::opt<bool>
45 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
46 cl::desc("Pop up a window to show dags before the second "
47 "dag combine pass"));
48#else
49 static const bool ViewDAGCombine1 = false;
50 static const bool ViewDAGCombine2 = false;
51#endif
52
53 static cl::opt<bool>
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Turn on alias analysis during testing"));
56
57 static cl::opt<bool>
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Include global information in alias analysis"));
60
61//------------------------------ DAGCombiner ---------------------------------//
62
63 class VISIBILITY_HIDDEN DAGCombiner {
64 SelectionDAG &DAG;
65 TargetLowering &TLI;
66 bool AfterLegalize;
67
68 // Worklist of all of the nodes that need to be simplified.
69 std::vector<SDNode*> WorkList;
70
71 // AA - Used for DAG load/store alias analysis.
72 AliasAnalysis &AA;
73
74 /// AddUsersToWorkList - When an instruction is simplified, add all users of
75 /// the instruction to the work lists because they might get more simplified
76 /// now.
77 ///
78 void AddUsersToWorkList(SDNode *N) {
79 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
80 UI != UE; ++UI)
Roman Levenstein05650fd2008-04-07 10:06:32 +000081 AddToWorkList(UI->getUser());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000082 }
83
Dan Gohman6c89ea72007-10-08 17:57:15 +000084 /// visit - call the node-specific routine that knows how to fold each
85 /// particular type of node.
86 SDOperand visit(SDNode *N);
87
Dan Gohmanf17a25c2007-07-18 16:29:46 +000088 public:
89 /// AddToWorkList - Add to the work list making sure it's instance is at the
90 /// the back (next to be processed.)
91 void AddToWorkList(SDNode *N) {
92 removeFromWorkList(N);
93 WorkList.push_back(N);
94 }
95
Chris Lattner7bcb18f2008-02-03 06:49:24 +000096 /// removeFromWorkList - remove all instances of N from the worklist.
97 ///
98 void removeFromWorkList(SDNode *N) {
99 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
100 WorkList.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000101 }
102
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000103 SDOperand CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
104 bool AddTo = true);
105
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000106 SDOperand CombineTo(SDNode *N, SDOperand Res, bool AddTo = true) {
107 return CombineTo(N, &Res, 1, AddTo);
108 }
109
110 SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1,
111 bool AddTo = true) {
112 SDOperand To[] = { Res0, Res1 };
113 return CombineTo(N, To, 2, AddTo);
114 }
Chris Lattner5872a362008-01-17 07:00:52 +0000115
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000116 private:
117
118 /// SimplifyDemandedBits - Check the specified integer node value to see if
119 /// it can be simplified or if things it uses can be simplified by bit
120 /// propagation. If so, return true.
Dan Gohman11607792008-02-27 00:25:32 +0000121 bool SimplifyDemandedBits(SDOperand Op) {
122 APInt Demanded = APInt::getAllOnesValue(Op.getValueSizeInBits());
123 return SimplifyDemandedBits(Op, Demanded);
124 }
125
126 bool SimplifyDemandedBits(SDOperand Op, const APInt &Demanded);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127
128 bool CombineToPreIndexedLoadStore(SDNode *N);
129 bool CombineToPostIndexedLoadStore(SDNode *N);
130
131
Dan Gohman6c89ea72007-10-08 17:57:15 +0000132 /// combine - call the node-specific routine that knows how to fold each
133 /// particular type of node. If that doesn't do anything, try the
134 /// target-specific DAG combines.
135 SDOperand combine(SDNode *N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000136
137 // Visitation implementation - Implement dag node combining for different
138 // node types. The semantics are as follows:
139 // Return Value:
140 // SDOperand.Val == 0 - No change was made
141 // SDOperand.Val == N - N was replaced, is dead, and is already handled.
142 // otherwise - N should be replaced by the returned Operand.
143 //
144 SDOperand visitTokenFactor(SDNode *N);
Chris Lattnerf32fa7f2008-02-13 07:25:05 +0000145 SDOperand visitMERGE_VALUES(SDNode *N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000146 SDOperand visitADD(SDNode *N);
147 SDOperand visitSUB(SDNode *N);
148 SDOperand visitADDC(SDNode *N);
149 SDOperand visitADDE(SDNode *N);
150 SDOperand visitMUL(SDNode *N);
151 SDOperand visitSDIV(SDNode *N);
152 SDOperand visitUDIV(SDNode *N);
153 SDOperand visitSREM(SDNode *N);
154 SDOperand visitUREM(SDNode *N);
155 SDOperand visitMULHU(SDNode *N);
156 SDOperand visitMULHS(SDNode *N);
Dan Gohman6c89ea72007-10-08 17:57:15 +0000157 SDOperand visitSMUL_LOHI(SDNode *N);
158 SDOperand visitUMUL_LOHI(SDNode *N);
159 SDOperand visitSDIVREM(SDNode *N);
160 SDOperand visitUDIVREM(SDNode *N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161 SDOperand visitAND(SDNode *N);
162 SDOperand visitOR(SDNode *N);
163 SDOperand visitXOR(SDNode *N);
164 SDOperand SimplifyVBinOp(SDNode *N);
165 SDOperand visitSHL(SDNode *N);
166 SDOperand visitSRA(SDNode *N);
167 SDOperand visitSRL(SDNode *N);
168 SDOperand visitCTLZ(SDNode *N);
169 SDOperand visitCTTZ(SDNode *N);
170 SDOperand visitCTPOP(SDNode *N);
171 SDOperand visitSELECT(SDNode *N);
172 SDOperand visitSELECT_CC(SDNode *N);
173 SDOperand visitSETCC(SDNode *N);
174 SDOperand visitSIGN_EXTEND(SDNode *N);
175 SDOperand visitZERO_EXTEND(SDNode *N);
176 SDOperand visitANY_EXTEND(SDNode *N);
177 SDOperand visitSIGN_EXTEND_INREG(SDNode *N);
178 SDOperand visitTRUNCATE(SDNode *N);
179 SDOperand visitBIT_CONVERT(SDNode *N);
Evan Chengb6290462008-05-12 23:04:07 +0000180 SDOperand visitBUILD_PAIR(SDNode *N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000181 SDOperand visitFADD(SDNode *N);
182 SDOperand visitFSUB(SDNode *N);
183 SDOperand visitFMUL(SDNode *N);
184 SDOperand visitFDIV(SDNode *N);
185 SDOperand visitFREM(SDNode *N);
186 SDOperand visitFCOPYSIGN(SDNode *N);
187 SDOperand visitSINT_TO_FP(SDNode *N);
188 SDOperand visitUINT_TO_FP(SDNode *N);
189 SDOperand visitFP_TO_SINT(SDNode *N);
190 SDOperand visitFP_TO_UINT(SDNode *N);
191 SDOperand visitFP_ROUND(SDNode *N);
192 SDOperand visitFP_ROUND_INREG(SDNode *N);
193 SDOperand visitFP_EXTEND(SDNode *N);
194 SDOperand visitFNEG(SDNode *N);
195 SDOperand visitFABS(SDNode *N);
196 SDOperand visitBRCOND(SDNode *N);
197 SDOperand visitBR_CC(SDNode *N);
198 SDOperand visitLOAD(SDNode *N);
199 SDOperand visitSTORE(SDNode *N);
200 SDOperand visitINSERT_VECTOR_ELT(SDNode *N);
Evan Chengd7ba7ed2007-10-06 08:19:55 +0000201 SDOperand visitEXTRACT_VECTOR_ELT(SDNode *N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000202 SDOperand visitBUILD_VECTOR(SDNode *N);
203 SDOperand visitCONCAT_VECTORS(SDNode *N);
204 SDOperand visitVECTOR_SHUFFLE(SDNode *N);
205
206 SDOperand XformToShuffleWithZero(SDNode *N);
207 SDOperand ReassociateOps(unsigned Opc, SDOperand LHS, SDOperand RHS);
208
Chris Lattner91ed3c32007-12-06 07:33:36 +0000209 SDOperand visitShiftByConstant(SDNode *N, unsigned Amt);
210
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211 bool SimplifySelectOps(SDNode *SELECT, SDOperand LHS, SDOperand RHS);
212 SDOperand SimplifyBinOpWithSameOpcodeHands(SDNode *N);
213 SDOperand SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2);
214 SDOperand SimplifySelectCC(SDOperand N0, SDOperand N1, SDOperand N2,
215 SDOperand N3, ISD::CondCode CC,
216 bool NotExtCompare = false);
217 SDOperand SimplifySetCC(MVT::ValueType VT, SDOperand N0, SDOperand N1,
218 ISD::CondCode Cond, bool foldBooleans = true);
Chris Lattner4a7c8452008-01-26 01:09:19 +0000219 SDOperand SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
220 unsigned HiOp);
Evan Chengb6290462008-05-12 23:04:07 +0000221 SDOperand CombineConsecutiveLoads(SDNode *N, MVT::ValueType VT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222 SDOperand ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, MVT::ValueType);
223 SDOperand BuildSDIV(SDNode *N);
224 SDOperand BuildUDIV(SDNode *N);
225 SDNode *MatchRotate(SDOperand LHS, SDOperand RHS);
226 SDOperand ReduceLoadWidth(SDNode *N);
227
Dan Gohman07961cd2008-02-25 21:11:39 +0000228 SDOperand GetDemandedBits(SDOperand V, const APInt &Mask);
Chris Lattnere8671c52007-10-13 06:35:54 +0000229
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
231 /// looking for aliasing nodes and adding them to the Aliases vector.
232 void GatherAllAliases(SDNode *N, SDOperand OriginalChain,
233 SmallVector<SDOperand, 8> &Aliases);
234
235 /// isAlias - Return true if there is any possibility that the two addresses
236 /// overlap.
237 bool isAlias(SDOperand Ptr1, int64_t Size1,
238 const Value *SrcValue1, int SrcValueOffset1,
239 SDOperand Ptr2, int64_t Size2,
240 const Value *SrcValue2, int SrcValueOffset2);
241
242 /// FindAliasInfo - Extracts the relevant alias information from the memory
243 /// node. Returns true if the operand was a load.
244 bool FindAliasInfo(SDNode *N,
245 SDOperand &Ptr, int64_t &Size,
246 const Value *&SrcValue, int &SrcValueOffset);
247
248 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
249 /// looking for a better chain (aliasing node.)
250 SDOperand FindBetterChain(SDNode *N, SDOperand Chain);
251
252public:
253 DAGCombiner(SelectionDAG &D, AliasAnalysis &A)
254 : DAG(D),
255 TLI(D.getTargetLoweringInfo()),
256 AfterLegalize(false),
257 AA(A) {}
258
259 /// Run - runs the dag combiner on all nodes in the work list
260 void Run(bool RunningAfterLegalize);
261 };
262}
263
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000264
265namespace {
266/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
267/// nodes from the worklist.
268class VISIBILITY_HIDDEN WorkListRemover :
269 public SelectionDAG::DAGUpdateListener {
270 DAGCombiner &DC;
271public:
Dan Gohmana789bff2008-02-20 16:44:09 +0000272 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000273
274 virtual void NodeDeleted(SDNode *N) {
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000275 DC.removeFromWorkList(N);
276 }
277
278 virtual void NodeUpdated(SDNode *N) {
279 // Ignore updates.
280 }
281};
282}
283
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000284//===----------------------------------------------------------------------===//
285// TargetLowering::DAGCombinerInfo implementation
286//===----------------------------------------------------------------------===//
287
288void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
289 ((DAGCombiner*)DC)->AddToWorkList(N);
290}
291
292SDOperand TargetLowering::DAGCombinerInfo::
293CombineTo(SDNode *N, const std::vector<SDOperand> &To) {
294 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
295}
296
297SDOperand TargetLowering::DAGCombinerInfo::
298CombineTo(SDNode *N, SDOperand Res) {
299 return ((DAGCombiner*)DC)->CombineTo(N, Res);
300}
301
302
303SDOperand TargetLowering::DAGCombinerInfo::
304CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
305 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
306}
307
308
309//===----------------------------------------------------------------------===//
310// Helper Functions
311//===----------------------------------------------------------------------===//
312
313/// isNegatibleForFree - Return 1 if we can compute the negated form of the
314/// specified expression for the same cost as the expression itself, or 2 if we
315/// can compute the negated form more cheaply than the expression itself.
Chris Lattnere0992b82008-02-26 07:04:54 +0000316static char isNegatibleForFree(SDOperand Op, bool AfterLegalize,
317 unsigned Depth = 0) {
Dale Johannesenb89072e2007-10-16 23:38:29 +0000318 // No compile time optimizations on this type.
319 if (Op.getValueType() == MVT::ppcf128)
320 return 0;
321
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000322 // fneg is removable even if it has multiple uses.
323 if (Op.getOpcode() == ISD::FNEG) return 2;
324
325 // Don't allow anything with multiple uses.
326 if (!Op.hasOneUse()) return 0;
327
328 // Don't recurse exponentially.
329 if (Depth > 6) return 0;
330
331 switch (Op.getOpcode()) {
332 default: return false;
333 case ISD::ConstantFP:
Chris Lattnere0992b82008-02-26 07:04:54 +0000334 // Don't invert constant FP values after legalize. The negated constant
335 // isn't necessarily legal.
336 return AfterLegalize ? 0 : 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000337 case ISD::FADD:
338 // FIXME: determine better conditions for this xform.
339 if (!UnsafeFPMath) return 0;
340
341 // -(A+B) -> -A - B
Chris Lattnere0992b82008-02-26 07:04:54 +0000342 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000343 return V;
344 // -(A+B) -> -B - A
Chris Lattnere0992b82008-02-26 07:04:54 +0000345 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346 case ISD::FSUB:
347 // We can't turn -(A-B) into B-A when we honor signed zeros.
348 if (!UnsafeFPMath) return 0;
349
350 // -(A-B) -> B-A
351 return 1;
352
353 case ISD::FMUL:
354 case ISD::FDIV:
355 if (HonorSignDependentRoundingFPMath()) return 0;
356
357 // -(X*Y) -> (-X * Y) or (X*-Y)
Chris Lattnere0992b82008-02-26 07:04:54 +0000358 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000359 return V;
360
Chris Lattnere0992b82008-02-26 07:04:54 +0000361 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000362
363 case ISD::FP_EXTEND:
364 case ISD::FP_ROUND:
365 case ISD::FSIN:
Chris Lattnere0992b82008-02-26 07:04:54 +0000366 return isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000367 }
368}
369
370/// GetNegatedExpression - If isNegatibleForFree returns true, this function
371/// returns the newly negated expression.
372static SDOperand GetNegatedExpression(SDOperand Op, SelectionDAG &DAG,
Chris Lattnere0992b82008-02-26 07:04:54 +0000373 bool AfterLegalize, unsigned Depth = 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000374 // fneg is removable even if it has multiple uses.
375 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
376
377 // Don't allow anything with multiple uses.
378 assert(Op.hasOneUse() && "Unknown reuse!");
379
380 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
381 switch (Op.getOpcode()) {
382 default: assert(0 && "Unknown code");
Dale Johannesen7604c1b2007-08-31 23:34:27 +0000383 case ISD::ConstantFP: {
384 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
385 V.changeSign();
386 return DAG.getConstantFP(V, Op.getValueType());
387 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000388 case ISD::FADD:
389 // FIXME: determine better conditions for this xform.
390 assert(UnsafeFPMath);
391
392 // -(A+B) -> -A - B
Chris Lattnere0992b82008-02-26 07:04:54 +0000393 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000394 return DAG.getNode(ISD::FSUB, Op.getValueType(),
Chris Lattnere0992b82008-02-26 07:04:54 +0000395 GetNegatedExpression(Op.getOperand(0), DAG,
396 AfterLegalize, Depth+1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000397 Op.getOperand(1));
398 // -(A+B) -> -B - A
399 return DAG.getNode(ISD::FSUB, Op.getValueType(),
Chris Lattnere0992b82008-02-26 07:04:54 +0000400 GetNegatedExpression(Op.getOperand(1), DAG,
401 AfterLegalize, Depth+1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000402 Op.getOperand(0));
403 case ISD::FSUB:
404 // We can't turn -(A-B) into B-A when we honor signed zeros.
405 assert(UnsafeFPMath);
406
407 // -(0-B) -> B
408 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen7604c1b2007-08-31 23:34:27 +0000409 if (N0CFP->getValueAPF().isZero())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000410 return Op.getOperand(1);
411
412 // -(A-B) -> B-A
413 return DAG.getNode(ISD::FSUB, Op.getValueType(), Op.getOperand(1),
414 Op.getOperand(0));
415
416 case ISD::FMUL:
417 case ISD::FDIV:
418 assert(!HonorSignDependentRoundingFPMath());
419
420 // -(X*Y) -> -X * Y
Chris Lattner46360032008-02-26 17:09:59 +0000421 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000422 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
Chris Lattnere0992b82008-02-26 07:04:54 +0000423 GetNegatedExpression(Op.getOperand(0), DAG,
424 AfterLegalize, Depth+1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000425 Op.getOperand(1));
426
427 // -(X*Y) -> X * -Y
428 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
429 Op.getOperand(0),
Chris Lattnere0992b82008-02-26 07:04:54 +0000430 GetNegatedExpression(Op.getOperand(1), DAG,
431 AfterLegalize, Depth+1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432
433 case ISD::FP_EXTEND:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000434 case ISD::FSIN:
435 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
Chris Lattnere0992b82008-02-26 07:04:54 +0000436 GetNegatedExpression(Op.getOperand(0), DAG,
437 AfterLegalize, Depth+1));
Chris Lattner5872a362008-01-17 07:00:52 +0000438 case ISD::FP_ROUND:
439 return DAG.getNode(ISD::FP_ROUND, Op.getValueType(),
Chris Lattnere0992b82008-02-26 07:04:54 +0000440 GetNegatedExpression(Op.getOperand(0), DAG,
441 AfterLegalize, Depth+1),
Chris Lattner5872a362008-01-17 07:00:52 +0000442 Op.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000443 }
444}
445
446
447// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
448// that selects between the values 1 and 0, making it equivalent to a setcc.
449// Also, set the incoming LHS, RHS, and CC references to the appropriate
450// nodes based on the type of node we are checking. This simplifies life a
451// bit for the callers.
452static bool isSetCCEquivalent(SDOperand N, SDOperand &LHS, SDOperand &RHS,
453 SDOperand &CC) {
454 if (N.getOpcode() == ISD::SETCC) {
455 LHS = N.getOperand(0);
456 RHS = N.getOperand(1);
457 CC = N.getOperand(2);
458 return true;
459 }
460 if (N.getOpcode() == ISD::SELECT_CC &&
461 N.getOperand(2).getOpcode() == ISD::Constant &&
462 N.getOperand(3).getOpcode() == ISD::Constant &&
Dan Gohman9d24dc72008-03-13 22:13:53 +0000463 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000464 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
465 LHS = N.getOperand(0);
466 RHS = N.getOperand(1);
467 CC = N.getOperand(4);
468 return true;
469 }
470 return false;
471}
472
473// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
474// one use. If this is true, it allows the users to invert the operation for
475// free when it is profitable to do so.
476static bool isOneUseSetCC(SDOperand N) {
477 SDOperand N0, N1, N2;
478 if (isSetCCEquivalent(N, N0, N1, N2) && N.Val->hasOneUse())
479 return true;
480 return false;
481}
482
483SDOperand DAGCombiner::ReassociateOps(unsigned Opc, SDOperand N0, SDOperand N1){
484 MVT::ValueType VT = N0.getValueType();
485 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
486 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
487 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
488 if (isa<ConstantSDNode>(N1)) {
489 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1);
490 AddToWorkList(OpNode.Val);
491 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0));
492 } else if (N0.hasOneUse()) {
493 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1);
494 AddToWorkList(OpNode.Val);
495 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(1));
496 }
497 }
498 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
499 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
500 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
501 if (isa<ConstantSDNode>(N0)) {
502 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0);
503 AddToWorkList(OpNode.Val);
504 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0));
505 } else if (N1.hasOneUse()) {
506 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0);
507 AddToWorkList(OpNode.Val);
508 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1));
509 }
510 }
511 return SDOperand();
512}
513
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000514SDOperand DAGCombiner::CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
515 bool AddTo) {
516 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
517 ++NodesCombined;
518 DOUT << "\nReplacing.1 "; DEBUG(N->dump(&DAG));
519 DOUT << "\nWith: "; DEBUG(To[0].Val->dump(&DAG));
520 DOUT << " and " << NumTo-1 << " other values\n";
521 WorkListRemover DeadNodes(*this);
522 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
523
524 if (AddTo) {
525 // Push the new nodes and any users onto the worklist
526 for (unsigned i = 0, e = NumTo; i != e; ++i) {
527 AddToWorkList(To[i].Val);
528 AddUsersToWorkList(To[i].Val);
529 }
530 }
531
532 // Nodes can be reintroduced into the worklist. Make sure we do not
533 // process a node that has been replaced.
534 removeFromWorkList(N);
535
536 // Finally, since the node is now dead, remove it from the graph.
537 DAG.DeleteNode(N);
538 return SDOperand(N, 0);
539}
540
541/// SimplifyDemandedBits - Check the specified integer node value to see if
542/// it can be simplified or if things it uses can be simplified by bit
543/// propagation. If so, return true.
Dan Gohman11607792008-02-27 00:25:32 +0000544bool DAGCombiner::SimplifyDemandedBits(SDOperand Op, const APInt &Demanded) {
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000545 TargetLowering::TargetLoweringOpt TLO(DAG, AfterLegalize);
Dan Gohman11607792008-02-27 00:25:32 +0000546 APInt KnownZero, KnownOne;
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000547 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
548 return false;
549
550 // Revisit the node.
551 AddToWorkList(Op.Val);
552
553 // Replace the old value with the new one.
554 ++NodesCombined;
555 DOUT << "\nReplacing.2 "; DEBUG(TLO.Old.Val->dump(&DAG));
556 DOUT << "\nWith: "; DEBUG(TLO.New.Val->dump(&DAG));
557 DOUT << '\n';
558
559 // Replace all uses. If any nodes become isomorphic to other nodes and
560 // are deleted, make sure to remove them from our worklist.
561 WorkListRemover DeadNodes(*this);
562 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
563
564 // Push the new node and any (possibly new) users onto the worklist.
565 AddToWorkList(TLO.New.Val);
566 AddUsersToWorkList(TLO.New.Val);
567
568 // Finally, if the node is now dead, remove it from the graph. The node
569 // may not be dead if the replacement process recursively simplified to
570 // something else needing this node.
571 if (TLO.Old.Val->use_empty()) {
572 removeFromWorkList(TLO.Old.Val);
573
574 // If the operands of this node are only used by the node, they will now
575 // be dead. Make sure to visit them first to delete dead nodes early.
576 for (unsigned i = 0, e = TLO.Old.Val->getNumOperands(); i != e; ++i)
577 if (TLO.Old.Val->getOperand(i).Val->hasOneUse())
578 AddToWorkList(TLO.Old.Val->getOperand(i).Val);
579
580 DAG.DeleteNode(TLO.Old.Val);
581 }
582 return true;
583}
584
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000585//===----------------------------------------------------------------------===//
586// Main DAG Combiner implementation
587//===----------------------------------------------------------------------===//
588
589void DAGCombiner::Run(bool RunningAfterLegalize) {
590 // set the instance variable, so that the various visit routines may use it.
591 AfterLegalize = RunningAfterLegalize;
592
593 // Add all the dag nodes to the worklist.
594 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
595 E = DAG.allnodes_end(); I != E; ++I)
596 WorkList.push_back(I);
597
598 // Create a dummy node (which is not added to allnodes), that adds a reference
599 // to the root node, preventing it from being deleted, and tracking any
600 // changes of the root.
601 HandleSDNode Dummy(DAG.getRoot());
602
603 // The root of the dag may dangle to deleted nodes until the dag combiner is
604 // done. Set it to null to avoid confusion.
605 DAG.setRoot(SDOperand());
606
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000607 // while the worklist isn't empty, inspect the node on the end of it and
608 // try and combine it.
609 while (!WorkList.empty()) {
610 SDNode *N = WorkList.back();
611 WorkList.pop_back();
612
613 // If N has no uses, it is dead. Make sure to revisit all N's operands once
614 // N is deleted from the DAG, since they too may now be dead or may have a
615 // reduced number of uses, allowing other xforms.
616 if (N->use_empty() && N != &Dummy) {
617 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
618 AddToWorkList(N->getOperand(i).Val);
619
620 DAG.DeleteNode(N);
621 continue;
622 }
623
Dan Gohman6c89ea72007-10-08 17:57:15 +0000624 SDOperand RV = combine(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000625
Chris Lattner20e53902008-01-25 23:34:24 +0000626 if (RV.Val == 0)
627 continue;
628
629 ++NodesCombined;
Chris Lattner4a7c8452008-01-26 01:09:19 +0000630
Chris Lattner20e53902008-01-25 23:34:24 +0000631 // If we get back the same node we passed in, rather than a new node or
632 // zero, we know that the node must have defined multiple values and
633 // CombineTo was used. Since CombineTo takes care of the worklist
634 // mechanics for us, we have no work to do in this case.
635 if (RV.Val == N)
636 continue;
637
638 assert(N->getOpcode() != ISD::DELETED_NODE &&
639 RV.Val->getOpcode() != ISD::DELETED_NODE &&
640 "Node was deleted but visit returned new node!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000641
Chris Lattner20e53902008-01-25 23:34:24 +0000642 DOUT << "\nReplacing.3 "; DEBUG(N->dump(&DAG));
643 DOUT << "\nWith: "; DEBUG(RV.Val->dump(&DAG));
644 DOUT << '\n';
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000645 WorkListRemover DeadNodes(*this);
Chris Lattner20e53902008-01-25 23:34:24 +0000646 if (N->getNumValues() == RV.Val->getNumValues())
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000647 DAG.ReplaceAllUsesWith(N, RV.Val, &DeadNodes);
Chris Lattner20e53902008-01-25 23:34:24 +0000648 else {
Chris Lattner4a7c8452008-01-26 01:09:19 +0000649 assert(N->getValueType(0) == RV.getValueType() &&
650 N->getNumValues() == 1 && "Type mismatch");
Chris Lattner20e53902008-01-25 23:34:24 +0000651 SDOperand OpV = RV;
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000652 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000653 }
Chris Lattner20e53902008-01-25 23:34:24 +0000654
655 // Push the new node and any users onto the worklist
656 AddToWorkList(RV.Val);
657 AddUsersToWorkList(RV.Val);
658
659 // Add any uses of the old node to the worklist in case this node is the
660 // last one that uses them. They may become dead after this node is
661 // deleted.
662 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
663 AddToWorkList(N->getOperand(i).Val);
664
665 // Nodes can be reintroduced into the worklist. Make sure we do not
666 // process a node that has been replaced.
667 removeFromWorkList(N);
Chris Lattner20e53902008-01-25 23:34:24 +0000668
669 // Finally, since the node is now dead, remove it from the graph.
670 DAG.DeleteNode(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000671 }
672
673 // If the root changed (e.g. it was a dead load, update the root).
674 DAG.setRoot(Dummy.getValue());
675}
676
677SDOperand DAGCombiner::visit(SDNode *N) {
678 switch(N->getOpcode()) {
679 default: break;
680 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattnerf32fa7f2008-02-13 07:25:05 +0000681 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000682 case ISD::ADD: return visitADD(N);
683 case ISD::SUB: return visitSUB(N);
684 case ISD::ADDC: return visitADDC(N);
685 case ISD::ADDE: return visitADDE(N);
686 case ISD::MUL: return visitMUL(N);
687 case ISD::SDIV: return visitSDIV(N);
688 case ISD::UDIV: return visitUDIV(N);
689 case ISD::SREM: return visitSREM(N);
690 case ISD::UREM: return visitUREM(N);
691 case ISD::MULHU: return visitMULHU(N);
692 case ISD::MULHS: return visitMULHS(N);
Dan Gohman6c89ea72007-10-08 17:57:15 +0000693 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
694 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
695 case ISD::SDIVREM: return visitSDIVREM(N);
696 case ISD::UDIVREM: return visitUDIVREM(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000697 case ISD::AND: return visitAND(N);
698 case ISD::OR: return visitOR(N);
699 case ISD::XOR: return visitXOR(N);
700 case ISD::SHL: return visitSHL(N);
701 case ISD::SRA: return visitSRA(N);
702 case ISD::SRL: return visitSRL(N);
703 case ISD::CTLZ: return visitCTLZ(N);
704 case ISD::CTTZ: return visitCTTZ(N);
705 case ISD::CTPOP: return visitCTPOP(N);
706 case ISD::SELECT: return visitSELECT(N);
707 case ISD::SELECT_CC: return visitSELECT_CC(N);
708 case ISD::SETCC: return visitSETCC(N);
709 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
710 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
711 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
712 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
713 case ISD::TRUNCATE: return visitTRUNCATE(N);
714 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
Evan Chengb6290462008-05-12 23:04:07 +0000715 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000716 case ISD::FADD: return visitFADD(N);
717 case ISD::FSUB: return visitFSUB(N);
718 case ISD::FMUL: return visitFMUL(N);
719 case ISD::FDIV: return visitFDIV(N);
720 case ISD::FREM: return visitFREM(N);
721 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
722 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
723 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
724 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
725 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
726 case ISD::FP_ROUND: return visitFP_ROUND(N);
727 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
728 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
729 case ISD::FNEG: return visitFNEG(N);
730 case ISD::FABS: return visitFABS(N);
731 case ISD::BRCOND: return visitBRCOND(N);
732 case ISD::BR_CC: return visitBR_CC(N);
733 case ISD::LOAD: return visitLOAD(N);
734 case ISD::STORE: return visitSTORE(N);
735 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Chengd7ba7ed2007-10-06 08:19:55 +0000736 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000737 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
738 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
739 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
740 }
741 return SDOperand();
742}
743
Dan Gohman6c89ea72007-10-08 17:57:15 +0000744SDOperand DAGCombiner::combine(SDNode *N) {
745
746 SDOperand RV = visit(N);
747
748 // If nothing happened, try a target-specific DAG combine.
749 if (RV.Val == 0) {
750 assert(N->getOpcode() != ISD::DELETED_NODE &&
751 "Node was deleted but visit returned NULL!");
752
753 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
754 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
755
756 // Expose the DAG combiner to the target combiner impls.
757 TargetLowering::DAGCombinerInfo
758 DagCombineInfo(DAG, !AfterLegalize, false, this);
759
760 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
761 }
762 }
763
Evan Chengd1113582008-03-22 01:55:50 +0000764 // If N is a commutative binary node, try commuting it to enable more
765 // sdisel CSE.
766 if (RV.Val == 0 &&
767 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
768 N->getNumValues() == 1) {
769 SDOperand N0 = N->getOperand(0);
770 SDOperand N1 = N->getOperand(1);
771 // Constant operands are canonicalized to RHS.
772 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
773 SDOperand Ops[] = { N1, N0 };
774 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
775 Ops, 2);
Evan Chenge40b51c2008-03-24 23:55:16 +0000776 if (CSENode)
Evan Chengd1113582008-03-22 01:55:50 +0000777 return SDOperand(CSENode, 0);
778 }
779 }
780
Dan Gohman6c89ea72007-10-08 17:57:15 +0000781 return RV;
782}
783
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000784/// getInputChainForNode - Given a node, return its input chain if it has one,
785/// otherwise return a null sd operand.
786static SDOperand getInputChainForNode(SDNode *N) {
787 if (unsigned NumOps = N->getNumOperands()) {
788 if (N->getOperand(0).getValueType() == MVT::Other)
789 return N->getOperand(0);
790 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
791 return N->getOperand(NumOps-1);
792 for (unsigned i = 1; i < NumOps-1; ++i)
793 if (N->getOperand(i).getValueType() == MVT::Other)
794 return N->getOperand(i);
795 }
796 return SDOperand(0, 0);
797}
798
799SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
800 // If N has two operands, where one has an input chain equal to the other,
801 // the 'other' chain is redundant.
802 if (N->getNumOperands() == 2) {
803 if (getInputChainForNode(N->getOperand(0).Val) == N->getOperand(1))
804 return N->getOperand(0);
805 if (getInputChainForNode(N->getOperand(1).Val) == N->getOperand(0))
806 return N->getOperand(1);
807 }
808
809 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
810 SmallVector<SDOperand, 8> Ops; // Ops for replacing token factor.
811 SmallPtrSet<SDNode*, 16> SeenOps;
812 bool Changed = false; // If we should replace this token factor.
813
814 // Start out with this token factor.
815 TFs.push_back(N);
816
817 // Iterate through token factors. The TFs grows when new token factors are
818 // encountered.
819 for (unsigned i = 0; i < TFs.size(); ++i) {
820 SDNode *TF = TFs[i];
821
822 // Check each of the operands.
823 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
824 SDOperand Op = TF->getOperand(i);
825
826 switch (Op.getOpcode()) {
827 case ISD::EntryToken:
828 // Entry tokens don't need to be added to the list. They are
829 // rededundant.
830 Changed = true;
831 break;
832
833 case ISD::TokenFactor:
834 if ((CombinerAA || Op.hasOneUse()) &&
835 std::find(TFs.begin(), TFs.end(), Op.Val) == TFs.end()) {
836 // Queue up for processing.
837 TFs.push_back(Op.Val);
838 // Clean up in case the token factor is removed.
839 AddToWorkList(Op.Val);
840 Changed = true;
841 break;
842 }
843 // Fall thru
844
845 default:
846 // Only add if it isn't already in the list.
847 if (SeenOps.insert(Op.Val))
848 Ops.push_back(Op);
849 else
850 Changed = true;
851 break;
852 }
853 }
854 }
855
856 SDOperand Result;
857
858 // If we've change things around then replace token factor.
859 if (Changed) {
Dan Gohman301f4052008-01-29 13:02:09 +0000860 if (Ops.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000861 // The entry token is the only possible outcome.
862 Result = DAG.getEntryNode();
863 } else {
864 // New and improved token factor.
865 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
866 }
867
868 // Don't add users to work list.
869 return CombineTo(N, Result, false);
870 }
871
872 return Result;
873}
874
Chris Lattnerf32fa7f2008-02-13 07:25:05 +0000875/// MERGE_VALUES can always be eliminated.
876SDOperand DAGCombiner::visitMERGE_VALUES(SDNode *N) {
877 WorkListRemover DeadNodes(*this);
878 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
879 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, i), N->getOperand(i),
880 &DeadNodes);
881 removeFromWorkList(N);
882 DAG.DeleteNode(N);
883 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
884}
885
886
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000887static
888SDOperand combineShlAddConstant(SDOperand N0, SDOperand N1, SelectionDAG &DAG) {
889 MVT::ValueType VT = N0.getValueType();
890 SDOperand N00 = N0.getOperand(0);
891 SDOperand N01 = N0.getOperand(1);
892 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
893 if (N01C && N00.getOpcode() == ISD::ADD && N00.Val->hasOneUse() &&
894 isa<ConstantSDNode>(N00.getOperand(1))) {
895 N0 = DAG.getNode(ISD::ADD, VT,
896 DAG.getNode(ISD::SHL, VT, N00.getOperand(0), N01),
897 DAG.getNode(ISD::SHL, VT, N00.getOperand(1), N01));
898 return DAG.getNode(ISD::ADD, VT, N0, N1);
899 }
900 return SDOperand();
901}
902
903static
904SDOperand combineSelectAndUse(SDNode *N, SDOperand Slct, SDOperand OtherOp,
905 SelectionDAG &DAG) {
906 MVT::ValueType VT = N->getValueType(0);
907 unsigned Opc = N->getOpcode();
908 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
909 SDOperand LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
910 SDOperand RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
911 ISD::CondCode CC = ISD::SETCC_INVALID;
912 if (isSlctCC)
913 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
914 else {
915 SDOperand CCOp = Slct.getOperand(0);
916 if (CCOp.getOpcode() == ISD::SETCC)
917 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
918 }
919
920 bool DoXform = false;
921 bool InvCC = false;
922 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
923 "Bad input!");
924 if (LHS.getOpcode() == ISD::Constant &&
925 cast<ConstantSDNode>(LHS)->isNullValue())
926 DoXform = true;
927 else if (CC != ISD::SETCC_INVALID &&
928 RHS.getOpcode() == ISD::Constant &&
929 cast<ConstantSDNode>(RHS)->isNullValue()) {
930 std::swap(LHS, RHS);
Chris Lattner667f9c12008-01-17 07:20:38 +0000931 SDOperand Op0 = Slct.getOperand(0);
932 bool isInt = MVT::isInteger(isSlctCC ? Op0.getValueType()
933 : Op0.getOperand(0).getValueType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000934 CC = ISD::getSetCCInverse(CC, isInt);
935 DoXform = true;
936 InvCC = true;
937 }
938
939 if (DoXform) {
940 SDOperand Result = DAG.getNode(Opc, VT, OtherOp, RHS);
941 if (isSlctCC)
942 return DAG.getSelectCC(OtherOp, Result,
943 Slct.getOperand(0), Slct.getOperand(1), CC);
944 SDOperand CCOp = Slct.getOperand(0);
945 if (InvCC)
946 CCOp = DAG.getSetCC(CCOp.getValueType(), CCOp.getOperand(0),
947 CCOp.getOperand(1), CC);
948 return DAG.getNode(ISD::SELECT, VT, CCOp, OtherOp, Result);
949 }
950 return SDOperand();
951}
952
953SDOperand DAGCombiner::visitADD(SDNode *N) {
954 SDOperand N0 = N->getOperand(0);
955 SDOperand N1 = N->getOperand(1);
956 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
957 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
958 MVT::ValueType VT = N0.getValueType();
959
960 // fold vector ops
961 if (MVT::isVector(VT)) {
962 SDOperand FoldedVOp = SimplifyVBinOp(N);
963 if (FoldedVOp.Val) return FoldedVOp;
964 }
965
966 // fold (add x, undef) -> undef
967 if (N0.getOpcode() == ISD::UNDEF)
968 return N0;
969 if (N1.getOpcode() == ISD::UNDEF)
970 return N1;
971 // fold (add c1, c2) -> c1+c2
972 if (N0C && N1C)
Dan Gohman9d24dc72008-03-13 22:13:53 +0000973 return DAG.getConstant(N0C->getAPIntValue() + N1C->getAPIntValue(), VT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000974 // canonicalize constant to RHS
975 if (N0C && !N1C)
976 return DAG.getNode(ISD::ADD, VT, N1, N0);
977 // fold (add x, 0) -> x
978 if (N1C && N1C->isNullValue())
979 return N0;
980 // fold ((c1-A)+c2) -> (c1+c2)-A
981 if (N1C && N0.getOpcode() == ISD::SUB)
982 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
983 return DAG.getNode(ISD::SUB, VT,
Dan Gohman9d24dc72008-03-13 22:13:53 +0000984 DAG.getConstant(N1C->getAPIntValue()+
985 N0C->getAPIntValue(), VT),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000986 N0.getOperand(1));
987 // reassociate add
988 SDOperand RADD = ReassociateOps(ISD::ADD, N0, N1);
989 if (RADD.Val != 0)
990 return RADD;
991 // fold ((0-A) + B) -> B-A
992 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
993 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
994 return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
995 // fold (A + (0-B)) -> A-B
996 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
997 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
998 return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
999 // fold (A+(B-A)) -> B
1000 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1001 return N1.getOperand(0);
1002
1003 if (!MVT::isVector(VT) && SimplifyDemandedBits(SDOperand(N, 0)))
1004 return SDOperand(N, 0);
1005
1006 // fold (a+b) -> (a|b) iff a and b share no bits.
1007 if (MVT::isInteger(VT) && !MVT::isVector(VT)) {
Dan Gohmanbea075f2008-02-20 16:33:30 +00001008 APInt LHSZero, LHSOne;
1009 APInt RHSZero, RHSOne;
1010 APInt Mask = APInt::getAllOnesValue(MVT::getSizeInBits(VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001011 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
Dan Gohmanbea075f2008-02-20 16:33:30 +00001012 if (LHSZero.getBoolValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001013 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1014
1015 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1016 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1017 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1018 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1019 return DAG.getNode(ISD::OR, VT, N0, N1);
1020 }
1021 }
1022
1023 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1024 if (N0.getOpcode() == ISD::SHL && N0.Val->hasOneUse()) {
1025 SDOperand Result = combineShlAddConstant(N0, N1, DAG);
1026 if (Result.Val) return Result;
1027 }
1028 if (N1.getOpcode() == ISD::SHL && N1.Val->hasOneUse()) {
1029 SDOperand Result = combineShlAddConstant(N1, N0, DAG);
1030 if (Result.Val) return Result;
1031 }
1032
1033 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
1034 if (N0.getOpcode() == ISD::SELECT && N0.Val->hasOneUse()) {
1035 SDOperand Result = combineSelectAndUse(N, N0, N1, DAG);
1036 if (Result.Val) return Result;
1037 }
1038 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1039 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1040 if (Result.Val) return Result;
1041 }
1042
1043 return SDOperand();
1044}
1045
1046SDOperand DAGCombiner::visitADDC(SDNode *N) {
1047 SDOperand N0 = N->getOperand(0);
1048 SDOperand N1 = N->getOperand(1);
1049 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1050 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1051 MVT::ValueType VT = N0.getValueType();
1052
1053 // If the flag result is dead, turn this into an ADD.
1054 if (N->hasNUsesOfValue(0, 1))
1055 return CombineTo(N, DAG.getNode(ISD::ADD, VT, N1, N0),
1056 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1057
1058 // canonicalize constant to RHS.
1059 if (N0C && !N1C) {
1060 SDOperand Ops[] = { N1, N0 };
1061 return DAG.getNode(ISD::ADDC, N->getVTList(), Ops, 2);
1062 }
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;
1071 APInt Mask = APInt::getAllOnesValue(MVT::getSizeInBits(VT));
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);
1093 //MVT::ValueType VT = N0.getValueType();
1094
1095 // canonicalize constant to RHS
1096 if (N0C && !N1C) {
1097 SDOperand Ops[] = { N1, N0, CarryIn };
1098 return DAG.getNode(ISD::ADDE, N->getVTList(), Ops, 3);
1099 }
1100
1101 // fold (adde x, y, false) -> (addc x, y)
1102 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) {
1103 SDOperand Ops[] = { N1, N0 };
1104 return DAG.getNode(ISD::ADDC, N->getVTList(), Ops, 2);
1105 }
1106
1107 return SDOperand();
1108}
1109
1110
1111
1112SDOperand DAGCombiner::visitSUB(SDNode *N) {
1113 SDOperand N0 = N->getOperand(0);
1114 SDOperand N1 = N->getOperand(1);
1115 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1116 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1117 MVT::ValueType VT = N0.getValueType();
1118
1119 // fold vector ops
1120 if (MVT::isVector(VT)) {
1121 SDOperand FoldedVOp = SimplifyVBinOp(N);
1122 if (FoldedVOp.Val) return FoldedVOp;
1123 }
1124
1125 // fold (sub x, x) -> 0
Evan Chenga15896e2008-03-12 07:02:50 +00001126 if (N0 == N1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001127 return DAG.getConstant(0, N->getValueType(0));
1128 // fold (sub c1, c2) -> c1-c2
1129 if (N0C && N1C)
1130 return DAG.getNode(ISD::SUB, VT, N0, N1);
1131 // fold (sub x, c) -> (add x, -c)
1132 if (N1C)
Dan Gohman9d24dc72008-03-13 22:13:53 +00001133 return DAG.getNode(ISD::ADD, VT, N0,
1134 DAG.getConstant(-N1C->getAPIntValue(), VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001135 // fold (A+B)-A -> B
1136 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1137 return N0.getOperand(1);
1138 // fold (A+B)-B -> A
1139 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1140 return N0.getOperand(0);
1141 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
1142 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1143 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1144 if (Result.Val) return Result;
1145 }
1146 // If either operand of a sub is undef, the result is undef
1147 if (N0.getOpcode() == ISD::UNDEF)
1148 return N0;
1149 if (N1.getOpcode() == ISD::UNDEF)
1150 return N1;
1151
1152 return SDOperand();
1153}
1154
1155SDOperand DAGCombiner::visitMUL(SDNode *N) {
1156 SDOperand N0 = N->getOperand(0);
1157 SDOperand N1 = N->getOperand(1);
1158 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1159 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1160 MVT::ValueType VT = N0.getValueType();
1161
1162 // fold vector ops
1163 if (MVT::isVector(VT)) {
1164 SDOperand FoldedVOp = SimplifyVBinOp(N);
1165 if (FoldedVOp.Val) return FoldedVOp;
1166 }
1167
1168 // fold (mul x, undef) -> 0
1169 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1170 return DAG.getConstant(0, VT);
1171 // fold (mul c1, c2) -> c1*c2
1172 if (N0C && N1C)
1173 return DAG.getNode(ISD::MUL, VT, N0, N1);
1174 // canonicalize constant to RHS
1175 if (N0C && !N1C)
1176 return DAG.getNode(ISD::MUL, VT, N1, N0);
1177 // fold (mul x, 0) -> 0
1178 if (N1C && N1C->isNullValue())
1179 return N1;
1180 // fold (mul x, -1) -> 0-x
1181 if (N1C && N1C->isAllOnesValue())
1182 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1183 // fold (mul x, (1 << c)) -> x << c
Dan Gohman9d24dc72008-03-13 22:13:53 +00001184 if (N1C && N1C->getAPIntValue().isPowerOf2())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001185 return DAG.getNode(ISD::SHL, VT, N0,
Dan Gohman9d24dc72008-03-13 22:13:53 +00001186 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001187 TLI.getShiftAmountTy()));
1188 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1189 if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
1190 // FIXME: If the input is something that is easily negated (e.g. a
1191 // single-use add), we should put the negate there.
1192 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
1193 DAG.getNode(ISD::SHL, VT, N0,
1194 DAG.getConstant(Log2_64(-N1C->getSignExtended()),
1195 TLI.getShiftAmountTy())));
1196 }
1197
1198 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1199 if (N1C && N0.getOpcode() == ISD::SHL &&
1200 isa<ConstantSDNode>(N0.getOperand(1))) {
1201 SDOperand C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
1202 AddToWorkList(C3.Val);
1203 return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
1204 }
1205
1206 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1207 // use.
1208 {
1209 SDOperand Sh(0,0), Y(0,0);
1210 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1211 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1212 N0.Val->hasOneUse()) {
1213 Sh = N0; Y = N1;
1214 } else if (N1.getOpcode() == ISD::SHL &&
1215 isa<ConstantSDNode>(N1.getOperand(1)) && N1.Val->hasOneUse()) {
1216 Sh = N1; Y = N0;
1217 }
1218 if (Sh.Val) {
1219 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
1220 return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
1221 }
1222 }
1223 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1224 if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
1225 isa<ConstantSDNode>(N0.getOperand(1))) {
1226 return DAG.getNode(ISD::ADD, VT,
1227 DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
1228 DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
1229 }
1230
1231 // reassociate mul
1232 SDOperand RMUL = ReassociateOps(ISD::MUL, N0, N1);
1233 if (RMUL.Val != 0)
1234 return RMUL;
1235
1236 return SDOperand();
1237}
1238
1239SDOperand DAGCombiner::visitSDIV(SDNode *N) {
1240 SDOperand N0 = N->getOperand(0);
1241 SDOperand N1 = N->getOperand(1);
1242 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1243 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1244 MVT::ValueType VT = N->getValueType(0);
1245
1246 // fold vector ops
1247 if (MVT::isVector(VT)) {
1248 SDOperand FoldedVOp = SimplifyVBinOp(N);
1249 if (FoldedVOp.Val) return FoldedVOp;
1250 }
1251
1252 // fold (sdiv c1, c2) -> c1/c2
1253 if (N0C && N1C && !N1C->isNullValue())
1254 return DAG.getNode(ISD::SDIV, VT, N0, N1);
1255 // fold (sdiv X, 1) -> X
1256 if (N1C && N1C->getSignExtended() == 1LL)
1257 return N0;
1258 // fold (sdiv X, -1) -> 0-X
1259 if (N1C && N1C->isAllOnesValue())
1260 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1261 // If we know the sign bits of both operands are zero, strength reduce to a
1262 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Chris Lattner336672f2008-01-27 23:32:17 +00001263 if (!MVT::isVector(VT)) {
Dan Gohman07961cd2008-02-25 21:11:39 +00001264 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Chris Lattner336672f2008-01-27 23:32:17 +00001265 return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
1266 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001267 // fold (sdiv X, pow2) -> simple ops after legalize
Dan Gohman9d24dc72008-03-13 22:13:53 +00001268 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001269 (isPowerOf2_64(N1C->getSignExtended()) ||
1270 isPowerOf2_64(-N1C->getSignExtended()))) {
1271 // If dividing by powers of two is cheap, then don't perform the following
1272 // fold.
1273 if (TLI.isPow2DivCheap())
1274 return SDOperand();
1275 int64_t pow2 = N1C->getSignExtended();
1276 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1277 unsigned lg2 = Log2_64(abs2);
1278 // Splat the sign bit into the register
1279 SDOperand SGN = DAG.getNode(ISD::SRA, VT, N0,
1280 DAG.getConstant(MVT::getSizeInBits(VT)-1,
1281 TLI.getShiftAmountTy()));
1282 AddToWorkList(SGN.Val);
1283 // Add (N0 < 0) ? abs2 - 1 : 0;
1284 SDOperand SRL = DAG.getNode(ISD::SRL, VT, SGN,
1285 DAG.getConstant(MVT::getSizeInBits(VT)-lg2,
1286 TLI.getShiftAmountTy()));
1287 SDOperand ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
1288 AddToWorkList(SRL.Val);
1289 AddToWorkList(ADD.Val); // Divide by pow2
1290 SDOperand SRA = DAG.getNode(ISD::SRA, VT, ADD,
1291 DAG.getConstant(lg2, TLI.getShiftAmountTy()));
1292 // If we're dividing by a positive value, we're done. Otherwise, we must
1293 // negate the result.
1294 if (pow2 > 0)
1295 return SRA;
1296 AddToWorkList(SRA.Val);
1297 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
1298 }
1299 // if integer divide is expensive and we satisfy the requirements, emit an
1300 // alternate sequence.
1301 if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) &&
1302 !TLI.isIntDivCheap()) {
1303 SDOperand Op = BuildSDIV(N);
1304 if (Op.Val) return Op;
1305 }
1306
1307 // undef / X -> 0
1308 if (N0.getOpcode() == ISD::UNDEF)
1309 return DAG.getConstant(0, VT);
1310 // X / undef -> undef
1311 if (N1.getOpcode() == ISD::UNDEF)
1312 return N1;
1313
1314 return SDOperand();
1315}
1316
1317SDOperand DAGCombiner::visitUDIV(SDNode *N) {
1318 SDOperand N0 = N->getOperand(0);
1319 SDOperand N1 = N->getOperand(1);
1320 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1321 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1322 MVT::ValueType VT = N->getValueType(0);
1323
1324 // fold vector ops
1325 if (MVT::isVector(VT)) {
1326 SDOperand FoldedVOp = SimplifyVBinOp(N);
1327 if (FoldedVOp.Val) return FoldedVOp;
1328 }
1329
1330 // fold (udiv c1, c2) -> c1/c2
1331 if (N0C && N1C && !N1C->isNullValue())
1332 return DAG.getNode(ISD::UDIV, VT, N0, N1);
1333 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohman9d24dc72008-03-13 22:13:53 +00001334 if (N1C && N1C->getAPIntValue().isPowerOf2())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001335 return DAG.getNode(ISD::SRL, VT, N0,
Dan Gohman9d24dc72008-03-13 22:13:53 +00001336 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001337 TLI.getShiftAmountTy()));
1338 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1339 if (N1.getOpcode() == ISD::SHL) {
1340 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohman9d24dc72008-03-13 22:13:53 +00001341 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001342 MVT::ValueType ADDVT = N1.getOperand(1).getValueType();
1343 SDOperand Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
Dan Gohman9d24dc72008-03-13 22:13:53 +00001344 DAG.getConstant(SHC->getAPIntValue()
1345 .logBase2(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001346 ADDVT));
1347 AddToWorkList(Add.Val);
1348 return DAG.getNode(ISD::SRL, VT, N0, Add);
1349 }
1350 }
1351 }
1352 // fold (udiv x, c) -> alternate
Dan Gohman9d24dc72008-03-13 22:13:53 +00001353 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001354 SDOperand Op = BuildUDIV(N);
1355 if (Op.Val) return Op;
1356 }
1357
1358 // undef / X -> 0
1359 if (N0.getOpcode() == ISD::UNDEF)
1360 return DAG.getConstant(0, VT);
1361 // X / undef -> undef
1362 if (N1.getOpcode() == ISD::UNDEF)
1363 return N1;
1364
1365 return SDOperand();
1366}
1367
1368SDOperand DAGCombiner::visitSREM(SDNode *N) {
1369 SDOperand N0 = N->getOperand(0);
1370 SDOperand N1 = N->getOperand(1);
1371 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1372 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1373 MVT::ValueType VT = N->getValueType(0);
1374
1375 // fold (srem c1, c2) -> c1%c2
1376 if (N0C && N1C && !N1C->isNullValue())
1377 return DAG.getNode(ISD::SREM, VT, N0, N1);
1378 // If we know the sign bits of both operands are zero, strength reduce to a
1379 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Chris Lattnerce602f52008-01-27 23:21:58 +00001380 if (!MVT::isVector(VT)) {
Dan Gohman07961cd2008-02-25 21:11:39 +00001381 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Chris Lattnerce602f52008-01-27 23:21:58 +00001382 return DAG.getNode(ISD::UREM, VT, N0, N1);
1383 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001384
Dan Gohmanfdb31f12007-11-26 23:46:11 +00001385 // If X/C can be simplified by the division-by-constant logic, lower
1386 // X%C to the equivalent of X-X/C*C.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001387 if (N1C && !N1C->isNullValue()) {
1388 SDOperand Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
Chris Lattner4a7c8452008-01-26 01:09:19 +00001389 AddToWorkList(Div.Val);
Dan Gohmanfdb31f12007-11-26 23:46:11 +00001390 SDOperand OptimizedDiv = combine(Div.Val);
1391 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1392 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1393 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1394 AddToWorkList(Mul.Val);
1395 return Sub;
1396 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001397 }
1398
1399 // undef % X -> 0
1400 if (N0.getOpcode() == ISD::UNDEF)
1401 return DAG.getConstant(0, VT);
1402 // X % undef -> undef
1403 if (N1.getOpcode() == ISD::UNDEF)
1404 return N1;
1405
1406 return SDOperand();
1407}
1408
1409SDOperand DAGCombiner::visitUREM(SDNode *N) {
1410 SDOperand N0 = N->getOperand(0);
1411 SDOperand N1 = N->getOperand(1);
1412 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1413 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1414 MVT::ValueType VT = N->getValueType(0);
1415
1416 // fold (urem c1, c2) -> c1%c2
1417 if (N0C && N1C && !N1C->isNullValue())
1418 return DAG.getNode(ISD::UREM, VT, N0, N1);
1419 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohman9d24dc72008-03-13 22:13:53 +00001420 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1421 return DAG.getNode(ISD::AND, VT, N0,
1422 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001423 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1424 if (N1.getOpcode() == ISD::SHL) {
1425 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohman9d24dc72008-03-13 22:13:53 +00001426 if (SHC->getAPIntValue().isPowerOf2()) {
1427 SDOperand Add =
1428 DAG.getNode(ISD::ADD, VT, N1,
1429 DAG.getConstant(APInt::getAllOnesValue(MVT::getSizeInBits(VT)),
1430 VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001431 AddToWorkList(Add.Val);
1432 return DAG.getNode(ISD::AND, VT, N0, Add);
1433 }
1434 }
1435 }
1436
Dan Gohmanfdb31f12007-11-26 23:46:11 +00001437 // If X/C can be simplified by the division-by-constant logic, lower
1438 // X%C to the equivalent of X-X/C*C.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001439 if (N1C && !N1C->isNullValue()) {
1440 SDOperand Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
Dan Gohmanfdb31f12007-11-26 23:46:11 +00001441 SDOperand OptimizedDiv = combine(Div.Val);
1442 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1443 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1444 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1445 AddToWorkList(Mul.Val);
1446 return Sub;
1447 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001448 }
1449
1450 // undef % X -> 0
1451 if (N0.getOpcode() == ISD::UNDEF)
1452 return DAG.getConstant(0, VT);
1453 // X % undef -> undef
1454 if (N1.getOpcode() == ISD::UNDEF)
1455 return N1;
1456
1457 return SDOperand();
1458}
1459
1460SDOperand DAGCombiner::visitMULHS(SDNode *N) {
1461 SDOperand N0 = N->getOperand(0);
1462 SDOperand N1 = N->getOperand(1);
1463 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1464 MVT::ValueType VT = N->getValueType(0);
1465
1466 // fold (mulhs x, 0) -> 0
1467 if (N1C && N1C->isNullValue())
1468 return N1;
1469 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohman9d24dc72008-03-13 22:13:53 +00001470 if (N1C && N1C->getAPIntValue() == 1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001471 return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
1472 DAG.getConstant(MVT::getSizeInBits(N0.getValueType())-1,
1473 TLI.getShiftAmountTy()));
1474 // fold (mulhs x, undef) -> 0
1475 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1476 return DAG.getConstant(0, VT);
1477
1478 return SDOperand();
1479}
1480
1481SDOperand DAGCombiner::visitMULHU(SDNode *N) {
1482 SDOperand N0 = N->getOperand(0);
1483 SDOperand N1 = N->getOperand(1);
1484 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1485 MVT::ValueType VT = N->getValueType(0);
1486
1487 // fold (mulhu x, 0) -> 0
1488 if (N1C && N1C->isNullValue())
1489 return N1;
1490 // fold (mulhu x, 1) -> 0
Dan Gohman9d24dc72008-03-13 22:13:53 +00001491 if (N1C && N1C->getAPIntValue() == 1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001492 return DAG.getConstant(0, N0.getValueType());
1493 // fold (mulhu x, undef) -> 0
1494 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1495 return DAG.getConstant(0, VT);
1496
1497 return SDOperand();
1498}
1499
Dan Gohman6c89ea72007-10-08 17:57:15 +00001500/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1501/// compute two values. LoOp and HiOp give the opcodes for the two computations
1502/// that are being performed. Return true if a simplification was made.
1503///
Chris Lattner4a7c8452008-01-26 01:09:19 +00001504SDOperand DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1505 unsigned HiOp) {
Dan Gohman6c89ea72007-10-08 17:57:15 +00001506 // If the high half is not needed, just compute the low half.
Evan Chengddfa8c72007-11-08 09:25:29 +00001507 bool HiExists = N->hasAnyUseOfValue(1);
1508 if (!HiExists &&
Dan Gohman6c89ea72007-10-08 17:57:15 +00001509 (!AfterLegalize ||
1510 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
Chris Lattner4a7c8452008-01-26 01:09:19 +00001511 SDOperand Res = DAG.getNode(LoOp, N->getValueType(0), N->op_begin(),
1512 N->getNumOperands());
1513 return CombineTo(N, Res, Res);
Dan Gohman6c89ea72007-10-08 17:57:15 +00001514 }
1515
1516 // If the low half is not needed, just compute the high half.
Evan Chengddfa8c72007-11-08 09:25:29 +00001517 bool LoExists = N->hasAnyUseOfValue(0);
1518 if (!LoExists &&
Dan Gohman6c89ea72007-10-08 17:57:15 +00001519 (!AfterLegalize ||
1520 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Chris Lattner4a7c8452008-01-26 01:09:19 +00001521 SDOperand Res = DAG.getNode(HiOp, N->getValueType(1), N->op_begin(),
1522 N->getNumOperands());
1523 return CombineTo(N, Res, Res);
Dan Gohman6c89ea72007-10-08 17:57:15 +00001524 }
1525
Evan Chengddfa8c72007-11-08 09:25:29 +00001526 // If both halves are used, return as it is.
1527 if (LoExists && HiExists)
Chris Lattner4a7c8452008-01-26 01:09:19 +00001528 return SDOperand();
Evan Chengddfa8c72007-11-08 09:25:29 +00001529
1530 // If the two computed results can be simplified separately, separate them.
Evan Chengddfa8c72007-11-08 09:25:29 +00001531 if (LoExists) {
1532 SDOperand Lo = DAG.getNode(LoOp, N->getValueType(0),
1533 N->op_begin(), N->getNumOperands());
Chris Lattner4a7c8452008-01-26 01:09:19 +00001534 AddToWorkList(Lo.Val);
Evan Chengddfa8c72007-11-08 09:25:29 +00001535 SDOperand LoOpt = combine(Lo.Val);
Chris Lattner4a7c8452008-01-26 01:09:19 +00001536 if (LoOpt.Val && LoOpt.Val != Lo.Val &&
1537 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))
1538 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman6c89ea72007-10-08 17:57:15 +00001539 }
1540
Evan Chengddfa8c72007-11-08 09:25:29 +00001541 if (HiExists) {
1542 SDOperand Hi = DAG.getNode(HiOp, N->getValueType(1),
1543 N->op_begin(), N->getNumOperands());
Chris Lattner4a7c8452008-01-26 01:09:19 +00001544 AddToWorkList(Hi.Val);
Evan Chengddfa8c72007-11-08 09:25:29 +00001545 SDOperand HiOpt = combine(Hi.Val);
1546 if (HiOpt.Val && HiOpt != Hi &&
Chris Lattner4a7c8452008-01-26 01:09:19 +00001547 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))
1548 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);
1585 MVT::ValueType VT = N0.getValueType();
1586 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);
1626 MVT::ValueType VT = N1.getValueType();
Dan Gohman07961cd2008-02-25 21:11:39 +00001627 unsigned BitWidth = MVT::getSizeInBits(VT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001628
1629 // fold vector ops
1630 if (MVT::isVector(VT)) {
1631 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 &&
1685 MVT::isInteger(LL.getValueType())) {
1686 // 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) {
1711 bool isInteger = MVT::isInteger(LL.getValueType());
1712 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.
1726 if (!MVT::isVector(VT) &&
1727 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);
Dan Gohman9a4c92c2008-01-30 00:15:11 +00001732 MVT::ValueType 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,
1737 BitWidth - MVT::getSizeInBits(EVT))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001738 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1739 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1740 LN0->getBasePtr(), LN0->getSrcValue(),
1741 LN0->getSrcValueOffset(), EVT,
1742 LN0->isVolatile(),
1743 LN0->getAlignment());
1744 AddToWorkList(N);
1745 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1746 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1747 }
1748 }
1749 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1750 if (ISD::isSEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
1751 N0.hasOneUse()) {
1752 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman9a4c92c2008-01-30 00:15:11 +00001753 MVT::ValueType EVT = LN0->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001754 // If we zero all the possible extended bits, then we can turn this into
1755 // a zextload if we are running before legalize or the operation is legal.
Dan Gohman07961cd2008-02-25 21:11:39 +00001756 unsigned BitWidth = N1.getValueSizeInBits();
1757 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1758 BitWidth - MVT::getSizeInBits(EVT))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001759 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1760 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1761 LN0->getBasePtr(), LN0->getSrcValue(),
1762 LN0->getSrcValueOffset(), EVT,
1763 LN0->isVolatile(),
1764 LN0->getAlignment());
1765 AddToWorkList(N);
1766 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1767 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1768 }
1769 }
1770
1771 // fold (and (load x), 255) -> (zextload x, i8)
1772 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1773 if (N1C && N0.getOpcode() == ISD::LOAD) {
1774 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1775 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Chris Lattner3bc08502008-01-17 19:59:44 +00001776 LN0->isUnindexed() && N0.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001777 MVT::ValueType EVT, LoadedVT;
Dan Gohman9d24dc72008-03-13 22:13:53 +00001778 if (N1C->getAPIntValue() == 255)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001779 EVT = MVT::i8;
Dan Gohman9d24dc72008-03-13 22:13:53 +00001780 else if (N1C->getAPIntValue() == 65535)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001781 EVT = MVT::i16;
Dan Gohman9d24dc72008-03-13 22:13:53 +00001782 else if (N1C->getAPIntValue() == ~0U)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001783 EVT = MVT::i32;
1784 else
1785 EVT = MVT::Other;
1786
Dan Gohman9a4c92c2008-01-30 00:15:11 +00001787 LoadedVT = LN0->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001788 if (EVT != MVT::Other && LoadedVT > EVT &&
1789 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1790 MVT::ValueType PtrType = N0.getOperand(1).getValueType();
1791 // For big endian targets, we need to add an offset to the pointer to
1792 // load the correct bytes. For little endian systems, we merely need to
1793 // read fewer bytes from the same pointer.
Duncan Sands4f18d4f2007-11-09 08:57:19 +00001794 unsigned LVTStoreBytes = MVT::getStoreSizeInBits(LoadedVT)/8;
1795 unsigned EVTStoreBytes = MVT::getStoreSizeInBits(EVT)/8;
1796 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Duncan Sandsa3691432007-10-28 12:59:45 +00001797 unsigned Alignment = LN0->getAlignment();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001798 SDOperand NewPtr = LN0->getBasePtr();
Duncan Sands9ff8fbf2008-02-11 10:37:04 +00001799 if (TLI.isBigEndian()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001800 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1801 DAG.getConstant(PtrOff, PtrType));
Duncan Sandsa3691432007-10-28 12:59:45 +00001802 Alignment = MinAlign(Alignment, PtrOff);
1803 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001804 AddToWorkList(NewPtr.Val);
1805 SDOperand Load =
1806 DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
1807 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
Duncan Sandsa3691432007-10-28 12:59:45 +00001808 LN0->isVolatile(), Alignment);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001809 AddToWorkList(N);
1810 CombineTo(N0.Val, Load, Load.getValue(1));
1811 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1812 }
1813 }
1814 }
1815
1816 return SDOperand();
1817}
1818
1819SDOperand DAGCombiner::visitOR(SDNode *N) {
1820 SDOperand N0 = N->getOperand(0);
1821 SDOperand N1 = N->getOperand(1);
1822 SDOperand LL, LR, RL, RR, CC0, CC1;
1823 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1824 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1825 MVT::ValueType VT = N1.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001826
1827 // fold vector ops
1828 if (MVT::isVector(VT)) {
1829 SDOperand FoldedVOp = SimplifyVBinOp(N);
1830 if (FoldedVOp.Val) return FoldedVOp;
1831 }
1832
1833 // fold (or x, undef) -> -1
1834 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1835 return DAG.getConstant(~0ULL, VT);
1836 // fold (or c1, c2) -> c1|c2
1837 if (N0C && N1C)
1838 return DAG.getNode(ISD::OR, VT, N0, N1);
1839 // canonicalize constant to RHS
1840 if (N0C && !N1C)
1841 return DAG.getNode(ISD::OR, VT, N1, N0);
1842 // fold (or x, 0) -> x
1843 if (N1C && N1C->isNullValue())
1844 return N0;
1845 // fold (or x, -1) -> -1
1846 if (N1C && N1C->isAllOnesValue())
1847 return N1;
1848 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman07961cd2008-02-25 21:11:39 +00001849 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001850 return N1;
1851 // reassociate or
1852 SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
1853 if (ROR.Val != 0)
1854 return ROR;
1855 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1856 if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1857 isa<ConstantSDNode>(N0.getOperand(1))) {
1858 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1859 return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1860 N1),
Dan Gohman9d24dc72008-03-13 22:13:53 +00001861 DAG.getConstant(N1C->getAPIntValue() |
1862 C1->getAPIntValue(), VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001863 }
1864 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1865 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1866 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1867 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1868
1869 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1870 MVT::isInteger(LL.getValueType())) {
1871 // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1872 // fold (X < 0) | (Y < 0) -> (X|Y < 0)
Dan Gohman9d24dc72008-03-13 22:13:53 +00001873 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001874 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1875 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1876 AddToWorkList(ORNode.Val);
1877 return DAG.getSetCC(VT, ORNode, LR, Op1);
1878 }
1879 // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1880 // fold (X > -1) | (Y > -1) -> (X&Y > -1)
1881 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1882 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1883 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1884 AddToWorkList(ANDNode.Val);
1885 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1886 }
1887 }
1888 // canonicalize equivalent to ll == rl
1889 if (LL == RR && LR == RL) {
1890 Op1 = ISD::getSetCCSwappedOperands(Op1);
1891 std::swap(RL, RR);
1892 }
1893 if (LL == RL && LR == RR) {
1894 bool isInteger = MVT::isInteger(LL.getValueType());
1895 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1896 if (Result != ISD::SETCC_INVALID)
1897 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1898 }
1899 }
1900
1901 // Simplify: or (op x...), (op y...) -> (op (or x, y))
1902 if (N0.getOpcode() == N1.getOpcode()) {
1903 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1904 if (Tmp.Val) return Tmp;
1905 }
1906
1907 // (X & C1) | (Y & C2) -> (X|Y) & C3 if possible.
1908 if (N0.getOpcode() == ISD::AND &&
1909 N1.getOpcode() == ISD::AND &&
1910 N0.getOperand(1).getOpcode() == ISD::Constant &&
1911 N1.getOperand(1).getOpcode() == ISD::Constant &&
1912 // Don't increase # computations.
1913 (N0.Val->hasOneUse() || N1.Val->hasOneUse())) {
1914 // We can only do this xform if we know that bits from X that are set in C2
1915 // but not in C1 are already zero. Likewise for Y.
Dan Gohman07961cd2008-02-25 21:11:39 +00001916 const APInt &LHSMask =
1917 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1918 const APInt &RHSMask =
1919 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001920
1921 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
1922 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
1923 SDOperand X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
1924 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
1925 }
1926 }
1927
1928
1929 // See if this is some rotate idiom.
1930 if (SDNode *Rot = MatchRotate(N0, N1))
1931 return SDOperand(Rot, 0);
1932
1933 return SDOperand();
1934}
1935
1936
1937/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
1938static bool MatchRotateHalf(SDOperand Op, SDOperand &Shift, SDOperand &Mask) {
1939 if (Op.getOpcode() == ISD::AND) {
1940 if (isa<ConstantSDNode>(Op.getOperand(1))) {
1941 Mask = Op.getOperand(1);
1942 Op = Op.getOperand(0);
1943 } else {
1944 return false;
1945 }
1946 }
1947
1948 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
1949 Shift = Op;
1950 return true;
1951 }
1952 return false;
1953}
1954
1955
1956// MatchRotate - Handle an 'or' of two operands. If this is one of the many
1957// idioms for rotate, and if the target supports rotation instructions, generate
1958// a rot[lr].
1959SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
1960 // Must be a legal type. Expanded an promoted things won't work with rotates.
1961 MVT::ValueType VT = LHS.getValueType();
1962 if (!TLI.isTypeLegal(VT)) return 0;
1963
1964 // The target must have at least one rotate flavor.
1965 bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
1966 bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
1967 if (!HasROTL && !HasROTR) return 0;
1968
1969 // Match "(X shl/srl V1) & V2" where V2 may not be present.
1970 SDOperand LHSShift; // The shift.
1971 SDOperand LHSMask; // AND value if any.
1972 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
1973 return 0; // Not part of a rotate.
1974
1975 SDOperand RHSShift; // The shift.
1976 SDOperand RHSMask; // AND value if any.
1977 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
1978 return 0; // Not part of a rotate.
1979
1980 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
1981 return 0; // Not shifting the same value.
1982
1983 if (LHSShift.getOpcode() == RHSShift.getOpcode())
1984 return 0; // Shifts must disagree.
1985
1986 // Canonicalize shl to left side in a shl/srl pair.
1987 if (RHSShift.getOpcode() == ISD::SHL) {
1988 std::swap(LHS, RHS);
1989 std::swap(LHSShift, RHSShift);
1990 std::swap(LHSMask , RHSMask );
1991 }
1992
1993 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1994 SDOperand LHSShiftArg = LHSShift.getOperand(0);
1995 SDOperand LHSShiftAmt = LHSShift.getOperand(1);
1996 SDOperand RHSShiftAmt = RHSShift.getOperand(1);
1997
1998 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
1999 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
2000 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2001 RHSShiftAmt.getOpcode() == ISD::Constant) {
2002 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getValue();
2003 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getValue();
2004 if ((LShVal + RShVal) != OpSizeInBits)
2005 return 0;
2006
2007 SDOperand Rot;
2008 if (HasROTL)
2009 Rot = DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt);
2010 else
2011 Rot = DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt);
2012
2013 // If there is an AND of either shifted operand, apply it to the result.
2014 if (LHSMask.Val || RHSMask.Val) {
Dan Gohmand047c3e2008-03-03 23:51:38 +00002015 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002016
2017 if (LHSMask.Val) {
Dan Gohmand047c3e2008-03-03 23:51:38 +00002018 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2019 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002020 }
2021 if (RHSMask.Val) {
Dan Gohmand047c3e2008-03-03 23:51:38 +00002022 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2023 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002024 }
2025
2026 Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
2027 }
2028
2029 return Rot.Val;
2030 }
2031
2032 // If there is a mask here, and we have a variable shift, we can't be sure
2033 // that we're masking out the right stuff.
2034 if (LHSMask.Val || RHSMask.Val)
2035 return 0;
2036
2037 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2038 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2039 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2040 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2041 if (ConstantSDNode *SUBC =
2042 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
Dan Gohman9d24dc72008-03-13 22:13:53 +00002043 if (SUBC->getAPIntValue() == OpSizeInBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002044 if (HasROTL)
2045 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2046 else
2047 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
Anton Korobeynikov53422f62008-02-20 11:10:28 +00002048 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002049 }
2050 }
2051
2052 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2053 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2054 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2055 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2056 if (ConstantSDNode *SUBC =
2057 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
Dan Gohman9d24dc72008-03-13 22:13:53 +00002058 if (SUBC->getAPIntValue() == OpSizeInBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002059 if (HasROTL)
2060 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2061 else
2062 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
Anton Korobeynikov53422f62008-02-20 11:10:28 +00002063 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002064 }
2065 }
2066
2067 // Look for sign/zext/any-extended cases:
2068 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2069 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2070 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND) &&
2071 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2072 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2073 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND)) {
2074 SDOperand LExtOp0 = LHSShiftAmt.getOperand(0);
2075 SDOperand RExtOp0 = RHSShiftAmt.getOperand(0);
2076 if (RExtOp0.getOpcode() == ISD::SUB &&
2077 RExtOp0.getOperand(1) == LExtOp0) {
2078 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2079 // (rotr x, y)
2080 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2081 // (rotl x, (sub 32, y))
2082 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
Dan Gohman9d24dc72008-03-13 22:13:53 +00002083 if (SUBC->getAPIntValue() == OpSizeInBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002084 if (HasROTL)
2085 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2086 else
2087 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2088 }
2089 }
2090 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2091 RExtOp0 == LExtOp0.getOperand(1)) {
2092 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2093 // (rotl x, y)
2094 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2095 // (rotr x, (sub 32, y))
2096 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
Dan Gohman9d24dc72008-03-13 22:13:53 +00002097 if (SUBC->getAPIntValue() == OpSizeInBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002098 if (HasROTL)
2099 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, RHSShiftAmt).Val;
2100 else
2101 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2102 }
2103 }
2104 }
2105 }
2106
2107 return 0;
2108}
2109
2110
2111SDOperand DAGCombiner::visitXOR(SDNode *N) {
2112 SDOperand N0 = N->getOperand(0);
2113 SDOperand N1 = N->getOperand(1);
2114 SDOperand LHS, RHS, CC;
2115 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2116 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2117 MVT::ValueType VT = N0.getValueType();
2118
2119 // fold vector ops
2120 if (MVT::isVector(VT)) {
2121 SDOperand FoldedVOp = SimplifyVBinOp(N);
2122 if (FoldedVOp.Val) return FoldedVOp;
2123 }
2124
Evan Cheng5d00cb42008-03-25 20:08:07 +00002125 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2126 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2127 return DAG.getConstant(0, VT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002128 // fold (xor x, undef) -> undef
2129 if (N0.getOpcode() == ISD::UNDEF)
2130 return N0;
2131 if (N1.getOpcode() == ISD::UNDEF)
2132 return N1;
2133 // fold (xor c1, c2) -> c1^c2
2134 if (N0C && N1C)
2135 return DAG.getNode(ISD::XOR, VT, N0, N1);
2136 // canonicalize constant to RHS
2137 if (N0C && !N1C)
2138 return DAG.getNode(ISD::XOR, VT, N1, N0);
2139 // fold (xor x, 0) -> x
2140 if (N1C && N1C->isNullValue())
2141 return N0;
2142 // reassociate xor
2143 SDOperand RXOR = ReassociateOps(ISD::XOR, N0, N1);
2144 if (RXOR.Val != 0)
2145 return RXOR;
2146 // fold !(x cc y) -> (x !cc y)
Dan Gohman9d24dc72008-03-13 22:13:53 +00002147 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002148 bool isInt = MVT::isInteger(LHS.getValueType());
2149 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2150 isInt);
2151 if (N0.getOpcode() == ISD::SETCC)
2152 return DAG.getSetCC(VT, LHS, RHS, NotCC);
2153 if (N0.getOpcode() == ISD::SELECT_CC)
2154 return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
2155 assert(0 && "Unhandled SetCC Equivalent!");
2156 abort();
2157 }
Chris Lattnere27cd502007-09-10 21:39:07 +00002158 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohman9d24dc72008-03-13 22:13:53 +00002159 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Chris Lattnere27cd502007-09-10 21:39:07 +00002160 N0.Val->hasOneUse() && isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2161 SDOperand V = N0.getOperand(0);
2162 V = DAG.getNode(ISD::XOR, V.getValueType(), V,
Duncan Sandsbed21472007-10-10 09:54:50 +00002163 DAG.getConstant(1, V.getValueType()));
Chris Lattnere27cd502007-09-10 21:39:07 +00002164 AddToWorkList(V.Val);
2165 return DAG.getNode(ISD::ZERO_EXTEND, VT, V);
2166 }
2167
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002168 // fold !(x or y) -> (!x and !y) iff x or y are setcc
Dan Gohman9d24dc72008-03-13 22:13:53 +00002169 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002170 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2171 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2172 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2173 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2174 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2175 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2176 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2177 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2178 }
2179 }
2180 // fold !(x or y) -> (!x and !y) iff x or y are constants
2181 if (N1C && N1C->isAllOnesValue() &&
2182 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2183 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2184 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2185 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2186 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2187 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2188 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2189 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2190 }
2191 }
2192 // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
2193 if (N1C && N0.getOpcode() == ISD::XOR) {
2194 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2195 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2196 if (N00C)
2197 return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
Dan Gohman9d24dc72008-03-13 22:13:53 +00002198 DAG.getConstant(N1C->getAPIntValue()^
2199 N00C->getAPIntValue(), VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002200 if (N01C)
2201 return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
Dan Gohman9d24dc72008-03-13 22:13:53 +00002202 DAG.getConstant(N1C->getAPIntValue()^
2203 N01C->getAPIntValue(), VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002204 }
2205 // fold (xor x, x) -> 0
2206 if (N0 == N1) {
2207 if (!MVT::isVector(VT)) {
2208 return DAG.getConstant(0, VT);
2209 } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
2210 // Produce a vector of zeros.
2211 SDOperand El = DAG.getConstant(0, MVT::getVectorElementType(VT));
2212 std::vector<SDOperand> Ops(MVT::getVectorNumElements(VT), El);
2213 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
2214 }
2215 }
2216
2217 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2218 if (N0.getOpcode() == N1.getOpcode()) {
2219 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2220 if (Tmp.Val) return Tmp;
2221 }
2222
2223 // Simplify the expression using non-local knowledge.
2224 if (!MVT::isVector(VT) &&
2225 SimplifyDemandedBits(SDOperand(N, 0)))
2226 return SDOperand(N, 0);
2227
2228 return SDOperand();
2229}
2230
Chris Lattner91ed3c32007-12-06 07:33:36 +00002231/// visitShiftByConstant - Handle transforms common to the three shifts, when
2232/// the shift amount is a constant.
2233SDOperand DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2234 SDNode *LHS = N->getOperand(0).Val;
2235 if (!LHS->hasOneUse()) return SDOperand();
2236
2237 // We want to pull some binops through shifts, so that we have (and (shift))
2238 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2239 // thing happens with address calculations, so it's important to canonicalize
2240 // it.
2241 bool HighBitSet = false; // Can we transform this if the high bit is set?
2242
2243 switch (LHS->getOpcode()) {
2244 default: return SDOperand();
2245 case ISD::OR:
2246 case ISD::XOR:
2247 HighBitSet = false; // We can only transform sra if the high bit is clear.
2248 break;
2249 case ISD::AND:
2250 HighBitSet = true; // We can only transform sra if the high bit is set.
2251 break;
2252 case ISD::ADD:
2253 if (N->getOpcode() != ISD::SHL)
2254 return SDOperand(); // only shl(add) not sr[al](add).
2255 HighBitSet = false; // We can only transform sra if the high bit is clear.
2256 break;
2257 }
2258
2259 // We require the RHS of the binop to be a constant as well.
2260 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2261 if (!BinOpCst) return SDOperand();
2262
Chris Lattnerdcd19762007-12-06 07:47:55 +00002263
2264 // FIXME: disable this for unless the input to the binop is a shift by a
2265 // constant. If it is not a shift, it pessimizes some common cases like:
2266 //
2267 //void foo(int *X, int i) { X[i & 1235] = 1; }
2268 //int bar(int *X, int i) { return X[i & 255]; }
2269 SDNode *BinOpLHSVal = LHS->getOperand(0).Val;
2270 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2271 BinOpLHSVal->getOpcode() != ISD::SRA &&
2272 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2273 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2274 return SDOperand();
2275
Chris Lattner91ed3c32007-12-06 07:33:36 +00002276 MVT::ValueType VT = N->getValueType(0);
2277
2278 // If this is a signed shift right, and the high bit is modified
2279 // by the logical operation, do not perform the transformation.
2280 // The highBitSet boolean indicates the value of the high bit of
2281 // the constant which would cause it to be modified for this
2282 // operation.
2283 if (N->getOpcode() == ISD::SRA) {
Dan Gohmand047c3e2008-03-03 23:51:38 +00002284 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2285 if (BinOpRHSSignSet != HighBitSet)
Chris Lattner91ed3c32007-12-06 07:33:36 +00002286 return SDOperand();
2287 }
2288
2289 // Fold the constants, shifting the binop RHS by the shift amount.
2290 SDOperand NewRHS = DAG.getNode(N->getOpcode(), N->getValueType(0),
2291 LHS->getOperand(1), N->getOperand(1));
2292
2293 // Create the new shift.
2294 SDOperand NewShift = DAG.getNode(N->getOpcode(), VT, LHS->getOperand(0),
2295 N->getOperand(1));
2296
2297 // Create the new binop.
2298 return DAG.getNode(LHS->getOpcode(), VT, NewShift, NewRHS);
2299}
2300
2301
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002302SDOperand DAGCombiner::visitSHL(SDNode *N) {
2303 SDOperand N0 = N->getOperand(0);
2304 SDOperand N1 = N->getOperand(1);
2305 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2306 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2307 MVT::ValueType VT = N0.getValueType();
2308 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
2309
2310 // fold (shl c1, c2) -> c1<<c2
2311 if (N0C && N1C)
2312 return DAG.getNode(ISD::SHL, VT, N0, N1);
2313 // fold (shl 0, x) -> 0
2314 if (N0C && N0C->isNullValue())
2315 return N0;
2316 // fold (shl x, c >= size(x)) -> undef
2317 if (N1C && N1C->getValue() >= OpSizeInBits)
2318 return DAG.getNode(ISD::UNDEF, VT);
2319 // fold (shl x, 0) -> x
2320 if (N1C && N1C->isNullValue())
2321 return N0;
2322 // if (shl x, c) is known to be zero, return 0
Dan Gohman07961cd2008-02-25 21:11:39 +00002323 if (DAG.MaskedValueIsZero(SDOperand(N, 0),
2324 APInt::getAllOnesValue(MVT::getSizeInBits(VT))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002325 return DAG.getConstant(0, VT);
2326 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2327 return SDOperand(N, 0);
2328 // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
2329 if (N1C && N0.getOpcode() == ISD::SHL &&
2330 N0.getOperand(1).getOpcode() == ISD::Constant) {
2331 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2332 uint64_t c2 = N1C->getValue();
2333 if (c1 + c2 > OpSizeInBits)
2334 return DAG.getConstant(0, VT);
2335 return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
2336 DAG.getConstant(c1 + c2, N1.getValueType()));
2337 }
2338 // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
2339 // (srl (and x, -1 << c1), c1-c2)
2340 if (N1C && N0.getOpcode() == ISD::SRL &&
2341 N0.getOperand(1).getOpcode() == ISD::Constant) {
2342 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2343 uint64_t c2 = N1C->getValue();
2344 SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2345 DAG.getConstant(~0ULL << c1, VT));
2346 if (c2 > c1)
2347 return DAG.getNode(ISD::SHL, VT, Mask,
2348 DAG.getConstant(c2-c1, N1.getValueType()));
2349 else
2350 return DAG.getNode(ISD::SRL, VT, Mask,
2351 DAG.getConstant(c1-c2, N1.getValueType()));
2352 }
2353 // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
2354 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
2355 return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2356 DAG.getConstant(~0ULL << N1C->getValue(), VT));
Chris Lattner91ed3c32007-12-06 07:33:36 +00002357
2358 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002359}
2360
2361SDOperand DAGCombiner::visitSRA(SDNode *N) {
2362 SDOperand N0 = N->getOperand(0);
2363 SDOperand N1 = N->getOperand(1);
2364 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2365 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2366 MVT::ValueType VT = N0.getValueType();
2367
2368 // fold (sra c1, c2) -> c1>>c2
2369 if (N0C && N1C)
2370 return DAG.getNode(ISD::SRA, VT, N0, N1);
2371 // fold (sra 0, x) -> 0
2372 if (N0C && N0C->isNullValue())
2373 return N0;
2374 // fold (sra -1, x) -> -1
2375 if (N0C && N0C->isAllOnesValue())
2376 return N0;
2377 // fold (sra x, c >= size(x)) -> undef
2378 if (N1C && N1C->getValue() >= MVT::getSizeInBits(VT))
2379 return DAG.getNode(ISD::UNDEF, VT);
2380 // fold (sra x, 0) -> x
2381 if (N1C && N1C->isNullValue())
2382 return N0;
2383 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2384 // sext_inreg.
2385 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2386 unsigned LowBits = MVT::getSizeInBits(VT) - (unsigned)N1C->getValue();
2387 MVT::ValueType EVT;
2388 switch (LowBits) {
2389 default: EVT = MVT::Other; break;
2390 case 1: EVT = MVT::i1; break;
2391 case 8: EVT = MVT::i8; break;
2392 case 16: EVT = MVT::i16; break;
2393 case 32: EVT = MVT::i32; break;
2394 }
2395 if (EVT > MVT::Other && TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT))
2396 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
2397 DAG.getValueType(EVT));
2398 }
2399
2400 // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
2401 if (N1C && N0.getOpcode() == ISD::SRA) {
2402 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2403 unsigned Sum = N1C->getValue() + C1->getValue();
2404 if (Sum >= MVT::getSizeInBits(VT)) Sum = MVT::getSizeInBits(VT)-1;
2405 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
2406 DAG.getConstant(Sum, N1C->getValueType(0)));
2407 }
2408 }
Christopher Lambfc5c1642008-03-19 08:30:06 +00002409
2410 // fold sra (shl X, m), result_size - n
2411 // -> (sign_extend (trunc (shl X, result_size - n - m))) for
Christopher Lamb21e8a952008-03-20 04:31:39 +00002412 // result_size - n != m.
2413 // If truncate is free for the target sext(shl) is likely to result in better
2414 // code.
Christopher Lambfc5c1642008-03-19 08:30:06 +00002415 if (N0.getOpcode() == ISD::SHL) {
2416 // Get the two constanst of the shifts, CN0 = m, CN = n.
2417 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2418 if (N01C && N1C) {
Christopher Lamb21e8a952008-03-20 04:31:39 +00002419 // Determine what the truncate's result bitsize and type would be.
Christopher Lambfc5c1642008-03-19 08:30:06 +00002420 unsigned VTValSize = MVT::getSizeInBits(VT);
2421 MVT::ValueType TruncVT = MVT::getIntegerType(VTValSize - N1C->getValue());
Christopher Lamb21e8a952008-03-20 04:31:39 +00002422 // Determine the residual right-shift amount.
Christopher Lambfc5c1642008-03-19 08:30:06 +00002423 unsigned ShiftAmt = N1C->getValue() - N01C->getValue();
Christopher Lamb21e8a952008-03-20 04:31:39 +00002424
2425 // If the shift is not a no-op (in which case this should be just a sign
2426 // extend already), the truncated to type is legal, sign_extend is legal
2427 // on that type, and the the truncate to that type is both legal and free,
2428 // perform the transform.
2429 if (ShiftAmt &&
2430 TLI.isTypeLegal(TruncVT) &&
2431 TLI.isOperationLegal(ISD::SIGN_EXTEND, TruncVT) &&
2432 TLI.isOperationLegal(ISD::TRUNCATE, VT) &&
Evan Chengca0e80f2008-03-20 02:18:41 +00002433 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb21e8a952008-03-20 04:31:39 +00002434
2435 SDOperand Amt = DAG.getConstant(ShiftAmt, TLI.getShiftAmountTy());
2436 SDOperand Shift = DAG.getNode(ISD::SRL, VT, N0.getOperand(0), Amt);
2437 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, TruncVT, Shift);
2438 return DAG.getNode(ISD::SIGN_EXTEND, N->getValueType(0), Trunc);
Christopher Lambfc5c1642008-03-19 08:30:06 +00002439 }
2440 }
2441 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002442
2443 // Simplify, based on bits shifted out of the LHS.
2444 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2445 return SDOperand(N, 0);
2446
2447
2448 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman07961cd2008-02-25 21:11:39 +00002449 if (DAG.SignBitIsZero(N0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002450 return DAG.getNode(ISD::SRL, VT, N0, N1);
Chris Lattner91ed3c32007-12-06 07:33:36 +00002451
2452 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002453}
2454
2455SDOperand DAGCombiner::visitSRL(SDNode *N) {
2456 SDOperand N0 = N->getOperand(0);
2457 SDOperand N1 = N->getOperand(1);
2458 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2459 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2460 MVT::ValueType VT = N0.getValueType();
2461 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
2462
2463 // fold (srl c1, c2) -> c1 >>u c2
2464 if (N0C && N1C)
2465 return DAG.getNode(ISD::SRL, VT, N0, N1);
2466 // fold (srl 0, x) -> 0
2467 if (N0C && N0C->isNullValue())
2468 return N0;
2469 // fold (srl x, c >= size(x)) -> undef
2470 if (N1C && N1C->getValue() >= OpSizeInBits)
2471 return DAG.getNode(ISD::UNDEF, VT);
2472 // fold (srl x, 0) -> x
2473 if (N1C && N1C->isNullValue())
2474 return N0;
2475 // if (srl x, c) is known to be zero, return 0
Dan Gohman07961cd2008-02-25 21:11:39 +00002476 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
2477 APInt::getAllOnesValue(OpSizeInBits)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002478 return DAG.getConstant(0, VT);
2479
2480 // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
2481 if (N1C && N0.getOpcode() == ISD::SRL &&
2482 N0.getOperand(1).getOpcode() == ISD::Constant) {
2483 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2484 uint64_t c2 = N1C->getValue();
2485 if (c1 + c2 > OpSizeInBits)
2486 return DAG.getConstant(0, VT);
2487 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
2488 DAG.getConstant(c1 + c2, N1.getValueType()));
2489 }
2490
2491 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2492 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2493 // Shifting in all undef bits?
2494 MVT::ValueType SmallVT = N0.getOperand(0).getValueType();
2495 if (N1C->getValue() >= MVT::getSizeInBits(SmallVT))
2496 return DAG.getNode(ISD::UNDEF, VT);
2497
2498 SDOperand SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
2499 AddToWorkList(SmallShift.Val);
2500 return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
2501 }
2502
2503 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
2504 // bit, which is unmodified by sra.
2505 if (N1C && N1C->getValue()+1 == MVT::getSizeInBits(VT)) {
2506 if (N0.getOpcode() == ISD::SRA)
2507 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1);
2508 }
2509
2510 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
2511 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Dan Gohman9d24dc72008-03-13 22:13:53 +00002512 N1C->getAPIntValue() == Log2_32(MVT::getSizeInBits(VT))) {
Dan Gohmanbea075f2008-02-20 16:33:30 +00002513 APInt KnownZero, KnownOne;
2514 APInt Mask = APInt::getAllOnesValue(MVT::getSizeInBits(VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002515 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2516
2517 // If any of the input bits are KnownOne, then the input couldn't be all
2518 // zeros, thus the result of the srl will always be zero.
Dan Gohmanbea075f2008-02-20 16:33:30 +00002519 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002520
2521 // If all of the bits input the to ctlz node are known to be zero, then
2522 // the result of the ctlz is "32" and the result of the shift is one.
Dan Gohmanbea075f2008-02-20 16:33:30 +00002523 APInt UnknownBits = ~KnownZero & Mask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002524 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2525
2526 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2527 if ((UnknownBits & (UnknownBits-1)) == 0) {
2528 // Okay, we know that only that the single bit specified by UnknownBits
2529 // could be set on input to the CTLZ node. If this bit is set, the SRL
2530 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2531 // to an SRL,XOR pair, which is likely to simplify more.
Dan Gohmanbea075f2008-02-20 16:33:30 +00002532 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002533 SDOperand Op = N0.getOperand(0);
2534 if (ShAmt) {
2535 Op = DAG.getNode(ISD::SRL, VT, Op,
2536 DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
2537 AddToWorkList(Op.Val);
2538 }
2539 return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
2540 }
2541 }
2542
2543 // fold operands of srl based on knowledge that the low bits are not
2544 // demanded.
2545 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2546 return SDOperand(N, 0);
2547
Chris Lattner91ed3c32007-12-06 07:33:36 +00002548 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002549}
2550
2551SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
2552 SDOperand N0 = N->getOperand(0);
2553 MVT::ValueType VT = N->getValueType(0);
2554
2555 // fold (ctlz c1) -> c2
2556 if (isa<ConstantSDNode>(N0))
2557 return DAG.getNode(ISD::CTLZ, VT, N0);
2558 return SDOperand();
2559}
2560
2561SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
2562 SDOperand N0 = N->getOperand(0);
2563 MVT::ValueType VT = N->getValueType(0);
2564
2565 // fold (cttz c1) -> c2
2566 if (isa<ConstantSDNode>(N0))
2567 return DAG.getNode(ISD::CTTZ, VT, N0);
2568 return SDOperand();
2569}
2570
2571SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
2572 SDOperand N0 = N->getOperand(0);
2573 MVT::ValueType VT = N->getValueType(0);
2574
2575 // fold (ctpop c1) -> c2
2576 if (isa<ConstantSDNode>(N0))
2577 return DAG.getNode(ISD::CTPOP, VT, N0);
2578 return SDOperand();
2579}
2580
2581SDOperand DAGCombiner::visitSELECT(SDNode *N) {
2582 SDOperand N0 = N->getOperand(0);
2583 SDOperand N1 = N->getOperand(1);
2584 SDOperand N2 = N->getOperand(2);
2585 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2586 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2587 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2588 MVT::ValueType VT = N->getValueType(0);
Evan Chengff601dc2007-08-18 05:57:05 +00002589 MVT::ValueType VT0 = N0.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002590
2591 // fold select C, X, X -> X
2592 if (N1 == N2)
2593 return N1;
2594 // fold select true, X, Y -> X
2595 if (N0C && !N0C->isNullValue())
2596 return N1;
2597 // fold select false, X, Y -> Y
2598 if (N0C && N0C->isNullValue())
2599 return N2;
2600 // fold select C, 1, X -> C | X
Dan Gohman9d24dc72008-03-13 22:13:53 +00002601 if (MVT::i1 == VT && N1C && N1C->getAPIntValue() == 1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002602 return DAG.getNode(ISD::OR, VT, N0, N2);
Evan Chengff601dc2007-08-18 05:57:05 +00002603 // fold select C, 0, 1 -> ~C
2604 if (MVT::isInteger(VT) && MVT::isInteger(VT0) &&
Dan Gohman9d24dc72008-03-13 22:13:53 +00002605 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Evan Chengff601dc2007-08-18 05:57:05 +00002606 SDOperand XORNode = DAG.getNode(ISD::XOR, VT0, N0, DAG.getConstant(1, VT0));
2607 if (VT == VT0)
2608 return XORNode;
2609 AddToWorkList(XORNode.Val);
2610 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(VT0))
2611 return DAG.getNode(ISD::ZERO_EXTEND, VT, XORNode);
2612 return DAG.getNode(ISD::TRUNCATE, VT, XORNode);
2613 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002614 // fold select C, 0, X -> ~C & X
Dale Johannesen53e0ad72007-12-06 17:53:31 +00002615 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
2616 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002617 AddToWorkList(XORNode.Val);
2618 return DAG.getNode(ISD::AND, VT, XORNode, N2);
2619 }
2620 // fold select C, X, 1 -> ~C | X
Dan Gohman9d24dc72008-03-13 22:13:53 +00002621 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Dale Johannesen53e0ad72007-12-06 17:53:31 +00002622 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002623 AddToWorkList(XORNode.Val);
2624 return DAG.getNode(ISD::OR, VT, XORNode, N1);
2625 }
2626 // fold select C, X, 0 -> C & X
2627 // FIXME: this should check for C type == X type, not i1?
2628 if (MVT::i1 == VT && N2C && N2C->isNullValue())
2629 return DAG.getNode(ISD::AND, VT, N0, N1);
2630 // fold X ? X : Y --> X ? 1 : Y --> X | Y
2631 if (MVT::i1 == VT && N0 == N1)
2632 return DAG.getNode(ISD::OR, VT, N0, N2);
2633 // fold X ? Y : X --> X ? Y : 0 --> X & Y
2634 if (MVT::i1 == VT && N0 == N2)
2635 return DAG.getNode(ISD::AND, VT, N0, N1);
2636
2637 // If we can fold this based on the true/false value, do so.
2638 if (SimplifySelectOps(N, N1, N2))
2639 return SDOperand(N, 0); // Don't revisit N.
2640
2641 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov53422f62008-02-20 11:10:28 +00002642 if (N0.getOpcode() == ISD::SETCC) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002643 // FIXME:
2644 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2645 // having to say they don't support SELECT_CC on every type the DAG knows
2646 // about, since there is no way to mark an opcode illegal at all value types
2647 if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
2648 return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
2649 N1, N2, N0.getOperand(2));
2650 else
2651 return SimplifySelect(N0, N1, N2);
Anton Korobeynikov53422f62008-02-20 11:10:28 +00002652 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002653 return SDOperand();
2654}
2655
2656SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
2657 SDOperand N0 = N->getOperand(0);
2658 SDOperand N1 = N->getOperand(1);
2659 SDOperand N2 = N->getOperand(2);
2660 SDOperand N3 = N->getOperand(3);
2661 SDOperand N4 = N->getOperand(4);
2662 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2663
2664 // fold select_cc lhs, rhs, x, x, cc -> x
2665 if (N2 == N3)
2666 return N2;
2667
2668 // Determine if the condition we're dealing with is constant
Scott Michel502151f2008-03-10 15:42:14 +00002669 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002670 if (SCC.Val) AddToWorkList(SCC.Val);
2671
2672 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val)) {
Dan Gohman9d24dc72008-03-13 22:13:53 +00002673 if (!SCCC->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002674 return N2; // cond always true -> true val
2675 else
2676 return N3; // cond always false -> false val
2677 }
2678
2679 // Fold to a simpler select_cc
2680 if (SCC.Val && SCC.getOpcode() == ISD::SETCC)
2681 return DAG.getNode(ISD::SELECT_CC, N2.getValueType(),
2682 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2683 SCC.getOperand(2));
2684
2685 // If we can fold this based on the true/false value, do so.
2686 if (SimplifySelectOps(N, N2, N3))
2687 return SDOperand(N, 0); // Don't revisit N.
2688
2689 // fold select_cc into other things, such as min/max/abs
2690 return SimplifySelectCC(N0, N1, N2, N3, CC);
2691}
2692
2693SDOperand DAGCombiner::visitSETCC(SDNode *N) {
2694 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2695 cast<CondCodeSDNode>(N->getOperand(2))->get());
2696}
2697
Evan Cheng9decb332007-10-29 19:58:20 +00002698// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
2699// "fold ({s|z}ext (load x)) -> ({s|z}ext (truncate ({s|z}extload x)))"
2700// transformation. Returns true if extension are possible and the above
2701// mentioned transformation is profitable.
2702static bool ExtendUsesToFormExtLoad(SDNode *N, SDOperand N0,
2703 unsigned ExtOpc,
2704 SmallVector<SDNode*, 4> &ExtendNodes,
2705 TargetLowering &TLI) {
2706 bool HasCopyToRegUses = false;
2707 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
2708 for (SDNode::use_iterator UI = N0.Val->use_begin(), UE = N0.Val->use_end();
2709 UI != UE; ++UI) {
Roman Levenstein05650fd2008-04-07 10:06:32 +00002710 SDNode *User = UI->getUser();
Evan Cheng9decb332007-10-29 19:58:20 +00002711 if (User == N)
2712 continue;
2713 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
2714 if (User->getOpcode() == ISD::SETCC) {
2715 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
2716 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
2717 // Sign bits will be lost after a zext.
2718 return false;
2719 bool Add = false;
2720 for (unsigned i = 0; i != 2; ++i) {
2721 SDOperand UseOp = User->getOperand(i);
2722 if (UseOp == N0)
2723 continue;
2724 if (!isa<ConstantSDNode>(UseOp))
2725 return false;
2726 Add = true;
2727 }
2728 if (Add)
2729 ExtendNodes.push_back(User);
2730 } else {
2731 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2732 SDOperand UseOp = User->getOperand(i);
2733 if (UseOp == N0) {
2734 // If truncate from extended type to original load type is free
2735 // on this target, then it's ok to extend a CopyToReg.
2736 if (isTruncFree && User->getOpcode() == ISD::CopyToReg)
2737 HasCopyToRegUses = true;
2738 else
2739 return false;
2740 }
2741 }
2742 }
2743 }
2744
2745 if (HasCopyToRegUses) {
2746 bool BothLiveOut = false;
2747 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
2748 UI != UE; ++UI) {
Roman Levenstein05650fd2008-04-07 10:06:32 +00002749 SDNode *User = UI->getUser();
Evan Cheng9decb332007-10-29 19:58:20 +00002750 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2751 SDOperand UseOp = User->getOperand(i);
2752 if (UseOp.Val == N && UseOp.ResNo == 0) {
2753 BothLiveOut = true;
2754 break;
2755 }
2756 }
2757 }
2758 if (BothLiveOut)
2759 // Both unextended and extended values are live out. There had better be
2760 // good a reason for the transformation.
2761 return ExtendNodes.size();
2762 }
2763 return true;
2764}
2765
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002766SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2767 SDOperand N0 = N->getOperand(0);
2768 MVT::ValueType VT = N->getValueType(0);
2769
2770 // fold (sext c1) -> c1
2771 if (isa<ConstantSDNode>(N0))
2772 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
2773
2774 // fold (sext (sext x)) -> (sext x)
2775 // fold (sext (aext x)) -> (sext x)
2776 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2777 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
2778
2779 // fold (sext (truncate (load x))) -> (sext (smaller load x))
2780 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
2781 if (N0.getOpcode() == ISD::TRUNCATE) {
2782 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2783 if (NarrowLoad.Val) {
2784 if (NarrowLoad.Val != N0.Val)
2785 CombineTo(N0.Val, NarrowLoad);
2786 return DAG.getNode(ISD::SIGN_EXTEND, VT, NarrowLoad);
2787 }
2788 }
2789
2790 // See if the value being truncated is already sign extended. If so, just
2791 // eliminate the trunc/sext pair.
2792 if (N0.getOpcode() == ISD::TRUNCATE) {
2793 SDOperand Op = N0.getOperand(0);
2794 unsigned OpBits = MVT::getSizeInBits(Op.getValueType());
2795 unsigned MidBits = MVT::getSizeInBits(N0.getValueType());
2796 unsigned DestBits = MVT::getSizeInBits(VT);
2797 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
2798
2799 if (OpBits == DestBits) {
2800 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
2801 // bits, it is already ready.
2802 if (NumSignBits > DestBits-MidBits)
2803 return Op;
2804 } else if (OpBits < DestBits) {
2805 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
2806 // bits, just sext from i32.
2807 if (NumSignBits > OpBits-MidBits)
2808 return DAG.getNode(ISD::SIGN_EXTEND, VT, Op);
2809 } else {
2810 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
2811 // bits, just truncate to i32.
2812 if (NumSignBits > OpBits-MidBits)
2813 return DAG.getNode(ISD::TRUNCATE, VT, Op);
2814 }
2815
2816 // fold (sext (truncate x)) -> (sextinreg x).
2817 if (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
2818 N0.getValueType())) {
2819 if (Op.getValueType() < VT)
2820 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2821 else if (Op.getValueType() > VT)
2822 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2823 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op,
2824 DAG.getValueType(N0.getValueType()));
2825 }
2826 }
2827
2828 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Evan Cheng9decb332007-10-29 19:58:20 +00002829 if (ISD::isNON_EXTLoad(N0.Val) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002830 (!AfterLegalize||TLI.isLoadXLegal(ISD::SEXTLOAD, N0.getValueType()))){
Evan Cheng9decb332007-10-29 19:58:20 +00002831 bool DoXform = true;
2832 SmallVector<SDNode*, 4> SetCCs;
2833 if (!N0.hasOneUse())
2834 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
2835 if (DoXform) {
2836 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2837 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2838 LN0->getBasePtr(), LN0->getSrcValue(),
2839 LN0->getSrcValueOffset(),
2840 N0.getValueType(),
2841 LN0->isVolatile(),
2842 LN0->getAlignment());
2843 CombineTo(N, ExtLoad);
2844 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2845 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2846 // Extend SetCC uses if necessary.
2847 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2848 SDNode *SetCC = SetCCs[i];
2849 SmallVector<SDOperand, 4> Ops;
2850 for (unsigned j = 0; j != 2; ++j) {
2851 SDOperand SOp = SetCC->getOperand(j);
2852 if (SOp == Trunc)
2853 Ops.push_back(ExtLoad);
2854 else
2855 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, VT, SOp));
2856 }
2857 Ops.push_back(SetCC->getOperand(2));
2858 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2859 &Ops[0], Ops.size()));
2860 }
2861 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2862 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002863 }
2864
2865 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
2866 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
2867 if ((ISD::isSEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2868 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2869 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman9a4c92c2008-01-30 00:15:11 +00002870 MVT::ValueType EVT = LN0->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002871 if (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT)) {
2872 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2873 LN0->getBasePtr(), LN0->getSrcValue(),
2874 LN0->getSrcValueOffset(), EVT,
2875 LN0->isVolatile(),
2876 LN0->getAlignment());
2877 CombineTo(N, ExtLoad);
2878 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2879 ExtLoad.getValue(1));
2880 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2881 }
2882 }
2883
2884 // sext(setcc x,y,cc) -> select_cc x, y, -1, 0, cc
2885 if (N0.getOpcode() == ISD::SETCC) {
2886 SDOperand SCC =
2887 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2888 DAG.getConstant(~0ULL, VT), DAG.getConstant(0, VT),
2889 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2890 if (SCC.Val) return SCC;
2891 }
2892
Dan Gohman415e13a2008-04-28 16:58:24 +00002893 // fold (sext x) -> (zext x) if the sign bit is known zero.
Dan Gohman5b37f9d2008-04-28 18:47:17 +00002894 if ((!AfterLegalize || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
2895 DAG.SignBitIsZero(N0))
Dan Gohman415e13a2008-04-28 16:58:24 +00002896 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2897
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002898 return SDOperand();
2899}
2900
2901SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
2902 SDOperand N0 = N->getOperand(0);
2903 MVT::ValueType VT = N->getValueType(0);
2904
2905 // fold (zext c1) -> c1
2906 if (isa<ConstantSDNode>(N0))
2907 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2908 // fold (zext (zext x)) -> (zext x)
2909 // fold (zext (aext x)) -> (zext x)
2910 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2911 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
2912
2913 // fold (zext (truncate (load x))) -> (zext (smaller load x))
2914 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
2915 if (N0.getOpcode() == ISD::TRUNCATE) {
2916 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2917 if (NarrowLoad.Val) {
2918 if (NarrowLoad.Val != N0.Val)
2919 CombineTo(N0.Val, NarrowLoad);
2920 return DAG.getNode(ISD::ZERO_EXTEND, VT, NarrowLoad);
2921 }
2922 }
2923
2924 // fold (zext (truncate x)) -> (and x, mask)
2925 if (N0.getOpcode() == ISD::TRUNCATE &&
2926 (!AfterLegalize || TLI.isOperationLegal(ISD::AND, VT))) {
2927 SDOperand Op = N0.getOperand(0);
2928 if (Op.getValueType() < VT) {
2929 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2930 } else if (Op.getValueType() > VT) {
2931 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2932 }
2933 return DAG.getZeroExtendInReg(Op, N0.getValueType());
2934 }
2935
2936 // fold (zext (and (trunc x), cst)) -> (and x, cst).
2937 if (N0.getOpcode() == ISD::AND &&
2938 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2939 N0.getOperand(1).getOpcode() == ISD::Constant) {
2940 SDOperand X = N0.getOperand(0).getOperand(0);
2941 if (X.getValueType() < VT) {
2942 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2943 } else if (X.getValueType() > VT) {
2944 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2945 }
Dan Gohmand047c3e2008-03-03 23:51:38 +00002946 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2947 Mask.zext(MVT::getSizeInBits(VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002948 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2949 }
2950
2951 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Evan Cheng9decb332007-10-29 19:58:20 +00002952 if (ISD::isNON_EXTLoad(N0.Val) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002953 (!AfterLegalize||TLI.isLoadXLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Cheng9decb332007-10-29 19:58:20 +00002954 bool DoXform = true;
2955 SmallVector<SDNode*, 4> SetCCs;
2956 if (!N0.hasOneUse())
2957 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
2958 if (DoXform) {
2959 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2960 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2961 LN0->getBasePtr(), LN0->getSrcValue(),
2962 LN0->getSrcValueOffset(),
2963 N0.getValueType(),
2964 LN0->isVolatile(),
2965 LN0->getAlignment());
2966 CombineTo(N, ExtLoad);
2967 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2968 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2969 // Extend SetCC uses if necessary.
2970 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2971 SDNode *SetCC = SetCCs[i];
2972 SmallVector<SDOperand, 4> Ops;
2973 for (unsigned j = 0; j != 2; ++j) {
2974 SDOperand SOp = SetCC->getOperand(j);
2975 if (SOp == Trunc)
2976 Ops.push_back(ExtLoad);
2977 else
Evan Cheng06aaf4c2007-10-30 20:11:21 +00002978 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND, VT, SOp));
Evan Cheng9decb332007-10-29 19:58:20 +00002979 }
2980 Ops.push_back(SetCC->getOperand(2));
2981 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2982 &Ops[0], Ops.size()));
2983 }
2984 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2985 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002986 }
2987
2988 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
2989 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
2990 if ((ISD::isZEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2991 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2992 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman9a4c92c2008-01-30 00:15:11 +00002993 MVT::ValueType EVT = LN0->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002994 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2995 LN0->getBasePtr(), LN0->getSrcValue(),
2996 LN0->getSrcValueOffset(), EVT,
2997 LN0->isVolatile(),
2998 LN0->getAlignment());
2999 CombineTo(N, ExtLoad);
3000 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3001 ExtLoad.getValue(1));
3002 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3003 }
3004
3005 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3006 if (N0.getOpcode() == ISD::SETCC) {
3007 SDOperand SCC =
3008 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3009 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3010 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3011 if (SCC.Val) return SCC;
3012 }
3013
3014 return SDOperand();
3015}
3016
3017SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
3018 SDOperand N0 = N->getOperand(0);
3019 MVT::ValueType VT = N->getValueType(0);
3020
3021 // fold (aext c1) -> c1
3022 if (isa<ConstantSDNode>(N0))
3023 return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
3024 // fold (aext (aext x)) -> (aext x)
3025 // fold (aext (zext x)) -> (zext x)
3026 // fold (aext (sext x)) -> (sext x)
3027 if (N0.getOpcode() == ISD::ANY_EXTEND ||
3028 N0.getOpcode() == ISD::ZERO_EXTEND ||
3029 N0.getOpcode() == ISD::SIGN_EXTEND)
3030 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3031
3032 // fold (aext (truncate (load x))) -> (aext (smaller load x))
3033 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
3034 if (N0.getOpcode() == ISD::TRUNCATE) {
3035 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
3036 if (NarrowLoad.Val) {
3037 if (NarrowLoad.Val != N0.Val)
3038 CombineTo(N0.Val, NarrowLoad);
3039 return DAG.getNode(ISD::ANY_EXTEND, VT, NarrowLoad);
3040 }
3041 }
3042
3043 // fold (aext (truncate x))
3044 if (N0.getOpcode() == ISD::TRUNCATE) {
3045 SDOperand TruncOp = N0.getOperand(0);
3046 if (TruncOp.getValueType() == VT)
3047 return TruncOp; // x iff x size == zext size.
3048 if (TruncOp.getValueType() > VT)
3049 return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
3050 return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
3051 }
3052
3053 // fold (aext (and (trunc x), cst)) -> (and x, cst).
3054 if (N0.getOpcode() == ISD::AND &&
3055 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3056 N0.getOperand(1).getOpcode() == ISD::Constant) {
3057 SDOperand X = N0.getOperand(0).getOperand(0);
3058 if (X.getValueType() < VT) {
3059 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
3060 } else if (X.getValueType() > VT) {
3061 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3062 }
Dan Gohmand047c3e2008-03-03 23:51:38 +00003063 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3064 Mask.zext(MVT::getSizeInBits(VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003065 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
3066 }
3067
3068 // fold (aext (load x)) -> (aext (truncate (extload x)))
3069 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3070 (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3071 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);
Dan Gohman9a4c92c2008-01-30 00:15:11 +00003091 MVT::ValueType 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);
3158 MVT::ValueType VT = N->getValueType(0);
3159 MVT::ValueType EVT = N->getValueType(0);
3160
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
3170 unsigned EVTBits = MVT::getSizeInBits(EVT);
3171 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);
3179 if (MVT::getSizeInBits(N0.getValueType()) <= EVTBits)
3180 return SDOperand();
3181 CombineSRL = true;
3182 }
3183 }
3184 }
3185
3186 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3187 // Do not allow folding to i1 here. i1 is implicitly stored in memory in
3188 // zero extended form: by shrinking the load, we lose track of the fact
3189 // that it is already zero extended.
3190 // FIXME: This should be reevaluated.
3191 VT != MVT::i1) {
3192 assert(MVT::getSizeInBits(N0.getValueType()) > EVTBits &&
3193 "Cannot truncate to larger type!");
3194 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3195 MVT::ValueType PtrType = N0.getOperand(1).getValueType();
3196 // For big endian targets, we need to adjust the offset to the pointer to
3197 // load the correct bytes.
Duncan Sands9ff8fbf2008-02-11 10:37:04 +00003198 if (TLI.isBigEndian()) {
Duncan Sands4f18d4f2007-11-09 08:57:19 +00003199 unsigned LVTStoreBits = MVT::getStoreSizeInBits(N0.getValueType());
3200 unsigned EVTStoreBits = MVT::getStoreSizeInBits(EVT);
3201 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3202 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003203 uint64_t PtrOff = ShAmt / 8;
Duncan Sandsa3691432007-10-28 12:59:45 +00003204 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003205 SDOperand NewPtr = DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
3206 DAG.getConstant(PtrOff, PtrType));
3207 AddToWorkList(NewPtr.Val);
3208 SDOperand Load = (ExtType == ISD::NON_EXTLOAD)
3209 ? DAG.getLoad(VT, LN0->getChain(), NewPtr,
3210 LN0->getSrcValue(), LN0->getSrcValueOffset(),
Duncan Sandsa3691432007-10-28 12:59:45 +00003211 LN0->isVolatile(), NewAlign)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003212 : DAG.getExtLoad(ExtType, VT, LN0->getChain(), NewPtr,
3213 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
Duncan Sandsa3691432007-10-28 12:59:45 +00003214 LN0->isVolatile(), NewAlign);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003215 AddToWorkList(N);
3216 if (CombineSRL) {
Chris Lattner7bcb18f2008-02-03 06:49:24 +00003217 WorkListRemover DeadNodes(*this);
3218 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3219 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003220 CombineTo(N->getOperand(0).Val, Load);
3221 } else
3222 CombineTo(N0.Val, Load, Load.getValue(1));
3223 if (ShAmt) {
3224 if (Opc == ISD::SIGN_EXTEND_INREG)
3225 return DAG.getNode(Opc, VT, Load, N->getOperand(1));
3226 else
3227 return DAG.getNode(Opc, VT, Load);
3228 }
3229 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3230 }
3231
3232 return SDOperand();
3233}
3234
3235
3236SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
3237 SDOperand N0 = N->getOperand(0);
3238 SDOperand N1 = N->getOperand(1);
3239 MVT::ValueType VT = N->getValueType(0);
3240 MVT::ValueType EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman07961cd2008-02-25 21:11:39 +00003241 unsigned VTBits = MVT::getSizeInBits(VT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003242 unsigned EVTBits = MVT::getSizeInBits(EVT);
3243
3244 // fold (sext_in_reg c1) -> c1
3245 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
3246 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
3247
3248 // If the input is already sign extended, just drop the extension.
3249 if (DAG.ComputeNumSignBits(N0) >= MVT::getSizeInBits(VT)-EVTBits+1)
3250 return N0;
3251
3252 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
3253 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3254 EVT < cast<VTSDNode>(N0.getOperand(1))->getVT()) {
3255 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
3256 }
3257
3258 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman07961cd2008-02-25 21:11:39 +00003259 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003260 return DAG.getZeroExtendInReg(N0, EVT);
3261
3262 // fold operands of sext_in_reg based on knowledge that the top bits are not
3263 // demanded.
3264 if (SimplifyDemandedBits(SDOperand(N, 0)))
3265 return SDOperand(N, 0);
3266
3267 // fold (sext_in_reg (load x)) -> (smaller sextload x)
3268 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
3269 SDOperand NarrowLoad = ReduceLoadWidth(N);
3270 if (NarrowLoad.Val)
3271 return NarrowLoad;
3272
3273 // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
3274 // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
3275 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
3276 if (N0.getOpcode() == ISD::SRL) {
3277 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3278 if (ShAmt->getValue()+EVTBits <= MVT::getSizeInBits(VT)) {
3279 // We can turn this into an SRA iff the input to the SRL is already sign
3280 // extended enough.
3281 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
3282 if (MVT::getSizeInBits(VT)-(ShAmt->getValue()+EVTBits) < InSignBits)
3283 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
3284 }
3285 }
3286
3287 // fold (sext_inreg (extload x)) -> (sextload x)
3288 if (ISD::isEXTLoad(N0.Val) &&
3289 ISD::isUNINDEXEDLoad(N0.Val) &&
Dan Gohman9a4c92c2008-01-30 00:15:11 +00003290 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003291 (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3292 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() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003306 (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3307 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3308 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3309 LN0->getBasePtr(), LN0->getSrcValue(),
3310 LN0->getSrcValueOffset(), EVT,
3311 LN0->isVolatile(),
3312 LN0->getAlignment());
3313 CombineTo(N, ExtLoad);
3314 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3315 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3316 }
3317 return SDOperand();
3318}
3319
3320SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
3321 SDOperand N0 = N->getOperand(0);
3322 MVT::ValueType VT = N->getValueType(0);
3323
3324 // noop truncate
3325 if (N0.getValueType() == N->getValueType(0))
3326 return N0;
3327 // fold (truncate c1) -> c1
3328 if (isa<ConstantSDNode>(N0))
3329 return DAG.getNode(ISD::TRUNCATE, VT, N0);
3330 // fold (truncate (truncate x)) -> (truncate x)
3331 if (N0.getOpcode() == ISD::TRUNCATE)
3332 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3333 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
3334 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
3335 N0.getOpcode() == ISD::ANY_EXTEND) {
3336 if (N0.getOperand(0).getValueType() < VT)
3337 // if the source is smaller than the dest, we still need an extend
3338 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3339 else if (N0.getOperand(0).getValueType() > VT)
3340 // if the source is larger than the dest, than we just need the truncate
3341 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3342 else
3343 // if the source and dest are the same type, we can drop both the extend
3344 // and the truncate
3345 return N0.getOperand(0);
3346 }
3347
Chris Lattnere8671c52007-10-13 06:35:54 +00003348 // See if we can simplify the input to this truncate through knowledge that
3349 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
3350 // -> trunc y
Dan Gohman07961cd2008-02-25 21:11:39 +00003351 SDOperand Shorter =
3352 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
3353 MVT::getSizeInBits(VT)));
Chris Lattnere8671c52007-10-13 06:35:54 +00003354 if (Shorter.Val)
3355 return DAG.getNode(ISD::TRUNCATE, VT, Shorter);
3356
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003357 // fold (truncate (load x)) -> (smaller load x)
3358 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
3359 return ReduceLoadWidth(N);
3360}
3361
Evan Chengb6290462008-05-12 23:04:07 +00003362static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
3363 SDOperand Elt = N->getOperand(i);
3364 if (Elt.getOpcode() != ISD::MERGE_VALUES)
3365 return Elt.Val;
3366 return Elt.getOperand(Elt.ResNo).Val;
3367}
3368
3369/// CombineConsecutiveLoads - build_pair (load, load) -> load
3370/// if load locations are consecutive.
3371SDOperand DAGCombiner::CombineConsecutiveLoads(SDNode *N, MVT::ValueType VT) {
3372 assert(N->getOpcode() == ISD::BUILD_PAIR);
3373
3374 SDNode *LD1 = getBuildPairElt(N, 0);
3375 if (!ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse())
3376 return SDOperand();
3377 MVT::ValueType LD1VT = LD1->getValueType(0);
3378 SDNode *LD2 = getBuildPairElt(N, 1);
3379 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3380 if (ISD::isNON_EXTLoad(LD2) &&
3381 LD2->hasOneUse() &&
3382 TLI.isConsecutiveLoad(LD2, LD1, MVT::getSizeInBits(LD1VT)/8, 1, MFI)) {
3383 LoadSDNode *LD = cast<LoadSDNode>(LD1);
3384 unsigned Align = LD->getAlignment();
3385 unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
3386 getABITypeAlignment(MVT::getTypeForValueType(VT));
3387 if ((!AfterLegalize || TLI.isTypeLegal(VT)) &&
3388 TLI.isOperationLegal(ISD::LOAD, VT) && NewAlign <= Align)
3389 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(),
3390 LD->getSrcValue(), LD->getSrcValueOffset(),
3391 LD->isVolatile(), Align);
3392 }
3393 return SDOperand();
3394}
3395
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003396SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
3397 SDOperand N0 = N->getOperand(0);
3398 MVT::ValueType VT = N->getValueType(0);
3399
3400 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
3401 // Only do this before legalize, since afterward the target may be depending
3402 // on the bitconvert.
3403 // First check to see if this is all constant.
3404 if (!AfterLegalize &&
3405 N0.getOpcode() == ISD::BUILD_VECTOR && N0.Val->hasOneUse() &&
3406 MVT::isVector(VT)) {
3407 bool isSimple = true;
3408 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
3409 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
3410 N0.getOperand(i).getOpcode() != ISD::Constant &&
3411 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
3412 isSimple = false;
3413 break;
3414 }
3415
3416 MVT::ValueType DestEltVT = MVT::getVectorElementType(N->getValueType(0));
3417 assert(!MVT::isVector(DestEltVT) &&
3418 "Element type of vector ValueType must not be vector!");
3419 if (isSimple) {
3420 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.Val, DestEltVT);
3421 }
3422 }
3423
3424 // If the input is a constant, let getNode() fold it.
3425 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
3426 SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3427 if (Res.Val != N) return Res;
3428 }
3429
3430 if (N0.getOpcode() == ISD::BIT_CONVERT) // conv(conv(x,t1),t2) -> conv(x,t2)
3431 return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3432
3433 // fold (conv (load x)) -> (load (conv*)x)
Evan Chengd7ba7ed2007-10-06 08:19:55 +00003434 // If the resultant load doesn't need a higher alignment than the original!
3435 if (ISD::isNormalLoad(N0.Val) && N0.hasOneUse() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003436 TLI.isOperationLegal(ISD::LOAD, VT)) {
3437 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3438 unsigned Align = TLI.getTargetMachine().getTargetData()->
3439 getABITypeAlignment(MVT::getTypeForValueType(VT));
3440 unsigned OrigAlign = LN0->getAlignment();
3441 if (Align <= OrigAlign) {
3442 SDOperand Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(),
3443 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3444 LN0->isVolatile(), Align);
3445 AddToWorkList(N);
3446 CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
3447 Load.getValue(1));
3448 return Load;
3449 }
3450 }
3451
Chris Lattneref26cbc2008-01-27 17:42:27 +00003452 // Fold bitconvert(fneg(x)) -> xor(bitconvert(x), signbit)
3453 // Fold bitconvert(fabs(x)) -> and(bitconvert(x), ~signbit)
3454 // This often reduces constant pool loads.
3455 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
3456 N0.Val->hasOneUse() && MVT::isInteger(VT) && !MVT::isVector(VT)) {
3457 SDOperand NewConv = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3458 AddToWorkList(NewConv.Val);
3459
Dan Gohmand047c3e2008-03-03 23:51:38 +00003460 APInt SignBit = APInt::getSignBit(MVT::getSizeInBits(VT));
Chris Lattneref26cbc2008-01-27 17:42:27 +00003461 if (N0.getOpcode() == ISD::FNEG)
3462 return DAG.getNode(ISD::XOR, VT, NewConv, DAG.getConstant(SignBit, VT));
3463 assert(N0.getOpcode() == ISD::FABS);
3464 return DAG.getNode(ISD::AND, VT, NewConv, DAG.getConstant(~SignBit, VT));
3465 }
3466
3467 // Fold bitconvert(fcopysign(cst, x)) -> bitconvert(x)&sign | cst&~sign'
3468 // Note that we don't handle copysign(x,cst) because this can always be folded
3469 // to an fneg or fabs.
3470 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse() &&
Chris Lattner336672f2008-01-27 23:32:17 +00003471 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
3472 MVT::isInteger(VT) && !MVT::isVector(VT)) {
Chris Lattneref26cbc2008-01-27 17:42:27 +00003473 unsigned OrigXWidth = MVT::getSizeInBits(N0.getOperand(1).getValueType());
3474 SDOperand X = DAG.getNode(ISD::BIT_CONVERT, MVT::getIntegerType(OrigXWidth),
3475 N0.getOperand(1));
3476 AddToWorkList(X.Val);
3477
3478 // If X has a different width than the result/lhs, sext it or truncate it.
3479 unsigned VTWidth = MVT::getSizeInBits(VT);
3480 if (OrigXWidth < VTWidth) {
3481 X = DAG.getNode(ISD::SIGN_EXTEND, VT, X);
3482 AddToWorkList(X.Val);
3483 } else if (OrigXWidth > VTWidth) {
3484 // To get the sign bit in the right place, we have to shift it right
3485 // before truncating.
3486 X = DAG.getNode(ISD::SRL, X.getValueType(), X,
3487 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
3488 AddToWorkList(X.Val);
3489 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3490 AddToWorkList(X.Val);
3491 }
3492
Dan Gohmand047c3e2008-03-03 23:51:38 +00003493 APInt SignBit = APInt::getSignBit(MVT::getSizeInBits(VT));
Chris Lattneref26cbc2008-01-27 17:42:27 +00003494 X = DAG.getNode(ISD::AND, VT, X, DAG.getConstant(SignBit, VT));
3495 AddToWorkList(X.Val);
3496
3497 SDOperand Cst = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3498 Cst = DAG.getNode(ISD::AND, VT, Cst, DAG.getConstant(~SignBit, VT));
3499 AddToWorkList(Cst.Val);
3500
3501 return DAG.getNode(ISD::OR, VT, X, Cst);
3502 }
Evan Chengb6290462008-05-12 23:04:07 +00003503
3504 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
3505 if (N0.getOpcode() == ISD::BUILD_PAIR) {
3506 SDOperand CombineLD = CombineConsecutiveLoads(N0.Val, VT);
3507 if (CombineLD.Val)
3508 return CombineLD;
3509 }
Chris Lattneref26cbc2008-01-27 17:42:27 +00003510
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003511 return SDOperand();
3512}
3513
Evan Chengb6290462008-05-12 23:04:07 +00003514SDOperand DAGCombiner::visitBUILD_PAIR(SDNode *N) {
3515 MVT::ValueType VT = N->getValueType(0);
3516 return CombineConsecutiveLoads(N, VT);
3517}
3518
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003519/// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
3520/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
3521/// destination element value type.
3522SDOperand DAGCombiner::
3523ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT::ValueType DstEltVT) {
3524 MVT::ValueType SrcEltVT = BV->getOperand(0).getValueType();
3525
3526 // If this is already the right type, we're done.
3527 if (SrcEltVT == DstEltVT) return SDOperand(BV, 0);
3528
3529 unsigned SrcBitSize = MVT::getSizeInBits(SrcEltVT);
3530 unsigned DstBitSize = MVT::getSizeInBits(DstEltVT);
3531
3532 // If this is a conversion of N elements of one type to N elements of another
3533 // type, convert each element. This handles FP<->INT cases.
3534 if (SrcBitSize == DstBitSize) {
3535 SmallVector<SDOperand, 8> Ops;
3536 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3537 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
3538 AddToWorkList(Ops.back().Val);
3539 }
3540 MVT::ValueType VT =
3541 MVT::getVectorType(DstEltVT,
3542 MVT::getVectorNumElements(BV->getValueType(0)));
3543 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3544 }
3545
3546 // Otherwise, we're growing or shrinking the elements. To avoid having to
3547 // handle annoying details of growing/shrinking FP values, we convert them to
3548 // int first.
3549 if (MVT::isFloatingPoint(SrcEltVT)) {
3550 // Convert the input float vector to a int vector where the elements are the
3551 // same sizes.
3552 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
3553 MVT::ValueType IntVT = SrcEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
3554 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).Val;
3555 SrcEltVT = IntVT;
3556 }
3557
3558 // Now we know the input is an integer vector. If the output is a FP type,
3559 // convert to integer first, then to FP of the right size.
3560 if (MVT::isFloatingPoint(DstEltVT)) {
3561 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
3562 MVT::ValueType TmpVT = DstEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
3563 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).Val;
3564
3565 // Next, convert to FP elements of the same size.
3566 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
3567 }
3568
3569 // Okay, we know the src/dst types are both integers of differing types.
3570 // Handling growing first.
3571 assert(MVT::isInteger(SrcEltVT) && MVT::isInteger(DstEltVT));
3572 if (SrcBitSize < DstBitSize) {
3573 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
3574
3575 SmallVector<SDOperand, 8> Ops;
3576 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
3577 i += NumInputsPerOutput) {
3578 bool isLE = TLI.isLittleEndian();
Dan Gohmand047c3e2008-03-03 23:51:38 +00003579 APInt NewBits = APInt(DstBitSize, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003580 bool EltIsUndef = true;
3581 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
3582 // Shift the previously computed bits over.
3583 NewBits <<= SrcBitSize;
3584 SDOperand Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
3585 if (Op.getOpcode() == ISD::UNDEF) continue;
3586 EltIsUndef = false;
3587
Dan Gohmand047c3e2008-03-03 23:51:38 +00003588 NewBits |=
3589 APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).zext(DstBitSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003590 }
3591
3592 if (EltIsUndef)
3593 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3594 else
3595 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
3596 }
3597
Evan Chengd1045a62008-02-18 23:04:32 +00003598 MVT::ValueType VT = MVT::getVectorType(DstEltVT, Ops.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003599 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3600 }
3601
3602 // Finally, this must be the case where we are shrinking elements: each input
3603 // turns into multiple outputs.
Evan Chengd1045a62008-02-18 23:04:32 +00003604 bool isS2V = ISD::isScalarToVector(BV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003605 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Evan Chengd1045a62008-02-18 23:04:32 +00003606 MVT::ValueType VT = MVT::getVectorType(DstEltVT,
3607 NumOutputsPerInput * BV->getNumOperands());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003608 SmallVector<SDOperand, 8> Ops;
3609 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3610 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
3611 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
3612 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3613 continue;
3614 }
Dan Gohmand047c3e2008-03-03 23:51:38 +00003615 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getAPIntValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003616 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Dan Gohmand047c3e2008-03-03 23:51:38 +00003617 APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003618 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Dan Gohmand047c3e2008-03-03 23:51:38 +00003619 if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
Evan Chengd1045a62008-02-18 23:04:32 +00003620 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
3621 return DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Ops[0]);
Dan Gohmand047c3e2008-03-03 23:51:38 +00003622 OpVal = OpVal.lshr(DstBitSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003623 }
3624
3625 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands9ff8fbf2008-02-11 10:37:04 +00003626 if (TLI.isBigEndian())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003627 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
3628 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003629 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3630}
3631
3632
3633
3634SDOperand DAGCombiner::visitFADD(SDNode *N) {
3635 SDOperand N0 = N->getOperand(0);
3636 SDOperand N1 = N->getOperand(1);
3637 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3638 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3639 MVT::ValueType VT = N->getValueType(0);
3640
3641 // fold vector ops
3642 if (MVT::isVector(VT)) {
3643 SDOperand FoldedVOp = SimplifyVBinOp(N);
3644 if (FoldedVOp.Val) return FoldedVOp;
3645 }
3646
3647 // fold (fadd c1, c2) -> c1+c2
Dale Johannesenb89072e2007-10-16 23:38:29 +00003648 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003649 return DAG.getNode(ISD::FADD, VT, N0, N1);
3650 // canonicalize constant to RHS
3651 if (N0CFP && !N1CFP)
3652 return DAG.getNode(ISD::FADD, VT, N1, N0);
3653 // fold (A + (-B)) -> A-B
Chris Lattnere0992b82008-02-26 07:04:54 +00003654 if (isNegatibleForFree(N1, AfterLegalize) == 2)
3655 return DAG.getNode(ISD::FSUB, VT, N0,
3656 GetNegatedExpression(N1, DAG, AfterLegalize));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003657 // fold ((-A) + B) -> B-A
Chris Lattnere0992b82008-02-26 07:04:54 +00003658 if (isNegatibleForFree(N0, AfterLegalize) == 2)
3659 return DAG.getNode(ISD::FSUB, VT, N1,
3660 GetNegatedExpression(N0, DAG, AfterLegalize));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003661
3662 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
3663 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
3664 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3665 return DAG.getNode(ISD::FADD, VT, N0.getOperand(0),
3666 DAG.getNode(ISD::FADD, VT, N0.getOperand(1), N1));
3667
3668 return SDOperand();
3669}
3670
3671SDOperand DAGCombiner::visitFSUB(SDNode *N) {
3672 SDOperand N0 = N->getOperand(0);
3673 SDOperand N1 = N->getOperand(1);
3674 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3675 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3676 MVT::ValueType VT = N->getValueType(0);
3677
3678 // fold vector ops
3679 if (MVT::isVector(VT)) {
3680 SDOperand FoldedVOp = SimplifyVBinOp(N);
3681 if (FoldedVOp.Val) return FoldedVOp;
3682 }
3683
3684 // fold (fsub c1, c2) -> c1-c2
Dale Johannesenb89072e2007-10-16 23:38:29 +00003685 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003686 return DAG.getNode(ISD::FSUB, VT, N0, N1);
3687 // fold (0-B) -> -B
Dale Johannesen7604c1b2007-08-31 23:34:27 +00003688 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
Chris Lattnere0992b82008-02-26 07:04:54 +00003689 if (isNegatibleForFree(N1, AfterLegalize))
3690 return GetNegatedExpression(N1, DAG, AfterLegalize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003691 return DAG.getNode(ISD::FNEG, VT, N1);
3692 }
3693 // fold (A-(-B)) -> A+B
Chris Lattnere0992b82008-02-26 07:04:54 +00003694 if (isNegatibleForFree(N1, AfterLegalize))
3695 return DAG.getNode(ISD::FADD, VT, N0,
3696 GetNegatedExpression(N1, DAG, AfterLegalize));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003697
3698 return SDOperand();
3699}
3700
3701SDOperand DAGCombiner::visitFMUL(SDNode *N) {
3702 SDOperand N0 = N->getOperand(0);
3703 SDOperand N1 = N->getOperand(1);
3704 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3705 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3706 MVT::ValueType VT = N->getValueType(0);
3707
3708 // fold vector ops
3709 if (MVT::isVector(VT)) {
3710 SDOperand FoldedVOp = SimplifyVBinOp(N);
3711 if (FoldedVOp.Val) return FoldedVOp;
3712 }
3713
3714 // fold (fmul c1, c2) -> c1*c2
Dale Johannesenb89072e2007-10-16 23:38:29 +00003715 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003716 return DAG.getNode(ISD::FMUL, VT, N0, N1);
3717 // canonicalize constant to RHS
3718 if (N0CFP && !N1CFP)
3719 return DAG.getNode(ISD::FMUL, VT, N1, N0);
3720 // fold (fmul X, 2.0) -> (fadd X, X)
3721 if (N1CFP && N1CFP->isExactlyValue(+2.0))
3722 return DAG.getNode(ISD::FADD, VT, N0, N0);
3723 // fold (fmul X, -1.0) -> (fneg X)
3724 if (N1CFP && N1CFP->isExactlyValue(-1.0))
3725 return DAG.getNode(ISD::FNEG, VT, N0);
3726
3727 // -X * -Y -> X*Y
Chris Lattnere0992b82008-02-26 07:04:54 +00003728 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3729 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003730 // Both can be negated for free, check to see if at least one is cheaper
3731 // negated.
3732 if (LHSNeg == 2 || RHSNeg == 2)
Chris Lattnere0992b82008-02-26 07:04:54 +00003733 return DAG.getNode(ISD::FMUL, VT,
3734 GetNegatedExpression(N0, DAG, AfterLegalize),
3735 GetNegatedExpression(N1, DAG, AfterLegalize));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003736 }
3737 }
3738
3739 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
3740 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
3741 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3742 return DAG.getNode(ISD::FMUL, VT, N0.getOperand(0),
3743 DAG.getNode(ISD::FMUL, VT, N0.getOperand(1), N1));
3744
3745 return SDOperand();
3746}
3747
3748SDOperand DAGCombiner::visitFDIV(SDNode *N) {
3749 SDOperand N0 = N->getOperand(0);
3750 SDOperand N1 = N->getOperand(1);
3751 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3752 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3753 MVT::ValueType VT = N->getValueType(0);
3754
3755 // fold vector ops
3756 if (MVT::isVector(VT)) {
3757 SDOperand FoldedVOp = SimplifyVBinOp(N);
3758 if (FoldedVOp.Val) return FoldedVOp;
3759 }
3760
3761 // fold (fdiv c1, c2) -> c1/c2
Dale Johannesenb89072e2007-10-16 23:38:29 +00003762 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003763 return DAG.getNode(ISD::FDIV, VT, N0, N1);
3764
3765
3766 // -X / -Y -> X*Y
Chris Lattnere0992b82008-02-26 07:04:54 +00003767 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3768 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003769 // Both can be negated for free, check to see if at least one is cheaper
3770 // negated.
3771 if (LHSNeg == 2 || RHSNeg == 2)
Chris Lattnere0992b82008-02-26 07:04:54 +00003772 return DAG.getNode(ISD::FDIV, VT,
3773 GetNegatedExpression(N0, DAG, AfterLegalize),
3774 GetNegatedExpression(N1, DAG, AfterLegalize));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003775 }
3776 }
3777
3778 return SDOperand();
3779}
3780
3781SDOperand DAGCombiner::visitFREM(SDNode *N) {
3782 SDOperand N0 = N->getOperand(0);
3783 SDOperand N1 = N->getOperand(1);
3784 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3785 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3786 MVT::ValueType VT = N->getValueType(0);
3787
3788 // fold (frem c1, c2) -> fmod(c1,c2)
Dale Johannesenb89072e2007-10-16 23:38:29 +00003789 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003790 return DAG.getNode(ISD::FREM, VT, N0, N1);
3791
3792 return SDOperand();
3793}
3794
3795SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
3796 SDOperand N0 = N->getOperand(0);
3797 SDOperand N1 = N->getOperand(1);
3798 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3799 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3800 MVT::ValueType VT = N->getValueType(0);
3801
Dale Johannesenb89072e2007-10-16 23:38:29 +00003802 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003803 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
3804
3805 if (N1CFP) {
Dale Johannesenc53301c2007-08-26 01:18:27 +00003806 const APFloat& V = N1CFP->getValueAPF();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003807 // copysign(x, c1) -> fabs(x) iff ispos(c1)
3808 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dale Johannesen7f2c1d12007-08-25 22:10:57 +00003809 if (!V.isNegative())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003810 return DAG.getNode(ISD::FABS, VT, N0);
3811 else
3812 return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
3813 }
3814
3815 // copysign(fabs(x), y) -> copysign(x, y)
3816 // copysign(fneg(x), y) -> copysign(x, y)
3817 // copysign(copysign(x,z), y) -> copysign(x, y)
3818 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
3819 N0.getOpcode() == ISD::FCOPYSIGN)
3820 return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
3821
3822 // copysign(x, abs(y)) -> abs(x)
3823 if (N1.getOpcode() == ISD::FABS)
3824 return DAG.getNode(ISD::FABS, VT, N0);
3825
3826 // copysign(x, copysign(y,z)) -> copysign(x, z)
3827 if (N1.getOpcode() == ISD::FCOPYSIGN)
3828 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
3829
3830 // copysign(x, fp_extend(y)) -> copysign(x, y)
3831 // copysign(x, fp_round(y)) -> copysign(x, y)
3832 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
3833 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
3834
3835 return SDOperand();
3836}
3837
3838
3839
3840SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
3841 SDOperand N0 = N->getOperand(0);
3842 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3843 MVT::ValueType VT = N->getValueType(0);
3844
3845 // fold (sint_to_fp c1) -> c1fp
Dale Johannesenb89072e2007-10-16 23:38:29 +00003846 if (N0C && N0.getValueType() != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003847 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
3848 return SDOperand();
3849}
3850
3851SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
3852 SDOperand N0 = N->getOperand(0);
3853 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3854 MVT::ValueType VT = N->getValueType(0);
3855
3856 // fold (uint_to_fp c1) -> c1fp
Dale Johannesenb89072e2007-10-16 23:38:29 +00003857 if (N0C && N0.getValueType() != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003858 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
3859 return SDOperand();
3860}
3861
3862SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
3863 SDOperand N0 = N->getOperand(0);
3864 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3865 MVT::ValueType VT = N->getValueType(0);
3866
3867 // fold (fp_to_sint c1fp) -> c1
3868 if (N0CFP)
3869 return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
3870 return SDOperand();
3871}
3872
3873SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
3874 SDOperand N0 = N->getOperand(0);
3875 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3876 MVT::ValueType VT = N->getValueType(0);
3877
3878 // fold (fp_to_uint c1fp) -> c1
Dale Johannesenb89072e2007-10-16 23:38:29 +00003879 if (N0CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003880 return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
3881 return SDOperand();
3882}
3883
3884SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
3885 SDOperand N0 = N->getOperand(0);
Chris Lattner5872a362008-01-17 07:00:52 +00003886 SDOperand N1 = N->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003887 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3888 MVT::ValueType VT = N->getValueType(0);
3889
3890 // fold (fp_round c1fp) -> c1fp
Dale Johannesenb89072e2007-10-16 23:38:29 +00003891 if (N0CFP && N0.getValueType() != MVT::ppcf128)
Chris Lattner5872a362008-01-17 07:00:52 +00003892 return DAG.getNode(ISD::FP_ROUND, VT, N0, N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003893
3894 // fold (fp_round (fp_extend x)) -> x
3895 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
3896 return N0.getOperand(0);
3897
Chris Lattner7afb8552008-01-24 06:45:35 +00003898 // fold (fp_round (fp_round x)) -> (fp_round x)
3899 if (N0.getOpcode() == ISD::FP_ROUND) {
3900 // This is a value preserving truncation if both round's are.
3901 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
3902 N0.Val->getConstantOperandVal(1) == 1;
3903 return DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0),
3904 DAG.getIntPtrConstant(IsTrunc));
3905 }
3906
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003907 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
3908 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
Chris Lattner5872a362008-01-17 07:00:52 +00003909 SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0), N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003910 AddToWorkList(Tmp.Val);
3911 return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
3912 }
3913
3914 return SDOperand();
3915}
3916
3917SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
3918 SDOperand N0 = N->getOperand(0);
3919 MVT::ValueType VT = N->getValueType(0);
3920 MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3921 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3922
3923 // fold (fp_round_inreg c1fp) -> c1fp
3924 if (N0CFP) {
Dale Johannesen7604c1b2007-08-31 23:34:27 +00003925 SDOperand Round = DAG.getConstantFP(N0CFP->getValueAPF(), EVT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003926 return DAG.getNode(ISD::FP_EXTEND, VT, Round);
3927 }
3928 return SDOperand();
3929}
3930
3931SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
3932 SDOperand N0 = N->getOperand(0);
3933 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3934 MVT::ValueType VT = N->getValueType(0);
3935
Chris Lattner6f981fc2007-12-29 06:55:23 +00003936 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Roman Levenstein98b8fcb2008-04-16 16:15:27 +00003937 if (N->hasOneUse() &&
3938 N->use_begin()->getSDOperand().getOpcode() == ISD::FP_ROUND)
Chris Lattner6f981fc2007-12-29 06:55:23 +00003939 return SDOperand();
Chris Lattner5872a362008-01-17 07:00:52 +00003940
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003941 // fold (fp_extend c1fp) -> c1fp
Dale Johannesenb89072e2007-10-16 23:38:29 +00003942 if (N0CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003943 return DAG.getNode(ISD::FP_EXTEND, VT, N0);
Chris Lattner5872a362008-01-17 07:00:52 +00003944
3945 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
3946 // value of X.
3947 if (N0.getOpcode() == ISD::FP_ROUND && N0.Val->getConstantOperandVal(1) == 1){
3948 SDOperand In = N0.getOperand(0);
3949 if (In.getValueType() == VT) return In;
3950 if (VT < In.getValueType())
3951 return DAG.getNode(ISD::FP_ROUND, VT, In, N0.getOperand(1));
3952 return DAG.getNode(ISD::FP_EXTEND, VT, In);
3953 }
3954
3955 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Dale Johannesen2550e3a2007-10-19 20:29:00 +00003956 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003957 (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3958 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3959 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3960 LN0->getBasePtr(), LN0->getSrcValue(),
3961 LN0->getSrcValueOffset(),
3962 N0.getValueType(),
3963 LN0->isVolatile(),
3964 LN0->getAlignment());
3965 CombineTo(N, ExtLoad);
Chris Lattner5872a362008-01-17 07:00:52 +00003966 CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad,
3967 DAG.getIntPtrConstant(1)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003968 ExtLoad.getValue(1));
3969 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3970 }
3971
3972
3973 return SDOperand();
3974}
3975
3976SDOperand DAGCombiner::visitFNEG(SDNode *N) {
3977 SDOperand N0 = N->getOperand(0);
3978
Chris Lattnere0992b82008-02-26 07:04:54 +00003979 if (isNegatibleForFree(N0, AfterLegalize))
3980 return GetNegatedExpression(N0, DAG, AfterLegalize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003981
Chris Lattneref26cbc2008-01-27 17:42:27 +00003982 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
3983 // constant pool values.
Chris Lattner336672f2008-01-27 23:32:17 +00003984 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
3985 MVT::isInteger(N0.getOperand(0).getValueType()) &&
3986 !MVT::isVector(N0.getOperand(0).getValueType())) {
Chris Lattneref26cbc2008-01-27 17:42:27 +00003987 SDOperand Int = N0.getOperand(0);
3988 MVT::ValueType IntVT = Int.getValueType();
3989 if (MVT::isInteger(IntVT) && !MVT::isVector(IntVT)) {
3990 Int = DAG.getNode(ISD::XOR, IntVT, Int,
3991 DAG.getConstant(MVT::getIntVTSignBit(IntVT), IntVT));
3992 AddToWorkList(Int.Val);
3993 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
3994 }
3995 }
3996
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003997 return SDOperand();
3998}
3999
4000SDOperand DAGCombiner::visitFABS(SDNode *N) {
4001 SDOperand N0 = N->getOperand(0);
4002 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4003 MVT::ValueType VT = N->getValueType(0);
4004
4005 // fold (fabs c1) -> fabs(c1)
Dale Johannesenb89072e2007-10-16 23:38:29 +00004006 if (N0CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004007 return DAG.getNode(ISD::FABS, VT, N0);
4008 // fold (fabs (fabs x)) -> (fabs x)
4009 if (N0.getOpcode() == ISD::FABS)
4010 return N->getOperand(0);
4011 // fold (fabs (fneg x)) -> (fabs x)
4012 // fold (fabs (fcopysign x, y)) -> (fabs x)
4013 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
4014 return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
4015
Chris Lattneref26cbc2008-01-27 17:42:27 +00004016 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
4017 // constant pool values.
Chris Lattner336672f2008-01-27 23:32:17 +00004018 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
4019 MVT::isInteger(N0.getOperand(0).getValueType()) &&
4020 !MVT::isVector(N0.getOperand(0).getValueType())) {
Chris Lattneref26cbc2008-01-27 17:42:27 +00004021 SDOperand Int = N0.getOperand(0);
4022 MVT::ValueType IntVT = Int.getValueType();
4023 if (MVT::isInteger(IntVT) && !MVT::isVector(IntVT)) {
4024 Int = DAG.getNode(ISD::AND, IntVT, Int,
4025 DAG.getConstant(~MVT::getIntVTSignBit(IntVT), IntVT));
4026 AddToWorkList(Int.Val);
4027 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
4028 }
4029 }
4030
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004031 return SDOperand();
4032}
4033
4034SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
4035 SDOperand Chain = N->getOperand(0);
4036 SDOperand N1 = N->getOperand(1);
4037 SDOperand N2 = N->getOperand(2);
4038 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4039
4040 // never taken branch, fold to chain
4041 if (N1C && N1C->isNullValue())
4042 return Chain;
4043 // unconditional branch
Dan Gohman9d24dc72008-03-13 22:13:53 +00004044 if (N1C && N1C->getAPIntValue() == 1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004045 return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
4046 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
4047 // on the target.
4048 if (N1.getOpcode() == ISD::SETCC &&
4049 TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
4050 return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
4051 N1.getOperand(0), N1.getOperand(1), N2);
4052 }
4053 return SDOperand();
4054}
4055
4056// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
4057//
4058SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
4059 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
4060 SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
4061
4062 // Use SimplifySetCC to simplify SETCC's.
4063 SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
4064 if (Simp.Val) AddToWorkList(Simp.Val);
4065
4066 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
4067
4068 // fold br_cc true, dest -> br dest (unconditional branch)
Dan Gohman9d24dc72008-03-13 22:13:53 +00004069 if (SCCC && !SCCC->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004070 return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
4071 N->getOperand(4));
4072 // fold br_cc false, dest -> unconditional fall through
4073 if (SCCC && SCCC->isNullValue())
4074 return N->getOperand(0);
4075
4076 // fold to a simpler setcc
4077 if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
4078 return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
4079 Simp.getOperand(2), Simp.getOperand(0),
4080 Simp.getOperand(1), N->getOperand(4));
4081 return SDOperand();
4082}
4083
4084
4085/// CombineToPreIndexedLoadStore - Try turning a load / store and a
4086/// pre-indexed load / store when the base pointer is a add or subtract
4087/// and it has other uses besides the load / store. After the
4088/// transformation, the new indexed load / store has effectively folded
4089/// the add / subtract in and all of its other uses are redirected to the
4090/// new load / store.
4091bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
4092 if (!AfterLegalize)
4093 return false;
4094
4095 bool isLoad = true;
4096 SDOperand Ptr;
4097 MVT::ValueType VT;
4098 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner3bc08502008-01-17 19:59:44 +00004099 if (LD->isIndexed())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004100 return false;
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004101 VT = LD->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004102 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
4103 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
4104 return false;
4105 Ptr = LD->getBasePtr();
4106 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner3bc08502008-01-17 19:59:44 +00004107 if (ST->isIndexed())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004108 return false;
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004109 VT = ST->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004110 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
4111 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
4112 return false;
4113 Ptr = ST->getBasePtr();
4114 isLoad = false;
4115 } else
4116 return false;
4117
4118 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
4119 // out. There is no reason to make this a preinc/predec.
4120 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
4121 Ptr.Val->hasOneUse())
4122 return false;
4123
4124 // Ask the target to do addressing mode selection.
4125 SDOperand BasePtr;
4126 SDOperand Offset;
4127 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4128 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
4129 return false;
4130 // Don't create a indexed load / store with zero offset.
4131 if (isa<ConstantSDNode>(Offset) &&
Dan Gohman9d24dc72008-03-13 22:13:53 +00004132 cast<ConstantSDNode>(Offset)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004133 return false;
4134
4135 // Try turning it into a pre-indexed load / store except when:
4136 // 1) The new base ptr is a frame index.
4137 // 2) If N is a store and the new base ptr is either the same as or is a
4138 // predecessor of the value being stored.
4139 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
4140 // that would create a cycle.
4141 // 4) All uses are load / store ops that use it as old base ptr.
4142
4143 // Check #1. Preinc'ing a frame index would require copying the stack pointer
4144 // (plus the implicit offset) to a register to preinc anyway.
4145 if (isa<FrameIndexSDNode>(BasePtr))
4146 return false;
4147
4148 // Check #2.
4149 if (!isLoad) {
4150 SDOperand Val = cast<StoreSDNode>(N)->getValue();
Evan Chengd9387682008-03-04 00:41:45 +00004151 if (Val == BasePtr || BasePtr.Val->isPredecessorOf(Val.Val))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004152 return false;
4153 }
4154
4155 // Now check for #3 and #4.
4156 bool RealUse = false;
4157 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4158 E = Ptr.Val->use_end(); I != E; ++I) {
Roman Levenstein05650fd2008-04-07 10:06:32 +00004159 SDNode *Use = I->getUser();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004160 if (Use == N)
4161 continue;
Evan Chengd9387682008-03-04 00:41:45 +00004162 if (Use->isPredecessorOf(N))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004163 return false;
4164
4165 if (!((Use->getOpcode() == ISD::LOAD &&
4166 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
Anton Korobeynikov53422f62008-02-20 11:10:28 +00004167 (Use->getOpcode() == ISD::STORE &&
4168 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004169 RealUse = true;
4170 }
4171 if (!RealUse)
4172 return false;
4173
4174 SDOperand Result;
4175 if (isLoad)
4176 Result = DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM);
4177 else
4178 Result = DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4179 ++PreIndexedNodes;
4180 ++NodesCombined;
4181 DOUT << "\nReplacing.4 "; DEBUG(N->dump(&DAG));
4182 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4183 DOUT << '\n';
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004184 WorkListRemover DeadNodes(*this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004185 if (isLoad) {
4186 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004187 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004188 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004189 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004190 } else {
4191 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004192 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004193 }
4194
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004195 // Finally, since the node is now dead, remove it from the graph.
4196 DAG.DeleteNode(N);
4197
4198 // Replace the uses of Ptr with uses of the updated base value.
4199 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004200 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004201 removeFromWorkList(Ptr.Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004202 DAG.DeleteNode(Ptr.Val);
4203
4204 return true;
4205}
4206
4207/// CombineToPostIndexedLoadStore - Try combine a load / store with a
4208/// add / sub of the base pointer node into a post-indexed load / store.
4209/// The transformation folded the add / subtract into the new indexed
4210/// load / store effectively and all of its uses are redirected to the
4211/// new load / store.
4212bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
4213 if (!AfterLegalize)
4214 return false;
4215
4216 bool isLoad = true;
4217 SDOperand Ptr;
4218 MVT::ValueType VT;
4219 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner3bc08502008-01-17 19:59:44 +00004220 if (LD->isIndexed())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004221 return false;
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004222 VT = LD->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004223 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
4224 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
4225 return false;
4226 Ptr = LD->getBasePtr();
4227 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner3bc08502008-01-17 19:59:44 +00004228 if (ST->isIndexed())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004229 return false;
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004230 VT = ST->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004231 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
4232 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
4233 return false;
4234 Ptr = ST->getBasePtr();
4235 isLoad = false;
4236 } else
4237 return false;
4238
4239 if (Ptr.Val->hasOneUse())
4240 return false;
4241
4242 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4243 E = Ptr.Val->use_end(); I != E; ++I) {
Roman Levenstein05650fd2008-04-07 10:06:32 +00004244 SDNode *Op = I->getUser();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004245 if (Op == N ||
4246 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
4247 continue;
4248
4249 SDOperand BasePtr;
4250 SDOperand Offset;
4251 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4252 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
4253 if (Ptr == Offset)
4254 std::swap(BasePtr, Offset);
4255 if (Ptr != BasePtr)
4256 continue;
4257 // Don't create a indexed load / store with zero offset.
4258 if (isa<ConstantSDNode>(Offset) &&
Dan Gohman9d24dc72008-03-13 22:13:53 +00004259 cast<ConstantSDNode>(Offset)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004260 continue;
4261
4262 // Try turning it into a post-indexed load / store except when
4263 // 1) All uses are load / store ops that use it as base ptr.
4264 // 2) Op must be independent of N, i.e. Op is neither a predecessor
4265 // nor a successor of N. Otherwise, if Op is folded that would
4266 // create a cycle.
4267
4268 // Check for #1.
4269 bool TryNext = false;
4270 for (SDNode::use_iterator II = BasePtr.Val->use_begin(),
4271 EE = BasePtr.Val->use_end(); II != EE; ++II) {
Roman Levenstein05650fd2008-04-07 10:06:32 +00004272 SDNode *Use = II->getUser();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004273 if (Use == Ptr.Val)
4274 continue;
4275
4276 // If all the uses are load / store addresses, then don't do the
4277 // transformation.
4278 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
4279 bool RealUse = false;
4280 for (SDNode::use_iterator III = Use->use_begin(),
4281 EEE = Use->use_end(); III != EEE; ++III) {
Roman Levenstein05650fd2008-04-07 10:06:32 +00004282 SDNode *UseUse = III->getUser();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004283 if (!((UseUse->getOpcode() == ISD::LOAD &&
4284 cast<LoadSDNode>(UseUse)->getBasePtr().Val == Use) ||
Anton Korobeynikov53422f62008-02-20 11:10:28 +00004285 (UseUse->getOpcode() == ISD::STORE &&
4286 cast<StoreSDNode>(UseUse)->getBasePtr().Val == Use)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004287 RealUse = true;
4288 }
4289
4290 if (!RealUse) {
4291 TryNext = true;
4292 break;
4293 }
4294 }
4295 }
4296 if (TryNext)
4297 continue;
4298
4299 // Check for #2
Evan Chengd9387682008-03-04 00:41:45 +00004300 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004301 SDOperand Result = isLoad
4302 ? DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM)
4303 : DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4304 ++PostIndexedNodes;
4305 ++NodesCombined;
4306 DOUT << "\nReplacing.5 "; DEBUG(N->dump(&DAG));
4307 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4308 DOUT << '\n';
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004309 WorkListRemover DeadNodes(*this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004310 if (isLoad) {
4311 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004312 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004313 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004314 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004315 } else {
4316 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004317 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004318 }
4319
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004320 // Finally, since the node is now dead, remove it from the graph.
4321 DAG.DeleteNode(N);
4322
4323 // Replace the uses of Use with uses of the updated base value.
4324 DAG.ReplaceAllUsesOfValueWith(SDOperand(Op, 0),
4325 Result.getValue(isLoad ? 1 : 0),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004326 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004327 removeFromWorkList(Op);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004328 DAG.DeleteNode(Op);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004329 return true;
4330 }
4331 }
4332 }
4333 return false;
4334}
4335
Chris Lattner4e137af2008-01-25 07:20:16 +00004336/// InferAlignment - If we can infer some alignment information from this
4337/// pointer, return it.
4338static unsigned InferAlignment(SDOperand Ptr, SelectionDAG &DAG) {
4339 // If this is a direct reference to a stack slot, use information about the
4340 // stack slot's alignment.
Chris Lattner1e3362f2008-01-26 19:45:50 +00004341 int FrameIdx = 1 << 31;
4342 int64_t FrameOffset = 0;
Chris Lattner4e137af2008-01-25 07:20:16 +00004343 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
Chris Lattner1e3362f2008-01-26 19:45:50 +00004344 FrameIdx = FI->getIndex();
4345 } else if (Ptr.getOpcode() == ISD::ADD &&
4346 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4347 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4348 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4349 FrameOffset = Ptr.getConstantOperandVal(1);
Chris Lattner4e137af2008-01-25 07:20:16 +00004350 }
Chris Lattner1e3362f2008-01-26 19:45:50 +00004351
4352 if (FrameIdx != (1 << 31)) {
4353 // FIXME: Handle FI+CST.
4354 const MachineFrameInfo &MFI = *DAG.getMachineFunction().getFrameInfo();
4355 if (MFI.isFixedObjectIndex(FrameIdx)) {
4356 int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx);
4357
4358 // The alignment of the frame index can be determined from its offset from
4359 // the incoming frame position. If the frame object is at offset 32 and
4360 // the stack is guaranteed to be 16-byte aligned, then we know that the
4361 // object is 16-byte aligned.
4362 unsigned StackAlign = DAG.getTarget().getFrameInfo()->getStackAlignment();
4363 unsigned Align = MinAlign(ObjectOffset, StackAlign);
4364
4365 // Finally, the frame object itself may have a known alignment. Factor
4366 // the alignment + offset into a new alignment. For example, if we know
4367 // the FI is 8 byte aligned, but the pointer is 4 off, we really have a
4368 // 4-byte alignment of the resultant pointer. Likewise align 4 + 4-byte
4369 // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
4370 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
4371 FrameOffset);
4372 return std::max(Align, FIInfoAlign);
4373 }
4374 }
Chris Lattner4e137af2008-01-25 07:20:16 +00004375
4376 return 0;
4377}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004378
4379SDOperand DAGCombiner::visitLOAD(SDNode *N) {
4380 LoadSDNode *LD = cast<LoadSDNode>(N);
4381 SDOperand Chain = LD->getChain();
4382 SDOperand Ptr = LD->getBasePtr();
Chris Lattner4e137af2008-01-25 07:20:16 +00004383
4384 // Try to infer better alignment information than the load already has.
4385 if (LD->isUnindexed()) {
4386 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4387 if (Align > LD->getAlignment())
4388 return DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
4389 Chain, Ptr, LD->getSrcValue(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004390 LD->getSrcValueOffset(), LD->getMemoryVT(),
Chris Lattner4e137af2008-01-25 07:20:16 +00004391 LD->isVolatile(), Align);
4392 }
4393 }
4394
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004395
4396 // If load is not volatile and there are no uses of the loaded value (and
4397 // the updated indexed value in case of indexed loads), change uses of the
4398 // chain value into uses of the chain input (i.e. delete the dead load).
4399 if (!LD->isVolatile()) {
4400 if (N->getValueType(1) == MVT::Other) {
4401 // Unindexed loads.
Evan Chenge8b886a2008-01-16 23:11:54 +00004402 if (N->hasNUsesOfValue(0, 0)) {
4403 // It's not safe to use the two value CombineTo variant here. e.g.
4404 // v1, chain2 = load chain1, loc
4405 // v2, chain3 = load chain2, loc
4406 // v3 = add v2, c
Chris Lattnerbb67c192008-01-24 07:57:06 +00004407 // Now we replace use of chain2 with chain1. This makes the second load
4408 // isomorphic to the one we are deleting, and thus makes this load live.
Evan Chenge8b886a2008-01-16 23:11:54 +00004409 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
Chris Lattnerbb67c192008-01-24 07:57:06 +00004410 DOUT << "\nWith chain: "; DEBUG(Chain.Val->dump(&DAG));
4411 DOUT << "\n";
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004412 WorkListRemover DeadNodes(*this);
4413 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Chain, &DeadNodes);
Chris Lattnerbb67c192008-01-24 07:57:06 +00004414 if (N->use_empty()) {
4415 removeFromWorkList(N);
4416 DAG.DeleteNode(N);
4417 }
Evan Chenge8b886a2008-01-16 23:11:54 +00004418 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
4419 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004420 } else {
4421 // Indexed loads.
4422 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
4423 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
Evan Chenge8b886a2008-01-16 23:11:54 +00004424 SDOperand Undef = DAG.getNode(ISD::UNDEF, N->getValueType(0));
4425 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4426 DOUT << "\nWith: "; DEBUG(Undef.Val->dump(&DAG));
4427 DOUT << " and 2 other values\n";
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004428 WorkListRemover DeadNodes(*this);
4429 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Undef, &DeadNodes);
Evan Chenge8b886a2008-01-16 23:11:54 +00004430 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1),
Chris Lattner667f9c12008-01-17 07:20:38 +00004431 DAG.getNode(ISD::UNDEF, N->getValueType(1)),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004432 &DeadNodes);
4433 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 2), Chain, &DeadNodes);
Evan Chenge8b886a2008-01-16 23:11:54 +00004434 removeFromWorkList(N);
Evan Chenge8b886a2008-01-16 23:11:54 +00004435 DAG.DeleteNode(N);
4436 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004437 }
4438 }
4439 }
4440
4441 // If this load is directly stored, replace the load value with the stored
4442 // value.
4443 // TODO: Handle store large -> read small portion.
4444 // TODO: Handle TRUNCSTORE/LOADEXT
Dan Gohman729b5ff2008-03-31 20:32:52 +00004445 if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
4446 !LD->isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004447 if (ISD::isNON_TRUNCStore(Chain.Val)) {
4448 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
4449 if (PrevST->getBasePtr() == Ptr &&
4450 PrevST->getValue().getValueType() == N->getValueType(0))
4451 return CombineTo(N, Chain.getOperand(1), Chain);
4452 }
4453 }
4454
4455 if (CombinerAA) {
4456 // Walk up chain skipping non-aliasing memory nodes.
4457 SDOperand BetterChain = FindBetterChain(N, Chain);
4458
4459 // If there is a better chain.
4460 if (Chain != BetterChain) {
4461 SDOperand ReplLoad;
4462
4463 // Replace the chain to void dependency.
4464 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4465 ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
Duncan Sandsa3691432007-10-28 12:59:45 +00004466 LD->getSrcValue(), LD->getSrcValueOffset(),
4467 LD->isVolatile(), LD->getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004468 } else {
4469 ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
4470 LD->getValueType(0),
4471 BetterChain, Ptr, LD->getSrcValue(),
4472 LD->getSrcValueOffset(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004473 LD->getMemoryVT(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004474 LD->isVolatile(),
4475 LD->getAlignment());
4476 }
4477
4478 // Create token factor to keep old chain connected.
4479 SDOperand Token = DAG.getNode(ISD::TokenFactor, MVT::Other,
4480 Chain, ReplLoad.getValue(1));
4481
4482 // Replace uses with load result and token factor. Don't add users
4483 // to work list.
4484 return CombineTo(N, ReplLoad.getValue(0), Token, false);
4485 }
4486 }
4487
4488 // Try transforming N to an indexed load.
4489 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4490 return SDOperand(N, 0);
4491
4492 return SDOperand();
4493}
4494
Chris Lattner2e023772008-01-08 23:08:06 +00004495
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004496SDOperand DAGCombiner::visitSTORE(SDNode *N) {
4497 StoreSDNode *ST = cast<StoreSDNode>(N);
4498 SDOperand Chain = ST->getChain();
4499 SDOperand Value = ST->getValue();
4500 SDOperand Ptr = ST->getBasePtr();
4501
Chris Lattner4e137af2008-01-25 07:20:16 +00004502 // Try to infer better alignment information than the store already has.
4503 if (ST->isUnindexed()) {
4504 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4505 if (Align > ST->getAlignment())
4506 return DAG.getTruncStore(Chain, Value, Ptr, ST->getSrcValue(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004507 ST->getSrcValueOffset(), ST->getMemoryVT(),
Chris Lattner4e137af2008-01-25 07:20:16 +00004508 ST->isVolatile(), Align);
4509 }
4510 }
4511
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004512 // If this is a store of a bit convert, store the input value if the
4513 // resultant store does not need a higher alignment than the original.
4514 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
Chris Lattner3bc08502008-01-17 19:59:44 +00004515 ST->isUnindexed()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004516 unsigned Align = ST->getAlignment();
4517 MVT::ValueType SVT = Value.getOperand(0).getValueType();
4518 unsigned OrigAlign = TLI.getTargetMachine().getTargetData()->
4519 getABITypeAlignment(MVT::getTypeForValueType(SVT));
4520 if (Align <= OrigAlign && TLI.isOperationLegal(ISD::STORE, SVT))
4521 return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4522 ST->getSrcValueOffset(), ST->isVolatile(), Align);
4523 }
4524
4525 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
4526 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
4527 if (Value.getOpcode() != ISD::TargetConstantFP) {
4528 SDOperand Tmp;
4529 switch (CFP->getValueType(0)) {
4530 default: assert(0 && "Unknown FP type");
Dale Johannesen1b4181d2007-09-18 18:36:59 +00004531 case MVT::f80: // We don't do this for these yet.
4532 case MVT::f128:
4533 case MVT::ppcf128:
4534 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004535 case MVT::f32:
4536 if (!AfterLegalize || TLI.isTypeLegal(MVT::i32)) {
Dale Johannesenfbd9cda2007-09-12 03:30:33 +00004537 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
4538 convertToAPInt().getZExtValue(), MVT::i32);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004539 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4540 ST->getSrcValueOffset(), ST->isVolatile(),
4541 ST->getAlignment());
4542 }
4543 break;
4544 case MVT::f64:
4545 if (!AfterLegalize || TLI.isTypeLegal(MVT::i64)) {
Dale Johannesenfbd9cda2007-09-12 03:30:33 +00004546 Tmp = DAG.getConstant(CFP->getValueAPF().convertToAPInt().
4547 getZExtValue(), MVT::i64);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004548 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4549 ST->getSrcValueOffset(), ST->isVolatile(),
4550 ST->getAlignment());
4551 } else if (TLI.isTypeLegal(MVT::i32)) {
Duncan Sandsa3691432007-10-28 12:59:45 +00004552 // Many FP stores are not made apparent until after legalize, e.g. for
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004553 // argument passing. Since this is so common, custom legalize the
4554 // 64-bit integer store into two 32-bit stores.
Dale Johannesenfbd9cda2007-09-12 03:30:33 +00004555 uint64_t Val = CFP->getValueAPF().convertToAPInt().getZExtValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004556 SDOperand Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
4557 SDOperand Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands9ff8fbf2008-02-11 10:37:04 +00004558 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004559
4560 int SVOffset = ST->getSrcValueOffset();
4561 unsigned Alignment = ST->getAlignment();
4562 bool isVolatile = ST->isVolatile();
4563
4564 SDOperand St0 = DAG.getStore(Chain, Lo, Ptr, ST->getSrcValue(),
4565 ST->getSrcValueOffset(),
4566 isVolatile, ST->getAlignment());
4567 Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4568 DAG.getConstant(4, Ptr.getValueType()));
4569 SVOffset += 4;
Duncan Sandsa3691432007-10-28 12:59:45 +00004570 Alignment = MinAlign(Alignment, 4U);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004571 SDOperand St1 = DAG.getStore(Chain, Hi, Ptr, ST->getSrcValue(),
4572 SVOffset, isVolatile, Alignment);
4573 return DAG.getNode(ISD::TokenFactor, MVT::Other, St0, St1);
4574 }
4575 break;
4576 }
4577 }
4578 }
4579
4580 if (CombinerAA) {
4581 // Walk up chain skipping non-aliasing memory nodes.
4582 SDOperand BetterChain = FindBetterChain(N, Chain);
4583
4584 // If there is a better chain.
4585 if (Chain != BetterChain) {
4586 // Replace the chain to avoid dependency.
4587 SDOperand ReplStore;
4588 if (ST->isTruncatingStore()) {
4589 ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
Chris Lattner667f9c12008-01-17 07:20:38 +00004590 ST->getSrcValue(),ST->getSrcValueOffset(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004591 ST->getMemoryVT(),
Chris Lattner667f9c12008-01-17 07:20:38 +00004592 ST->isVolatile(), ST->getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004593 } else {
4594 ReplStore = DAG.getStore(BetterChain, Value, Ptr,
Chris Lattner667f9c12008-01-17 07:20:38 +00004595 ST->getSrcValue(), ST->getSrcValueOffset(),
4596 ST->isVolatile(), ST->getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004597 }
4598
4599 // Create token to keep both nodes around.
4600 SDOperand Token =
4601 DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore);
4602
4603 // Don't add users to work list.
4604 return CombineTo(N, Token, false);
4605 }
4606 }
4607
4608 // Try transforming N to an indexed store.
4609 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4610 return SDOperand(N, 0);
4611
Chris Lattner447d8e82007-12-29 06:26:16 +00004612 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner3bc08502008-01-17 19:59:44 +00004613 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Chris Lattnere8671c52007-10-13 06:35:54 +00004614 MVT::isInteger(Value.getValueType())) {
4615 // See if we can simplify the input to this truncstore with knowledge that
4616 // only the low bits are being used. For example:
4617 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
4618 SDOperand Shorter =
Dan Gohman07961cd2008-02-25 21:11:39 +00004619 GetDemandedBits(Value,
4620 APInt::getLowBitsSet(Value.getValueSizeInBits(),
4621 MVT::getSizeInBits(ST->getMemoryVT())));
Chris Lattnere8671c52007-10-13 06:35:54 +00004622 AddToWorkList(Value.Val);
4623 if (Shorter.Val)
4624 return DAG.getTruncStore(Chain, Shorter, Ptr, ST->getSrcValue(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004625 ST->getSrcValueOffset(), ST->getMemoryVT(),
Chris Lattnere8671c52007-10-13 06:35:54 +00004626 ST->isVolatile(), ST->getAlignment());
Chris Lattnerb77ea552007-10-13 06:58:48 +00004627
4628 // Otherwise, see if we can simplify the operation with
4629 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohman11607792008-02-27 00:25:32 +00004630 if (SimplifyDemandedBits(Value,
4631 APInt::getLowBitsSet(
4632 Value.getValueSizeInBits(),
4633 MVT::getSizeInBits(ST->getMemoryVT()))))
Chris Lattnerb77ea552007-10-13 06:58:48 +00004634 return SDOperand(N, 0);
Chris Lattnere8671c52007-10-13 06:35:54 +00004635 }
4636
Chris Lattner447d8e82007-12-29 06:26:16 +00004637 // If this is a load followed by a store to the same location, then the store
4638 // is dead/noop.
4639 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004640 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner3bc08502008-01-17 19:59:44 +00004641 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner2e023772008-01-08 23:08:06 +00004642 // There can't be any side effects between the load and store, such as
4643 // a call or store.
Chris Lattner10d94f92008-01-16 05:49:24 +00004644 Chain.reachesChainWithoutSideEffects(SDOperand(Ld, 1))) {
Chris Lattner447d8e82007-12-29 06:26:16 +00004645 // The store is dead, remove it.
4646 return Chain;
4647 }
4648 }
4649
Chris Lattner3bc08502008-01-17 19:59:44 +00004650 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
4651 // truncating store. We can do this even if this is already a truncstore.
4652 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
4653 && TLI.isTypeLegal(Value.getOperand(0).getValueType()) &&
4654 Value.Val->hasOneUse() && ST->isUnindexed() &&
4655 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004656 ST->getMemoryVT())) {
Chris Lattner3bc08502008-01-17 19:59:44 +00004657 return DAG.getTruncStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004658 ST->getSrcValueOffset(), ST->getMemoryVT(),
Chris Lattner3bc08502008-01-17 19:59:44 +00004659 ST->isVolatile(), ST->getAlignment());
4660 }
4661
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004662 return SDOperand();
4663}
4664
4665SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
4666 SDOperand InVec = N->getOperand(0);
4667 SDOperand InVal = N->getOperand(1);
4668 SDOperand EltNo = N->getOperand(2);
4669
4670 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
4671 // vector with the inserted element.
4672 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
4673 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4674 SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
4675 if (Elt < Ops.size())
4676 Ops[Elt] = InVal;
4677 return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
4678 &Ops[0], Ops.size());
4679 }
4680
4681 return SDOperand();
4682}
4683
Evan Chengd7ba7ed2007-10-06 08:19:55 +00004684SDOperand DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
4685 SDOperand InVec = N->getOperand(0);
4686 SDOperand EltNo = N->getOperand(1);
4687
4688 // (vextract (v4f32 s2v (f32 load $addr)), 0) -> (f32 load $addr)
4689 // (vextract (v4i32 bc (v4f32 s2v (f32 load $addr))), 0) -> (i32 load $addr)
4690 if (isa<ConstantSDNode>(EltNo)) {
4691 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4692 bool NewLoad = false;
4693 if (Elt == 0) {
4694 MVT::ValueType VT = InVec.getValueType();
4695 MVT::ValueType EVT = MVT::getVectorElementType(VT);
4696 MVT::ValueType LVT = EVT;
4697 unsigned NumElts = MVT::getVectorNumElements(VT);
4698 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
4699 MVT::ValueType BCVT = InVec.getOperand(0).getValueType();
Dan Gohmana3591d92007-10-29 20:44:42 +00004700 if (!MVT::isVector(BCVT) ||
4701 NumElts != MVT::getVectorNumElements(BCVT))
Evan Chengd7ba7ed2007-10-06 08:19:55 +00004702 return SDOperand();
4703 InVec = InVec.getOperand(0);
4704 EVT = MVT::getVectorElementType(BCVT);
4705 NewLoad = true;
4706 }
4707 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4708 InVec.getOperand(0).getValueType() == EVT &&
4709 ISD::isNormalLoad(InVec.getOperand(0).Val) &&
4710 InVec.getOperand(0).hasOneUse()) {
4711 LoadSDNode *LN0 = cast<LoadSDNode>(InVec.getOperand(0));
4712 unsigned Align = LN0->getAlignment();
4713 if (NewLoad) {
4714 // Check the resultant load doesn't need a higher alignment than the
4715 // original load.
4716 unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
4717 getABITypeAlignment(MVT::getTypeForValueType(LVT));
4718 if (!TLI.isOperationLegal(ISD::LOAD, LVT) || NewAlign > Align)
4719 return SDOperand();
4720 Align = NewAlign;
4721 }
4722
4723 return DAG.getLoad(LVT, LN0->getChain(), LN0->getBasePtr(),
4724 LN0->getSrcValue(), LN0->getSrcValueOffset(),
4725 LN0->isVolatile(), Align);
4726 }
4727 }
4728 }
4729 return SDOperand();
4730}
4731
4732
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004733SDOperand DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
4734 unsigned NumInScalars = N->getNumOperands();
4735 MVT::ValueType VT = N->getValueType(0);
4736 unsigned NumElts = MVT::getVectorNumElements(VT);
4737 MVT::ValueType EltType = MVT::getVectorElementType(VT);
4738
4739 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
4740 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
4741 // at most two distinct vectors, turn this into a shuffle node.
4742 SDOperand VecIn1, VecIn2;
4743 for (unsigned i = 0; i != NumInScalars; ++i) {
4744 // Ignore undef inputs.
4745 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
4746
4747 // If this input is something other than a EXTRACT_VECTOR_ELT with a
4748 // constant index, bail out.
4749 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4750 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
4751 VecIn1 = VecIn2 = SDOperand(0, 0);
4752 break;
4753 }
4754
4755 // If the input vector type disagrees with the result of the build_vector,
4756 // we can't make a shuffle.
4757 SDOperand ExtractedFromVec = N->getOperand(i).getOperand(0);
4758 if (ExtractedFromVec.getValueType() != VT) {
4759 VecIn1 = VecIn2 = SDOperand(0, 0);
4760 break;
4761 }
4762
4763 // Otherwise, remember this. We allow up to two distinct input vectors.
4764 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
4765 continue;
4766
4767 if (VecIn1.Val == 0) {
4768 VecIn1 = ExtractedFromVec;
4769 } else if (VecIn2.Val == 0) {
4770 VecIn2 = ExtractedFromVec;
4771 } else {
4772 // Too many inputs.
4773 VecIn1 = VecIn2 = SDOperand(0, 0);
4774 break;
4775 }
4776 }
4777
4778 // If everything is good, we can make a shuffle operation.
4779 if (VecIn1.Val) {
4780 SmallVector<SDOperand, 8> BuildVecIndices;
4781 for (unsigned i = 0; i != NumInScalars; ++i) {
4782 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
4783 BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, TLI.getPointerTy()));
4784 continue;
4785 }
4786
4787 SDOperand Extract = N->getOperand(i);
4788
4789 // If extracting from the first vector, just use the index directly.
4790 if (Extract.getOperand(0) == VecIn1) {
4791 BuildVecIndices.push_back(Extract.getOperand(1));
4792 continue;
4793 }
4794
4795 // Otherwise, use InIdx + VecSize
4796 unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue();
Chris Lattner5872a362008-01-17 07:00:52 +00004797 BuildVecIndices.push_back(DAG.getIntPtrConstant(Idx+NumInScalars));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004798 }
4799
4800 // Add count and size info.
Chris Lattner5872a362008-01-17 07:00:52 +00004801 MVT::ValueType BuildVecVT = MVT::getVectorType(TLI.getPointerTy(), NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004802
4803 // Return the new VECTOR_SHUFFLE node.
4804 SDOperand Ops[5];
4805 Ops[0] = VecIn1;
4806 if (VecIn2.Val) {
4807 Ops[1] = VecIn2;
4808 } else {
4809 // Use an undef build_vector as input for the second operand.
4810 std::vector<SDOperand> UnOps(NumInScalars,
4811 DAG.getNode(ISD::UNDEF,
4812 EltType));
4813 Ops[1] = DAG.getNode(ISD::BUILD_VECTOR, VT,
4814 &UnOps[0], UnOps.size());
4815 AddToWorkList(Ops[1].Val);
4816 }
4817 Ops[2] = DAG.getNode(ISD::BUILD_VECTOR, BuildVecVT,
4818 &BuildVecIndices[0], BuildVecIndices.size());
4819 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Ops, 3);
4820 }
4821
4822 return SDOperand();
4823}
4824
4825SDOperand DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
4826 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
4827 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
4828 // inputs come from at most two distinct vectors, turn this into a shuffle
4829 // node.
4830
4831 // If we only have one input vector, we don't need to do any concatenation.
4832 if (N->getNumOperands() == 1) {
4833 return N->getOperand(0);
4834 }
4835
4836 return SDOperand();
4837}
4838
4839SDOperand DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
4840 SDOperand ShufMask = N->getOperand(2);
4841 unsigned NumElts = ShufMask.getNumOperands();
4842
4843 // If the shuffle mask is an identity operation on the LHS, return the LHS.
4844 bool isIdentity = true;
4845 for (unsigned i = 0; i != NumElts; ++i) {
4846 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4847 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
4848 isIdentity = false;
4849 break;
4850 }
4851 }
4852 if (isIdentity) return N->getOperand(0);
4853
4854 // If the shuffle mask is an identity operation on the RHS, return the RHS.
4855 isIdentity = true;
4856 for (unsigned i = 0; i != NumElts; ++i) {
4857 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4858 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
4859 isIdentity = false;
4860 break;
4861 }
4862 }
4863 if (isIdentity) return N->getOperand(1);
4864
4865 // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
4866 // needed at all.
4867 bool isUnary = true;
4868 bool isSplat = true;
4869 int VecNum = -1;
4870 unsigned BaseIdx = 0;
4871 for (unsigned i = 0; i != NumElts; ++i)
4872 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
4873 unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
4874 int V = (Idx < NumElts) ? 0 : 1;
4875 if (VecNum == -1) {
4876 VecNum = V;
4877 BaseIdx = Idx;
4878 } else {
4879 if (BaseIdx != Idx)
4880 isSplat = false;
4881 if (VecNum != V) {
4882 isUnary = false;
4883 break;
4884 }
4885 }
4886 }
4887
4888 SDOperand N0 = N->getOperand(0);
4889 SDOperand N1 = N->getOperand(1);
4890 // Normalize unary shuffle so the RHS is undef.
4891 if (isUnary && VecNum == 1)
4892 std::swap(N0, N1);
4893
4894 // If it is a splat, check if the argument vector is a build_vector with
4895 // all scalar elements the same.
4896 if (isSplat) {
4897 SDNode *V = N0.Val;
4898
4899 // If this is a bit convert that changes the element type of the vector but
4900 // not the number of vector elements, look through it. Be careful not to
4901 // look though conversions that change things like v4f32 to v2f64.
4902 if (V->getOpcode() == ISD::BIT_CONVERT) {
4903 SDOperand ConvInput = V->getOperand(0);
4904 if (MVT::getVectorNumElements(ConvInput.getValueType()) == NumElts)
4905 V = ConvInput.Val;
4906 }
4907
4908 if (V->getOpcode() == ISD::BUILD_VECTOR) {
4909 unsigned NumElems = V->getNumOperands();
4910 if (NumElems > BaseIdx) {
4911 SDOperand Base;
4912 bool AllSame = true;
4913 for (unsigned i = 0; i != NumElems; ++i) {
4914 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
4915 Base = V->getOperand(i);
4916 break;
4917 }
4918 }
4919 // Splat of <u, u, u, u>, return <u, u, u, u>
4920 if (!Base.Val)
4921 return N0;
4922 for (unsigned i = 0; i != NumElems; ++i) {
Evan Cheng8d68c2b2007-09-18 21:54:37 +00004923 if (V->getOperand(i) != Base) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004924 AllSame = false;
4925 break;
4926 }
4927 }
4928 // Splat of <x, x, x, x>, return <x, x, x, x>
4929 if (AllSame)
4930 return N0;
4931 }
4932 }
4933 }
4934
4935 // If it is a unary or the LHS and the RHS are the same node, turn the RHS
4936 // into an undef.
4937 if (isUnary || N0 == N1) {
4938 // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
4939 // first operand.
4940 SmallVector<SDOperand, 8> MappedOps;
4941 for (unsigned i = 0; i != NumElts; ++i) {
4942 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
4943 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
4944 MappedOps.push_back(ShufMask.getOperand(i));
4945 } else {
4946 unsigned NewIdx =
4947 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
4948 MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
4949 }
4950 }
4951 ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
4952 &MappedOps[0], MappedOps.size());
4953 AddToWorkList(ShufMask.Val);
4954 return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
4955 N0,
4956 DAG.getNode(ISD::UNDEF, N->getValueType(0)),
4957 ShufMask);
4958 }
4959
4960 return SDOperand();
4961}
4962
4963/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
4964/// an AND to a vector_shuffle with the destination vector and a zero vector.
4965/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
4966/// vector_shuffle V, Zero, <0, 4, 2, 4>
4967SDOperand DAGCombiner::XformToShuffleWithZero(SDNode *N) {
4968 SDOperand LHS = N->getOperand(0);
4969 SDOperand RHS = N->getOperand(1);
4970 if (N->getOpcode() == ISD::AND) {
4971 if (RHS.getOpcode() == ISD::BIT_CONVERT)
4972 RHS = RHS.getOperand(0);
4973 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
4974 std::vector<SDOperand> IdxOps;
4975 unsigned NumOps = RHS.getNumOperands();
4976 unsigned NumElts = NumOps;
4977 MVT::ValueType EVT = MVT::getVectorElementType(RHS.getValueType());
4978 for (unsigned i = 0; i != NumElts; ++i) {
4979 SDOperand Elt = RHS.getOperand(i);
4980 if (!isa<ConstantSDNode>(Elt))
4981 return SDOperand();
4982 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
4983 IdxOps.push_back(DAG.getConstant(i, EVT));
4984 else if (cast<ConstantSDNode>(Elt)->isNullValue())
4985 IdxOps.push_back(DAG.getConstant(NumElts, EVT));
4986 else
4987 return SDOperand();
4988 }
4989
4990 // Let's see if the target supports this vector_shuffle.
4991 if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG))
4992 return SDOperand();
4993
4994 // Return the new VECTOR_SHUFFLE node.
4995 MVT::ValueType VT = MVT::getVectorType(EVT, NumElts);
4996 std::vector<SDOperand> Ops;
4997 LHS = DAG.getNode(ISD::BIT_CONVERT, VT, LHS);
4998 Ops.push_back(LHS);
4999 AddToWorkList(LHS.Val);
5000 std::vector<SDOperand> ZeroOps(NumElts, DAG.getConstant(0, EVT));
5001 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
5002 &ZeroOps[0], ZeroOps.size()));
5003 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
5004 &IdxOps[0], IdxOps.size()));
5005 SDOperand Result = DAG.getNode(ISD::VECTOR_SHUFFLE, VT,
5006 &Ops[0], Ops.size());
5007 if (VT != LHS.getValueType()) {
5008 Result = DAG.getNode(ISD::BIT_CONVERT, LHS.getValueType(), Result);
5009 }
5010 return Result;
5011 }
5012 }
5013 return SDOperand();
5014}
5015
5016/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
5017SDOperand DAGCombiner::SimplifyVBinOp(SDNode *N) {
5018 // After legalize, the target may be depending on adds and other
5019 // binary ops to provide legal ways to construct constants or other
5020 // things. Simplifying them may result in a loss of legality.
5021 if (AfterLegalize) return SDOperand();
5022
5023 MVT::ValueType VT = N->getValueType(0);
5024 assert(MVT::isVector(VT) && "SimplifyVBinOp only works on vectors!");
5025
5026 MVT::ValueType EltType = MVT::getVectorElementType(VT);
5027 SDOperand LHS = N->getOperand(0);
5028 SDOperand RHS = N->getOperand(1);
5029 SDOperand Shuffle = XformToShuffleWithZero(N);
5030 if (Shuffle.Val) return Shuffle;
5031
5032 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
5033 // this operation.
5034 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
5035 RHS.getOpcode() == ISD::BUILD_VECTOR) {
5036 SmallVector<SDOperand, 8> Ops;
5037 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
5038 SDOperand LHSOp = LHS.getOperand(i);
5039 SDOperand RHSOp = RHS.getOperand(i);
5040 // If these two elements can't be folded, bail out.
5041 if ((LHSOp.getOpcode() != ISD::UNDEF &&
5042 LHSOp.getOpcode() != ISD::Constant &&
5043 LHSOp.getOpcode() != ISD::ConstantFP) ||
5044 (RHSOp.getOpcode() != ISD::UNDEF &&
5045 RHSOp.getOpcode() != ISD::Constant &&
5046 RHSOp.getOpcode() != ISD::ConstantFP))
5047 break;
5048 // Can't fold divide by zero.
5049 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
5050 N->getOpcode() == ISD::FDIV) {
5051 if ((RHSOp.getOpcode() == ISD::Constant &&
5052 cast<ConstantSDNode>(RHSOp.Val)->isNullValue()) ||
5053 (RHSOp.getOpcode() == ISD::ConstantFP &&
Dale Johannesen7604c1b2007-08-31 23:34:27 +00005054 cast<ConstantFPSDNode>(RHSOp.Val)->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005055 break;
5056 }
5057 Ops.push_back(DAG.getNode(N->getOpcode(), EltType, LHSOp, RHSOp));
5058 AddToWorkList(Ops.back().Val);
5059 assert((Ops.back().getOpcode() == ISD::UNDEF ||
5060 Ops.back().getOpcode() == ISD::Constant ||
5061 Ops.back().getOpcode() == ISD::ConstantFP) &&
5062 "Scalar binop didn't fold!");
5063 }
5064
5065 if (Ops.size() == LHS.getNumOperands()) {
5066 MVT::ValueType VT = LHS.getValueType();
5067 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
5068 }
5069 }
5070
5071 return SDOperand();
5072}
5073
5074SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
5075 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
5076
5077 SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
5078 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5079 // If we got a simplified select_cc node back from SimplifySelectCC, then
5080 // break it down into a new SETCC node, and a new SELECT node, and then return
5081 // the SELECT node, since we were called with a SELECT node.
5082 if (SCC.Val) {
5083 // Check to see if we got a select_cc back (to turn into setcc/select).
5084 // Otherwise, just return whatever node we got back, like fabs.
5085 if (SCC.getOpcode() == ISD::SELECT_CC) {
5086 SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
5087 SCC.getOperand(0), SCC.getOperand(1),
5088 SCC.getOperand(4));
5089 AddToWorkList(SETCC.Val);
5090 return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
5091 SCC.getOperand(3), SETCC);
5092 }
5093 return SCC;
5094 }
5095 return SDOperand();
5096}
5097
5098/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
5099/// are the two values being selected between, see if we can simplify the
5100/// select. Callers of this should assume that TheSelect is deleted if this
5101/// returns true. As such, they should return the appropriate thing (e.g. the
5102/// node) back to the top-level of the DAG combiner loop to avoid it being
5103/// looked at.
5104///
5105bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
5106 SDOperand RHS) {
5107
5108 // If this is a select from two identical things, try to pull the operation
5109 // through the select.
5110 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
5111 // If this is a load and the token chain is identical, replace the select
5112 // of two loads with a load through a select of the address to load from.
5113 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
5114 // constants have been dropped into the constant pool.
5115 if (LHS.getOpcode() == ISD::LOAD &&
5116 // Token chains must be identical.
5117 LHS.getOperand(0) == RHS.getOperand(0)) {
5118 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
5119 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
5120
5121 // If this is an EXTLOAD, the VT's must match.
Dan Gohman9a4c92c2008-01-30 00:15:11 +00005122 if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005123 // FIXME: this conflates two src values, discarding one. This is not
5124 // the right thing to do, but nothing uses srcvalues now. When they do,
5125 // turn SrcValue into a list of locations.
5126 SDOperand Addr;
5127 if (TheSelect->getOpcode() == ISD::SELECT) {
5128 // Check that the condition doesn't reach either load. If so, folding
5129 // this will induce a cycle into the DAG.
Evan Chengd9387682008-03-04 00:41:45 +00005130 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5131 !RLD->isPredecessorOf(TheSelect->getOperand(0).Val)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005132 Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
5133 TheSelect->getOperand(0), LLD->getBasePtr(),
5134 RLD->getBasePtr());
5135 }
5136 } else {
5137 // Check that the condition doesn't reach either load. If so, folding
5138 // this will induce a cycle into the DAG.
Evan Chengd9387682008-03-04 00:41:45 +00005139 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5140 !RLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5141 !LLD->isPredecessorOf(TheSelect->getOperand(1).Val) &&
5142 !RLD->isPredecessorOf(TheSelect->getOperand(1).Val)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005143 Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
5144 TheSelect->getOperand(0),
5145 TheSelect->getOperand(1),
5146 LLD->getBasePtr(), RLD->getBasePtr(),
5147 TheSelect->getOperand(4));
5148 }
5149 }
5150
5151 if (Addr.Val) {
5152 SDOperand Load;
5153 if (LLD->getExtensionType() == ISD::NON_EXTLOAD)
5154 Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(),
5155 Addr,LLD->getSrcValue(),
5156 LLD->getSrcValueOffset(),
5157 LLD->isVolatile(),
5158 LLD->getAlignment());
5159 else {
5160 Load = DAG.getExtLoad(LLD->getExtensionType(),
5161 TheSelect->getValueType(0),
5162 LLD->getChain(), Addr, LLD->getSrcValue(),
5163 LLD->getSrcValueOffset(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00005164 LLD->getMemoryVT(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005165 LLD->isVolatile(),
5166 LLD->getAlignment());
5167 }
5168 // Users of the select now use the result of the load.
5169 CombineTo(TheSelect, Load);
5170
5171 // Users of the old loads now use the new load's chain. We know the
5172 // old-load value is dead now.
5173 CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
5174 CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
5175 return true;
5176 }
5177 }
5178 }
5179 }
5180
5181 return false;
5182}
5183
5184SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
5185 SDOperand N2, SDOperand N3,
5186 ISD::CondCode CC, bool NotExtCompare) {
5187
5188 MVT::ValueType VT = N2.getValueType();
5189 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
5190 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
5191 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
5192
5193 // Determine if the condition we're dealing with is constant
Scott Michel502151f2008-03-10 15:42:14 +00005194 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005195 if (SCC.Val) AddToWorkList(SCC.Val);
5196 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
5197
5198 // fold select_cc true, x, y -> x
Dan Gohman9d24dc72008-03-13 22:13:53 +00005199 if (SCCC && !SCCC->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005200 return N2;
5201 // fold select_cc false, x, y -> y
Dan Gohman9d24dc72008-03-13 22:13:53 +00005202 if (SCCC && SCCC->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005203 return N3;
5204
5205 // Check to see if we can simplify the select into an fabs node
5206 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
5207 // Allow either -0.0 or 0.0
Dale Johannesen7f2c1d12007-08-25 22:10:57 +00005208 if (CFP->getValueAPF().isZero()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005209 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
5210 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
5211 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
5212 N2 == N3.getOperand(0))
5213 return DAG.getNode(ISD::FABS, VT, N0);
5214
5215 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
5216 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
5217 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
5218 N2.getOperand(0) == N3)
5219 return DAG.getNode(ISD::FABS, VT, N3);
5220 }
5221 }
5222
5223 // Check to see if we can perform the "gzip trick", transforming
5224 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
5225 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
5226 MVT::isInteger(N0.getValueType()) &&
5227 MVT::isInteger(N2.getValueType()) &&
Dan Gohman9d24dc72008-03-13 22:13:53 +00005228 (N1C->isNullValue() || // (a < 0) ? b : 0
5229 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005230 MVT::ValueType XType = N0.getValueType();
5231 MVT::ValueType AType = N2.getValueType();
5232 if (XType >= AType) {
5233 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
5234 // single-bit constant.
Dan Gohman9d24dc72008-03-13 22:13:53 +00005235 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
5236 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005237 ShCtV = MVT::getSizeInBits(XType)-ShCtV-1;
5238 SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
5239 SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
5240 AddToWorkList(Shift.Val);
5241 if (XType > AType) {
5242 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5243 AddToWorkList(Shift.Val);
5244 }
5245 return DAG.getNode(ISD::AND, AType, Shift, N2);
5246 }
5247 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5248 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5249 TLI.getShiftAmountTy()));
5250 AddToWorkList(Shift.Val);
5251 if (XType > AType) {
5252 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5253 AddToWorkList(Shift.Val);
5254 }
5255 return DAG.getNode(ISD::AND, AType, Shift, N2);
5256 }
5257 }
5258
5259 // fold select C, 16, 0 -> shl C, 4
Dan Gohman9d24dc72008-03-13 22:13:53 +00005260 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005261 TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
5262
5263 // If the caller doesn't want us to simplify this into a zext of a compare,
5264 // don't do it.
Dan Gohman9d24dc72008-03-13 22:13:53 +00005265 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005266 return SDOperand();
5267
5268 // Get a SetCC of the condition
5269 // FIXME: Should probably make sure that setcc is legal if we ever have a
5270 // target where it isn't.
5271 SDOperand Temp, SCC;
5272 // cast from setcc result type to select result type
5273 if (AfterLegalize) {
Scott Michel502151f2008-03-10 15:42:14 +00005274 SCC = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005275 if (N2.getValueType() < SCC.getValueType())
5276 Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
5277 else
5278 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5279 } else {
5280 SCC = DAG.getSetCC(MVT::i1, N0, N1, CC);
5281 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5282 }
5283 AddToWorkList(SCC.Val);
5284 AddToWorkList(Temp.Val);
5285
Dan Gohman9d24dc72008-03-13 22:13:53 +00005286 if (N2C->getAPIntValue() == 1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005287 return Temp;
5288 // shl setcc result by log2 n2c
5289 return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
Dan Gohman9d24dc72008-03-13 22:13:53 +00005290 DAG.getConstant(N2C->getAPIntValue().logBase2(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005291 TLI.getShiftAmountTy()));
5292 }
5293
5294 // Check to see if this is the equivalent of setcc
5295 // FIXME: Turn all of these into setcc if setcc if setcc is legal
5296 // otherwise, go ahead with the folds.
Dan Gohman9d24dc72008-03-13 22:13:53 +00005297 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005298 MVT::ValueType XType = N0.getValueType();
Scott Michel502151f2008-03-10 15:42:14 +00005299 if (TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(N0))) {
5300 SDOperand Res = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005301 if (Res.getValueType() != VT)
5302 Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
5303 return Res;
5304 }
5305
5306 // seteq X, 0 -> srl (ctlz X, log2(size(X)))
5307 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
5308 TLI.isOperationLegal(ISD::CTLZ, XType)) {
5309 SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
5310 return DAG.getNode(ISD::SRL, XType, Ctlz,
5311 DAG.getConstant(Log2_32(MVT::getSizeInBits(XType)),
5312 TLI.getShiftAmountTy()));
5313 }
5314 // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
5315 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
5316 SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
5317 N0);
5318 SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0,
5319 DAG.getConstant(~0ULL, XType));
5320 return DAG.getNode(ISD::SRL, XType,
5321 DAG.getNode(ISD::AND, XType, NegN0, NotN0),
5322 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5323 TLI.getShiftAmountTy()));
5324 }
5325 // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
5326 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
5327 SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
5328 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5329 TLI.getShiftAmountTy()));
5330 return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
5331 }
5332 }
5333
5334 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
5335 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5336 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
5337 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
5338 N2.getOperand(0) == N1 && MVT::isInteger(N0.getValueType())) {
5339 MVT::ValueType XType = N0.getValueType();
5340 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5341 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5342 TLI.getShiftAmountTy()));
5343 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5344 AddToWorkList(Shift.Val);
5345 AddToWorkList(Add.Val);
5346 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5347 }
5348 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
5349 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5350 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
5351 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
5352 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
5353 MVT::ValueType XType = N0.getValueType();
5354 if (SubC->isNullValue() && MVT::isInteger(XType)) {
5355 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5356 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5357 TLI.getShiftAmountTy()));
5358 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5359 AddToWorkList(Shift.Val);
5360 AddToWorkList(Add.Val);
5361 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5362 }
5363 }
5364 }
5365
5366 return SDOperand();
5367}
5368
5369/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
5370SDOperand DAGCombiner::SimplifySetCC(MVT::ValueType VT, SDOperand N0,
5371 SDOperand N1, ISD::CondCode Cond,
5372 bool foldBooleans) {
5373 TargetLowering::DAGCombinerInfo
5374 DagCombineInfo(DAG, !AfterLegalize, false, this);
5375 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo);
5376}
5377
5378/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
5379/// return a DAG expression to select that will generate the same value by
5380/// multiplying by a magic number. See:
5381/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5382SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
5383 std::vector<SDNode*> Built;
5384 SDOperand S = TLI.BuildSDIV(N, DAG, &Built);
5385
5386 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5387 ii != ee; ++ii)
5388 AddToWorkList(*ii);
5389 return S;
5390}
5391
5392/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
5393/// return a DAG expression to select that will generate the same value by
5394/// multiplying by a magic number. See:
5395/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5396SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
5397 std::vector<SDNode*> Built;
5398 SDOperand S = TLI.BuildUDIV(N, DAG, &Built);
5399
5400 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5401 ii != ee; ++ii)
5402 AddToWorkList(*ii);
5403 return S;
5404}
5405
5406/// FindBaseOffset - Return true if base is known not to alias with anything
5407/// but itself. Provides base object and offset as results.
5408static bool FindBaseOffset(SDOperand Ptr, SDOperand &Base, int64_t &Offset) {
5409 // Assume it is a primitive operation.
5410 Base = Ptr; Offset = 0;
5411
5412 // If it's an adding a simple constant then integrate the offset.
5413 if (Base.getOpcode() == ISD::ADD) {
5414 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
5415 Base = Base.getOperand(0);
5416 Offset += C->getValue();
5417 }
5418 }
5419
5420 // If it's any of the following then it can't alias with anything but itself.
5421 return isa<FrameIndexSDNode>(Base) ||
5422 isa<ConstantPoolSDNode>(Base) ||
5423 isa<GlobalAddressSDNode>(Base);
5424}
5425
5426/// isAlias - Return true if there is any possibility that the two addresses
5427/// overlap.
5428bool DAGCombiner::isAlias(SDOperand Ptr1, int64_t Size1,
5429 const Value *SrcValue1, int SrcValueOffset1,
5430 SDOperand Ptr2, int64_t Size2,
5431 const Value *SrcValue2, int SrcValueOffset2)
5432{
5433 // If they are the same then they must be aliases.
5434 if (Ptr1 == Ptr2) return true;
5435
5436 // Gather base node and offset information.
5437 SDOperand Base1, Base2;
5438 int64_t Offset1, Offset2;
5439 bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
5440 bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
5441
5442 // If they have a same base address then...
5443 if (Base1 == Base2) {
5444 // Check to see if the addresses overlap.
5445 return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
5446 }
5447
5448 // If we know both bases then they can't alias.
5449 if (KnownBase1 && KnownBase2) return false;
5450
5451 if (CombinerGlobalAA) {
5452 // Use alias analysis information.
Dan Gohmane142c2e2007-08-27 16:32:11 +00005453 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
5454 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
5455 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005456 AliasAnalysis::AliasResult AAResult =
5457 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
5458 if (AAResult == AliasAnalysis::NoAlias)
5459 return false;
5460 }
5461
5462 // Otherwise we have to assume they alias.
5463 return true;
5464}
5465
5466/// FindAliasInfo - Extracts the relevant alias information from the memory
5467/// node. Returns true if the operand was a load.
5468bool DAGCombiner::FindAliasInfo(SDNode *N,
5469 SDOperand &Ptr, int64_t &Size,
5470 const Value *&SrcValue, int &SrcValueOffset) {
5471 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5472 Ptr = LD->getBasePtr();
Dan Gohman9a4c92c2008-01-30 00:15:11 +00005473 Size = MVT::getSizeInBits(LD->getMemoryVT()) >> 3;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005474 SrcValue = LD->getSrcValue();
5475 SrcValueOffset = LD->getSrcValueOffset();
5476 return true;
5477 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5478 Ptr = ST->getBasePtr();
Dan Gohman9a4c92c2008-01-30 00:15:11 +00005479 Size = MVT::getSizeInBits(ST->getMemoryVT()) >> 3;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005480 SrcValue = ST->getSrcValue();
5481 SrcValueOffset = ST->getSrcValueOffset();
5482 } else {
5483 assert(0 && "FindAliasInfo expected a memory operand");
5484 }
5485
5486 return false;
5487}
5488
5489/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
5490/// looking for aliasing nodes and adding them to the Aliases vector.
5491void DAGCombiner::GatherAllAliases(SDNode *N, SDOperand OriginalChain,
5492 SmallVector<SDOperand, 8> &Aliases) {
5493 SmallVector<SDOperand, 8> Chains; // List of chains to visit.
5494 std::set<SDNode *> Visited; // Visited node set.
5495
5496 // Get alias information for node.
5497 SDOperand Ptr;
5498 int64_t Size;
5499 const Value *SrcValue;
5500 int SrcValueOffset;
5501 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
5502
5503 // Starting off.
5504 Chains.push_back(OriginalChain);
5505
5506 // Look at each chain and determine if it is an alias. If so, add it to the
5507 // aliases list. If not, then continue up the chain looking for the next
5508 // candidate.
5509 while (!Chains.empty()) {
5510 SDOperand Chain = Chains.back();
5511 Chains.pop_back();
5512
5513 // Don't bother if we've been before.
5514 if (Visited.find(Chain.Val) != Visited.end()) continue;
5515 Visited.insert(Chain.Val);
5516
5517 switch (Chain.getOpcode()) {
5518 case ISD::EntryToken:
5519 // Entry token is ideal chain operand, but handled in FindBetterChain.
5520 break;
5521
5522 case ISD::LOAD:
5523 case ISD::STORE: {
5524 // Get alias information for Chain.
5525 SDOperand OpPtr;
5526 int64_t OpSize;
5527 const Value *OpSrcValue;
5528 int OpSrcValueOffset;
5529 bool IsOpLoad = FindAliasInfo(Chain.Val, OpPtr, OpSize,
5530 OpSrcValue, OpSrcValueOffset);
5531
5532 // If chain is alias then stop here.
5533 if (!(IsLoad && IsOpLoad) &&
5534 isAlias(Ptr, Size, SrcValue, SrcValueOffset,
5535 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
5536 Aliases.push_back(Chain);
5537 } else {
5538 // Look further up the chain.
5539 Chains.push_back(Chain.getOperand(0));
5540 // Clean up old chain.
5541 AddToWorkList(Chain.Val);
5542 }
5543 break;
5544 }
5545
5546 case ISD::TokenFactor:
5547 // We have to check each of the operands of the token factor, so we queue
5548 // then up. Adding the operands to the queue (stack) in reverse order
5549 // maintains the original order and increases the likelihood that getNode
5550 // will find a matching token factor (CSE.)
5551 for (unsigned n = Chain.getNumOperands(); n;)
5552 Chains.push_back(Chain.getOperand(--n));
5553 // Eliminate the token factor if we can.
5554 AddToWorkList(Chain.Val);
5555 break;
5556
5557 default:
5558 // For all other instructions we will just have to take what we can get.
5559 Aliases.push_back(Chain);
5560 break;
5561 }
5562 }
5563}
5564
5565/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
5566/// for a better chain (aliasing node.)
5567SDOperand DAGCombiner::FindBetterChain(SDNode *N, SDOperand OldChain) {
5568 SmallVector<SDOperand, 8> Aliases; // Ops for replacing token factor.
5569
5570 // Accumulate all the aliases to this node.
5571 GatherAllAliases(N, OldChain, Aliases);
5572
5573 if (Aliases.size() == 0) {
5574 // If no operands then chain to entry token.
5575 return DAG.getEntryNode();
5576 } else if (Aliases.size() == 1) {
5577 // If a single operand then chain to it. We don't need to revisit it.
5578 return Aliases[0];
5579 }
5580
5581 // Construct a custom tailored token factor.
5582 SDOperand NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5583 &Aliases[0], Aliases.size());
5584
5585 // Make sure the old chain gets cleaned up.
5586 if (NewChain != OldChain) AddToWorkList(OldChain.Val);
5587
5588 return NewChain;
5589}
5590
5591// SelectionDAG::Combine - This is the entry point for the file.
5592//
5593void SelectionDAG::Combine(bool RunningAfterLegalize, AliasAnalysis &AA) {
5594 if (!RunningAfterLegalize && ViewDAGCombine1)
5595 viewGraph();
5596 if (RunningAfterLegalize && ViewDAGCombine2)
5597 viewGraph();
5598 /// run - This is the main entry point to this class.
5599 ///
5600 DAGCombiner(*this, AA).Run(RunningAfterLegalize);
5601}