blob: cc0c5fa07665a2a9cf531b10de1b3d7aead5e838 [file] [log] [blame]
Nate Begeman4ebd8052005-09-01 23:24:04 +00001//===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
Nate Begeman1d4d4142005-09-01 00:19:25 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Nate Begeman1d4d4142005-09-01 00:19:25 +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.
Scott Michelfdc40a02009-02-17 22:15:04 +000012//
Dan Gohman41287002009-04-25 17:09:45 +000013// This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14// primarily intended to handle simplification opportunities that are implicit
15// in the LLVM IR and exposed by the various codegen lowering phases.
16//
Nate Begeman1d4d4142005-09-01 00:19:25 +000017//===----------------------------------------------------------------------===//
18
19#define DEBUG_TYPE "dagcombine"
Nate Begeman1d4d4142005-09-01 00:19:25 +000020#include "llvm/CodeGen/SelectionDAG.h"
Chris Lattnerc76d4412007-05-16 06:37:59 +000021#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/Statistic.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000023#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/LLVMContext.h"
Jim Laskeyd1aed7a2006-09-21 16:28:59 +000030#include "llvm/Support/CommandLine.h"
Chris Lattnerc76d4412007-05-16 06:37:59 +000031#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000032#include "llvm/Support/ErrorHandling.h"
Chris Lattnerc76d4412007-05-16 06:37:59 +000033#include "llvm/Support/MathExtras.h"
Chris Lattnerbbbfa992009-08-23 06:35:02 +000034#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000035#include "llvm/Target/TargetLowering.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetOptions.h"
Quentin Colombet83f743a2013-10-11 18:29:42 +000038#include "llvm/Target/TargetRegisterInfo.h"
Hal Finkel253acef2013-08-29 03:29:55 +000039#include "llvm/Target/TargetSubtargetInfo.h"
Chris Lattnera500fc62005-09-09 23:53:39 +000040#include <algorithm>
Nate Begeman1d4d4142005-09-01 00:19:25 +000041using namespace llvm;
42
Chris Lattnercd3245a2006-12-19 22:41:21 +000043STATISTIC(NodesCombined , "Number of dag nodes combined");
44STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
45STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
Evan Cheng8b944d32009-05-28 00:35:15 +000046STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
Evan Cheng31959b12011-02-02 01:06:55 +000047STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
Quentin Colombet83f743a2013-10-11 18:29:42 +000048STATISTIC(SlicedLoads, "Number of load sliced");
Chris Lattnercd3245a2006-12-19 22:41:21 +000049
Nate Begeman1d4d4142005-09-01 00:19:25 +000050namespace {
Jim Laskey71382342006-10-07 23:37:56 +000051 static cl::opt<bool>
Owen Anderson0dcc8142010-09-19 21:01:26 +000052 CombinerAA("combiner-alias-analysis", cl::Hidden,
Stephen Hines36b56882014-04-23 16:57:46 -070053 cl::desc("Enable DAG combiner alias-analysis heuristics"));
Jim Laskey3ad175b2006-10-12 15:22:24 +000054
Jim Laskey07a27092006-10-18 19:08:31 +000055 static cl::opt<bool>
56 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
Stephen Hines36b56882014-04-23 16:57:46 -070057 cl::desc("Enable DAG combiner's use of IR alias analysis"));
58
59// FIXME: Enable the use of TBAA. There are two known issues preventing this:
60// 1. Stack coloring does not update TBAA when merging allocas
61// 2. CGP inserts ptrtoint/inttoptr pairs when sinking address computations.
62// Because BasicAA does not handle inttoptr, we'll often miss basic type
63// punning idioms that we need to catch so we don't miscompile real-world
64// code.
65 static cl::opt<bool>
66 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(false),
67 cl::desc("Enable DAG combiner's use of TBAA"));
68
69#ifndef NDEBUG
70 static cl::opt<std::string>
71 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
72 cl::desc("Only use DAG-combiner alias analysis in this"
73 " function"));
74#endif
Jim Laskey07a27092006-10-18 19:08:31 +000075
Quentin Colombet83f743a2013-10-11 18:29:42 +000076 /// Hidden option to stress test load slicing, i.e., when this option
77 /// is enabled, load slicing bypasses most of its profitability guards.
78 static cl::opt<bool>
79 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
80 cl::desc("Bypass the profitability model of load "
81 "slicing"),
82 cl::init(false));
83
Jim Laskeybc588b82006-10-05 15:07:25 +000084//------------------------------ DAGCombiner ---------------------------------//
85
Nick Lewycky6726b6d2009-10-25 06:33:48 +000086 class DAGCombiner {
Nate Begeman1d4d4142005-09-01 00:19:25 +000087 SelectionDAG &DAG;
Dan Gohman79ce2762009-01-15 19:20:50 +000088 const TargetLowering &TLI;
Duncan Sands25cf2272008-11-24 14:53:14 +000089 CombineLevel Level;
Bill Wendling98a366d2009-04-29 23:29:43 +000090 CodeGenOpt::Level OptLevel;
Duncan Sands25cf2272008-11-24 14:53:14 +000091 bool LegalOperations;
92 bool LegalTypes;
Quentin Colombet83f743a2013-10-11 18:29:42 +000093 bool ForCodeSize;
Nate Begeman1d4d4142005-09-01 00:19:25 +000094
95 // Worklist of all of the nodes that need to be simplified.
James Molloy6660c052012-02-16 09:17:04 +000096 //
97 // This has the semantics that when adding to the worklist,
98 // the item added must be next to be processed. It should
99 // also only appear once. The naive approach to this takes
100 // linear time.
101 //
102 // To reduce the insert/remove time to logarithmic, we use
103 // a set and a vector to maintain our worklist.
104 //
105 // The set contains the items on the worklist, but does not
106 // maintain the order they should be visited.
107 //
108 // The vector maintains the order nodes should be visited, but may
109 // contain duplicate or removed nodes. When choosing a node to
110 // visit, we pop off the order stack until we find an item that is
111 // also in the contents set. All operations are O(log N).
112 SmallPtrSet<SDNode*, 64> WorkListContents;
Benjamin Kramerd5f76902012-03-10 00:23:58 +0000113 SmallVector<SDNode*, 64> WorkListOrder;
Nate Begeman1d4d4142005-09-01 00:19:25 +0000114
Jim Laskeyc7c3f112006-10-16 20:52:31 +0000115 // AA - Used for DAG load/store alias analysis.
116 AliasAnalysis &AA;
117
Nate Begeman1d4d4142005-09-01 00:19:25 +0000118 /// AddUsersToWorkList - When an instruction is simplified, add all users of
119 /// the instruction to the work lists because they might get more simplified
120 /// now.
121 ///
122 void AddUsersToWorkList(SDNode *N) {
123 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
Nate Begeman4ebd8052005-09-01 23:24:04 +0000124 UI != UE; ++UI)
Dan Gohman89684502008-07-27 20:43:25 +0000125 AddToWorkList(*UI);
Nate Begeman1d4d4142005-09-01 00:19:25 +0000126 }
127
Dan Gohman389079b2007-10-08 17:57:15 +0000128 /// visit - call the node-specific routine that knows how to fold each
129 /// particular type of node.
Dan Gohman475871a2008-07-27 21:46:04 +0000130 SDValue visit(SDNode *N);
Dan Gohman389079b2007-10-08 17:57:15 +0000131
Chris Lattner24664722006-03-01 04:53:38 +0000132 public:
James Molloy6afa3f72012-02-16 09:48:07 +0000133 /// AddToWorkList - Add to the work list making sure its instance is at the
James Molloy6660c052012-02-16 09:17:04 +0000134 /// back (next to be processed.)
Chris Lattner5750df92006-03-01 04:03:14 +0000135 void AddToWorkList(SDNode *N) {
James Molloy6660c052012-02-16 09:17:04 +0000136 WorkListContents.insert(N);
137 WorkListOrder.push_back(N);
Chris Lattner5750df92006-03-01 04:03:14 +0000138 }
Jim Laskey6ff23e52006-10-04 16:53:27 +0000139
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000140 /// removeFromWorkList - remove all instances of N from the worklist.
141 ///
142 void removeFromWorkList(SDNode *N) {
James Molloy6660c052012-02-16 09:17:04 +0000143 WorkListContents.erase(N);
Chris Lattner01a22022005-10-10 22:04:48 +0000144 }
Scott Michelfdc40a02009-02-17 22:15:04 +0000145
Dan Gohman475871a2008-07-27 21:46:04 +0000146 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
Evan Cheng0b0cd912009-03-28 05:57:29 +0000147 bool AddTo = true);
Scott Michelfdc40a02009-02-17 22:15:04 +0000148
Dan Gohman475871a2008-07-27 21:46:04 +0000149 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
Jim Laskey274062c2006-10-13 23:32:28 +0000150 return CombineTo(N, &Res, 1, AddTo);
Chris Lattner24664722006-03-01 04:53:38 +0000151 }
Scott Michelfdc40a02009-02-17 22:15:04 +0000152
Dan Gohman475871a2008-07-27 21:46:04 +0000153 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
Evan Cheng0b0cd912009-03-28 05:57:29 +0000154 bool AddTo = true) {
Dan Gohman475871a2008-07-27 21:46:04 +0000155 SDValue To[] = { Res0, Res1 };
Jim Laskey274062c2006-10-13 23:32:28 +0000156 return CombineTo(N, To, 2, AddTo);
Chris Lattner24664722006-03-01 04:53:38 +0000157 }
Dan Gohmane5af2d32009-01-29 01:59:02 +0000158
159 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
Scott Michelfdc40a02009-02-17 22:15:04 +0000160
161 private:
162
Chris Lattner012f2412006-02-17 21:58:01 +0000163 /// SimplifyDemandedBits - Check the specified integer node value to see if
Chris Lattnerb2742f42006-03-01 19:55:35 +0000164 /// it can be simplified or if things it uses can be simplified by bit
Chris Lattner012f2412006-02-17 21:58:01 +0000165 /// propagation. If so, return true.
Dan Gohman475871a2008-07-27 21:46:04 +0000166 bool SimplifyDemandedBits(SDValue Op) {
Dan Gohman87862e72009-12-11 21:31:27 +0000167 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
168 APInt Demanded = APInt::getAllOnesValue(BitWidth);
Dan Gohman7b8d4a92008-02-27 00:25:32 +0000169 return SimplifyDemandedBits(Op, Demanded);
170 }
171
Dan Gohman475871a2008-07-27 21:46:04 +0000172 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
Chris Lattner87514ca2005-10-10 22:31:19 +0000173
Chris Lattner448f2192006-11-11 00:39:41 +0000174 bool CombineToPreIndexedLoadStore(SDNode *N);
175 bool CombineToPostIndexedLoadStore(SDNode *N);
Quentin Colombet83f743a2013-10-11 18:29:42 +0000176 bool SliceUpLoad(SDNode *N);
Scott Michelfdc40a02009-02-17 22:15:04 +0000177
Evan Cheng95c57ea2010-04-24 04:43:44 +0000178 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
179 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
180 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
181 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
Evan Cheng64b7bf72010-04-16 06:14:10 +0000182 SDValue PromoteIntBinOp(SDValue Op);
Evan Cheng07c4e102010-04-22 20:19:46 +0000183 SDValue PromoteIntShiftOp(SDValue Op);
Evan Cheng4c26e932010-04-19 19:29:22 +0000184 SDValue PromoteExtend(SDValue Op);
185 bool PromoteLoad(SDValue Op);
Scott Michelfdc40a02009-02-17 22:15:04 +0000186
Craig Topper6c64fba2013-07-13 07:43:40 +0000187 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickac6d9be2013-05-25 02:42:55 +0000188 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +0000189 ISD::NodeType ExtType);
190
Dan Gohman389079b2007-10-08 17:57:15 +0000191 /// combine - call the node-specific routine that knows how to fold each
192 /// particular type of node. If that doesn't do anything, try the
193 /// target-specific DAG combines.
Dan Gohman475871a2008-07-27 21:46:04 +0000194 SDValue combine(SDNode *N);
Nate Begeman1d4d4142005-09-01 00:19:25 +0000195
196 // Visitation implementation - Implement dag node combining for different
197 // node types. The semantics are as follows:
198 // Return Value:
Evan Cheng17a568b2008-08-29 22:21:44 +0000199 // SDValue.getNode() == 0 - No change was made
200 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
201 // otherwise - N should be replaced by the returned Operand.
Nate Begeman1d4d4142005-09-01 00:19:25 +0000202 //
Dan Gohman475871a2008-07-27 21:46:04 +0000203 SDValue visitTokenFactor(SDNode *N);
204 SDValue visitMERGE_VALUES(SDNode *N);
205 SDValue visitADD(SDNode *N);
206 SDValue visitSUB(SDNode *N);
207 SDValue visitADDC(SDNode *N);
Craig Toppercc274522012-01-07 09:06:39 +0000208 SDValue visitSUBC(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000209 SDValue visitADDE(SDNode *N);
Craig Toppercc274522012-01-07 09:06:39 +0000210 SDValue visitSUBE(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000211 SDValue visitMUL(SDNode *N);
212 SDValue visitSDIV(SDNode *N);
213 SDValue visitUDIV(SDNode *N);
214 SDValue visitSREM(SDNode *N);
215 SDValue visitUREM(SDNode *N);
216 SDValue visitMULHU(SDNode *N);
217 SDValue visitMULHS(SDNode *N);
218 SDValue visitSMUL_LOHI(SDNode *N);
219 SDValue visitUMUL_LOHI(SDNode *N);
Benjamin Kramerf55d26e2011-05-21 18:31:55 +0000220 SDValue visitSMULO(SDNode *N);
221 SDValue visitUMULO(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000222 SDValue visitSDIVREM(SDNode *N);
223 SDValue visitUDIVREM(SDNode *N);
224 SDValue visitAND(SDNode *N);
225 SDValue visitOR(SDNode *N);
226 SDValue visitXOR(SDNode *N);
227 SDValue SimplifyVBinOp(SDNode *N);
Craig Topperdd201ff2012-09-11 01:45:21 +0000228 SDValue SimplifyVUnaryOp(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000229 SDValue visitSHL(SDNode *N);
230 SDValue visitSRA(SDNode *N);
231 SDValue visitSRL(SDNode *N);
Stephen Hines36b56882014-04-23 16:57:46 -0700232 SDValue visitRotate(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000233 SDValue visitCTLZ(SDNode *N);
Chandler Carruth63974b22011-12-13 01:56:10 +0000234 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000235 SDValue visitCTTZ(SDNode *N);
Chandler Carruth63974b22011-12-13 01:56:10 +0000236 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000237 SDValue visitCTPOP(SDNode *N);
238 SDValue visitSELECT(SDNode *N);
Benjamin Kramer6242fda2013-04-26 09:19:19 +0000239 SDValue visitVSELECT(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000240 SDValue visitSELECT_CC(SDNode *N);
241 SDValue visitSETCC(SDNode *N);
242 SDValue visitSIGN_EXTEND(SDNode *N);
243 SDValue visitZERO_EXTEND(SDNode *N);
244 SDValue visitANY_EXTEND(SDNode *N);
245 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
246 SDValue visitTRUNCATE(SDNode *N);
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000247 SDValue visitBITCAST(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000248 SDValue visitBUILD_PAIR(SDNode *N);
249 SDValue visitFADD(SDNode *N);
250 SDValue visitFSUB(SDNode *N);
251 SDValue visitFMUL(SDNode *N);
Owen Anderson062c0a52012-05-02 22:17:40 +0000252 SDValue visitFMA(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000253 SDValue visitFDIV(SDNode *N);
254 SDValue visitFREM(SDNode *N);
255 SDValue visitFCOPYSIGN(SDNode *N);
256 SDValue visitSINT_TO_FP(SDNode *N);
257 SDValue visitUINT_TO_FP(SDNode *N);
258 SDValue visitFP_TO_SINT(SDNode *N);
259 SDValue visitFP_TO_UINT(SDNode *N);
260 SDValue visitFP_ROUND(SDNode *N);
261 SDValue visitFP_ROUND_INREG(SDNode *N);
262 SDValue visitFP_EXTEND(SDNode *N);
263 SDValue visitFNEG(SDNode *N);
264 SDValue visitFABS(SDNode *N);
Owen Anderson7c626d32012-08-13 23:32:49 +0000265 SDValue visitFCEIL(SDNode *N);
266 SDValue visitFTRUNC(SDNode *N);
267 SDValue visitFFLOOR(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000268 SDValue visitBRCOND(SDNode *N);
269 SDValue visitBR_CC(SDNode *N);
270 SDValue visitLOAD(SDNode *N);
271 SDValue visitSTORE(SDNode *N);
272 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
273 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
274 SDValue visitBUILD_VECTOR(SDNode *N);
275 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopese97190f2011-09-20 23:19:33 +0000276 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000277 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Stephen Hines36b56882014-04-23 16:57:46 -0700278 SDValue visitINSERT_SUBVECTOR(SDNode *N);
Chris Lattner01a22022005-10-10 22:04:48 +0000279
Dan Gohman475871a2008-07-27 21:46:04 +0000280 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickac6d9be2013-05-25 02:42:55 +0000281 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelfdc40a02009-02-17 22:15:04 +0000282
Stephen Hines36b56882014-04-23 16:57:46 -0700283 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
Chris Lattnere70da202007-12-06 07:33:36 +0000284
Dan Gohman475871a2008-07-27 21:46:04 +0000285 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
286 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickac6d9be2013-05-25 02:42:55 +0000287 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
288 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelfdc40a02009-02-17 22:15:04 +0000289 SDValue N3, ISD::CondCode CC,
Bill Wendling836ca7d2009-01-30 23:59:18 +0000290 bool NotExtCompare = false);
Owen Andersone50ed302009-08-10 22:56:29 +0000291 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickac6d9be2013-05-25 02:42:55 +0000292 SDLoc DL, bool foldBooleans = true);
Stephen Hines36b56882014-04-23 16:57:46 -0700293
294 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
295 SDValue &CC) const;
296 bool isOneUseSetCC(SDValue N) const;
297
Scott Michelfdc40a02009-02-17 22:15:04 +0000298 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner5eee4272008-01-26 01:09:19 +0000299 unsigned HiOp);
Owen Andersone50ed302009-08-10 22:56:29 +0000300 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000301 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman475871a2008-07-27 21:46:04 +0000302 SDValue BuildSDIV(SDNode *N);
303 SDValue BuildUDIV(SDNode *N);
Evan Cheng9568e5c2011-06-21 06:01:08 +0000304 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
305 bool DemandHighBits = true);
306 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Stephen Hines36b56882014-04-23 16:57:46 -0700307 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
308 SDValue InnerPos, SDValue InnerNeg,
309 unsigned PosOpcode, unsigned NegOpcode,
310 SDLoc DL);
Andrew Trickac6d9be2013-05-25 02:42:55 +0000311 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman475871a2008-07-27 21:46:04 +0000312 SDValue ReduceLoadWidth(SDNode *N);
Evan Cheng8b944d32009-05-28 00:35:15 +0000313 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Cheng31959b12011-02-02 01:06:55 +0000314 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liaofac14ab2012-10-23 23:06:52 +0000315 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao1a5cc712012-10-24 04:14:18 +0000316 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelfdc40a02009-02-17 22:15:04 +0000317
Dan Gohman475871a2008-07-27 21:46:04 +0000318 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelfdc40a02009-02-17 22:15:04 +0000319
Jim Laskey6ff23e52006-10-04 16:53:27 +0000320 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
321 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman475871a2008-07-27 21:46:04 +0000322 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Toppera0ec3f92013-07-14 04:42:23 +0000323 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey6ff23e52006-10-04 16:53:27 +0000324
Jim Laskey096c22e2006-10-18 12:29:57 +0000325 /// isAlias - Return true if there is any possibility that the two addresses
326 /// overlap.
Richard Sandiforda7be36c2013-10-28 12:00:00 +0000327 bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
Jim Laskey096c22e2006-10-18 12:29:57 +0000328 const Value *SrcValue1, int SrcValueOffset1,
Nate Begemanb6aef5c2009-09-15 00:18:30 +0000329 unsigned SrcValueAlign1,
Dan Gohmanf96e4bd2010-10-20 00:31:05 +0000330 const MDNode *TBAAInfo1,
Richard Sandiforda7be36c2013-10-28 12:00:00 +0000331 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
Nate Begemanb6aef5c2009-09-15 00:18:30 +0000332 const Value *SrcValue2, int SrcValueOffset2,
Dan Gohmanf96e4bd2010-10-20 00:31:05 +0000333 unsigned SrcValueAlign2,
334 const MDNode *TBAAInfo2) const;
Scott Michelfdc40a02009-02-17 22:15:04 +0000335
Nadav Rotem90e11dc2012-11-29 00:00:08 +0000336 /// isAlias - Return true if there is any possibility that the two addresses
337 /// overlap.
338 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
339
Jim Laskey7ca56af2006-10-11 13:47:09 +0000340 /// FindAliasInfo - Extracts the relevant alias information from the memory
341 /// node. Returns true if the operand was a load.
342 bool FindAliasInfo(SDNode *N,
Richard Sandiforda7be36c2013-10-28 12:00:00 +0000343 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
Nate Begemanb6aef5c2009-09-15 00:18:30 +0000344 const Value *&SrcValue, int &SrcValueOffset,
Dan Gohmanf96e4bd2010-10-20 00:31:05 +0000345 unsigned &SrcValueAlignment,
346 const MDNode *&TBAAInfo) const;
Scott Michelfdc40a02009-02-17 22:15:04 +0000347
Jim Laskey279f0532006-09-25 16:29:54 +0000348 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
Jim Laskey6ff23e52006-10-04 16:53:27 +0000349 /// looking for a better chain (aliasing node.)
Dan Gohman475871a2008-07-27 21:46:04 +0000350 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands92abc622009-01-31 15:50:11 +0000351
Nadav Rotemc653de62012-10-03 16:11:15 +0000352 /// Merge consecutive store operations into a wide store.
353 /// This optimization uses wide integers or vectors when possible.
354 /// \return True if some memory operations were changed.
355 bool MergeConsecutiveStores(StoreSDNode *N);
356
Stephen Hines36b56882014-04-23 16:57:46 -0700357 /// \brief Try to transform a truncation where C is a constant:
358 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
359 ///
360 /// \p N needs to be a truncation and its first operand an AND. Other
361 /// requirements are checked by the function (e.g. that trunc is
362 /// single-use) and if missed an empty SDValue is returned.
363 SDValue distributeTruncateThroughAnd(SDNode *N);
364
Chris Lattner2392ae72010-04-15 04:48:01 +0000365 public:
Bill Wendling98a366d2009-04-29 23:29:43 +0000366 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombet83f743a2013-10-11 18:29:42 +0000367 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
368 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
369 AttributeSet FnAttrs =
370 DAG.getMachineFunction().getFunction()->getAttributes();
371 ForCodeSize =
372 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
373 Attribute::OptimizeForSize) ||
374 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
375 }
Scott Michelfdc40a02009-02-17 22:15:04 +0000376
Nate Begeman1d4d4142005-09-01 00:19:25 +0000377 /// Run - runs the dag combiner on all nodes in the work list
Duncan Sands25cf2272008-11-24 14:53:14 +0000378 void Run(CombineLevel AtLevel);
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000379
Chris Lattner2392ae72010-04-15 04:48:01 +0000380 SelectionDAG &getDAG() const { return DAG; }
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000381
Chris Lattner2392ae72010-04-15 04:48:01 +0000382 /// getShiftAmountTy - Returns a type large enough to hold any valid
383 /// shift amount - before type legalization these can be huge.
Owen Anderson95771af2011-02-25 21:41:48 +0000384 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky87070fe2013-06-26 10:55:03 +0000385 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
386 if (LHSTy.isVector())
387 return LHSTy;
Jack Carteradbd3ae2013-10-17 01:34:33 +0000388 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
389 : TLI.getPointerTy();
Chris Lattner2392ae72010-04-15 04:48:01 +0000390 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000391
Chris Lattner2392ae72010-04-15 04:48:01 +0000392 /// isTypeLegal - This method returns true if we are running before type
393 /// legalization or if the specified VT is legal.
394 bool isTypeLegal(const EVT &VT) {
395 if (!LegalTypes) return true;
396 return TLI.isTypeLegal(VT);
397 }
Matt Arsenault225ed702013-05-18 00:21:46 +0000398
399 /// getSetCCResultType - Convenience wrapper around
400 /// TargetLowering::getSetCCResultType
401 EVT getSetCCResultType(EVT VT) const {
402 return TLI.getSetCCResultType(*DAG.getContext(), VT);
403 }
Nate Begeman1d4d4142005-09-01 00:19:25 +0000404 };
405}
406
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000407
408namespace {
409/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
410/// nodes from the worklist.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000411class WorkListRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000412 DAGCombiner &DC;
413public:
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +0000414 explicit WorkListRemover(DAGCombiner &dc)
415 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelfdc40a02009-02-17 22:15:04 +0000416
Stephen Hines36b56882014-04-23 16:57:46 -0700417 void NodeDeleted(SDNode *N, SDNode *E) override {
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000418 DC.removeFromWorkList(N);
419 }
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000420};
421}
422
Chris Lattner24664722006-03-01 04:53:38 +0000423//===----------------------------------------------------------------------===//
424// TargetLowering::DAGCombinerInfo implementation
425//===----------------------------------------------------------------------===//
426
427void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
428 ((DAGCombiner*)DC)->AddToWorkList(N);
429}
430
Cameron Zwariched3caf92011-04-02 02:40:26 +0000431void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
432 ((DAGCombiner*)DC)->removeFromWorkList(N);
433}
434
Dan Gohman475871a2008-07-27 21:46:04 +0000435SDValue TargetLowering::DAGCombinerInfo::
Evan Cheng0b0cd912009-03-28 05:57:29 +0000436CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
437 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattner24664722006-03-01 04:53:38 +0000438}
439
Dan Gohman475871a2008-07-27 21:46:04 +0000440SDValue TargetLowering::DAGCombinerInfo::
Evan Cheng0b0cd912009-03-28 05:57:29 +0000441CombineTo(SDNode *N, SDValue Res, bool AddTo) {
442 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattner24664722006-03-01 04:53:38 +0000443}
444
445
Dan Gohman475871a2008-07-27 21:46:04 +0000446SDValue TargetLowering::DAGCombinerInfo::
Evan Cheng0b0cd912009-03-28 05:57:29 +0000447CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
448 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattner24664722006-03-01 04:53:38 +0000449}
450
Dan Gohmane5af2d32009-01-29 01:59:02 +0000451void TargetLowering::DAGCombinerInfo::
452CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
453 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
454}
Chris Lattner24664722006-03-01 04:53:38 +0000455
Chris Lattner24664722006-03-01 04:53:38 +0000456//===----------------------------------------------------------------------===//
Chris Lattner29446522007-05-14 22:04:50 +0000457// Helper Functions
458//===----------------------------------------------------------------------===//
459
460/// isNegatibleForFree - Return 1 if we can compute the negated form of the
461/// specified expression for the same cost as the expression itself, or 2 if we
462/// can compute the negated form more cheaply than the expression itself.
Duncan Sands25cf2272008-11-24 14:53:14 +0000463static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Andersonafd3d562012-03-06 00:29:31 +0000464 const TargetLowering &TLI,
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000465 const TargetOptions *Options,
Chris Lattner0254e702008-02-26 07:04:54 +0000466 unsigned Depth = 0) {
Chris Lattner29446522007-05-14 22:04:50 +0000467 // fneg is removable even if it has multiple uses.
468 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelfdc40a02009-02-17 22:15:04 +0000469
Chris Lattner29446522007-05-14 22:04:50 +0000470 // Don't allow anything with multiple uses.
471 if (!Op.hasOneUse()) return 0;
Scott Michelfdc40a02009-02-17 22:15:04 +0000472
Chris Lattner3adf9512007-05-25 02:19:06 +0000473 // Don't recurse exponentially.
474 if (Depth > 6) return 0;
Scott Michelfdc40a02009-02-17 22:15:04 +0000475
Chris Lattner29446522007-05-14 22:04:50 +0000476 switch (Op.getOpcode()) {
477 default: return false;
478 case ISD::ConstantFP:
Chris Lattner0254e702008-02-26 07:04:54 +0000479 // Don't invert constant FP values after legalize. The negated constant
480 // isn't necessarily legal.
Duncan Sands25cf2272008-11-24 14:53:14 +0000481 return LegalOperations ? 0 : 1;
Chris Lattner29446522007-05-14 22:04:50 +0000482 case ISD::FADD:
483 // FIXME: determine better conditions for this xform.
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000484 if (!Options->UnsafeFPMath) return 0;
Scott Michelfdc40a02009-02-17 22:15:04 +0000485
Owen Andersonafd3d562012-03-06 00:29:31 +0000486 // After operation legalization, it might not be legal to create new FSUBs.
487 if (LegalOperations &&
488 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
489 return 0;
490
Craig Topper956342b2012-09-09 22:58:45 +0000491 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Andersonafd3d562012-03-06 00:29:31 +0000492 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
493 Options, Depth + 1))
Chris Lattner29446522007-05-14 22:04:50 +0000494 return V;
Bill Wendlingd34470c2009-01-30 23:10:18 +0000495 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Andersonafd3d562012-03-06 00:29:31 +0000496 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000497 Depth + 1);
Chris Lattner29446522007-05-14 22:04:50 +0000498 case ISD::FSUB:
Scott Michelfdc40a02009-02-17 22:15:04 +0000499 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000500 if (!Options->UnsafeFPMath) return 0;
Scott Michelfdc40a02009-02-17 22:15:04 +0000501
Bill Wendlingd34470c2009-01-30 23:10:18 +0000502 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattner29446522007-05-14 22:04:50 +0000503 return 1;
Scott Michelfdc40a02009-02-17 22:15:04 +0000504
Chris Lattner29446522007-05-14 22:04:50 +0000505 case ISD::FMUL:
506 case ISD::FDIV:
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000507 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelfdc40a02009-02-17 22:15:04 +0000508
Bill Wendlingd34470c2009-01-30 23:10:18 +0000509 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Andersonafd3d562012-03-06 00:29:31 +0000510 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
511 Options, Depth + 1))
Chris Lattner29446522007-05-14 22:04:50 +0000512 return V;
Scott Michelfdc40a02009-02-17 22:15:04 +0000513
Owen Andersonafd3d562012-03-06 00:29:31 +0000514 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000515 Depth + 1);
Scott Michelfdc40a02009-02-17 22:15:04 +0000516
Chris Lattner29446522007-05-14 22:04:50 +0000517 case ISD::FP_EXTEND:
518 case ISD::FP_ROUND:
519 case ISD::FSIN:
Owen Andersonafd3d562012-03-06 00:29:31 +0000520 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000521 Depth + 1);
Chris Lattner29446522007-05-14 22:04:50 +0000522 }
523}
524
525/// GetNegatedExpression - If isNegatibleForFree returns true, this function
526/// returns the newly negated expression.
Dan Gohman475871a2008-07-27 21:46:04 +0000527static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sands25cf2272008-11-24 14:53:14 +0000528 bool LegalOperations, unsigned Depth = 0) {
Chris Lattner29446522007-05-14 22:04:50 +0000529 // fneg is removable even if it has multiple uses.
530 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelfdc40a02009-02-17 22:15:04 +0000531
Chris Lattner29446522007-05-14 22:04:50 +0000532 // Don't allow anything with multiple uses.
533 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelfdc40a02009-02-17 22:15:04 +0000534
Chris Lattner3adf9512007-05-25 02:19:06 +0000535 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattner29446522007-05-14 22:04:50 +0000536 switch (Op.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000537 default: llvm_unreachable("Unknown code");
Dale Johannesenc4dd3c32007-08-31 23:34:27 +0000538 case ISD::ConstantFP: {
539 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
540 V.changeSign();
541 return DAG.getConstantFP(V, Op.getValueType());
542 }
Chris Lattner29446522007-05-14 22:04:50 +0000543 case ISD::FADD:
544 // FIXME: determine better conditions for this xform.
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000545 assert(DAG.getTarget().Options.UnsafeFPMath);
Scott Michelfdc40a02009-02-17 22:15:04 +0000546
Bill Wendlingd34470c2009-01-30 23:10:18 +0000547 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000548 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Andersonafd3d562012-03-06 00:29:31 +0000549 DAG.getTargetLoweringInfo(),
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000550 &DAG.getTarget().Options, Depth+1))
Andrew Trickac6d9be2013-05-25 02:42:55 +0000551 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelfdc40a02009-02-17 22:15:04 +0000552 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sands25cf2272008-11-24 14:53:14 +0000553 LegalOperations, Depth+1),
Chris Lattner29446522007-05-14 22:04:50 +0000554 Op.getOperand(1));
Bill Wendlingd34470c2009-01-30 23:10:18 +0000555 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickac6d9be2013-05-25 02:42:55 +0000556 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelfdc40a02009-02-17 22:15:04 +0000557 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sands25cf2272008-11-24 14:53:14 +0000558 LegalOperations, Depth+1),
Chris Lattner29446522007-05-14 22:04:50 +0000559 Op.getOperand(0));
560 case ISD::FSUB:
Scott Michelfdc40a02009-02-17 22:15:04 +0000561 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000562 assert(DAG.getTarget().Options.UnsafeFPMath);
Dan Gohman23ff1822007-07-02 15:48:56 +0000563
Bill Wendlingd34470c2009-01-30 23:10:18 +0000564 // fold (fneg (fsub 0, B)) -> B
Dan Gohman23ff1822007-07-02 15:48:56 +0000565 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesenc4dd3c32007-08-31 23:34:27 +0000566 if (N0CFP->getValueAPF().isZero())
Dan Gohman23ff1822007-07-02 15:48:56 +0000567 return Op.getOperand(1);
Scott Michelfdc40a02009-02-17 22:15:04 +0000568
Bill Wendlingd34470c2009-01-30 23:10:18 +0000569 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickac6d9be2013-05-25 02:42:55 +0000570 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendling35247c32009-01-30 00:45:56 +0000571 Op.getOperand(1), Op.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +0000572
Chris Lattner29446522007-05-14 22:04:50 +0000573 case ISD::FMUL:
574 case ISD::FDIV:
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000575 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
Scott Michelfdc40a02009-02-17 22:15:04 +0000576
Bill Wendlingd34470c2009-01-30 23:10:18 +0000577 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000578 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Andersonafd3d562012-03-06 00:29:31 +0000579 DAG.getTargetLoweringInfo(),
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000580 &DAG.getTarget().Options, Depth+1))
Andrew Trickac6d9be2013-05-25 02:42:55 +0000581 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelfdc40a02009-02-17 22:15:04 +0000582 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sands25cf2272008-11-24 14:53:14 +0000583 LegalOperations, Depth+1),
Chris Lattner29446522007-05-14 22:04:50 +0000584 Op.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +0000585
Bill Wendlingd34470c2009-01-30 23:10:18 +0000586 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickac6d9be2013-05-25 02:42:55 +0000587 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattner29446522007-05-14 22:04:50 +0000588 Op.getOperand(0),
Chris Lattner0254e702008-02-26 07:04:54 +0000589 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sands25cf2272008-11-24 14:53:14 +0000590 LegalOperations, Depth+1));
Scott Michelfdc40a02009-02-17 22:15:04 +0000591
Chris Lattner29446522007-05-14 22:04:50 +0000592 case ISD::FP_EXTEND:
Chris Lattner29446522007-05-14 22:04:50 +0000593 case ISD::FSIN:
Andrew Trickac6d9be2013-05-25 02:42:55 +0000594 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelfdc40a02009-02-17 22:15:04 +0000595 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sands25cf2272008-11-24 14:53:14 +0000596 LegalOperations, Depth+1));
Chris Lattner0bd48932008-01-17 07:00:52 +0000597 case ISD::FP_ROUND:
Andrew Trickac6d9be2013-05-25 02:42:55 +0000598 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelfdc40a02009-02-17 22:15:04 +0000599 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sands25cf2272008-11-24 14:53:14 +0000600 LegalOperations, Depth+1),
Chris Lattner0bd48932008-01-17 07:00:52 +0000601 Op.getOperand(1));
Chris Lattner29446522007-05-14 22:04:50 +0000602 }
603}
Chris Lattner24664722006-03-01 04:53:38 +0000604
Nate Begeman4ebd8052005-09-01 23:24:04 +0000605// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
Stephen Hines36b56882014-04-23 16:57:46 -0700606// that selects between the target values used for true and false, making it
607// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
608// the appropriate nodes based on the type of node we are checking. This
609// simplifies life a bit for the callers.
610bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
611 SDValue &CC) const {
Nate Begeman646d7e22005-09-02 21:18:40 +0000612 if (N.getOpcode() == ISD::SETCC) {
613 LHS = N.getOperand(0);
614 RHS = N.getOperand(1);
615 CC = N.getOperand(2);
Nate Begeman4ebd8052005-09-01 23:24:04 +0000616 return true;
Nate Begeman646d7e22005-09-02 21:18:40 +0000617 }
Stephen Hines36b56882014-04-23 16:57:46 -0700618
619 if (N.getOpcode() != ISD::SELECT_CC ||
620 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
621 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
622 return false;
623
624 LHS = N.getOperand(0);
625 RHS = N.getOperand(1);
626 CC = N.getOperand(4);
627 return true;
Nate Begeman1d4d4142005-09-01 00:19:25 +0000628}
629
Nate Begeman99801192005-09-07 23:25:52 +0000630// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
631// one use. If this is true, it allows the users to invert the operation for
632// free when it is profitable to do so.
Stephen Hines36b56882014-04-23 16:57:46 -0700633bool DAGCombiner::isOneUseSetCC(SDValue N) const {
Dan Gohman475871a2008-07-27 21:46:04 +0000634 SDValue N0, N1, N2;
Gabor Greifba36cb52008-08-28 21:40:38 +0000635 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman4ebd8052005-09-01 23:24:04 +0000636 return true;
637 return false;
638}
639
Stephen Hines36b56882014-04-23 16:57:46 -0700640/// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
641/// elements are all the same constant or undefined.
642static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
643 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
644 if (!C)
645 return false;
646
647 APInt SplatUndef;
648 unsigned SplatBitSize;
649 bool HasAnyUndefs;
650 EVT EltVT = N->getValueType(0).getVectorElementType();
651 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
652 HasAnyUndefs) &&
653 EltVT.getSizeInBits() >= SplatBitSize);
654}
655
656// \brief Returns the SDNode if it is a constant BuildVector or constant.
657static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
658 if (isa<ConstantSDNode>(N))
659 return N.getNode();
660 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
661 if(BV && BV->isConstant())
662 return BV;
663 return NULL;
664}
665
666// \brief Returns the SDNode if it is a constant splat BuildVector or constant
667// int.
668static ConstantSDNode *isConstOrConstSplat(SDValue N) {
669 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
670 return CN;
671
672 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N))
673 return BV->getConstantSplatValue();
674
675 return nullptr;
676}
677
Andrew Trickac6d9be2013-05-25 02:42:55 +0000678SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendling35247c32009-01-30 00:45:56 +0000679 SDValue N0, SDValue N1) {
Owen Andersone50ed302009-08-10 22:56:29 +0000680 EVT VT = N0.getValueType();
Stephen Hines36b56882014-04-23 16:57:46 -0700681 if (N0.getOpcode() == Opc) {
682 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
683 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
684 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
685 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
686 if (!OpNode.getNode())
687 return SDValue();
688 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
689 }
690 if (N0.hasOneUse()) {
691 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
692 // use
693 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
694 if (!OpNode.getNode())
695 return SDValue();
696 AddToWorkList(OpNode.getNode());
697 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
698 }
Nate Begemancd4d58c2006-02-03 06:46:56 +0000699 }
700 }
Bill Wendling35247c32009-01-30 00:45:56 +0000701
Stephen Hines36b56882014-04-23 16:57:46 -0700702 if (N1.getOpcode() == Opc) {
703 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
704 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
705 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
706 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
707 if (!OpNode.getNode())
708 return SDValue();
709 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
710 }
711 if (N1.hasOneUse()) {
712 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
713 // use
714 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
715 if (!OpNode.getNode())
716 return SDValue();
717 AddToWorkList(OpNode.getNode());
718 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
719 }
Nate Begemancd4d58c2006-02-03 06:46:56 +0000720 }
721 }
Bill Wendling35247c32009-01-30 00:45:56 +0000722
Dan Gohman475871a2008-07-27 21:46:04 +0000723 return SDValue();
Nate Begemancd4d58c2006-02-03 06:46:56 +0000724}
725
Dan Gohman475871a2008-07-27 21:46:04 +0000726SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
727 bool AddTo) {
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000728 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
729 ++NodesCombined;
David Greenef1090292010-01-05 01:25:00 +0000730 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000731 N->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +0000732 dbgs() << "\nWith: ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000733 To[0].getNode()->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +0000734 dbgs() << " and " << NumTo-1 << " other values\n";
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000735 for (unsigned i = 0, e = NumTo; i != e; ++i)
Jakob Stoklund Olesen9f0d4e62009-12-03 05:15:35 +0000736 assert((!To[i].getNode() ||
737 N->getValueType(i) == To[i].getValueType()) &&
Dan Gohman764fd0c2009-01-21 15:17:51 +0000738 "Cannot combine value to value of different type!"));
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000739 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +0000740 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000741 if (AddTo) {
742 // Push the new nodes and any users onto the worklist
743 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattnerd1980a52009-03-12 06:52:53 +0000744 if (To[i].getNode()) {
745 AddToWorkList(To[i].getNode());
746 AddUsersToWorkList(To[i].getNode());
747 }
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000748 }
749 }
Scott Michelfdc40a02009-02-17 22:15:04 +0000750
Dan Gohmandbe664a2009-01-19 21:44:21 +0000751 // Finally, if the node is now dead, remove it from the graph. The node
752 // may not be dead if the replacement process recursively simplified to
753 // something else needing this node.
754 if (N->use_empty()) {
755 // Nodes can be reintroduced into the worklist. Make sure we do not
756 // process a node that has been replaced.
757 removeFromWorkList(N);
Scott Michelfdc40a02009-02-17 22:15:04 +0000758
Dan Gohmandbe664a2009-01-19 21:44:21 +0000759 // Finally, since the node is now dead, remove it from the graph.
760 DAG.DeleteNode(N);
761 }
Dan Gohman475871a2008-07-27 21:46:04 +0000762 return SDValue(N, 0);
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000763}
764
Evan Chenge5b51ac2010-04-17 06:13:15 +0000765void DAGCombiner::
766CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelfdc40a02009-02-17 22:15:04 +0000767 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000768 // are deleted, make sure to remove them from our worklist.
769 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +0000770 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane5af2d32009-01-29 01:59:02 +0000771
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000772 // Push the new node and any (possibly new) users onto the worklist.
Gabor Greifba36cb52008-08-28 21:40:38 +0000773 AddToWorkList(TLO.New.getNode());
774 AddUsersToWorkList(TLO.New.getNode());
Scott Michelfdc40a02009-02-17 22:15:04 +0000775
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000776 // Finally, if the node is now dead, remove it from the graph. The node
777 // may not be dead if the replacement process recursively simplified to
778 // something else needing this node.
Gabor Greifba36cb52008-08-28 21:40:38 +0000779 if (TLO.Old.getNode()->use_empty()) {
780 removeFromWorkList(TLO.Old.getNode());
Scott Michelfdc40a02009-02-17 22:15:04 +0000781
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000782 // If the operands of this node are only used by the node, they will now
783 // be dead. Make sure to visit them first to delete dead nodes early.
Gabor Greifba36cb52008-08-28 21:40:38 +0000784 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
785 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
786 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
Scott Michelfdc40a02009-02-17 22:15:04 +0000787
Gabor Greifba36cb52008-08-28 21:40:38 +0000788 DAG.DeleteNode(TLO.Old.getNode());
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000789 }
Dan Gohmane5af2d32009-01-29 01:59:02 +0000790}
791
792/// SimplifyDemandedBits - Check the specified integer node value to see if
793/// it can be simplified or if things it uses can be simplified by bit
794/// propagation. If so, return true.
795bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chenge5b51ac2010-04-17 06:13:15 +0000796 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane5af2d32009-01-29 01:59:02 +0000797 APInt KnownZero, KnownOne;
798 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
799 return false;
Scott Michelfdc40a02009-02-17 22:15:04 +0000800
Dan Gohmane5af2d32009-01-29 01:59:02 +0000801 // Revisit the node.
802 AddToWorkList(Op.getNode());
Scott Michelfdc40a02009-02-17 22:15:04 +0000803
Dan Gohmane5af2d32009-01-29 01:59:02 +0000804 // Replace the old value with the new one.
805 ++NodesCombined;
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000806 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000807 TLO.Old.getNode()->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +0000808 dbgs() << "\nWith: ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000809 TLO.New.getNode()->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +0000810 dbgs() << '\n');
Scott Michelfdc40a02009-02-17 22:15:04 +0000811
Dan Gohmane5af2d32009-01-29 01:59:02 +0000812 CommitTargetLoweringOpt(TLO);
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000813 return true;
814}
815
Evan Cheng95c57ea2010-04-24 04:43:44 +0000816void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickac6d9be2013-05-25 02:42:55 +0000817 SDLoc dl(Load);
Evan Cheng95c57ea2010-04-24 04:43:44 +0000818 EVT VT = Load->getValueType(0);
819 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Cheng4c26e932010-04-19 19:29:22 +0000820
Evan Cheng95c57ea2010-04-24 04:43:44 +0000821 DEBUG(dbgs() << "\nReplacing.9 ";
822 Load->dump(&DAG);
823 dbgs() << "\nWith: ";
824 Trunc.getNode()->dump(&DAG);
825 dbgs() << '\n');
826 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +0000827 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
828 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Evan Cheng95c57ea2010-04-24 04:43:44 +0000829 removeFromWorkList(Load);
830 DAG.DeleteNode(Load);
Evan Chengac7eae52010-04-27 19:48:13 +0000831 AddToWorkList(Trunc.getNode());
Evan Cheng95c57ea2010-04-24 04:43:44 +0000832}
833
834SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
835 Replace = false;
Andrew Trickac6d9be2013-05-25 02:42:55 +0000836 SDLoc dl(Op);
Evan Chenge5b51ac2010-04-17 06:13:15 +0000837 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chengac7eae52010-04-27 19:48:13 +0000838 EVT MemVT = LD->getMemoryVT();
839 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Anderson95771af2011-02-25 21:41:48 +0000840 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopher503a64d2010-12-09 04:48:06 +0000841 : ISD::EXTLOAD)
Evan Chengac7eae52010-04-27 19:48:13 +0000842 : LD->getExtensionType();
Evan Cheng95c57ea2010-04-24 04:43:44 +0000843 Replace = true;
Stuart Hastingsa9011292011-02-16 16:23:55 +0000844 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge5b51ac2010-04-17 06:13:15 +0000845 LD->getChain(), LD->getBasePtr(),
Richard Sandiford66589dc2013-10-28 11:17:59 +0000846 MemVT, LD->getMemOperand());
Evan Chenge5b51ac2010-04-17 06:13:15 +0000847 }
848
Evan Cheng4c26e932010-04-19 19:29:22 +0000849 unsigned Opc = Op.getOpcode();
Evan Chengcaf77402010-04-23 19:10:30 +0000850 switch (Opc) {
851 default: break;
852 case ISD::AssertSext:
Evan Cheng4c26e932010-04-19 19:29:22 +0000853 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng95c57ea2010-04-24 04:43:44 +0000854 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Cheng4c26e932010-04-19 19:29:22 +0000855 Op.getOperand(1));
Evan Chengcaf77402010-04-23 19:10:30 +0000856 case ISD::AssertZext:
Evan Cheng4c26e932010-04-19 19:29:22 +0000857 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng95c57ea2010-04-24 04:43:44 +0000858 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Cheng4c26e932010-04-19 19:29:22 +0000859 Op.getOperand(1));
Evan Chengcaf77402010-04-23 19:10:30 +0000860 case ISD::Constant: {
861 unsigned ExtOpc =
Evan Cheng4c26e932010-04-19 19:29:22 +0000862 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengcaf77402010-04-23 19:10:30 +0000863 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000864 }
Evan Chengcaf77402010-04-23 19:10:30 +0000865 }
866
867 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chenge5b51ac2010-04-17 06:13:15 +0000868 return SDValue();
Evan Chengcaf77402010-04-23 19:10:30 +0000869 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Cheng64b7bf72010-04-16 06:14:10 +0000870}
871
Evan Cheng95c57ea2010-04-24 04:43:44 +0000872SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chenge5b51ac2010-04-17 06:13:15 +0000873 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
874 return SDValue();
875 EVT OldVT = Op.getValueType();
Andrew Trickac6d9be2013-05-25 02:42:55 +0000876 SDLoc dl(Op);
Evan Cheng95c57ea2010-04-24 04:43:44 +0000877 bool Replace = false;
878 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
879 if (NewOp.getNode() == 0)
Evan Chenge5b51ac2010-04-17 06:13:15 +0000880 return SDValue();
Evan Chengac7eae52010-04-27 19:48:13 +0000881 AddToWorkList(NewOp.getNode());
Evan Cheng95c57ea2010-04-24 04:43:44 +0000882
883 if (Replace)
884 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
885 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chenge5b51ac2010-04-17 06:13:15 +0000886 DAG.getValueType(OldVT));
887}
888
Evan Cheng95c57ea2010-04-24 04:43:44 +0000889SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chenge5b51ac2010-04-17 06:13:15 +0000890 EVT OldVT = Op.getValueType();
Andrew Trickac6d9be2013-05-25 02:42:55 +0000891 SDLoc dl(Op);
Evan Cheng95c57ea2010-04-24 04:43:44 +0000892 bool Replace = false;
893 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
894 if (NewOp.getNode() == 0)
Evan Chenge5b51ac2010-04-17 06:13:15 +0000895 return SDValue();
Evan Chengac7eae52010-04-27 19:48:13 +0000896 AddToWorkList(NewOp.getNode());
Evan Cheng95c57ea2010-04-24 04:43:44 +0000897
898 if (Replace)
899 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
900 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chenge5b51ac2010-04-17 06:13:15 +0000901}
902
Evan Cheng64b7bf72010-04-16 06:14:10 +0000903/// PromoteIntBinOp - Promote the specified integer binary operation if the
904/// target indicates it is beneficial. e.g. On x86, it's usually better to
905/// promote i16 operations to i32 since i16 instructions are longer.
906SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
907 if (!LegalOperations)
908 return SDValue();
909
910 EVT VT = Op.getValueType();
911 if (VT.isVector() || !VT.isInteger())
912 return SDValue();
913
Evan Chenge5b51ac2010-04-17 06:13:15 +0000914 // If operation type is 'undesirable', e.g. i16 on x86, consider
915 // promoting it.
916 unsigned Opc = Op.getOpcode();
917 if (TLI.isTypeDesirableForOp(Opc, VT))
918 return SDValue();
919
Evan Cheng64b7bf72010-04-16 06:14:10 +0000920 EVT PVT = VT;
Evan Chenge5b51ac2010-04-17 06:13:15 +0000921 // Consult target whether it is a good idea to promote this operation and
922 // what's the right type to promote it to.
923 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Cheng64b7bf72010-04-16 06:14:10 +0000924 assert(PVT != VT && "Don't know what type to promote to!");
925
Evan Cheng95c57ea2010-04-24 04:43:44 +0000926 bool Replace0 = false;
927 SDValue N0 = Op.getOperand(0);
928 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
929 if (NN0.getNode() == 0)
Evan Cheng07c4e102010-04-22 20:19:46 +0000930 return SDValue();
931
Evan Cheng95c57ea2010-04-24 04:43:44 +0000932 bool Replace1 = false;
933 SDValue N1 = Op.getOperand(1);
Evan Chengaad753b2010-05-10 19:03:57 +0000934 SDValue NN1;
935 if (N0 == N1)
936 NN1 = NN0;
937 else {
938 NN1 = PromoteOperand(N1, PVT, Replace1);
939 if (NN1.getNode() == 0)
940 return SDValue();
941 }
Evan Cheng07c4e102010-04-22 20:19:46 +0000942
Evan Cheng95c57ea2010-04-24 04:43:44 +0000943 AddToWorkList(NN0.getNode());
Evan Chengaad753b2010-05-10 19:03:57 +0000944 if (NN1.getNode())
945 AddToWorkList(NN1.getNode());
Evan Cheng95c57ea2010-04-24 04:43:44 +0000946
947 if (Replace0)
948 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
949 if (Replace1)
950 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Cheng07c4e102010-04-22 20:19:46 +0000951
Evan Chengac7eae52010-04-27 19:48:13 +0000952 DEBUG(dbgs() << "\nPromoting ";
953 Op.getNode()->dump(&DAG));
Andrew Trickac6d9be2013-05-25 02:42:55 +0000954 SDLoc dl(Op);
Evan Cheng07c4e102010-04-22 20:19:46 +0000955 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng95c57ea2010-04-24 04:43:44 +0000956 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Cheng07c4e102010-04-22 20:19:46 +0000957 }
958 return SDValue();
959}
960
961/// PromoteIntShiftOp - Promote the specified integer shift operation if the
962/// target indicates it is beneficial. e.g. On x86, it's usually better to
963/// promote i16 operations to i32 since i16 instructions are longer.
964SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
965 if (!LegalOperations)
966 return SDValue();
967
968 EVT VT = Op.getValueType();
969 if (VT.isVector() || !VT.isInteger())
970 return SDValue();
971
972 // If operation type is 'undesirable', e.g. i16 on x86, consider
973 // promoting it.
974 unsigned Opc = Op.getOpcode();
975 if (TLI.isTypeDesirableForOp(Opc, VT))
976 return SDValue();
977
978 EVT PVT = VT;
979 // Consult target whether it is a good idea to promote this operation and
980 // what's the right type to promote it to.
981 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
982 assert(PVT != VT && "Don't know what type to promote to!");
983
Evan Cheng95c57ea2010-04-24 04:43:44 +0000984 bool Replace = false;
Evan Chenge5b51ac2010-04-17 06:13:15 +0000985 SDValue N0 = Op.getOperand(0);
986 if (Opc == ISD::SRA)
Evan Cheng95c57ea2010-04-24 04:43:44 +0000987 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chenge5b51ac2010-04-17 06:13:15 +0000988 else if (Opc == ISD::SRL)
Evan Cheng95c57ea2010-04-24 04:43:44 +0000989 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chenge5b51ac2010-04-17 06:13:15 +0000990 else
Evan Cheng95c57ea2010-04-24 04:43:44 +0000991 N0 = PromoteOperand(N0, PVT, Replace);
Evan Chenge5b51ac2010-04-17 06:13:15 +0000992 if (N0.getNode() == 0)
993 return SDValue();
Evan Cheng95c57ea2010-04-24 04:43:44 +0000994
Evan Chenge5b51ac2010-04-17 06:13:15 +0000995 AddToWorkList(N0.getNode());
Evan Cheng95c57ea2010-04-24 04:43:44 +0000996 if (Replace)
997 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Cheng64b7bf72010-04-16 06:14:10 +0000998
Evan Chengac7eae52010-04-27 19:48:13 +0000999 DEBUG(dbgs() << "\nPromoting ";
1000 Op.getNode()->dump(&DAG));
Andrew Trickac6d9be2013-05-25 02:42:55 +00001001 SDLoc dl(Op);
Evan Cheng64b7bf72010-04-16 06:14:10 +00001002 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng07c4e102010-04-22 20:19:46 +00001003 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Cheng64b7bf72010-04-16 06:14:10 +00001004 }
1005 return SDValue();
1006}
1007
Evan Cheng4c26e932010-04-19 19:29:22 +00001008SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1009 if (!LegalOperations)
1010 return SDValue();
1011
1012 EVT VT = Op.getValueType();
1013 if (VT.isVector() || !VT.isInteger())
1014 return SDValue();
1015
1016 // If operation type is 'undesirable', e.g. i16 on x86, consider
1017 // promoting it.
1018 unsigned Opc = Op.getOpcode();
1019 if (TLI.isTypeDesirableForOp(Opc, VT))
1020 return SDValue();
1021
1022 EVT PVT = VT;
1023 // Consult target whether it is a good idea to promote this operation and
1024 // what's the right type to promote it to.
1025 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1026 assert(PVT != VT && "Don't know what type to promote to!");
1027 // fold (aext (aext x)) -> (aext x)
1028 // fold (aext (zext x)) -> (zext x)
1029 // fold (aext (sext x)) -> (sext x)
Evan Chengac7eae52010-04-27 19:48:13 +00001030 DEBUG(dbgs() << "\nPromoting ";
1031 Op.getNode()->dump(&DAG));
Andrew Trickac6d9be2013-05-25 02:42:55 +00001032 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Cheng4c26e932010-04-19 19:29:22 +00001033 }
1034 return SDValue();
1035}
1036
1037bool DAGCombiner::PromoteLoad(SDValue Op) {
1038 if (!LegalOperations)
1039 return false;
1040
1041 EVT VT = Op.getValueType();
1042 if (VT.isVector() || !VT.isInteger())
1043 return false;
1044
1045 // If operation type is 'undesirable', e.g. i16 on x86, consider
1046 // promoting it.
1047 unsigned Opc = Op.getOpcode();
1048 if (TLI.isTypeDesirableForOp(Opc, VT))
1049 return false;
1050
1051 EVT PVT = VT;
1052 // Consult target whether it is a good idea to promote this operation and
1053 // what's the right type to promote it to.
1054 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1055 assert(PVT != VT && "Don't know what type to promote to!");
1056
Andrew Trickac6d9be2013-05-25 02:42:55 +00001057 SDLoc dl(Op);
Evan Cheng4c26e932010-04-19 19:29:22 +00001058 SDNode *N = Op.getNode();
1059 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chengac7eae52010-04-27 19:48:13 +00001060 EVT MemVT = LD->getMemoryVT();
1061 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Anderson95771af2011-02-25 21:41:48 +00001062 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopher503a64d2010-12-09 04:48:06 +00001063 : ISD::EXTLOAD)
Evan Chengac7eae52010-04-27 19:48:13 +00001064 : LD->getExtensionType();
Stuart Hastingsa9011292011-02-16 16:23:55 +00001065 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Cheng4c26e932010-04-19 19:29:22 +00001066 LD->getChain(), LD->getBasePtr(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00001067 MemVT, LD->getMemOperand());
Evan Cheng4c26e932010-04-19 19:29:22 +00001068 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1069
Evan Cheng95c57ea2010-04-24 04:43:44 +00001070 DEBUG(dbgs() << "\nPromoting ";
Evan Cheng4c26e932010-04-19 19:29:22 +00001071 N->dump(&DAG);
Evan Cheng95c57ea2010-04-24 04:43:44 +00001072 dbgs() << "\nTo: ";
Evan Cheng4c26e932010-04-19 19:29:22 +00001073 Result.getNode()->dump(&DAG);
1074 dbgs() << '\n');
1075 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00001076 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1077 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Evan Cheng4c26e932010-04-19 19:29:22 +00001078 removeFromWorkList(N);
1079 DAG.DeleteNode(N);
Evan Chengac7eae52010-04-27 19:48:13 +00001080 AddToWorkList(Result.getNode());
Evan Cheng4c26e932010-04-19 19:29:22 +00001081 return true;
1082 }
1083 return false;
1084}
1085
Evan Chenge5b51ac2010-04-17 06:13:15 +00001086
Chris Lattner29446522007-05-14 22:04:50 +00001087//===----------------------------------------------------------------------===//
1088// Main DAG Combiner implementation
1089//===----------------------------------------------------------------------===//
1090
Duncan Sands25cf2272008-11-24 14:53:14 +00001091void DAGCombiner::Run(CombineLevel AtLevel) {
1092 // set the instance variables, so that the various visit routines may use it.
1093 Level = AtLevel;
Eli Friedman50185242011-11-12 00:35:34 +00001094 LegalOperations = Level >= AfterLegalizeVectorOps;
1095 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman4ebd8052005-09-01 23:24:04 +00001096
Evan Cheng17a568b2008-08-29 22:21:44 +00001097 // Add all the dag nodes to the worklist.
Evan Cheng17a568b2008-08-29 22:21:44 +00001098 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1099 E = DAG.allnodes_end(); I != E; ++I)
James Molloy6660c052012-02-16 09:17:04 +00001100 AddToWorkList(I);
Duncan Sands25cf2272008-11-24 14:53:14 +00001101
Evan Cheng17a568b2008-08-29 22:21:44 +00001102 // Create a dummy node (which is not added to allnodes), that adds a reference
1103 // to the root node, preventing it from being deleted, and tracking any
1104 // changes of the root.
1105 HandleSDNode Dummy(DAG.getRoot());
Scott Michelfdc40a02009-02-17 22:15:04 +00001106
Jim Laskey26f7fa72006-10-17 19:33:52 +00001107 // The root of the dag may dangle to deleted nodes until the dag combiner is
1108 // done. Set it to null to avoid confusion.
Dan Gohman475871a2008-07-27 21:46:04 +00001109 DAG.setRoot(SDValue());
Scott Michelfdc40a02009-02-17 22:15:04 +00001110
James Molloy6660c052012-02-16 09:17:04 +00001111 // while the worklist isn't empty, find a node and
Evan Cheng17a568b2008-08-29 22:21:44 +00001112 // try and combine it.
James Molloy6660c052012-02-16 09:17:04 +00001113 while (!WorkListContents.empty()) {
1114 SDNode *N;
Jack Carteradbd3ae2013-10-17 01:34:33 +00001115 // The WorkListOrder holds the SDNodes in order, but it may contain
1116 // duplicates.
James Molloy6660c052012-02-16 09:17:04 +00001117 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1118 // worklist *should* contain, and check the node we want to visit is should
1119 // actually be visited.
1120 do {
Benjamin Kramerd5f76902012-03-10 00:23:58 +00001121 N = WorkListOrder.pop_back_val();
James Molloy6660c052012-02-16 09:17:04 +00001122 } while (!WorkListContents.erase(N));
Scott Michelfdc40a02009-02-17 22:15:04 +00001123
Evan Cheng17a568b2008-08-29 22:21:44 +00001124 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1125 // N is deleted from the DAG, since they too may now be dead or may have a
1126 // reduced number of uses, allowing other xforms.
1127 if (N->use_empty() && N != &Dummy) {
1128 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1129 AddToWorkList(N->getOperand(i).getNode());
Scott Michelfdc40a02009-02-17 22:15:04 +00001130
Evan Cheng17a568b2008-08-29 22:21:44 +00001131 DAG.DeleteNode(N);
1132 continue;
Nate Begeman1d4d4142005-09-01 00:19:25 +00001133 }
Scott Michelfdc40a02009-02-17 22:15:04 +00001134
Evan Cheng17a568b2008-08-29 22:21:44 +00001135 SDValue RV = combine(N);
Scott Michelfdc40a02009-02-17 22:15:04 +00001136
Evan Cheng17a568b2008-08-29 22:21:44 +00001137 if (RV.getNode() == 0)
1138 continue;
Scott Michelfdc40a02009-02-17 22:15:04 +00001139
Evan Cheng17a568b2008-08-29 22:21:44 +00001140 ++NodesCombined;
Scott Michelfdc40a02009-02-17 22:15:04 +00001141
Evan Cheng17a568b2008-08-29 22:21:44 +00001142 // If we get back the same node we passed in, rather than a new node or
1143 // zero, we know that the node must have defined multiple values and
Scott Michelfdc40a02009-02-17 22:15:04 +00001144 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng17a568b2008-08-29 22:21:44 +00001145 // mechanics for us, we have no work to do in this case.
1146 if (RV.getNode() == N)
1147 continue;
Scott Michelfdc40a02009-02-17 22:15:04 +00001148
Evan Cheng17a568b2008-08-29 22:21:44 +00001149 assert(N->getOpcode() != ISD::DELETED_NODE &&
1150 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1151 "Node was deleted but visit returned new node!");
Chris Lattner729c6d12006-05-27 00:43:02 +00001152
Wesley Peckbf17cfa2010-11-23 03:31:01 +00001153 DEBUG(dbgs() << "\nReplacing.3 ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001154 N->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00001155 dbgs() << "\nWith: ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001156 RV.getNode()->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00001157 dbgs() << '\n');
Eric Christopher7332e6e2011-07-14 01:12:15 +00001158
Devang Patel9728ea22011-05-23 22:04:42 +00001159 // Transfer debug value.
1160 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng17a568b2008-08-29 22:21:44 +00001161 WorkListRemover DeadNodes(*this);
1162 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00001163 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng17a568b2008-08-29 22:21:44 +00001164 else {
1165 assert(N->getValueType(0) == RV.getValueType() &&
1166 N->getNumValues() == 1 && "Type mismatch");
1167 SDValue OpV = RV;
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00001168 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng17a568b2008-08-29 22:21:44 +00001169 }
Scott Michelfdc40a02009-02-17 22:15:04 +00001170
Evan Cheng17a568b2008-08-29 22:21:44 +00001171 // Push the new node and any users onto the worklist
1172 AddToWorkList(RV.getNode());
1173 AddUsersToWorkList(RV.getNode());
Scott Michelfdc40a02009-02-17 22:15:04 +00001174
Evan Cheng17a568b2008-08-29 22:21:44 +00001175 // Add any uses of the old node to the worklist in case this node is the
1176 // last one that uses them. They may become dead after this node is
1177 // deleted.
1178 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1179 AddToWorkList(N->getOperand(i).getNode());
Scott Michelfdc40a02009-02-17 22:15:04 +00001180
Dan Gohmandbe664a2009-01-19 21:44:21 +00001181 // Finally, if the node is now dead, remove it from the graph. The node
1182 // may not be dead if the replacement process recursively simplified to
1183 // something else needing this node.
1184 if (N->use_empty()) {
1185 // Nodes can be reintroduced into the worklist. Make sure we do not
1186 // process a node that has been replaced.
1187 removeFromWorkList(N);
Scott Michelfdc40a02009-02-17 22:15:04 +00001188
Dan Gohmandbe664a2009-01-19 21:44:21 +00001189 // Finally, since the node is now dead, remove it from the graph.
1190 DAG.DeleteNode(N);
1191 }
Evan Cheng17a568b2008-08-29 22:21:44 +00001192 }
Scott Michelfdc40a02009-02-17 22:15:04 +00001193
Chris Lattner95038592005-10-05 06:35:28 +00001194 // If the root changed (e.g. it was a dead load, update the root).
1195 DAG.setRoot(Dummy.getValue());
Hal Finkel31490ba2012-04-16 03:33:22 +00001196 DAG.RemoveDeadNodes();
Nate Begeman1d4d4142005-09-01 00:19:25 +00001197}
1198
Dan Gohman475871a2008-07-27 21:46:04 +00001199SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengb3a3d5e2010-04-28 07:10:39 +00001200 switch (N->getOpcode()) {
Nate Begeman1d4d4142005-09-01 00:19:25 +00001201 default: break;
Nate Begeman4942a962005-09-01 00:33:32 +00001202 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattnerfec42eb2008-02-13 07:25:05 +00001203 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001204 case ISD::ADD: return visitADD(N);
1205 case ISD::SUB: return visitSUB(N);
Chris Lattner91153682007-03-04 20:03:15 +00001206 case ISD::ADDC: return visitADDC(N);
Craig Toppercc274522012-01-07 09:06:39 +00001207 case ISD::SUBC: return visitSUBC(N);
Chris Lattner91153682007-03-04 20:03:15 +00001208 case ISD::ADDE: return visitADDE(N);
Craig Toppercc274522012-01-07 09:06:39 +00001209 case ISD::SUBE: return visitSUBE(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001210 case ISD::MUL: return visitMUL(N);
1211 case ISD::SDIV: return visitSDIV(N);
1212 case ISD::UDIV: return visitUDIV(N);
1213 case ISD::SREM: return visitSREM(N);
1214 case ISD::UREM: return visitUREM(N);
1215 case ISD::MULHU: return visitMULHU(N);
1216 case ISD::MULHS: return visitMULHS(N);
Dan Gohman389079b2007-10-08 17:57:15 +00001217 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1218 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramerf55d26e2011-05-21 18:31:55 +00001219 case ISD::SMULO: return visitSMULO(N);
1220 case ISD::UMULO: return visitUMULO(N);
Dan Gohman389079b2007-10-08 17:57:15 +00001221 case ISD::SDIVREM: return visitSDIVREM(N);
1222 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001223 case ISD::AND: return visitAND(N);
1224 case ISD::OR: return visitOR(N);
1225 case ISD::XOR: return visitXOR(N);
1226 case ISD::SHL: return visitSHL(N);
1227 case ISD::SRA: return visitSRA(N);
1228 case ISD::SRL: return visitSRL(N);
Stephen Hines36b56882014-04-23 16:57:46 -07001229 case ISD::ROTR:
1230 case ISD::ROTL: return visitRotate(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001231 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth63974b22011-12-13 01:56:10 +00001232 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001233 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth63974b22011-12-13 01:56:10 +00001234 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001235 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman452d7be2005-09-16 00:54:12 +00001236 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramer6242fda2013-04-26 09:19:19 +00001237 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman452d7be2005-09-16 00:54:12 +00001238 case ISD::SELECT_CC: return visitSELECT_CC(N);
1239 case ISD::SETCC: return visitSETCC(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001240 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1241 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner5ffc0662006-05-05 05:58:59 +00001242 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001243 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1244 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peckbf17cfa2010-11-23 03:31:01 +00001245 case ISD::BITCAST: return visitBITCAST(N);
Evan Cheng9bfa03c2008-05-12 23:04:07 +00001246 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner01b3d732005-09-28 22:28:18 +00001247 case ISD::FADD: return visitFADD(N);
1248 case ISD::FSUB: return visitFSUB(N);
1249 case ISD::FMUL: return visitFMUL(N);
Owen Anderson062c0a52012-05-02 22:17:40 +00001250 case ISD::FMA: return visitFMA(N);
Chris Lattner01b3d732005-09-28 22:28:18 +00001251 case ISD::FDIV: return visitFDIV(N);
1252 case ISD::FREM: return visitFREM(N);
Chris Lattner12d83032006-03-05 05:30:57 +00001253 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001254 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1255 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1256 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1257 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1258 case ISD::FP_ROUND: return visitFP_ROUND(N);
1259 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1260 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1261 case ISD::FNEG: return visitFNEG(N);
1262 case ISD::FABS: return visitFABS(N);
Owen Anderson7c626d32012-08-13 23:32:49 +00001263 case ISD::FFLOOR: return visitFFLOOR(N);
1264 case ISD::FCEIL: return visitFCEIL(N);
1265 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begeman44728a72005-09-19 22:34:01 +00001266 case ISD::BRCOND: return visitBRCOND(N);
Nate Begeman44728a72005-09-19 22:34:01 +00001267 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattner01a22022005-10-10 22:04:48 +00001268 case ISD::LOAD: return visitLOAD(N);
Chris Lattner87514ca2005-10-10 22:31:19 +00001269 case ISD::STORE: return visitSTORE(N);
Chris Lattnerca242442006-03-19 01:27:56 +00001270 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng513da432007-10-06 08:19:55 +00001271 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohman7f321562007-06-25 16:23:39 +00001272 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1273 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopese97190f2011-09-20 23:19:33 +00001274 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattner66445d32006-03-28 22:11:53 +00001275 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Stephen Hines36b56882014-04-23 16:57:46 -07001276 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Nate Begeman1d4d4142005-09-01 00:19:25 +00001277 }
Dan Gohman475871a2008-07-27 21:46:04 +00001278 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00001279}
1280
Dan Gohman475871a2008-07-27 21:46:04 +00001281SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman475871a2008-07-27 21:46:04 +00001282 SDValue RV = visit(N);
Dan Gohman389079b2007-10-08 17:57:15 +00001283
1284 // If nothing happened, try a target-specific DAG combine.
Gabor Greifba36cb52008-08-28 21:40:38 +00001285 if (RV.getNode() == 0) {
Dan Gohman389079b2007-10-08 17:57:15 +00001286 assert(N->getOpcode() != ISD::DELETED_NODE &&
1287 "Node was deleted but visit returned NULL!");
1288
1289 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1290 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1291
1292 // Expose the DAG combiner to the target combiner impls.
Scott Michelfdc40a02009-02-17 22:15:04 +00001293 TargetLowering::DAGCombinerInfo
Nadav Rotem444b4bf2012-12-27 06:47:41 +00001294 DagCombineInfo(DAG, Level, false, this);
Dan Gohman389079b2007-10-08 17:57:15 +00001295
1296 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1297 }
1298 }
1299
Evan Chengb3a3d5e2010-04-28 07:10:39 +00001300 // If nothing happened still, try promoting the operation.
1301 if (RV.getNode() == 0) {
1302 switch (N->getOpcode()) {
1303 default: break;
1304 case ISD::ADD:
1305 case ISD::SUB:
1306 case ISD::MUL:
1307 case ISD::AND:
1308 case ISD::OR:
1309 case ISD::XOR:
1310 RV = PromoteIntBinOp(SDValue(N, 0));
1311 break;
1312 case ISD::SHL:
1313 case ISD::SRA:
1314 case ISD::SRL:
1315 RV = PromoteIntShiftOp(SDValue(N, 0));
1316 break;
1317 case ISD::SIGN_EXTEND:
1318 case ISD::ZERO_EXTEND:
1319 case ISD::ANY_EXTEND:
1320 RV = PromoteExtend(SDValue(N, 0));
1321 break;
1322 case ISD::LOAD:
1323 if (PromoteLoad(SDValue(N, 0)))
1324 RV = SDValue(N, 0);
1325 break;
1326 }
1327 }
1328
Scott Michelfdc40a02009-02-17 22:15:04 +00001329 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng08b11732008-03-22 01:55:50 +00001330 // sdisel CSE.
Scott Michelfdc40a02009-02-17 22:15:04 +00001331 if (RV.getNode() == 0 &&
Evan Cheng08b11732008-03-22 01:55:50 +00001332 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1333 N->getNumValues() == 1) {
Dan Gohman475871a2008-07-27 21:46:04 +00001334 SDValue N0 = N->getOperand(0);
1335 SDValue N1 = N->getOperand(1);
Bill Wendling5c71acf2009-01-30 01:13:16 +00001336
Evan Cheng08b11732008-03-22 01:55:50 +00001337 // Constant operands are canonicalized to RHS.
1338 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Dan Gohman475871a2008-07-27 21:46:04 +00001339 SDValue Ops[] = { N1, N0 };
Evan Cheng08b11732008-03-22 01:55:50 +00001340 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1341 Ops, 2);
Evan Chengea100462008-03-24 23:55:16 +00001342 if (CSENode)
Dan Gohman475871a2008-07-27 21:46:04 +00001343 return SDValue(CSENode, 0);
Evan Cheng08b11732008-03-22 01:55:50 +00001344 }
1345 }
1346
Dan Gohman389079b2007-10-08 17:57:15 +00001347 return RV;
Scott Michelfdc40a02009-02-17 22:15:04 +00001348}
Dan Gohman389079b2007-10-08 17:57:15 +00001349
Chris Lattner6270f682006-10-08 22:57:01 +00001350/// getInputChainForNode - Given a node, return its input chain if it has one,
1351/// otherwise return a null sd operand.
Dan Gohman475871a2008-07-27 21:46:04 +00001352static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner6270f682006-10-08 22:57:01 +00001353 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001354 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner6270f682006-10-08 22:57:01 +00001355 return N->getOperand(0);
Stephen Linb4940152013-07-09 00:44:49 +00001356 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner6270f682006-10-08 22:57:01 +00001357 return N->getOperand(NumOps-1);
1358 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson825b72b2009-08-11 20:47:22 +00001359 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner6270f682006-10-08 22:57:01 +00001360 return N->getOperand(i);
1361 }
Bill Wendling5c71acf2009-01-30 01:13:16 +00001362 return SDValue();
Chris Lattner6270f682006-10-08 22:57:01 +00001363}
1364
Dan Gohman475871a2008-07-27 21:46:04 +00001365SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner6270f682006-10-08 22:57:01 +00001366 // If N has two operands, where one has an input chain equal to the other,
1367 // the 'other' chain is redundant.
1368 if (N->getNumOperands() == 2) {
Gabor Greifba36cb52008-08-28 21:40:38 +00001369 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner6270f682006-10-08 22:57:01 +00001370 return N->getOperand(0);
Gabor Greifba36cb52008-08-28 21:40:38 +00001371 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner6270f682006-10-08 22:57:01 +00001372 return N->getOperand(1);
1373 }
Scott Michelfdc40a02009-02-17 22:15:04 +00001374
Chris Lattnerc76d4412007-05-16 06:37:59 +00001375 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman475871a2008-07-27 21:46:04 +00001376 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelfdc40a02009-02-17 22:15:04 +00001377 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattnerc76d4412007-05-16 06:37:59 +00001378 bool Changed = false; // If we should replace this token factor.
Scott Michelfdc40a02009-02-17 22:15:04 +00001379
Jim Laskey6ff23e52006-10-04 16:53:27 +00001380 // Start out with this token factor.
Jim Laskey279f0532006-09-25 16:29:54 +00001381 TFs.push_back(N);
Scott Michelfdc40a02009-02-17 22:15:04 +00001382
Jim Laskey71382342006-10-07 23:37:56 +00001383 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskeybc588b82006-10-05 15:07:25 +00001384 // encountered.
1385 for (unsigned i = 0; i < TFs.size(); ++i) {
1386 SDNode *TF = TFs[i];
Scott Michelfdc40a02009-02-17 22:15:04 +00001387
Jim Laskey6ff23e52006-10-04 16:53:27 +00001388 // Check each of the operands.
1389 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00001390 SDValue Op = TF->getOperand(i);
Scott Michelfdc40a02009-02-17 22:15:04 +00001391
Jim Laskey6ff23e52006-10-04 16:53:27 +00001392 switch (Op.getOpcode()) {
1393 case ISD::EntryToken:
Jim Laskeybc588b82006-10-05 15:07:25 +00001394 // Entry tokens don't need to be added to the list. They are
1395 // rededundant.
1396 Changed = true;
Jim Laskey6ff23e52006-10-04 16:53:27 +00001397 break;
Scott Michelfdc40a02009-02-17 22:15:04 +00001398
Jim Laskey6ff23e52006-10-04 16:53:27 +00001399 case ISD::TokenFactor:
Nate Begemanb6aef5c2009-09-15 00:18:30 +00001400 if (Op.hasOneUse() &&
Gabor Greifba36cb52008-08-28 21:40:38 +00001401 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey6ff23e52006-10-04 16:53:27 +00001402 // Queue up for processing.
Gabor Greifba36cb52008-08-28 21:40:38 +00001403 TFs.push_back(Op.getNode());
Jim Laskey6ff23e52006-10-04 16:53:27 +00001404 // Clean up in case the token factor is removed.
Gabor Greifba36cb52008-08-28 21:40:38 +00001405 AddToWorkList(Op.getNode());
Jim Laskey6ff23e52006-10-04 16:53:27 +00001406 Changed = true;
1407 break;
Jim Laskey279f0532006-09-25 16:29:54 +00001408 }
Jim Laskey6ff23e52006-10-04 16:53:27 +00001409 // Fall thru
Scott Michelfdc40a02009-02-17 22:15:04 +00001410
Jim Laskey6ff23e52006-10-04 16:53:27 +00001411 default:
Chris Lattnerc76d4412007-05-16 06:37:59 +00001412 // Only add if it isn't already in the list.
Gabor Greifba36cb52008-08-28 21:40:38 +00001413 if (SeenOps.insert(Op.getNode()))
Jim Laskeybc588b82006-10-05 15:07:25 +00001414 Ops.push_back(Op);
Chris Lattnerc76d4412007-05-16 06:37:59 +00001415 else
1416 Changed = true;
Jim Laskey6ff23e52006-10-04 16:53:27 +00001417 break;
Jim Laskey279f0532006-09-25 16:29:54 +00001418 }
1419 }
Jim Laskey6ff23e52006-10-04 16:53:27 +00001420 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00001421
Dan Gohman475871a2008-07-27 21:46:04 +00001422 SDValue Result;
Jim Laskey6ff23e52006-10-04 16:53:27 +00001423
1424 // If we've change things around then replace token factor.
1425 if (Changed) {
Dan Gohman30359592008-01-29 13:02:09 +00001426 if (Ops.empty()) {
Jim Laskey6ff23e52006-10-04 16:53:27 +00001427 // The entry token is the only possible outcome.
1428 Result = DAG.getEntryNode();
1429 } else {
1430 // New and improved token factor.
Andrew Trickac6d9be2013-05-25 02:42:55 +00001431 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson825b72b2009-08-11 20:47:22 +00001432 MVT::Other, &Ops[0], Ops.size());
Nate Begemanded49632005-10-13 03:11:28 +00001433 }
Bill Wendling5c71acf2009-01-30 01:13:16 +00001434
Jim Laskey274062c2006-10-13 23:32:28 +00001435 // Don't add users to work list.
1436 return CombineTo(N, Result, false);
Nate Begemanded49632005-10-13 03:11:28 +00001437 }
Scott Michelfdc40a02009-02-17 22:15:04 +00001438
Jim Laskey6ff23e52006-10-04 16:53:27 +00001439 return Result;
Nate Begeman1d4d4142005-09-01 00:19:25 +00001440}
1441
Chris Lattnerfec42eb2008-02-13 07:25:05 +00001442/// MERGE_VALUES can always be eliminated.
Dan Gohman475871a2008-07-27 21:46:04 +00001443SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chris Lattnerfec42eb2008-02-13 07:25:05 +00001444 WorkListRemover DeadNodes(*this);
Dan Gohman00edf392009-08-10 23:43:19 +00001445 // Replacing results may cause a different MERGE_VALUES to suddenly
1446 // be CSE'd with N, and carry its uses with it. Iterate until no
1447 // uses remain, to ensure that the node can be safely deleted.
Pete Cooper3affd9e2012-06-20 19:35:43 +00001448 // First add the users of this node to the work list so that they
1449 // can be tried again once they have new operands.
1450 AddUsersToWorkList(N);
Dan Gohman00edf392009-08-10 23:43:19 +00001451 do {
1452 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00001453 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman00edf392009-08-10 23:43:19 +00001454 } while (!N->use_empty());
Chris Lattnerfec42eb2008-02-13 07:25:05 +00001455 removeFromWorkList(N);
1456 DAG.DeleteNode(N);
Dan Gohman475871a2008-07-27 21:46:04 +00001457 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattnerfec42eb2008-02-13 07:25:05 +00001458}
1459
Evan Cheng42d7ccf2007-01-19 17:51:44 +00001460static
Andrew Trickac6d9be2013-05-25 02:42:55 +00001461SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
Bill Wendlingd69c3142009-01-30 02:23:43 +00001462 SelectionDAG &DAG) {
Owen Andersone50ed302009-08-10 22:56:29 +00001463 EVT VT = N0.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00001464 SDValue N00 = N0.getOperand(0);
1465 SDValue N01 = N0.getOperand(1);
Evan Cheng42d7ccf2007-01-19 17:51:44 +00001466 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
Bill Wendlingd69c3142009-01-30 02:23:43 +00001467
Gabor Greifba36cb52008-08-28 21:40:38 +00001468 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
Evan Cheng42d7ccf2007-01-19 17:51:44 +00001469 isa<ConstantSDNode>(N00.getOperand(1))) {
Bill Wendlingd69c3142009-01-30 02:23:43 +00001470 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Andrew Trickac6d9be2013-05-25 02:42:55 +00001471 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1472 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
Bill Wendlingd69c3142009-01-30 02:23:43 +00001473 N00.getOperand(0), N01),
Andrew Trickac6d9be2013-05-25 02:42:55 +00001474 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
Bill Wendlingd69c3142009-01-30 02:23:43 +00001475 N00.getOperand(1), N01));
1476 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
Evan Cheng42d7ccf2007-01-19 17:51:44 +00001477 }
Bill Wendlingd69c3142009-01-30 02:23:43 +00001478
Dan Gohman475871a2008-07-27 21:46:04 +00001479 return SDValue();
Evan Cheng42d7ccf2007-01-19 17:51:44 +00001480}
1481
Dan Gohman475871a2008-07-27 21:46:04 +00001482SDValue DAGCombiner::visitADD(SDNode *N) {
1483 SDValue N0 = N->getOperand(0);
1484 SDValue N1 = N->getOperand(1);
Nate Begeman646d7e22005-09-02 21:18:40 +00001485 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1486 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00001487 EVT VT = N0.getValueType();
Dan Gohman7f321562007-06-25 16:23:39 +00001488
1489 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00001490 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00001491 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00001492 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper48b509c2012-12-10 08:12:29 +00001493
1494 // fold (add x, 0) -> x, vector edition
1495 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1496 return N0;
1497 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1498 return N1;
Dan Gohman05d92fe2007-07-13 20:03:40 +00001499 }
Bill Wendling2476e5d2008-12-10 22:36:00 +00001500
Dan Gohman613e0d82007-07-03 14:03:57 +00001501 // fold (add x, undef) -> undef
Dan Gohman70fb1ae2007-07-10 15:19:29 +00001502 if (N0.getOpcode() == ISD::UNDEF)
1503 return N0;
1504 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman613e0d82007-07-03 14:03:57 +00001505 return N1;
Nate Begeman1d4d4142005-09-01 00:19:25 +00001506 // fold (add c1, c2) -> c1+c2
Nate Begeman646d7e22005-09-02 21:18:40 +00001507 if (N0C && N1C)
Bill Wendlingf3cbca22008-09-24 10:25:02 +00001508 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman99801192005-09-07 23:25:52 +00001509 // canonicalize constant to RHS
Nate Begemana0e221d2005-10-18 00:28:13 +00001510 if (N0C && !N1C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001511 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00001512 // fold (add x, 0) -> x
Nate Begeman646d7e22005-09-02 21:18:40 +00001513 if (N1C && N1C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00001514 return N0;
Dan Gohman6520e202008-10-18 02:06:02 +00001515 // fold (add Sym, c) -> Sym+c
1516 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sands25cf2272008-11-24 14:53:14 +00001517 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman6520e202008-10-18 02:06:02 +00001518 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001519 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman6520e202008-10-18 02:06:02 +00001520 GA->getOffset() +
1521 (uint64_t)N1C->getSExtValue());
Chris Lattner4aafb4f2006-01-12 20:22:43 +00001522 // fold ((c1-A)+c2) -> (c1+c2)-A
1523 if (N1C && N0.getOpcode() == ISD::SUB)
1524 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001525 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohman002e5d02008-03-13 22:13:53 +00001526 DAG.getConstant(N1C->getAPIntValue()+
1527 N0C->getAPIntValue(), VT),
Chris Lattner4aafb4f2006-01-12 20:22:43 +00001528 N0.getOperand(1));
Nate Begemancd4d58c2006-02-03 06:46:56 +00001529 // reassociate add
Andrew Trickac6d9be2013-05-25 02:42:55 +00001530 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Gabor Greifba36cb52008-08-28 21:40:38 +00001531 if (RADD.getNode() != 0)
Nate Begemancd4d58c2006-02-03 06:46:56 +00001532 return RADD;
Nate Begeman1d4d4142005-09-01 00:19:25 +00001533 // fold ((0-A) + B) -> B-A
1534 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1535 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickac6d9be2013-05-25 02:42:55 +00001536 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman1d4d4142005-09-01 00:19:25 +00001537 // fold (A + (0-B)) -> A-B
1538 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1539 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickac6d9be2013-05-25 02:42:55 +00001540 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner01b3d732005-09-28 22:28:18 +00001541 // fold (A+(B-A)) -> B
1542 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begeman83e75ec2005-09-06 04:43:02 +00001543 return N1.getOperand(0);
Dale Johannesen56eca912008-11-27 00:43:21 +00001544 // fold ((B-A)+A) -> B
1545 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1546 return N0.getOperand(0);
Dale Johannesen221cd2f2008-12-02 01:30:54 +00001547 // fold (A+(B-(A+C))) to (B-C)
1548 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingf4eb2262009-01-30 02:31:17 +00001549 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001550 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen221cd2f2008-12-02 01:30:54 +00001551 N1.getOperand(1).getOperand(1));
Dale Johannesen221cd2f2008-12-02 01:30:54 +00001552 // fold (A+(B-(C+A))) to (B-C)
1553 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingf4eb2262009-01-30 02:31:17 +00001554 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001555 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen221cd2f2008-12-02 01:30:54 +00001556 N1.getOperand(1).getOperand(0));
Dale Johannesen7c7bc722008-12-23 23:47:22 +00001557 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen34d79852008-12-02 18:40:40 +00001558 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1559 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingf4eb2262009-01-30 02:31:17 +00001560 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001561 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingf4eb2262009-01-30 02:31:17 +00001562 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen34d79852008-12-02 18:40:40 +00001563
Dale Johannesen221cd2f2008-12-02 01:30:54 +00001564 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1565 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1566 SDValue N00 = N0.getOperand(0);
1567 SDValue N01 = N0.getOperand(1);
1568 SDValue N10 = N1.getOperand(0);
1569 SDValue N11 = N1.getOperand(1);
Bill Wendlingf4eb2262009-01-30 02:31:17 +00001570
1571 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001572 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1573 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1574 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen221cd2f2008-12-02 01:30:54 +00001575 }
Chris Lattner947c2892006-03-13 06:51:27 +00001576
Dan Gohman475871a2008-07-27 21:46:04 +00001577 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1578 return SDValue(N, 0);
Scott Michelfdc40a02009-02-17 22:15:04 +00001579
Sylvestre Ledru94c22712012-09-27 10:14:43 +00001580 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001581 if (VT.isInteger() && !VT.isVector()) {
Dan Gohman948d8ea2008-02-20 16:33:30 +00001582 APInt LHSZero, LHSOne;
1583 APInt RHSZero, RHSOne;
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00001584 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
Bill Wendlingf4eb2262009-01-30 02:31:17 +00001585
Dan Gohman948d8ea2008-02-20 16:33:30 +00001586 if (LHSZero.getBoolValue()) {
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00001587 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
Scott Michelfdc40a02009-02-17 22:15:04 +00001588
Chris Lattner947c2892006-03-13 06:51:27 +00001589 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1590 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Stephen Hines36b56882014-04-23 16:57:46 -07001591 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1592 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1593 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1594 }
Chris Lattner947c2892006-03-13 06:51:27 +00001595 }
1596 }
Evan Cheng3ef554d2006-11-06 08:14:30 +00001597
Evan Cheng42d7ccf2007-01-19 17:51:44 +00001598 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Gabor Greifba36cb52008-08-28 21:40:38 +00001599 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00001600 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
Gabor Greifba36cb52008-08-28 21:40:38 +00001601 if (Result.getNode()) return Result;
Evan Cheng42d7ccf2007-01-19 17:51:44 +00001602 }
Gabor Greifba36cb52008-08-28 21:40:38 +00001603 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00001604 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
Gabor Greifba36cb52008-08-28 21:40:38 +00001605 if (Result.getNode()) return Result;
Evan Cheng42d7ccf2007-01-19 17:51:44 +00001606 }
1607
Dan Gohmancd9e1552010-01-19 23:30:49 +00001608 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1609 if (N1.getOpcode() == ISD::SHL &&
1610 N1.getOperand(0).getOpcode() == ISD::SUB)
1611 if (ConstantSDNode *C =
1612 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1613 if (C->getAPIntValue() == 0)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001614 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1615 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohmancd9e1552010-01-19 23:30:49 +00001616 N1.getOperand(0).getOperand(1),
1617 N1.getOperand(1)));
1618 if (N0.getOpcode() == ISD::SHL &&
1619 N0.getOperand(0).getOpcode() == ISD::SUB)
1620 if (ConstantSDNode *C =
1621 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1622 if (C->getAPIntValue() == 0)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001623 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1624 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohmancd9e1552010-01-19 23:30:49 +00001625 N0.getOperand(0).getOperand(1),
1626 N0.getOperand(1)));
1627
Owen Andersonbc146b02010-09-21 20:42:50 +00001628 if (N1.getOpcode() == ISD::AND) {
1629 SDValue AndOp0 = N1.getOperand(0);
Wesley Peckbf17cfa2010-11-23 03:31:01 +00001630 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Andersonbc146b02010-09-21 20:42:50 +00001631 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1632 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peckbf17cfa2010-11-23 03:31:01 +00001633
Owen Andersonbc146b02010-09-21 20:42:50 +00001634 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1635 // and similar xforms where the inner op is either ~0 or 0.
1636 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00001637 SDLoc DL(N);
Owen Andersonbc146b02010-09-21 20:42:50 +00001638 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1639 }
1640 }
1641
Benjamin Kramerf50125e2010-12-22 23:17:45 +00001642 // add (sext i1), X -> sub X, (zext i1)
1643 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1644 N0.getOperand(0).getValueType() == MVT::i1 &&
1645 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00001646 SDLoc DL(N);
Benjamin Kramerf50125e2010-12-22 23:17:45 +00001647 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1648 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1649 }
1650
Evan Chengb3a3d5e2010-04-28 07:10:39 +00001651 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00001652}
1653
Dan Gohman475871a2008-07-27 21:46:04 +00001654SDValue DAGCombiner::visitADDC(SDNode *N) {
1655 SDValue N0 = N->getOperand(0);
1656 SDValue N1 = N->getOperand(1);
Chris Lattner91153682007-03-04 20:03:15 +00001657 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1658 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00001659 EVT VT = N0.getValueType();
Scott Michelfdc40a02009-02-17 22:15:04 +00001660
Chris Lattner91153682007-03-04 20:03:15 +00001661 // If the flag result is dead, turn this into an ADD.
Craig Topper704e1a02012-01-07 18:31:09 +00001662 if (!N->hasAnyUseOfValue(1))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001663 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen874ae252009-06-02 03:12:52 +00001664 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickac6d9be2013-05-25 02:42:55 +00001665 SDLoc(N), MVT::Glue));
Scott Michelfdc40a02009-02-17 22:15:04 +00001666
Chris Lattner91153682007-03-04 20:03:15 +00001667 // canonicalize constant to RHS.
Dan Gohman0a4627d2008-06-23 15:29:14 +00001668 if (N0C && !N1C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001669 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +00001670
Chris Lattnerb6541762007-03-04 20:40:38 +00001671 // fold (addc x, 0) -> x + no carry out
1672 if (N1C && N1C->isNullValue())
Dale Johannesen874ae252009-06-02 03:12:52 +00001673 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickac6d9be2013-05-25 02:42:55 +00001674 SDLoc(N), MVT::Glue));
Scott Michelfdc40a02009-02-17 22:15:04 +00001675
Sylvestre Ledru94c22712012-09-27 10:14:43 +00001676 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohman948d8ea2008-02-20 16:33:30 +00001677 APInt LHSZero, LHSOne;
1678 APInt RHSZero, RHSOne;
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00001679 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
Bill Wendling14036c02009-01-30 02:38:00 +00001680
Dan Gohman948d8ea2008-02-20 16:33:30 +00001681 if (LHSZero.getBoolValue()) {
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00001682 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
Scott Michelfdc40a02009-02-17 22:15:04 +00001683
Chris Lattnerb6541762007-03-04 20:40:38 +00001684 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1685 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00001686 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001687 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen874ae252009-06-02 03:12:52 +00001688 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickac6d9be2013-05-25 02:42:55 +00001689 SDLoc(N), MVT::Glue));
Chris Lattnerb6541762007-03-04 20:40:38 +00001690 }
Scott Michelfdc40a02009-02-17 22:15:04 +00001691
Dan Gohman475871a2008-07-27 21:46:04 +00001692 return SDValue();
Chris Lattner91153682007-03-04 20:03:15 +00001693}
1694
Dan Gohman475871a2008-07-27 21:46:04 +00001695SDValue DAGCombiner::visitADDE(SDNode *N) {
1696 SDValue N0 = N->getOperand(0);
1697 SDValue N1 = N->getOperand(1);
1698 SDValue CarryIn = N->getOperand(2);
Chris Lattner91153682007-03-04 20:03:15 +00001699 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1700 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelfdc40a02009-02-17 22:15:04 +00001701
Chris Lattner91153682007-03-04 20:03:15 +00001702 // canonicalize constant to RHS
Dan Gohman0a4627d2008-06-23 15:29:14 +00001703 if (N0C && !N1C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001704 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling14036c02009-01-30 02:38:00 +00001705 N1, N0, CarryIn);
Scott Michelfdc40a02009-02-17 22:15:04 +00001706
Chris Lattnerb6541762007-03-04 20:40:38 +00001707 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen874ae252009-06-02 03:12:52 +00001708 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001709 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelfdc40a02009-02-17 22:15:04 +00001710
Dan Gohman475871a2008-07-27 21:46:04 +00001711 return SDValue();
Chris Lattner91153682007-03-04 20:03:15 +00001712}
1713
Eric Christopher7bccf6a2011-02-16 04:50:12 +00001714// Since it may not be valid to emit a fold to zero for vector initializers
1715// check if we can before folding.
Andrew Trickac6d9be2013-05-25 02:42:55 +00001716static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkelbd6f1f62013-07-09 17:02:45 +00001717 SelectionDAG &DAG,
1718 bool LegalOperations, bool LegalTypes) {
Stephen Linb4940152013-07-09 00:44:49 +00001719 if (!VT.isVector())
Eric Christopher7bccf6a2011-02-16 04:50:12 +00001720 return DAG.getConstant(0, VT);
Daniel Sanders975e9582013-11-25 15:53:39 +00001721 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1722 return DAG.getConstant(0, VT);
Eric Christopher7bccf6a2011-02-16 04:50:12 +00001723 return SDValue();
1724}
1725
Dan Gohman475871a2008-07-27 21:46:04 +00001726SDValue DAGCombiner::visitSUB(SDNode *N) {
1727 SDValue N0 = N->getOperand(0);
1728 SDValue N1 = N->getOperand(1);
Gabor Greifba36cb52008-08-28 21:40:38 +00001729 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1730 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Eric Christopher7332e6e2011-07-14 01:12:15 +00001731 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1732 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Andersone50ed302009-08-10 22:56:29 +00001733 EVT VT = N0.getValueType();
Scott Michelfdc40a02009-02-17 22:15:04 +00001734
Dan Gohman7f321562007-06-25 16:23:39 +00001735 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00001736 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00001737 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00001738 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper48b509c2012-12-10 08:12:29 +00001739
1740 // fold (sub x, 0) -> x, vector edition
1741 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1742 return N0;
Dan Gohman05d92fe2007-07-13 20:03:40 +00001743 }
Bill Wendling2476e5d2008-12-10 22:36:00 +00001744
Chris Lattner854077d2005-10-17 01:07:11 +00001745 // fold (sub x, x) -> 0
Eric Christopher169e1552011-02-16 01:10:03 +00001746 // FIXME: Refactor this and xor and other similar operations together.
Eric Christopher7bccf6a2011-02-16 04:50:12 +00001747 if (N0 == N1)
Hal Finkelbd6f1f62013-07-09 17:02:45 +00001748 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman1d4d4142005-09-01 00:19:25 +00001749 // fold (sub c1, c2) -> c1-c2
Nate Begeman646d7e22005-09-02 21:18:40 +00001750 if (N0C && N1C)
Bill Wendlingf3cbca22008-09-24 10:25:02 +00001751 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattner05b57432005-10-11 06:07:15 +00001752 // fold (sub x, c) -> (add x, -c)
1753 if (N1C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001754 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohman002e5d02008-03-13 22:13:53 +00001755 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng1ad0e8b2010-01-18 21:38:44 +00001756 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1757 if (N0C && N0C->isAllOnesValue())
Andrew Trickac6d9be2013-05-25 02:42:55 +00001758 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer2c94b422011-01-29 12:34:05 +00001759 // fold A-(A-B) -> B
1760 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1761 return N1.getOperand(1);
Nate Begeman1d4d4142005-09-01 00:19:25 +00001762 // fold (A+B)-A -> B
Chris Lattner01b3d732005-09-28 22:28:18 +00001763 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begeman83e75ec2005-09-06 04:43:02 +00001764 return N0.getOperand(1);
Nate Begeman1d4d4142005-09-01 00:19:25 +00001765 // fold (A+B)-B -> A
Chris Lattner01b3d732005-09-28 22:28:18 +00001766 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelfdc40a02009-02-17 22:15:04 +00001767 return N0.getOperand(0);
Eric Christopher7332e6e2011-07-14 01:12:15 +00001768 // fold C2-(A+C1) -> (C2-C1)-A
1769 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem6dfabb62012-09-20 08:53:31 +00001770 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1771 VT);
Andrew Trickac6d9be2013-05-25 02:42:55 +00001772 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendling96cb1122012-07-19 00:04:14 +00001773 N1.getOperand(0));
Eric Christopher7332e6e2011-07-14 01:12:15 +00001774 }
Dale Johannesen7c7bc722008-12-23 23:47:22 +00001775 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenfd3b7b72008-12-16 22:13:49 +00001776 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenf9cbc1f2008-12-23 23:01:27 +00001777 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1778 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenfd3b7b72008-12-16 22:13:49 +00001779 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001780 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendlingb0702e02009-01-30 02:42:10 +00001781 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenf9cbc1f2008-12-23 23:01:27 +00001782 // fold ((A+(C+B))-B) -> A+C
1783 if (N0.getOpcode() == ISD::ADD &&
1784 N0.getOperand(1).getOpcode() == ISD::ADD &&
1785 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001786 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendlingb0702e02009-01-30 02:42:10 +00001787 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesen58e39b02008-12-23 01:59:54 +00001788 // fold ((A-(B-C))-C) -> A-B
1789 if (N0.getOpcode() == ISD::SUB &&
1790 N0.getOperand(1).getOpcode() == ISD::SUB &&
1791 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001792 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendlingb0702e02009-01-30 02:42:10 +00001793 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendlingb0702e02009-01-30 02:42:10 +00001794
Dan Gohman613e0d82007-07-03 14:03:57 +00001795 // If either operand of a sub is undef, the result is undef
Dan Gohman70fb1ae2007-07-10 15:19:29 +00001796 if (N0.getOpcode() == ISD::UNDEF)
1797 return N0;
1798 if (N1.getOpcode() == ISD::UNDEF)
1799 return N1;
Dan Gohman7f321562007-06-25 16:23:39 +00001800
Dan Gohman6520e202008-10-18 02:06:02 +00001801 // If the relocation model supports it, consider symbol offsets.
1802 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sands25cf2272008-11-24 14:53:14 +00001803 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman6520e202008-10-18 02:06:02 +00001804 // fold (sub Sym, c) -> Sym-c
1805 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001806 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman6520e202008-10-18 02:06:02 +00001807 GA->getOffset() -
1808 (uint64_t)N1C->getSExtValue());
1809 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1810 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1811 if (GA->getGlobal() == GB->getGlobal())
1812 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1813 VT);
1814 }
1815
Evan Chengb3a3d5e2010-04-28 07:10:39 +00001816 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00001817}
1818
Craig Toppercc274522012-01-07 09:06:39 +00001819SDValue DAGCombiner::visitSUBC(SDNode *N) {
1820 SDValue N0 = N->getOperand(0);
1821 SDValue N1 = N->getOperand(1);
1822 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1823 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1824 EVT VT = N0.getValueType();
1825
1826 // If the flag result is dead, turn this into an SUB.
Craig Topper704e1a02012-01-07 18:31:09 +00001827 if (!N->hasAnyUseOfValue(1))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001828 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1829 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Toppercc274522012-01-07 09:06:39 +00001830 MVT::Glue));
1831
1832 // fold (subc x, x) -> 0 + no borrow
1833 if (N0 == N1)
1834 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickac6d9be2013-05-25 02:42:55 +00001835 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Toppercc274522012-01-07 09:06:39 +00001836 MVT::Glue));
1837
1838 // fold (subc x, 0) -> x + no borrow
1839 if (N1C && N1C->isNullValue())
Andrew Trickac6d9be2013-05-25 02:42:55 +00001840 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Toppercc274522012-01-07 09:06:39 +00001841 MVT::Glue));
1842
1843 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1844 if (N0C && N0C->isAllOnesValue())
Andrew Trickac6d9be2013-05-25 02:42:55 +00001845 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1846 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Toppercc274522012-01-07 09:06:39 +00001847 MVT::Glue));
1848
1849 return SDValue();
1850}
1851
1852SDValue DAGCombiner::visitSUBE(SDNode *N) {
1853 SDValue N0 = N->getOperand(0);
1854 SDValue N1 = N->getOperand(1);
1855 SDValue CarryIn = N->getOperand(2);
1856
1857 // fold (sube x, y, false) -> (subc x, y)
1858 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001859 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Toppercc274522012-01-07 09:06:39 +00001860
1861 return SDValue();
1862}
1863
Dan Gohman475871a2008-07-27 21:46:04 +00001864SDValue DAGCombiner::visitMUL(SDNode *N) {
1865 SDValue N0 = N->getOperand(0);
1866 SDValue N1 = N->getOperand(1);
Owen Andersone50ed302009-08-10 22:56:29 +00001867 EVT VT = N0.getValueType();
Scott Michelfdc40a02009-02-17 22:15:04 +00001868
Dan Gohman613e0d82007-07-03 14:03:57 +00001869 // fold (mul x, undef) -> 0
Dan Gohmand595b5f2007-07-10 14:20:37 +00001870 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman613e0d82007-07-03 14:03:57 +00001871 return DAG.getConstant(0, VT);
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001872
1873 bool N0IsConst = false;
1874 bool N1IsConst = false;
1875 APInt ConstValue0, ConstValue1;
1876 // fold vector ops
1877 if (VT.isVector()) {
1878 SDValue FoldedVOp = SimplifyVBinOp(N);
1879 if (FoldedVOp.getNode()) return FoldedVOp;
1880
1881 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1882 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1883 } else {
1884 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
Jack Carteradbd3ae2013-10-17 01:34:33 +00001885 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1886 : APInt();
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001887 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
Jack Carteradbd3ae2013-10-17 01:34:33 +00001888 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1889 : APInt();
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001890 }
1891
Nate Begeman1d4d4142005-09-01 00:19:25 +00001892 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001893 if (N0IsConst && N1IsConst)
1894 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1895
Nate Begeman99801192005-09-07 23:25:52 +00001896 // canonicalize constant to RHS
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001897 if (N0IsConst && !N1IsConst)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001898 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00001899 // fold (mul x, 0) -> 0
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001900 if (N1IsConst && ConstValue1 == 0)
Nate Begeman83e75ec2005-09-06 04:43:02 +00001901 return N1;
Benjamin Kramer530d09a2013-09-19 13:28:20 +00001902 // We require a splat of the entire scalar bit width for non-contiguous
1903 // bit patterns.
1904 bool IsFullSplat =
1905 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001906 // fold (mul x, 1) -> x
Benjamin Kramer530d09a2013-09-19 13:28:20 +00001907 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001908 return N0;
Nate Begeman1d4d4142005-09-01 00:19:25 +00001909 // fold (mul x, -1) -> 0-x
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001910 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickac6d9be2013-05-25 02:42:55 +00001911 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling9c8148a2009-01-30 02:45:56 +00001912 DAG.getConstant(0, VT), N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00001913 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramer530d09a2013-09-19 13:28:20 +00001914 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001915 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001916 DAG.getConstant(ConstValue1.logBase2(),
Owen Anderson95771af2011-02-25 21:41:48 +00001917 getShiftAmountTy(N0.getValueType())));
Chris Lattner3e6099b2005-10-30 06:41:49 +00001918 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramer530d09a2013-09-19 13:28:20 +00001919 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001920 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelfdc40a02009-02-17 22:15:04 +00001921 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattner3e6099b2005-10-30 06:41:49 +00001922 // single-use add), we should put the negate there.
Andrew Trickac6d9be2013-05-25 02:42:55 +00001923 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling9c8148a2009-01-30 02:45:56 +00001924 DAG.getConstant(0, VT),
Andrew Trickac6d9be2013-05-25 02:42:55 +00001925 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Anderson95771af2011-02-25 21:41:48 +00001926 DAG.getConstant(Log2Val,
1927 getShiftAmountTy(N0.getValueType()))));
Chris Lattner66b8bc32009-03-09 20:22:18 +00001928 }
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001929
1930 APInt Val;
Chris Lattner0b1a85f2006-03-01 03:44:24 +00001931 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lin155615d2013-07-08 00:37:03 +00001932 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001933 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1934 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00001935 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling9c8148a2009-01-30 02:45:56 +00001936 N1, N0.getOperand(1));
Gabor Greifba36cb52008-08-28 21:40:38 +00001937 AddToWorkList(C3.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00001938 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling9c8148a2009-01-30 02:45:56 +00001939 N0.getOperand(0), C3);
Chris Lattner0b1a85f2006-03-01 03:44:24 +00001940 }
Scott Michelfdc40a02009-02-17 22:15:04 +00001941
Chris Lattner0b1a85f2006-03-01 03:44:24 +00001942 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1943 // use.
1944 {
Dan Gohman475871a2008-07-27 21:46:04 +00001945 SDValue Sh(0,0), Y(0,0);
Chris Lattner0b1a85f2006-03-01 03:44:24 +00001946 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lin155615d2013-07-08 00:37:03 +00001947 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001948 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1949 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greifba36cb52008-08-28 21:40:38 +00001950 N0.getNode()->hasOneUse()) {
Chris Lattner0b1a85f2006-03-01 03:44:24 +00001951 Sh = N0; Y = N1;
Scott Michelfdc40a02009-02-17 22:15:04 +00001952 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greif12632d22008-08-30 19:29:20 +00001953 isa<ConstantSDNode>(N1.getOperand(1)) &&
1954 N1.getNode()->hasOneUse()) {
Chris Lattner0b1a85f2006-03-01 03:44:24 +00001955 Sh = N1; Y = N0;
1956 }
Bill Wendling73e16b22009-01-30 02:49:26 +00001957
Gabor Greifba36cb52008-08-28 21:40:38 +00001958 if (Sh.getNode()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00001959 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling9c8148a2009-01-30 02:45:56 +00001960 Sh.getOperand(0), Y);
Andrew Trickac6d9be2013-05-25 02:42:55 +00001961 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling9c8148a2009-01-30 02:45:56 +00001962 Mul, Sh.getOperand(1));
Chris Lattner0b1a85f2006-03-01 03:44:24 +00001963 }
1964 }
Bill Wendling73e16b22009-01-30 02:49:26 +00001965
Chris Lattnera1deca32006-03-04 23:33:26 +00001966 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001967 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1968 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1969 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001970 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1971 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling9c8148a2009-01-30 02:45:56 +00001972 N0.getOperand(0), N1),
Andrew Trickac6d9be2013-05-25 02:42:55 +00001973 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling9c8148a2009-01-30 02:45:56 +00001974 N0.getOperand(1), N1));
Scott Michelfdc40a02009-02-17 22:15:04 +00001975
Nate Begemancd4d58c2006-02-03 06:46:56 +00001976 // reassociate mul
Andrew Trickac6d9be2013-05-25 02:42:55 +00001977 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Gabor Greifba36cb52008-08-28 21:40:38 +00001978 if (RMUL.getNode() != 0)
Nate Begemancd4d58c2006-02-03 06:46:56 +00001979 return RMUL;
Dan Gohman7f321562007-06-25 16:23:39 +00001980
Evan Chengb3a3d5e2010-04-28 07:10:39 +00001981 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00001982}
1983
Dan Gohman475871a2008-07-27 21:46:04 +00001984SDValue DAGCombiner::visitSDIV(SDNode *N) {
1985 SDValue N0 = N->getOperand(0);
1986 SDValue N1 = N->getOperand(1);
Gabor Greifba36cb52008-08-28 21:40:38 +00001987 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1988 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Owen Andersone50ed302009-08-10 22:56:29 +00001989 EVT VT = N->getValueType(0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00001990
Dan Gohman7f321562007-06-25 16:23:39 +00001991 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00001992 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00001993 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00001994 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman05d92fe2007-07-13 20:03:40 +00001995 }
Scott Michelfdc40a02009-02-17 22:15:04 +00001996
Nate Begeman1d4d4142005-09-01 00:19:25 +00001997 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman646d7e22005-09-02 21:18:40 +00001998 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingf3cbca22008-09-24 10:25:02 +00001999 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman405e3ec2005-10-21 00:02:42 +00002000 // fold (sdiv X, 1) -> X
Eli Friedmanfd58cd72011-10-27 02:06:39 +00002001 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman405e3ec2005-10-21 00:02:42 +00002002 return N0;
2003 // fold (sdiv X, -1) -> 0-X
2004 if (N1C && N1C->isAllOnesValue())
Andrew Trickac6d9be2013-05-25 02:42:55 +00002005 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling944d34b2009-01-30 02:52:17 +00002006 DAG.getConstant(0, VT), N0);
Chris Lattner094c8fc2005-10-07 06:10:46 +00002007 // If we know the sign bits of both operands are zero, strength reduce to a
2008 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands83ec4b62008-06-06 12:08:01 +00002009 if (!VT.isVector()) {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00002010 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00002011 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling944d34b2009-01-30 02:52:17 +00002012 N0, N1);
Chris Lattnerf32aac32008-01-27 23:32:17 +00002013 }
Nate Begemancd6a6ed2006-02-17 07:26:20 +00002014 // fold (sdiv X, pow2) -> simple ops after legalize
Eli Friedman1c663fe2011-12-07 03:55:52 +00002015 if (N1C && !N1C->isNullValue() &&
Eli Friedmanfd58cd72011-10-27 02:06:39 +00002016 (N1C->getAPIntValue().isPowerOf2() ||
2017 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman405e3ec2005-10-21 00:02:42 +00002018 // If dividing by powers of two is cheap, then don't perform the following
2019 // fold.
2020 if (TLI.isPow2DivCheap())
Dan Gohman475871a2008-07-27 21:46:04 +00002021 return SDValue();
Bill Wendling944d34b2009-01-30 02:52:17 +00002022
Eli Friedmanfd58cd72011-10-27 02:06:39 +00002023 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling944d34b2009-01-30 02:52:17 +00002024
Chris Lattner8f4880b2006-02-16 08:02:36 +00002025 // Splat the sign bit into the register
Andrew Trickac6d9be2013-05-25 02:42:55 +00002026 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
Bill Wendling944d34b2009-01-30 02:52:17 +00002027 DAG.getConstant(VT.getSizeInBits()-1,
Owen Anderson95771af2011-02-25 21:41:48 +00002028 getShiftAmountTy(N0.getValueType())));
Gabor Greifba36cb52008-08-28 21:40:38 +00002029 AddToWorkList(SGN.getNode());
Bill Wendling944d34b2009-01-30 02:52:17 +00002030
Chris Lattner8f4880b2006-02-16 08:02:36 +00002031 // Add (N0 < 0) ? abs2 - 1 : 0;
Andrew Trickac6d9be2013-05-25 02:42:55 +00002032 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
Bill Wendling944d34b2009-01-30 02:52:17 +00002033 DAG.getConstant(VT.getSizeInBits() - lg2,
Owen Anderson95771af2011-02-25 21:41:48 +00002034 getShiftAmountTy(SGN.getValueType())));
Andrew Trickac6d9be2013-05-25 02:42:55 +00002035 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Gabor Greifba36cb52008-08-28 21:40:38 +00002036 AddToWorkList(SRL.getNode());
2037 AddToWorkList(ADD.getNode()); // Divide by pow2
Andrew Trickac6d9be2013-05-25 02:42:55 +00002038 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Anderson95771af2011-02-25 21:41:48 +00002039 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling944d34b2009-01-30 02:52:17 +00002040
Nate Begeman405e3ec2005-10-21 00:02:42 +00002041 // If we're dividing by a positive value, we're done. Otherwise, we must
2042 // negate the result.
Eli Friedmanfd58cd72011-10-27 02:06:39 +00002043 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman405e3ec2005-10-21 00:02:42 +00002044 return SRA;
Bill Wendling944d34b2009-01-30 02:52:17 +00002045
Gabor Greifba36cb52008-08-28 21:40:38 +00002046 AddToWorkList(SRA.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002047 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling944d34b2009-01-30 02:52:17 +00002048 DAG.getConstant(0, VT), SRA);
Nate Begeman405e3ec2005-10-21 00:02:42 +00002049 }
Bill Wendling944d34b2009-01-30 02:52:17 +00002050
Nate Begeman69575232005-10-20 02:15:44 +00002051 // if integer divide is expensive and we satisfy the requirements, emit an
2052 // alternate sequence.
Eli Friedmanfd58cd72011-10-27 02:06:39 +00002053 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
Dan Gohman475871a2008-07-27 21:46:04 +00002054 SDValue Op = BuildSDIV(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00002055 if (Op.getNode()) return Op;
Nate Begeman69575232005-10-20 02:15:44 +00002056 }
Dan Gohman7f321562007-06-25 16:23:39 +00002057
Dan Gohman613e0d82007-07-03 14:03:57 +00002058 // undef / X -> 0
2059 if (N0.getOpcode() == ISD::UNDEF)
2060 return DAG.getConstant(0, VT);
2061 // X / undef -> undef
2062 if (N1.getOpcode() == ISD::UNDEF)
2063 return N1;
Dan Gohman7f321562007-06-25 16:23:39 +00002064
Dan Gohman475871a2008-07-27 21:46:04 +00002065 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00002066}
2067
Dan Gohman475871a2008-07-27 21:46:04 +00002068SDValue DAGCombiner::visitUDIV(SDNode *N) {
2069 SDValue N0 = N->getOperand(0);
2070 SDValue N1 = N->getOperand(1);
Gabor Greifba36cb52008-08-28 21:40:38 +00002071 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2072 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Owen Andersone50ed302009-08-10 22:56:29 +00002073 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00002074
Dan Gohman7f321562007-06-25 16:23:39 +00002075 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00002076 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00002077 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00002078 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman05d92fe2007-07-13 20:03:40 +00002079 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002080
Nate Begeman1d4d4142005-09-01 00:19:25 +00002081 // fold (udiv c1, c2) -> c1/c2
Nate Begeman646d7e22005-09-02 21:18:40 +00002082 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingf3cbca22008-09-24 10:25:02 +00002083 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman1d4d4142005-09-01 00:19:25 +00002084 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohman002e5d02008-03-13 22:13:53 +00002085 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickac6d9be2013-05-25 02:42:55 +00002086 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohman002e5d02008-03-13 22:13:53 +00002087 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Anderson95771af2011-02-25 21:41:48 +00002088 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002089 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begemanfb5e4bd2006-02-05 07:20:23 +00002090 if (N1.getOpcode() == ISD::SHL) {
2091 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohman002e5d02008-03-13 22:13:53 +00002092 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Andersone50ed302009-08-10 22:56:29 +00002093 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickac6d9be2013-05-25 02:42:55 +00002094 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendling07d85142009-01-30 02:55:25 +00002095 N1.getOperand(1),
2096 DAG.getConstant(SHC->getAPIntValue()
2097 .logBase2(),
2098 ADDVT));
Gabor Greifba36cb52008-08-28 21:40:38 +00002099 AddToWorkList(Add.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002100 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begemanfb5e4bd2006-02-05 07:20:23 +00002101 }
2102 }
2103 }
Nate Begeman69575232005-10-20 02:15:44 +00002104 // fold (udiv x, c) -> alternate
Dan Gohman002e5d02008-03-13 22:13:53 +00002105 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
Dan Gohman475871a2008-07-27 21:46:04 +00002106 SDValue Op = BuildUDIV(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00002107 if (Op.getNode()) return Op;
Chris Lattnere9936d12005-10-22 18:50:15 +00002108 }
Dan Gohman7f321562007-06-25 16:23:39 +00002109
Dan Gohman613e0d82007-07-03 14:03:57 +00002110 // undef / X -> 0
2111 if (N0.getOpcode() == ISD::UNDEF)
2112 return DAG.getConstant(0, VT);
2113 // X / undef -> undef
2114 if (N1.getOpcode() == ISD::UNDEF)
2115 return N1;
Dan Gohman7f321562007-06-25 16:23:39 +00002116
Dan Gohman475871a2008-07-27 21:46:04 +00002117 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00002118}
2119
Dan Gohman475871a2008-07-27 21:46:04 +00002120SDValue DAGCombiner::visitSREM(SDNode *N) {
2121 SDValue N0 = N->getOperand(0);
2122 SDValue N1 = N->getOperand(1);
Nate Begeman646d7e22005-09-02 21:18:40 +00002123 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2124 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00002125 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00002126
Nate Begeman1d4d4142005-09-01 00:19:25 +00002127 // fold (srem c1, c2) -> c1%c2
Nate Begeman646d7e22005-09-02 21:18:40 +00002128 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingf3cbca22008-09-24 10:25:02 +00002129 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman07ed4172005-10-10 21:26:48 +00002130 // If we know the sign bits of both operands are zero, strength reduce to a
2131 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands83ec4b62008-06-06 12:08:01 +00002132 if (!VT.isVector()) {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00002133 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00002134 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattneree339f42008-01-27 23:21:58 +00002135 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002136
Dan Gohman77003042007-11-26 23:46:11 +00002137 // If X/C can be simplified by the division-by-constant logic, lower
2138 // X%C to the equivalent of X-X/C*C.
Chris Lattner26d29902006-10-12 20:58:32 +00002139 if (N1C && !N1C->isNullValue()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002140 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Gabor Greifba36cb52008-08-28 21:40:38 +00002141 AddToWorkList(Div.getNode());
2142 SDValue OptimizedDiv = combine(Div.getNode());
2143 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002144 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling6d3bf8c2009-01-30 02:57:00 +00002145 OptimizedDiv, N1);
Andrew Trickac6d9be2013-05-25 02:42:55 +00002146 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greifba36cb52008-08-28 21:40:38 +00002147 AddToWorkList(Mul.getNode());
Dan Gohman77003042007-11-26 23:46:11 +00002148 return Sub;
2149 }
Chris Lattner26d29902006-10-12 20:58:32 +00002150 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002151
Dan Gohman613e0d82007-07-03 14:03:57 +00002152 // undef % X -> 0
2153 if (N0.getOpcode() == ISD::UNDEF)
2154 return DAG.getConstant(0, VT);
2155 // X % undef -> undef
2156 if (N1.getOpcode() == ISD::UNDEF)
2157 return N1;
Dan Gohman7f321562007-06-25 16:23:39 +00002158
Dan Gohman475871a2008-07-27 21:46:04 +00002159 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00002160}
2161
Dan Gohman475871a2008-07-27 21:46:04 +00002162SDValue DAGCombiner::visitUREM(SDNode *N) {
2163 SDValue N0 = N->getOperand(0);
2164 SDValue N1 = N->getOperand(1);
Nate Begeman646d7e22005-09-02 21:18:40 +00002165 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2166 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00002167 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00002168
Nate Begeman1d4d4142005-09-01 00:19:25 +00002169 // fold (urem c1, c2) -> c1%c2
Nate Begeman646d7e22005-09-02 21:18:40 +00002170 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingf3cbca22008-09-24 10:25:02 +00002171 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman07ed4172005-10-10 21:26:48 +00002172 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohman002e5d02008-03-13 22:13:53 +00002173 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickac6d9be2013-05-25 02:42:55 +00002174 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohman002e5d02008-03-13 22:13:53 +00002175 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc031e332006-02-05 07:36:48 +00002176 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2177 if (N1.getOpcode() == ISD::SHL) {
2178 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohman002e5d02008-03-13 22:13:53 +00002179 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman475871a2008-07-27 21:46:04 +00002180 SDValue Add =
Andrew Trickac6d9be2013-05-25 02:42:55 +00002181 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands83ec4b62008-06-06 12:08:01 +00002182 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohman002e5d02008-03-13 22:13:53 +00002183 VT));
Gabor Greifba36cb52008-08-28 21:40:38 +00002184 AddToWorkList(Add.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002185 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc031e332006-02-05 07:36:48 +00002186 }
2187 }
2188 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002189
Dan Gohman77003042007-11-26 23:46:11 +00002190 // If X/C can be simplified by the division-by-constant logic, lower
2191 // X%C to the equivalent of X-X/C*C.
Chris Lattner26d29902006-10-12 20:58:32 +00002192 if (N1C && !N1C->isNullValue()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002193 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Dan Gohman942ca7f2008-09-08 16:59:01 +00002194 AddToWorkList(Div.getNode());
Gabor Greifba36cb52008-08-28 21:40:38 +00002195 SDValue OptimizedDiv = combine(Div.getNode());
2196 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002197 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling6d3bf8c2009-01-30 02:57:00 +00002198 OptimizedDiv, N1);
Andrew Trickac6d9be2013-05-25 02:42:55 +00002199 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greifba36cb52008-08-28 21:40:38 +00002200 AddToWorkList(Mul.getNode());
Dan Gohman77003042007-11-26 23:46:11 +00002201 return Sub;
2202 }
Chris Lattner26d29902006-10-12 20:58:32 +00002203 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002204
Dan Gohman613e0d82007-07-03 14:03:57 +00002205 // undef % X -> 0
2206 if (N0.getOpcode() == ISD::UNDEF)
2207 return DAG.getConstant(0, VT);
2208 // X % undef -> undef
2209 if (N1.getOpcode() == ISD::UNDEF)
2210 return N1;
Dan Gohman7f321562007-06-25 16:23:39 +00002211
Dan Gohman475871a2008-07-27 21:46:04 +00002212 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00002213}
2214
Dan Gohman475871a2008-07-27 21:46:04 +00002215SDValue DAGCombiner::visitMULHS(SDNode *N) {
2216 SDValue N0 = N->getOperand(0);
2217 SDValue N1 = N->getOperand(1);
Nate Begeman646d7e22005-09-02 21:18:40 +00002218 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00002219 EVT VT = N->getValueType(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00002220 SDLoc DL(N);
Scott Michelfdc40a02009-02-17 22:15:04 +00002221
Nate Begeman1d4d4142005-09-01 00:19:25 +00002222 // fold (mulhs x, 0) -> 0
Nate Begeman646d7e22005-09-02 21:18:40 +00002223 if (N1C && N1C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00002224 return N1;
Nate Begeman1d4d4142005-09-01 00:19:25 +00002225 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohman002e5d02008-03-13 22:13:53 +00002226 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickac6d9be2013-05-25 02:42:55 +00002227 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendling326411d2009-01-30 03:00:18 +00002228 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Anderson95771af2011-02-25 21:41:48 +00002229 getShiftAmountTy(N0.getValueType())));
Dan Gohman613e0d82007-07-03 14:03:57 +00002230 // fold (mulhs x, undef) -> 0
Dan Gohmand595b5f2007-07-10 14:20:37 +00002231 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman613e0d82007-07-03 14:03:57 +00002232 return DAG.getConstant(0, VT);
Dan Gohman7f321562007-06-25 16:23:39 +00002233
Chris Lattnerde1c3602010-12-13 08:39:01 +00002234 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2235 // plus a shift.
2236 if (VT.isSimple() && !VT.isVector()) {
2237 MVT Simple = VT.getSimpleVT();
2238 unsigned SimpleSize = Simple.getSizeInBits();
2239 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2240 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2241 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2242 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2243 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattner1a0fbe22010-12-15 05:51:39 +00002244 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Anderson95771af2011-02-25 21:41:48 +00002245 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattnerde1c3602010-12-13 08:39:01 +00002246 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2247 }
2248 }
Owen Anderson95771af2011-02-25 21:41:48 +00002249
Dan Gohman475871a2008-07-27 21:46:04 +00002250 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00002251}
2252
Dan Gohman475871a2008-07-27 21:46:04 +00002253SDValue DAGCombiner::visitMULHU(SDNode *N) {
2254 SDValue N0 = N->getOperand(0);
2255 SDValue N1 = N->getOperand(1);
Nate Begeman646d7e22005-09-02 21:18:40 +00002256 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00002257 EVT VT = N->getValueType(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00002258 SDLoc DL(N);
Scott Michelfdc40a02009-02-17 22:15:04 +00002259
Nate Begeman1d4d4142005-09-01 00:19:25 +00002260 // fold (mulhu x, 0) -> 0
Nate Begeman646d7e22005-09-02 21:18:40 +00002261 if (N1C && N1C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00002262 return N1;
Nate Begeman1d4d4142005-09-01 00:19:25 +00002263 // fold (mulhu x, 1) -> 0
Dan Gohman002e5d02008-03-13 22:13:53 +00002264 if (N1C && N1C->getAPIntValue() == 1)
Nate Begeman83e75ec2005-09-06 04:43:02 +00002265 return DAG.getConstant(0, N0.getValueType());
Dan Gohman613e0d82007-07-03 14:03:57 +00002266 // fold (mulhu x, undef) -> 0
Dan Gohmand595b5f2007-07-10 14:20:37 +00002267 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman613e0d82007-07-03 14:03:57 +00002268 return DAG.getConstant(0, VT);
Dan Gohman7f321562007-06-25 16:23:39 +00002269
Chris Lattnerde1c3602010-12-13 08:39:01 +00002270 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2271 // plus a shift.
2272 if (VT.isSimple() && !VT.isVector()) {
2273 MVT Simple = VT.getSimpleVT();
2274 unsigned SimpleSize = Simple.getSizeInBits();
2275 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2276 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2277 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2278 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2279 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2280 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Anderson95771af2011-02-25 21:41:48 +00002281 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattnerde1c3602010-12-13 08:39:01 +00002282 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2283 }
2284 }
Owen Anderson95771af2011-02-25 21:41:48 +00002285
Dan Gohman475871a2008-07-27 21:46:04 +00002286 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00002287}
2288
Dan Gohman389079b2007-10-08 17:57:15 +00002289/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2290/// compute two values. LoOp and HiOp give the opcodes for the two computations
2291/// that are being performed. Return true if a simplification was made.
2292///
Scott Michelfdc40a02009-02-17 22:15:04 +00002293SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman475871a2008-07-27 21:46:04 +00002294 unsigned HiOp) {
Dan Gohman389079b2007-10-08 17:57:15 +00002295 // If the high half is not needed, just compute the low half.
Evan Cheng44711942007-11-08 09:25:29 +00002296 bool HiExists = N->hasAnyUseOfValue(1);
2297 if (!HiExists &&
Duncan Sands25cf2272008-11-24 14:53:14 +00002298 (!LegalOperations ||
Stephen Hines36b56882014-04-23 16:57:46 -07002299 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002300 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Bill Wendling826d1142009-01-30 03:08:40 +00002301 N->op_begin(), N->getNumOperands());
Chris Lattner5eee4272008-01-26 01:09:19 +00002302 return CombineTo(N, Res, Res);
Dan Gohman389079b2007-10-08 17:57:15 +00002303 }
2304
2305 // If the low half is not needed, just compute the high half.
Evan Cheng44711942007-11-08 09:25:29 +00002306 bool LoExists = N->hasAnyUseOfValue(0);
2307 if (!LoExists &&
Duncan Sands25cf2272008-11-24 14:53:14 +00002308 (!LegalOperations ||
Dan Gohman389079b2007-10-08 17:57:15 +00002309 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002310 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Bill Wendling826d1142009-01-30 03:08:40 +00002311 N->op_begin(), N->getNumOperands());
Chris Lattner5eee4272008-01-26 01:09:19 +00002312 return CombineTo(N, Res, Res);
Dan Gohman389079b2007-10-08 17:57:15 +00002313 }
2314
Evan Cheng44711942007-11-08 09:25:29 +00002315 // If both halves are used, return as it is.
2316 if (LoExists && HiExists)
Dan Gohman475871a2008-07-27 21:46:04 +00002317 return SDValue();
Evan Cheng44711942007-11-08 09:25:29 +00002318
2319 // If the two computed results can be simplified separately, separate them.
Evan Cheng44711942007-11-08 09:25:29 +00002320 if (LoExists) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002321 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Bill Wendling826d1142009-01-30 03:08:40 +00002322 N->op_begin(), N->getNumOperands());
Gabor Greifba36cb52008-08-28 21:40:38 +00002323 AddToWorkList(Lo.getNode());
2324 SDValue LoOpt = combine(Lo.getNode());
2325 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sands25cf2272008-11-24 14:53:14 +00002326 (!LegalOperations ||
Duncan Sandsd4b9c172008-06-13 19:07:40 +00002327 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner5eee4272008-01-26 01:09:19 +00002328 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman389079b2007-10-08 17:57:15 +00002329 }
2330
Evan Cheng44711942007-11-08 09:25:29 +00002331 if (HiExists) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002332 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Duncan Sands25cf2272008-11-24 14:53:14 +00002333 N->op_begin(), N->getNumOperands());
Gabor Greifba36cb52008-08-28 21:40:38 +00002334 AddToWorkList(Hi.getNode());
2335 SDValue HiOpt = combine(Hi.getNode());
2336 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sands25cf2272008-11-24 14:53:14 +00002337 (!LegalOperations ||
Duncan Sandsd4b9c172008-06-13 19:07:40 +00002338 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner5eee4272008-01-26 01:09:19 +00002339 return CombineTo(N, HiOpt, HiOpt);
Evan Cheng44711942007-11-08 09:25:29 +00002340 }
Bill Wendling826d1142009-01-30 03:08:40 +00002341
Dan Gohman475871a2008-07-27 21:46:04 +00002342 return SDValue();
Dan Gohman389079b2007-10-08 17:57:15 +00002343}
2344
Dan Gohman475871a2008-07-27 21:46:04 +00002345SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2346 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greifba36cb52008-08-28 21:40:38 +00002347 if (Res.getNode()) return Res;
Dan Gohman389079b2007-10-08 17:57:15 +00002348
Chris Lattner33e77d32010-12-15 06:04:19 +00002349 EVT VT = N->getValueType(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00002350 SDLoc DL(N);
Chris Lattner33e77d32010-12-15 06:04:19 +00002351
2352 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2353 // plus a shift.
2354 if (VT.isSimple() && !VT.isVector()) {
2355 MVT Simple = VT.getSimpleVT();
2356 unsigned SimpleSize = Simple.getSizeInBits();
2357 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2358 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2359 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2360 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2361 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2362 // Compute the high part as N1.
2363 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Anderson95771af2011-02-25 21:41:48 +00002364 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner33e77d32010-12-15 06:04:19 +00002365 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2366 // Compute the low part as N0.
2367 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2368 return CombineTo(N, Lo, Hi);
2369 }
2370 }
Owen Anderson95771af2011-02-25 21:41:48 +00002371
Dan Gohman475871a2008-07-27 21:46:04 +00002372 return SDValue();
Dan Gohman389079b2007-10-08 17:57:15 +00002373}
2374
Dan Gohman475871a2008-07-27 21:46:04 +00002375SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2376 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greifba36cb52008-08-28 21:40:38 +00002377 if (Res.getNode()) return Res;
Dan Gohman389079b2007-10-08 17:57:15 +00002378
Chris Lattner33e77d32010-12-15 06:04:19 +00002379 EVT VT = N->getValueType(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00002380 SDLoc DL(N);
Owen Anderson95771af2011-02-25 21:41:48 +00002381
Chris Lattner33e77d32010-12-15 06:04:19 +00002382 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2383 // plus a shift.
2384 if (VT.isSimple() && !VT.isVector()) {
2385 MVT Simple = VT.getSimpleVT();
2386 unsigned SimpleSize = Simple.getSizeInBits();
2387 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2388 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2389 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2390 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2391 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2392 // Compute the high part as N1.
2393 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Anderson95771af2011-02-25 21:41:48 +00002394 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner33e77d32010-12-15 06:04:19 +00002395 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2396 // Compute the low part as N0.
2397 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2398 return CombineTo(N, Lo, Hi);
2399 }
2400 }
Owen Anderson95771af2011-02-25 21:41:48 +00002401
Dan Gohman475871a2008-07-27 21:46:04 +00002402 return SDValue();
Dan Gohman389079b2007-10-08 17:57:15 +00002403}
2404
Benjamin Kramerf55d26e2011-05-21 18:31:55 +00002405SDValue DAGCombiner::visitSMULO(SDNode *N) {
2406 // (smulo x, 2) -> (saddo x, x)
2407 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2408 if (C2->getAPIntValue() == 2)
Andrew Trickac6d9be2013-05-25 02:42:55 +00002409 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramerf55d26e2011-05-21 18:31:55 +00002410 N->getOperand(0), N->getOperand(0));
2411
2412 return SDValue();
2413}
2414
2415SDValue DAGCombiner::visitUMULO(SDNode *N) {
2416 // (umulo x, 2) -> (uaddo x, x)
2417 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2418 if (C2->getAPIntValue() == 2)
Andrew Trickac6d9be2013-05-25 02:42:55 +00002419 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramerf55d26e2011-05-21 18:31:55 +00002420 N->getOperand(0), N->getOperand(0));
2421
2422 return SDValue();
2423}
2424
Dan Gohman475871a2008-07-27 21:46:04 +00002425SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2426 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greifba36cb52008-08-28 21:40:38 +00002427 if (Res.getNode()) return Res;
Scott Michelfdc40a02009-02-17 22:15:04 +00002428
Dan Gohman475871a2008-07-27 21:46:04 +00002429 return SDValue();
Dan Gohman389079b2007-10-08 17:57:15 +00002430}
2431
Dan Gohman475871a2008-07-27 21:46:04 +00002432SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2433 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greifba36cb52008-08-28 21:40:38 +00002434 if (Res.getNode()) return Res;
Scott Michelfdc40a02009-02-17 22:15:04 +00002435
Dan Gohman475871a2008-07-27 21:46:04 +00002436 return SDValue();
Dan Gohman389079b2007-10-08 17:57:15 +00002437}
2438
Chris Lattner35e5c142006-05-05 05:51:50 +00002439/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2440/// two operands of the same opcode, try to simplify it.
Dan Gohman475871a2008-07-27 21:46:04 +00002441SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2442 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Andersone50ed302009-08-10 22:56:29 +00002443 EVT VT = N0.getValueType();
Chris Lattner35e5c142006-05-05 05:51:50 +00002444 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelfdc40a02009-02-17 22:15:04 +00002445
Dan Gohmanff00a552010-01-14 03:08:49 +00002446 // Bail early if none of these transforms apply.
2447 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2448
Chris Lattner540121f2006-05-05 06:31:05 +00002449 // For each of OP in AND/OR/XOR:
2450 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2451 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2452 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Dan Gohman4e39e9d2010-06-24 14:30:44 +00002453 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman93e0ed32009-12-03 07:11:29 +00002454 //
2455 // do not sink logical op inside of a vector extend, since it may combine
2456 // into a vsetcc.
Evan Chengd40d03e2010-01-06 19:38:29 +00002457 EVT Op0VT = N0.getOperand(0).getValueType();
2458 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohman97121ba2009-04-08 00:15:30 +00002459 N0.getOpcode() == ISD::SIGN_EXTEND ||
Evan Chenge5b51ac2010-04-17 06:13:15 +00002460 // Avoid infinite looping with PromoteIntBinOp.
2461 (N0.getOpcode() == ISD::ANY_EXTEND &&
2462 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman4e39e9d2010-06-24 14:30:44 +00002463 (N0.getOpcode() == ISD::TRUNCATE &&
2464 (!TLI.isZExtFree(VT, Op0VT) ||
2465 !TLI.isTruncateFree(Op0VT, VT)) &&
2466 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman93e0ed32009-12-03 07:11:29 +00002467 !VT.isVector() &&
Evan Chengd40d03e2010-01-06 19:38:29 +00002468 Op0VT == N1.getOperand(0).getValueType() &&
2469 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002470 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendlingb74c8672009-01-30 19:25:47 +00002471 N0.getOperand(0).getValueType(),
2472 N0.getOperand(0), N1.getOperand(0));
Gabor Greifba36cb52008-08-28 21:40:38 +00002473 AddToWorkList(ORNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002474 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner35e5c142006-05-05 05:51:50 +00002475 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002476
Chris Lattnera3dc3f62006-05-05 06:10:43 +00002477 // For each of OP in SHL/SRL/SRA/AND...
2478 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2479 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2480 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner35e5c142006-05-05 05:51:50 +00002481 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattnera3dc3f62006-05-05 06:10:43 +00002482 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner35e5c142006-05-05 05:51:50 +00002483 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002484 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendlingb74c8672009-01-30 19:25:47 +00002485 N0.getOperand(0).getValueType(),
2486 N0.getOperand(0), N1.getOperand(0));
Gabor Greifba36cb52008-08-28 21:40:38 +00002487 AddToWorkList(ORNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002488 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendlingb74c8672009-01-30 19:25:47 +00002489 ORNode, N0.getOperand(1));
Chris Lattner35e5c142006-05-05 05:51:50 +00002490 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002491
Nadav Rotem4ac90812012-04-01 19:31:22 +00002492 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2493 // Only perform this optimization after type legalization and before
2494 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2495 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2496 // we don't want to undo this promotion.
2497 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2498 // on scalars.
Nadav Rotem6dfabb62012-09-20 08:53:31 +00002499 if ((N0.getOpcode() == ISD::BITCAST ||
2500 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2501 Level == AfterLegalizeTypes) {
Nadav Rotem4ac90812012-04-01 19:31:22 +00002502 SDValue In0 = N0.getOperand(0);
2503 SDValue In1 = N1.getOperand(0);
2504 EVT In0Ty = In0.getValueType();
2505 EVT In1Ty = In1.getValueType();
Andrew Trickac6d9be2013-05-25 02:42:55 +00002506 SDLoc DL(N);
Nadav Rotem6dfabb62012-09-20 08:53:31 +00002507 // If both incoming values are integers, and the original types are the
2508 // same.
Nadav Rotem4ac90812012-04-01 19:31:22 +00002509 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem6dfabb62012-09-20 08:53:31 +00002510 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2511 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Nadav Rotem4ac90812012-04-01 19:31:22 +00002512 AddToWorkList(Op.getNode());
2513 return BC;
2514 }
2515 }
2516
2517 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2518 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2519 // If both shuffles use the same mask, and both shuffle within a single
2520 // vector, then it is worthwhile to move the swizzle after the operation.
2521 // The type-legalizer generates this pattern when loading illegal
2522 // vector types from memory. In many cases this allows additional shuffle
2523 // optimizations.
Stephen Hines36b56882014-04-23 16:57:46 -07002524 // There are other cases where moving the shuffle after the xor/and/or
2525 // is profitable even if shuffles don't perform a swizzle.
2526 // If both shuffles use the same mask, and both shuffles have the same first
2527 // or second operand, then it might still be profitable to move the shuffle
2528 // after the xor/and/or operation.
2529 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
Nadav Rotem4ac90812012-04-01 19:31:22 +00002530 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2531 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topperf9204232012-04-09 07:19:09 +00002532
Stephen Hines36b56882014-04-23 16:57:46 -07002533 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
Craig Topperf9204232012-04-09 07:19:09 +00002534 "Inputs to shuffles are not the same type");
Stephen Hines36b56882014-04-23 16:57:46 -07002535
Nadav Rotem4ac90812012-04-01 19:31:22 +00002536 // Check that both shuffles use the same mask. The masks are known to be of
2537 // the same length because the result vector type is the same.
Stephen Hines36b56882014-04-23 16:57:46 -07002538 // Check also that shuffles have only one use to avoid introducing extra
2539 // instructions.
2540 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2541 SVN0->getMask().equals(SVN1->getMask())) {
2542 SDValue ShOp = N0->getOperand(1);
Nadav Rotem4ac90812012-04-01 19:31:22 +00002543
Stephen Hines36b56882014-04-23 16:57:46 -07002544 // Don't try to fold this node if it requires introducing a
2545 // build vector of all zeros that might be illegal at this stage.
2546 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2547 if (!LegalTypes)
2548 ShOp = DAG.getConstant(0, VT);
2549 else
2550 ShOp = SDValue();
2551 }
2552
2553 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2554 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2555 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2556 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2557 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2558 N0->getOperand(0), N1->getOperand(0));
2559 AddToWorkList(NewNode.getNode());
2560 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2561 &SVN0->getMask()[0]);
2562 }
2563
2564 // Don't try to fold this node if it requires introducing a
2565 // build vector of all zeros that might be illegal at this stage.
2566 ShOp = N0->getOperand(0);
2567 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2568 if (!LegalTypes)
2569 ShOp = DAG.getConstant(0, VT);
2570 else
2571 ShOp = SDValue();
2572 }
2573
2574 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2575 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2576 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2577 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2578 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2579 N0->getOperand(1), N1->getOperand(1));
2580 AddToWorkList(NewNode.getNode());
2581 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2582 &SVN0->getMask()[0]);
2583 }
Nadav Rotem4ac90812012-04-01 19:31:22 +00002584 }
2585 }
Craig Topperf9204232012-04-09 07:19:09 +00002586
Dan Gohman475871a2008-07-27 21:46:04 +00002587 return SDValue();
Chris Lattner35e5c142006-05-05 05:51:50 +00002588}
2589
Dan Gohman475871a2008-07-27 21:46:04 +00002590SDValue DAGCombiner::visitAND(SDNode *N) {
2591 SDValue N0 = N->getOperand(0);
2592 SDValue N1 = N->getOperand(1);
2593 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman646d7e22005-09-02 21:18:40 +00002594 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2595 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00002596 EVT VT = N1.getValueType();
Dan Gohman6900a392010-03-04 00:23:16 +00002597 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelfdc40a02009-02-17 22:15:04 +00002598
Dan Gohman7f321562007-06-25 16:23:39 +00002599 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00002600 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00002601 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00002602 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper9472b4f2012-12-08 22:49:19 +00002603
2604 // fold (and x, 0) -> 0, vector edition
2605 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2606 return N0;
2607 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2608 return N1;
2609
2610 // fold (and x, -1) -> x, vector edition
2611 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2612 return N1;
2613 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2614 return N0;
Dan Gohman05d92fe2007-07-13 20:03:40 +00002615 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002616
Dan Gohman613e0d82007-07-03 14:03:57 +00002617 // fold (and x, undef) -> 0
Dan Gohmand595b5f2007-07-10 14:20:37 +00002618 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman613e0d82007-07-03 14:03:57 +00002619 return DAG.getConstant(0, VT);
Nate Begeman1d4d4142005-09-01 00:19:25 +00002620 // fold (and c1, c2) -> c1&c2
Nate Begeman646d7e22005-09-02 21:18:40 +00002621 if (N0C && N1C)
Bill Wendlingf3cbca22008-09-24 10:25:02 +00002622 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman99801192005-09-07 23:25:52 +00002623 // canonicalize constant to RHS
Nate Begemana0e221d2005-10-18 00:28:13 +00002624 if (N0C && !N1C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00002625 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00002626 // fold (and x, -1) -> x
Nate Begeman646d7e22005-09-02 21:18:40 +00002627 if (N1C && N1C->isAllOnesValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00002628 return N0;
2629 // if (and x, c) is known to be zero, return 0
Dan Gohman475871a2008-07-27 21:46:04 +00002630 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman2e68b6f2008-02-25 21:11:39 +00002631 APInt::getAllOnesValue(BitWidth)))
Nate Begeman83e75ec2005-09-06 04:43:02 +00002632 return DAG.getConstant(0, VT);
Nate Begemancd4d58c2006-02-03 06:46:56 +00002633 // reassociate and
Andrew Trickac6d9be2013-05-25 02:42:55 +00002634 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Gabor Greifba36cb52008-08-28 21:40:38 +00002635 if (RAND.getNode() != 0)
Nate Begemancd4d58c2006-02-03 06:46:56 +00002636 return RAND;
Bill Wendling7d9f2b92010-03-03 00:35:56 +00002637 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begeman5dc7e862005-11-02 18:42:59 +00002638 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman1d4d4142005-09-01 00:19:25 +00002639 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman002e5d02008-03-13 22:13:53 +00002640 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00002641 return N1;
Chris Lattner3603cd62006-02-02 07:17:31 +00002642 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2643 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman475871a2008-07-27 21:46:04 +00002644 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman2e68b6f2008-02-25 21:11:39 +00002645 APInt Mask = ~N1C->getAPIntValue();
Jay Foad40f8f622010-12-07 08:25:19 +00002646 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman2e68b6f2008-02-25 21:11:39 +00002647 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002648 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling2627a882009-01-30 20:43:18 +00002649 N0.getValueType(), N0Op0);
Scott Michelfdc40a02009-02-17 22:15:04 +00002650
Chris Lattner1ec05d12006-03-01 21:47:21 +00002651 // Replace uses of the AND with uses of the Zero extend node.
2652 CombineTo(N, Zext);
Scott Michelfdc40a02009-02-17 22:15:04 +00002653
Chris Lattner3603cd62006-02-02 07:17:31 +00002654 // We actually want to replace all uses of the any_extend with the
2655 // zero_extend, to avoid duplicating things. This will later cause this
2656 // AND to be folded.
Gabor Greifba36cb52008-08-28 21:40:38 +00002657 CombineTo(N0.getNode(), Zext);
Dan Gohman475871a2008-07-27 21:46:04 +00002658 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3603cd62006-02-02 07:17:31 +00002659 }
2660 }
Stephen Lin155615d2013-07-08 00:37:03 +00002661 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy6259dcd2012-02-20 12:02:38 +00002662 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2663 // already be zero by virtue of the width of the base type of the load.
2664 //
2665 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2666 // more cases.
2667 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2668 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2669 N0.getOpcode() == ISD::LOAD) {
2670 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2671 N0 : N0.getOperand(0) );
2672
2673 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2674 // This can be a pure constant or a vector splat, in which case we treat the
2675 // vector as a scalar and use the splat value.
2676 APInt Constant = APInt::getNullValue(1);
2677 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2678 Constant = C->getAPIntValue();
2679 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2680 APInt SplatValue, SplatUndef;
2681 unsigned SplatBitSize;
2682 bool HasAnyUndefs;
2683 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2684 SplatBitSize, HasAnyUndefs);
2685 if (IsSplat) {
2686 // Undef bits can contribute to a possible optimisation if set, so
2687 // set them.
2688 SplatValue |= SplatUndef;
2689
2690 // The splat value may be something like "0x00FFFFFF", which means 0 for
2691 // the first vector value and FF for the rest, repeating. We need a mask
2692 // that will apply equally to all members of the vector, so AND all the
2693 // lanes of the constant together.
2694 EVT VT = Vector->getValueType(0);
2695 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3d5e1612012-09-05 08:57:21 +00002696
2697 // If the splat value has been compressed to a bitlength lower
2698 // than the size of the vector lane, we need to re-expand it to
2699 // the lane size.
2700 if (BitWidth > SplatBitSize)
2701 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2702 SplatBitSize < BitWidth;
2703 SplatBitSize = SplatBitSize * 2)
2704 SplatValue |= SplatValue.shl(SplatBitSize);
2705
James Molloy6259dcd2012-02-20 12:02:38 +00002706 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3d5e1612012-09-05 08:57:21 +00002707 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy6259dcd2012-02-20 12:02:38 +00002708 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2709 }
2710 }
2711
2712 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2713 // actually legal and isn't going to get expanded, else this is a false
2714 // optimisation.
2715 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2716 Load->getMemoryVT());
2717
2718 // Resize the constant to the same size as the original memory access before
2719 // extension. If it is still the AllOnesValue then this AND is completely
2720 // unneeded.
2721 Constant =
2722 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2723
2724 bool B;
2725 switch (Load->getExtensionType()) {
2726 default: B = false; break;
2727 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2728 case ISD::ZEXTLOAD:
2729 case ISD::NON_EXTLOAD: B = true; break;
2730 }
2731
2732 if (B && Constant.isAllOnesValue()) {
2733 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2734 // preserve semantics once we get rid of the AND.
2735 SDValue NewLoad(Load, 0);
2736 if (Load->getExtensionType() == ISD::EXTLOAD) {
2737 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickac6d9be2013-05-25 02:42:55 +00002738 Load->getValueType(0), SDLoc(Load),
James Molloy6259dcd2012-02-20 12:02:38 +00002739 Load->getChain(), Load->getBasePtr(),
2740 Load->getOffset(), Load->getMemoryVT(),
2741 Load->getMemOperand());
2742 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkeld65e4632012-06-20 15:42:48 +00002743 if (Load->getNumValues() == 3) {
2744 // PRE/POST_INC loads have 3 values.
2745 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2746 NewLoad.getValue(2) };
2747 CombineTo(Load, To, 3, true);
2748 } else {
2749 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2750 }
James Molloy6259dcd2012-02-20 12:02:38 +00002751 }
2752
2753 // Fold the AND away, taking care not to fold to the old load node if we
2754 // replaced it.
2755 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2756
2757 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2758 }
2759 }
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002760 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2761 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2762 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2763 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelfdc40a02009-02-17 22:15:04 +00002764
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002765 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands83ec4b62008-06-06 12:08:01 +00002766 LL.getValueType().isInteger()) {
Bill Wendling2627a882009-01-30 20:43:18 +00002767 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Dan Gohman002e5d02008-03-13 22:13:53 +00002768 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002769 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling2627a882009-01-30 20:43:18 +00002770 LR.getValueType(), LL, RL);
Gabor Greifba36cb52008-08-28 21:40:38 +00002771 AddToWorkList(ORNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002772 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002773 }
Bill Wendling2627a882009-01-30 20:43:18 +00002774 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002775 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002776 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling2627a882009-01-30 20:43:18 +00002777 LR.getValueType(), LL, RL);
Gabor Greifba36cb52008-08-28 21:40:38 +00002778 AddToWorkList(ANDNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002779 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002780 }
Bill Wendling2627a882009-01-30 20:43:18 +00002781 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002782 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002783 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling2627a882009-01-30 20:43:18 +00002784 LR.getValueType(), LL, RL);
Gabor Greifba36cb52008-08-28 21:40:38 +00002785 AddToWorkList(ORNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002786 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002787 }
2788 }
Jim Grosbach51a02802013-08-13 21:30:58 +00002789 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2790 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2791 Op0 == Op1 && LL.getValueType().isInteger() &&
2792 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2793 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2794 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2795 cast<ConstantSDNode>(RR)->isNullValue()))) {
2796 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2797 LL, DAG.getConstant(1, LL.getValueType()));
2798 AddToWorkList(ADDNode.getNode());
2799 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2800 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2801 }
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002802 // canonicalize equivalent to ll == rl
2803 if (LL == RR && LR == RL) {
2804 Op1 = ISD::getSetCCSwappedOperands(Op1);
2805 std::swap(RL, RR);
2806 }
2807 if (LL == RL && LR == RR) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00002808 bool isInteger = LL.getValueType().isInteger();
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002809 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner6e1c6232008-10-28 07:11:07 +00002810 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundfdbeb052012-12-19 10:19:55 +00002811 (!LegalOperations ||
Owen Anderson39125d92013-02-14 09:07:33 +00002812 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2813 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault225ed702013-05-18 00:21:46 +00002814 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickac6d9be2013-05-25 02:42:55 +00002815 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling2627a882009-01-30 20:43:18 +00002816 LL, LR, Result);
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002817 }
2818 }
Chris Lattner35e5c142006-05-05 05:51:50 +00002819
Bill Wendling2627a882009-01-30 20:43:18 +00002820 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner35e5c142006-05-05 05:51:50 +00002821 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman475871a2008-07-27 21:46:04 +00002822 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00002823 if (Tmp.getNode()) return Tmp;
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002824 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002825
Nate Begemande996292006-02-03 22:24:05 +00002826 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2827 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands83ec4b62008-06-06 12:08:01 +00002828 if (!VT.isVector() &&
Dan Gohman475871a2008-07-27 21:46:04 +00002829 SimplifyDemandedBits(SDValue(N, 0)))
2830 return SDValue(N, 0);
Evan Chengd40d03e2010-01-06 19:38:29 +00002831
Nate Begemanded49632005-10-13 03:11:28 +00002832 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greifba36cb52008-08-28 21:40:38 +00002833 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Cheng466685d2006-10-09 20:57:25 +00002834 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman8a55ce42009-09-23 21:02:20 +00002835 EVT MemVT = LN0->getMemoryVT();
Nate Begemanbfd65a02005-10-13 18:34:58 +00002836 // If we zero all the possible extended bits, then we can turn this into
2837 // a zextload if we are running before legalize or the operation is legal.
Dan Gohman6900a392010-03-04 00:23:16 +00002838 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman2e68b6f2008-02-25 21:11:39 +00002839 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohman6900a392010-03-04 00:23:16 +00002840 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sands25cf2272008-11-24 14:53:14 +00002841 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman8a55ce42009-09-23 21:02:20 +00002842 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002843 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling2627a882009-01-30 20:43:18 +00002844 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00002845 MemVT, LN0->getMemOperand());
Chris Lattner5750df92006-03-01 04:03:14 +00002846 AddToWorkList(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00002847 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman475871a2008-07-27 21:46:04 +00002848 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begemanded49632005-10-13 03:11:28 +00002849 }
2850 }
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002851 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greifba36cb52008-08-28 21:40:38 +00002852 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng83060c52007-03-07 08:07:03 +00002853 N0.hasOneUse()) {
Evan Cheng466685d2006-10-09 20:57:25 +00002854 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman8a55ce42009-09-23 21:02:20 +00002855 EVT MemVT = LN0->getMemoryVT();
Nate Begemanbfd65a02005-10-13 18:34:58 +00002856 // If we zero all the possible extended bits, then we can turn this into
2857 // a zextload if we are running before legalize or the operation is legal.
Dan Gohman6900a392010-03-04 00:23:16 +00002858 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman2e68b6f2008-02-25 21:11:39 +00002859 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohman6900a392010-03-04 00:23:16 +00002860 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sands25cf2272008-11-24 14:53:14 +00002861 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman8a55ce42009-09-23 21:02:20 +00002862 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002863 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford66589dc2013-10-28 11:17:59 +00002864 LN0->getChain(), LN0->getBasePtr(),
2865 MemVT, LN0->getMemOperand());
Chris Lattner5750df92006-03-01 04:03:14 +00002866 AddToWorkList(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00002867 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman475871a2008-07-27 21:46:04 +00002868 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begemanded49632005-10-13 03:11:28 +00002869 }
2870 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002871
Chris Lattner35a9f5a2006-02-28 06:49:37 +00002872 // fold (and (load x), 255) -> (zextload x, i8)
2873 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Chengd40d03e2010-01-06 19:38:29 +00002874 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2875 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2876 (N0.getOpcode() == ISD::ANY_EXTEND &&
2877 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2878 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2879 LoadSDNode *LN0 = HasAnyExt
2880 ? cast<LoadSDNode>(N0.getOperand(0))
2881 : cast<LoadSDNode>(N0);
Evan Cheng466685d2006-10-09 20:57:25 +00002882 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover5bce67a2013-07-02 09:58:53 +00002883 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands8eab8a22008-06-09 11:32:28 +00002884 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Chengd40d03e2010-01-06 19:38:29 +00002885 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2886 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2887 EVT LoadedVT = LN0->getMemoryVT();
Duncan Sands8eab8a22008-06-09 11:32:28 +00002888
Evan Chengd40d03e2010-01-06 19:38:29 +00002889 if (ExtVT == LoadedVT &&
2890 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
Chris Lattneref7634c2010-01-07 21:53:27 +00002891 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Wesley Peckbf17cfa2010-11-23 03:31:01 +00002892
2893 SDValue NewLoad =
Andrew Trickac6d9be2013-05-25 02:42:55 +00002894 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford66589dc2013-10-28 11:17:59 +00002895 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2896 LN0->getMemOperand());
Chris Lattneref7634c2010-01-07 21:53:27 +00002897 AddToWorkList(N);
2898 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2899 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2900 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00002901
Chris Lattneref7634c2010-01-07 21:53:27 +00002902 // Do not change the width of a volatile load.
2903 // Do not generate loads of non-round integer types since these can
2904 // be expensive (and would be wrong if the type is not byte sized).
2905 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2906 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2907 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling2627a882009-01-30 20:43:18 +00002908
Chris Lattneref7634c2010-01-07 21:53:27 +00002909 unsigned Alignment = LN0->getAlignment();
2910 SDValue NewPtr = LN0->getBasePtr();
2911
2912 // For big endian targets, we need to add an offset to the pointer
2913 // to load the correct bytes. For little endian systems, we merely
2914 // need to read fewer bytes from the same pointer.
2915 if (TLI.isBigEndian()) {
Evan Chengd40d03e2010-01-06 19:38:29 +00002916 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2917 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2918 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickac6d9be2013-05-25 02:42:55 +00002919 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattneref7634c2010-01-07 21:53:27 +00002920 NewPtr, DAG.getConstant(PtrOff, PtrType));
2921 Alignment = MinAlign(Alignment, PtrOff);
Evan Chengd40d03e2010-01-06 19:38:29 +00002922 }
Chris Lattneref7634c2010-01-07 21:53:27 +00002923
2924 AddToWorkList(NewPtr.getNode());
Wesley Peckbf17cfa2010-11-23 03:31:01 +00002925
Chris Lattneref7634c2010-01-07 21:53:27 +00002926 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2927 SDValue Load =
Andrew Trickac6d9be2013-05-25 02:42:55 +00002928 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattneref7634c2010-01-07 21:53:27 +00002929 LN0->getChain(), NewPtr,
Chris Lattner3d6ccfb2010-09-21 17:04:51 +00002930 LN0->getPointerInfo(),
David Greene1e559442010-02-15 17:00:31 +00002931 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00002932 Alignment, LN0->getTBAAInfo());
Chris Lattneref7634c2010-01-07 21:53:27 +00002933 AddToWorkList(N);
2934 CombineTo(LN0, Load, Load.getValue(1));
2935 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sandsdc846502007-10-28 12:59:45 +00002936 }
Evan Cheng466685d2006-10-09 20:57:25 +00002937 }
Chris Lattner15045b62006-02-28 06:35:35 +00002938 }
2939 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002940
Evan Chenga9e13ba2012-07-17 18:54:11 +00002941 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2942 VT.getSizeInBits() <= 64) {
2943 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2944 APInt ADDC = ADDI->getAPIntValue();
2945 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2946 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2947 // immediate for an add, but it is legal if its top c2 bits are set,
2948 // transform the ADD so the immediate doesn't need to be materialized
2949 // in a register.
2950 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2951 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2952 SRLI->getZExtValue());
2953 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2954 ADDC |= Mask;
2955 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2956 SDValue NewAdd =
Andrew Trickac6d9be2013-05-25 02:42:55 +00002957 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenga9e13ba2012-07-17 18:54:11 +00002958 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2959 CombineTo(N0.getNode(), NewAdd);
2960 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2961 }
2962 }
2963 }
2964 }
2965 }
2966 }
Evan Chenga9e13ba2012-07-17 18:54:11 +00002967
Tim Northover5d8c2e42013-08-27 13:46:45 +00002968 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2969 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2970 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2971 N0.getOperand(1), false);
2972 if (BSwap.getNode())
2973 return BSwap;
2974 }
2975
Evan Chengb3a3d5e2010-04-28 07:10:39 +00002976 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00002977}
2978
Evan Cheng9568e5c2011-06-21 06:01:08 +00002979/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2980///
2981SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2982 bool DemandHighBits) {
2983 if (!LegalOperations)
2984 return SDValue();
2985
2986 EVT VT = N->getValueType(0);
2987 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2988 return SDValue();
2989 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2990 return SDValue();
2991
2992 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2993 bool LookPassAnd0 = false;
2994 bool LookPassAnd1 = false;
2995 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2996 std::swap(N0, N1);
2997 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2998 std::swap(N0, N1);
2999 if (N0.getOpcode() == ISD::AND) {
3000 if (!N0.getNode()->hasOneUse())
3001 return SDValue();
3002 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3003 if (!N01C || N01C->getZExtValue() != 0xFF00)
3004 return SDValue();
3005 N0 = N0.getOperand(0);
3006 LookPassAnd0 = true;
3007 }
3008
3009 if (N1.getOpcode() == ISD::AND) {
3010 if (!N1.getNode()->hasOneUse())
3011 return SDValue();
3012 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3013 if (!N11C || N11C->getZExtValue() != 0xFF)
3014 return SDValue();
3015 N1 = N1.getOperand(0);
3016 LookPassAnd1 = true;
3017 }
3018
3019 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3020 std::swap(N0, N1);
3021 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3022 return SDValue();
3023 if (!N0.getNode()->hasOneUse() ||
3024 !N1.getNode()->hasOneUse())
3025 return SDValue();
3026
3027 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3028 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3029 if (!N01C || !N11C)
3030 return SDValue();
3031 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3032 return SDValue();
3033
3034 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3035 SDValue N00 = N0->getOperand(0);
3036 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3037 if (!N00.getNode()->hasOneUse())
3038 return SDValue();
3039 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3040 if (!N001C || N001C->getZExtValue() != 0xFF)
3041 return SDValue();
3042 N00 = N00.getOperand(0);
3043 LookPassAnd0 = true;
3044 }
3045
3046 SDValue N10 = N1->getOperand(0);
3047 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3048 if (!N10.getNode()->hasOneUse())
3049 return SDValue();
3050 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3051 if (!N101C || N101C->getZExtValue() != 0xFF00)
3052 return SDValue();
3053 N10 = N10.getOperand(0);
3054 LookPassAnd1 = true;
3055 }
3056
3057 if (N00 != N10)
3058 return SDValue();
3059
Tim Northover5d8c2e42013-08-27 13:46:45 +00003060 // Make sure everything beyond the low halfword gets set to zero since the SRL
3061 // 16 will clear the top bits.
Evan Cheng9568e5c2011-06-21 06:01:08 +00003062 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover5d8c2e42013-08-27 13:46:45 +00003063 if (DemandHighBits && OpSizeInBits > 16) {
3064 // If the left-shift isn't masked out then the only way this is a bswap is
3065 // if all bits beyond the low 8 are 0. In that case the entire pattern
3066 // reduces to a left shift anyway: leave it for other parts of the combiner.
3067 if (!LookPassAnd0)
3068 return SDValue();
3069
3070 // However, if the right shift isn't masked out then it might be because
3071 // it's not needed. See if we can spot that too.
3072 if (!LookPassAnd1 &&
3073 !DAG.MaskedValueIsZero(
3074 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3075 return SDValue();
3076 }
Eric Christopher7332e6e2011-07-14 01:12:15 +00003077
Andrew Trickac6d9be2013-05-25 02:42:55 +00003078 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng9568e5c2011-06-21 06:01:08 +00003079 if (OpSizeInBits > 16)
Andrew Trickac6d9be2013-05-25 02:42:55 +00003080 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng9568e5c2011-06-21 06:01:08 +00003081 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3082 return Res;
3083}
3084
3085/// isBSwapHWordElement - Return true if the specified node is an element
3086/// that makes up a 32-bit packed halfword byteswap. i.e.
3087/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
Craig Toppera0ec3f92013-07-14 04:42:23 +00003088static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
Evan Cheng9568e5c2011-06-21 06:01:08 +00003089 if (!N.getNode()->hasOneUse())
3090 return false;
3091
3092 unsigned Opc = N.getOpcode();
3093 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3094 return false;
3095
3096 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3097 if (!N1C)
3098 return false;
3099
3100 unsigned Num;
3101 switch (N1C->getZExtValue()) {
3102 default:
3103 return false;
3104 case 0xFF: Num = 0; break;
3105 case 0xFF00: Num = 1; break;
3106 case 0xFF0000: Num = 2; break;
3107 case 0xFF000000: Num = 3; break;
3108 }
3109
3110 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3111 SDValue N0 = N.getOperand(0);
3112 if (Opc == ISD::AND) {
3113 if (Num == 0 || Num == 2) {
3114 // (x >> 8) & 0xff
3115 // (x >> 8) & 0xff0000
3116 if (N0.getOpcode() != ISD::SRL)
3117 return false;
3118 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3119 if (!C || C->getZExtValue() != 8)
3120 return false;
3121 } else {
3122 // (x << 8) & 0xff00
3123 // (x << 8) & 0xff000000
3124 if (N0.getOpcode() != ISD::SHL)
3125 return false;
3126 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3127 if (!C || C->getZExtValue() != 8)
3128 return false;
3129 }
3130 } else if (Opc == ISD::SHL) {
3131 // (x & 0xff) << 8
3132 // (x & 0xff0000) << 8
3133 if (Num != 0 && Num != 2)
3134 return false;
3135 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3136 if (!C || C->getZExtValue() != 8)
3137 return false;
3138 } else { // Opc == ISD::SRL
3139 // (x & 0xff00) >> 8
3140 // (x & 0xff000000) >> 8
3141 if (Num != 1 && Num != 3)
3142 return false;
3143 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3144 if (!C || C->getZExtValue() != 8)
3145 return false;
3146 }
3147
3148 if (Parts[Num])
3149 return false;
3150
3151 Parts[Num] = N0.getOperand(0).getNode();
3152 return true;
3153}
3154
3155/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3156/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3157/// => (rotl (bswap x), 16)
3158SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3159 if (!LegalOperations)
3160 return SDValue();
3161
3162 EVT VT = N->getValueType(0);
3163 if (VT != MVT::i32)
3164 return SDValue();
3165 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3166 return SDValue();
3167
3168 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3169 // Look for either
3170 // (or (or (and), (and)), (or (and), (and)))
3171 // (or (or (or (and), (and)), (and)), (and))
3172 if (N0.getOpcode() != ISD::OR)
3173 return SDValue();
3174 SDValue N00 = N0.getOperand(0);
3175 SDValue N01 = N0.getOperand(1);
3176
Evan Cheng9a65a012012-12-13 01:34:32 +00003177 if (N1.getOpcode() == ISD::OR &&
3178 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng9568e5c2011-06-21 06:01:08 +00003179 // (or (or (and), (and)), (or (and), (and)))
3180 SDValue N000 = N00.getOperand(0);
3181 if (!isBSwapHWordElement(N000, Parts))
3182 return SDValue();
3183
3184 SDValue N001 = N00.getOperand(1);
3185 if (!isBSwapHWordElement(N001, Parts))
3186 return SDValue();
3187 SDValue N010 = N01.getOperand(0);
3188 if (!isBSwapHWordElement(N010, Parts))
3189 return SDValue();
3190 SDValue N011 = N01.getOperand(1);
3191 if (!isBSwapHWordElement(N011, Parts))
3192 return SDValue();
3193 } else {
3194 // (or (or (or (and), (and)), (and)), (and))
3195 if (!isBSwapHWordElement(N1, Parts))
3196 return SDValue();
3197 if (!isBSwapHWordElement(N01, Parts))
3198 return SDValue();
3199 if (N00.getOpcode() != ISD::OR)
3200 return SDValue();
3201 SDValue N000 = N00.getOperand(0);
3202 if (!isBSwapHWordElement(N000, Parts))
3203 return SDValue();
3204 SDValue N001 = N00.getOperand(1);
3205 if (!isBSwapHWordElement(N001, Parts))
3206 return SDValue();
3207 }
3208
3209 // Make sure the parts are all coming from the same node.
3210 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3211 return SDValue();
3212
Andrew Trickac6d9be2013-05-25 02:42:55 +00003213 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng9568e5c2011-06-21 06:01:08 +00003214 SDValue(Parts[0],0));
3215
Kay Tiong Khoo670711e2013-09-23 18:43:51 +00003216 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng9568e5c2011-06-21 06:01:08 +00003217 // do (x << 16) | (x >> 16).
3218 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3219 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickac6d9be2013-05-25 02:42:55 +00003220 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper0eb5dad2012-09-29 07:18:53 +00003221 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickac6d9be2013-05-25 02:42:55 +00003222 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3223 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3224 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3225 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng9568e5c2011-06-21 06:01:08 +00003226}
3227
Dan Gohman475871a2008-07-27 21:46:04 +00003228SDValue DAGCombiner::visitOR(SDNode *N) {
3229 SDValue N0 = N->getOperand(0);
3230 SDValue N1 = N->getOperand(1);
3231 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman646d7e22005-09-02 21:18:40 +00003232 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3233 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00003234 EVT VT = N1.getValueType();
Scott Michelfdc40a02009-02-17 22:15:04 +00003235
Dan Gohman7f321562007-06-25 16:23:39 +00003236 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00003237 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003238 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00003239 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper9472b4f2012-12-08 22:49:19 +00003240
3241 // fold (or x, 0) -> x, vector edition
3242 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3243 return N1;
3244 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3245 return N0;
3246
3247 // fold (or x, -1) -> -1, vector edition
3248 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3249 return N0;
3250 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3251 return N1;
Stephen Hines36b56882014-04-23 16:57:46 -07003252
3253 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3254 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3255 // Do this only if the resulting shuffle is legal.
3256 if (isa<ShuffleVectorSDNode>(N0) &&
3257 isa<ShuffleVectorSDNode>(N1) &&
3258 N0->getOperand(1) == N1->getOperand(1) &&
3259 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3260 bool CanFold = true;
3261 unsigned NumElts = VT.getVectorNumElements();
3262 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3263 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3264 // We construct two shuffle masks:
3265 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3266 // and N1 as the second operand.
3267 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3268 // and N0 as the second operand.
3269 // We do this because OR is commutable and therefore there might be
3270 // two ways to fold this node into a shuffle.
3271 SmallVector<int,4> Mask1;
3272 SmallVector<int,4> Mask2;
3273
3274 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3275 int M0 = SV0->getMaskElt(i);
3276 int M1 = SV1->getMaskElt(i);
3277
3278 // Both shuffle indexes are undef. Propagate Undef.
3279 if (M0 < 0 && M1 < 0) {
3280 Mask1.push_back(M0);
3281 Mask2.push_back(M0);
3282 continue;
3283 }
3284
3285 if (M0 < 0 || M1 < 0 ||
3286 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3287 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3288 CanFold = false;
3289 break;
3290 }
3291
3292 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3293 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3294 }
3295
3296 if (CanFold) {
3297 // Fold this sequence only if the resulting shuffle is 'legal'.
3298 if (TLI.isShuffleMaskLegal(Mask1, VT))
3299 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3300 N1->getOperand(0), &Mask1[0]);
3301 if (TLI.isShuffleMaskLegal(Mask2, VT))
3302 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3303 N0->getOperand(0), &Mask2[0]);
3304 }
3305 }
Dan Gohman05d92fe2007-07-13 20:03:40 +00003306 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003307
Dan Gohman613e0d82007-07-03 14:03:57 +00003308 // fold (or x, undef) -> -1
Bob Wilson86749492010-06-28 23:40:25 +00003309 if (!LegalOperations &&
3310 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman93e0ed32009-12-03 07:11:29 +00003311 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3312 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3313 }
Nate Begeman1d4d4142005-09-01 00:19:25 +00003314 // fold (or c1, c2) -> c1|c2
Nate Begeman646d7e22005-09-02 21:18:40 +00003315 if (N0C && N1C)
Bill Wendlingf3cbca22008-09-24 10:25:02 +00003316 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman99801192005-09-07 23:25:52 +00003317 // canonicalize constant to RHS
Nate Begemana0e221d2005-10-18 00:28:13 +00003318 if (N0C && !N1C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00003319 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00003320 // fold (or x, 0) -> x
Nate Begeman646d7e22005-09-02 21:18:40 +00003321 if (N1C && N1C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00003322 return N0;
Nate Begeman1d4d4142005-09-01 00:19:25 +00003323 // fold (or x, -1) -> -1
Nate Begeman646d7e22005-09-02 21:18:40 +00003324 if (N1C && N1C->isAllOnesValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00003325 return N1;
Sylvestre Ledru94c22712012-09-27 10:14:43 +00003326 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman2e68b6f2008-02-25 21:11:39 +00003327 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begeman83e75ec2005-09-06 04:43:02 +00003328 return N1;
Evan Cheng9568e5c2011-06-21 06:01:08 +00003329
3330 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3331 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3332 if (BSwap.getNode() != 0)
3333 return BSwap;
3334 BSwap = MatchBSwapHWordLow(N, N0, N1);
3335 if (BSwap.getNode() != 0)
3336 return BSwap;
3337
Nate Begemancd4d58c2006-02-03 06:46:56 +00003338 // reassociate or
Andrew Trickac6d9be2013-05-25 02:42:55 +00003339 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Gabor Greifba36cb52008-08-28 21:40:38 +00003340 if (ROR.getNode() != 0)
Nate Begemancd4d58c2006-02-03 06:46:56 +00003341 return ROR;
3342 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru94c22712012-09-27 10:14:43 +00003343 // iff (c1 & c2) == 0.
Gabor Greifba36cb52008-08-28 21:40:38 +00003344 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattner731d3482005-10-27 05:06:38 +00003345 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattner731d3482005-10-27 05:06:38 +00003346 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Stephen Hines36b56882014-04-23 16:57:46 -07003347 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3348 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3349 if (!COR.getNode())
3350 return SDValue();
Andrew Trickac6d9be2013-05-25 02:42:55 +00003351 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3352 DAG.getNode(ISD::OR, SDLoc(N0), VT,
Stephen Hines36b56882014-04-23 16:57:46 -07003353 N0.getOperand(0), N1), COR);
3354 }
Nate Begeman223df222005-09-08 20:18:10 +00003355 }
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003356 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3357 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3358 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3359 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelfdc40a02009-02-17 22:15:04 +00003360
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003361 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands83ec4b62008-06-06 12:08:01 +00003362 LL.getValueType().isInteger()) {
Bill Wendling09025642009-01-30 20:59:34 +00003363 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3364 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelfdc40a02009-02-17 22:15:04 +00003365 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003366 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00003367 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendling09025642009-01-30 20:59:34 +00003368 LR.getValueType(), LL, RL);
Gabor Greifba36cb52008-08-28 21:40:38 +00003369 AddToWorkList(ORNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00003370 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003371 }
Bill Wendling09025642009-01-30 20:59:34 +00003372 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3373 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelfdc40a02009-02-17 22:15:04 +00003374 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003375 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00003376 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendling09025642009-01-30 20:59:34 +00003377 LR.getValueType(), LL, RL);
Gabor Greifba36cb52008-08-28 21:40:38 +00003378 AddToWorkList(ANDNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00003379 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003380 }
3381 }
3382 // canonicalize equivalent to ll == rl
3383 if (LL == RR && LR == RL) {
3384 Op1 = ISD::getSetCCSwappedOperands(Op1);
3385 std::swap(RL, RR);
3386 }
3387 if (LL == RL && LR == RR) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003388 bool isInteger = LL.getValueType().isInteger();
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003389 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner6e1c6232008-10-28 07:11:07 +00003390 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundfdbeb052012-12-19 10:19:55 +00003391 (!LegalOperations ||
Owen Anderson39125d92013-02-14 09:07:33 +00003392 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3393 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault225ed702013-05-18 00:21:46 +00003394 getSetCCResultType(N0.getValueType())))))
Andrew Trickac6d9be2013-05-25 02:42:55 +00003395 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling09025642009-01-30 20:59:34 +00003396 LL, LR, Result);
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003397 }
3398 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003399
Bill Wendling09025642009-01-30 20:59:34 +00003400 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner35e5c142006-05-05 05:51:50 +00003401 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003402 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00003403 if (Tmp.getNode()) return Tmp;
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003404 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003405
Bill Wendling09025642009-01-30 20:59:34 +00003406 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner1ec72732006-09-14 21:11:37 +00003407 if (N0.getOpcode() == ISD::AND &&
3408 N1.getOpcode() == ISD::AND &&
3409 N0.getOperand(1).getOpcode() == ISD::Constant &&
3410 N1.getOperand(1).getOpcode() == ISD::Constant &&
3411 // Don't increase # computations.
Gabor Greifba36cb52008-08-28 21:40:38 +00003412 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner1ec72732006-09-14 21:11:37 +00003413 // We can only do this xform if we know that bits from X that are set in C2
3414 // but not in C1 are already zero. Likewise for Y.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00003415 const APInt &LHSMask =
3416 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3417 const APInt &RHSMask =
3418 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelfdc40a02009-02-17 22:15:04 +00003419
Dan Gohmanea859be2007-06-22 14:59:07 +00003420 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3421 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00003422 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendling09025642009-01-30 20:59:34 +00003423 N0.getOperand(0), N1.getOperand(0));
Andrew Trickac6d9be2013-05-25 02:42:55 +00003424 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendling09025642009-01-30 20:59:34 +00003425 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner1ec72732006-09-14 21:11:37 +00003426 }
3427 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003428
Chris Lattner516b9622006-09-14 20:50:57 +00003429 // See if this is some rotate idiom.
Andrew Trickac6d9be2013-05-25 02:42:55 +00003430 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman475871a2008-07-27 21:46:04 +00003431 return SDValue(Rot, 0);
Chris Lattner35e5c142006-05-05 05:51:50 +00003432
Dan Gohman4e39e9d2010-06-24 14:30:44 +00003433 // Simplify the operands using demanded-bits information.
3434 if (!VT.isVector() &&
3435 SimplifyDemandedBits(SDValue(N, 0)))
3436 return SDValue(N, 0);
3437
Evan Chengb3a3d5e2010-04-28 07:10:39 +00003438 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00003439}
3440
Chris Lattner516b9622006-09-14 20:50:57 +00003441/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman475871a2008-07-27 21:46:04 +00003442static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner516b9622006-09-14 20:50:57 +00003443 if (Op.getOpcode() == ISD::AND) {
Reid Spencer3ed469c2006-11-02 20:25:50 +00003444 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner516b9622006-09-14 20:50:57 +00003445 Mask = Op.getOperand(1);
3446 Op = Op.getOperand(0);
3447 } else {
3448 return false;
3449 }
3450 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003451
Chris Lattner516b9622006-09-14 20:50:57 +00003452 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3453 Shift = Op;
3454 return true;
3455 }
Bill Wendling09025642009-01-30 20:59:34 +00003456
Scott Michelfdc40a02009-02-17 22:15:04 +00003457 return false;
Chris Lattner516b9622006-09-14 20:50:57 +00003458}
3459
Stephen Hines36b56882014-04-23 16:57:46 -07003460// Return true if we can prove that, whenever Neg and Pos are both in the
3461// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3462// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3463//
3464// (or (shift1 X, Neg), (shift2 X, Pos))
3465//
3466// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3467// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3468// to consider shift amounts with defined behavior.
3469static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3470 // If OpSize is a power of 2 then:
3471 //
3472 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3473 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3474 //
3475 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3476 // for the stronger condition:
3477 //
3478 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3479 //
3480 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3481 // we can just replace Neg with Neg' for the rest of the function.
3482 //
3483 // In other cases we check for the even stronger condition:
3484 //
3485 // Neg == OpSize - Pos [B]
3486 //
3487 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3488 // behavior if Pos == 0 (and consequently Neg == OpSize).
3489 //
3490 // We could actually use [A] whenever OpSize is a power of 2, but the
3491 // only extra cases that it would match are those uninteresting ones
3492 // where Neg and Pos are never in range at the same time. E.g. for
3493 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3494 // as well as (sub 32, Pos), but:
3495 //
3496 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3497 //
3498 // always invokes undefined behavior for 32-bit X.
3499 //
3500 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3501 unsigned MaskLoBits = 0;
3502 if (Neg.getOpcode() == ISD::AND &&
3503 isPowerOf2_64(OpSize) &&
3504 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3505 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3506 Neg = Neg.getOperand(0);
3507 MaskLoBits = Log2_64(OpSize);
3508 }
3509
3510 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3511 if (Neg.getOpcode() != ISD::SUB)
3512 return 0;
3513 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3514 if (!NegC)
3515 return 0;
3516 SDValue NegOp1 = Neg.getOperand(1);
3517
3518 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3519 // Pos'. The truncation is redundant for the purpose of the equality.
3520 if (MaskLoBits &&
3521 Pos.getOpcode() == ISD::AND &&
3522 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3523 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3524 Pos = Pos.getOperand(0);
3525
3526 // The condition we need is now:
3527 //
3528 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3529 //
3530 // If NegOp1 == Pos then we need:
3531 //
3532 // OpSize & Mask == NegC & Mask
3533 //
3534 // (because "x & Mask" is a truncation and distributes through subtraction).
3535 APInt Width;
3536 if (Pos == NegOp1)
3537 Width = NegC->getAPIntValue();
3538 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3539 // Then the condition we want to prove becomes:
3540 //
3541 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3542 //
3543 // which, again because "x & Mask" is a truncation, becomes:
3544 //
3545 // NegC & Mask == (OpSize - PosC) & Mask
3546 // OpSize & Mask == (NegC + PosC) & Mask
3547 else if (Pos.getOpcode() == ISD::ADD &&
3548 Pos.getOperand(0) == NegOp1 &&
3549 Pos.getOperand(1).getOpcode() == ISD::Constant)
3550 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3551 NegC->getAPIntValue());
3552 else
3553 return false;
3554
3555 // Now we just need to check that OpSize & Mask == Width & Mask.
3556 if (MaskLoBits)
3557 // Opsize & Mask is 0 since Mask is Opsize - 1.
3558 return Width.getLoBits(MaskLoBits) == 0;
3559 return Width == OpSize;
3560}
3561
3562// A subroutine of MatchRotate used once we have found an OR of two opposite
3563// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3564// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3565// former being preferred if supported. InnerPos and InnerNeg are Pos and
3566// Neg with outer conversions stripped away.
3567SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3568 SDValue Neg, SDValue InnerPos,
3569 SDValue InnerNeg, unsigned PosOpcode,
3570 unsigned NegOpcode, SDLoc DL) {
3571 // fold (or (shl x, (*ext y)),
3572 // (srl x, (*ext (sub 32, y)))) ->
3573 // (rotl x, y) or (rotr x, (sub 32, y))
3574 //
3575 // fold (or (shl x, (*ext (sub 32, y))),
3576 // (srl x, (*ext y))) ->
3577 // (rotr x, y) or (rotl x, (sub 32, y))
3578 EVT VT = Shifted.getValueType();
3579 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3580 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3581 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3582 HasPos ? Pos : Neg).getNode();
3583 }
3584
3585 // fold (or (shl (*ext x), (*ext y)),
3586 // (srl (*ext x), (*ext (sub 32, y)))) ->
3587 // (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3588 //
3589 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3590 // (srl (*ext x), (*ext y))) ->
3591 // (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3592 if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3593 Shifted.getOpcode() == ISD::ANY_EXTEND) {
3594 SDValue InnerShifted = Shifted.getOperand(0);
3595 EVT InnerVT = InnerShifted.getValueType();
3596 bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3597 if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
3598 if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
3599 SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3600 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3601 return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3602 }
3603 }
3604 }
3605
3606 return 0;
3607}
3608
Chris Lattner516b9622006-09-14 20:50:57 +00003609// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3610// idioms for rotate, and if the target supports rotation instructions, generate
3611// a rot[lr].
Andrew Trickac6d9be2013-05-25 02:42:55 +00003612SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sandsd4b9c172008-06-13 19:07:40 +00003613 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Andersone50ed302009-08-10 22:56:29 +00003614 EVT VT = LHS.getValueType();
Chris Lattner516b9622006-09-14 20:50:57 +00003615 if (!TLI.isTypeLegal(VT)) return 0;
3616
3617 // The target must have at least one rotate flavor.
Dan Gohmanf560ffa2009-01-28 17:46:25 +00003618 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3619 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Chris Lattner516b9622006-09-14 20:50:57 +00003620 if (!HasROTL && !HasROTR) return 0;
Duncan Sandsd4b9c172008-06-13 19:07:40 +00003621
Chris Lattner516b9622006-09-14 20:50:57 +00003622 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman475871a2008-07-27 21:46:04 +00003623 SDValue LHSShift; // The shift.
3624 SDValue LHSMask; // AND value if any.
Chris Lattner516b9622006-09-14 20:50:57 +00003625 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3626 return 0; // Not part of a rotate.
3627
Dan Gohman475871a2008-07-27 21:46:04 +00003628 SDValue RHSShift; // The shift.
3629 SDValue RHSMask; // AND value if any.
Chris Lattner516b9622006-09-14 20:50:57 +00003630 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3631 return 0; // Not part of a rotate.
Scott Michelfdc40a02009-02-17 22:15:04 +00003632
Chris Lattner516b9622006-09-14 20:50:57 +00003633 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3634 return 0; // Not shifting the same value.
3635
3636 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3637 return 0; // Shifts must disagree.
Scott Michelfdc40a02009-02-17 22:15:04 +00003638
Chris Lattner516b9622006-09-14 20:50:57 +00003639 // Canonicalize shl to left side in a shl/srl pair.
3640 if (RHSShift.getOpcode() == ISD::SHL) {
3641 std::swap(LHS, RHS);
3642 std::swap(LHSShift, RHSShift);
3643 std::swap(LHSMask , RHSMask );
3644 }
3645
Duncan Sands83ec4b62008-06-06 12:08:01 +00003646 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman475871a2008-07-27 21:46:04 +00003647 SDValue LHSShiftArg = LHSShift.getOperand(0);
3648 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Stephen Hines36b56882014-04-23 16:57:46 -07003649 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman475871a2008-07-27 21:46:04 +00003650 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner516b9622006-09-14 20:50:57 +00003651
3652 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3653 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michelc9dc1142007-04-02 21:36:32 +00003654 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3655 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003656 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3657 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner516b9622006-09-14 20:50:57 +00003658 if ((LShVal + RShVal) != OpSizeInBits)
3659 return 0;
3660
Craig Topper32b73432012-09-29 06:54:22 +00003661 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3662 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelfdc40a02009-02-17 22:15:04 +00003663
Chris Lattner516b9622006-09-14 20:50:57 +00003664 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greifba36cb52008-08-28 21:40:38 +00003665 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohman220a8232008-03-03 23:51:38 +00003666 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelfdc40a02009-02-17 22:15:04 +00003667
Gabor Greifba36cb52008-08-28 21:40:38 +00003668 if (LHSMask.getNode()) {
Dan Gohman220a8232008-03-03 23:51:38 +00003669 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3670 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner516b9622006-09-14 20:50:57 +00003671 }
Gabor Greifba36cb52008-08-28 21:40:38 +00003672 if (RHSMask.getNode()) {
Dan Gohman220a8232008-03-03 23:51:38 +00003673 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3674 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner516b9622006-09-14 20:50:57 +00003675 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003676
Bill Wendling317bd702009-01-30 21:14:50 +00003677 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner516b9622006-09-14 20:50:57 +00003678 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003679
Gabor Greifba36cb52008-08-28 21:40:38 +00003680 return Rot.getNode();
Chris Lattner516b9622006-09-14 20:50:57 +00003681 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003682
Chris Lattner516b9622006-09-14 20:50:57 +00003683 // If there is a mask here, and we have a variable shift, we can't be sure
3684 // that we're masking out the right stuff.
Gabor Greifba36cb52008-08-28 21:40:38 +00003685 if (LHSMask.getNode() || RHSMask.getNode())
Chris Lattner516b9622006-09-14 20:50:57 +00003686 return 0;
Scott Michelfdc40a02009-02-17 22:15:04 +00003687
Benjamin Kramercd216b22013-09-24 14:21:28 +00003688 // If the shift amount is sign/zext/any-extended just peel it off.
3689 SDValue LExtOp0 = LHSShiftAmt;
3690 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper0eb5dad2012-09-29 07:18:53 +00003691 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3692 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3693 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3694 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3695 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3696 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3697 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3698 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramercd216b22013-09-24 14:21:28 +00003699 LExtOp0 = LHSShiftAmt.getOperand(0);
3700 RExtOp0 = RHSShiftAmt.getOperand(0);
3701 }
3702
Stephen Hines36b56882014-04-23 16:57:46 -07003703 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3704 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3705 if (TryL)
3706 return TryL;
3707
3708 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3709 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3710 if (TryR)
3711 return TryR;
Scott Michelfdc40a02009-02-17 22:15:04 +00003712
Chris Lattner516b9622006-09-14 20:50:57 +00003713 return 0;
3714}
3715
Dan Gohman475871a2008-07-27 21:46:04 +00003716SDValue DAGCombiner::visitXOR(SDNode *N) {
3717 SDValue N0 = N->getOperand(0);
3718 SDValue N1 = N->getOperand(1);
3719 SDValue LHS, RHS, CC;
Nate Begeman646d7e22005-09-02 21:18:40 +00003720 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3721 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00003722 EVT VT = N0.getValueType();
Scott Michelfdc40a02009-02-17 22:15:04 +00003723
Dan Gohman7f321562007-06-25 16:23:39 +00003724 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00003725 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003726 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00003727 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper9472b4f2012-12-08 22:49:19 +00003728
3729 // fold (xor x, 0) -> x, vector edition
3730 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3731 return N1;
3732 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3733 return N0;
Dan Gohman05d92fe2007-07-13 20:03:40 +00003734 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003735
Evan Cheng26471c42008-03-25 20:08:07 +00003736 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3737 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3738 return DAG.getConstant(0, VT);
Dan Gohman613e0d82007-07-03 14:03:57 +00003739 // fold (xor x, undef) -> undef
Dan Gohman70fb1ae2007-07-10 15:19:29 +00003740 if (N0.getOpcode() == ISD::UNDEF)
3741 return N0;
3742 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman613e0d82007-07-03 14:03:57 +00003743 return N1;
Nate Begeman1d4d4142005-09-01 00:19:25 +00003744 // fold (xor c1, c2) -> c1^c2
Nate Begeman646d7e22005-09-02 21:18:40 +00003745 if (N0C && N1C)
Bill Wendlingf3cbca22008-09-24 10:25:02 +00003746 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman99801192005-09-07 23:25:52 +00003747 // canonicalize constant to RHS
Nate Begemana0e221d2005-10-18 00:28:13 +00003748 if (N0C && !N1C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00003749 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00003750 // fold (xor x, 0) -> x
Nate Begeman646d7e22005-09-02 21:18:40 +00003751 if (N1C && N1C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00003752 return N0;
Nate Begemancd4d58c2006-02-03 06:46:56 +00003753 // reassociate xor
Andrew Trickac6d9be2013-05-25 02:42:55 +00003754 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Gabor Greifba36cb52008-08-28 21:40:38 +00003755 if (RXOR.getNode() != 0)
Nate Begemancd4d58c2006-02-03 06:46:56 +00003756 return RXOR;
Bill Wendlingae89bb12008-11-11 08:25:46 +00003757
Nate Begeman1d4d4142005-09-01 00:19:25 +00003758 // fold !(x cc y) -> (x !cc y)
Dan Gohman002e5d02008-03-13 22:13:53 +00003759 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003760 bool isInt = LHS.getValueType().isInteger();
Nate Begeman646d7e22005-09-02 21:18:40 +00003761 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3762 isInt);
Bill Wendlingae89bb12008-11-11 08:25:46 +00003763
Patrik Hagglundfdbeb052012-12-19 10:19:55 +00003764 if (!LegalOperations ||
3765 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendlingae89bb12008-11-11 08:25:46 +00003766 switch (N0.getOpcode()) {
3767 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003768 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendlingae89bb12008-11-11 08:25:46 +00003769 case ISD::SETCC:
Andrew Trickac6d9be2013-05-25 02:42:55 +00003770 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendlingae89bb12008-11-11 08:25:46 +00003771 case ISD::SELECT_CC:
Andrew Trickac6d9be2013-05-25 02:42:55 +00003772 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendlingae89bb12008-11-11 08:25:46 +00003773 N0.getOperand(3), NotCC);
3774 }
3775 }
Nate Begeman1d4d4142005-09-01 00:19:25 +00003776 }
Bill Wendlingae89bb12008-11-11 08:25:46 +00003777
Chris Lattner61c5ff42007-09-10 21:39:07 +00003778 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohman002e5d02008-03-13 22:13:53 +00003779 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greif12632d22008-08-30 19:29:20 +00003780 N0.getNode()->hasOneUse() &&
3781 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman475871a2008-07-27 21:46:04 +00003782 SDValue V = N0.getOperand(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00003783 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands272dce02007-10-10 09:54:50 +00003784 DAG.getConstant(1, V.getValueType()));
Gabor Greifba36cb52008-08-28 21:40:38 +00003785 AddToWorkList(V.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00003786 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner61c5ff42007-09-10 21:39:07 +00003787 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003788
Sylvestre Ledru94c22712012-09-27 10:14:43 +00003789 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson825b72b2009-08-11 20:47:22 +00003790 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman99801192005-09-07 23:25:52 +00003791 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman475871a2008-07-27 21:46:04 +00003792 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman99801192005-09-07 23:25:52 +00003793 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3794 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickac6d9be2013-05-25 02:42:55 +00003795 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3796 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greifba36cb52008-08-28 21:40:38 +00003797 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00003798 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman1d4d4142005-09-01 00:19:25 +00003799 }
3800 }
Sylvestre Ledru94c22712012-09-27 10:14:43 +00003801 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelfdc40a02009-02-17 22:15:04 +00003802 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman99801192005-09-07 23:25:52 +00003803 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman475871a2008-07-27 21:46:04 +00003804 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman99801192005-09-07 23:25:52 +00003805 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3806 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickac6d9be2013-05-25 02:42:55 +00003807 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3808 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greifba36cb52008-08-28 21:40:38 +00003809 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00003810 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman1d4d4142005-09-01 00:19:25 +00003811 }
3812 }
David Majnemer363160a2013-05-08 06:44:42 +00003813 // fold (xor (and x, y), y) -> (and (not x), y)
3814 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerd5ae5b02013-11-17 10:40:03 +00003815 N0->getOperand(1) == N1) {
David Majnemer363160a2013-05-08 06:44:42 +00003816 SDValue X = N0->getOperand(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00003817 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
David Majnemer363160a2013-05-08 06:44:42 +00003818 AddToWorkList(NotX.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00003819 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer363160a2013-05-08 06:44:42 +00003820 }
Bill Wendling317bd702009-01-30 21:14:50 +00003821 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman223df222005-09-08 20:18:10 +00003822 if (N1C && N0.getOpcode() == ISD::XOR) {
3823 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3824 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3825 if (N00C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00003826 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling317bd702009-01-30 21:14:50 +00003827 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohman002e5d02008-03-13 22:13:53 +00003828 N00C->getAPIntValue(), VT));
Nate Begeman223df222005-09-08 20:18:10 +00003829 if (N01C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00003830 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling317bd702009-01-30 21:14:50 +00003831 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohman002e5d02008-03-13 22:13:53 +00003832 N01C->getAPIntValue(), VT));
Nate Begeman223df222005-09-08 20:18:10 +00003833 }
3834 // fold (xor x, x) -> 0
Eric Christopher7bccf6a2011-02-16 04:50:12 +00003835 if (N0 == N1)
Hal Finkelbd6f1f62013-07-09 17:02:45 +00003836 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelfdc40a02009-02-17 22:15:04 +00003837
Chris Lattner35e5c142006-05-05 05:51:50 +00003838 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3839 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003840 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00003841 if (Tmp.getNode()) return Tmp;
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003842 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003843
Chris Lattner3e104b12006-04-08 04:15:24 +00003844 // Simplify the expression using non-local knowledge.
Duncan Sands83ec4b62008-06-06 12:08:01 +00003845 if (!VT.isVector() &&
Dan Gohman475871a2008-07-27 21:46:04 +00003846 SimplifyDemandedBits(SDValue(N, 0)))
3847 return SDValue(N, 0);
Scott Michelfdc40a02009-02-17 22:15:04 +00003848
Evan Chengb3a3d5e2010-04-28 07:10:39 +00003849 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00003850}
3851
Chris Lattnere70da202007-12-06 07:33:36 +00003852/// visitShiftByConstant - Handle transforms common to the three shifts, when
3853/// the shift amount is a constant.
Stephen Hines36b56882014-04-23 16:57:46 -07003854SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3855 // We can't and shouldn't fold opaque constants.
3856 if (Amt->isOpaque())
3857 return SDValue();
3858
Gabor Greifba36cb52008-08-28 21:40:38 +00003859 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman475871a2008-07-27 21:46:04 +00003860 if (!LHS->hasOneUse()) return SDValue();
Scott Michelfdc40a02009-02-17 22:15:04 +00003861
Chris Lattnere70da202007-12-06 07:33:36 +00003862 // We want to pull some binops through shifts, so that we have (and (shift))
3863 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3864 // thing happens with address calculations, so it's important to canonicalize
3865 // it.
3866 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelfdc40a02009-02-17 22:15:04 +00003867
Chris Lattnere70da202007-12-06 07:33:36 +00003868 switch (LHS->getOpcode()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003869 default: return SDValue();
Chris Lattnere70da202007-12-06 07:33:36 +00003870 case ISD::OR:
3871 case ISD::XOR:
3872 HighBitSet = false; // We can only transform sra if the high bit is clear.
3873 break;
3874 case ISD::AND:
3875 HighBitSet = true; // We can only transform sra if the high bit is set.
3876 break;
3877 case ISD::ADD:
Scott Michelfdc40a02009-02-17 22:15:04 +00003878 if (N->getOpcode() != ISD::SHL)
Dan Gohman475871a2008-07-27 21:46:04 +00003879 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattnere70da202007-12-06 07:33:36 +00003880 HighBitSet = false; // We can only transform sra if the high bit is clear.
3881 break;
3882 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003883
Stephen Hines36b56882014-04-23 16:57:46 -07003884 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattnere70da202007-12-06 07:33:36 +00003885 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Stephen Hines36b56882014-04-23 16:57:46 -07003886 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendling88103372009-01-30 21:37:17 +00003887
3888 // FIXME: disable this unless the input to the binop is a shift by a constant.
3889 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnerd3fd6d22007-12-06 07:47:55 +00003890 //
Bill Wendling88103372009-01-30 21:37:17 +00003891 // void foo(int *X, int i) { X[i & 1235] = 1; }
3892 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greifba36cb52008-08-28 21:40:38 +00003893 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelfdc40a02009-02-17 22:15:04 +00003894 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnerd3fd6d22007-12-06 07:47:55 +00003895 BinOpLHSVal->getOpcode() != ISD::SRA &&
3896 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3897 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman475871a2008-07-27 21:46:04 +00003898 return SDValue();
Scott Michelfdc40a02009-02-17 22:15:04 +00003899
Owen Andersone50ed302009-08-10 22:56:29 +00003900 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00003901
Bill Wendling88103372009-01-30 21:37:17 +00003902 // If this is a signed shift right, and the high bit is modified by the
3903 // logical operation, do not perform the transformation. The highBitSet
3904 // boolean indicates the value of the high bit of the constant which would
3905 // cause it to be modified for this operation.
Chris Lattnere70da202007-12-06 07:33:36 +00003906 if (N->getOpcode() == ISD::SRA) {
Dan Gohman220a8232008-03-03 23:51:38 +00003907 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3908 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman475871a2008-07-27 21:46:04 +00003909 return SDValue();
Chris Lattnere70da202007-12-06 07:33:36 +00003910 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003911
Chris Lattnere70da202007-12-06 07:33:36 +00003912 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickac6d9be2013-05-25 02:42:55 +00003913 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendling88103372009-01-30 21:37:17 +00003914 N->getValueType(0),
3915 LHS->getOperand(1), N->getOperand(1));
Stephen Hines36b56882014-04-23 16:57:46 -07003916 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattnere70da202007-12-06 07:33:36 +00003917
3918 // Create the new shift.
Eric Christopher503a64d2010-12-09 04:48:06 +00003919 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickac6d9be2013-05-25 02:42:55 +00003920 SDLoc(LHS->getOperand(0)),
Bill Wendling88103372009-01-30 21:37:17 +00003921 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattnere70da202007-12-06 07:33:36 +00003922
3923 // Create the new binop.
Andrew Trickac6d9be2013-05-25 02:42:55 +00003924 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattnere70da202007-12-06 07:33:36 +00003925}
3926
Stephen Hines36b56882014-04-23 16:57:46 -07003927SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3928 assert(N->getOpcode() == ISD::TRUNCATE);
3929 assert(N->getOperand(0).getOpcode() == ISD::AND);
3930
3931 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3932 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3933 SDValue N01 = N->getOperand(0).getOperand(1);
3934
3935 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3936 EVT TruncVT = N->getValueType(0);
3937 SDValue N00 = N->getOperand(0).getOperand(0);
3938 APInt TruncC = N01C->getAPIntValue();
3939 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3940
3941 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3942 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3943 DAG.getConstant(TruncC, TruncVT));
3944 }
3945 }
3946
3947 return SDValue();
3948}
3949
3950SDValue DAGCombiner::visitRotate(SDNode *N) {
3951 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3952 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3953 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3954 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3955 if (NewOp1.getNode())
3956 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3957 N->getOperand(0), NewOp1);
3958 }
3959 return SDValue();
3960}
3961
Dan Gohman475871a2008-07-27 21:46:04 +00003962SDValue DAGCombiner::visitSHL(SDNode *N) {
3963 SDValue N0 = N->getOperand(0);
3964 SDValue N1 = N->getOperand(1);
Nate Begeman646d7e22005-09-02 21:18:40 +00003965 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3966 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00003967 EVT VT = N0.getValueType();
Stephen Hines36b56882014-04-23 16:57:46 -07003968 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelfdc40a02009-02-17 22:15:04 +00003969
Daniel Sanders028e4d22013-11-11 17:23:41 +00003970 // fold vector ops
3971 if (VT.isVector()) {
3972 SDValue FoldedVOp = SimplifyVBinOp(N);
3973 if (FoldedVOp.getNode()) return FoldedVOp;
Stephen Hines36b56882014-04-23 16:57:46 -07003974
3975 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3976 // If setcc produces all-one true value then:
3977 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3978 if (N1CV && N1CV->isConstant()) {
3979 if (N0.getOpcode() == ISD::AND &&
3980 TLI.getBooleanContents(true) ==
3981 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3982 SDValue N00 = N0->getOperand(0);
3983 SDValue N01 = N0->getOperand(1);
3984 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3985
3986 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3987 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3988 if (C.getNode())
3989 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3990 }
3991 } else {
3992 N1C = isConstOrConstSplat(N1);
3993 }
3994 }
Daniel Sanders028e4d22013-11-11 17:23:41 +00003995 }
3996
Nate Begeman1d4d4142005-09-01 00:19:25 +00003997 // fold (shl c1, c2) -> c1<<c2
Nate Begeman646d7e22005-09-02 21:18:40 +00003998 if (N0C && N1C)
Bill Wendlingf3cbca22008-09-24 10:25:02 +00003999 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman1d4d4142005-09-01 00:19:25 +00004000 // fold (shl 0, x) -> 0
Nate Begeman646d7e22005-09-02 21:18:40 +00004001 if (N0C && N0C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00004002 return N0;
Nate Begeman1d4d4142005-09-01 00:19:25 +00004003 // fold (shl x, c >= size(x)) -> undef
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00004004 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesene8d72302009-02-06 23:05:02 +00004005 return DAG.getUNDEF(VT);
Nate Begeman1d4d4142005-09-01 00:19:25 +00004006 // fold (shl x, 0) -> x
Nate Begeman646d7e22005-09-02 21:18:40 +00004007 if (N1C && N1C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00004008 return N0;
Chad Rosier92bcd962011-06-14 22:29:10 +00004009 // fold (shl undef, x) -> 0
4010 if (N0.getOpcode() == ISD::UNDEF)
4011 return DAG.getConstant(0, VT);
Nate Begeman1d4d4142005-09-01 00:19:25 +00004012 // if (shl x, c) is known to be zero, return 0
Dan Gohman475871a2008-07-27 21:46:04 +00004013 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman87862e72009-12-11 21:31:27 +00004014 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begeman83e75ec2005-09-06 04:43:02 +00004015 return DAG.getConstant(0, VT);
Duncan Sandsb0d5cdd2009-02-01 18:06:53 +00004016 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengeb9f8922008-08-30 02:03:58 +00004017 if (N1.getOpcode() == ISD::TRUNCATE &&
Stephen Hines36b56882014-04-23 16:57:46 -07004018 N1.getOperand(0).getOpcode() == ISD::AND) {
4019 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4020 if (NewOp1.getNode())
4021 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengeb9f8922008-08-30 02:03:58 +00004022 }
4023
Dan Gohman475871a2008-07-27 21:46:04 +00004024 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4025 return SDValue(N, 0);
Bill Wendling88103372009-01-30 21:37:17 +00004026
4027 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Stephen Hines36b56882014-04-23 16:57:46 -07004028 if (N1C && N0.getOpcode() == ISD::SHL) {
4029 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4030 uint64_t c1 = N0C1->getZExtValue();
4031 uint64_t c2 = N1C->getZExtValue();
4032 if (c1 + c2 >= OpSizeInBits)
4033 return DAG.getConstant(0, VT);
4034 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4035 DAG.getConstant(c1 + c2, N1.getValueType()));
4036 }
Nate Begeman1d4d4142005-09-01 00:19:25 +00004037 }
Dale Johannesenc72b18c2010-12-21 21:55:50 +00004038
4039 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4040 // For this to be valid, the second form must not preserve any of the bits
4041 // that are shifted out by the inner shift in the first form. This means
4042 // the outer shift size must be >= the number of bits added by the ext.
4043 // As a corollary, we don't care what kind of ext it is.
4044 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4045 N0.getOpcode() == ISD::ANY_EXTEND ||
4046 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Stephen Hines36b56882014-04-23 16:57:46 -07004047 N0.getOperand(0).getOpcode() == ISD::SHL) {
4048 SDValue N0Op0 = N0.getOperand(0);
4049 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4050 uint64_t c1 = N0Op0C1->getZExtValue();
4051 uint64_t c2 = N1C->getZExtValue();
4052 EVT InnerShiftVT = N0Op0.getValueType();
4053 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4054 if (c2 >= OpSizeInBits - InnerShiftSize) {
4055 if (c1 + c2 >= OpSizeInBits)
4056 return DAG.getConstant(0, VT);
4057 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4058 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4059 N0Op0->getOperand(0)),
4060 DAG.getConstant(c1 + c2, N1.getValueType()));
4061 }
Dale Johannesenc72b18c2010-12-21 21:55:50 +00004062 }
4063 }
4064
Andrea Di Biagioa9f113d2013-09-27 11:37:05 +00004065 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4066 // Only fold this if the inner zext has no other uses to avoid increasing
4067 // the total number of instructions.
4068 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Stephen Hines36b56882014-04-23 16:57:46 -07004069 N0.getOperand(0).getOpcode() == ISD::SRL) {
4070 SDValue N0Op0 = N0.getOperand(0);
4071 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4072 uint64_t c1 = N0Op0C1->getZExtValue();
4073 if (c1 < VT.getScalarSizeInBits()) {
4074 uint64_t c2 = N1C->getZExtValue();
4075 if (c1 == c2) {
4076 SDValue NewOp0 = N0.getOperand(0);
4077 EVT CountVT = NewOp0.getOperand(1).getValueType();
4078 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4079 NewOp0, DAG.getConstant(c2, CountVT));
4080 AddToWorkList(NewSHL.getNode());
4081 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4082 }
Andrea Di Biagioa9f113d2013-09-27 11:37:05 +00004083 }
4084 }
4085 }
4086
Eli Friedman2a6d9eb2011-06-09 22:14:44 +00004087 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4088 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruth62dfc512012-01-05 11:05:55 +00004089 // Only fold this if the inner shift has no other uses -- if it does, folding
4090 // this will increase the total number of instructions.
Stephen Hines36b56882014-04-23 16:57:46 -07004091 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4092 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4093 uint64_t c1 = N0C1->getZExtValue();
4094 if (c1 < OpSizeInBits) {
4095 uint64_t c2 = N1C->getZExtValue();
4096 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4097 SDValue Shift;
4098 if (c2 > c1) {
4099 Mask = Mask.shl(c2 - c1);
4100 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4101 DAG.getConstant(c2 - c1, N1.getValueType()));
4102 } else {
4103 Mask = Mask.lshr(c1 - c2);
4104 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4105 DAG.getConstant(c1 - c2, N1.getValueType()));
4106 }
4107 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4108 DAG.getConstant(Mask, VT));
Eli Friedman2a6d9eb2011-06-09 22:14:44 +00004109 }
Evan Chengd101a722009-07-21 05:40:15 +00004110 }
Nate Begeman1d4d4142005-09-01 00:19:25 +00004111 }
Bill Wendling88103372009-01-30 21:37:17 +00004112 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5cbd37e2009-08-06 09:18:59 +00004113 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Stephen Hines36b56882014-04-23 16:57:46 -07004114 unsigned BitSize = VT.getScalarSizeInBits();
Dan Gohman5cbd37e2009-08-06 09:18:59 +00004115 SDValue HiBitsMask =
Stephen Hines36b56882014-04-23 16:57:46 -07004116 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4117 BitSize - N1C->getZExtValue()), VT);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004118 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5cbd37e2009-08-06 09:18:59 +00004119 HiBitsMask);
4120 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004121
Evan Chenge5b51ac2010-04-17 06:13:15 +00004122 if (N1C) {
Stephen Hines36b56882014-04-23 16:57:46 -07004123 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chenge5b51ac2010-04-17 06:13:15 +00004124 if (NewSHL.getNode())
4125 return NewSHL;
4126 }
4127
Evan Chengb3a3d5e2010-04-28 07:10:39 +00004128 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00004129}
4130
Dan Gohman475871a2008-07-27 21:46:04 +00004131SDValue DAGCombiner::visitSRA(SDNode *N) {
4132 SDValue N0 = N->getOperand(0);
4133 SDValue N1 = N->getOperand(1);
Nate Begeman646d7e22005-09-02 21:18:40 +00004134 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4135 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00004136 EVT VT = N0.getValueType();
Dan Gohman87862e72009-12-11 21:31:27 +00004137 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelfdc40a02009-02-17 22:15:04 +00004138
Daniel Sanders028e4d22013-11-11 17:23:41 +00004139 // fold vector ops
4140 if (VT.isVector()) {
4141 SDValue FoldedVOp = SimplifyVBinOp(N);
4142 if (FoldedVOp.getNode()) return FoldedVOp;
Stephen Hines36b56882014-04-23 16:57:46 -07004143
4144 N1C = isConstOrConstSplat(N1);
Daniel Sanders028e4d22013-11-11 17:23:41 +00004145 }
4146
Bill Wendling88103372009-01-30 21:37:17 +00004147 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman646d7e22005-09-02 21:18:40 +00004148 if (N0C && N1C)
Bill Wendlingf3cbca22008-09-24 10:25:02 +00004149 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman1d4d4142005-09-01 00:19:25 +00004150 // fold (sra 0, x) -> 0
Nate Begeman646d7e22005-09-02 21:18:40 +00004151 if (N0C && N0C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00004152 return N0;
Nate Begeman1d4d4142005-09-01 00:19:25 +00004153 // fold (sra -1, x) -> -1
Nate Begeman646d7e22005-09-02 21:18:40 +00004154 if (N0C && N0C->isAllOnesValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00004155 return N0;
Bill Wendling88103372009-01-30 21:37:17 +00004156 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman87862e72009-12-11 21:31:27 +00004157 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesene8d72302009-02-06 23:05:02 +00004158 return DAG.getUNDEF(VT);
Nate Begeman1d4d4142005-09-01 00:19:25 +00004159 // fold (sra x, 0) -> x
Nate Begeman646d7e22005-09-02 21:18:40 +00004160 if (N1C && N1C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00004161 return N0;
Nate Begemanfb7217b2006-02-17 19:54:08 +00004162 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4163 // sext_inreg.
4164 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman87862e72009-12-11 21:31:27 +00004165 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohmand1996362010-01-09 02:13:55 +00004166 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4167 if (VT.isVector())
4168 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4169 ExtVT, VT.getVectorNumElements());
4170 if ((!LegalOperations ||
4171 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004172 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohmand1996362010-01-09 02:13:55 +00004173 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb7217b2006-02-17 19:54:08 +00004174 }
Duncan Sandsd4b9c172008-06-13 19:07:40 +00004175
Bill Wendling88103372009-01-30 21:37:17 +00004176 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner71d9ebc2006-02-28 06:23:04 +00004177 if (N1C && N0.getOpcode() == ISD::SRA) {
Stephen Hines36b56882014-04-23 16:57:46 -07004178 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00004179 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Stephen Hines36b56882014-04-23 16:57:46 -07004180 if (Sum >= OpSizeInBits)
4181 Sum = OpSizeInBits - 1;
Andrew Trickac6d9be2013-05-25 02:42:55 +00004182 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Stephen Hines36b56882014-04-23 16:57:46 -07004183 DAG.getConstant(Sum, N1.getValueType()));
Chris Lattner71d9ebc2006-02-28 06:23:04 +00004184 }
4185 }
Christopher Lamb15cbde32008-03-19 08:30:06 +00004186
Bill Wendling88103372009-01-30 21:37:17 +00004187 // fold (sra (shl X, m), (sub result_size, n))
4188 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelfdc40a02009-02-17 22:15:04 +00004189 // result_size - n != m.
4190 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lambb9b04282008-03-20 04:31:39 +00004191 // code.
Stephen Hines36b56882014-04-23 16:57:46 -07004192 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb15cbde32008-03-19 08:30:06 +00004193 // Get the two constanst of the shifts, CN0 = m, CN = n.
Stephen Hines36b56882014-04-23 16:57:46 -07004194 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4195 if (N01C) {
4196 LLVMContext &Ctx = *DAG.getContext();
Christopher Lambb9b04282008-03-20 04:31:39 +00004197 // Determine what the truncate's result bitsize and type would be.
Stephen Hines36b56882014-04-23 16:57:46 -07004198 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4199
4200 if (VT.isVector())
4201 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4202
Christopher Lambb9b04282008-03-20 04:31:39 +00004203 // Determine the residual right-shift amount.
Torok Edwin6bb49582009-05-23 17:29:48 +00004204 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sandsd4b9c172008-06-13 19:07:40 +00004205
Scott Michelfdc40a02009-02-17 22:15:04 +00004206 // If the shift is not a no-op (in which case this should be just a sign
4207 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohmanf451cb82010-02-10 16:03:48 +00004208 // on that type, and the truncate to that type is both legal and free,
Christopher Lambb9b04282008-03-20 04:31:39 +00004209 // perform the transform.
Torok Edwin6bb49582009-05-23 17:29:48 +00004210 if ((ShiftAmt > 0) &&
Dan Gohmanf560ffa2009-01-28 17:46:25 +00004211 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4212 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng260e07e2008-03-20 02:18:41 +00004213 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lambb9b04282008-03-20 04:31:39 +00004214
Owen Anderson95771af2011-02-25 21:41:48 +00004215 SDValue Amt = DAG.getConstant(ShiftAmt,
4216 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickac6d9be2013-05-25 02:42:55 +00004217 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendling88103372009-01-30 21:37:17 +00004218 N0.getOperand(0), Amt);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004219 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendling88103372009-01-30 21:37:17 +00004220 Shift);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004221 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendling88103372009-01-30 21:37:17 +00004222 N->getValueType(0), Trunc);
Christopher Lamb15cbde32008-03-19 08:30:06 +00004223 }
4224 }
4225 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004226
Duncan Sandsb0d5cdd2009-02-01 18:06:53 +00004227 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengeb9f8922008-08-30 02:03:58 +00004228 if (N1.getOpcode() == ISD::TRUNCATE &&
Stephen Hines36b56882014-04-23 16:57:46 -07004229 N1.getOperand(0).getOpcode() == ISD::AND) {
4230 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4231 if (NewOp1.getNode())
4232 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengeb9f8922008-08-30 02:03:58 +00004233 }
4234
Stephen Hines36b56882014-04-23 16:57:46 -07004235 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer9b108a32011-01-30 16:38:43 +00004236 // if c1 is equal to the number of bits the trunc removes
4237 if (N0.getOpcode() == ISD::TRUNCATE &&
4238 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4239 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4240 N0.getOperand(0).hasOneUse() &&
4241 N0.getOperand(0).getOperand(1).hasOneUse() &&
Stephen Hines36b56882014-04-23 16:57:46 -07004242 N1C) {
4243 SDValue N0Op0 = N0.getOperand(0);
4244 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4245 unsigned LargeShiftVal = LargeShift->getZExtValue();
4246 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer9b108a32011-01-30 16:38:43 +00004247
Stephen Hines36b56882014-04-23 16:57:46 -07004248 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4249 SDValue Amt =
4250 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4251 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4252 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4253 N0Op0.getOperand(0), Amt);
4254 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4255 }
Benjamin Kramer9b108a32011-01-30 16:38:43 +00004256 }
4257 }
4258
Scott Michelfdc40a02009-02-17 22:15:04 +00004259 // Simplify, based on bits shifted out of the LHS.
Dan Gohman475871a2008-07-27 21:46:04 +00004260 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4261 return SDValue(N, 0);
Scott Michelfdc40a02009-02-17 22:15:04 +00004262
4263
Nate Begeman1d4d4142005-09-01 00:19:25 +00004264 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00004265 if (DAG.SignBitIsZero(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004266 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattnere70da202007-12-06 07:33:36 +00004267
Evan Chenge5b51ac2010-04-17 06:13:15 +00004268 if (N1C) {
Stephen Hines36b56882014-04-23 16:57:46 -07004269 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chenge5b51ac2010-04-17 06:13:15 +00004270 if (NewSRA.getNode())
4271 return NewSRA;
4272 }
4273
Evan Chengb3a3d5e2010-04-28 07:10:39 +00004274 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00004275}
4276
Dan Gohman475871a2008-07-27 21:46:04 +00004277SDValue DAGCombiner::visitSRL(SDNode *N) {
4278 SDValue N0 = N->getOperand(0);
4279 SDValue N1 = N->getOperand(1);
Nate Begeman646d7e22005-09-02 21:18:40 +00004280 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4281 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00004282 EVT VT = N0.getValueType();
Dan Gohman87862e72009-12-11 21:31:27 +00004283 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelfdc40a02009-02-17 22:15:04 +00004284
Daniel Sanders028e4d22013-11-11 17:23:41 +00004285 // fold vector ops
4286 if (VT.isVector()) {
4287 SDValue FoldedVOp = SimplifyVBinOp(N);
4288 if (FoldedVOp.getNode()) return FoldedVOp;
Stephen Hines36b56882014-04-23 16:57:46 -07004289
4290 N1C = isConstOrConstSplat(N1);
Daniel Sanders028e4d22013-11-11 17:23:41 +00004291 }
4292
Nate Begeman1d4d4142005-09-01 00:19:25 +00004293 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman646d7e22005-09-02 21:18:40 +00004294 if (N0C && N1C)
Bill Wendlingf3cbca22008-09-24 10:25:02 +00004295 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman1d4d4142005-09-01 00:19:25 +00004296 // fold (srl 0, x) -> 0
Nate Begeman646d7e22005-09-02 21:18:40 +00004297 if (N0C && N0C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00004298 return N0;
Nate Begeman1d4d4142005-09-01 00:19:25 +00004299 // fold (srl x, c >= size(x)) -> undef
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00004300 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesene8d72302009-02-06 23:05:02 +00004301 return DAG.getUNDEF(VT);
Nate Begeman1d4d4142005-09-01 00:19:25 +00004302 // fold (srl x, 0) -> x
Nate Begeman646d7e22005-09-02 21:18:40 +00004303 if (N1C && N1C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00004304 return N0;
Nate Begeman1d4d4142005-09-01 00:19:25 +00004305 // if (srl x, c) is known to be zero, return 0
Dan Gohman475871a2008-07-27 21:46:04 +00004306 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman2e68b6f2008-02-25 21:11:39 +00004307 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begeman83e75ec2005-09-06 04:43:02 +00004308 return DAG.getConstant(0, VT);
Scott Michelfdc40a02009-02-17 22:15:04 +00004309
Bill Wendling88103372009-01-30 21:37:17 +00004310 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Stephen Hines36b56882014-04-23 16:57:46 -07004311 if (N1C && N0.getOpcode() == ISD::SRL) {
4312 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4313 uint64_t c1 = N01C->getZExtValue();
4314 uint64_t c2 = N1C->getZExtValue();
4315 if (c1 + c2 >= OpSizeInBits)
4316 return DAG.getConstant(0, VT);
4317 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4318 DAG.getConstant(c1 + c2, N1.getValueType()));
4319 }
Nate Begeman1d4d4142005-09-01 00:19:25 +00004320 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004321
Dale Johannesenf5daf8b2010-12-17 21:45:49 +00004322 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesenf5daf8b2010-12-17 21:45:49 +00004323 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4324 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen025cc6e2010-12-20 20:10:50 +00004325 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Anderson95771af2011-02-25 21:41:48 +00004326 uint64_t c1 =
Dale Johannesenf5daf8b2010-12-17 21:45:49 +00004327 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4328 uint64_t c2 = N1C->getZExtValue();
Dale Johannesenc72b18c2010-12-21 21:55:50 +00004329 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4330 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesenf5daf8b2010-12-17 21:45:49 +00004331 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen025cc6e2010-12-20 20:10:50 +00004332 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesenf5daf8b2010-12-17 21:45:49 +00004333 if (c1 + OpSizeInBits == InnerShiftSize) {
4334 if (c1 + c2 >= InnerShiftSize)
4335 return DAG.getConstant(0, VT);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004336 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4337 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesenf5daf8b2010-12-17 21:45:49 +00004338 N0.getOperand(0)->getOperand(0),
Dale Johannesenc72b18c2010-12-21 21:55:50 +00004339 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesenf5daf8b2010-12-17 21:45:49 +00004340 }
4341 }
4342
Chris Lattnerefcddc32010-04-15 05:28:43 +00004343 // fold (srl (shl x, c), c) -> (and x, cst2)
Stephen Hines36b56882014-04-23 16:57:46 -07004344 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4345 unsigned BitSize = N0.getScalarValueSizeInBits();
4346 if (BitSize <= 64) {
4347 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4348 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4349 DAG.getConstant(~0ULL >> ShAmt, VT));
4350 }
Chris Lattnerefcddc32010-04-15 05:28:43 +00004351 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004352
Michael Liao2da86392013-06-21 18:45:27 +00004353 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner06afe072006-05-05 22:53:17 +00004354 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4355 // Shifting in all undef bits?
Owen Andersone50ed302009-08-10 22:56:29 +00004356 EVT SmallVT = N0.getOperand(0).getValueType();
Stephen Hines36b56882014-04-23 16:57:46 -07004357 unsigned BitSize = SmallVT.getScalarSizeInBits();
4358 if (N1C->getZExtValue() >= BitSize)
Dale Johannesene8d72302009-02-06 23:05:02 +00004359 return DAG.getUNDEF(VT);
Chris Lattner06afe072006-05-05 22:53:17 +00004360
Evan Chenge5b51ac2010-04-17 06:13:15 +00004361 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona34d9362011-04-14 17:30:49 +00004362 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickac6d9be2013-05-25 02:42:55 +00004363 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona34d9362011-04-14 17:30:49 +00004364 N0.getOperand(0),
4365 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Evan Chenge5b51ac2010-04-17 06:13:15 +00004366 AddToWorkList(SmallShift.getNode());
Stephen Hines36b56882014-04-23 16:57:46 -07004367 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Michael Liao2da86392013-06-21 18:45:27 +00004368 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4369 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4370 DAG.getConstant(Mask, VT));
Evan Chenge5b51ac2010-04-17 06:13:15 +00004371 }
Chris Lattner06afe072006-05-05 22:53:17 +00004372 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004373
Chris Lattner3657ffe2006-10-12 20:23:19 +00004374 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4375 // bit, which is unmodified by sra.
Stephen Hines36b56882014-04-23 16:57:46 -07004376 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner3657ffe2006-10-12 20:23:19 +00004377 if (N0.getOpcode() == ISD::SRA)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004378 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner3657ffe2006-10-12 20:23:19 +00004379 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004380
Sylvestre Ledru94c22712012-09-27 10:14:43 +00004381 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelfdc40a02009-02-17 22:15:04 +00004382 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Stephen Hines36b56882014-04-23 16:57:46 -07004383 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohman948d8ea2008-02-20 16:33:30 +00004384 APInt KnownZero, KnownOne;
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00004385 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelfdc40a02009-02-17 22:15:04 +00004386
Chris Lattner350bec02006-04-02 06:11:11 +00004387 // If any of the input bits are KnownOne, then the input couldn't be all
4388 // zeros, thus the result of the srl will always be zero.
Dan Gohman948d8ea2008-02-20 16:33:30 +00004389 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelfdc40a02009-02-17 22:15:04 +00004390
Chris Lattner350bec02006-04-02 06:11:11 +00004391 // If all of the bits input the to ctlz node are known to be zero, then
4392 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00004393 APInt UnknownBits = ~KnownZero;
Chris Lattner350bec02006-04-02 06:11:11 +00004394 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelfdc40a02009-02-17 22:15:04 +00004395
Chris Lattner350bec02006-04-02 06:11:11 +00004396 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendling88103372009-01-30 21:37:17 +00004397 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner350bec02006-04-02 06:11:11 +00004398 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendling88103372009-01-30 21:37:17 +00004399 // could be set on input to the CTLZ node. If this bit is set, the SRL
4400 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4401 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohman948d8ea2008-02-20 16:33:30 +00004402 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman475871a2008-07-27 21:46:04 +00004403 SDValue Op = N0.getOperand(0);
Bill Wendling88103372009-01-30 21:37:17 +00004404
Chris Lattner350bec02006-04-02 06:11:11 +00004405 if (ShAmt) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00004406 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Anderson95771af2011-02-25 21:41:48 +00004407 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Gabor Greifba36cb52008-08-28 21:40:38 +00004408 AddToWorkList(Op.getNode());
Chris Lattner350bec02006-04-02 06:11:11 +00004409 }
Bill Wendling88103372009-01-30 21:37:17 +00004410
Andrew Trickac6d9be2013-05-25 02:42:55 +00004411 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling88103372009-01-30 21:37:17 +00004412 Op, DAG.getConstant(1, VT));
Chris Lattner350bec02006-04-02 06:11:11 +00004413 }
4414 }
Evan Chengeb9f8922008-08-30 02:03:58 +00004415
Duncan Sandsb0d5cdd2009-02-01 18:06:53 +00004416 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengeb9f8922008-08-30 02:03:58 +00004417 if (N1.getOpcode() == ISD::TRUNCATE &&
Stephen Hines36b56882014-04-23 16:57:46 -07004418 N1.getOperand(0).getOpcode() == ISD::AND) {
4419 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4420 if (NewOp1.getNode())
4421 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengeb9f8922008-08-30 02:03:58 +00004422 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004423
Chris Lattner61a4c072007-04-18 03:06:49 +00004424 // fold operands of srl based on knowledge that the low bits are not
4425 // demanded.
Dan Gohman475871a2008-07-27 21:46:04 +00004426 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4427 return SDValue(N, 0);
Scott Michelfdc40a02009-02-17 22:15:04 +00004428
Evan Cheng9ab2b982009-12-18 21:31:31 +00004429 if (N1C) {
Stephen Hines36b56882014-04-23 16:57:46 -07004430 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Cheng9ab2b982009-12-18 21:31:31 +00004431 if (NewSRL.getNode())
4432 return NewSRL;
4433 }
4434
Dan Gohman4e39e9d2010-06-24 14:30:44 +00004435 // Attempt to convert a srl of a load into a narrower zero-extending load.
4436 SDValue NarrowLoad = ReduceLoadWidth(N);
4437 if (NarrowLoad.getNode())
4438 return NarrowLoad;
4439
Evan Cheng9ab2b982009-12-18 21:31:31 +00004440 // Here is a common situation. We want to optimize:
4441 //
4442 // %a = ...
4443 // %b = and i32 %a, 2
4444 // %c = srl i32 %b, 1
4445 // brcond i32 %c ...
4446 //
4447 // into
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004448 //
Evan Cheng9ab2b982009-12-18 21:31:31 +00004449 // %a = ...
4450 // %b = and %a, 2
4451 // %c = setcc eq %b, 0
4452 // brcond %c ...
4453 //
4454 // However when after the source operand of SRL is optimized into AND, the SRL
4455 // itself may not be optimized further. Look for it and add the BRCOND into
4456 // the worklist.
Evan Chengd40d03e2010-01-06 19:38:29 +00004457 if (N->hasOneUse()) {
4458 SDNode *Use = *N->use_begin();
4459 if (Use->getOpcode() == ISD::BRCOND)
4460 AddToWorkList(Use);
4461 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4462 // Also look pass the truncate.
4463 Use = *Use->use_begin();
4464 if (Use->getOpcode() == ISD::BRCOND)
4465 AddToWorkList(Use);
4466 }
4467 }
Evan Cheng9ab2b982009-12-18 21:31:31 +00004468
Evan Chengb3a3d5e2010-04-28 07:10:39 +00004469 return SDValue();
Evan Cheng4c26e932010-04-19 19:29:22 +00004470}
4471
Dan Gohman475871a2008-07-27 21:46:04 +00004472SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4473 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00004474 EVT VT = N->getValueType(0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00004475
4476 // fold (ctlz c1) -> c2
Chris Lattner310b5782006-05-06 23:06:26 +00004477 if (isa<ConstantSDNode>(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004478 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman475871a2008-07-27 21:46:04 +00004479 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00004480}
4481
Chandler Carruth63974b22011-12-13 01:56:10 +00004482SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4483 SDValue N0 = N->getOperand(0);
4484 EVT VT = N->getValueType(0);
4485
4486 // fold (ctlz_zero_undef c1) -> c2
4487 if (isa<ConstantSDNode>(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004488 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth63974b22011-12-13 01:56:10 +00004489 return SDValue();
4490}
4491
Dan Gohman475871a2008-07-27 21:46:04 +00004492SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4493 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00004494 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00004495
Nate Begeman1d4d4142005-09-01 00:19:25 +00004496 // fold (cttz c1) -> c2
Chris Lattner310b5782006-05-06 23:06:26 +00004497 if (isa<ConstantSDNode>(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004498 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman475871a2008-07-27 21:46:04 +00004499 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00004500}
4501
Chandler Carruth63974b22011-12-13 01:56:10 +00004502SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4503 SDValue N0 = N->getOperand(0);
4504 EVT VT = N->getValueType(0);
4505
4506 // fold (cttz_zero_undef c1) -> c2
4507 if (isa<ConstantSDNode>(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004508 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth63974b22011-12-13 01:56:10 +00004509 return SDValue();
4510}
4511
Dan Gohman475871a2008-07-27 21:46:04 +00004512SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4513 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00004514 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00004515
Nate Begeman1d4d4142005-09-01 00:19:25 +00004516 // fold (ctpop c1) -> c2
Chris Lattner310b5782006-05-06 23:06:26 +00004517 if (isa<ConstantSDNode>(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004518 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman475871a2008-07-27 21:46:04 +00004519 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00004520}
4521
Dan Gohman475871a2008-07-27 21:46:04 +00004522SDValue DAGCombiner::visitSELECT(SDNode *N) {
4523 SDValue N0 = N->getOperand(0);
4524 SDValue N1 = N->getOperand(1);
4525 SDValue N2 = N->getOperand(2);
Nate Begeman452d7be2005-09-16 00:54:12 +00004526 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4527 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4528 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Andersone50ed302009-08-10 22:56:29 +00004529 EVT VT = N->getValueType(0);
4530 EVT VT0 = N0.getValueType();
Nate Begeman44728a72005-09-19 22:34:01 +00004531
Bill Wendling34584e62009-01-30 22:02:18 +00004532 // fold (select C, X, X) -> X
Nate Begeman452d7be2005-09-16 00:54:12 +00004533 if (N1 == N2)
4534 return N1;
Bill Wendling34584e62009-01-30 22:02:18 +00004535 // fold (select true, X, Y) -> X
Nate Begeman452d7be2005-09-16 00:54:12 +00004536 if (N0C && !N0C->isNullValue())
4537 return N1;
Bill Wendling34584e62009-01-30 22:02:18 +00004538 // fold (select false, X, Y) -> Y
Nate Begeman452d7be2005-09-16 00:54:12 +00004539 if (N0C && N0C->isNullValue())
4540 return N2;
Bill Wendling34584e62009-01-30 22:02:18 +00004541 // fold (select C, 1, X) -> (or C, X)
Owen Anderson825b72b2009-08-11 20:47:22 +00004542 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004543 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendling34584e62009-01-30 22:02:18 +00004544 // fold (select C, 0, 1) -> (xor C, 1)
Bob Wilson67ba2232009-01-22 22:05:48 +00004545 if (VT.isInteger() &&
Owen Anderson825b72b2009-08-11 20:47:22 +00004546 (VT0 == MVT::i1 ||
Bob Wilson67ba2232009-01-22 22:05:48 +00004547 (VT0.isInteger() &&
Nadav Rotem6dfabb62012-09-20 08:53:31 +00004548 TLI.getBooleanContents(false) ==
4549 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohman002e5d02008-03-13 22:13:53 +00004550 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendling34584e62009-01-30 22:02:18 +00004551 SDValue XORNode;
Evan Cheng571c4782007-08-18 05:57:05 +00004552 if (VT == VT0)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004553 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendling34584e62009-01-30 22:02:18 +00004554 N0, DAG.getConstant(1, VT0));
Andrew Trickac6d9be2013-05-25 02:42:55 +00004555 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendling34584e62009-01-30 22:02:18 +00004556 N0, DAG.getConstant(1, VT0));
Gabor Greifba36cb52008-08-28 21:40:38 +00004557 AddToWorkList(XORNode.getNode());
Duncan Sands8e4eb092008-06-08 20:54:56 +00004558 if (VT.bitsGT(VT0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004559 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4560 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Cheng571c4782007-08-18 05:57:05 +00004561 }
Bill Wendling34584e62009-01-30 22:02:18 +00004562 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson825b72b2009-08-11 20:47:22 +00004563 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00004564 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilson4c245462009-01-22 17:39:32 +00004565 AddToWorkList(NOTNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00004566 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman452d7be2005-09-16 00:54:12 +00004567 }
Bill Wendling34584e62009-01-30 22:02:18 +00004568 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson825b72b2009-08-11 20:47:22 +00004569 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00004570 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilson4c245462009-01-22 17:39:32 +00004571 AddToWorkList(NOTNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00004572 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman452d7be2005-09-16 00:54:12 +00004573 }
Bill Wendling34584e62009-01-30 22:02:18 +00004574 // fold (select C, X, 0) -> (and C, X)
Owen Anderson825b72b2009-08-11 20:47:22 +00004575 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickac6d9be2013-05-25 02:42:55 +00004576 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendling34584e62009-01-30 22:02:18 +00004577 // fold (select X, X, Y) -> (or X, Y)
4578 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson825b72b2009-08-11 20:47:22 +00004579 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004580 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendling34584e62009-01-30 22:02:18 +00004581 // fold (select X, Y, X) -> (and X, Y)
4582 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson825b72b2009-08-11 20:47:22 +00004583 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004584 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelfdc40a02009-02-17 22:15:04 +00004585
Chris Lattner40c62d52005-10-18 06:04:22 +00004586 // If we can fold this based on the true/false value, do so.
4587 if (SimplifySelectOps(N, N1, N2))
Dan Gohman475871a2008-07-27 21:46:04 +00004588 return SDValue(N, 0); // Don't revisit N.
Duncan Sandsd4b9c172008-06-13 19:07:40 +00004589
Nate Begeman44728a72005-09-19 22:34:01 +00004590 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00004591 if (N0.getOpcode() == ISD::SETCC) {
Nate Begeman750ac1b2006-02-01 07:19:44 +00004592 // FIXME:
Owen Anderson825b72b2009-08-11 20:47:22 +00004593 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
Nate Begeman750ac1b2006-02-01 07:19:44 +00004594 // having to say they don't support SELECT_CC on every type the DAG knows
4595 // about, since there is no way to mark an opcode illegal at all value types
Owen Anderson825b72b2009-08-11 20:47:22 +00004596 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
Dan Gohman4ea48042009-08-02 16:19:38 +00004597 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004598 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendling34584e62009-01-30 22:02:18 +00004599 N0.getOperand(0), N0.getOperand(1),
Nate Begeman750ac1b2006-02-01 07:19:44 +00004600 N1, N2, N0.getOperand(2));
Andrew Trickac6d9be2013-05-25 02:42:55 +00004601 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00004602 }
Bill Wendling34584e62009-01-30 22:02:18 +00004603
Dan Gohman475871a2008-07-27 21:46:04 +00004604 return SDValue();
Nate Begeman452d7be2005-09-16 00:54:12 +00004605}
4606
Bill Wendlingf62b2742013-11-22 05:18:07 +00004607static
4608std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4609 SDLoc DL(N);
4610 EVT LoVT, HiVT;
Stephen Hines36b56882014-04-23 16:57:46 -07004611 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Bill Wendlingf62b2742013-11-22 05:18:07 +00004612
4613 // Split the inputs.
4614 SDValue Lo, Hi, LL, LH, RL, RH;
Stephen Hines36b56882014-04-23 16:57:46 -07004615 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4616 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Bill Wendlingf62b2742013-11-22 05:18:07 +00004617
4618 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4619 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4620
4621 return std::make_pair(Lo, Hi);
4622}
4623
Benjamin Kramer6242fda2013-04-26 09:19:19 +00004624SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4625 SDValue N0 = N->getOperand(0);
4626 SDValue N1 = N->getOperand(1);
4627 SDValue N2 = N->getOperand(2);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004628 SDLoc DL(N);
Benjamin Kramer6242fda2013-04-26 09:19:19 +00004629
4630 // Canonicalize integer abs.
4631 // vselect (setg[te] X, 0), X, -X ->
4632 // vselect (setgt X, -1), X, -X ->
4633 // vselect (setl[te] X, 0), -X, X ->
4634 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4635 if (N0.getOpcode() == ISD::SETCC) {
4636 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4637 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4638 bool isAbs = false;
4639 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4640
4641 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4642 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4643 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4644 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4645 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4646 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4647 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4648
4649 if (isAbs) {
4650 EVT VT = LHS.getValueType();
4651 SDValue Shift = DAG.getNode(
4652 ISD::SRA, DL, VT, LHS,
4653 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4654 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4655 AddToWorkList(Shift.getNode());
4656 AddToWorkList(Add.getNode());
4657 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4658 }
4659 }
4660
Bill Wendlingf62b2742013-11-22 05:18:07 +00004661 // If the VSELECT result requires splitting and the mask is provided by a
4662 // SETCC, then split both nodes and its operands before legalization. This
4663 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4664 // and enables future optimizations (e.g. min/max pattern matching on X86).
4665 if (N0.getOpcode() == ISD::SETCC) {
4666 EVT VT = N->getValueType(0);
Juergen Ributzkac7e77f92013-11-13 01:57:54 +00004667
Bill Wendlingf62b2742013-11-22 05:18:07 +00004668 // Check if any splitting is required.
4669 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4670 TargetLowering::TypeSplitVector)
4671 return SDValue();
Juergen Ributzkac7e77f92013-11-13 01:57:54 +00004672
Bill Wendlingf62b2742013-11-22 05:18:07 +00004673 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Stephen Hines36b56882014-04-23 16:57:46 -07004674 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4675 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4676 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzkac7e77f92013-11-13 01:57:54 +00004677
Bill Wendlingf62b2742013-11-22 05:18:07 +00004678 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4679 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzkac7e77f92013-11-13 01:57:54 +00004680
Bill Wendlingf62b2742013-11-22 05:18:07 +00004681 // Add the new VSELECT nodes to the work list in case they need to be split
4682 // again.
4683 AddToWorkList(Lo.getNode());
4684 AddToWorkList(Hi.getNode());
4685
4686 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzkac7e77f92013-11-13 01:57:54 +00004687 }
4688
Stephen Hines36b56882014-04-23 16:57:46 -07004689 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4690 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4691 return N1;
4692 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4693 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4694 return N2;
4695
Benjamin Kramer6242fda2013-04-26 09:19:19 +00004696 return SDValue();
4697}
4698
Dan Gohman475871a2008-07-27 21:46:04 +00004699SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4700 SDValue N0 = N->getOperand(0);
4701 SDValue N1 = N->getOperand(1);
4702 SDValue N2 = N->getOperand(2);
4703 SDValue N3 = N->getOperand(3);
4704 SDValue N4 = N->getOperand(4);
Nate Begeman44728a72005-09-19 22:34:01 +00004705 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelfdc40a02009-02-17 22:15:04 +00004706
Nate Begeman44728a72005-09-19 22:34:01 +00004707 // fold select_cc lhs, rhs, x, x, cc -> x
4708 if (N2 == N3)
4709 return N2;
Scott Michelfdc40a02009-02-17 22:15:04 +00004710
Chris Lattner5f42a242006-09-20 06:19:26 +00004711 // Determine if the condition we're dealing with is constant
Matt Arsenault225ed702013-05-18 00:21:46 +00004712 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickac6d9be2013-05-25 02:42:55 +00004713 N0, N1, CC, SDLoc(N), false);
Stephen Lin7e6d6202013-06-15 04:03:33 +00004714 if (SCC.getNode()) {
4715 AddToWorkList(SCC.getNode());
Chris Lattner5f42a242006-09-20 06:19:26 +00004716
Stephen Lin7e6d6202013-06-15 04:03:33 +00004717 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4718 if (!SCCC->isNullValue())
4719 return N2; // cond always true -> true val
4720 else
4721 return N3; // cond always false -> false val
4722 }
4723
4724 // Fold to a simpler select_cc
4725 if (SCC.getOpcode() == ISD::SETCC)
4726 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4727 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4728 SCC.getOperand(2));
Chris Lattner5f42a242006-09-20 06:19:26 +00004729 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004730
Chris Lattner40c62d52005-10-18 06:04:22 +00004731 // If we can fold this based on the true/false value, do so.
4732 if (SimplifySelectOps(N, N2, N3))
Dan Gohman475871a2008-07-27 21:46:04 +00004733 return SDValue(N, 0); // Don't revisit N.
Scott Michelfdc40a02009-02-17 22:15:04 +00004734
Nate Begeman44728a72005-09-19 22:34:01 +00004735 // fold select_cc into other things, such as min/max/abs
Andrew Trickac6d9be2013-05-25 02:42:55 +00004736 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman452d7be2005-09-16 00:54:12 +00004737}
4738
Dan Gohman475871a2008-07-27 21:46:04 +00004739SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman452d7be2005-09-16 00:54:12 +00004740 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenff97d4f2009-02-03 00:47:48 +00004741 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickac6d9be2013-05-25 02:42:55 +00004742 SDLoc(N));
Nate Begeman452d7be2005-09-16 00:54:12 +00004743}
4744
Stephen Hines36b56882014-04-23 16:57:46 -07004745// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4746// dag node into a ConstantSDNode or a build_vector of constants.
4747// This function is called by the DAGCombiner when visiting sext/zext/aext
4748// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4749// Vector extends are not folded if operations are legal; this is to
4750// avoid introducing illegal build_vector dag nodes.
4751static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4752 SelectionDAG &DAG, bool LegalTypes,
4753 bool LegalOperations) {
4754 unsigned Opcode = N->getOpcode();
4755 SDValue N0 = N->getOperand(0);
4756 EVT VT = N->getValueType(0);
4757
4758 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4759 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4760
4761 // fold (sext c1) -> c1
4762 // fold (zext c1) -> c1
4763 // fold (aext c1) -> c1
4764 if (isa<ConstantSDNode>(N0))
4765 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4766
4767 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4768 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4769 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4770 EVT SVT = VT.getScalarType();
4771 if (!(VT.isVector() &&
4772 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4773 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4774 return 0;
4775
4776 // We can fold this node into a build_vector.
4777 unsigned VTBits = SVT.getSizeInBits();
4778 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4779 unsigned ShAmt = VTBits - EVTBits;
4780 SmallVector<SDValue, 8> Elts;
4781 unsigned NumElts = N0->getNumOperands();
4782 SDLoc DL(N);
4783
4784 for (unsigned i=0; i != NumElts; ++i) {
4785 SDValue Op = N0->getOperand(i);
4786 if (Op->getOpcode() == ISD::UNDEF) {
4787 Elts.push_back(DAG.getUNDEF(SVT));
4788 continue;
4789 }
4790
4791 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4792 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4793 if (Opcode == ISD::SIGN_EXTEND)
4794 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4795 SVT));
4796 else
4797 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4798 SVT));
4799 }
4800
4801 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode();
4802}
4803
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004804// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman57fc82d2009-04-09 03:51:29 +00004805// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004806// transformation. Returns true if extension are possible and the above
Scott Michelfdc40a02009-02-17 22:15:04 +00004807// mentioned transformation is profitable.
Dan Gohman475871a2008-07-27 21:46:04 +00004808static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004809 unsigned ExtOpc,
Craig Toppera0ec3f92013-07-14 04:42:23 +00004810 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman79ce2762009-01-15 19:20:50 +00004811 const TargetLowering &TLI) {
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004812 bool HasCopyToRegUses = false;
4813 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greif12632d22008-08-30 19:29:20 +00004814 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4815 UE = N0.getNode()->use_end();
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004816 UI != UE; ++UI) {
Dan Gohman89684502008-07-27 20:43:25 +00004817 SDNode *User = *UI;
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004818 if (User == N)
4819 continue;
Dan Gohman57fc82d2009-04-09 03:51:29 +00004820 if (UI.getUse().getResNo() != N0.getResNo())
4821 continue;
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004822 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman57fc82d2009-04-09 03:51:29 +00004823 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004824 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4825 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4826 // Sign bits will be lost after a zext.
4827 return false;
4828 bool Add = false;
4829 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00004830 SDValue UseOp = User->getOperand(i);
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004831 if (UseOp == N0)
4832 continue;
4833 if (!isa<ConstantSDNode>(UseOp))
4834 return false;
4835 Add = true;
4836 }
4837 if (Add)
4838 ExtendNodes.push_back(User);
Dan Gohman57fc82d2009-04-09 03:51:29 +00004839 continue;
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004840 }
Dan Gohman57fc82d2009-04-09 03:51:29 +00004841 // If truncates aren't free and there are users we can't
4842 // extend, it isn't worthwhile.
4843 if (!isTruncFree)
4844 return false;
4845 // Remember if this value is live-out.
4846 if (User->getOpcode() == ISD::CopyToReg)
4847 HasCopyToRegUses = true;
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004848 }
4849
4850 if (HasCopyToRegUses) {
4851 bool BothLiveOut = false;
4852 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4853 UI != UE; ++UI) {
Dan Gohman57fc82d2009-04-09 03:51:29 +00004854 SDUse &Use = UI.getUse();
4855 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4856 BothLiveOut = true;
4857 break;
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004858 }
4859 }
4860 if (BothLiveOut)
4861 // Both unextended and extended values are live out. There had better be
Bob Wilsonbebfbc52010-11-28 06:51:19 +00004862 // a good reason for the transformation.
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004863 return ExtendNodes.size();
4864 }
4865 return true;
4866}
4867
Craig Topper6c64fba2013-07-13 07:43:40 +00004868void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickac6d9be2013-05-25 02:42:55 +00004869 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004870 ISD::NodeType ExtType) {
4871 // Extend SetCC uses if necessary.
4872 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4873 SDNode *SetCC = SetCCs[i];
4874 SmallVector<SDValue, 4> Ops;
4875
4876 for (unsigned j = 0; j != 2; ++j) {
4877 SDValue SOp = SetCC->getOperand(j);
4878 if (SOp == Trunc)
4879 Ops.push_back(ExtLoad);
4880 else
4881 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4882 }
4883
4884 Ops.push_back(SetCC->getOperand(2));
4885 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4886 &Ops[0], Ops.size()));
4887 }
4888}
4889
Dan Gohman475871a2008-07-27 21:46:04 +00004890SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4891 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00004892 EVT VT = N->getValueType(0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00004893
Stephen Hines36b56882014-04-23 16:57:46 -07004894 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4895 LegalOperations))
4896 return SDValue(Res, 0);
Scott Michelfdc40a02009-02-17 22:15:04 +00004897
Nadav Rotem0c8607b2013-01-20 08:35:56 +00004898 // fold (sext (sext x)) -> (sext x)
4899 // fold (sext (aext x)) -> (sext x)
4900 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004901 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem0c8607b2013-01-20 08:35:56 +00004902 N0.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00004903
Chris Lattner22558872007-02-26 03:13:59 +00004904 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman1fdfa6a2008-05-20 20:56:33 +00004905 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4906 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greifba36cb52008-08-28 21:40:38 +00004907 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4908 if (NarrowLoad.getNode()) {
Dale Johannesen61734eb2010-05-25 17:50:03 +00004909 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4910 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greifba36cb52008-08-28 21:40:38 +00004911 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen61734eb2010-05-25 17:50:03 +00004912 // CombineTo deleted the truncate, if needed, but not what's under it.
4913 AddToWorkList(oye);
4914 }
Dan Gohmanc7b34442009-04-27 02:00:55 +00004915 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng0b063de2007-03-23 02:16:52 +00004916 }
Evan Chengc88138f2007-03-22 01:54:19 +00004917
Dan Gohman1fdfa6a2008-05-20 20:56:33 +00004918 // See if the value being truncated is already sign extended. If so, just
4919 // eliminate the trunc/sext pair.
Dan Gohman475871a2008-07-27 21:46:04 +00004920 SDValue Op = N0.getOperand(0);
Dan Gohmand1996362010-01-09 02:13:55 +00004921 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4922 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4923 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohmanea859be2007-06-22 14:59:07 +00004924 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelfdc40a02009-02-17 22:15:04 +00004925
Chris Lattner22558872007-02-26 03:13:59 +00004926 if (OpBits == DestBits) {
4927 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4928 // bits, it is already ready.
4929 if (NumSignBits > DestBits-MidBits)
4930 return Op;
4931 } else if (OpBits < DestBits) {
4932 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4933 // bits, just sext from i32.
4934 if (NumSignBits > OpBits-MidBits)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004935 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattner22558872007-02-26 03:13:59 +00004936 } else {
4937 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4938 // bits, just truncate to i32.
4939 if (NumSignBits > OpBits-MidBits)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004940 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattner6007b842006-09-21 06:00:20 +00004941 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004942
Chris Lattner22558872007-02-26 03:13:59 +00004943 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sands25cf2272008-11-24 14:53:14 +00004944 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4945 N0.getValueType())) {
Dan Gohmand1996362010-01-09 02:13:55 +00004946 if (OpBits < DestBits)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004947 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohmand1996362010-01-09 02:13:55 +00004948 else if (OpBits > DestBits)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004949 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4950 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohmand1996362010-01-09 02:13:55 +00004951 DAG.getValueType(N0.getValueType()));
Chris Lattner22558872007-02-26 03:13:59 +00004952 }
Chris Lattner6007b842006-09-21 06:00:20 +00004953 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004954
Evan Cheng110dec22005-12-14 02:19:23 +00004955 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Nadav Rotem8c20ec52011-02-24 21:01:34 +00004956 // None of the supported targets knows how to perform load and sign extend
Nadav Rotemfcd96192011-02-27 07:40:43 +00004957 // on vectors in one instruction. We only perform this transformation on
4958 // scalars.
Nadav Rotem8c20ec52011-02-24 21:01:34 +00004959 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Duncan Sands25cf2272008-11-24 14:53:14 +00004960 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng03294662008-10-14 21:26:46 +00004961 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004962 bool DoXform = true;
4963 SmallVector<SDNode*, 4> SetCCs;
4964 if (!N0.hasOneUse())
4965 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4966 if (DoXform) {
4967 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004968 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman57fc82d2009-04-09 03:51:29 +00004969 LN0->getChain(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00004970 LN0->getBasePtr(), N0.getValueType(),
4971 LN0->getMemOperand());
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004972 CombineTo(N, ExtLoad);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004973 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendling6ce610f2009-01-30 22:23:15 +00004974 N0.getValueType(), ExtLoad);
Gabor Greifba36cb52008-08-28 21:40:38 +00004975 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickac6d9be2013-05-25 02:42:55 +00004976 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004977 ISD::SIGN_EXTEND);
Dan Gohman475871a2008-07-27 21:46:04 +00004978 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004979 }
Nate Begeman3df4d522005-10-12 20:40:40 +00004980 }
Chris Lattnerad25d4e2005-12-14 19:05:06 +00004981
4982 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4983 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greifba36cb52008-08-28 21:40:38 +00004984 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4985 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Cheng466685d2006-10-09 20:57:25 +00004986 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman8a55ce42009-09-23 21:02:20 +00004987 EVT MemVT = LN0->getMemoryVT();
Duncan Sands25cf2272008-11-24 14:53:14 +00004988 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman8a55ce42009-09-23 21:02:20 +00004989 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00004990 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling6ce610f2009-01-30 22:23:15 +00004991 LN0->getChain(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00004992 LN0->getBasePtr(), MemVT,
4993 LN0->getMemOperand());
Jim Laskeyf6c4ccf2006-12-15 21:38:30 +00004994 CombineTo(N, ExtLoad);
Gabor Greif12632d22008-08-30 19:29:20 +00004995 CombineTo(N0.getNode(),
Andrew Trickac6d9be2013-05-25 02:42:55 +00004996 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendling6ce610f2009-01-30 22:23:15 +00004997 N0.getValueType(), ExtLoad),
Jim Laskeyf6c4ccf2006-12-15 21:38:30 +00004998 ExtLoad.getValue(1));
Dan Gohman475871a2008-07-27 21:46:04 +00004999 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskeyf6c4ccf2006-12-15 21:38:30 +00005000 }
Chris Lattnerad25d4e2005-12-14 19:05:06 +00005001 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005002
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005003 // fold (sext (and/or/xor (load x), cst)) ->
5004 // (and/or/xor (sextload x), (sext cst))
5005 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5006 N0.getOpcode() == ISD::XOR) &&
5007 isa<LoadSDNode>(N0.getOperand(0)) &&
5008 N0.getOperand(1).getOpcode() == ISD::Constant &&
5009 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5010 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5011 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5012 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
5013 bool DoXform = true;
5014 SmallVector<SDNode*, 4> SetCCs;
5015 if (!N0.hasOneUse())
5016 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5017 SetCCs, TLI);
5018 if (DoXform) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005019 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005020 LN0->getChain(), LN0->getBasePtr(),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005021 LN0->getMemoryVT(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005022 LN0->getMemOperand());
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005023 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5024 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickac6d9be2013-05-25 02:42:55 +00005025 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005026 ExtLoad, DAG.getConstant(Mask, VT));
5027 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickac6d9be2013-05-25 02:42:55 +00005028 SDLoc(N0.getOperand(0)),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005029 N0.getOperand(0).getValueType(), ExtLoad);
5030 CombineTo(N, And);
5031 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickac6d9be2013-05-25 02:42:55 +00005032 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005033 ISD::SIGN_EXTEND);
5034 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5035 }
5036 }
5037 }
5038
Chris Lattner20a35c32007-04-11 05:32:27 +00005039 if (N0.getOpcode() == ISD::SETCC) {
Chris Lattner2b7a2712009-07-08 00:31:33 +00005040 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohman3ce89f42010-04-30 17:19:19 +00005041 // Only do this before legalize for now.
Owen Andersoned5707b2013-04-23 18:09:28 +00005042 if (VT.isVector() && !LegalOperations &&
Stephen Lin155615d2013-07-08 00:37:03 +00005043 TLI.getBooleanContents(true) ==
Owen Andersoned5707b2013-04-23 18:09:28 +00005044 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Dan Gohman3ce89f42010-04-30 17:19:19 +00005045 EVT N0VT = N0.getOperand(0).getValueType();
Nadav Rotem2e506192012-04-11 08:26:11 +00005046 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5047 // of the same size as the compared operands. Only optimize sext(setcc())
5048 // if this is the case.
Matt Arsenault225ed702013-05-18 00:21:46 +00005049 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem2e506192012-04-11 08:26:11 +00005050
5051 // We know that the # elements of the results is the same as the
5052 // # elements of the compare (and the # elements of the compare result
5053 // for that matter). Check to see that they are the same size. If so,
5054 // we know that the element size of the sext'd result matches the
5055 // element size of the compare operands.
5056 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickac6d9be2013-05-25 02:42:55 +00005057 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands34727662010-07-12 08:16:59 +00005058 N0.getOperand(1),
5059 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault9aa8fdf2013-05-17 21:43:43 +00005060
Dan Gohman3ce89f42010-04-30 17:19:19 +00005061 // If the desired elements are smaller or larger than the source
5062 // elements we can use a matching integer vector type and then
5063 // truncate/sign extend
Matt Arsenault9aa8fdf2013-05-17 21:43:43 +00005064 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper0eb5dad2012-09-29 07:18:53 +00005065 if (SVT == MatchingVectorType) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005066 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper0eb5dad2012-09-29 07:18:53 +00005067 N0.getOperand(0), N0.getOperand(1),
5068 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickac6d9be2013-05-25 02:42:55 +00005069 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohman3ce89f42010-04-30 17:19:19 +00005070 }
Chris Lattner2b7a2712009-07-08 00:31:33 +00005071 }
Dan Gohman3ce89f42010-04-30 17:19:19 +00005072
Stephen Hines36b56882014-04-23 16:57:46 -07005073 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohmana7bcef12010-04-24 01:17:30 +00005074 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5cbd37e2009-08-06 09:18:59 +00005075 SDValue NegOne =
Dan Gohmana7bcef12010-04-24 01:17:30 +00005076 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelfdc40a02009-02-17 22:15:04 +00005077 SDValue SCC =
Andrew Trickac6d9be2013-05-25 02:42:55 +00005078 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5cbd37e2009-08-06 09:18:59 +00005079 NegOne, DAG.getConstant(0, VT),
Chris Lattner1eba01e2007-04-11 06:50:51 +00005080 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greifba36cb52008-08-28 21:40:38 +00005081 if (SCC.getNode()) return SCC;
Stephen Hines36b56882014-04-23 16:57:46 -07005082
5083 if (!VT.isVector()) {
5084 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5085 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5086 SDLoc DL(N);
5087 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5088 SDValue SetCC = DAG.getSetCC(DL,
5089 SetCCVT,
5090 N0.getOperand(0), N0.getOperand(1), CC);
5091 EVT SelectVT = getSetCCResultType(VT);
5092 return DAG.getSelect(DL, VT,
5093 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5094 NegOne, DAG.getConstant(0, VT));
5095
5096 }
Matt Arsenaultb05e4772013-06-14 22:04:37 +00005097 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00005098 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005099
Dan Gohman8f0ad582008-04-28 16:58:24 +00005100 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sands25cf2272008-11-24 14:53:14 +00005101 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohman187db7b2008-04-28 18:47:17 +00005102 DAG.SignBitIsZero(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00005103 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +00005104
Evan Chengb3a3d5e2010-04-28 07:10:39 +00005105 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00005106}
5107
Rafael Espindoladecbc432012-04-09 16:06:03 +00005108// isTruncateOf - If N is a truncate of some other value, return true, record
5109// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5110// This function computes KnownZero to avoid a duplicated call to
5111// ComputeMaskedBits in the caller.
5112static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5113 APInt &KnownZero) {
5114 APInt KnownOne;
5115 if (N->getOpcode() == ISD::TRUNCATE) {
5116 Op = N->getOperand(0);
5117 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5118 return true;
5119 }
5120
5121 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5122 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5123 return false;
5124
5125 SDValue Op0 = N->getOperand(0);
5126 SDValue Op1 = N->getOperand(1);
5127 assert(Op0.getValueType() == Op1.getValueType());
5128
5129 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5130 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindolafdb230a2012-04-10 00:16:22 +00005131 if (COp0 && COp0->isNullValue())
Rafael Espindoladecbc432012-04-09 16:06:03 +00005132 Op = Op1;
Rafael Espindolafdb230a2012-04-10 00:16:22 +00005133 else if (COp1 && COp1->isNullValue())
Rafael Espindoladecbc432012-04-09 16:06:03 +00005134 Op = Op0;
5135 else
5136 return false;
5137
5138 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5139
5140 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5141 return false;
5142
5143 return true;
5144}
5145
Dan Gohman475871a2008-07-27 21:46:04 +00005146SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5147 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00005148 EVT VT = N->getValueType(0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00005149
Stephen Hines36b56882014-04-23 16:57:46 -07005150 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5151 LegalOperations))
5152 return SDValue(Res, 0);
5153
Nate Begeman1d4d4142005-09-01 00:19:25 +00005154 // fold (zext (zext x)) -> (zext x)
Chris Lattner310b5782006-05-06 23:06:26 +00005155 // fold (zext (aext x)) -> (zext x)
5156 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickac6d9be2013-05-25 02:42:55 +00005157 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendling6ce610f2009-01-30 22:23:15 +00005158 N0.getOperand(0));
Chris Lattner6007b842006-09-21 06:00:20 +00005159
Chandler Carruthf103b3d2012-01-11 08:41:08 +00005160 // fold (zext (truncate x)) -> (zext x) or
5161 // (zext (truncate x)) -> (truncate x)
5162 // This is valid when the truncated bits of x are already zero.
5163 // FIXME: We should extend this to work for vectors too.
Rafael Espindoladecbc432012-04-09 16:06:03 +00005164 SDValue Op;
5165 APInt KnownZero;
5166 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5167 APInt TruncatedBits =
5168 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5169 APInt(Op.getValueSizeInBits(), 0) :
5170 APInt::getBitsSet(Op.getValueSizeInBits(),
5171 N0.getValueSizeInBits(),
5172 std::min(Op.getValueSizeInBits(),
5173 VT.getSizeInBits()));
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00005174 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruthf103b3d2012-01-11 08:41:08 +00005175 if (VT.bitsGT(Op.getValueType()))
Andrew Trickac6d9be2013-05-25 02:42:55 +00005176 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruthf103b3d2012-01-11 08:41:08 +00005177 if (VT.bitsLT(Op.getValueType()))
Andrew Trickac6d9be2013-05-25 02:42:55 +00005178 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruthf103b3d2012-01-11 08:41:08 +00005179
5180 return Op;
5181 }
5182 }
5183
Evan Chengc88138f2007-03-22 01:54:19 +00005184 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5185 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen2041a0e2007-03-30 21:38:07 +00005186 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greifba36cb52008-08-28 21:40:38 +00005187 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5188 if (NarrowLoad.getNode()) {
Dale Johannesen61734eb2010-05-25 17:50:03 +00005189 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5190 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greifba36cb52008-08-28 21:40:38 +00005191 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen61734eb2010-05-25 17:50:03 +00005192 // CombineTo deleted the truncate, if needed, but not what's under it.
5193 AddToWorkList(oye);
5194 }
Eli Friedmane545d382011-04-16 23:25:34 +00005195 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng0b063de2007-03-23 02:16:52 +00005196 }
Evan Chengc88138f2007-03-22 01:54:19 +00005197 }
5198
Chris Lattner6007b842006-09-21 06:00:20 +00005199 // fold (zext (truncate x)) -> (and x, mask)
5200 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman4e39e9d2010-06-24 14:30:44 +00005201 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman394d6292010-11-03 01:47:46 +00005202
5203 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5204 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5205 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5206 if (NarrowLoad.getNode()) {
5207 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5208 if (NarrowLoad.getNode() != N0.getNode()) {
5209 CombineTo(N0.getNode(), NarrowLoad);
5210 // CombineTo deleted the truncate, if needed, but not what's under it.
5211 AddToWorkList(oye);
5212 }
5213 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5214 }
5215
Dan Gohman475871a2008-07-27 21:46:04 +00005216 SDValue Op = N0.getOperand(0);
Duncan Sands8e4eb092008-06-08 20:54:56 +00005217 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005218 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Elena Demikhovsky1da58672012-04-22 09:39:03 +00005219 AddToWorkList(Op.getNode());
Duncan Sands8e4eb092008-06-08 20:54:56 +00005220 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005221 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Elena Demikhovsky1da58672012-04-22 09:39:03 +00005222 AddToWorkList(Op.getNode());
Chris Lattner6007b842006-09-21 06:00:20 +00005223 }
Andrew Trickac6d9be2013-05-25 02:42:55 +00005224 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman87862e72009-12-11 21:31:27 +00005225 N0.getValueType().getScalarType());
Chris Lattner6007b842006-09-21 06:00:20 +00005226 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005227
Dan Gohman97121ba2009-04-08 00:15:30 +00005228 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5229 // if either of the casts is not free.
Chris Lattner111c2282006-09-21 06:14:31 +00005230 if (N0.getOpcode() == ISD::AND &&
5231 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohman97121ba2009-04-08 00:15:30 +00005232 N0.getOperand(1).getOpcode() == ISD::Constant &&
5233 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5234 N0.getValueType()) ||
5235 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman475871a2008-07-27 21:46:04 +00005236 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands8e4eb092008-06-08 20:54:56 +00005237 if (X.getValueType().bitsLT(VT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005238 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands8e4eb092008-06-08 20:54:56 +00005239 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005240 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner111c2282006-09-21 06:14:31 +00005241 }
Dan Gohman220a8232008-03-03 23:51:38 +00005242 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad40f8f622010-12-07 08:25:19 +00005243 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickac6d9be2013-05-25 02:42:55 +00005244 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling6ce610f2009-01-30 22:23:15 +00005245 X, DAG.getConstant(Mask, VT));
Chris Lattner111c2282006-09-21 06:14:31 +00005246 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005247
Evan Cheng110dec22005-12-14 02:19:23 +00005248 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Nadav Rotemed9b9342011-02-20 12:37:50 +00005249 // None of the supported targets knows how to perform load and vector_zext
Nadav Rotemfcd96192011-02-27 07:40:43 +00005250 // on vectors in one instruction. We only perform this transformation on
5251 // scalars.
Nadav Rotemed9b9342011-02-20 12:37:50 +00005252 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Duncan Sands25cf2272008-11-24 14:53:14 +00005253 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng03294662008-10-14 21:26:46 +00005254 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Cheng3c3ddb32007-10-29 19:58:20 +00005255 bool DoXform = true;
5256 SmallVector<SDNode*, 4> SetCCs;
5257 if (!N0.hasOneUse())
5258 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5259 if (DoXform) {
5260 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00005261 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendling6ce610f2009-01-30 22:23:15 +00005262 LN0->getChain(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005263 LN0->getBasePtr(), N0.getValueType(),
5264 LN0->getMemOperand());
Evan Cheng3c3ddb32007-10-29 19:58:20 +00005265 CombineTo(N, ExtLoad);
Andrew Trickac6d9be2013-05-25 02:42:55 +00005266 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendling6ce610f2009-01-30 22:23:15 +00005267 N0.getValueType(), ExtLoad);
Gabor Greifba36cb52008-08-28 21:40:38 +00005268 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendling6ce610f2009-01-30 22:23:15 +00005269
Andrew Trickac6d9be2013-05-25 02:42:55 +00005270 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005271 ISD::ZERO_EXTEND);
Dan Gohman475871a2008-07-27 21:46:04 +00005272 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng3c3ddb32007-10-29 19:58:20 +00005273 }
Evan Cheng110dec22005-12-14 02:19:23 +00005274 }
Chris Lattnerad25d4e2005-12-14 19:05:06 +00005275
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005276 // fold (zext (and/or/xor (load x), cst)) ->
5277 // (and/or/xor (zextload x), (zext cst))
5278 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5279 N0.getOpcode() == ISD::XOR) &&
5280 isa<LoadSDNode>(N0.getOperand(0)) &&
5281 N0.getOperand(1).getOpcode() == ISD::Constant &&
5282 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5283 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5284 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5285 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
5286 bool DoXform = true;
5287 SmallVector<SDNode*, 4> SetCCs;
5288 if (!N0.hasOneUse())
5289 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5290 SetCCs, TLI);
5291 if (DoXform) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005292 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005293 LN0->getChain(), LN0->getBasePtr(),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005294 LN0->getMemoryVT(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005295 LN0->getMemOperand());
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005296 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5297 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickac6d9be2013-05-25 02:42:55 +00005298 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005299 ExtLoad, DAG.getConstant(Mask, VT));
5300 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickac6d9be2013-05-25 02:42:55 +00005301 SDLoc(N0.getOperand(0)),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005302 N0.getOperand(0).getValueType(), ExtLoad);
5303 CombineTo(N, And);
5304 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickac6d9be2013-05-25 02:42:55 +00005305 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005306 ISD::ZERO_EXTEND);
5307 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5308 }
5309 }
5310 }
5311
Chris Lattnerad25d4e2005-12-14 19:05:06 +00005312 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5313 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greifba36cb52008-08-28 21:40:38 +00005314 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5315 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Cheng466685d2006-10-09 20:57:25 +00005316 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman8a55ce42009-09-23 21:02:20 +00005317 EVT MemVT = LN0->getMemoryVT();
Duncan Sands25cf2272008-11-24 14:53:14 +00005318 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman8a55ce42009-09-23 21:02:20 +00005319 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005320 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendling6ce610f2009-01-30 22:23:15 +00005321 LN0->getChain(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005322 LN0->getBasePtr(), MemVT,
5323 LN0->getMemOperand());
Duncan Sandsd4b9c172008-06-13 19:07:40 +00005324 CombineTo(N, ExtLoad);
Gabor Greif12632d22008-08-30 19:29:20 +00005325 CombineTo(N0.getNode(),
Andrew Trickac6d9be2013-05-25 02:42:55 +00005326 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendling6ce610f2009-01-30 22:23:15 +00005327 ExtLoad),
Duncan Sandsd4b9c172008-06-13 19:07:40 +00005328 ExtLoad.getValue(1));
Dan Gohman475871a2008-07-27 21:46:04 +00005329 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sandsd4b9c172008-06-13 19:07:40 +00005330 }
Chris Lattnerad25d4e2005-12-14 19:05:06 +00005331 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005332
Chris Lattner20a35c32007-04-11 05:32:27 +00005333 if (N0.getOpcode() == ISD::SETCC) {
Stephen Hines36b56882014-04-23 16:57:46 -07005334 if (!LegalOperations && VT.isVector() &&
5335 N0.getValueType().getVectorElementType() == MVT::i1) {
5336 EVT N0VT = N0.getOperand(0).getValueType();
5337 if (getSetCCResultType(N0VT) == N0.getValueType())
5338 return SDValue();
5339
Evan Cheng0a942db2010-05-19 01:08:17 +00005340 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5341 // Only do this before legalize for now.
Evan Cheng0a942db2010-05-19 01:08:17 +00005342 EVT EltVT = VT.getVectorElementType();
5343 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5344 DAG.getConstant(1, EltVT));
Dan Gohman71dc7c92011-05-17 22:20:36 +00005345 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Cheng0a942db2010-05-19 01:08:17 +00005346 // We know that the # elements of the results is the same as the
5347 // # elements of the compare (and the # elements of the compare result
5348 // for that matter). Check to see that they are the same size. If so,
5349 // we know that the element size of the sext'd result matches the
5350 // element size of the compare operands.
Andrew Trickac6d9be2013-05-25 02:42:55 +00005351 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5352 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Cheng0a942db2010-05-19 01:08:17 +00005353 N0.getOperand(1),
5354 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickac6d9be2013-05-25 02:42:55 +00005355 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Evan Cheng0a942db2010-05-19 01:08:17 +00005356 &OneOps[0], OneOps.size()));
Dan Gohman71dc7c92011-05-17 22:20:36 +00005357
5358 // If the desired elements are smaller or larger than the source
5359 // elements we can use a matching integer vector type and then
5360 // truncate/sign extend
5361 EVT MatchingElementType =
5362 EVT::getIntegerVT(*DAG.getContext(),
5363 N0VT.getScalarType().getSizeInBits());
5364 EVT MatchingVectorType =
5365 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5366 N0VT.getVectorNumElements());
5367 SDValue VsetCC =
Andrew Trickac6d9be2013-05-25 02:42:55 +00005368 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman71dc7c92011-05-17 22:20:36 +00005369 N0.getOperand(1),
5370 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickac6d9be2013-05-25 02:42:55 +00005371 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5372 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5373 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Dan Gohman71dc7c92011-05-17 22:20:36 +00005374 &OneOps[0], OneOps.size()));
Evan Cheng0a942db2010-05-19 01:08:17 +00005375 }
5376
5377 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelfdc40a02009-02-17 22:15:04 +00005378 SDValue SCC =
Andrew Trickac6d9be2013-05-25 02:42:55 +00005379 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner20a35c32007-04-11 05:32:27 +00005380 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner1eba01e2007-04-11 06:50:51 +00005381 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greifba36cb52008-08-28 21:40:38 +00005382 if (SCC.getNode()) return SCC;
Chris Lattner20a35c32007-04-11 05:32:27 +00005383 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005384
Evan Cheng9818c042009-12-15 03:00:32 +00005385 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Cheng99b653c2009-12-15 00:41:36 +00005386 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng9818c042009-12-15 03:00:32 +00005387 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Cheng99b653c2009-12-15 00:41:36 +00005388 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5389 N0.hasOneUse()) {
Chris Lattnere0751182011-02-13 19:09:16 +00005390 SDValue ShAmt = N0.getOperand(1);
5391 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng9818c042009-12-15 03:00:32 +00005392 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere0751182011-02-13 19:09:16 +00005393 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng9818c042009-12-15 03:00:32 +00005394 // If the original shl may be shifting out bits, do not perform this
5395 // transformation.
Chris Lattnere0751182011-02-13 19:09:16 +00005396 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5397 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5398 if (ShAmtVal > KnownZeroBits)
Evan Cheng9818c042009-12-15 03:00:32 +00005399 return SDValue();
5400 }
Chris Lattnere0751182011-02-13 19:09:16 +00005401
Andrew Trickac6d9be2013-05-25 02:42:55 +00005402 SDLoc DL(N);
Owen Anderson95771af2011-02-25 21:41:48 +00005403
5404 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere0751182011-02-13 19:09:16 +00005405 if (VT.getSizeInBits() >= 256)
5406 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Anderson95771af2011-02-25 21:41:48 +00005407
Chris Lattnere0751182011-02-13 19:09:16 +00005408 return DAG.getNode(N0.getOpcode(), DL, VT,
5409 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5410 ShAmt);
Evan Cheng99b653c2009-12-15 00:41:36 +00005411 }
5412
Evan Chengb3a3d5e2010-04-28 07:10:39 +00005413 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00005414}
5415
Dan Gohman475871a2008-07-27 21:46:04 +00005416SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5417 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00005418 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00005419
Stephen Hines36b56882014-04-23 16:57:46 -07005420 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5421 LegalOperations))
5422 return SDValue(Res, 0);
5423
Chris Lattner5ffc0662006-05-05 05:58:59 +00005424 // fold (aext (aext x)) -> (aext x)
5425 // fold (aext (zext x)) -> (zext x)
5426 // fold (aext (sext x)) -> (sext x)
5427 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5428 N0.getOpcode() == ISD::ZERO_EXTEND ||
5429 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickac6d9be2013-05-25 02:42:55 +00005430 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00005431
Evan Chengc88138f2007-03-22 01:54:19 +00005432 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5433 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5434 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greifba36cb52008-08-28 21:40:38 +00005435 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5436 if (NarrowLoad.getNode()) {
Dale Johannesen86234c32010-05-25 18:47:23 +00005437 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5438 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greifba36cb52008-08-28 21:40:38 +00005439 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen86234c32010-05-25 18:47:23 +00005440 // CombineTo deleted the truncate, if needed, but not what's under it.
5441 AddToWorkList(oye);
5442 }
Eli Friedmane545d382011-04-16 23:25:34 +00005443 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng0b063de2007-03-23 02:16:52 +00005444 }
Evan Chengc88138f2007-03-22 01:54:19 +00005445 }
5446
Chris Lattner84750582006-09-20 06:29:17 +00005447 // fold (aext (truncate x))
5448 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman475871a2008-07-27 21:46:04 +00005449 SDValue TruncOp = N0.getOperand(0);
Chris Lattner84750582006-09-20 06:29:17 +00005450 if (TruncOp.getValueType() == VT)
Sylvestre Ledru94c22712012-09-27 10:14:43 +00005451 return TruncOp; // x iff x size == zext size.
Duncan Sands8e4eb092008-06-08 20:54:56 +00005452 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickac6d9be2013-05-25 02:42:55 +00005453 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5454 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner84750582006-09-20 06:29:17 +00005455 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005456
Dan Gohman97121ba2009-04-08 00:15:30 +00005457 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5458 // if the trunc is not free.
Chris Lattner0e4b9222006-09-21 06:40:43 +00005459 if (N0.getOpcode() == ISD::AND &&
5460 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohman97121ba2009-04-08 00:15:30 +00005461 N0.getOperand(1).getOpcode() == ISD::Constant &&
5462 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5463 N0.getValueType())) {
Dan Gohman475871a2008-07-27 21:46:04 +00005464 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands8e4eb092008-06-08 20:54:56 +00005465 if (X.getValueType().bitsLT(VT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005466 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands8e4eb092008-06-08 20:54:56 +00005467 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005468 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner0e4b9222006-09-21 06:40:43 +00005469 }
Dan Gohman220a8232008-03-03 23:51:38 +00005470 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad40f8f622010-12-07 08:25:19 +00005471 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickac6d9be2013-05-25 02:42:55 +00005472 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling683c9572009-01-30 22:27:33 +00005473 X, DAG.getConstant(Mask, VT));
Chris Lattner0e4b9222006-09-21 06:40:43 +00005474 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005475
Chris Lattner5ffc0662006-05-05 05:58:59 +00005476 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem8c20ec52011-02-24 21:01:34 +00005477 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemfcd96192011-02-27 07:40:43 +00005478 // on vectors in one instruction. We only perform this transformation on
5479 // scalars.
Nadav Rotem8c20ec52011-02-24 21:01:34 +00005480 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Duncan Sands25cf2272008-11-24 14:53:14 +00005481 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng03294662008-10-14 21:26:46 +00005482 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Dan Gohman57fc82d2009-04-09 03:51:29 +00005483 bool DoXform = true;
5484 SmallVector<SDNode*, 4> SetCCs;
5485 if (!N0.hasOneUse())
5486 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5487 if (DoXform) {
5488 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00005489 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman57fc82d2009-04-09 03:51:29 +00005490 LN0->getChain(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005491 LN0->getBasePtr(), N0.getValueType(),
5492 LN0->getMemOperand());
Dan Gohman57fc82d2009-04-09 03:51:29 +00005493 CombineTo(N, ExtLoad);
Andrew Trickac6d9be2013-05-25 02:42:55 +00005494 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman57fc82d2009-04-09 03:51:29 +00005495 N0.getValueType(), ExtLoad);
5496 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickac6d9be2013-05-25 02:42:55 +00005497 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005498 ISD::ANY_EXTEND);
Dan Gohman57fc82d2009-04-09 03:51:29 +00005499 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5500 }
Chris Lattner5ffc0662006-05-05 05:58:59 +00005501 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005502
Chris Lattner5ffc0662006-05-05 05:58:59 +00005503 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5504 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5505 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng83060c52007-03-07 08:07:03 +00005506 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greifba36cb52008-08-28 21:40:38 +00005507 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng466685d2006-10-09 20:57:25 +00005508 N0.hasOneUse()) {
5509 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman8a55ce42009-09-23 21:02:20 +00005510 EVT MemVT = LN0->getMemoryVT();
Andrew Trickac6d9be2013-05-25 02:42:55 +00005511 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
Stuart Hastingsa9011292011-02-16 16:23:55 +00005512 VT, LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005513 MemVT, LN0->getMemOperand());
Chris Lattner5ffc0662006-05-05 05:58:59 +00005514 CombineTo(N, ExtLoad);
Evan Cheng45299662008-08-29 23:20:46 +00005515 CombineTo(N0.getNode(),
Andrew Trickac6d9be2013-05-25 02:42:55 +00005516 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendling683c9572009-01-30 22:27:33 +00005517 N0.getValueType(), ExtLoad),
Chris Lattner5ffc0662006-05-05 05:58:59 +00005518 ExtLoad.getValue(1));
Dan Gohman475871a2008-07-27 21:46:04 +00005519 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner5ffc0662006-05-05 05:58:59 +00005520 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005521
Chris Lattner20a35c32007-04-11 05:32:27 +00005522 if (N0.getOpcode() == ISD::SETCC) {
Evan Cheng0a942db2010-05-19 01:08:17 +00005523 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5524 // Only do this before legalize for now.
5525 if (VT.isVector() && !LegalOperations) {
5526 EVT N0VT = N0.getOperand(0).getValueType();
5527 // We know that the # elements of the results is the same as the
5528 // # elements of the compare (and the # elements of the compare result
5529 // for that matter). Check to see that they are the same size. If so,
5530 // we know that the element size of the sext'd result matches the
5531 // element size of the compare operands.
5532 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickac6d9be2013-05-25 02:42:55 +00005533 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands34727662010-07-12 08:16:59 +00005534 N0.getOperand(1),
5535 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Cheng0a942db2010-05-19 01:08:17 +00005536 // If the desired elements are smaller or larger than the source
5537 // elements we can use a matching integer vector type and then
5538 // truncate/sign extend
5539 else {
Duncan Sands34727662010-07-12 08:16:59 +00005540 EVT MatchingElementType =
5541 EVT::getIntegerVT(*DAG.getContext(),
5542 N0VT.getScalarType().getSizeInBits());
5543 EVT MatchingVectorType =
5544 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5545 N0VT.getVectorNumElements());
5546 SDValue VsetCC =
Andrew Trickac6d9be2013-05-25 02:42:55 +00005547 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands34727662010-07-12 08:16:59 +00005548 N0.getOperand(1),
5549 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickac6d9be2013-05-25 02:42:55 +00005550 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Cheng0a942db2010-05-19 01:08:17 +00005551 }
5552 }
5553
5554 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelfdc40a02009-02-17 22:15:04 +00005555 SDValue SCC =
Andrew Trickac6d9be2013-05-25 02:42:55 +00005556 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner1eba01e2007-04-11 06:50:51 +00005557 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnerc24bbad2007-04-11 16:51:53 +00005558 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greifba36cb52008-08-28 21:40:38 +00005559 if (SCC.getNode())
Chris Lattnerc56a81d2007-04-11 06:43:25 +00005560 return SCC;
Chris Lattner20a35c32007-04-11 05:32:27 +00005561 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005562
Evan Chengb3a3d5e2010-04-28 07:10:39 +00005563 return SDValue();
Chris Lattner5ffc0662006-05-05 05:58:59 +00005564}
5565
Chris Lattner2b4c2792007-10-13 06:35:54 +00005566/// GetDemandedBits - See if the specified operand can be simplified with the
5567/// knowledge that only the bits specified by Mask are used. If so, return the
Dan Gohman475871a2008-07-27 21:46:04 +00005568/// simpler operand, otherwise return a null SDValue.
5569SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner2b4c2792007-10-13 06:35:54 +00005570 switch (V.getOpcode()) {
5571 default: break;
Lang Hames5207bf22011-11-08 18:56:23 +00005572 case ISD::Constant: {
5573 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5574 assert(CV != 0 && "Const value should be ConstSDNode.");
5575 const APInt &CVal = CV->getAPIntValue();
5576 APInt NewVal = CVal & Mask;
Stephen Linb4940152013-07-09 00:44:49 +00005577 if (NewVal != CVal)
Lang Hames5207bf22011-11-08 18:56:23 +00005578 return DAG.getConstant(NewVal, V.getValueType());
Lang Hames5207bf22011-11-08 18:56:23 +00005579 break;
5580 }
Chris Lattner2b4c2792007-10-13 06:35:54 +00005581 case ISD::OR:
5582 case ISD::XOR:
5583 // If the LHS or RHS don't contribute bits to the or, drop them.
5584 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5585 return V.getOperand(1);
5586 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5587 return V.getOperand(0);
5588 break;
Chris Lattnere33544c2007-10-13 06:58:48 +00005589 case ISD::SRL:
5590 // Only look at single-use SRLs.
Gabor Greifba36cb52008-08-28 21:40:38 +00005591 if (!V.getNode()->hasOneUse())
Chris Lattnere33544c2007-10-13 06:58:48 +00005592 break;
5593 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5594 // See if we can recursively simplify the LHS.
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005595 unsigned Amt = RHSC->getZExtValue();
Bill Wendling8509c902009-01-30 22:33:24 +00005596
Dan Gohmancc91d632009-01-03 19:22:06 +00005597 // Watch out for shift count overflow though.
5598 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005599 APInt NewMask = Mask << Amt;
Dan Gohman475871a2008-07-27 21:46:04 +00005600 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling8509c902009-01-30 22:33:24 +00005601 if (SimplifyLHS.getNode())
Andrew Trickac6d9be2013-05-25 02:42:55 +00005602 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnere33544c2007-10-13 06:58:48 +00005603 SimplifyLHS, V.getOperand(1));
Chris Lattnere33544c2007-10-13 06:58:48 +00005604 }
Chris Lattner2b4c2792007-10-13 06:35:54 +00005605 }
Dan Gohman475871a2008-07-27 21:46:04 +00005606 return SDValue();
Chris Lattner2b4c2792007-10-13 06:35:54 +00005607}
5608
Evan Chengc88138f2007-03-22 01:54:19 +00005609/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5610/// bits and then truncated to a narrower type and where N is a multiple
5611/// of number of bits of the narrower type, transform it to a narrower load
5612/// from address + N / num of bits of new type. If the result is to be
5613/// extended, also fold the extension to form a extending load.
Dan Gohman475871a2008-07-27 21:46:04 +00005614SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Chengc88138f2007-03-22 01:54:19 +00005615 unsigned Opc = N->getOpcode();
Dan Gohman4e39e9d2010-06-24 14:30:44 +00005616
Evan Chengc88138f2007-03-22 01:54:19 +00005617 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman475871a2008-07-27 21:46:04 +00005618 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00005619 EVT VT = N->getValueType(0);
5620 EVT ExtVT = VT;
Evan Chengc88138f2007-03-22 01:54:19 +00005621
Dan Gohman7f8613e2008-08-14 20:04:46 +00005622 // This transformation isn't valid for vector loads.
5623 if (VT.isVector())
5624 return SDValue();
5625
Dan Gohmand1996362010-01-09 02:13:55 +00005626 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenge177e302007-03-23 22:13:36 +00005627 // extended to VT.
Evan Chengc88138f2007-03-22 01:54:19 +00005628 if (Opc == ISD::SIGN_EXTEND_INREG) {
5629 ExtType = ISD::SEXTLOAD;
Owen Andersone50ed302009-08-10 22:56:29 +00005630 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman4e39e9d2010-06-24 14:30:44 +00005631 } else if (Opc == ISD::SRL) {
Chris Lattner90b03642010-12-21 18:05:22 +00005632 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman4e39e9d2010-06-24 14:30:44 +00005633 ExtType = ISD::ZEXTLOAD;
5634 N0 = SDValue(N, 0);
5635 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5636 if (!N01) return SDValue();
5637 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5638 VT.getSizeInBits() - N01->getZExtValue());
Evan Chengc88138f2007-03-22 01:54:19 +00005639 }
Richard Osborne4e3740e2011-01-31 17:41:44 +00005640 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5641 return SDValue();
Evan Chengc88138f2007-03-22 01:54:19 +00005642
Owen Andersone50ed302009-08-10 22:56:29 +00005643 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Anderson95771af2011-02-25 21:41:48 +00005644
Chris Lattner7a2a7fa2010-12-22 08:01:44 +00005645 // Do not generate loads of non-round integer types since these can
5646 // be expensive (and would be wrong if the type is not byte sized).
5647 if (!ExtVT.isRound())
5648 return SDValue();
Owen Anderson95771af2011-02-25 21:41:48 +00005649
Evan Chengc88138f2007-03-22 01:54:19 +00005650 unsigned ShAmt = 0;
Chris Lattner7a2a7fa2010-12-22 08:01:44 +00005651 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Chengc88138f2007-03-22 01:54:19 +00005652 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005653 ShAmt = N01->getZExtValue();
Evan Chengc88138f2007-03-22 01:54:19 +00005654 // Is the shift amount a multiple of size of VT?
5655 if ((ShAmt & (EVTBits-1)) == 0) {
5656 N0 = N0.getOperand(0);
Eli Friedmand68eea22009-08-19 08:46:10 +00005657 // Is the load width a multiple of size of VT?
5658 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman475871a2008-07-27 21:46:04 +00005659 return SDValue();
Evan Chengc88138f2007-03-22 01:54:19 +00005660 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00005661
Chris Lattnercbf68df2010-12-22 08:02:57 +00005662 // At this point, we must have a load or else we can't do the transform.
5663 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Anderson95771af2011-02-25 21:41:48 +00005664
Chandler Carruth1c49fda2012-12-11 00:36:57 +00005665 // Because a SRL must be assumed to *need* to zero-extend the high bits
5666 // (as opposed to anyext the high bits), we can't combine the zextload
5667 // lowering of SRL and an sextload.
5668 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5669 return SDValue();
5670
Chris Lattner2831a192010-10-01 05:36:09 +00005671 // If the shift amount is larger than the input type then we're not
5672 // accessing any of the loaded bytes. If the load was a zextload/extload
5673 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercbf68df2010-12-22 08:02:57 +00005674 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattner2831a192010-10-01 05:36:09 +00005675 return SDValue();
Evan Chengc88138f2007-03-22 01:54:19 +00005676 }
5677 }
5678
Dan Gohman394d6292010-11-03 01:47:46 +00005679 // If the load is shifted left (and the result isn't shifted back right),
5680 // we can fold the truncate through the shift.
5681 unsigned ShLeftAmt = 0;
5682 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner4c32bc22010-12-22 07:36:50 +00005683 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman394d6292010-11-03 01:47:46 +00005684 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5685 ShLeftAmt = N01->getZExtValue();
5686 N0 = N0.getOperand(0);
5687 }
5688 }
Owen Anderson95771af2011-02-25 21:41:48 +00005689
Chris Lattner4c32bc22010-12-22 07:36:50 +00005690 // If we haven't found a load, we can't narrow it. Don't transform one with
5691 // multiple uses, this would require adding a new load.
Bill Schmidt89e88e32013-01-14 22:04:38 +00005692 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5693 return SDValue();
5694
5695 // Don't change the width of a volatile load.
5696 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5697 if (LN0->isVolatile())
Chris Lattner4c32bc22010-12-22 07:36:50 +00005698 return SDValue();
Owen Anderson95771af2011-02-25 21:41:48 +00005699
Chris Lattner7a2a7fa2010-12-22 08:01:44 +00005700 // Verify that we are actually reducing a load width here.
Bill Schmidt89e88e32013-01-14 22:04:38 +00005701 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner4c32bc22010-12-22 07:36:50 +00005702 return SDValue();
Owen Anderson95771af2011-02-25 21:41:48 +00005703
Bill Schmidt89e88e32013-01-14 22:04:38 +00005704 // For the transform to be legal, the load must produce only two values
5705 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lin155615d2013-07-08 00:37:03 +00005706 // load, for example, which produces an extra value. Otherwise the
Bill Schmidt89e88e32013-01-14 22:04:38 +00005707 // transformation is not equivalent, and the downstream logic to replace
5708 // uses gets things wrong.
5709 if (LN0->getNumValues() > 2)
5710 return SDValue();
5711
Benjamin Kramerf4eeab42013-07-06 14:05:09 +00005712 // If the load that we're shrinking is an extload and we're not just
5713 // discarding the extension we can't simply shrink the load. Bail.
5714 // TODO: It would be possible to merge the extensions in some cases.
5715 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5716 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5717 return SDValue();
5718
Chris Lattner4c32bc22010-12-22 07:36:50 +00005719 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling8509c902009-01-30 22:33:24 +00005720
Evan Cheng16436df2012-06-26 01:19:33 +00005721 if (PtrType == MVT::Untyped || PtrType.isExtended())
5722 // It's not possible to generate a constant of extended or untyped type.
5723 return SDValue();
5724
Chris Lattner4c32bc22010-12-22 07:36:50 +00005725 // For big endian targets, we need to adjust the offset to the pointer to
5726 // load the correct bytes.
5727 if (TLI.isBigEndian()) {
5728 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5729 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5730 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Chengc88138f2007-03-22 01:54:19 +00005731 }
5732
Chris Lattner4c32bc22010-12-22 07:36:50 +00005733 uint64_t PtrOff = ShAmt / 8;
5734 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickac6d9be2013-05-25 02:42:55 +00005735 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner4c32bc22010-12-22 07:36:50 +00005736 PtrType, LN0->getBasePtr(),
5737 DAG.getConstant(PtrOff, PtrType));
5738 AddToWorkList(NewPtr.getNode());
5739
Chris Lattner7a2a7fa2010-12-22 08:01:44 +00005740 SDValue Load;
5741 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickac6d9be2013-05-25 02:42:55 +00005742 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner7a2a7fa2010-12-22 08:01:44 +00005743 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooperd752e0f2011-11-08 18:42:53 +00005744 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005745 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
Chris Lattner7a2a7fa2010-12-22 08:01:44 +00005746 else
Andrew Trickac6d9be2013-05-25 02:42:55 +00005747 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner7a2a7fa2010-12-22 08:01:44 +00005748 LN0->getPointerInfo().getWithOffset(PtrOff),
5749 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005750 NewAlign, LN0->getTBAAInfo());
Chris Lattner4c32bc22010-12-22 07:36:50 +00005751
5752 // Replace the old load's chain with the new load's chain.
5753 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00005754 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner4c32bc22010-12-22 07:36:50 +00005755
5756 // Shift the result left, if we've swallowed a left shift.
5757 SDValue Result = Load;
5758 if (ShLeftAmt != 0) {
Owen Anderson95771af2011-02-25 21:41:48 +00005759 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner4c32bc22010-12-22 07:36:50 +00005760 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5761 ShImmTy = VT;
Paul Redmond5c974502013-02-12 15:21:21 +00005762 // If the shift amount is as large as the result size (but, presumably,
5763 // no larger than the source) then the useful bits of the result are
5764 // zero; we can't simply return the shortened shift, because the result
5765 // of that operation is undefined.
5766 if (ShLeftAmt >= VT.getSizeInBits())
5767 Result = DAG.getConstant(0, VT);
5768 else
Andrew Trickac6d9be2013-05-25 02:42:55 +00005769 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond5c974502013-02-12 15:21:21 +00005770 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner4c32bc22010-12-22 07:36:50 +00005771 }
5772
5773 // Return the new loaded value.
5774 return Result;
Evan Chengc88138f2007-03-22 01:54:19 +00005775}
5776
Dan Gohman475871a2008-07-27 21:46:04 +00005777SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5778 SDValue N0 = N->getOperand(0);
5779 SDValue N1 = N->getOperand(1);
Owen Andersone50ed302009-08-10 22:56:29 +00005780 EVT VT = N->getValueType(0);
5781 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman87862e72009-12-11 21:31:27 +00005782 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohmand1996362010-01-09 02:13:55 +00005783 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelfdc40a02009-02-17 22:15:04 +00005784
Nate Begeman1d4d4142005-09-01 00:19:25 +00005785 // fold (sext_in_reg c1) -> c1
Chris Lattnereaeda562006-05-08 20:59:41 +00005786 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickac6d9be2013-05-25 02:42:55 +00005787 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelfdc40a02009-02-17 22:15:04 +00005788
Chris Lattner541a24f2006-05-06 22:43:44 +00005789 // If the input is already sign extended, just drop the extension.
Dan Gohman87862e72009-12-11 21:31:27 +00005790 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattneree4ea922006-05-06 09:30:03 +00005791 return N0;
Scott Michelfdc40a02009-02-17 22:15:04 +00005792
Nate Begeman646d7e22005-09-02 21:18:40 +00005793 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5794 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Linb4940152013-07-09 00:44:49 +00005795 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickac6d9be2013-05-25 02:42:55 +00005796 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling8509c902009-01-30 22:33:24 +00005797 N0.getOperand(0), N1);
Chris Lattner4b37e872006-05-08 21:18:59 +00005798
Dan Gohman75dcf082008-07-31 00:50:31 +00005799 // fold (sext_in_reg (sext x)) -> (sext x)
5800 // fold (sext_in_reg (aext x)) -> (sext x)
5801 // if x is small enough.
5802 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5803 SDValue N00 = N0.getOperand(0);
Evan Cheng003d7c42010-04-16 22:26:19 +00005804 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5805 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00005806 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman75dcf082008-07-31 00:50:31 +00005807 }
5808
Chris Lattner95a5e052007-04-17 19:03:21 +00005809 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005810 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00005811 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelfdc40a02009-02-17 22:15:04 +00005812
Chris Lattner95a5e052007-04-17 19:03:21 +00005813 // fold operands of sext_in_reg based on knowledge that the top bits are not
5814 // demanded.
Dan Gohman475871a2008-07-27 21:46:04 +00005815 if (SimplifyDemandedBits(SDValue(N, 0)))
5816 return SDValue(N, 0);
Scott Michelfdc40a02009-02-17 22:15:04 +00005817
Evan Chengc88138f2007-03-22 01:54:19 +00005818 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5819 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman475871a2008-07-27 21:46:04 +00005820 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00005821 if (NarrowLoad.getNode())
Evan Chengc88138f2007-03-22 01:54:19 +00005822 return NarrowLoad;
5823
Bill Wendling8509c902009-01-30 22:33:24 +00005824 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru94c22712012-09-27 10:14:43 +00005825 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner4b37e872006-05-08 21:18:59 +00005826 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5827 if (N0.getOpcode() == ISD::SRL) {
5828 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman87862e72009-12-11 21:31:27 +00005829 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru94c22712012-09-27 10:14:43 +00005830 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner4b37e872006-05-08 21:18:59 +00005831 // extended enough.
Dan Gohmanea859be2007-06-22 14:59:07 +00005832 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman87862e72009-12-11 21:31:27 +00005833 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickac6d9be2013-05-25 02:42:55 +00005834 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling8509c902009-01-30 22:33:24 +00005835 N0.getOperand(0), N0.getOperand(1));
Chris Lattner4b37e872006-05-08 21:18:59 +00005836 }
5837 }
Evan Chengc88138f2007-03-22 01:54:19 +00005838
Nate Begemanded49632005-10-13 03:11:28 +00005839 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelfdc40a02009-02-17 22:15:04 +00005840 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greifba36cb52008-08-28 21:40:38 +00005841 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohmanb625f2f2008-01-30 00:15:11 +00005842 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sands25cf2272008-11-24 14:53:14 +00005843 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng03294662008-10-14 21:26:46 +00005844 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Cheng466685d2006-10-09 20:57:25 +00005845 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00005846 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling8509c902009-01-30 22:33:24 +00005847 LN0->getChain(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005848 LN0->getBasePtr(), EVT,
5849 LN0->getMemOperand());
Chris Lattnerd4771842005-12-14 19:25:30 +00005850 CombineTo(N, ExtLoad);
Gabor Greifba36cb52008-08-28 21:40:38 +00005851 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Elena Demikhovsky4b977312012-12-19 07:50:20 +00005852 AddToWorkList(ExtLoad.getNode());
Dan Gohman475871a2008-07-27 21:46:04 +00005853 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begemanded49632005-10-13 03:11:28 +00005854 }
Sylvestre Ledru94c22712012-09-27 10:14:43 +00005855 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greifba36cb52008-08-28 21:40:38 +00005856 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng83060c52007-03-07 08:07:03 +00005857 N0.hasOneUse() &&
Dan Gohmanb625f2f2008-01-30 00:15:11 +00005858 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sands25cf2272008-11-24 14:53:14 +00005859 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng03294662008-10-14 21:26:46 +00005860 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Cheng466685d2006-10-09 20:57:25 +00005861 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00005862 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling8509c902009-01-30 22:33:24 +00005863 LN0->getChain(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005864 LN0->getBasePtr(), EVT,
5865 LN0->getMemOperand());
Chris Lattnerd4771842005-12-14 19:25:30 +00005866 CombineTo(N, ExtLoad);
Gabor Greifba36cb52008-08-28 21:40:38 +00005867 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman475871a2008-07-27 21:46:04 +00005868 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begemanded49632005-10-13 03:11:28 +00005869 }
Evan Cheng9568e5c2011-06-21 06:01:08 +00005870
5871 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5872 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5873 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5874 N0.getOperand(1), false);
5875 if (BSwap.getNode() != 0)
Andrew Trickac6d9be2013-05-25 02:42:55 +00005876 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng9568e5c2011-06-21 06:01:08 +00005877 BSwap, N1);
5878 }
5879
Stephen Hines36b56882014-04-23 16:57:46 -07005880 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5881 // into a build_vector.
5882 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5883 SmallVector<SDValue, 8> Elts;
5884 unsigned NumElts = N0->getNumOperands();
5885 unsigned ShAmt = VTBits - EVTBits;
5886
5887 for (unsigned i = 0; i != NumElts; ++i) {
5888 SDValue Op = N0->getOperand(i);
5889 if (Op->getOpcode() == ISD::UNDEF) {
5890 Elts.push_back(Op);
5891 continue;
5892 }
5893
5894 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5895 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5896 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5897 Op.getValueType()));
5898 }
5899
5900 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5901 }
5902
Dan Gohman475871a2008-07-27 21:46:04 +00005903 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00005904}
5905
Dan Gohman475871a2008-07-27 21:46:04 +00005906SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5907 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00005908 EVT VT = N->getValueType(0);
Nadav Rotem7e413e9c2012-02-03 13:18:25 +00005909 bool isLE = TLI.isLittleEndian();
Nate Begeman1d4d4142005-09-01 00:19:25 +00005910
5911 // noop truncate
5912 if (N0.getValueType() == N->getValueType(0))
Nate Begeman83e75ec2005-09-06 04:43:02 +00005913 return N0;
Nate Begeman1d4d4142005-09-01 00:19:25 +00005914 // fold (truncate c1) -> c1
Chris Lattner310b5782006-05-06 23:06:26 +00005915 if (isa<ConstantSDNode>(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00005916 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00005917 // fold (truncate (truncate x)) -> (truncate x)
5918 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickac6d9be2013-05-25 02:42:55 +00005919 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman1d4d4142005-09-01 00:19:25 +00005920 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner7f893c02010-04-07 18:13:33 +00005921 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5922 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattnerb72773b2006-05-05 22:56:26 +00005923 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands8e4eb092008-06-08 20:54:56 +00005924 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman1d4d4142005-09-01 00:19:25 +00005925 // if the source is smaller than the dest, we still need an extend
Andrew Trickac6d9be2013-05-25 02:42:55 +00005926 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling67a67682009-01-30 22:44:24 +00005927 N0.getOperand(0));
Craig Topper0eb5dad2012-09-29 07:18:53 +00005928 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman1d4d4142005-09-01 00:19:25 +00005929 // if the source is larger than the dest, than we just need the truncate
Andrew Trickac6d9be2013-05-25 02:42:55 +00005930 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper0eb5dad2012-09-29 07:18:53 +00005931 // if the source and dest are the same type, we can drop both the extend
5932 // and the truncate.
5933 return N0.getOperand(0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00005934 }
Evan Cheng007b69e2007-03-21 20:14:05 +00005935
Nadav Rotemcc870a82012-02-05 11:39:23 +00005936 // Fold extract-and-trunc into a narrow extract. For example:
5937 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5938 // i32 y = TRUNCATE(i64 x)
5939 // -- becomes --
5940 // v16i8 b = BITCAST (v2i64 val)
5941 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5942 //
5943 // Note: We only run this optimization after type legalization (which often
Nadav Rotem7e413e9c2012-02-03 13:18:25 +00005944 // creates this pattern) and before operation legalization after which
5945 // we need to be more careful about the vector instructions that we generate.
5946 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Stephen Hines36b56882014-04-23 16:57:46 -07005947 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem7e413e9c2012-02-03 13:18:25 +00005948
5949 EVT VecTy = N0.getOperand(0).getValueType();
5950 EVT ExTy = N0.getValueType();
5951 EVT TrTy = N->getValueType(0);
5952
5953 unsigned NumElem = VecTy.getVectorNumElements();
5954 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5955
5956 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5957 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5958
5959 SDValue EltNo = N0->getOperand(1);
5960 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5961 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellard425b76c2013-08-05 22:22:01 +00005962 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem7e413e9c2012-02-03 13:18:25 +00005963 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5964
Andrew Trickac6d9be2013-05-25 02:42:55 +00005965 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem7e413e9c2012-02-03 13:18:25 +00005966 NVT, N0.getOperand(0));
5967
5968 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickac6d9be2013-05-25 02:42:55 +00005969 SDLoc(N), TrTy, V,
Jim Grosbacha249f7d2012-05-08 20:56:07 +00005970 DAG.getConstant(Index, IndexTy));
Nadav Rotem7e413e9c2012-02-03 13:18:25 +00005971 }
5972 }
5973
Arnold Schwaighoferc46e2df2013-02-20 21:33:32 +00005974 // Fold a series of buildvector, bitcast, and truncate if possible.
5975 // For example fold
5976 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5977 // (2xi32 (buildvector x, y)).
5978 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5979 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5980 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5981 N0.getOperand(0).hasOneUse()) {
5982
5983 SDValue BuildVect = N0.getOperand(0);
5984 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5985 EVT TruncVecEltTy = VT.getVectorElementType();
5986
5987 // Check that the element types match.
5988 if (BuildVectEltTy == TruncVecEltTy) {
5989 // Now we only need to compute the offset of the truncated elements.
5990 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5991 unsigned TruncVecNumElts = VT.getVectorNumElements();
5992 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5993
5994 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5995 "Invalid number of elements");
5996
5997 SmallVector<SDValue, 8> Opnds;
5998 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5999 Opnds.push_back(BuildVect.getOperand(i));
6000
Andrew Trickac6d9be2013-05-25 02:42:55 +00006001 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
Arnold Schwaighoferc46e2df2013-02-20 21:33:32 +00006002 Opnds.size());
6003 }
6004 }
6005
Chris Lattner2b4c2792007-10-13 06:35:54 +00006006 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem8c20ec52011-02-24 21:01:34 +00006007 // only the low bits are being used.
6008 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemfcd96192011-02-27 07:40:43 +00006009 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem8c20ec52011-02-24 21:01:34 +00006010 // may have different active low bits.
6011 if (!VT.isVector()) {
6012 SDValue Shorter =
6013 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6014 VT.getSizeInBits()));
6015 if (Shorter.getNode())
Andrew Trickac6d9be2013-05-25 02:42:55 +00006016 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem8c20ec52011-02-24 21:01:34 +00006017 }
Nate Begeman3df4d522005-10-12 20:40:40 +00006018 // fold (truncate (load x)) -> (smaller load x)
Evan Cheng007b69e2007-03-21 20:14:05 +00006019 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman4e39e9d2010-06-24 14:30:44 +00006020 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6021 SDValue Reduced = ReduceLoadWidth(N);
6022 if (Reduced.getNode())
6023 return Reduced;
Stephen Hines36b56882014-04-23 16:57:46 -07006024 // Handle the case where the load remains an extending load even
6025 // after truncation.
6026 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6027 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6028 if (!LN0->isVolatile() &&
6029 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6030 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6031 VT, LN0->getChain(), LN0->getBasePtr(),
6032 LN0->getMemoryVT(),
6033 LN0->getMemOperand());
6034 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6035 return NewLoad;
6036 }
6037 }
Dan Gohman4e39e9d2010-06-24 14:30:44 +00006038 }
Michael Liao07edaf32012-10-17 23:45:54 +00006039 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6040 // where ... are all 'undef'.
6041 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6042 SmallVector<EVT, 8> VTs;
6043 SDValue V;
6044 unsigned Idx = 0;
6045 unsigned NumDefs = 0;
6046
6047 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6048 SDValue X = N0.getOperand(i);
6049 if (X.getOpcode() != ISD::UNDEF) {
6050 V = X;
6051 Idx = i;
6052 NumDefs++;
6053 }
6054 // Stop if more than one members are non-undef.
6055 if (NumDefs > 1)
6056 break;
6057 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6058 VT.getVectorElementType(),
6059 X.getValueType().getVectorNumElements()));
6060 }
6061
6062 if (NumDefs == 0)
6063 return DAG.getUNDEF(VT);
6064
6065 if (NumDefs == 1) {
6066 assert(V.getNode() && "The single defined operand is empty!");
6067 SmallVector<SDValue, 8> Opnds;
6068 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6069 if (i != Idx) {
6070 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6071 continue;
6072 }
Andrew Trickac6d9be2013-05-25 02:42:55 +00006073 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Michael Liao07edaf32012-10-17 23:45:54 +00006074 AddToWorkList(NV.getNode());
6075 Opnds.push_back(NV);
6076 }
Andrew Trickac6d9be2013-05-25 02:42:55 +00006077 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
Michael Liao07edaf32012-10-17 23:45:54 +00006078 &Opnds[0], Opnds.size());
6079 }
6080 }
Dan Gohman4e39e9d2010-06-24 14:30:44 +00006081
6082 // Simplify the operands using demanded-bits information.
6083 if (!VT.isVector() &&
6084 SimplifyDemandedBits(SDValue(N, 0)))
6085 return SDValue(N, 0);
6086
Evan Chenge5b51ac2010-04-17 06:13:15 +00006087 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00006088}
6089
Evan Cheng9bfa03c2008-05-12 23:04:07 +00006090static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman475871a2008-07-27 21:46:04 +00006091 SDValue Elt = N->getOperand(i);
Evan Cheng9bfa03c2008-05-12 23:04:07 +00006092 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greifba36cb52008-08-28 21:40:38 +00006093 return Elt.getNode();
6094 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Cheng9bfa03c2008-05-12 23:04:07 +00006095}
6096
6097/// CombineConsecutiveLoads - build_pair (load, load) -> load
Scott Michelfdc40a02009-02-17 22:15:04 +00006098/// if load locations are consecutive.
Owen Andersone50ed302009-08-10 22:56:29 +00006099SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Cheng9bfa03c2008-05-12 23:04:07 +00006100 assert(N->getOpcode() == ISD::BUILD_PAIR);
6101
Nate Begemanabc01992009-06-05 21:37:30 +00006102 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6103 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerfa459012010-09-21 16:08:50 +00006104 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Stephen Hines36b56882014-04-23 16:57:46 -07006105 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman475871a2008-07-27 21:46:04 +00006106 return SDValue();
Owen Andersone50ed302009-08-10 22:56:29 +00006107 EVT LD1VT = LD1->getValueType(0);
Bill Wendling67a67682009-01-30 22:44:24 +00006108
Evan Cheng9bfa03c2008-05-12 23:04:07 +00006109 if (ISD::isNON_EXTLoad(LD2) &&
6110 LD2->hasOneUse() &&
Duncan Sandsd4b9c172008-06-13 19:07:40 +00006111 // If both are volatile this would reduce the number of volatile loads.
6112 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begemanabc01992009-06-05 21:37:30 +00006113 !LD1->isVolatile() &&
6114 !LD2->isVolatile() &&
Evan Cheng64fa4a92009-12-09 01:36:00 +00006115 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begemanabc01992009-06-05 21:37:30 +00006116 unsigned Align = LD1->getAlignment();
Micah Villmow3574eca2012-10-08 16:38:25 +00006117 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson23b9b192009-08-12 00:36:31 +00006118 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling67a67682009-01-30 22:44:24 +00006119
Duncan Sandsd4b9c172008-06-13 19:07:40 +00006120 if (NewAlign <= Align &&
Duncan Sands25cf2272008-11-24 14:53:14 +00006121 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006122 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerfa459012010-09-21 16:08:50 +00006123 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooperd752e0f2011-11-08 18:42:53 +00006124 false, false, false, Align);
Evan Cheng9bfa03c2008-05-12 23:04:07 +00006125 }
Bill Wendling67a67682009-01-30 22:44:24 +00006126
Dan Gohman475871a2008-07-27 21:46:04 +00006127 return SDValue();
Evan Cheng9bfa03c2008-05-12 23:04:07 +00006128}
6129
Wesley Peckbf17cfa2010-11-23 03:31:01 +00006130SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman475871a2008-07-27 21:46:04 +00006131 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00006132 EVT VT = N->getValueType(0);
Chris Lattner94683772005-12-23 05:30:37 +00006133
Dan Gohman7f321562007-06-25 16:23:39 +00006134 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6135 // Only do this before legalize, since afterward the target may be depending
6136 // on the bitconvert.
6137 // First check to see if this is all constant.
Duncan Sands25cf2272008-11-24 14:53:14 +00006138 if (!LegalTypes &&
Gabor Greifba36cb52008-08-28 21:40:38 +00006139 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands83ec4b62008-06-06 12:08:01 +00006140 VT.isVector()) {
Stephen Hines36b56882014-04-23 16:57:46 -07006141 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelfdc40a02009-02-17 22:15:04 +00006142
Owen Andersone50ed302009-08-10 22:56:29 +00006143 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands83ec4b62008-06-06 12:08:01 +00006144 assert(!DestEltVT.isVector() &&
Dan Gohman7f321562007-06-25 16:23:39 +00006145 "Element type of vector ValueType must not be vector!");
Bill Wendling67a67682009-01-30 22:44:24 +00006146 if (isSimple)
Wesley Peckbf17cfa2010-11-23 03:31:01 +00006147 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohman7f321562007-06-25 16:23:39 +00006148 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006149
Dan Gohman3dd168d2008-09-05 01:58:21 +00006150 // If the input is a constant, let getNode fold it.
Chris Lattner94683772005-12-23 05:30:37 +00006151 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006152 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Dan Gohmana407ca12009-08-10 23:15:10 +00006153 if (Res.getNode() != N) {
6154 if (!LegalOperations ||
6155 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6156 return Res;
6157
6158 // Folding it resulted in an illegal node, and it's too late to
6159 // do that. Clean up the old node and forego the transformation.
6160 // Ideally this won't happen very often, because instcombine
6161 // and the earlier dagcombine runs (where illegal nodes are
6162 // permitted) should have folded most of them already.
6163 DAG.DeleteNode(Res.getNode());
6164 }
Chris Lattner94683772005-12-23 05:30:37 +00006165 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006166
Bill Wendling67a67682009-01-30 22:44:24 +00006167 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peckbf17cfa2010-11-23 03:31:01 +00006168 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006169 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling67a67682009-01-30 22:44:24 +00006170 N0.getOperand(0));
Chris Lattner6258fb22006-04-02 02:53:43 +00006171
Chris Lattner57104102005-12-23 05:44:41 +00006172 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng513da432007-10-06 08:19:55 +00006173 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greifba36cb52008-08-28 21:40:38 +00006174 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sandsd4b9c172008-06-13 19:07:40 +00006175 // Do not change the width of a volatile load.
6176 !cast<LoadSDNode>(N0)->isVolatile() &&
Matt Arsenault509a4922013-11-15 04:42:23 +00006177 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6178 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Cheng466685d2006-10-09 20:57:25 +00006179 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmow3574eca2012-10-08 16:38:25 +00006180 unsigned Align = TLI.getDataLayout()->
Owen Anderson23b9b192009-08-12 00:36:31 +00006181 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Cheng59d5b682007-05-07 21:27:48 +00006182 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling67a67682009-01-30 22:44:24 +00006183
Evan Cheng59d5b682007-05-07 21:27:48 +00006184 if (Align <= OrigAlign) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006185 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerfa459012010-09-21 16:08:50 +00006186 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene1e559442010-02-15 17:00:31 +00006187 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00006188 LN0->isInvariant(), OrigAlign,
6189 LN0->getTBAAInfo());
Evan Cheng59d5b682007-05-07 21:27:48 +00006190 AddToWorkList(N);
Gabor Greif12632d22008-08-30 19:29:20 +00006191 CombineTo(N0.getNode(),
Andrew Trickac6d9be2013-05-25 02:42:55 +00006192 DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling67a67682009-01-30 22:44:24 +00006193 N0.getValueType(), Load),
Evan Cheng59d5b682007-05-07 21:27:48 +00006194 Load.getValue(1));
6195 return Load;
6196 }
Chris Lattner57104102005-12-23 05:44:41 +00006197 }
Duncan Sandsd4b9c172008-06-13 19:07:40 +00006198
Bill Wendling67a67682009-01-30 22:44:24 +00006199 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6200 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner3bd39d42008-01-27 17:42:27 +00006201 // This often reduces constant pool loads.
Tom Stellard1f67c632013-07-23 23:55:03 +00006202 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6203 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem91a7e012012-09-13 14:54:28 +00006204 N0.getNode()->hasOneUse() && VT.isInteger() &&
6205 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006206 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling67a67682009-01-30 22:44:24 +00006207 N0.getOperand(0));
Gabor Greifba36cb52008-08-28 21:40:38 +00006208 AddToWorkList(NewConv.getNode());
Scott Michelfdc40a02009-02-17 22:15:04 +00006209
Duncan Sands83ec4b62008-06-06 12:08:01 +00006210 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner3bd39d42008-01-27 17:42:27 +00006211 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006212 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling67a67682009-01-30 22:44:24 +00006213 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner3bd39d42008-01-27 17:42:27 +00006214 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickac6d9be2013-05-25 02:42:55 +00006215 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling67a67682009-01-30 22:44:24 +00006216 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner3bd39d42008-01-27 17:42:27 +00006217 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006218
Bill Wendling67a67682009-01-30 22:44:24 +00006219 // fold (bitconvert (fcopysign cst, x)) ->
6220 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6221 // Note that we don't handle (copysign x, cst) because this can always be
6222 // folded to an fneg or fabs.
Gabor Greifba36cb52008-08-28 21:40:38 +00006223 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattnerf32aac32008-01-27 23:32:17 +00006224 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands83ec4b62008-06-06 12:08:01 +00006225 VT.isInteger() && !VT.isVector()) {
6226 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson23b9b192009-08-12 00:36:31 +00006227 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner2392ae72010-04-15 04:48:01 +00006228 if (isTypeLegal(IntXVT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006229 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling67a67682009-01-30 22:44:24 +00006230 IntXVT, N0.getOperand(1));
Duncan Sands25cf2272008-11-24 14:53:14 +00006231 AddToWorkList(X.getNode());
Chris Lattner3bd39d42008-01-27 17:42:27 +00006232
Duncan Sands25cf2272008-11-24 14:53:14 +00006233 // If X has a different width than the result/lhs, sext it or truncate it.
6234 unsigned VTWidth = VT.getSizeInBits();
6235 if (OrigXWidth < VTWidth) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006236 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Duncan Sands25cf2272008-11-24 14:53:14 +00006237 AddToWorkList(X.getNode());
6238 } else if (OrigXWidth > VTWidth) {
6239 // To get the sign bit in the right place, we have to shift it right
6240 // before truncating.
Andrew Trickac6d9be2013-05-25 02:42:55 +00006241 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling67a67682009-01-30 22:44:24 +00006242 X.getValueType(), X,
Duncan Sands25cf2272008-11-24 14:53:14 +00006243 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6244 AddToWorkList(X.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00006245 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Duncan Sands25cf2272008-11-24 14:53:14 +00006246 AddToWorkList(X.getNode());
6247 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006248
Duncan Sands25cf2272008-11-24 14:53:14 +00006249 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickac6d9be2013-05-25 02:42:55 +00006250 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling67a67682009-01-30 22:44:24 +00006251 X, DAG.getConstant(SignBit, VT));
Duncan Sands25cf2272008-11-24 14:53:14 +00006252 AddToWorkList(X.getNode());
Chris Lattner3bd39d42008-01-27 17:42:27 +00006253
Andrew Trickac6d9be2013-05-25 02:42:55 +00006254 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling67a67682009-01-30 22:44:24 +00006255 VT, N0.getOperand(0));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006256 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling67a67682009-01-30 22:44:24 +00006257 Cst, DAG.getConstant(~SignBit, VT));
Duncan Sands25cf2272008-11-24 14:53:14 +00006258 AddToWorkList(Cst.getNode());
Chris Lattner3bd39d42008-01-27 17:42:27 +00006259
Andrew Trickac6d9be2013-05-25 02:42:55 +00006260 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sands25cf2272008-11-24 14:53:14 +00006261 }
Chris Lattner3bd39d42008-01-27 17:42:27 +00006262 }
Evan Cheng9bfa03c2008-05-12 23:04:07 +00006263
Sylvestre Ledru94c22712012-09-27 10:14:43 +00006264 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Cheng9bfa03c2008-05-12 23:04:07 +00006265 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greifba36cb52008-08-28 21:40:38 +00006266 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6267 if (CombineLD.getNode())
Evan Cheng9bfa03c2008-05-12 23:04:07 +00006268 return CombineLD;
6269 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006270
Dan Gohman475871a2008-07-27 21:46:04 +00006271 return SDValue();
Chris Lattner94683772005-12-23 05:30:37 +00006272}
6273
Dan Gohman475871a2008-07-27 21:46:04 +00006274SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Andersone50ed302009-08-10 22:56:29 +00006275 EVT VT = N->getValueType(0);
Evan Cheng9bfa03c2008-05-12 23:04:07 +00006276 return CombineConsecutiveLoads(N, VT);
6277}
6278
Wesley Peckbf17cfa2010-11-23 03:31:01 +00006279/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
Scott Michelfdc40a02009-02-17 22:15:04 +00006280/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
Chris Lattner6258fb22006-04-02 02:53:43 +00006281/// destination element value type.
Dan Gohman475871a2008-07-27 21:46:04 +00006282SDValue DAGCombiner::
Wesley Peckbf17cfa2010-11-23 03:31:01 +00006283ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Andersone50ed302009-08-10 22:56:29 +00006284 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelfdc40a02009-02-17 22:15:04 +00006285
Chris Lattner6258fb22006-04-02 02:53:43 +00006286 // If this is already the right type, we're done.
Dan Gohman475871a2008-07-27 21:46:04 +00006287 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelfdc40a02009-02-17 22:15:04 +00006288
Duncan Sands83ec4b62008-06-06 12:08:01 +00006289 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6290 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelfdc40a02009-02-17 22:15:04 +00006291
Chris Lattner6258fb22006-04-02 02:53:43 +00006292 // If this is a conversion of N elements of one type to N elements of another
6293 // type, convert each element. This handles FP<->INT cases.
6294 if (SrcBitSize == DstBitSize) {
Nate Begemane0efc212010-07-27 18:02:18 +00006295 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6296 BV->getValueType(0).getVectorNumElements());
6297
6298 // Due to the FP element handling below calling this routine recursively,
6299 // we can end up with a scalar-to-vector node here.
6300 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006301 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6302 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begemane0efc212010-07-27 18:02:18 +00006303 DstEltVT, BV->getOperand(0)));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00006304
Dan Gohman475871a2008-07-27 21:46:04 +00006305 SmallVector<SDValue, 8> Ops;
Dan Gohman7f321562007-06-25 16:23:39 +00006306 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilsonb1303d02009-04-13 22:05:19 +00006307 SDValue Op = BV->getOperand(i);
6308 // If the vector element type is not legal, the BUILD_VECTOR operands
6309 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonc8851652009-04-20 17:27:09 +00006310 if (Op.getValueType() != SrcEltVT)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006311 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6312 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilsonb1303d02009-04-13 22:05:19 +00006313 DstEltVT, Op));
Gabor Greifba36cb52008-08-28 21:40:38 +00006314 AddToWorkList(Ops.back().getNode());
Chris Lattner3e104b12006-04-08 04:15:24 +00006315 }
Andrew Trickac6d9be2013-05-25 02:42:55 +00006316 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga87008d2009-02-25 22:49:59 +00006317 &Ops[0], Ops.size());
Chris Lattner6258fb22006-04-02 02:53:43 +00006318 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006319
Chris Lattner6258fb22006-04-02 02:53:43 +00006320 // Otherwise, we're growing or shrinking the elements. To avoid having to
6321 // handle annoying details of growing/shrinking FP values, we convert them to
6322 // int first.
Duncan Sands83ec4b62008-06-06 12:08:01 +00006323 if (SrcEltVT.isFloatingPoint()) {
Chris Lattner6258fb22006-04-02 02:53:43 +00006324 // Convert the input float vector to a int vector where the elements are the
6325 // same sizes.
Owen Anderson825b72b2009-08-11 20:47:22 +00006326 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson23b9b192009-08-12 00:36:31 +00006327 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peckbf17cfa2010-11-23 03:31:01 +00006328 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattner6258fb22006-04-02 02:53:43 +00006329 SrcEltVT = IntVT;
6330 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006331
Chris Lattner6258fb22006-04-02 02:53:43 +00006332 // Now we know the input is an integer vector. If the output is a FP type,
6333 // convert to integer first, then to FP of the right size.
Duncan Sands83ec4b62008-06-06 12:08:01 +00006334 if (DstEltVT.isFloatingPoint()) {
Owen Anderson825b72b2009-08-11 20:47:22 +00006335 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson23b9b192009-08-12 00:36:31 +00006336 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peckbf17cfa2010-11-23 03:31:01 +00006337 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelfdc40a02009-02-17 22:15:04 +00006338
Chris Lattner6258fb22006-04-02 02:53:43 +00006339 // Next, convert to FP elements of the same size.
Wesley Peckbf17cfa2010-11-23 03:31:01 +00006340 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattner6258fb22006-04-02 02:53:43 +00006341 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006342
Chris Lattner6258fb22006-04-02 02:53:43 +00006343 // Okay, we know the src/dst types are both integers of differing types.
6344 // Handling growing first.
Duncan Sands83ec4b62008-06-06 12:08:01 +00006345 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattner6258fb22006-04-02 02:53:43 +00006346 if (SrcBitSize < DstBitSize) {
6347 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelfdc40a02009-02-17 22:15:04 +00006348
Dan Gohman475871a2008-07-27 21:46:04 +00006349 SmallVector<SDValue, 8> Ops;
Dan Gohman7f321562007-06-25 16:23:39 +00006350 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattner6258fb22006-04-02 02:53:43 +00006351 i += NumInputsPerOutput) {
6352 bool isLE = TLI.isLittleEndian();
Dan Gohman220a8232008-03-03 23:51:38 +00006353 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattner6258fb22006-04-02 02:53:43 +00006354 bool EltIsUndef = true;
6355 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6356 // Shift the previously computed bits over.
6357 NewBits <<= SrcBitSize;
Dan Gohman475871a2008-07-27 21:46:04 +00006358 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattner6258fb22006-04-02 02:53:43 +00006359 if (Op.getOpcode() == ISD::UNDEF) continue;
6360 EltIsUndef = false;
Scott Michelfdc40a02009-02-17 22:15:04 +00006361
Jay Foad40f8f622010-12-07 08:25:19 +00006362 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohman58c25872010-04-12 02:24:01 +00006363 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattner6258fb22006-04-02 02:53:43 +00006364 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006365
Chris Lattner6258fb22006-04-02 02:53:43 +00006366 if (EltIsUndef)
Dale Johannesene8d72302009-02-06 23:05:02 +00006367 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattner6258fb22006-04-02 02:53:43 +00006368 else
6369 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6370 }
6371
Owen Anderson23b9b192009-08-12 00:36:31 +00006372 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Andrew Trickac6d9be2013-05-25 02:42:55 +00006373 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga87008d2009-02-25 22:49:59 +00006374 &Ops[0], Ops.size());
Chris Lattner6258fb22006-04-02 02:53:43 +00006375 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006376
Chris Lattner6258fb22006-04-02 02:53:43 +00006377 // Finally, this must be the case where we are shrinking elements: each input
6378 // turns into multiple outputs.
Evan Chengefec7512008-02-18 23:04:32 +00006379 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattner6258fb22006-04-02 02:53:43 +00006380 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson23b9b192009-08-12 00:36:31 +00006381 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6382 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman475871a2008-07-27 21:46:04 +00006383 SmallVector<SDValue, 8> Ops;
Bill Wendlingb0162f52009-01-30 22:53:48 +00006384
Dan Gohman7f321562007-06-25 16:23:39 +00006385 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattner6258fb22006-04-02 02:53:43 +00006386 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6387 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesene8d72302009-02-06 23:05:02 +00006388 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattner6258fb22006-04-02 02:53:43 +00006389 continue;
6390 }
Bill Wendlingb0162f52009-01-30 22:53:48 +00006391
Jay Foad40f8f622010-12-07 08:25:19 +00006392 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6393 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingb0162f52009-01-30 22:53:48 +00006394
Chris Lattner6258fb22006-04-02 02:53:43 +00006395 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad40f8f622010-12-07 08:25:19 +00006396 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattner6258fb22006-04-02 02:53:43 +00006397 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad40f8f622010-12-07 08:25:19 +00006398 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Chengefec7512008-02-18 23:04:32 +00006399 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickac6d9be2013-05-25 02:42:55 +00006400 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingb0162f52009-01-30 22:53:48 +00006401 Ops[0]);
Dan Gohman220a8232008-03-03 23:51:38 +00006402 OpVal = OpVal.lshr(DstBitSize);
Chris Lattner6258fb22006-04-02 02:53:43 +00006403 }
6404
6405 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands0753fc12008-02-11 10:37:04 +00006406 if (TLI.isBigEndian())
Chris Lattner6258fb22006-04-02 02:53:43 +00006407 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6408 }
Bill Wendlingb0162f52009-01-30 22:53:48 +00006409
Andrew Trickac6d9be2013-05-25 02:42:55 +00006410 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga87008d2009-02-25 22:49:59 +00006411 &Ops[0], Ops.size());
Chris Lattner6258fb22006-04-02 02:53:43 +00006412}
6413
Dan Gohman475871a2008-07-27 21:46:04 +00006414SDValue DAGCombiner::visitFADD(SDNode *N) {
6415 SDValue N0 = N->getOperand(0);
6416 SDValue N1 = N->getOperand(1);
Nate Begemana0e221d2005-10-18 00:28:13 +00006417 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6418 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00006419 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00006420
Dan Gohman7f321562007-06-25 16:23:39 +00006421 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00006422 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00006423 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00006424 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman05d92fe2007-07-13 20:03:40 +00006425 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006426
Lang Hames01806942012-06-14 20:37:15 +00006427 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigande669c932012-10-29 18:35:49 +00006428 if (N0CFP && N1CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006429 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Nate Begemana0e221d2005-10-18 00:28:13 +00006430 // canonicalize constant to RHS
6431 if (N0CFP && !N1CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006432 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Bill Wendlingb0162f52009-01-30 22:53:48 +00006433 // fold (fadd A, 0) -> A
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006434 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6435 N1CFP->getValueAPF().isZero())
Dan Gohman760f86f2009-01-22 21:58:43 +00006436 return N0;
Bill Wendlingb0162f52009-01-30 22:53:48 +00006437 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Andersonafd3d562012-03-06 00:29:31 +00006438 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem6dfabb62012-09-20 08:53:31 +00006439 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006440 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sands25cf2272008-11-24 14:53:14 +00006441 GetNegatedExpression(N1, DAG, LegalOperations));
Bill Wendlingb0162f52009-01-30 22:53:48 +00006442 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Andersonafd3d562012-03-06 00:29:31 +00006443 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem6dfabb62012-09-20 08:53:31 +00006444 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006445 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sands25cf2272008-11-24 14:53:14 +00006446 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelfdc40a02009-02-17 22:15:04 +00006447
Chris Lattnerddae4bd2007-01-08 23:04:05 +00006448 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006449 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6450 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6451 isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006452 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6453 DAG.getNode(ISD::FADD, SDLoc(N), VT,
Bill Wendlingfc4b6772009-02-01 11:19:36 +00006454 N0.getOperand(1), N1));
Scott Michelfdc40a02009-02-17 22:15:04 +00006455
Shuxin Yang1cd1d022013-03-25 22:52:29 +00006456 // No FP constant should be created after legalization as Instruction
6457 // Selection pass has hard time in dealing with FP constant.
6458 //
6459 // We don't need test this condition for transformation like following, as
6460 // the DAG being transformed implies it is legal to take FP constant as
6461 // operand.
Stephen Lin155615d2013-07-08 00:37:03 +00006462 //
Shuxin Yang1cd1d022013-03-25 22:52:29 +00006463 // (fadd (fmul c, x), x) -> (fmul c+1, x)
Stephen Lin155615d2013-07-08 00:37:03 +00006464 //
Shuxin Yang1cd1d022013-03-25 22:52:29 +00006465 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6466
Owen Anderson607ebde2012-11-01 02:00:53 +00006467 // If allow, fold (fadd (fneg x), x) -> 0.0
Shuxin Yang1cd1d022013-03-25 22:52:29 +00006468 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Linb4940152013-07-09 00:44:49 +00006469 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
Owen Anderson607ebde2012-11-01 02:00:53 +00006470 return DAG.getConstantFP(0.0, VT);
Owen Anderson607ebde2012-11-01 02:00:53 +00006471
6472 // If allow, fold (fadd x, (fneg x)) -> 0.0
Shuxin Yang1cd1d022013-03-25 22:52:29 +00006473 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Linb4940152013-07-09 00:44:49 +00006474 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
Owen Anderson607ebde2012-11-01 02:00:53 +00006475 return DAG.getConstantFP(0.0, VT);
Owen Anderson607ebde2012-11-01 02:00:53 +00006476
Owen Anderson43da6c72012-08-30 23:35:16 +00006477 // In unsafe math mode, we can fold chains of FADD's of the same value
6478 // into multiplications. This transform is not safe in general because
6479 // we are reducing the number of rounding steps.
6480 if (DAG.getTarget().Options.UnsafeFPMath &&
6481 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6482 !N0CFP && !N1CFP) {
6483 if (N0.getOpcode() == ISD::FMUL) {
6484 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6485 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6486
Stephen Lin38103d12013-06-14 18:17:35 +00006487 // (fadd (fmul c, x), x) -> (fmul x, c+1)
Owen Anderson43da6c72012-08-30 23:35:16 +00006488 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006489 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006490 SDValue(CFP00, 0),
6491 DAG.getConstantFP(1.0, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006492 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006493 N1, NewCFP);
6494 }
6495
Stephen Lin38103d12013-06-14 18:17:35 +00006496 // (fadd (fmul x, c), x) -> (fmul x, c+1)
Owen Anderson43da6c72012-08-30 23:35:16 +00006497 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006498 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006499 SDValue(CFP01, 0),
6500 DAG.getConstantFP(1.0, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006501 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006502 N1, NewCFP);
6503 }
6504
Stephen Lin38103d12013-06-14 18:17:35 +00006505 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
Owen Anderson43da6c72012-08-30 23:35:16 +00006506 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6507 N1.getOperand(0) == N1.getOperand(1) &&
6508 N0.getOperand(1) == N1.getOperand(0)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006509 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006510 SDValue(CFP00, 0),
6511 DAG.getConstantFP(2.0, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006512 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006513 N0.getOperand(1), NewCFP);
6514 }
6515
Stephen Lin38103d12013-06-14 18:17:35 +00006516 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
Owen Anderson43da6c72012-08-30 23:35:16 +00006517 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6518 N1.getOperand(0) == N1.getOperand(1) &&
6519 N0.getOperand(0) == N1.getOperand(0)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006520 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006521 SDValue(CFP01, 0),
6522 DAG.getConstantFP(2.0, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006523 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006524 N0.getOperand(0), NewCFP);
6525 }
6526 }
6527
6528 if (N1.getOpcode() == ISD::FMUL) {
6529 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6530 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6531
Stephen Lin38103d12013-06-14 18:17:35 +00006532 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
Owen Anderson43da6c72012-08-30 23:35:16 +00006533 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006534 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006535 SDValue(CFP10, 0),
6536 DAG.getConstantFP(1.0, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006537 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006538 N0, NewCFP);
6539 }
6540
Stephen Lin38103d12013-06-14 18:17:35 +00006541 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
Owen Anderson43da6c72012-08-30 23:35:16 +00006542 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006543 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006544 SDValue(CFP11, 0),
6545 DAG.getConstantFP(1.0, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006546 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006547 N0, NewCFP);
6548 }
6549
Owen Anderson43da6c72012-08-30 23:35:16 +00006550
Stephen Lin38103d12013-06-14 18:17:35 +00006551 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6552 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6553 N0.getOperand(0) == N0.getOperand(1) &&
6554 N1.getOperand(1) == N0.getOperand(0)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006555 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006556 SDValue(CFP10, 0),
6557 DAG.getConstantFP(2.0, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006558 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Lin38103d12013-06-14 18:17:35 +00006559 N1.getOperand(1), NewCFP);
Owen Anderson43da6c72012-08-30 23:35:16 +00006560 }
6561
Stephen Lin38103d12013-06-14 18:17:35 +00006562 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6563 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6564 N0.getOperand(0) == N0.getOperand(1) &&
6565 N1.getOperand(0) == N0.getOperand(0)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006566 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006567 SDValue(CFP11, 0),
6568 DAG.getConstantFP(2.0, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006569 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Lin38103d12013-06-14 18:17:35 +00006570 N1.getOperand(0), NewCFP);
Owen Anderson43da6c72012-08-30 23:35:16 +00006571 }
6572 }
6573
Shuxin Yang1cd1d022013-03-25 22:52:29 +00006574 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yang98b93e52013-02-02 00:22:03 +00006575 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
Stephen Lina553bed2013-06-14 21:33:58 +00006576 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
Shuxin Yang98b93e52013-02-02 00:22:03 +00006577 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
Stephen Linb4940152013-07-09 00:44:49 +00006578 (N0.getOperand(0) == N1))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006579 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yang98b93e52013-02-02 00:22:03 +00006580 N1, DAG.getConstantFP(3.0, VT));
Shuxin Yang98b93e52013-02-02 00:22:03 +00006581 }
6582
Shuxin Yang1cd1d022013-03-25 22:52:29 +00006583 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yang98b93e52013-02-02 00:22:03 +00006584 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
Stephen Lina553bed2013-06-14 21:33:58 +00006585 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
Shuxin Yang98b93e52013-02-02 00:22:03 +00006586 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
Stephen Linb4940152013-07-09 00:44:49 +00006587 N1.getOperand(0) == N0)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006588 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yang98b93e52013-02-02 00:22:03 +00006589 N0, DAG.getConstantFP(3.0, VT));
Shuxin Yang98b93e52013-02-02 00:22:03 +00006590 }
6591
Stephen Lina553bed2013-06-14 21:33:58 +00006592 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
Shuxin Yang1cd1d022013-03-25 22:52:29 +00006593 if (AllowNewFpConst &&
6594 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Owen Anderson43da6c72012-08-30 23:35:16 +00006595 N0.getOperand(0) == N0.getOperand(1) &&
6596 N1.getOperand(0) == N1.getOperand(1) &&
Stephen Linb4940152013-07-09 00:44:49 +00006597 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006598 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006599 N0.getOperand(0),
6600 DAG.getConstantFP(4.0, VT));
Owen Anderson43da6c72012-08-30 23:35:16 +00006601 }
6602
Lang Hamesd693caf2012-06-19 22:51:23 +00006603 // FADD -> FMA combines:
Lang Hamese0231412012-06-22 01:09:09 +00006604 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hamesd693caf2012-06-19 22:51:23 +00006605 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Line54885a2013-07-09 18:16:56 +00006606 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6607 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hamesd693caf2012-06-19 22:51:23 +00006608
6609 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Stephen Linb4940152013-07-09 00:44:49 +00006610 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Andrew Trickac6d9be2013-05-25 02:42:55 +00006611 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hamesd693caf2012-06-19 22:51:23 +00006612 N0.getOperand(0), N0.getOperand(1), N1);
Owen Anderson43da6c72012-08-30 23:35:16 +00006613
Michael Liaob79bff52012-09-01 04:09:16 +00006614 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hamesd693caf2012-06-19 22:51:23 +00006615 // Note: Commutes FADD operands.
Stephen Linb4940152013-07-09 00:44:49 +00006616 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Andrew Trickac6d9be2013-05-25 02:42:55 +00006617 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hamesd693caf2012-06-19 22:51:23 +00006618 N1.getOperand(0), N1.getOperand(1), N0);
Lang Hamesd693caf2012-06-19 22:51:23 +00006619 }
6620
Dan Gohman475871a2008-07-27 21:46:04 +00006621 return SDValue();
Chris Lattner01b3d732005-09-28 22:28:18 +00006622}
6623
Dan Gohman475871a2008-07-27 21:46:04 +00006624SDValue DAGCombiner::visitFSUB(SDNode *N) {
6625 SDValue N0 = N->getOperand(0);
6626 SDValue N1 = N->getOperand(1);
Nate Begemana0e221d2005-10-18 00:28:13 +00006627 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6628 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00006629 EVT VT = N->getValueType(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00006630 SDLoc dl(N);
Scott Michelfdc40a02009-02-17 22:15:04 +00006631
Dan Gohman7f321562007-06-25 16:23:39 +00006632 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00006633 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00006634 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00006635 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman05d92fe2007-07-13 20:03:40 +00006636 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006637
Nate Begemana0e221d2005-10-18 00:28:13 +00006638 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigande669c932012-10-29 18:35:49 +00006639 if (N0CFP && N1CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006640 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Bill Wendlingb0162f52009-01-30 22:53:48 +00006641 // fold (fsub A, 0) -> A
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006642 if (DAG.getTarget().Options.UnsafeFPMath &&
6643 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohmana90c8e62009-01-23 19:10:37 +00006644 return N0;
Bill Wendlingb0162f52009-01-30 22:53:48 +00006645 // fold (fsub 0, B) -> -B
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006646 if (DAG.getTarget().Options.UnsafeFPMath &&
6647 N0CFP && N0CFP->getValueAPF().isZero()) {
Owen Andersonafd3d562012-03-06 00:29:31 +00006648 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Duncan Sands25cf2272008-11-24 14:53:14 +00006649 return GetNegatedExpression(N1, DAG, LegalOperations);
Dan Gohman760f86f2009-01-22 21:58:43 +00006650 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Elena Demikhovsky1503aba2012-08-01 12:06:00 +00006651 return DAG.getNode(ISD::FNEG, dl, VT, N1);
Dan Gohman23ff1822007-07-02 15:48:56 +00006652 }
Bill Wendlingb0162f52009-01-30 22:53:48 +00006653 // fold (fsub A, (fneg B)) -> (fadd A, B)
Owen Andersonafd3d562012-03-06 00:29:31 +00006654 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Elena Demikhovsky1503aba2012-08-01 12:06:00 +00006655 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sands25cf2272008-11-24 14:53:14 +00006656 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelfdc40a02009-02-17 22:15:04 +00006657
Bill Wendling5a894342012-03-15 05:12:00 +00006658 // If 'unsafe math' is enabled, fold
Owen Anderson713e9532012-05-07 20:51:25 +00006659 // (fsub x, x) -> 0.0 &
Bill Wendling5a894342012-03-15 05:12:00 +00006660 // (fsub x, (fadd x, y)) -> (fneg y) &
6661 // (fsub x, (fadd y, x)) -> (fneg y)
6662 if (DAG.getTarget().Options.UnsafeFPMath) {
Owen Anderson713e9532012-05-07 20:51:25 +00006663 if (N0 == N1)
6664 return DAG.getConstantFP(0.0f, VT);
6665
Bill Wendling5a894342012-03-15 05:12:00 +00006666 if (N1.getOpcode() == ISD::FADD) {
6667 SDValue N10 = N1->getOperand(0);
6668 SDValue N11 = N1->getOperand(1);
6669
6670 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6671 &DAG.getTarget().Options))
6672 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin75d13062013-07-10 20:47:39 +00006673
Stephen Linb4940152013-07-09 00:44:49 +00006674 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6675 &DAG.getTarget().Options))
Bill Wendling5a894342012-03-15 05:12:00 +00006676 return GetNegatedExpression(N10, DAG, LegalOperations);
6677 }
6678 }
6679
Lang Hamesd693caf2012-06-19 22:51:23 +00006680 // FSUB -> FMA combines:
Lang Hamese0231412012-06-22 01:09:09 +00006681 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hamesd693caf2012-06-19 22:51:23 +00006682 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Line54885a2013-07-09 18:16:56 +00006683 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6684 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hamesd693caf2012-06-19 22:51:23 +00006685
6686 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Stephen Linb4940152013-07-09 00:44:49 +00006687 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Elena Demikhovsky1503aba2012-08-01 12:06:00 +00006688 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hamesd693caf2012-06-19 22:51:23 +00006689 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky1503aba2012-08-01 12:06:00 +00006690 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hamesd693caf2012-06-19 22:51:23 +00006691
6692 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6693 // Note: Commutes FSUB operands.
Stephen Lin75d13062013-07-10 20:47:39 +00006694 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Elena Demikhovsky1503aba2012-08-01 12:06:00 +00006695 return DAG.getNode(ISD::FMA, dl, VT,
6696 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hamesd693caf2012-06-19 22:51:23 +00006697 N1.getOperand(0)),
6698 N1.getOperand(1), N0);
Elena Demikhovsky1503aba2012-08-01 12:06:00 +00006699
Stephen Linb4940152013-07-09 00:44:49 +00006700 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lin155615d2013-07-08 00:37:03 +00006701 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky1503aba2012-08-01 12:06:00 +00006702 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6703 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6704 SDValue N00 = N0.getOperand(0).getOperand(0);
6705 SDValue N01 = N0.getOperand(0).getOperand(1);
6706 return DAG.getNode(ISD::FMA, dl, VT,
6707 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6708 DAG.getNode(ISD::FNEG, dl, VT, N1));
6709 }
Lang Hamesd693caf2012-06-19 22:51:23 +00006710 }
6711
Dan Gohman475871a2008-07-27 21:46:04 +00006712 return SDValue();
Chris Lattner01b3d732005-09-28 22:28:18 +00006713}
6714
Dan Gohman475871a2008-07-27 21:46:04 +00006715SDValue DAGCombiner::visitFMUL(SDNode *N) {
6716 SDValue N0 = N->getOperand(0);
6717 SDValue N1 = N->getOperand(1);
Nate Begeman11af4ea2005-10-17 20:40:11 +00006718 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6719 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00006720 EVT VT = N->getValueType(0);
Owen Andersonafd3d562012-03-06 00:29:31 +00006721 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner01b3d732005-09-28 22:28:18 +00006722
Dan Gohman7f321562007-06-25 16:23:39 +00006723 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00006724 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00006725 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00006726 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman05d92fe2007-07-13 20:03:40 +00006727 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006728
Nate Begeman11af4ea2005-10-17 20:40:11 +00006729 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigande669c932012-10-29 18:35:49 +00006730 if (N0CFP && N1CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006731 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Nate Begeman11af4ea2005-10-17 20:40:11 +00006732 // canonicalize constant to RHS
Nate Begemana0e221d2005-10-18 00:28:13 +00006733 if (N0CFP && !N1CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006734 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Bill Wendlinga03e74b2009-01-30 22:57:07 +00006735 // fold (fmul A, 0) -> 0
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006736 if (DAG.getTarget().Options.UnsafeFPMath &&
6737 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman760f86f2009-01-22 21:58:43 +00006738 return N1;
Dan Gohman77b81fe2009-06-04 17:12:12 +00006739 // fold (fmul A, 0) -> 0, vector edition.
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006740 if (DAG.getTarget().Options.UnsafeFPMath &&
6741 ISD::isBuildVectorAllZeros(N1.getNode()))
Dan Gohman77b81fe2009-06-04 17:12:12 +00006742 return N1;
Owen Anderson363e4b92012-05-02 21:32:35 +00006743 // fold (fmul A, 1.0) -> A
6744 if (N1CFP && N1CFP->isExactlyValue(1.0))
6745 return N0;
Nate Begeman11af4ea2005-10-17 20:40:11 +00006746 // fold (fmul X, 2.0) -> (fadd X, X)
6747 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006748 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Dan Gohmaneb1fedc2009-08-10 16:50:32 +00006749 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattner29446522007-05-14 22:04:50 +00006750 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman760f86f2009-01-22 21:58:43 +00006751 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006752 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +00006753
Bill Wendlinga03e74b2009-01-30 22:57:07 +00006754 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Owen Andersonafd3d562012-03-06 00:29:31 +00006755 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006756 &DAG.getTarget().Options)) {
Stephen Lin155615d2013-07-08 00:37:03 +00006757 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006758 &DAG.getTarget().Options)) {
Chris Lattner29446522007-05-14 22:04:50 +00006759 // Both can be negated for free, check to see if at least one is cheaper
6760 // negated.
6761 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006762 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sands25cf2272008-11-24 14:53:14 +00006763 GetNegatedExpression(N0, DAG, LegalOperations),
6764 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattner29446522007-05-14 22:04:50 +00006765 }
6766 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006767
Chris Lattnerddae4bd2007-01-08 23:04:05 +00006768 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006769 if (DAG.getTarget().Options.UnsafeFPMath &&
6770 N1CFP && N0.getOpcode() == ISD::FMUL &&
Gabor Greifba36cb52008-08-28 21:40:38 +00006771 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006772 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6773 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Dale Johannesende064702009-02-06 21:50:26 +00006774 N0.getOperand(1), N1));
Scott Michelfdc40a02009-02-17 22:15:04 +00006775
Dan Gohman475871a2008-07-27 21:46:04 +00006776 return SDValue();
Chris Lattner01b3d732005-09-28 22:28:18 +00006777}
6778
Owen Anderson062c0a52012-05-02 22:17:40 +00006779SDValue DAGCombiner::visitFMA(SDNode *N) {
6780 SDValue N0 = N->getOperand(0);
6781 SDValue N1 = N->getOperand(1);
6782 SDValue N2 = N->getOperand(2);
6783 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6784 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6785 EVT VT = N->getValueType(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00006786 SDLoc dl(N);
Owen Anderson062c0a52012-05-02 22:17:40 +00006787
Owen Anderson607ebde2012-11-01 02:00:53 +00006788 if (DAG.getTarget().Options.UnsafeFPMath) {
6789 if (N0CFP && N0CFP->isZero())
6790 return N2;
6791 if (N1CFP && N1CFP->isZero())
6792 return N2;
6793 }
Owen Anderson062c0a52012-05-02 22:17:40 +00006794 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006795 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson062c0a52012-05-02 22:17:40 +00006796 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006797 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson062c0a52012-05-02 22:17:40 +00006798
Owen Anderson85ef6f42012-05-30 18:50:39 +00006799 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Andersonf917d202012-05-30 18:54:50 +00006800 if (N0CFP && !N1CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006801 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Anderson85ef6f42012-05-30 18:50:39 +00006802
Owen Anderson58d57292012-09-01 06:04:27 +00006803 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6804 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6805 N2.getOpcode() == ISD::FMUL &&
6806 N0 == N2.getOperand(0) &&
6807 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6808 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6809 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6810 }
6811
6812
6813 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6814 if (DAG.getTarget().Options.UnsafeFPMath &&
6815 N0.getOpcode() == ISD::FMUL && N1CFP &&
6816 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6817 return DAG.getNode(ISD::FMA, dl, VT,
6818 N0.getOperand(0),
6819 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6820 N2);
6821 }
6822
6823 // (fma x, 1, y) -> (fadd x, y)
6824 // (fma x, -1, y) -> (fadd (fneg x), y)
6825 if (N1CFP) {
6826 if (N1CFP->isExactlyValue(1.0))
6827 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6828
6829 if (N1CFP->isExactlyValue(-1.0) &&
6830 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6831 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6832 AddToWorkList(RHSNeg.getNode());
6833 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6834 }
6835 }
6836
6837 // (fma x, c, x) -> (fmul x, (c+1))
Stephen Linb4940152013-07-09 00:44:49 +00006838 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6839 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson58d57292012-09-01 06:04:27 +00006840 DAG.getNode(ISD::FADD, dl, VT,
6841 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson58d57292012-09-01 06:04:27 +00006842
6843 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6844 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
Stephen Linb4940152013-07-09 00:44:49 +00006845 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6846 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson58d57292012-09-01 06:04:27 +00006847 DAG.getNode(ISD::FADD, dl, VT,
6848 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson58d57292012-09-01 06:04:27 +00006849
6850
Owen Anderson062c0a52012-05-02 22:17:40 +00006851 return SDValue();
6852}
6853
Dan Gohman475871a2008-07-27 21:46:04 +00006854SDValue DAGCombiner::visitFDIV(SDNode *N) {
6855 SDValue N0 = N->getOperand(0);
6856 SDValue N1 = N->getOperand(1);
Nate Begemana148d982006-01-18 22:35:16 +00006857 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6858 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00006859 EVT VT = N->getValueType(0);
Owen Andersonafd3d562012-03-06 00:29:31 +00006860 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner01b3d732005-09-28 22:28:18 +00006861
Dan Gohman7f321562007-06-25 16:23:39 +00006862 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00006863 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00006864 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00006865 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman05d92fe2007-07-13 20:03:40 +00006866 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006867
Nate Begemana148d982006-01-18 22:35:16 +00006868 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigande669c932012-10-29 18:35:49 +00006869 if (N0CFP && N1CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006870 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelfdc40a02009-02-17 22:15:04 +00006871
Duncan Sands3ef3fcf2012-04-08 18:08:12 +00006872 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
Ulrich Weigande669c932012-10-29 18:35:49 +00006873 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
Duncan Sands961d6662012-04-07 20:04:00 +00006874 // Compute the reciprocal 1.0 / c2.
6875 APFloat N1APF = N1CFP->getValueAPF();
6876 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6877 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
Duncan Sands507bb7a2012-04-10 20:35:27 +00006878 // Only do the transform if the reciprocal is a legal fp immediate that
6879 // isn't too nasty (eg NaN, denormal, ...).
6880 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
Anton Korobeynikov999821c2012-04-10 13:22:49 +00006881 (!LegalOperations ||
6882 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6883 // backend)... we should handle this gracefully after Legalize.
6884 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6885 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6886 TLI.isFPImmLegal(Recip, VT)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006887 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
Duncan Sands961d6662012-04-07 20:04:00 +00006888 DAG.getConstantFP(Recip, VT));
6889 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006890
Bill Wendlinga03e74b2009-01-30 22:57:07 +00006891 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Owen Andersonafd3d562012-03-06 00:29:31 +00006892 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006893 &DAG.getTarget().Options)) {
Owen Andersonafd3d562012-03-06 00:29:31 +00006894 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006895 &DAG.getTarget().Options)) {
Chris Lattner29446522007-05-14 22:04:50 +00006896 // Both can be negated for free, check to see if at least one is cheaper
6897 // negated.
6898 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006899 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sands25cf2272008-11-24 14:53:14 +00006900 GetNegatedExpression(N0, DAG, LegalOperations),
6901 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattner29446522007-05-14 22:04:50 +00006902 }
6903 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006904
Dan Gohman475871a2008-07-27 21:46:04 +00006905 return SDValue();
Chris Lattner01b3d732005-09-28 22:28:18 +00006906}
6907
Dan Gohman475871a2008-07-27 21:46:04 +00006908SDValue DAGCombiner::visitFREM(SDNode *N) {
6909 SDValue N0 = N->getOperand(0);
6910 SDValue N1 = N->getOperand(1);
Nate Begemana148d982006-01-18 22:35:16 +00006911 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6912 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00006913 EVT VT = N->getValueType(0);
Chris Lattner01b3d732005-09-28 22:28:18 +00006914
Nate Begemana148d982006-01-18 22:35:16 +00006915 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigande669c932012-10-29 18:35:49 +00006916 if (N0CFP && N1CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006917 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohman7f321562007-06-25 16:23:39 +00006918
Dan Gohman475871a2008-07-27 21:46:04 +00006919 return SDValue();
Chris Lattner01b3d732005-09-28 22:28:18 +00006920}
6921
Dan Gohman475871a2008-07-27 21:46:04 +00006922SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6923 SDValue N0 = N->getOperand(0);
6924 SDValue N1 = N->getOperand(1);
Chris Lattner12d83032006-03-05 05:30:57 +00006925 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6926 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00006927 EVT VT = N->getValueType(0);
Chris Lattner12d83032006-03-05 05:30:57 +00006928
Ulrich Weigande669c932012-10-29 18:35:49 +00006929 if (N0CFP && N1CFP) // Constant fold
Andrew Trickac6d9be2013-05-25 02:42:55 +00006930 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelfdc40a02009-02-17 22:15:04 +00006931
Chris Lattner12d83032006-03-05 05:30:57 +00006932 if (N1CFP) {
Dale Johannesene6c17422007-08-26 01:18:27 +00006933 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru94c22712012-09-27 10:14:43 +00006934 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6935 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman760f86f2009-01-22 21:58:43 +00006936 if (!V.isNegative()) {
6937 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006938 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman760f86f2009-01-22 21:58:43 +00006939 } else {
6940 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006941 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6942 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman760f86f2009-01-22 21:58:43 +00006943 }
Chris Lattner12d83032006-03-05 05:30:57 +00006944 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006945
Chris Lattner12d83032006-03-05 05:30:57 +00006946 // copysign(fabs(x), y) -> copysign(x, y)
6947 // copysign(fneg(x), y) -> copysign(x, y)
6948 // copysign(copysign(x,z), y) -> copysign(x, y)
6949 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6950 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006951 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0225a1d2009-01-30 23:15:49 +00006952 N0.getOperand(0), N1);
Chris Lattner12d83032006-03-05 05:30:57 +00006953
6954 // copysign(x, abs(y)) -> abs(x)
6955 if (N1.getOpcode() == ISD::FABS)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006956 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +00006957
Chris Lattner12d83032006-03-05 05:30:57 +00006958 // copysign(x, copysign(y,z)) -> copysign(x, z)
6959 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006960 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0225a1d2009-01-30 23:15:49 +00006961 N0, N1.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00006962
Chris Lattner12d83032006-03-05 05:30:57 +00006963 // copysign(x, fp_extend(y)) -> copysign(x, y)
6964 // copysign(x, fp_round(y)) -> copysign(x, y)
6965 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006966 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0225a1d2009-01-30 23:15:49 +00006967 N0, N1.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00006968
Dan Gohman475871a2008-07-27 21:46:04 +00006969 return SDValue();
Chris Lattner12d83032006-03-05 05:30:57 +00006970}
6971
Dan Gohman475871a2008-07-27 21:46:04 +00006972SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6973 SDValue N0 = N->getOperand(0);
Nate Begeman646d7e22005-09-02 21:18:40 +00006974 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Andersone50ed302009-08-10 22:56:29 +00006975 EVT VT = N->getValueType(0);
6976 EVT OpVT = N0.getValueType();
Chris Lattnercda88752008-06-26 00:16:49 +00006977
Nate Begeman1d4d4142005-09-01 00:19:25 +00006978 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigande669c932012-10-29 18:35:49 +00006979 if (N0C &&
Stuart Hastings7e334182011-03-02 19:36:30 +00006980 // ...but only if the target supports immediate floating-point values
Eli Friedman50185242011-11-12 00:35:34 +00006981 (!LegalOperations ||
Evan Cheng9568e5c2011-06-21 06:01:08 +00006982 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006983 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +00006984
Chris Lattnercda88752008-06-26 00:16:49 +00006985 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6986 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohmanf560ffa2009-01-28 17:46:25 +00006987 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6988 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelfdc40a02009-02-17 22:15:04 +00006989 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnercda88752008-06-26 00:16:49 +00006990 if (DAG.SignBitIsZero(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006991 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnercda88752008-06-26 00:16:49 +00006992 }
Bill Wendling0225a1d2009-01-30 23:15:49 +00006993
Stephen Hines36b56882014-04-23 16:57:46 -07006994 // The next optimizations are desirable only if SELECT_CC can be lowered.
Nadav Rotemed1a3352012-07-23 07:59:50 +00006995 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6996 // having to say they don't support SELECT_CC on every type the DAG knows
6997 // about, since there is no way to mark an opcode illegal at all value types
6998 // (See also visitSELECT)
6999 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7000 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7001 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7002 !VT.isVector() &&
7003 (!LegalOperations ||
7004 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7005 SDValue Ops[] =
7006 { N0.getOperand(0), N0.getOperand(1),
7007 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7008 N0.getOperand(2) };
Andrew Trickac6d9be2013-05-25 02:42:55 +00007009 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotemed1a3352012-07-23 07:59:50 +00007010 }
Owen Andersond9bf71f2012-07-09 20:31:12 +00007011
Nadav Rotemed1a3352012-07-23 07:59:50 +00007012 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7013 // (select_cc x, y, 1.0, 0.0,, cc)
7014 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7015 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7016 (!LegalOperations ||
7017 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7018 SDValue Ops[] =
7019 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7020 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7021 N0.getOperand(0).getOperand(2) };
Andrew Trickac6d9be2013-05-25 02:42:55 +00007022 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotemed1a3352012-07-23 07:59:50 +00007023 }
Owen Andersond9bf71f2012-07-09 20:31:12 +00007024 }
7025
Dan Gohman475871a2008-07-27 21:46:04 +00007026 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00007027}
7028
Dan Gohman475871a2008-07-27 21:46:04 +00007029SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7030 SDValue N0 = N->getOperand(0);
Nate Begeman646d7e22005-09-02 21:18:40 +00007031 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Andersone50ed302009-08-10 22:56:29 +00007032 EVT VT = N->getValueType(0);
7033 EVT OpVT = N0.getValueType();
Nate Begemana148d982006-01-18 22:35:16 +00007034
Nate Begeman1d4d4142005-09-01 00:19:25 +00007035 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigande669c932012-10-29 18:35:49 +00007036 if (N0C &&
Stuart Hastings7e334182011-03-02 19:36:30 +00007037 // ...but only if the target supports immediate floating-point values
Eli Friedman50185242011-11-12 00:35:34 +00007038 (!LegalOperations ||
Evan Cheng9568e5c2011-06-21 06:01:08 +00007039 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00007040 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +00007041
Chris Lattnercda88752008-06-26 00:16:49 +00007042 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7043 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohmanf560ffa2009-01-28 17:46:25 +00007044 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7045 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelfdc40a02009-02-17 22:15:04 +00007046 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnercda88752008-06-26 00:16:49 +00007047 if (DAG.SignBitIsZero(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00007048 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnercda88752008-06-26 00:16:49 +00007049 }
Scott Michelfdc40a02009-02-17 22:15:04 +00007050
Stephen Hines36b56882014-04-23 16:57:46 -07007051 // The next optimizations are desirable only if SELECT_CC can be lowered.
Nadav Rotemed1a3352012-07-23 07:59:50 +00007052 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7053 // having to say they don't support SELECT_CC on every type the DAG knows
7054 // about, since there is no way to mark an opcode illegal at all value types
7055 // (See also visitSELECT)
7056 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7057 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond9bf71f2012-07-09 20:31:12 +00007058
Nadav Rotemed1a3352012-07-23 07:59:50 +00007059 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7060 (!LegalOperations ||
7061 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7062 SDValue Ops[] =
7063 { N0.getOperand(0), N0.getOperand(1),
7064 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7065 N0.getOperand(2) };
Andrew Trickac6d9be2013-05-25 02:42:55 +00007066 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotemed1a3352012-07-23 07:59:50 +00007067 }
7068 }
Owen Andersond9bf71f2012-07-09 20:31:12 +00007069
Dan Gohman475871a2008-07-27 21:46:04 +00007070 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00007071}
7072
Dan Gohman475871a2008-07-27 21:46:04 +00007073SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7074 SDValue N0 = N->getOperand(0);
Nate Begemana148d982006-01-18 22:35:16 +00007075 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Andersone50ed302009-08-10 22:56:29 +00007076 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00007077
Nate Begeman1d4d4142005-09-01 00:19:25 +00007078 // fold (fp_to_sint c1fp) -> c1
Nate Begeman646d7e22005-09-02 21:18:40 +00007079 if (N0CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007080 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0225a1d2009-01-30 23:15:49 +00007081
Dan Gohman475871a2008-07-27 21:46:04 +00007082 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00007083}
7084
Dan Gohman475871a2008-07-27 21:46:04 +00007085SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7086 SDValue N0 = N->getOperand(0);
Nate Begemana148d982006-01-18 22:35:16 +00007087 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Andersone50ed302009-08-10 22:56:29 +00007088 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00007089
Nate Begeman1d4d4142005-09-01 00:19:25 +00007090 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigande669c932012-10-29 18:35:49 +00007091 if (N0CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007092 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0225a1d2009-01-30 23:15:49 +00007093
Dan Gohman475871a2008-07-27 21:46:04 +00007094 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00007095}
7096
Dan Gohman475871a2008-07-27 21:46:04 +00007097SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7098 SDValue N0 = N->getOperand(0);
7099 SDValue N1 = N->getOperand(1);
Nate Begemana148d982006-01-18 22:35:16 +00007100 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Andersone50ed302009-08-10 22:56:29 +00007101 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00007102
Nate Begeman1d4d4142005-09-01 00:19:25 +00007103 // fold (fp_round c1fp) -> c1fp
Ulrich Weigande669c932012-10-29 18:35:49 +00007104 if (N0CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007105 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelfdc40a02009-02-17 22:15:04 +00007106
Chris Lattner79dbea52006-03-13 06:26:26 +00007107 // fold (fp_round (fp_extend x)) -> x
7108 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7109 return N0.getOperand(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00007110
Chris Lattner0aa5e6f2008-01-24 06:45:35 +00007111 // fold (fp_round (fp_round x)) -> (fp_round x)
7112 if (N0.getOpcode() == ISD::FP_ROUND) {
7113 // This is a value preserving truncation if both round's are.
7114 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
Gabor Greifba36cb52008-08-28 21:40:38 +00007115 N0.getNode()->getConstantOperandVal(1) == 1;
Andrew Trickac6d9be2013-05-25 02:42:55 +00007116 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0aa5e6f2008-01-24 06:45:35 +00007117 DAG.getIntPtrConstant(IsTrunc));
7118 }
Scott Michelfdc40a02009-02-17 22:15:04 +00007119
Chris Lattner79dbea52006-03-13 06:26:26 +00007120 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greifba36cb52008-08-28 21:40:38 +00007121 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00007122 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0225a1d2009-01-30 23:15:49 +00007123 N0.getOperand(0), N1);
Gabor Greifba36cb52008-08-28 21:40:38 +00007124 AddToWorkList(Tmp.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00007125 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0225a1d2009-01-30 23:15:49 +00007126 Tmp, N0.getOperand(1));
Chris Lattner79dbea52006-03-13 06:26:26 +00007127 }
Scott Michelfdc40a02009-02-17 22:15:04 +00007128
Dan Gohman475871a2008-07-27 21:46:04 +00007129 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00007130}
7131
Dan Gohman475871a2008-07-27 21:46:04 +00007132SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7133 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00007134 EVT VT = N->getValueType(0);
7135 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman646d7e22005-09-02 21:18:40 +00007136 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelfdc40a02009-02-17 22:15:04 +00007137
Nate Begeman1d4d4142005-09-01 00:19:25 +00007138 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner2392ae72010-04-15 04:48:01 +00007139 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohman4fbd7962008-09-12 18:08:03 +00007140 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickac6d9be2013-05-25 02:42:55 +00007141 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman1d4d4142005-09-01 00:19:25 +00007142 }
Bill Wendling0225a1d2009-01-30 23:15:49 +00007143
Dan Gohman475871a2008-07-27 21:46:04 +00007144 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00007145}
7146
Dan Gohman475871a2008-07-27 21:46:04 +00007147SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7148 SDValue N0 = N->getOperand(0);
Nate Begemana148d982006-01-18 22:35:16 +00007149 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Andersone50ed302009-08-10 22:56:29 +00007150 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00007151
Chris Lattner5938bef2007-12-29 06:55:23 +00007152 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelfdc40a02009-02-17 22:15:04 +00007153 if (N->hasOneUse() &&
Dan Gohmane7852d02009-01-26 04:35:06 +00007154 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman475871a2008-07-27 21:46:04 +00007155 return SDValue();
Chris Lattner0bd48932008-01-17 07:00:52 +00007156
Nate Begeman1d4d4142005-09-01 00:19:25 +00007157 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigande669c932012-10-29 18:35:49 +00007158 if (N0CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007159 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner0bd48932008-01-17 07:00:52 +00007160
7161 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7162 // value of X.
Gabor Greif12632d22008-08-30 19:29:20 +00007163 if (N0.getOpcode() == ISD::FP_ROUND
7164 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman475871a2008-07-27 21:46:04 +00007165 SDValue In = N0.getOperand(0);
Chris Lattner0bd48932008-01-17 07:00:52 +00007166 if (In.getValueType() == VT) return In;
Duncan Sands8e4eb092008-06-08 20:54:56 +00007167 if (VT.bitsLT(In.getValueType()))
Andrew Trickac6d9be2013-05-25 02:42:55 +00007168 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0225a1d2009-01-30 23:15:49 +00007169 In, N0.getOperand(1));
Andrew Trickac6d9be2013-05-25 02:42:55 +00007170 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner0bd48932008-01-17 07:00:52 +00007171 }
Scott Michelfdc40a02009-02-17 22:15:04 +00007172
Chris Lattner0bd48932008-01-17 07:00:52 +00007173 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkel03c8f8f2013-10-04 22:18:12 +00007174 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands25cf2272008-11-24 14:53:14 +00007175 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng03294662008-10-14 21:26:46 +00007176 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Evan Cheng466685d2006-10-09 20:57:25 +00007177 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00007178 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0225a1d2009-01-30 23:15:49 +00007179 LN0->getChain(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00007180 LN0->getBasePtr(), N0.getValueType(),
7181 LN0->getMemOperand());
Chris Lattnere564dbb2006-05-05 21:34:35 +00007182 CombineTo(N, ExtLoad);
Bill Wendling0225a1d2009-01-30 23:15:49 +00007183 CombineTo(N0.getNode(),
Andrew Trickac6d9be2013-05-25 02:42:55 +00007184 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0225a1d2009-01-30 23:15:49 +00007185 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattnere564dbb2006-05-05 21:34:35 +00007186 ExtLoad.getValue(1));
Dan Gohman475871a2008-07-27 21:46:04 +00007187 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattnere564dbb2006-05-05 21:34:35 +00007188 }
Duncan Sandsd4b9c172008-06-13 19:07:40 +00007189
Dan Gohman475871a2008-07-27 21:46:04 +00007190 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00007191}
7192
Dan Gohman475871a2008-07-27 21:46:04 +00007193SDValue DAGCombiner::visitFNEG(SDNode *N) {
7194 SDValue N0 = N->getOperand(0);
Anton Korobeynikov2bcf60a2009-10-20 21:37:45 +00007195 EVT VT = N->getValueType(0);
Nate Begemana148d982006-01-18 22:35:16 +00007196
Craig Topperdd201ff2012-09-11 01:45:21 +00007197 if (VT.isVector()) {
7198 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7199 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper956342b2012-09-09 22:58:45 +00007200 }
7201
Owen Andersonafd3d562012-03-06 00:29:31 +00007202 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7203 &DAG.getTarget().Options))
Duncan Sands25cf2272008-11-24 14:53:14 +00007204 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman23ff1822007-07-02 15:48:56 +00007205
Chris Lattner3bd39d42008-01-27 17:42:27 +00007206 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7207 // constant pool values.
Owen Anderson29f60f32012-04-02 22:10:29 +00007208 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
Anton Korobeynikov2bcf60a2009-10-20 21:37:45 +00007209 !VT.isVector() &&
7210 N0.getNode()->hasOneUse() &&
7211 N0.getOperand(0).getValueType().isInteger()) {
Dan Gohman475871a2008-07-27 21:46:04 +00007212 SDValue Int = N0.getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00007213 EVT IntVT = Int.getValueType();
Duncan Sands83ec4b62008-06-06 12:08:01 +00007214 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00007215 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Duncan Sandsb0d5cdd2009-02-01 18:06:53 +00007216 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greifba36cb52008-08-28 21:40:38 +00007217 AddToWorkList(Int.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00007218 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Anton Korobeynikov2bcf60a2009-10-20 21:37:45 +00007219 VT, Int);
Chris Lattner3bd39d42008-01-27 17:42:27 +00007220 }
7221 }
Scott Michelfdc40a02009-02-17 22:15:04 +00007222
Owen Anderson58d57292012-09-01 06:04:27 +00007223 // (fneg (fmul c, x)) -> (fmul -c, x)
7224 if (N0.getOpcode() == ISD::FMUL) {
7225 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Stephen Linb4940152013-07-09 00:44:49 +00007226 if (CFP1)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007227 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson58d57292012-09-01 06:04:27 +00007228 N0.getOperand(0),
Andrew Trickac6d9be2013-05-25 02:42:55 +00007229 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
Owen Anderson58d57292012-09-01 06:04:27 +00007230 N0.getOperand(1)));
Owen Anderson58d57292012-09-01 06:04:27 +00007231 }
7232
Dan Gohman475871a2008-07-27 21:46:04 +00007233 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00007234}
7235
Owen Anderson7c626d32012-08-13 23:32:49 +00007236SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7237 SDValue N0 = N->getOperand(0);
7238 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7239 EVT VT = N->getValueType(0);
7240
7241 // fold (fceil c1) -> fceil(c1)
Ulrich Weigande669c932012-10-29 18:35:49 +00007242 if (N0CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007243 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
Owen Anderson7c626d32012-08-13 23:32:49 +00007244
7245 return SDValue();
7246}
7247
7248SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7249 SDValue N0 = N->getOperand(0);
7250 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7251 EVT VT = N->getValueType(0);
7252
7253 // fold (ftrunc c1) -> ftrunc(c1)
Ulrich Weigande669c932012-10-29 18:35:49 +00007254 if (N0CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007255 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
Owen Anderson7c626d32012-08-13 23:32:49 +00007256
7257 return SDValue();
7258}
7259
7260SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7261 SDValue N0 = N->getOperand(0);
7262 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7263 EVT VT = N->getValueType(0);
7264
7265 // fold (ffloor c1) -> ffloor(c1)
Ulrich Weigande669c932012-10-29 18:35:49 +00007266 if (N0CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007267 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
Owen Anderson7c626d32012-08-13 23:32:49 +00007268
7269 return SDValue();
7270}
7271
Dan Gohman475871a2008-07-27 21:46:04 +00007272SDValue DAGCombiner::visitFABS(SDNode *N) {
7273 SDValue N0 = N->getOperand(0);
Nate Begemana148d982006-01-18 22:35:16 +00007274 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Andersone50ed302009-08-10 22:56:29 +00007275 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00007276
Craig Topperdd201ff2012-09-11 01:45:21 +00007277 if (VT.isVector()) {
7278 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7279 if (FoldedVOp.getNode()) return FoldedVOp;
7280 }
7281
Nate Begeman1d4d4142005-09-01 00:19:25 +00007282 // fold (fabs c1) -> fabs(c1)
Ulrich Weigande669c932012-10-29 18:35:49 +00007283 if (N0CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007284 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00007285 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner12d83032006-03-05 05:30:57 +00007286 if (N0.getOpcode() == ISD::FABS)
Nate Begeman83e75ec2005-09-06 04:43:02 +00007287 return N->getOperand(0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00007288 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner12d83032006-03-05 05:30:57 +00007289 // fold (fabs (fcopysign x, y)) -> (fabs x)
7290 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007291 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00007292
Chris Lattner3bd39d42008-01-27 17:42:27 +00007293 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7294 // constant pool values.
Stephen Lin155615d2013-07-08 00:37:03 +00007295 if (!TLI.isFAbsFree(VT) &&
Owen Anderson29f60f32012-04-02 22:10:29 +00007296 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
Duncan Sands83ec4b62008-06-06 12:08:01 +00007297 N0.getOperand(0).getValueType().isInteger() &&
7298 !N0.getOperand(0).getValueType().isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00007299 SDValue Int = N0.getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00007300 EVT IntVT = Int.getValueType();
Duncan Sands83ec4b62008-06-06 12:08:01 +00007301 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00007302 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Duncan Sandsb0d5cdd2009-02-01 18:06:53 +00007303 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greifba36cb52008-08-28 21:40:38 +00007304 AddToWorkList(Int.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00007305 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Bill Wendlingc0debad2009-01-30 23:27:35 +00007306 N->getValueType(0), Int);
Chris Lattner3bd39d42008-01-27 17:42:27 +00007307 }
7308 }
Scott Michelfdc40a02009-02-17 22:15:04 +00007309
Dan Gohman475871a2008-07-27 21:46:04 +00007310 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00007311}
7312
Dan Gohman475871a2008-07-27 21:46:04 +00007313SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7314 SDValue Chain = N->getOperand(0);
7315 SDValue N1 = N->getOperand(1);
7316 SDValue N2 = N->getOperand(2);
Scott Michelfdc40a02009-02-17 22:15:04 +00007317
Dan Gohmane0f06c72009-11-17 00:47:23 +00007318 // If N is a constant we could fold this into a fallthrough or unconditional
7319 // branch. However that doesn't happen very often in normal code, because
7320 // Instcombine/SimplifyCFG should have handled the available opportunities.
7321 // If we did this folding here, it would be necessary to update the
7322 // MachineBasicBlock CFG, which is awkward.
7323
Nate Begeman750ac1b2006-02-01 07:19:44 +00007324 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7325 // on the target.
Scott Michelfdc40a02009-02-17 22:15:04 +00007326 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellard3ef53832013-03-08 15:36:57 +00007327 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7328 N1.getOperand(0).getValueType())) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00007329 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendlingc0debad2009-01-30 23:27:35 +00007330 Chain, N1.getOperand(2),
Nate Begeman750ac1b2006-02-01 07:19:44 +00007331 N1.getOperand(0), N1.getOperand(1), N2);
7332 }
Bill Wendlingc0debad2009-01-30 23:27:35 +00007333
Evan Cheng2a135ae2010-10-04 22:41:01 +00007334 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7335 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7336 (N1.getOperand(0).hasOneUse() &&
7337 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7338 SDNode *Trunc = 0;
7339 if (N1.getOpcode() == ISD::TRUNCATE) {
7340 // Look pass the truncate.
7341 Trunc = N1.getNode();
7342 N1 = N1.getOperand(0);
7343 }
Evan Chengd40d03e2010-01-06 19:38:29 +00007344
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007345 // Match this pattern so that we can generate simpler code:
7346 //
7347 // %a = ...
7348 // %b = and i32 %a, 2
7349 // %c = srl i32 %b, 1
7350 // brcond i32 %c ...
7351 //
7352 // into
Wesley Peckbf17cfa2010-11-23 03:31:01 +00007353 //
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007354 // %a = ...
Evan Chengd40d03e2010-01-06 19:38:29 +00007355 // %b = and i32 %a, 2
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007356 // %c = setcc eq %b, 0
7357 // brcond %c ...
7358 //
7359 // This applies only when the AND constant value has one bit set and the
7360 // SRL constant is equal to the log2 of the AND constant. The back-end is
7361 // smart enough to convert the result into a TEST/JMP sequence.
7362 SDValue Op0 = N1.getOperand(0);
7363 SDValue Op1 = N1.getOperand(1);
7364
7365 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007366 Op1.getOpcode() == ISD::Constant) {
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007367 SDValue AndOp1 = Op0.getOperand(1);
7368
7369 if (AndOp1.getOpcode() == ISD::Constant) {
7370 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7371
7372 if (AndConst.isPowerOf2() &&
7373 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7374 SDValue SetCC =
Andrew Trickac6d9be2013-05-25 02:42:55 +00007375 DAG.getSetCC(SDLoc(N),
Matt Arsenault225ed702013-05-18 00:21:46 +00007376 getSetCCResultType(Op0.getValueType()),
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007377 Op0, DAG.getConstant(0, Op0.getValueType()),
7378 ISD::SETNE);
7379
Andrew Trickac6d9be2013-05-25 02:42:55 +00007380 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Chengd40d03e2010-01-06 19:38:29 +00007381 MVT::Other, Chain, SetCC, N2);
7382 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7383 // will convert it back to (X & C1) >> C2.
7384 CombineTo(N, NewBRCond, false);
7385 // Truncate is dead.
7386 if (Trunc) {
7387 removeFromWorkList(Trunc);
7388 DAG.DeleteNode(Trunc);
7389 }
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007390 // Replace the uses of SRL with SETCC
Evan Cheng2c755ba2010-02-27 07:36:59 +00007391 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007392 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007393 removeFromWorkList(N1.getNode());
7394 DAG.DeleteNode(N1.getNode());
Evan Chengd40d03e2010-01-06 19:38:29 +00007395 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007396 }
7397 }
7398 }
Evan Cheng2a135ae2010-10-04 22:41:01 +00007399
7400 if (Trunc)
7401 // Restore N1 if the above transformation doesn't match.
7402 N1 = N->getOperand(1);
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007403 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00007404
Evan Cheng2c755ba2010-02-27 07:36:59 +00007405 // Transform br(xor(x, y)) -> br(x != y)
7406 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7407 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7408 SDNode *TheXor = N1.getNode();
7409 SDValue Op0 = TheXor->getOperand(0);
7410 SDValue Op1 = TheXor->getOperand(1);
7411 if (Op0.getOpcode() == Op1.getOpcode()) {
7412 // Avoid missing important xor optimizations.
7413 SDValue Tmp = visitXOR(TheXor);
Evan Cheng78ec0252013-01-09 20:56:40 +00007414 if (Tmp.getNode()) {
7415 if (Tmp.getNode() != TheXor) {
7416 DEBUG(dbgs() << "\nReplacing.8 ";
7417 TheXor->dump(&DAG);
7418 dbgs() << "\nWith: ";
7419 Tmp.getNode()->dump(&DAG);
7420 dbgs() << '\n');
7421 WorkListRemover DeadNodes(*this);
7422 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7423 removeFromWorkList(TheXor);
7424 DAG.DeleteNode(TheXor);
Andrew Trickac6d9be2013-05-25 02:42:55 +00007425 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng78ec0252013-01-09 20:56:40 +00007426 MVT::Other, Chain, Tmp, N2);
7427 }
7428
Benjamin Kramer0b68b752013-03-30 21:28:18 +00007429 // visitXOR has changed XOR's operands or replaced the XOR completely,
7430 // bail out.
7431 return SDValue(N, 0);
Evan Cheng2c755ba2010-02-27 07:36:59 +00007432 }
7433 }
7434
7435 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7436 bool Equal = false;
7437 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7438 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7439 Op0.getOpcode() == ISD::XOR) {
7440 TheXor = Op0.getNode();
7441 Equal = true;
7442 }
7443
Evan Cheng2a135ae2010-10-04 22:41:01 +00007444 EVT SetCCVT = N1.getValueType();
Evan Cheng2c755ba2010-02-27 07:36:59 +00007445 if (LegalTypes)
Matt Arsenault225ed702013-05-18 00:21:46 +00007446 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickac6d9be2013-05-25 02:42:55 +00007447 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng2c755ba2010-02-27 07:36:59 +00007448 SetCCVT,
7449 Op0, Op1,
7450 Equal ? ISD::SETEQ : ISD::SETNE);
7451 // Replace the uses of XOR with SETCC
7452 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007453 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Evan Cheng2a135ae2010-10-04 22:41:01 +00007454 removeFromWorkList(N1.getNode());
7455 DAG.DeleteNode(N1.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00007456 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng2c755ba2010-02-27 07:36:59 +00007457 MVT::Other, Chain, SetCC, N2);
7458 }
7459 }
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007460
Dan Gohman475871a2008-07-27 21:46:04 +00007461 return SDValue();
Nate Begeman44728a72005-09-19 22:34:01 +00007462}
7463
Chris Lattner3ea0b472005-10-05 06:47:48 +00007464// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7465//
Dan Gohman475871a2008-07-27 21:46:04 +00007466SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattner3ea0b472005-10-05 06:47:48 +00007467 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman475871a2008-07-27 21:46:04 +00007468 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelfdc40a02009-02-17 22:15:04 +00007469
Dan Gohmane0f06c72009-11-17 00:47:23 +00007470 // If N is a constant we could fold this into a fallthrough or unconditional
7471 // branch. However that doesn't happen very often in normal code, because
7472 // Instcombine/SimplifyCFG should have handled the available opportunities.
7473 // If we did this folding here, it would be necessary to update the
7474 // MachineBasicBlock CFG, which is awkward.
7475
Duncan Sands8eab8a22008-06-09 11:32:28 +00007476 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault225ed702013-05-18 00:21:46 +00007477 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickac6d9be2013-05-25 02:42:55 +00007478 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenff97d4f2009-02-03 00:47:48 +00007479 false);
Gabor Greifba36cb52008-08-28 21:40:38 +00007480 if (Simp.getNode()) AddToWorkList(Simp.getNode());
Chris Lattner30f73e72006-10-14 03:52:46 +00007481
Nate Begemane17daeb2005-10-05 21:43:42 +00007482 // fold to a simpler setcc
Gabor Greifba36cb52008-08-28 21:40:38 +00007483 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007484 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendlingc0debad2009-01-30 23:27:35 +00007485 N->getOperand(0), Simp.getOperand(2),
7486 Simp.getOperand(0), Simp.getOperand(1),
7487 N->getOperand(4));
7488
Dan Gohman475871a2008-07-27 21:46:04 +00007489 return SDValue();
Nate Begeman44728a72005-09-19 22:34:01 +00007490}
7491
Evan Chengc4b527a2012-01-13 01:37:24 +00007492/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7493/// uses N as its base pointer and that N may be folded in the load / store
Evan Cheng03be3622012-03-06 23:33:32 +00007494/// addressing mode.
Evan Chengc4b527a2012-01-13 01:37:24 +00007495static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7496 SelectionDAG &DAG,
7497 const TargetLowering &TLI) {
7498 EVT VT;
7499 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7500 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7501 return false;
7502 VT = Use->getValueType(0);
7503 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7504 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7505 return false;
7506 VT = ST->getValue().getValueType();
7507 } else
7508 return false;
7509
Chandler Carruth56d433d2013-01-07 15:14:13 +00007510 TargetLowering::AddrMode AM;
Evan Chengc4b527a2012-01-13 01:37:24 +00007511 if (N->getOpcode() == ISD::ADD) {
7512 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7513 if (Offset)
Evan Cheng03be3622012-03-06 23:33:32 +00007514 // [reg +/- imm]
Evan Chengc4b527a2012-01-13 01:37:24 +00007515 AM.BaseOffs = Offset->getSExtValue();
7516 else
Evan Cheng03be3622012-03-06 23:33:32 +00007517 // [reg +/- reg]
7518 AM.Scale = 1;
Evan Chengc4b527a2012-01-13 01:37:24 +00007519 } else if (N->getOpcode() == ISD::SUB) {
7520 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7521 if (Offset)
Evan Cheng03be3622012-03-06 23:33:32 +00007522 // [reg +/- imm]
Evan Chengc4b527a2012-01-13 01:37:24 +00007523 AM.BaseOffs = -Offset->getSExtValue();
7524 else
Evan Cheng03be3622012-03-06 23:33:32 +00007525 // [reg +/- reg]
7526 AM.Scale = 1;
Evan Chengc4b527a2012-01-13 01:37:24 +00007527 } else
7528 return false;
7529
7530 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7531}
7532
Duncan Sandsec87aa82008-06-15 20:12:31 +00007533/// CombineToPreIndexedLoadStore - Try turning a load / store into a
7534/// pre-indexed load / store when the base pointer is an add or subtract
Chris Lattner448f2192006-11-11 00:39:41 +00007535/// and it has other uses besides the load / store. After the
7536/// transformation, the new indexed load / store has effectively folded
7537/// the add / subtract in and all of its other uses are redirected to the
7538/// new load / store.
7539bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman50185242011-11-12 00:35:34 +00007540 if (Level < AfterLegalizeDAG)
Chris Lattner448f2192006-11-11 00:39:41 +00007541 return false;
7542
7543 bool isLoad = true;
Dan Gohman475871a2008-07-27 21:46:04 +00007544 SDValue Ptr;
Owen Andersone50ed302009-08-10 22:56:29 +00007545 EVT VT;
Chris Lattner448f2192006-11-11 00:39:41 +00007546 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattnerddf89562008-01-17 19:59:44 +00007547 if (LD->isIndexed())
Evan Chenge90460e2006-12-16 06:25:23 +00007548 return false;
Dan Gohmanb625f2f2008-01-30 00:15:11 +00007549 VT = LD->getMemoryVT();
Evan Cheng83060c52007-03-07 08:07:03 +00007550 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattner448f2192006-11-11 00:39:41 +00007551 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7552 return false;
7553 Ptr = LD->getBasePtr();
7554 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattnerddf89562008-01-17 19:59:44 +00007555 if (ST->isIndexed())
Evan Chenge90460e2006-12-16 06:25:23 +00007556 return false;
Dan Gohmanb625f2f2008-01-30 00:15:11 +00007557 VT = ST->getMemoryVT();
Chris Lattner448f2192006-11-11 00:39:41 +00007558 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7559 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7560 return false;
7561 Ptr = ST->getBasePtr();
7562 isLoad = false;
Bill Wendlingc0debad2009-01-30 23:27:35 +00007563 } else {
Chris Lattner448f2192006-11-11 00:39:41 +00007564 return false;
Bill Wendlingc0debad2009-01-30 23:27:35 +00007565 }
Chris Lattner448f2192006-11-11 00:39:41 +00007566
Chris Lattner9f1794e2006-11-11 00:56:29 +00007567 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7568 // out. There is no reason to make this a preinc/predec.
7569 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greifba36cb52008-08-28 21:40:38 +00007570 Ptr.getNode()->hasOneUse())
Chris Lattner9f1794e2006-11-11 00:56:29 +00007571 return false;
Chris Lattner448f2192006-11-11 00:39:41 +00007572
Chris Lattner9f1794e2006-11-11 00:56:29 +00007573 // Ask the target to do addressing mode selection.
Dan Gohman475871a2008-07-27 21:46:04 +00007574 SDValue BasePtr;
7575 SDValue Offset;
Chris Lattner9f1794e2006-11-11 00:56:29 +00007576 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7577 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7578 return false;
Hal Finkel089a5f82013-02-08 21:35:47 +00007579
7580 // Backends without true r+i pre-indexed forms may need to pass a
7581 // constant base with a variable offset so that constant coercion
7582 // will work with the patterns in canonical form.
7583 bool Swapped = false;
7584 if (isa<ConstantSDNode>(BasePtr)) {
7585 std::swap(BasePtr, Offset);
7586 Swapped = true;
7587 }
7588
Evan Chenga7d4a042007-05-03 23:52:19 +00007589 // Don't create a indexed load / store with zero offset.
7590 if (isa<ConstantSDNode>(Offset) &&
Dan Gohman002e5d02008-03-13 22:13:53 +00007591 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Chenga7d4a042007-05-03 23:52:19 +00007592 return false;
Scott Michelfdc40a02009-02-17 22:15:04 +00007593
Chris Lattner41e53fd2006-11-11 01:00:15 +00007594 // Try turning it into a pre-indexed load / store except when:
Evan Chengc843abe2007-05-24 02:35:39 +00007595 // 1) The new base ptr is a frame index.
7596 // 2) If N is a store and the new base ptr is either the same as or is a
Chris Lattner9f1794e2006-11-11 00:56:29 +00007597 // predecessor of the value being stored.
Evan Chengc843abe2007-05-24 02:35:39 +00007598 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattner9f1794e2006-11-11 00:56:29 +00007599 // that would create a cycle.
Evan Chengc843abe2007-05-24 02:35:39 +00007600 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattner448f2192006-11-11 00:39:41 +00007601
Chris Lattner41e53fd2006-11-11 01:00:15 +00007602 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7603 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcaab1292009-05-06 18:25:01 +00007604 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattner41e53fd2006-11-11 01:00:15 +00007605 return false;
Scott Michelfdc40a02009-02-17 22:15:04 +00007606
Chris Lattner41e53fd2006-11-11 01:00:15 +00007607 // Check #2.
Chris Lattner9f1794e2006-11-11 00:56:29 +00007608 if (!isLoad) {
Dan Gohman475871a2008-07-27 21:46:04 +00007609 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greifba36cb52008-08-28 21:40:38 +00007610 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattner9f1794e2006-11-11 00:56:29 +00007611 return false;
Chris Lattner448f2192006-11-11 00:39:41 +00007612 }
Chris Lattner9f1794e2006-11-11 00:56:29 +00007613
Hal Finkel089a5f82013-02-08 21:35:47 +00007614 // If the offset is a constant, there may be other adds of constants that
7615 // can be folded with this one. We should do this to avoid having to keep
7616 // a copy of the original base pointer.
7617 SmallVector<SDNode *, 16> OtherUses;
7618 if (isa<ConstantSDNode>(Offset))
7619 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7620 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7621 SDNode *Use = *I;
7622 if (Use == Ptr.getNode())
7623 continue;
7624
7625 if (Use->isPredecessorOf(N))
7626 continue;
7627
7628 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7629 OtherUses.clear();
7630 break;
7631 }
7632
7633 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7634 if (Op1.getNode() == BasePtr.getNode())
7635 std::swap(Op0, Op1);
7636 assert(Op0.getNode() == BasePtr.getNode() &&
7637 "Use of ADD/SUB but not an operand");
7638
7639 if (!isa<ConstantSDNode>(Op1)) {
7640 OtherUses.clear();
7641 break;
7642 }
7643
7644 // FIXME: In some cases, we can be smarter about this.
7645 if (Op1.getValueType() != Offset.getValueType()) {
7646 OtherUses.clear();
7647 break;
7648 }
7649
7650 OtherUses.push_back(Use);
7651 }
7652
7653 if (Swapped)
7654 std::swap(BasePtr, Offset);
7655
Evan Chengc843abe2007-05-24 02:35:39 +00007656 // Now check for #3 and #4.
Chris Lattner9f1794e2006-11-11 00:56:29 +00007657 bool RealUse = false;
Lang Hames944520f2011-07-07 04:31:51 +00007658
7659 // Caches for hasPredecessorHelper
7660 SmallPtrSet<const SDNode *, 32> Visited;
7661 SmallVector<const SDNode *, 16> Worklist;
7662
Gabor Greifba36cb52008-08-28 21:40:38 +00007663 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7664 E = Ptr.getNode()->use_end(); I != E; ++I) {
Dan Gohman89684502008-07-27 20:43:25 +00007665 SDNode *Use = *I;
Chris Lattner9f1794e2006-11-11 00:56:29 +00007666 if (Use == N)
7667 continue;
Lang Hames944520f2011-07-07 04:31:51 +00007668 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattner9f1794e2006-11-11 00:56:29 +00007669 return false;
7670
Evan Chengc4b527a2012-01-13 01:37:24 +00007671 // If Ptr may be folded in addressing mode of other use, then it's
7672 // not profitable to do this transformation.
7673 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattner9f1794e2006-11-11 00:56:29 +00007674 RealUse = true;
7675 }
Bill Wendlingc0debad2009-01-30 23:27:35 +00007676
Chris Lattner9f1794e2006-11-11 00:56:29 +00007677 if (!RealUse)
7678 return false;
7679
Dan Gohman475871a2008-07-27 21:46:04 +00007680 SDValue Result;
Chris Lattner9f1794e2006-11-11 00:56:29 +00007681 if (isLoad)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007682 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendlingc0debad2009-01-30 23:27:35 +00007683 BasePtr, Offset, AM);
Chris Lattner9f1794e2006-11-11 00:56:29 +00007684 else
Andrew Trickac6d9be2013-05-25 02:42:55 +00007685 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendlingc0debad2009-01-30 23:27:35 +00007686 BasePtr, Offset, AM);
Chris Lattner9f1794e2006-11-11 00:56:29 +00007687 ++PreIndexedNodes;
7688 ++NodesCombined;
David Greenef1090292010-01-05 01:25:00 +00007689 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00007690 N->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00007691 dbgs() << "\nWith: ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00007692 Result.getNode()->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00007693 dbgs() << '\n');
Chris Lattnerf8dc0612008-02-03 06:49:24 +00007694 WorkListRemover DeadNodes(*this);
Chris Lattner9f1794e2006-11-11 00:56:29 +00007695 if (isLoad) {
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007696 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7697 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattner9f1794e2006-11-11 00:56:29 +00007698 } else {
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007699 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattner9f1794e2006-11-11 00:56:29 +00007700 }
7701
Chris Lattner9f1794e2006-11-11 00:56:29 +00007702 // Finally, since the node is now dead, remove it from the graph.
7703 DAG.DeleteNode(N);
7704
Hal Finkel089a5f82013-02-08 21:35:47 +00007705 if (Swapped)
7706 std::swap(BasePtr, Offset);
7707
7708 // Replace other uses of BasePtr that can be updated to use Ptr
7709 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7710 unsigned OffsetIdx = 1;
7711 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7712 OffsetIdx = 0;
7713 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7714 BasePtr.getNode() && "Expected BasePtr operand");
7715
Silviu Baranga730a5702013-04-26 15:52:24 +00007716 // We need to replace ptr0 in the following expression:
7717 // x0 * offset0 + y0 * ptr0 = t0
7718 // knowing that
7719 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lin155615d2013-07-08 00:37:03 +00007720 //
Silviu Baranga730a5702013-04-26 15:52:24 +00007721 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7722 // indexed load/store and the expresion that needs to be re-written.
7723 //
7724 // Therefore, we have:
7725 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel089a5f82013-02-08 21:35:47 +00007726
7727 ConstantSDNode *CN =
7728 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Baranga730a5702013-04-26 15:52:24 +00007729 int X0, X1, Y0, Y1;
7730 APInt Offset0 = CN->getAPIntValue();
7731 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel089a5f82013-02-08 21:35:47 +00007732
Silviu Baranga730a5702013-04-26 15:52:24 +00007733 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7734 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7735 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7736 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel089a5f82013-02-08 21:35:47 +00007737
Silviu Baranga730a5702013-04-26 15:52:24 +00007738 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7739
7740 APInt CNV = Offset0;
7741 if (X0 < 0) CNV = -CNV;
7742 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7743 else CNV = CNV - Offset1;
7744
7745 // We can now generate the new expression.
7746 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7747 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7748
7749 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickac6d9be2013-05-25 02:42:55 +00007750 SDLoc(OtherUses[i]),
Hal Finkel089a5f82013-02-08 21:35:47 +00007751 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7752 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7753 removeFromWorkList(OtherUses[i]);
7754 DAG.DeleteNode(OtherUses[i]);
7755 }
7756
Chris Lattner9f1794e2006-11-11 00:56:29 +00007757 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007758 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Gabor Greifba36cb52008-08-28 21:40:38 +00007759 removeFromWorkList(Ptr.getNode());
7760 DAG.DeleteNode(Ptr.getNode());
Chris Lattner9f1794e2006-11-11 00:56:29 +00007761
7762 return true;
Chris Lattner448f2192006-11-11 00:39:41 +00007763}
7764
Duncan Sandsec87aa82008-06-15 20:12:31 +00007765/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
Chris Lattner448f2192006-11-11 00:39:41 +00007766/// add / sub of the base pointer node into a post-indexed load / store.
7767/// The transformation folded the add / subtract into the new indexed
7768/// load / store effectively and all of its uses are redirected to the
7769/// new load / store.
7770bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman50185242011-11-12 00:35:34 +00007771 if (Level < AfterLegalizeDAG)
Chris Lattner448f2192006-11-11 00:39:41 +00007772 return false;
7773
7774 bool isLoad = true;
Dan Gohman475871a2008-07-27 21:46:04 +00007775 SDValue Ptr;
Owen Andersone50ed302009-08-10 22:56:29 +00007776 EVT VT;
Chris Lattner448f2192006-11-11 00:39:41 +00007777 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattnerddf89562008-01-17 19:59:44 +00007778 if (LD->isIndexed())
Evan Chenge90460e2006-12-16 06:25:23 +00007779 return false;
Dan Gohmanb625f2f2008-01-30 00:15:11 +00007780 VT = LD->getMemoryVT();
Chris Lattner448f2192006-11-11 00:39:41 +00007781 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7782 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7783 return false;
7784 Ptr = LD->getBasePtr();
7785 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattnerddf89562008-01-17 19:59:44 +00007786 if (ST->isIndexed())
Evan Chenge90460e2006-12-16 06:25:23 +00007787 return false;
Dan Gohmanb625f2f2008-01-30 00:15:11 +00007788 VT = ST->getMemoryVT();
Chris Lattner448f2192006-11-11 00:39:41 +00007789 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7790 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7791 return false;
7792 Ptr = ST->getBasePtr();
7793 isLoad = false;
Bill Wendlingc0debad2009-01-30 23:27:35 +00007794 } else {
Chris Lattner448f2192006-11-11 00:39:41 +00007795 return false;
Bill Wendlingc0debad2009-01-30 23:27:35 +00007796 }
Chris Lattner448f2192006-11-11 00:39:41 +00007797
Gabor Greifba36cb52008-08-28 21:40:38 +00007798 if (Ptr.getNode()->hasOneUse())
Chris Lattner9f1794e2006-11-11 00:56:29 +00007799 return false;
Scott Michelfdc40a02009-02-17 22:15:04 +00007800
Gabor Greifba36cb52008-08-28 21:40:38 +00007801 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7802 E = Ptr.getNode()->use_end(); I != E; ++I) {
Dan Gohman89684502008-07-27 20:43:25 +00007803 SDNode *Op = *I;
Chris Lattner9f1794e2006-11-11 00:56:29 +00007804 if (Op == N ||
7805 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7806 continue;
7807
Dan Gohman475871a2008-07-27 21:46:04 +00007808 SDValue BasePtr;
7809 SDValue Offset;
Chris Lattner9f1794e2006-11-11 00:56:29 +00007810 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7811 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Chenga7d4a042007-05-03 23:52:19 +00007812 // Don't create a indexed load / store with zero offset.
7813 if (isa<ConstantSDNode>(Offset) &&
Dan Gohman002e5d02008-03-13 22:13:53 +00007814 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Chenga7d4a042007-05-03 23:52:19 +00007815 continue;
Chris Lattner448f2192006-11-11 00:39:41 +00007816
Chris Lattner9f1794e2006-11-11 00:56:29 +00007817 // Try turning it into a post-indexed load / store except when
Evan Chengc4b527a2012-01-13 01:37:24 +00007818 // 1) All uses are load / store ops that use it as base ptr (and
7819 // it may be folded as addressing mmode).
Chris Lattner9f1794e2006-11-11 00:56:29 +00007820 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7821 // nor a successor of N. Otherwise, if Op is folded that would
7822 // create a cycle.
7823
Evan Chengcaab1292009-05-06 18:25:01 +00007824 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7825 continue;
7826
Chris Lattner9f1794e2006-11-11 00:56:29 +00007827 // Check for #1.
7828 bool TryNext = false;
Gabor Greifba36cb52008-08-28 21:40:38 +00007829 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7830 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
Dan Gohman89684502008-07-27 20:43:25 +00007831 SDNode *Use = *II;
Gabor Greifba36cb52008-08-28 21:40:38 +00007832 if (Use == Ptr.getNode())
Chris Lattner448f2192006-11-11 00:39:41 +00007833 continue;
7834
Chris Lattner9f1794e2006-11-11 00:56:29 +00007835 // If all the uses are load / store addresses, then don't do the
7836 // transformation.
7837 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7838 bool RealUse = false;
7839 for (SDNode::use_iterator III = Use->use_begin(),
7840 EEE = Use->use_end(); III != EEE; ++III) {
Dan Gohman89684502008-07-27 20:43:25 +00007841 SDNode *UseUse = *III;
Stephen Lin155615d2013-07-08 00:37:03 +00007842 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattner9f1794e2006-11-11 00:56:29 +00007843 RealUse = true;
7844 }
Chris Lattner448f2192006-11-11 00:39:41 +00007845
Chris Lattner9f1794e2006-11-11 00:56:29 +00007846 if (!RealUse) {
7847 TryNext = true;
7848 break;
Chris Lattner448f2192006-11-11 00:39:41 +00007849 }
7850 }
Chris Lattner9f1794e2006-11-11 00:56:29 +00007851 }
Bill Wendlingc0debad2009-01-30 23:27:35 +00007852
Chris Lattner9f1794e2006-11-11 00:56:29 +00007853 if (TryNext)
7854 continue;
Chris Lattner448f2192006-11-11 00:39:41 +00007855
Chris Lattner9f1794e2006-11-11 00:56:29 +00007856 // Check for #2
Evan Cheng917be682008-03-04 00:41:45 +00007857 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman475871a2008-07-27 21:46:04 +00007858 SDValue Result = isLoad
Andrew Trickac6d9be2013-05-25 02:42:55 +00007859 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendlingc0debad2009-01-30 23:27:35 +00007860 BasePtr, Offset, AM)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007861 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendlingc0debad2009-01-30 23:27:35 +00007862 BasePtr, Offset, AM);
Chris Lattner9f1794e2006-11-11 00:56:29 +00007863 ++PostIndexedNodes;
7864 ++NodesCombined;
David Greenef1090292010-01-05 01:25:00 +00007865 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00007866 N->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00007867 dbgs() << "\nWith: ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00007868 Result.getNode()->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00007869 dbgs() << '\n');
Chris Lattnerf8dc0612008-02-03 06:49:24 +00007870 WorkListRemover DeadNodes(*this);
Chris Lattner9f1794e2006-11-11 00:56:29 +00007871 if (isLoad) {
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007872 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7873 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattner9f1794e2006-11-11 00:56:29 +00007874 } else {
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007875 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattner448f2192006-11-11 00:39:41 +00007876 }
Chris Lattner9f1794e2006-11-11 00:56:29 +00007877
Chris Lattner9f1794e2006-11-11 00:56:29 +00007878 // Finally, since the node is now dead, remove it from the graph.
7879 DAG.DeleteNode(N);
7880
7881 // Replace the uses of Use with uses of the updated base value.
Dan Gohman475871a2008-07-27 21:46:04 +00007882 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007883 Result.getValue(isLoad ? 1 : 0));
Chris Lattner9f1794e2006-11-11 00:56:29 +00007884 removeFromWorkList(Op);
Chris Lattner9f1794e2006-11-11 00:56:29 +00007885 DAG.DeleteNode(Op);
Chris Lattner9f1794e2006-11-11 00:56:29 +00007886 return true;
Chris Lattner448f2192006-11-11 00:39:41 +00007887 }
7888 }
7889 }
Bill Wendlingc0debad2009-01-30 23:27:35 +00007890
Chris Lattner448f2192006-11-11 00:39:41 +00007891 return false;
7892}
7893
Dan Gohman475871a2008-07-27 21:46:04 +00007894SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Cheng466685d2006-10-09 20:57:25 +00007895 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman475871a2008-07-27 21:46:04 +00007896 SDValue Chain = LD->getChain();
7897 SDValue Ptr = LD->getBasePtr();
Scott Michelfdc40a02009-02-17 22:15:04 +00007898
Evan Cheng45a7ca92007-05-01 00:38:21 +00007899 // If load is not volatile and there are no uses of the loaded value (and
7900 // the updated indexed value in case of indexed loads), change uses of the
7901 // chain value into uses of the chain input (i.e. delete the dead load).
7902 if (!LD->isVolatile()) {
Owen Anderson825b72b2009-08-11 20:47:22 +00007903 if (N->getValueType(1) == MVT::Other) {
Evan Cheng498f5592007-05-01 08:53:39 +00007904 // Unindexed loads.
Craig Topper704e1a02012-01-07 18:31:09 +00007905 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng02c42852008-01-16 23:11:54 +00007906 // It's not safe to use the two value CombineTo variant here. e.g.
7907 // v1, chain2 = load chain1, loc
7908 // v2, chain3 = load chain2, loc
7909 // v3 = add v2, c
Chris Lattner125991a2008-01-24 07:57:06 +00007910 // Now we replace use of chain2 with chain1. This makes the second load
7911 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenef1090292010-01-05 01:25:00 +00007912 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00007913 N->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00007914 dbgs() << "\nWith chain: ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00007915 Chain.getNode()->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00007916 dbgs() << "\n");
Chris Lattnerf8dc0612008-02-03 06:49:24 +00007917 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007918 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendlingc0debad2009-01-30 23:27:35 +00007919
Chris Lattner125991a2008-01-24 07:57:06 +00007920 if (N->use_empty()) {
7921 removeFromWorkList(N);
7922 DAG.DeleteNode(N);
7923 }
Bill Wendlingc0debad2009-01-30 23:27:35 +00007924
Dan Gohman475871a2008-07-27 21:46:04 +00007925 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng02c42852008-01-16 23:11:54 +00007926 }
Evan Cheng498f5592007-05-01 08:53:39 +00007927 } else {
7928 // Indexed loads.
Owen Anderson825b72b2009-08-11 20:47:22 +00007929 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Craig Topper704e1a02012-01-07 18:31:09 +00007930 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
Dale Johannesene8d72302009-02-06 23:05:02 +00007931 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Evan Cheng2c755ba2010-02-27 07:36:59 +00007932 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00007933 N->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00007934 dbgs() << "\nWith: ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00007935 Undef.getNode()->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00007936 dbgs() << " and 2 other values\n");
Chris Lattnerf8dc0612008-02-03 06:49:24 +00007937 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007938 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Dan Gohman475871a2008-07-27 21:46:04 +00007939 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007940 DAG.getUNDEF(N->getValueType(1)));
7941 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Evan Cheng02c42852008-01-16 23:11:54 +00007942 removeFromWorkList(N);
Evan Cheng02c42852008-01-16 23:11:54 +00007943 DAG.DeleteNode(N);
Dan Gohman475871a2008-07-27 21:46:04 +00007944 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng45a7ca92007-05-01 00:38:21 +00007945 }
Evan Cheng45a7ca92007-05-01 00:38:21 +00007946 }
7947 }
Scott Michelfdc40a02009-02-17 22:15:04 +00007948
Chris Lattner01a22022005-10-10 22:04:48 +00007949 // If this load is directly stored, replace the load value with the stored
7950 // value.
7951 // TODO: Handle store large -> read small portion.
Jim Laskeyc2b19f32006-10-11 17:47:52 +00007952 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Cheng9ef82ce2011-03-11 00:48:56 +00007953 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greifba36cb52008-08-28 21:40:38 +00007954 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Cheng8b2794a2006-10-13 21:14:26 +00007955 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7956 if (PrevST->getBasePtr() == Ptr &&
7957 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskeyc2b19f32006-10-11 17:47:52 +00007958 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Cheng8b2794a2006-10-13 21:14:26 +00007959 }
Jim Laskeyc2b19f32006-10-11 17:47:52 +00007960 }
Scott Michelfdc40a02009-02-17 22:15:04 +00007961
Evan Cheng255f20f2010-04-01 06:04:33 +00007962 // Try to infer better alignment information than the load already has.
7963 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Chenged1c0c72011-11-28 22:37:34 +00007964 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonb48783b2013-02-05 19:24:39 +00007965 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7966 SDValue NewLoad =
Andrew Trickac6d9be2013-05-25 02:42:55 +00007967 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Chenged1c0c72011-11-28 22:37:34 +00007968 LD->getValueType(0),
7969 Chain, Ptr, LD->getPointerInfo(),
7970 LD->getMemoryVT(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00007971 LD->isVolatile(), LD->isNonTemporal(), Align,
7972 LD->getTBAAInfo());
Owen Andersonb48783b2013-02-05 19:24:39 +00007973 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7974 }
Evan Cheng255f20f2010-04-01 06:04:33 +00007975 }
7976 }
7977
Hal Finkel253acef2013-08-29 03:29:55 +00007978 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7979 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Stephen Hines36b56882014-04-23 16:57:46 -07007980#ifndef NDEBUG
7981 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7982 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7983 UseAA = false;
7984#endif
7985 if (UseAA && LD->isUnindexed()) {
Jim Laskey279f0532006-09-25 16:29:54 +00007986 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman475871a2008-07-27 21:46:04 +00007987 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelfdc40a02009-02-17 22:15:04 +00007988
Jim Laskey6ff23e52006-10-04 16:53:27 +00007989 // If there is a better chain.
Jim Laskey279f0532006-09-25 16:29:54 +00007990 if (Chain != BetterChain) {
Dan Gohman475871a2008-07-27 21:46:04 +00007991 SDValue ReplLoad;
Jim Laskeyc2b19f32006-10-11 17:47:52 +00007992
Jim Laskey279f0532006-09-25 16:29:54 +00007993 // Replace the chain to void dependency.
Jim Laskeyc2b19f32006-10-11 17:47:52 +00007994 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00007995 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford66589dc2013-10-28 11:17:59 +00007996 BetterChain, Ptr, LD->getMemOperand());
Jim Laskeyc2b19f32006-10-11 17:47:52 +00007997 } else {
Andrew Trickac6d9be2013-05-25 02:42:55 +00007998 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastingsa9011292011-02-16 16:23:55 +00007999 LD->getValueType(0),
Richard Sandiford66589dc2013-10-28 11:17:59 +00008000 BetterChain, Ptr, LD->getMemoryVT(),
8001 LD->getMemOperand());
Jim Laskeyc2b19f32006-10-11 17:47:52 +00008002 }
Jim Laskey279f0532006-09-25 16:29:54 +00008003
Jim Laskey6ff23e52006-10-04 16:53:27 +00008004 // Create token factor to keep old chain connected.
Andrew Trickac6d9be2013-05-25 02:42:55 +00008005 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson825b72b2009-08-11 20:47:22 +00008006 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008007
Nate Begemanb6aef5c2009-09-15 00:18:30 +00008008 // Make sure the new and old chains are cleaned up.
8009 AddToWorkList(Token.getNode());
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008010
Jim Laskey274062c2006-10-13 23:32:28 +00008011 // Replace uses with load result and token factor. Don't add users
8012 // to work list.
8013 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskey279f0532006-09-25 16:29:54 +00008014 }
8015 }
8016
Evan Cheng7fc033a2006-11-03 03:06:21 +00008017 // Try transforming N to an indexed load.
Evan Chengbbd6f6e2006-11-07 09:03:05 +00008018 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman475871a2008-07-27 21:46:04 +00008019 return SDValue(N, 0);
Evan Cheng7fc033a2006-11-03 03:06:21 +00008020
Quentin Colombet83f743a2013-10-11 18:29:42 +00008021 // Try to slice up N to more direct loads if the slices are mapped to
8022 // different register banks or pairing can take place.
8023 if (SliceUpLoad(N))
8024 return SDValue(N, 0);
8025
Dan Gohman475871a2008-07-27 21:46:04 +00008026 return SDValue();
Chris Lattner01a22022005-10-10 22:04:48 +00008027}
8028
Quentin Colombet83f743a2013-10-11 18:29:42 +00008029namespace {
8030/// \brief Helper structure used to slice a load in smaller loads.
8031/// Basically a slice is obtained from the following sequence:
8032/// Origin = load Ty1, Base
8033/// Shift = srl Ty1 Origin, CstTy Amount
8034/// Inst = trunc Shift to Ty2
8035///
8036/// Then, it will be rewriten into:
8037/// Slice = load SliceTy, Base + SliceOffset
8038/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8039///
8040/// SliceTy is deduced from the number of bits that are actually used to
8041/// build Inst.
8042struct LoadedSlice {
8043 /// \brief Helper structure used to compute the cost of a slice.
8044 struct Cost {
8045 /// Are we optimizing for code size.
8046 bool ForCodeSize;
8047 /// Various cost.
8048 unsigned Loads;
8049 unsigned Truncates;
8050 unsigned CrossRegisterBanksCopies;
8051 unsigned ZExts;
8052 unsigned Shift;
8053
8054 Cost(bool ForCodeSize = false)
8055 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8056 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8057
8058 /// \brief Get the cost of one isolated slice.
8059 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8060 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8061 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8062 EVT TruncType = LS.Inst->getValueType(0);
8063 EVT LoadedType = LS.getLoadedType();
8064 if (TruncType != LoadedType &&
8065 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8066 ZExts = 1;
8067 }
8068
8069 /// \brief Account for slicing gain in the current cost.
8070 /// Slicing provide a few gains like removing a shift or a
8071 /// truncate. This method allows to grow the cost of the original
8072 /// load with the gain from this slice.
8073 void addSliceGain(const LoadedSlice &LS) {
8074 // Each slice saves a truncate.
8075 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8076 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8077 LS.Inst->getOperand(0).getValueType()))
8078 ++Truncates;
8079 // If there is a shift amount, this slice gets rid of it.
8080 if (LS.Shift)
8081 ++Shift;
8082 // If this slice can merge a cross register bank copy, account for it.
8083 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8084 ++CrossRegisterBanksCopies;
8085 }
8086
8087 Cost &operator+=(const Cost &RHS) {
8088 Loads += RHS.Loads;
8089 Truncates += RHS.Truncates;
8090 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8091 ZExts += RHS.ZExts;
8092 Shift += RHS.Shift;
8093 return *this;
8094 }
8095
8096 bool operator==(const Cost &RHS) const {
8097 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8098 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8099 ZExts == RHS.ZExts && Shift == RHS.Shift;
8100 }
8101
8102 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8103
8104 bool operator<(const Cost &RHS) const {
8105 // Assume cross register banks copies are as expensive as loads.
8106 // FIXME: Do we want some more target hooks?
8107 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8108 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8109 // Unless we are optimizing for code size, consider the
8110 // expensive operation first.
8111 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8112 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8113 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8114 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8115 }
8116
8117 bool operator>(const Cost &RHS) const { return RHS < *this; }
8118
8119 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8120
8121 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8122 };
8123 // The last instruction that represent the slice. This should be a
8124 // truncate instruction.
8125 SDNode *Inst;
8126 // The original load instruction.
8127 LoadSDNode *Origin;
8128 // The right shift amount in bits from the original load.
8129 unsigned Shift;
8130 // The DAG from which Origin came from.
8131 // This is used to get some contextual information about legal types, etc.
8132 SelectionDAG *DAG;
8133
8134 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
8135 unsigned Shift = 0, SelectionDAG *DAG = NULL)
8136 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8137
8138 LoadedSlice(const LoadedSlice &LS)
8139 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8140
8141 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8142 /// \return Result is \p BitWidth and has used bits set to 1 and
8143 /// not used bits set to 0.
8144 APInt getUsedBits() const {
8145 // Reproduce the trunc(lshr) sequence:
8146 // - Start from the truncated value.
8147 // - Zero extend to the desired bit width.
8148 // - Shift left.
8149 assert(Origin && "No original load to compare against.");
8150 unsigned BitWidth = Origin->getValueSizeInBits(0);
8151 assert(Inst && "This slice is not bound to an instruction");
8152 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8153 "Extracted slice is bigger than the whole type!");
8154 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8155 UsedBits.setAllBits();
8156 UsedBits = UsedBits.zext(BitWidth);
8157 UsedBits <<= Shift;
8158 return UsedBits;
8159 }
8160
8161 /// \brief Get the size of the slice to be loaded in bytes.
8162 unsigned getLoadedSize() const {
8163 unsigned SliceSize = getUsedBits().countPopulation();
8164 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8165 return SliceSize / 8;
8166 }
8167
8168 /// \brief Get the type that will be loaded for this slice.
8169 /// Note: This may not be the final type for the slice.
8170 EVT getLoadedType() const {
8171 assert(DAG && "Missing context");
8172 LLVMContext &Ctxt = *DAG->getContext();
8173 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8174 }
8175
8176 /// \brief Get the alignment of the load used for this slice.
8177 unsigned getAlignment() const {
8178 unsigned Alignment = Origin->getAlignment();
8179 unsigned Offset = getOffsetFromBase();
8180 if (Offset != 0)
8181 Alignment = MinAlign(Alignment, Alignment + Offset);
8182 return Alignment;
8183 }
8184
8185 /// \brief Check if this slice can be rewritten with legal operations.
8186 bool isLegal() const {
8187 // An invalid slice is not legal.
8188 if (!Origin || !Inst || !DAG)
8189 return false;
8190
8191 // Offsets are for indexed load only, we do not handle that.
8192 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8193 return false;
8194
8195 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8196
8197 // Check that the type is legal.
8198 EVT SliceType = getLoadedType();
8199 if (!TLI.isTypeLegal(SliceType))
8200 return false;
8201
8202 // Check that the load is legal for this type.
8203 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8204 return false;
8205
8206 // Check that the offset can be computed.
8207 // 1. Check its type.
8208 EVT PtrType = Origin->getBasePtr().getValueType();
8209 if (PtrType == MVT::Untyped || PtrType.isExtended())
8210 return false;
8211
8212 // 2. Check that it fits in the immediate.
8213 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8214 return false;
8215
8216 // 3. Check that the computation is legal.
8217 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8218 return false;
8219
8220 // Check that the zext is legal if it needs one.
8221 EVT TruncateType = Inst->getValueType(0);
8222 if (TruncateType != SliceType &&
8223 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8224 return false;
8225
8226 return true;
8227 }
8228
8229 /// \brief Get the offset in bytes of this slice in the original chunk of
8230 /// bits.
8231 /// \pre DAG != NULL.
8232 uint64_t getOffsetFromBase() const {
8233 assert(DAG && "Missing context.");
8234 bool IsBigEndian =
8235 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8236 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8237 uint64_t Offset = Shift / 8;
8238 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8239 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8240 "The size of the original loaded type is not a multiple of a"
8241 " byte.");
8242 // If Offset is bigger than TySizeInBytes, it means we are loading all
8243 // zeros. This should have been optimized before in the process.
8244 assert(TySizeInBytes > Offset &&
8245 "Invalid shift amount for given loaded size");
8246 if (IsBigEndian)
8247 Offset = TySizeInBytes - Offset - getLoadedSize();
8248 return Offset;
8249 }
8250
8251 /// \brief Generate the sequence of instructions to load the slice
8252 /// represented by this object and redirect the uses of this slice to
8253 /// this new sequence of instructions.
8254 /// \pre this->Inst && this->Origin are valid Instructions and this
8255 /// object passed the legal check: LoadedSlice::isLegal returned true.
8256 /// \return The last instruction of the sequence used to load the slice.
8257 SDValue loadSlice() const {
8258 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8259 const SDValue &OldBaseAddr = Origin->getBasePtr();
8260 SDValue BaseAddr = OldBaseAddr;
8261 // Get the offset in that chunk of bytes w.r.t. the endianess.
8262 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8263 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8264 if (Offset) {
8265 // BaseAddr = BaseAddr + Offset.
8266 EVT ArithType = BaseAddr.getValueType();
8267 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8268 DAG->getConstant(Offset, ArithType));
8269 }
8270
8271 // Create the type of the loaded slice according to its size.
8272 EVT SliceType = getLoadedType();
8273
8274 // Create the load for the slice.
8275 SDValue LastInst = DAG->getLoad(
8276 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8277 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8278 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8279 // If the final type is not the same as the loaded type, this means that
8280 // we have to pad with zero. Create a zero extend for that.
8281 EVT FinalType = Inst->getValueType(0);
8282 if (SliceType != FinalType)
8283 LastInst =
8284 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8285 return LastInst;
8286 }
8287
8288 /// \brief Check if this slice can be merged with an expensive cross register
8289 /// bank copy. E.g.,
8290 /// i = load i32
8291 /// f = bitcast i32 i to float
8292 bool canMergeExpensiveCrossRegisterBankCopy() const {
8293 if (!Inst || !Inst->hasOneUse())
8294 return false;
8295 SDNode *Use = *Inst->use_begin();
8296 if (Use->getOpcode() != ISD::BITCAST)
8297 return false;
8298 assert(DAG && "Missing context");
8299 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8300 EVT ResVT = Use->getValueType(0);
8301 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8302 const TargetRegisterClass *ArgRC =
8303 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8304 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8305 return false;
8306
8307 // At this point, we know that we perform a cross-register-bank copy.
8308 // Check if it is expensive.
8309 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8310 // Assume bitcasts are cheap, unless both register classes do not
8311 // explicitly share a common sub class.
8312 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8313 return false;
8314
8315 // Check if it will be merged with the load.
8316 // 1. Check the alignment constraint.
8317 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8318 ResVT.getTypeForEVT(*DAG->getContext()));
8319
8320 if (RequiredAlignment > getAlignment())
8321 return false;
8322
8323 // 2. Check that the load is a legal operation for that type.
8324 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8325 return false;
8326
8327 // 3. Check that we do not have a zext in the way.
8328 if (Inst->getValueType(0) != getLoadedType())
8329 return false;
8330
8331 return true;
8332 }
8333};
8334}
8335
Quentin Colombet83f743a2013-10-11 18:29:42 +00008336/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8337/// \p UsedBits looks like 0..0 1..1 0..0.
8338static bool areUsedBitsDense(const APInt &UsedBits) {
8339 // If all the bits are one, this is dense!
8340 if (UsedBits.isAllOnesValue())
8341 return true;
8342
8343 // Get rid of the unused bits on the right.
8344 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8345 // Get rid of the unused bits on the left.
8346 if (NarrowedUsedBits.countLeadingZeros())
8347 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8348 // Check that the chunk of bits is completely used.
8349 return NarrowedUsedBits.isAllOnesValue();
8350}
8351
8352/// \brief Check whether or not \p First and \p Second are next to each other
8353/// in memory. This means that there is no hole between the bits loaded
8354/// by \p First and the bits loaded by \p Second.
8355static bool areSlicesNextToEachOther(const LoadedSlice &First,
8356 const LoadedSlice &Second) {
8357 assert(First.Origin == Second.Origin && First.Origin &&
8358 "Unable to match different memory origins.");
8359 APInt UsedBits = First.getUsedBits();
8360 assert((UsedBits & Second.getUsedBits()) == 0 &&
8361 "Slices are not supposed to overlap.");
8362 UsedBits |= Second.getUsedBits();
8363 return areUsedBitsDense(UsedBits);
8364}
8365
8366/// \brief Adjust the \p GlobalLSCost according to the target
8367/// paring capabilities and the layout of the slices.
8368/// \pre \p GlobalLSCost should account for at least as many loads as
8369/// there is in the slices in \p LoadedSlices.
8370static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8371 LoadedSlice::Cost &GlobalLSCost) {
8372 unsigned NumberOfSlices = LoadedSlices.size();
8373 // If there is less than 2 elements, no pairing is possible.
8374 if (NumberOfSlices < 2)
8375 return;
8376
8377 // Sort the slices so that elements that are likely to be next to each
8378 // other in memory are next to each other in the list.
Stephen Hines36b56882014-04-23 16:57:46 -07008379 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8380 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8381 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8382 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8383 });
Quentin Colombet83f743a2013-10-11 18:29:42 +00008384 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8385 // First (resp. Second) is the first (resp. Second) potentially candidate
8386 // to be placed in a paired load.
8387 const LoadedSlice *First = NULL;
8388 const LoadedSlice *Second = NULL;
8389 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8390 // Set the beginning of the pair.
8391 First = Second) {
8392
8393 Second = &LoadedSlices[CurrSlice];
8394
8395 // If First is NULL, it means we start a new pair.
8396 // Get to the next slice.
8397 if (!First)
8398 continue;
8399
8400 EVT LoadedType = First->getLoadedType();
8401
8402 // If the types of the slices are different, we cannot pair them.
8403 if (LoadedType != Second->getLoadedType())
8404 continue;
8405
8406 // Check if the target supplies paired loads for this type.
8407 unsigned RequiredAlignment = 0;
8408 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8409 // move to the next pair, this type is hopeless.
8410 Second = NULL;
8411 continue;
8412 }
8413 // Check if we meet the alignment requirement.
8414 if (RequiredAlignment > First->getAlignment())
8415 continue;
8416
8417 // Check that both loads are next to each other in memory.
8418 if (!areSlicesNextToEachOther(*First, *Second))
8419 continue;
8420
8421 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8422 --GlobalLSCost.Loads;
8423 // Move to the next pair.
8424 Second = NULL;
8425 }
8426}
8427
8428/// \brief Check the profitability of all involved LoadedSlice.
8429/// Currently, it is considered profitable if there is exactly two
8430/// involved slices (1) which are (2) next to each other in memory, and
8431/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8432///
8433/// Note: The order of the elements in \p LoadedSlices may be modified, but not
8434/// the elements themselves.
8435///
8436/// FIXME: When the cost model will be mature enough, we can relax
8437/// constraints (1) and (2).
8438static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8439 const APInt &UsedBits, bool ForCodeSize) {
8440 unsigned NumberOfSlices = LoadedSlices.size();
8441 if (StressLoadSlicing)
8442 return NumberOfSlices > 1;
8443
8444 // Check (1).
8445 if (NumberOfSlices != 2)
8446 return false;
8447
8448 // Check (2).
8449 if (!areUsedBitsDense(UsedBits))
8450 return false;
8451
8452 // Check (3).
8453 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8454 // The original code has one big load.
8455 OrigCost.Loads = 1;
8456 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8457 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8458 // Accumulate the cost of all the slices.
8459 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8460 GlobalSlicingCost += SliceCost;
8461
8462 // Account as cost in the original configuration the gain obtained
8463 // with the current slices.
8464 OrigCost.addSliceGain(LS);
8465 }
8466
8467 // If the target supports paired load, adjust the cost accordingly.
8468 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8469 return OrigCost > GlobalSlicingCost;
8470}
8471
8472/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8473/// operations, split it in the various pieces being extracted.
8474///
8475/// This sort of thing is introduced by SROA.
8476/// This slicing takes care not to insert overlapping loads.
8477/// \pre LI is a simple load (i.e., not an atomic or volatile load).
8478bool DAGCombiner::SliceUpLoad(SDNode *N) {
8479 if (Level < AfterLegalizeDAG)
8480 return false;
8481
8482 LoadSDNode *LD = cast<LoadSDNode>(N);
8483 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8484 !LD->getValueType(0).isInteger())
8485 return false;
8486
8487 // Keep track of already used bits to detect overlapping values.
8488 // In that case, we will just abort the transformation.
8489 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8490
8491 SmallVector<LoadedSlice, 4> LoadedSlices;
8492
8493 // Check if this load is used as several smaller chunks of bits.
8494 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8495 // of computation for each trunc.
8496 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8497 UI != UIEnd; ++UI) {
8498 // Skip the uses of the chain.
8499 if (UI.getUse().getResNo() != 0)
8500 continue;
8501
8502 SDNode *User = *UI;
8503 unsigned Shift = 0;
8504
8505 // Check if this is a trunc(lshr).
8506 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8507 isa<ConstantSDNode>(User->getOperand(1))) {
8508 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8509 User = *User->use_begin();
8510 }
8511
8512 // At this point, User is a Truncate, iff we encountered, trunc or
8513 // trunc(lshr).
8514 if (User->getOpcode() != ISD::TRUNCATE)
8515 return false;
8516
8517 // The width of the type must be a power of 2 and greater than 8-bits.
8518 // Otherwise the load cannot be represented in LLVM IR.
Stephen Hines36b56882014-04-23 16:57:46 -07008519 // Moreover, if we shifted with a non-8-bits multiple, the slice
8520 // will be across several bytes. We do not support that.
Quentin Colombet83f743a2013-10-11 18:29:42 +00008521 unsigned Width = User->getValueSizeInBits(0);
8522 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8523 return 0;
8524
8525 // Build the slice for this chain of computations.
8526 LoadedSlice LS(User, LD, Shift, &DAG);
8527 APInt CurrentUsedBits = LS.getUsedBits();
8528
8529 // Check if this slice overlaps with another.
8530 if ((CurrentUsedBits & UsedBits) != 0)
8531 return false;
8532 // Update the bits used globally.
8533 UsedBits |= CurrentUsedBits;
8534
8535 // Check if the new slice would be legal.
8536 if (!LS.isLegal())
8537 return false;
8538
8539 // Record the slice.
8540 LoadedSlices.push_back(LS);
8541 }
8542
8543 // Abort slicing if it does not seem to be profitable.
8544 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8545 return false;
8546
8547 ++SlicedLoads;
8548
8549 // Rewrite each chain to use an independent load.
8550 // By construction, each chain can be represented by a unique load.
8551
8552 // Prepare the argument for the new token factor for all the slices.
8553 SmallVector<SDValue, 8> ArgChains;
8554 for (SmallVectorImpl<LoadedSlice>::const_iterator
8555 LSIt = LoadedSlices.begin(),
8556 LSItEnd = LoadedSlices.end();
8557 LSIt != LSItEnd; ++LSIt) {
8558 SDValue SliceInst = LSIt->loadSlice();
8559 CombineTo(LSIt->Inst, SliceInst, true);
8560 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8561 SliceInst = SliceInst.getOperand(0);
8562 assert(SliceInst->getOpcode() == ISD::LOAD &&
8563 "It takes more than a zext to get to the loaded slice!!");
8564 ArgChains.push_back(SliceInst.getValue(1));
8565 }
8566
8567 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8568 &ArgChains[0], ArgChains.size());
8569 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8570 return true;
8571}
8572
Chris Lattner2392ae72010-04-15 04:48:01 +00008573/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8574/// load is having specific bytes cleared out. If so, return the byte size
8575/// being masked out and the shift amount.
8576static std::pair<unsigned, unsigned>
8577CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8578 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008579
Chris Lattner2392ae72010-04-15 04:48:01 +00008580 // Check for the structure we're looking for.
8581 if (V->getOpcode() != ISD::AND ||
8582 !isa<ConstantSDNode>(V->getOperand(1)) ||
8583 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8584 return Result;
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008585
Chris Lattnere6987582010-04-15 06:10:49 +00008586 // Check the chain and pointer.
Chris Lattner2392ae72010-04-15 04:48:01 +00008587 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattnere6987582010-04-15 06:10:49 +00008588 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008589
Chris Lattnere6987582010-04-15 06:10:49 +00008590 // The store should be chained directly to the load or be an operand of a
8591 // tokenfactor.
8592 if (LD == Chain.getNode())
8593 ; // ok.
8594 else if (Chain->getOpcode() != ISD::TokenFactor)
8595 return Result; // Fail.
8596 else {
8597 bool isOk = false;
8598 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8599 if (Chain->getOperand(i).getNode() == LD) {
8600 isOk = true;
8601 break;
8602 }
8603 if (!isOk) return Result;
8604 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008605
Chris Lattner2392ae72010-04-15 04:48:01 +00008606 // This only handles simple types.
8607 if (V.getValueType() != MVT::i16 &&
8608 V.getValueType() != MVT::i32 &&
8609 V.getValueType() != MVT::i64)
8610 return Result;
8611
8612 // Check the constant mask. Invert it so that the bits being masked out are
8613 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8614 // follow the sign bit for uniformity.
8615 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerc6af2432013-05-24 22:23:49 +00008616 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner2392ae72010-04-15 04:48:01 +00008617 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerc6af2432013-05-24 22:23:49 +00008618 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner2392ae72010-04-15 04:48:01 +00008619 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8620 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008621
Chris Lattner2392ae72010-04-15 04:48:01 +00008622 // See if we have a continuous run of bits. If so, we have 0*1+0*
8623 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8624 return Result;
8625
8626 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8627 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8628 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008629
Chris Lattner2392ae72010-04-15 04:48:01 +00008630 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8631 switch (MaskedBytes) {
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008632 case 1:
8633 case 2:
Chris Lattner2392ae72010-04-15 04:48:01 +00008634 case 4: break;
8635 default: return Result; // All one mask, or 5-byte mask.
8636 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008637
Chris Lattner2392ae72010-04-15 04:48:01 +00008638 // Verify that the first bit starts at a multiple of mask so that the access
8639 // is aligned the same as the access width.
8640 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008641
Chris Lattner2392ae72010-04-15 04:48:01 +00008642 Result.first = MaskedBytes;
8643 Result.second = NotMaskTZ/8;
8644 return Result;
8645}
8646
8647
8648/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8649/// provides a value as specified by MaskInfo. If so, replace the specified
8650/// store with a narrower store of truncated IVal.
8651static SDNode *
8652ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8653 SDValue IVal, StoreSDNode *St,
8654 DAGCombiner *DC) {
8655 unsigned NumBytes = MaskInfo.first;
8656 unsigned ByteShift = MaskInfo.second;
8657 SelectionDAG &DAG = DC->getDAG();
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008658
Chris Lattner2392ae72010-04-15 04:48:01 +00008659 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8660 // that uses this. If not, this is not a replacement.
8661 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8662 ByteShift*8, (ByteShift+NumBytes)*8);
8663 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008664
Chris Lattner2392ae72010-04-15 04:48:01 +00008665 // Check that it is legal on the target to do this. It is legal if the new
8666 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8667 // legalization.
8668 MVT VT = MVT::getIntegerVT(NumBytes*8);
8669 if (!DC->isTypeLegal(VT))
8670 return 0;
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008671
Chris Lattner2392ae72010-04-15 04:48:01 +00008672 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8673 // shifted by ByteShift and truncated down to NumBytes.
8674 if (ByteShift)
Andrew Trickac6d9be2013-05-25 02:42:55 +00008675 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Anderson95771af2011-02-25 21:41:48 +00008676 DAG.getConstant(ByteShift*8,
8677 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner2392ae72010-04-15 04:48:01 +00008678
8679 // Figure out the offset for the store and the alignment of the access.
8680 unsigned StOffset;
8681 unsigned NewAlign = St->getAlignment();
8682
8683 if (DAG.getTargetLoweringInfo().isLittleEndian())
8684 StOffset = ByteShift;
8685 else
8686 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008687
Chris Lattner2392ae72010-04-15 04:48:01 +00008688 SDValue Ptr = St->getBasePtr();
8689 if (StOffset) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00008690 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner2392ae72010-04-15 04:48:01 +00008691 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8692 NewAlign = MinAlign(NewAlign, StOffset);
8693 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008694
Chris Lattner2392ae72010-04-15 04:48:01 +00008695 // Truncate down to the new size.
Andrew Trickac6d9be2013-05-25 02:42:55 +00008696 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008697
Chris Lattner2392ae72010-04-15 04:48:01 +00008698 ++OpsNarrowed;
Andrew Trickac6d9be2013-05-25 02:42:55 +00008699 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner6229d0a2010-09-21 18:41:36 +00008700 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner2392ae72010-04-15 04:48:01 +00008701 false, false, NewAlign).getNode();
8702}
8703
Evan Cheng8b944d32009-05-28 00:35:15 +00008704
8705/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8706/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8707/// of the loaded bits, try narrowing the load and store if it would end up
8708/// being a win for performance or code size.
8709SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8710 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Chengcdcecc02009-05-28 18:41:02 +00008711 if (ST->isVolatile())
8712 return SDValue();
8713
Evan Cheng8b944d32009-05-28 00:35:15 +00008714 SDValue Chain = ST->getChain();
8715 SDValue Value = ST->getValue();
8716 SDValue Ptr = ST->getBasePtr();
Owen Andersone50ed302009-08-10 22:56:29 +00008717 EVT VT = Value.getValueType();
Evan Cheng8b944d32009-05-28 00:35:15 +00008718
8719 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Chengcdcecc02009-05-28 18:41:02 +00008720 return SDValue();
Evan Cheng8b944d32009-05-28 00:35:15 +00008721
8722 unsigned Opc = Value.getOpcode();
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008723
Chris Lattner2392ae72010-04-15 04:48:01 +00008724 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8725 // is a byte mask indicating a consecutive number of bytes, check to see if
8726 // Y is known to provide just those bytes. If so, we try to replace the
8727 // load + replace + store sequence with a single (narrower) store, which makes
8728 // the load dead.
8729 if (Opc == ISD::OR) {
8730 std::pair<unsigned, unsigned> MaskedLoad;
8731 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8732 if (MaskedLoad.first)
8733 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8734 Value.getOperand(1), ST,this))
8735 return SDValue(NewST, 0);
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008736
Chris Lattner2392ae72010-04-15 04:48:01 +00008737 // Or is commutative, so try swapping X and Y.
8738 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8739 if (MaskedLoad.first)
8740 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8741 Value.getOperand(0), ST,this))
8742 return SDValue(NewST, 0);
8743 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008744
Evan Cheng8b944d32009-05-28 00:35:15 +00008745 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8746 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Chengcdcecc02009-05-28 18:41:02 +00008747 return SDValue();
Evan Cheng8b944d32009-05-28 00:35:15 +00008748
8749 SDValue N0 = Value.getOperand(0);
Dan Gohman24bde5b2010-09-02 21:18:42 +00008750 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8751 Chain == SDValue(N0.getNode(), 1)) {
Evan Cheng8b944d32009-05-28 00:35:15 +00008752 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerfa459012010-09-21 16:08:50 +00008753 if (LD->getBasePtr() != Ptr ||
8754 LD->getPointerInfo().getAddrSpace() !=
8755 ST->getPointerInfo().getAddrSpace())
Evan Chengcdcecc02009-05-28 18:41:02 +00008756 return SDValue();
Evan Cheng8b944d32009-05-28 00:35:15 +00008757
8758 // Find the type to narrow it the load / op / store to.
8759 SDValue N1 = Value.getOperand(1);
8760 unsigned BitWidth = N1.getValueSizeInBits();
8761 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8762 if (Opc == ISD::AND)
8763 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Chengd3c76bb2009-05-28 23:52:18 +00008764 if (Imm == 0 || Imm.isAllOnesValue())
8765 return SDValue();
Evan Cheng8b944d32009-05-28 00:35:15 +00008766 unsigned ShAmt = Imm.countTrailingZeros();
8767 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8768 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson23b9b192009-08-12 00:36:31 +00008769 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Cheng8b944d32009-05-28 00:35:15 +00008770 while (NewBW < BitWidth &&
Evan Chengcdcecc02009-05-28 18:41:02 +00008771 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
Evan Cheng8b944d32009-05-28 00:35:15 +00008772 TLI.isNarrowingProfitable(VT, NewVT))) {
8773 NewBW = NextPowerOf2(NewBW);
Owen Anderson23b9b192009-08-12 00:36:31 +00008774 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Cheng8b944d32009-05-28 00:35:15 +00008775 }
Evan Chengcdcecc02009-05-28 18:41:02 +00008776 if (NewBW >= BitWidth)
8777 return SDValue();
Evan Cheng8b944d32009-05-28 00:35:15 +00008778
8779 // If the lsb changed does not start at the type bitwidth boundary,
8780 // start at the previous one.
8781 if (ShAmt % NewBW)
8782 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren981b9632012-12-12 01:13:50 +00008783 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8784 std::min(BitWidth, ShAmt + NewBW));
Evan Cheng8b944d32009-05-28 00:35:15 +00008785 if ((Imm & Mask) == Imm) {
8786 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8787 if (Opc == ISD::AND)
8788 NewImm ^= APInt::getAllOnesValue(NewBW);
8789 uint64_t PtrOff = ShAmt / 8;
8790 // For big endian targets, we need to adjust the offset to the pointer to
8791 // load the correct bytes.
8792 if (TLI.isBigEndian())
Evan Chengcdcecc02009-05-28 18:41:02 +00008793 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Cheng8b944d32009-05-28 00:35:15 +00008794
8795 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00008796 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmow3574eca2012-10-08 16:38:25 +00008797 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Chengcdcecc02009-05-28 18:41:02 +00008798 return SDValue();
8799
Andrew Trickac6d9be2013-05-25 02:42:55 +00008800 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Cheng8b944d32009-05-28 00:35:15 +00008801 Ptr.getValueType(), Ptr,
8802 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickac6d9be2013-05-25 02:42:55 +00008803 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Cheng8b944d32009-05-28 00:35:15 +00008804 LD->getChain(), NewPtr,
Chris Lattnerfa459012010-09-21 16:08:50 +00008805 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene1e559442010-02-15 17:00:31 +00008806 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00008807 LD->isInvariant(), NewAlign,
8808 LD->getTBAAInfo());
Andrew Trickac6d9be2013-05-25 02:42:55 +00008809 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Cheng8b944d32009-05-28 00:35:15 +00008810 DAG.getConstant(NewImm, NewVT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00008811 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Cheng8b944d32009-05-28 00:35:15 +00008812 NewVal, NewPtr,
Chris Lattnerfa459012010-09-21 16:08:50 +00008813 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene1e559442010-02-15 17:00:31 +00008814 false, false, NewAlign);
Evan Cheng8b944d32009-05-28 00:35:15 +00008815
8816 AddToWorkList(NewPtr.getNode());
8817 AddToWorkList(NewLD.getNode());
8818 AddToWorkList(NewVal.getNode());
8819 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00008820 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Cheng8b944d32009-05-28 00:35:15 +00008821 ++OpsNarrowed;
8822 return NewST;
8823 }
8824 }
8825
Evan Chengcdcecc02009-05-28 18:41:02 +00008826 return SDValue();
Evan Cheng8b944d32009-05-28 00:35:15 +00008827}
8828
Evan Cheng31959b12011-02-02 01:06:55 +00008829/// TransformFPLoadStorePair - For a given floating point load / store pair,
8830/// if the load value isn't used by any other operations, then consider
8831/// transforming the pair to integer load / store operations if the target
8832/// deems the transformation profitable.
8833SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8834 StoreSDNode *ST = cast<StoreSDNode>(N);
8835 SDValue Chain = ST->getChain();
8836 SDValue Value = ST->getValue();
8837 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8838 Value.hasOneUse() &&
8839 Chain == SDValue(Value.getNode(), 1)) {
8840 LoadSDNode *LD = cast<LoadSDNode>(Value);
8841 EVT VT = LD->getMemoryVT();
8842 if (!VT.isFloatingPoint() ||
8843 VT != ST->getMemoryVT() ||
8844 LD->isNonTemporal() ||
8845 ST->isNonTemporal() ||
8846 LD->getPointerInfo().getAddrSpace() != 0 ||
8847 ST->getPointerInfo().getAddrSpace() != 0)
8848 return SDValue();
8849
8850 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8851 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8852 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8853 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8854 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8855 return SDValue();
8856
8857 unsigned LDAlign = LD->getAlignment();
8858 unsigned STAlign = ST->getAlignment();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00008859 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmow3574eca2012-10-08 16:38:25 +00008860 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Cheng31959b12011-02-02 01:06:55 +00008861 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8862 return SDValue();
8863
Andrew Trickac6d9be2013-05-25 02:42:55 +00008864 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Cheng31959b12011-02-02 01:06:55 +00008865 LD->getChain(), LD->getBasePtr(),
8866 LD->getPointerInfo(),
Pete Cooperd752e0f2011-11-08 18:42:53 +00008867 false, false, false, LDAlign);
Evan Cheng31959b12011-02-02 01:06:55 +00008868
Andrew Trickac6d9be2013-05-25 02:42:55 +00008869 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Cheng31959b12011-02-02 01:06:55 +00008870 NewLD, ST->getBasePtr(),
8871 ST->getPointerInfo(),
8872 false, false, STAlign);
8873
8874 AddToWorkList(NewLD.getNode());
8875 AddToWorkList(NewST.getNode());
8876 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00008877 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Cheng31959b12011-02-02 01:06:55 +00008878 ++LdStFP2Int;
8879 return NewST;
8880 }
8881
8882 return SDValue();
8883}
8884
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008885/// Helper struct to parse and store a memory address as base + index + offset.
8886/// We ignore sign extensions when it is safe to do so.
8887/// The following two expressions are not equivalent. To differentiate we need
8888/// to store whether there was a sign extension involved in the index
8889/// computation.
8890/// (load (i64 add (i64 copyfromreg %c)
8891/// (i64 signextend (add (i8 load %index)
8892/// (i8 1))))
8893/// vs
8894///
8895/// (load (i64 add (i64 copyfromreg %c)
8896/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8897/// (i32 1)))))
8898struct BaseIndexOffset {
8899 SDValue Base;
8900 SDValue Index;
8901 int64_t Offset;
8902 bool IsIndexSignExt;
8903
8904 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8905
8906 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8907 bool IsIndexSignExt) :
8908 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8909
8910 bool equalBaseIndex(const BaseIndexOffset &Other) {
8911 return Other.Base == Base && Other.Index == Index &&
8912 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotemc653de62012-10-03 16:11:15 +00008913 }
8914
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008915 /// Parses tree in Ptr for base, index, offset addresses.
8916 static BaseIndexOffset match(SDValue Ptr) {
8917 bool IsIndexSignExt = false;
8918
Juergen Ributzka915e9362013-08-21 21:53:38 +00008919 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8920 // instruction, then it could be just the BASE or everything else we don't
8921 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008922 if (Ptr->getOpcode() != ISD::ADD)
8923 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8924
Juergen Ributzka915e9362013-08-21 21:53:38 +00008925 // We know that we have at least an ADD instruction. Try to pattern match
8926 // the simple case of BASE + OFFSET.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008927 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8928 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8929 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8930 IsIndexSignExt);
8931 }
8932
Juergen Ributzka915e9362013-08-21 21:53:38 +00008933 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka2b884bc2013-08-28 22:33:58 +00008934 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka915e9362013-08-21 21:53:38 +00008935 // (i64 add (i64 %array_ptr)
8936 // (i64 mul (i64 %induction_var)
8937 // (i64 %element_size)))
Juergen Ributzka2b884bc2013-08-28 22:33:58 +00008938 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka915e9362013-08-21 21:53:38 +00008939 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka915e9362013-08-21 21:53:38 +00008940
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008941 // Look at Base + Index + Offset cases.
8942 SDValue Base = Ptr->getOperand(0);
8943 SDValue IndexOffset = Ptr->getOperand(1);
8944
8945 // Skip signextends.
8946 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8947 IndexOffset = IndexOffset->getOperand(0);
8948 IsIndexSignExt = true;
8949 }
8950
8951 // Either the case of Base + Index (no offset) or something else.
8952 if (IndexOffset->getOpcode() != ISD::ADD)
8953 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8954
8955 // Now we have the case of Base + Index + offset.
8956 SDValue Index = IndexOffset->getOperand(0);
8957 SDValue Offset = IndexOffset->getOperand(1);
8958
8959 if (!isa<ConstantSDNode>(Offset))
8960 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8961
8962 // Ignore signextends.
8963 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8964 Index = Index->getOperand(0);
8965 IsIndexSignExt = true;
8966 } else IsIndexSignExt = false;
8967
8968 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8969 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8970 }
8971};
Nadav Rotemc653de62012-10-03 16:11:15 +00008972
8973/// Holds a pointer to an LSBaseSDNode as well as information on where it
8974/// is located in a sequence of memory operations connected by a chain.
8975struct MemOpLink {
8976 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8977 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8978 // Ptr to the mem node.
8979 LSBaseSDNode *MemNode;
8980 // Offset from the base ptr.
8981 int64_t OffsetFromBase;
8982 // What is the sequence number of this mem node.
8983 // Lowest mem operand in the DAG starts at zero.
8984 unsigned SequenceNum;
8985};
8986
Nadav Rotemc653de62012-10-03 16:11:15 +00008987bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8988 EVT MemVT = St->getMemoryVT();
8989 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Nadav Rotem6cc4b8d2013-02-14 18:28:52 +00008990 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8991 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
Nadav Rotemc653de62012-10-03 16:11:15 +00008992
8993 // Don't merge vectors into wider inputs.
8994 if (MemVT.isVector() || !MemVT.isSimple())
8995 return false;
8996
8997 // Perform an early exit check. Do not bother looking at stored values that
8998 // are not constants or loads.
8999 SDValue StoredVal = St->getValue();
9000 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9001 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9002 !IsLoadSrc)
9003 return false;
9004
9005 // Only look at ends of store sequences.
9006 SDValue Chain = SDValue(St, 1);
9007 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9008 return false;
9009
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00009010 // This holds the base pointer, index, and the offset in bytes from the base
9011 // pointer.
9012 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotemc653de62012-10-03 16:11:15 +00009013
9014 // We must have a base and an offset.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00009015 if (!BasePtr.Base.getNode())
Nadav Rotemc653de62012-10-03 16:11:15 +00009016 return false;
9017
9018 // Do not handle stores to undef base pointers.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00009019 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotemc653de62012-10-03 16:11:15 +00009020 return false;
9021
Nadav Rotem90e11dc2012-11-29 00:00:08 +00009022 // Save the LoadSDNodes that we find in the chain.
9023 // We need to make sure that these nodes do not interfere with
9024 // any of the store nodes.
9025 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9026
9027 // Save the StoreSDNodes that we find in the chain.
Nadav Rotemc653de62012-10-03 16:11:15 +00009028 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem90e11dc2012-11-29 00:00:08 +00009029
Nadav Rotemc653de62012-10-03 16:11:15 +00009030 // Walk up the chain and look for nodes with offsets from the same
9031 // base pointer. Stop when reaching an instruction with a different kind
9032 // or instruction which has a different base pointer.
9033 unsigned Seq = 0;
9034 StoreSDNode *Index = St;
9035 while (Index) {
9036 // If the chain has more than one use, then we can't reorder the mem ops.
9037 if (Index != St && !SDValue(Index, 1)->hasOneUse())
9038 break;
9039
9040 // Find the base pointer and offset for this memory node.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00009041 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotemc653de62012-10-03 16:11:15 +00009042
9043 // Check that the base pointer is the same as the original one.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00009044 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotemc653de62012-10-03 16:11:15 +00009045 break;
9046
9047 // Check that the alignment is the same.
9048 if (Index->getAlignment() != St->getAlignment())
9049 break;
9050
9051 // The memory operands must not be volatile.
9052 if (Index->isVolatile() || Index->isIndexed())
9053 break;
9054
9055 // No truncation.
9056 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9057 if (St->isTruncatingStore())
9058 break;
9059
9060 // The stored memory type must be the same.
9061 if (Index->getMemoryVT() != MemVT)
9062 break;
9063
9064 // We do not allow unaligned stores because we want to prevent overriding
9065 // stores.
9066 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9067 break;
9068
9069 // We found a potential memory operand to merge.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00009070 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotemc653de62012-10-03 16:11:15 +00009071
Nadav Rotem90e11dc2012-11-29 00:00:08 +00009072 // Find the next memory operand in the chain. If the next operand in the
9073 // chain is a store then move up and continue the scan with the next
9074 // memory operand. If the next operand is a load save it and use alias
9075 // information to check if it interferes with anything.
9076 SDNode *NextInChain = Index->getChain().getNode();
9077 while (1) {
Nadav Rotemdde785c2012-12-06 17:34:13 +00009078 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem90e11dc2012-11-29 00:00:08 +00009079 // We found a store node. Use it for the next iteration.
Nadav Rotemdde785c2012-12-06 17:34:13 +00009080 Index = STn;
Nadav Rotem90e11dc2012-11-29 00:00:08 +00009081 break;
9082 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling13498992013-11-25 18:08:07 +00009083 if (Ldn->isVolatile()) {
9084 Index = NULL;
9085 break;
9086 }
9087
Nadav Rotem90e11dc2012-11-29 00:00:08 +00009088 // Save the load node for later. Continue the scan.
9089 AliasLoadNodes.push_back(Ldn);
9090 NextInChain = Ldn->getChain().getNode();
9091 continue;
9092 } else {
9093 Index = NULL;
9094 break;
9095 }
9096 }
Nadav Rotemc653de62012-10-03 16:11:15 +00009097 }
9098
9099 // Check if there is anything to merge.
9100 if (StoreNodes.size() < 2)
9101 return false;
9102
9103 // Sort the memory operands according to their distance from the base pointer.
9104 std::sort(StoreNodes.begin(), StoreNodes.end(),
Stephen Hines36b56882014-04-23 16:57:46 -07009105 [](MemOpLink LHS, MemOpLink RHS) {
9106 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9107 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9108 LHS.SequenceNum > RHS.SequenceNum);
9109 });
Nadav Rotemc653de62012-10-03 16:11:15 +00009110
9111 // Scan the memory operations on the chain and find the first non-consecutive
9112 // store memory address.
9113 unsigned LastConsecutiveStore = 0;
9114 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemdde785c2012-12-06 17:34:13 +00009115 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9116
9117 // Check that the addresses are consecutive starting from the second
9118 // element in the list of stores.
9119 if (i > 0) {
9120 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9121 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9122 break;
9123 }
Nadav Rotemc653de62012-10-03 16:11:15 +00009124
Nadav Rotem90e11dc2012-11-29 00:00:08 +00009125 bool Alias = false;
9126 // Check if this store interferes with any of the loads that we found.
9127 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9128 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9129 Alias = true;
9130 break;
9131 }
Nadav Rotem90e11dc2012-11-29 00:00:08 +00009132 // We found a load that alias with this store. Stop the sequence.
9133 if (Alias)
9134 break;
9135
Nadav Rotemc653de62012-10-03 16:11:15 +00009136 // Mark this node as useful.
9137 LastConsecutiveStore = i;
9138 }
9139
9140 // The node with the lowest store address.
9141 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9142
9143 // Store the constants into memory as one consecutive store.
9144 if (!IsLoadSrc) {
Nadav Rotemc653de62012-10-03 16:11:15 +00009145 unsigned LastLegalType = 0;
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009146 unsigned LastLegalVectorType = 0;
9147 bool NonZero = false;
Nadav Rotemc653de62012-10-03 16:11:15 +00009148 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9149 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9150 SDValue StoredVal = St->getValue();
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009151
9152 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramerebd7eab2012-10-05 18:19:44 +00009153 NonZero |= !C->isNullValue();
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009154 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramerebd7eab2012-10-05 18:19:44 +00009155 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009156 } else {
Stephen Hines36b56882014-04-23 16:57:46 -07009157 // Non-constant.
Nadav Rotemc653de62012-10-03 16:11:15 +00009158 break;
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009159 }
Nadav Rotemc653de62012-10-03 16:11:15 +00009160
Nadav Rotemc653de62012-10-03 16:11:15 +00009161 // Find a legal type for the constant store.
9162 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9163 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9164 if (TLI.isTypeLegal(StoreTy))
9165 LastLegalType = i+1;
Arnold Schwaighofere7370182013-04-02 15:58:51 +00009166 // Or check whether a truncstore is legal.
9167 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9168 TargetLowering::TypePromoteInteger) {
9169 EVT LegalizedStoredValueTy =
9170 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9171 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9172 LastLegalType = i+1;
9173 }
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009174
9175 // Find a legal type for the vector store.
9176 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9177 if (TLI.isTypeLegal(Ty))
9178 LastLegalVectorType = i + 1;
Nadav Rotemc653de62012-10-03 16:11:15 +00009179 }
9180
Bob Wilson99d8e762012-12-20 01:36:20 +00009181 // We only use vectors if the constant is known to be zero and the
9182 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem6cc4b8d2013-02-14 18:28:52 +00009183 if (NonZero || NoVectors)
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009184 LastLegalVectorType = 0;
9185
Nadav Rotemc653de62012-10-03 16:11:15 +00009186 // Check if we found a legal integer type to store.
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009187 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotemc653de62012-10-03 16:11:15 +00009188 return false;
9189
Nadav Rotem6cc4b8d2013-02-14 18:28:52 +00009190 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009191 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9192
9193 // Make sure we have something to merge.
9194 if (NumElem < 2)
9195 return false;
Nadav Rotemc653de62012-10-03 16:11:15 +00009196
9197 unsigned EarliestNodeUsed = 0;
9198 for (unsigned i=0; i < NumElem; ++i) {
9199 // Find a chain for the new wide-store operand. Notice that some
9200 // of the store nodes that we found may not be selected for inclusion
9201 // in the wide store. The chain we use needs to be the chain of the
9202 // earliest store node which is *used* and replaced by the wide store.
9203 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9204 EarliestNodeUsed = i;
9205 }
9206
9207 // The earliest Node in the DAG.
9208 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
Andrew Trickac6d9be2013-05-25 02:42:55 +00009209 SDLoc DL(StoreNodes[0].MemNode);
Nadav Rotemc653de62012-10-03 16:11:15 +00009210
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009211 SDValue StoredVal;
9212 if (UseVector) {
9213 // Find a legal type for the vector store.
9214 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9215 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9216 StoredVal = DAG.getConstant(0, Ty);
9217 } else {
9218 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9219 APInt StoreInt(StoreBW, 0);
9220
9221 // Construct a single integer constant which is made of the smaller
9222 // constant inputs.
9223 bool IsLE = TLI.isLittleEndian();
9224 for (unsigned i = 0; i < NumElem ; ++i) {
9225 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9226 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9227 SDValue Val = St->getValue();
9228 StoreInt<<=ElementSizeBytes*8;
9229 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9230 StoreInt|=C->getAPIntValue().zext(StoreBW);
9231 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9232 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9233 } else {
9234 assert(false && "Invalid constant element type");
9235 }
Nadav Rotemc653de62012-10-03 16:11:15 +00009236 }
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009237
9238 // Create the new Load and Store operations.
9239 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9240 StoredVal = DAG.getConstant(StoreInt, StoreTy);
Nadav Rotemc653de62012-10-03 16:11:15 +00009241 }
9242
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009243 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
Nadav Rotemc653de62012-10-03 16:11:15 +00009244 FirstInChain->getBasePtr(),
9245 FirstInChain->getPointerInfo(),
9246 false, false,
9247 FirstInChain->getAlignment());
9248
9249 // Replace the first store with the new store
9250 CombineTo(EarliestOp, NewStore);
9251 // Erase all other stores.
9252 for (unsigned i = 0; i < NumElem ; ++i) {
9253 if (StoreNodes[i].MemNode == EarliestOp)
9254 continue;
9255 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Rafael Espindola8e2b8ae2012-11-14 05:08:56 +00009256 // ReplaceAllUsesWith will replace all uses that existed when it was
9257 // called, but graph optimizations may cause new ones to appear. For
9258 // example, the case in pr14333 looks like
9259 //
9260 // St's chain -> St -> another store -> X
9261 //
9262 // And the only difference from St to the other store is the chain.
9263 // When we change it's chain to be St's chain they become identical,
9264 // get CSEed and the net result is that X is now a use of St.
9265 // Since we know that St is redundant, just iterate.
9266 while (!St->use_empty())
9267 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
Nadav Rotemc653de62012-10-03 16:11:15 +00009268 removeFromWorkList(St);
9269 DAG.DeleteNode(St);
9270 }
9271
9272 return true;
9273 }
9274
9275 // Below we handle the case of multiple consecutive stores that
9276 // come from multiple consecutive loads. We merge them into a single
9277 // wide load and a single wide store.
9278
9279 // Look for load nodes which are used by the stored values.
9280 SmallVector<MemOpLink, 8> LoadNodes;
9281
9282 // Find acceptable loads. Loads need to have the same chain (token factor),
9283 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00009284 BaseIndexOffset LdBasePtr;
Nadav Rotemc653de62012-10-03 16:11:15 +00009285 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9286 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9287 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9288 if (!Ld) break;
9289
9290 // Loads must only have one use.
9291 if (!Ld->hasNUsesOfValue(1, 0))
9292 break;
9293
9294 // Check that the alignment is the same as the stores.
9295 if (Ld->getAlignment() != St->getAlignment())
9296 break;
9297
9298 // The memory operands must not be volatile.
9299 if (Ld->isVolatile() || Ld->isIndexed())
9300 break;
9301
9302 // We do not accept ext loads.
9303 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9304 break;
9305
9306 // The stored memory type must be the same.
9307 if (Ld->getMemoryVT() != MemVT)
9308 break;
9309
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00009310 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotemc653de62012-10-03 16:11:15 +00009311 // If this is not the first ptr that we check.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00009312 if (LdBasePtr.Base.getNode()) {
Nadav Rotemc653de62012-10-03 16:11:15 +00009313 // The base ptr must be the same.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00009314 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotemc653de62012-10-03 16:11:15 +00009315 break;
9316 } else {
9317 // Check that all other base pointers are the same as this one.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00009318 LdBasePtr = LdPtr;
Nadav Rotemc653de62012-10-03 16:11:15 +00009319 }
9320
9321 // We found a potential memory operand to merge.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00009322 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotemc653de62012-10-03 16:11:15 +00009323 }
9324
9325 if (LoadNodes.size() < 2)
9326 return false;
9327
9328 // Scan the memory operations on the chain and find the first non-consecutive
9329 // load memory address. These variables hold the index in the store node
9330 // array.
9331 unsigned LastConsecutiveLoad = 0;
9332 // This variable refers to the size and not index in the array.
9333 unsigned LastLegalVectorType = 0;
9334 unsigned LastLegalIntegerType = 0;
9335 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotem2e7d3812012-10-03 19:30:31 +00009336 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9337 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9338 // All loads much share the same chain.
9339 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9340 break;
Nadav Rotem6cc4b8d2013-02-14 18:28:52 +00009341
Nadav Rotemc653de62012-10-03 16:11:15 +00009342 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9343 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9344 break;
9345 LastConsecutiveLoad = i;
9346
9347 // Find a legal type for the vector store.
9348 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9349 if (TLI.isTypeLegal(StoreTy))
9350 LastLegalVectorType = i + 1;
9351
9352 // Find a legal type for the integer store.
9353 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9354 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9355 if (TLI.isTypeLegal(StoreTy))
9356 LastLegalIntegerType = i + 1;
Arnold Schwaighofere7370182013-04-02 15:58:51 +00009357 // Or check whether a truncstore and extload is legal.
9358 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9359 TargetLowering::TypePromoteInteger) {
9360 EVT LegalizedStoredValueTy =
9361 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9362 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9363 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9364 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9365 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9366 LastLegalIntegerType = i+1;
9367 }
Nadav Rotemc653de62012-10-03 16:11:15 +00009368 }
9369
9370 // Only use vector types if the vector type is larger than the integer type.
9371 // If they are the same, use integers.
Nadav Rotem6cc4b8d2013-02-14 18:28:52 +00009372 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotemc653de62012-10-03 16:11:15 +00009373 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9374
9375 // We add +1 here because the LastXXX variables refer to location while
9376 // the NumElem refers to array/index size.
9377 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9378 NumElem = std::min(LastLegalType, NumElem);
9379
9380 if (NumElem < 2)
9381 return false;
9382
9383 // The earliest Node in the DAG.
9384 unsigned EarliestNodeUsed = 0;
9385 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9386 for (unsigned i=1; i<NumElem; ++i) {
9387 // Find a chain for the new wide-store operand. Notice that some
9388 // of the store nodes that we found may not be selected for inclusion
9389 // in the wide store. The chain we use needs to be the chain of the
9390 // earliest store node which is *used* and replaced by the wide store.
9391 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9392 EarliestNodeUsed = i;
9393 }
9394
9395 // Find if it is better to use vectors or integers to load and store
9396 // to memory.
9397 EVT JointMemOpVT;
9398 if (UseVectorTy) {
9399 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9400 } else {
9401 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9402 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9403 }
9404
Andrew Trickac6d9be2013-05-25 02:42:55 +00009405 SDLoc LoadDL(LoadNodes[0].MemNode);
9406 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotemc653de62012-10-03 16:11:15 +00009407
9408 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9409 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9410 FirstLoad->getChain(),
9411 FirstLoad->getBasePtr(),
9412 FirstLoad->getPointerInfo(),
9413 false, false, false,
9414 FirstLoad->getAlignment());
9415
9416 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9417 FirstInChain->getBasePtr(),
9418 FirstInChain->getPointerInfo(), false, false,
9419 FirstInChain->getAlignment());
9420
Nadav Rotem2e7d3812012-10-03 19:30:31 +00009421 // Replace one of the loads with the new load.
9422 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9423 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9424 SDValue(NewLoad.getNode(), 1));
9425
9426 // Remove the rest of the load chains.
9427 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotemc653de62012-10-03 16:11:15 +00009428 // Replace all chain users of the old load nodes with the chain of the new
9429 // load node.
9430 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotem2e7d3812012-10-03 19:30:31 +00009431 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9432 }
Nadav Rotemc653de62012-10-03 16:11:15 +00009433
Nadav Rotem2e7d3812012-10-03 19:30:31 +00009434 // Replace the first store with the new store.
9435 CombineTo(EarliestOp, NewStore);
9436 // Erase all other stores.
9437 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotemc653de62012-10-03 16:11:15 +00009438 // Remove all Store nodes.
9439 if (StoreNodes[i].MemNode == EarliestOp)
9440 continue;
9441 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9442 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9443 removeFromWorkList(St);
9444 DAG.DeleteNode(St);
9445 }
9446
9447 return true;
9448}
9449
Dan Gohman475871a2008-07-27 21:46:04 +00009450SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Cheng8b2794a2006-10-13 21:14:26 +00009451 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman475871a2008-07-27 21:46:04 +00009452 SDValue Chain = ST->getChain();
9453 SDValue Value = ST->getValue();
9454 SDValue Ptr = ST->getBasePtr();
Scott Michelfdc40a02009-02-17 22:15:04 +00009455
Evan Cheng59d5b682007-05-07 21:27:48 +00009456 // If this is a store of a bit convert, store the input value if the
Evan Cheng2c4f9432007-05-09 21:49:47 +00009457 // resultant store does not need a higher alignment than the original.
Wesley Peckbf17cfa2010-11-23 03:31:01 +00009458 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattnerddf89562008-01-17 19:59:44 +00009459 ST->isUnindexed()) {
Dan Gohman1ba519b2009-02-20 23:29:13 +00009460 unsigned OrigAlign = ST->getAlignment();
Owen Andersone50ed302009-08-10 22:56:29 +00009461 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmow3574eca2012-10-08 16:38:25 +00009462 unsigned Align = TLI.getDataLayout()->
Owen Anderson23b9b192009-08-12 00:36:31 +00009463 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sandsd4b9c172008-06-13 19:07:40 +00009464 if (Align <= OrigAlign &&
Duncan Sands25cf2272008-11-24 14:53:14 +00009465 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohmanf560ffa2009-01-28 17:46:25 +00009466 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00009467 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner6229d0a2010-09-21 18:41:36 +00009468 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00009469 ST->isNonTemporal(), OrigAlign,
9470 ST->getTBAAInfo());
Jim Laskey279f0532006-09-25 16:29:54 +00009471 }
Owen Andersona34d9362011-04-14 17:30:49 +00009472
Chris Lattnerb3452ea2011-04-09 02:32:02 +00009473 // Turn 'store undef, Ptr' -> nothing.
9474 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9475 return Chain;
Duncan Sandsd4b9c172008-06-13 19:07:40 +00009476
Nate Begeman2cbba892006-12-11 02:23:46 +00009477 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman2cbba892006-12-11 02:23:46 +00009478 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sandsd4b9c172008-06-13 19:07:40 +00009479 // NOTE: If the original store is volatile, this transform must not increase
9480 // the number of stores. For example, on x86-32 an f64 can be stored in one
9481 // processor operation but an i64 (which is not legal) requires two. So the
9482 // transform should not be done in this case.
Evan Cheng25ece662006-12-11 17:25:19 +00009483 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman475871a2008-07-27 21:46:04 +00009484 SDValue Tmp;
Craig Topper0ff11902013-08-15 02:44:19 +00009485 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009486 default: llvm_unreachable("Unknown FP type");
Pete Cooper438c0402012-06-21 18:00:39 +00009487 case MVT::f16: // We don't do this for these yet.
9488 case MVT::f80:
Owen Anderson825b72b2009-08-11 20:47:22 +00009489 case MVT::f128:
9490 case MVT::ppcf128:
Dale Johannesenc7b21d52007-09-18 18:36:59 +00009491 break;
Owen Anderson825b72b2009-08-11 20:47:22 +00009492 case MVT::f32:
Chris Lattner2392ae72010-04-15 04:48:01 +00009493 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson825b72b2009-08-11 20:47:22 +00009494 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen9d5f4562007-09-12 03:30:33 +00009495 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson825b72b2009-08-11 20:47:22 +00009496 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickac6d9be2013-05-25 02:42:55 +00009497 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford66589dc2013-10-28 11:17:59 +00009498 Ptr, ST->getMemOperand());
Chris Lattner62be1a72006-12-12 04:16:14 +00009499 }
9500 break;
Owen Anderson825b72b2009-08-11 20:47:22 +00009501 case MVT::f64:
Chris Lattner2392ae72010-04-15 04:48:01 +00009502 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohmanf560ffa2009-01-28 17:46:25 +00009503 !ST->isVolatile()) ||
Owen Anderson825b72b2009-08-11 20:47:22 +00009504 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen7111b022008-10-09 18:53:47 +00009505 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson825b72b2009-08-11 20:47:22 +00009506 getZExtValue(), MVT::i64);
Andrew Trickac6d9be2013-05-25 02:42:55 +00009507 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford66589dc2013-10-28 11:17:59 +00009508 Ptr, ST->getMemOperand());
Chris Lattnerb3452ea2011-04-09 02:32:02 +00009509 }
Owen Andersona34d9362011-04-14 17:30:49 +00009510
Chris Lattnerb3452ea2011-04-09 02:32:02 +00009511 if (!ST->isVolatile() &&
9512 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sandsdc846502007-10-28 12:59:45 +00009513 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattner62be1a72006-12-12 04:16:14 +00009514 // argument passing. Since this is so common, custom legalize the
9515 // 64-bit integer store into two 32-bit stores.
Dale Johannesen7111b022008-10-09 18:53:47 +00009516 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson825b72b2009-08-11 20:47:22 +00009517 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9518 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands0753fc12008-02-11 10:37:04 +00009519 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattner62be1a72006-12-12 04:16:14 +00009520
Dan Gohmand6fd1bc2007-07-09 22:18:38 +00009521 unsigned Alignment = ST->getAlignment();
9522 bool isVolatile = ST->isVolatile();
David Greene1e559442010-02-15 17:00:31 +00009523 bool isNonTemporal = ST->isNonTemporal();
Richard Sandiford66589dc2013-10-28 11:17:59 +00009524 const MDNode *TBAAInfo = ST->getTBAAInfo();
Dan Gohmand6fd1bc2007-07-09 22:18:38 +00009525
Andrew Trickac6d9be2013-05-25 02:42:55 +00009526 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner6229d0a2010-09-21 18:41:36 +00009527 Ptr, ST->getPointerInfo(),
David Greene1e559442010-02-15 17:00:31 +00009528 isVolatile, isNonTemporal,
Richard Sandiford66589dc2013-10-28 11:17:59 +00009529 ST->getAlignment(), TBAAInfo);
Andrew Trickac6d9be2013-05-25 02:42:55 +00009530 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattner62be1a72006-12-12 04:16:14 +00009531 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sandsdc846502007-10-28 12:59:45 +00009532 Alignment = MinAlign(Alignment, 4U);
Andrew Trickac6d9be2013-05-25 02:42:55 +00009533 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner6229d0a2010-09-21 18:41:36 +00009534 Ptr, ST->getPointerInfo().getWithOffset(4),
9535 isVolatile, isNonTemporal,
Richard Sandiford66589dc2013-10-28 11:17:59 +00009536 Alignment, TBAAInfo);
Andrew Trickac6d9be2013-05-25 02:42:55 +00009537 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendlingc144a572009-01-30 23:36:47 +00009538 St0, St1);
Chris Lattner62be1a72006-12-12 04:16:14 +00009539 }
Bill Wendlingc144a572009-01-30 23:36:47 +00009540
Chris Lattner62be1a72006-12-12 04:16:14 +00009541 break;
Evan Cheng25ece662006-12-11 17:25:19 +00009542 }
Nate Begeman2cbba892006-12-11 02:23:46 +00009543 }
Nate Begeman2cbba892006-12-11 02:23:46 +00009544 }
9545
Evan Cheng255f20f2010-04-01 06:04:33 +00009546 // Try to infer better alignment information than the store already has.
9547 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Chenged1c0c72011-11-28 22:37:34 +00009548 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9549 if (Align > ST->getAlignment())
Andrew Trickac6d9be2013-05-25 02:42:55 +00009550 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Chenged1c0c72011-11-28 22:37:34 +00009551 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00009552 ST->isVolatile(), ST->isNonTemporal(), Align,
9553 ST->getTBAAInfo());
Evan Cheng255f20f2010-04-01 06:04:33 +00009554 }
9555 }
9556
Evan Cheng31959b12011-02-02 01:06:55 +00009557 // Try transforming a pair floating point load / store ops to integer
9558 // load / store ops.
9559 SDValue NewST = TransformFPLoadStorePair(N);
9560 if (NewST.getNode())
9561 return NewST;
9562
Hal Finkel253acef2013-08-29 03:29:55 +00009563 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9564 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Stephen Hines36b56882014-04-23 16:57:46 -07009565#ifndef NDEBUG
9566 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9567 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9568 UseAA = false;
9569#endif
9570 if (UseAA && ST->isUnindexed()) {
Jim Laskey279f0532006-09-25 16:29:54 +00009571 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman475871a2008-07-27 21:46:04 +00009572 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelfdc40a02009-02-17 22:15:04 +00009573
Jim Laskey6ff23e52006-10-04 16:53:27 +00009574 // If there is a better chain.
Jim Laskey279f0532006-09-25 16:29:54 +00009575 if (Chain != BetterChain) {
Dan Gohman475871a2008-07-27 21:46:04 +00009576 SDValue ReplStore;
Nate Begemanb6aef5c2009-09-15 00:18:30 +00009577
9578 // Replace the chain to avoid dependency.
Jim Laskeyd4edf2c2006-10-14 12:14:27 +00009579 if (ST->isTruncatingStore()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00009580 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford66589dc2013-10-28 11:17:59 +00009581 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskeyd4edf2c2006-10-14 12:14:27 +00009582 } else {
Andrew Trickac6d9be2013-05-25 02:42:55 +00009583 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford66589dc2013-10-28 11:17:59 +00009584 ST->getMemOperand());
Jim Laskeyd4edf2c2006-10-14 12:14:27 +00009585 }
Scott Michelfdc40a02009-02-17 22:15:04 +00009586
Jim Laskey279f0532006-09-25 16:29:54 +00009587 // Create token to keep both nodes around.
Andrew Trickac6d9be2013-05-25 02:42:55 +00009588 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson825b72b2009-08-11 20:47:22 +00009589 MVT::Other, Chain, ReplStore);
Bill Wendlingc144a572009-01-30 23:36:47 +00009590
Nate Begemanb6aef5c2009-09-15 00:18:30 +00009591 // Make sure the new and old chains are cleaned up.
9592 AddToWorkList(Token.getNode());
9593
Jim Laskey274062c2006-10-13 23:32:28 +00009594 // Don't add users to work list.
9595 return CombineTo(N, Token, false);
Jim Laskey279f0532006-09-25 16:29:54 +00009596 }
Jim Laskeyd1aed7a2006-09-21 16:28:59 +00009597 }
Scott Michelfdc40a02009-02-17 22:15:04 +00009598
Evan Cheng33dbedc2006-11-05 09:31:14 +00009599 // Try transforming N to an indexed store.
Evan Chengbbd6f6e2006-11-07 09:03:05 +00009600 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman475871a2008-07-27 21:46:04 +00009601 return SDValue(N, 0);
Evan Cheng33dbedc2006-11-05 09:31:14 +00009602
Chris Lattner3c872852007-12-29 06:26:16 +00009603 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattnerddf89562008-01-17 19:59:44 +00009604 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotembaff46f2011-06-15 11:19:12 +00009605 Value.getValueType().isInteger()) {
Chris Lattner2b4c2792007-10-13 06:35:54 +00009606 // See if we can simplify the input to this truncstore with knowledge that
9607 // only the low bits are being used. For example:
9608 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelfdc40a02009-02-17 22:15:04 +00009609 SDValue Shorter =
Dan Gohman2e68b6f2008-02-25 21:11:39 +00009610 GetDemandedBits(Value,
Nadav Rotembaff46f2011-06-15 11:19:12 +00009611 APInt::getLowBitsSet(
9612 Value.getValueType().getScalarType().getSizeInBits(),
9613 ST->getMemoryVT().getScalarType().getSizeInBits()));
Gabor Greifba36cb52008-08-28 21:40:38 +00009614 AddToWorkList(Value.getNode());
9615 if (Shorter.getNode())
Andrew Trickac6d9be2013-05-25 02:42:55 +00009616 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford66589dc2013-10-28 11:17:59 +00009617 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelfdc40a02009-02-17 22:15:04 +00009618
Chris Lattnere33544c2007-10-13 06:58:48 +00009619 // Otherwise, see if we can simplify the operation with
9620 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohman7b8d4a92008-02-27 00:25:32 +00009621 if (SimplifyDemandedBits(Value,
Eric Christopher503a64d2010-12-09 04:48:06 +00009622 APInt::getLowBitsSet(
9623 Value.getValueType().getScalarType().getSizeInBits(),
9624 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman475871a2008-07-27 21:46:04 +00009625 return SDValue(N, 0);
Chris Lattner2b4c2792007-10-13 06:35:54 +00009626 }
Scott Michelfdc40a02009-02-17 22:15:04 +00009627
Chris Lattner3c872852007-12-29 06:26:16 +00009628 // If this is a load followed by a store to the same location, then the store
9629 // is dead/noop.
9630 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohmanb625f2f2008-01-30 00:15:11 +00009631 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattnerddf89562008-01-17 19:59:44 +00009632 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner07649d92008-01-08 23:08:06 +00009633 // There can't be any side effects between the load and store, such as
9634 // a call or store.
Dan Gohman475871a2008-07-27 21:46:04 +00009635 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3c872852007-12-29 06:26:16 +00009636 // The store is dead, remove it.
9637 return Chain;
9638 }
9639 }
Duncan Sandsd4b9c172008-06-13 19:07:40 +00009640
Chris Lattnerddf89562008-01-17 19:59:44 +00009641 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9642 // truncating store. We can do this even if this is already a truncstore.
9643 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greifba36cb52008-08-28 21:40:38 +00009644 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattnerddf89562008-01-17 19:59:44 +00009645 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohmanb625f2f2008-01-30 00:15:11 +00009646 ST->getMemoryVT())) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00009647 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford66589dc2013-10-28 11:17:59 +00009648 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattnerddf89562008-01-17 19:59:44 +00009649 }
Duncan Sandsd4b9c172008-06-13 19:07:40 +00009650
Nadav Rotemc653de62012-10-03 16:11:15 +00009651 // Only perform this optimization before the types are legal, because we
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009652 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotema569a802012-12-02 17:14:09 +00009653 if (!LegalTypes) {
9654 bool EverChanged = false;
9655
9656 do {
9657 // There can be multiple store sequences on the same chain.
9658 // Keep trying to merge store sequences until we are unable to do so
9659 // or until we merge the last store on the chain.
9660 bool Changed = MergeConsecutiveStores(ST);
9661 EverChanged |= Changed;
9662 if (!Changed) break;
9663 } while (ST->getOpcode() != ISD::DELETED_NODE);
9664
9665 if (EverChanged)
9666 return SDValue(N, 0);
9667 }
Nadav Rotemc653de62012-10-03 16:11:15 +00009668
Evan Cheng8b944d32009-05-28 00:35:15 +00009669 return ReduceLoadOpStoreWidth(N);
Chris Lattner87514ca2005-10-10 22:31:19 +00009670}
9671
Dan Gohman475871a2008-07-27 21:46:04 +00009672SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9673 SDValue InVec = N->getOperand(0);
9674 SDValue InVal = N->getOperand(1);
9675 SDValue EltNo = N->getOperand(2);
Andrew Trickac6d9be2013-05-25 02:42:55 +00009676 SDLoc dl(N);
Scott Michelfdc40a02009-02-17 22:15:04 +00009677
Bob Wilson492fd452010-05-19 23:42:58 +00009678 // If the inserted element is an UNDEF, just use the input vector.
9679 if (InVal.getOpcode() == ISD::UNDEF)
9680 return InVec;
9681
Nadav Rotem609d54e2011-02-12 14:40:33 +00009682 EVT VT = InVec.getValueType();
9683
Owen Anderson95771af2011-02-25 21:41:48 +00009684 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotem609d54e2011-02-12 14:40:33 +00009685 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9686 return SDValue();
9687
Eli Friedman9db817f2011-09-09 21:04:06 +00009688 // Check that we know which element is being inserted
9689 if (!isa<ConstantSDNode>(EltNo))
9690 return SDValue();
9691 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelfdc40a02009-02-17 22:15:04 +00009692
Eli Friedman9db817f2011-09-09 21:04:06 +00009693 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9694 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9695 // vector elements.
9696 SmallVector<SDValue, 8> Ops;
Quentin Colombet75c94332013-07-30 00:24:09 +00009697 // Do not combine these two vectors if the output vector will not replace
9698 // the input vector.
9699 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedman9db817f2011-09-09 21:04:06 +00009700 Ops.append(InVec.getNode()->op_begin(),
9701 InVec.getNode()->op_end());
9702 } else if (InVec.getOpcode() == ISD::UNDEF) {
9703 unsigned NElts = VT.getVectorNumElements();
9704 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9705 } else {
9706 return SDValue();
Nate Begeman9008ca62009-04-27 18:41:29 +00009707 }
Eli Friedman9db817f2011-09-09 21:04:06 +00009708
9709 // Insert the element
9710 if (Elt < Ops.size()) {
9711 // All the operands of BUILD_VECTOR must have the same type;
9712 // we enforce that here.
9713 EVT OpVT = Ops[0].getValueType();
9714 if (InVal.getValueType() != OpVT)
9715 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9716 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9717 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9718 Ops[Elt] = InVal;
9719 }
9720
9721 // Return the new vector
9722 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9723 VT, &Ops[0], Ops.size());
Chris Lattnerca242442006-03-19 01:27:56 +00009724}
9725
Dan Gohman475871a2008-07-27 21:46:04 +00009726SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wang7ac9cdf2009-01-17 00:07:25 +00009727 // (vextract (scalar_to_vector val, 0) -> val
9728 SDValue InVec = N->getOperand(0);
Nadav Rotemba05c912012-01-17 21:44:01 +00009729 EVT VT = InVec.getValueType();
9730 EVT NVT = N->getValueType(0);
Mon P Wang7ac9cdf2009-01-17 00:07:25 +00009731
Duncan Sandsc356f332011-05-09 08:03:33 +00009732 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9733 // Check if the result type doesn't match the inserted element type. A
9734 // SCALAR_TO_VECTOR may truncate the inserted element and the
9735 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9736 SDValue InOp = InVec.getOperand(0);
Duncan Sandsc356f332011-05-09 08:03:33 +00009737 if (InOp.getValueType() != NVT) {
9738 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickac6d9be2013-05-25 02:42:55 +00009739 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sandsc356f332011-05-09 08:03:33 +00009740 }
9741 return InOp;
9742 }
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009743
Nadav Rotemba05c912012-01-17 21:44:01 +00009744 SDValue EltNo = N->getOperand(1);
9745 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9746
9747 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9748 // We only perform this optimization before the op legalization phase because
Nadav Rotem6dfabb62012-09-20 08:53:31 +00009749 // we may introduce new vector instructions which are not backed by TD
9750 // patterns. For example on AVX, extracting elements from a wide vector
Stephen Hines36b56882014-04-23 16:57:46 -07009751 // without using extract_subvector. However, if we can find an underlying
9752 // scalar value, then we can always use that.
Nadav Rotemba05c912012-01-17 21:44:01 +00009753 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Stephen Hines36b56882014-04-23 16:57:46 -07009754 && ConstEltNo) {
Nadav Rotemba05c912012-01-17 21:44:01 +00009755 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9756 int NumElem = VT.getVectorNumElements();
9757 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9758 // Find the new index to extract from.
9759 int OrigElt = SVOp->getMaskElt(Elt);
9760
9761 // Extracting an undef index is undef.
9762 if (OrigElt == -1)
9763 return DAG.getUNDEF(NVT);
9764
9765 // Select the right vector half to extract from.
Stephen Hines36b56882014-04-23 16:57:46 -07009766 SDValue SVInVec;
Nadav Rotemba05c912012-01-17 21:44:01 +00009767 if (OrigElt < NumElem) {
Stephen Hines36b56882014-04-23 16:57:46 -07009768 SVInVec = InVec->getOperand(0);
Nadav Rotemba05c912012-01-17 21:44:01 +00009769 } else {
Stephen Hines36b56882014-04-23 16:57:46 -07009770 SVInVec = InVec->getOperand(1);
Nadav Rotemba05c912012-01-17 21:44:01 +00009771 OrigElt -= NumElem;
9772 }
9773
Stephen Hines36b56882014-04-23 16:57:46 -07009774 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9775 SDValue InOp = SVInVec.getOperand(OrigElt);
9776 if (InOp.getValueType() != NVT) {
9777 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9778 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9779 }
9780
9781 return InOp;
9782 }
9783
9784 // FIXME: We should handle recursing on other vector shuffles and
9785 // scalar_to_vector here as well.
9786
9787 if (!LegalOperations) {
9788 EVT IndexTy = TLI.getVectorIdxTy();
9789 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9790 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9791 }
Nadav Rotemba05c912012-01-17 21:44:01 +00009792 }
9793
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009794 // Perform only after legalization to ensure build_vector / vector_shuffle
9795 // optimizations have already been done.
Duncan Sands25cf2272008-11-24 14:53:14 +00009796 if (!LegalOperations) return SDValue();
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009797
Mon P Wang7ac9cdf2009-01-17 00:07:25 +00009798 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9799 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9800 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng513da432007-10-06 08:19:55 +00009801
Nadav Rotemba05c912012-01-17 21:44:01 +00009802 if (ConstEltNo) {
Eric Christophercaebdd42010-11-03 09:36:40 +00009803 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng513da432007-10-06 08:19:55 +00009804 bool NewLoad = false;
Mon P Wanga60b5232008-12-11 00:26:16 +00009805 bool BCNumEltsChanged = false;
Owen Andersone50ed302009-08-10 22:56:29 +00009806 EVT ExtVT = VT.getVectorElementType();
9807 EVT LVT = ExtVT;
Bill Wendlingc144a572009-01-30 23:36:47 +00009808
Evan Cheng84387ea2012-03-13 22:00:52 +00009809 // If the result of load has to be truncated, then it's not necessarily
9810 // profitable.
Evan Chenga03d3662012-03-13 22:16:11 +00009811 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
Evan Cheng84387ea2012-03-13 22:00:52 +00009812 return SDValue();
9813
Wesley Peckbf17cfa2010-11-23 03:31:01 +00009814 if (InVec.getOpcode() == ISD::BITCAST) {
Eli Friedmand6e25602011-12-26 22:49:32 +00009815 // Don't duplicate a load with other uses.
9816 if (!InVec.hasOneUse())
9817 return SDValue();
9818
Owen Andersone50ed302009-08-10 22:56:29 +00009819 EVT BCVT = InVec.getOperand(0).getValueType();
9820 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
Dan Gohman475871a2008-07-27 21:46:04 +00009821 return SDValue();
Mon P Wanga60b5232008-12-11 00:26:16 +00009822 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9823 BCNumEltsChanged = true;
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009824 InVec = InVec.getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00009825 ExtVT = BCVT.getVectorElementType();
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009826 NewLoad = true;
9827 }
Evan Cheng513da432007-10-06 08:19:55 +00009828
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009829 LoadSDNode *LN0 = NULL;
Nate Begeman5a5ca152009-04-29 05:20:52 +00009830 const ShuffleVectorSDNode *SVN = NULL;
Bill Wendlingc144a572009-01-30 23:36:47 +00009831 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009832 LN0 = cast<LoadSDNode>(InVec);
Bill Wendlingc144a572009-01-30 23:36:47 +00009833 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Andersone50ed302009-08-10 22:56:29 +00009834 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendlingc144a572009-01-30 23:36:47 +00009835 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmand6e25602011-12-26 22:49:32 +00009836 // Don't duplicate a load with other uses.
9837 if (!InVec.hasOneUse())
9838 return SDValue();
9839
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009840 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5a5ca152009-04-29 05:20:52 +00009841 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009842 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9843 // =>
9844 // (load $addr+1*size)
Scott Michelfdc40a02009-02-17 22:15:04 +00009845
Eli Friedmand6e25602011-12-26 22:49:32 +00009846 // Don't duplicate a load with other uses.
9847 if (!InVec.hasOneUse())
9848 return SDValue();
9849
Mon P Wanga60b5232008-12-11 00:26:16 +00009850 // If the bit convert changed the number of elements, it is unsafe
9851 // to examine the mask.
9852 if (BCNumEltsChanged)
9853 return SDValue();
Nate Begeman5a5ca152009-04-29 05:20:52 +00009854
9855 // Select the input vector, guarding against out of range extract vector.
9856 unsigned NumElems = VT.getVectorNumElements();
Eric Christophercaebdd42010-11-03 09:36:40 +00009857 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5a5ca152009-04-29 05:20:52 +00009858 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9859
Eli Friedmand6e25602011-12-26 22:49:32 +00009860 if (InVec.getOpcode() == ISD::BITCAST) {
9861 // Don't duplicate a load with other uses.
9862 if (!InVec.hasOneUse())
9863 return SDValue();
9864
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009865 InVec = InVec.getOperand(0);
Eli Friedmand6e25602011-12-26 22:49:32 +00009866 }
Gabor Greifba36cb52008-08-28 21:40:38 +00009867 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009868 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd0e88f32010-04-08 18:49:30 +00009869 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Evan Cheng513da432007-10-06 08:19:55 +00009870 }
9871 }
Bill Wendlingc144a572009-01-30 23:36:47 +00009872
Eli Friedmand6e25602011-12-26 22:49:32 +00009873 // Make sure we found a non-volatile load and the extractelement is
9874 // the only use.
Nadav Rotem42febc62011-05-11 14:40:50 +00009875 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman475871a2008-07-27 21:46:04 +00009876 return SDValue();
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009877
Eric Christopherd81f17a2010-11-03 20:44:42 +00009878 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9879 if (Elt == -1)
Eli Friedmaned4b4272011-07-25 22:25:42 +00009880 return DAG.getUNDEF(LVT);
Eric Christopherd81f17a2010-11-03 20:44:42 +00009881
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009882 unsigned Align = LN0->getAlignment();
9883 if (NewLoad) {
9884 // Check the resultant load doesn't need a higher alignment than the
9885 // original load.
Bill Wendlingc144a572009-01-30 23:36:47 +00009886 unsigned NewAlign =
Micah Villmow3574eca2012-10-08 16:38:25 +00009887 TLI.getDataLayout()
Eric Christopher503a64d2010-12-09 04:48:06 +00009888 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
Bill Wendlingc144a572009-01-30 23:36:47 +00009889
Dan Gohmanf560ffa2009-01-28 17:46:25 +00009890 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
Dan Gohman475871a2008-07-27 21:46:04 +00009891 return SDValue();
Bill Wendlingc144a572009-01-30 23:36:47 +00009892
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009893 Align = NewAlign;
9894 }
9895
Dan Gohman475871a2008-07-27 21:46:04 +00009896 SDValue NewPtr = LN0->getBasePtr();
Chris Lattnerfa459012010-09-21 16:08:50 +00009897 unsigned PtrOff = 0;
Wesley Peckbf17cfa2010-11-23 03:31:01 +00009898
Eric Christopherd81f17a2010-11-03 20:44:42 +00009899 if (Elt) {
Chris Lattnerfa459012010-09-21 16:08:50 +00009900 PtrOff = LVT.getSizeInBits() * Elt / 8;
Owen Andersone50ed302009-08-10 22:56:29 +00009901 EVT PtrType = NewPtr.getValueType();
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009902 if (TLI.isBigEndian())
Duncan Sands83ec4b62008-06-06 12:08:01 +00009903 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
Andrew Trickac6d9be2013-05-25 02:42:55 +00009904 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009905 DAG.getConstant(PtrOff, PtrType));
9906 }
Bill Wendlingc144a572009-01-30 23:36:47 +00009907
Eli Friedman4db4add2011-11-16 23:50:22 +00009908 // The replacement we need to do here is a little tricky: we need to
9909 // replace an extractelement of a load with a load.
9910 // Use ReplaceAllUsesOfValuesWith to do the replacement.
Eli Friedmand6e25602011-12-26 22:49:32 +00009911 // Note that this replacement assumes that the extractvalue is the only
9912 // use of the load; that's okay because we don't want to perform this
9913 // transformation in other cases anyway.
Evan Cheng84387ea2012-03-13 22:00:52 +00009914 SDValue Load;
Evan Chenga03d3662012-03-13 22:16:11 +00009915 SDValue Chain;
Evan Cheng84387ea2012-03-13 22:00:52 +00009916 if (NVT.bitsGT(LVT)) {
9917 // If the result type of vextract is wider than the load, then issue an
9918 // extending load instead.
9919 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9920 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
Andrew Trickac6d9be2013-05-25 02:42:55 +00009921 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
Evan Cheng84387ea2012-03-13 22:00:52 +00009922 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
Richard Sandiford66589dc2013-10-28 11:17:59 +00009923 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9924 Align, LN0->getTBAAInfo());
Evan Chenga03d3662012-03-13 22:16:11 +00009925 Chain = Load.getValue(1);
9926 } else {
Andrew Trickac6d9be2013-05-25 02:42:55 +00009927 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
Evan Cheng84387ea2012-03-13 22:00:52 +00009928 LN0->getPointerInfo().getWithOffset(PtrOff),
Stephen Lin155615d2013-07-08 00:37:03 +00009929 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00009930 LN0->isInvariant(), Align, LN0->getTBAAInfo());
Evan Chenga03d3662012-03-13 22:16:11 +00009931 Chain = Load.getValue(1);
9932 if (NVT.bitsLT(LVT))
Andrew Trickac6d9be2013-05-25 02:42:55 +00009933 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
Evan Chenga03d3662012-03-13 22:16:11 +00009934 else
Andrew Trickac6d9be2013-05-25 02:42:55 +00009935 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
Evan Chenga03d3662012-03-13 22:16:11 +00009936 }
Eli Friedman4db4add2011-11-16 23:50:22 +00009937 WorkListRemover DeadNodes(*this);
9938 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
Evan Chenga03d3662012-03-13 22:16:11 +00009939 SDValue To[] = { Load, Chain };
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00009940 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
Eli Friedman4db4add2011-11-16 23:50:22 +00009941 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9942 // worklist explicitly as well.
9943 AddToWorkList(Load.getNode());
Craig Topper0c9da212012-03-20 05:28:39 +00009944 AddUsersToWorkList(Load.getNode()); // Add users too
Eli Friedman4db4add2011-11-16 23:50:22 +00009945 // Make sure to revisit this node to clean it up; it will usually be dead.
9946 AddToWorkList(N);
9947 return SDValue(N, 0);
Evan Cheng513da432007-10-06 08:19:55 +00009948 }
Bill Wendlingc144a572009-01-30 23:36:47 +00009949
Dan Gohman475871a2008-07-27 21:46:04 +00009950 return SDValue();
Evan Cheng513da432007-10-06 08:19:55 +00009951}
Evan Cheng513da432007-10-06 08:19:55 +00009952
Michael Liaofac14ab2012-10-23 23:06:52 +00009953// Simplify (build_vec (ext )) to (bitcast (build_vec ))
9954SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9955 // We perform this optimization post type-legalization because
9956 // the type-legalizer often scalarizes integer-promoted vectors.
9957 // Performing this optimization before may create bit-casts which
9958 // will be type-legalized to complex code sequences.
9959 // We perform this optimization only before the operation legalizer because we
9960 // may introduce illegal operations.
9961 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9962 return SDValue();
9963
Dan Gohman7f321562007-06-25 16:23:39 +00009964 unsigned NumInScalars = N->getNumOperands();
Andrew Trickac6d9be2013-05-25 02:42:55 +00009965 SDLoc dl(N);
Owen Andersone50ed302009-08-10 22:56:29 +00009966 EVT VT = N->getValueType(0);
Nadav Rotemb87bdac2012-07-15 08:38:23 +00009967
Nadav Rotemb00418a2011-10-29 21:23:04 +00009968 // Check to see if this is a BUILD_VECTOR of a bunch of values
9969 // which come from any_extend or zero_extend nodes. If so, we can create
9970 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf47368b2011-10-31 20:08:25 +00009971 // optimizations. We do not handle sign-extend because we can't fill the sign
9972 // using shuffles.
Nadav Rotemb00418a2011-10-29 21:23:04 +00009973 EVT SourceType = MVT::Other;
Craig Topperd3b58892012-01-17 09:09:48 +00009974 bool AllAnyExt = true;
Nadav Rotemb87bdac2012-07-15 08:38:23 +00009975
Craig Topperd3b58892012-01-17 09:09:48 +00009976 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotemb00418a2011-10-29 21:23:04 +00009977 SDValue In = N->getOperand(i);
9978 // Ignore undef inputs.
9979 if (In.getOpcode() == ISD::UNDEF) continue;
9980
9981 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9982 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9983
Nadav Rotemf47368b2011-10-31 20:08:25 +00009984 // Abort if the element is not an extension.
Nadav Rotemb00418a2011-10-29 21:23:04 +00009985 if (!ZeroExt && !AnyExt) {
Nadav Rotemf47368b2011-10-31 20:08:25 +00009986 SourceType = MVT::Other;
Nadav Rotemb00418a2011-10-29 21:23:04 +00009987 break;
9988 }
9989
9990 // The input is a ZeroExt or AnyExt. Check the original type.
9991 EVT InTy = In.getOperand(0).getValueType();
9992
9993 // Check that all of the widened source types are the same.
9994 if (SourceType == MVT::Other)
Nadav Rotemf47368b2011-10-31 20:08:25 +00009995 // First time.
Nadav Rotemb00418a2011-10-29 21:23:04 +00009996 SourceType = InTy;
9997 else if (InTy != SourceType) {
9998 // Multiple income types. Abort.
Nadav Rotemf47368b2011-10-31 20:08:25 +00009999 SourceType = MVT::Other;
Nadav Rotemb00418a2011-10-29 21:23:04 +000010000 break;
10001 }
10002
10003 // Check if all of the extends are ANY_EXTENDs.
Craig Topperd3b58892012-01-17 09:09:48 +000010004 AllAnyExt &= AnyExt;
Nadav Rotemb00418a2011-10-29 21:23:04 +000010005 }
10006
Nadav Rotemf47368b2011-10-31 20:08:25 +000010007 // In order to have valid types, all of the inputs must be extended from the
10008 // same source type and all of the inputs must be any or zero extend.
10009 // Scalar sizes must be a power of two.
Michael Liaofac14ab2012-10-23 23:06:52 +000010010 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem2ee746b2012-02-12 15:05:31 +000010011 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf47368b2011-10-31 20:08:25 +000010012 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10013 isPowerOf2_32(SourceType.getSizeInBits());
10014
Nadav Rotem6431ff92012-03-15 08:49:06 +000010015 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10016 // turn into a single shuffle instruction.
Michael Liaofac14ab2012-10-23 23:06:52 +000010017 if (!ValidTypes)
10018 return SDValue();
Nadav Rotemb00418a2011-10-29 21:23:04 +000010019
Michael Liaofac14ab2012-10-23 23:06:52 +000010020 bool isLE = TLI.isLittleEndian();
10021 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10022 assert(ElemRatio > 1 && "Invalid element size ratio");
10023 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10024 DAG.getConstant(0, SourceType);
Nadav Rotemb00418a2011-10-29 21:23:04 +000010025
Michael Liaofac14ab2012-10-23 23:06:52 +000010026 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10027 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotemb00418a2011-10-29 21:23:04 +000010028
Michael Liaofac14ab2012-10-23 23:06:52 +000010029 // Populate the new build_vector
Jakub Staszakadf38912012-10-24 00:38:25 +000010030 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liaofac14ab2012-10-23 23:06:52 +000010031 SDValue Cast = N->getOperand(i);
10032 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10033 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10034 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10035 SDValue In;
10036 if (Cast.getOpcode() == ISD::UNDEF)
10037 In = DAG.getUNDEF(SourceType);
10038 else
10039 In = Cast->getOperand(0);
10040 unsigned Index = isLE ? (i * ElemRatio) :
10041 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotemb00418a2011-10-29 21:23:04 +000010042
Michael Liaofac14ab2012-10-23 23:06:52 +000010043 assert(Index < Ops.size() && "Invalid index");
10044 Ops[Index] = In;
Nadav Rotemb00418a2011-10-29 21:23:04 +000010045 }
Chris Lattnerca242442006-03-19 01:27:56 +000010046
Michael Liaofac14ab2012-10-23 23:06:52 +000010047 // The type of the new BUILD_VECTOR node.
10048 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10049 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10050 "Invalid vector size");
10051 // Check if the new vector type is legal.
10052 if (!isTypeLegal(VecVT)) return SDValue();
10053
10054 // Make the new BUILD_VECTOR.
10055 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
10056
10057 // The new BUILD_VECTOR node has the potential to be further optimized.
10058 AddToWorkList(BV.getNode());
10059 // Bitcast to the desired type.
10060 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10061}
10062
Michael Liao1a5cc712012-10-24 04:14:18 +000010063SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10064 EVT VT = N->getValueType(0);
10065
10066 unsigned NumInScalars = N->getNumOperands();
Andrew Trickac6d9be2013-05-25 02:42:55 +000010067 SDLoc dl(N);
Michael Liao1a5cc712012-10-24 04:14:18 +000010068
10069 EVT SrcVT = MVT::Other;
10070 unsigned Opcode = ISD::DELETED_NODE;
10071 unsigned NumDefs = 0;
10072
10073 for (unsigned i = 0; i != NumInScalars; ++i) {
10074 SDValue In = N->getOperand(i);
10075 unsigned Opc = In.getOpcode();
10076
10077 if (Opc == ISD::UNDEF)
10078 continue;
10079
10080 // If all scalar values are floats and converted from integers.
10081 if (Opcode == ISD::DELETED_NODE &&
10082 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10083 Opcode = Opc;
Michael Liao1a5cc712012-10-24 04:14:18 +000010084 }
Tom Stellardd40758b2013-01-02 22:13:01 +000010085
Michael Liao1a5cc712012-10-24 04:14:18 +000010086 if (Opc != Opcode)
10087 return SDValue();
10088
10089 EVT InVT = In.getOperand(0).getValueType();
10090
10091 // If all scalar values are typed differently, bail out. It's chosen to
10092 // simplify BUILD_VECTOR of integer types.
10093 if (SrcVT == MVT::Other)
10094 SrcVT = InVT;
10095 if (SrcVT != InVT)
10096 return SDValue();
10097 NumDefs++;
10098 }
10099
10100 // If the vector has just one element defined, it's not worth to fold it into
10101 // a vectorized one.
10102 if (NumDefs < 2)
10103 return SDValue();
10104
10105 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10106 && "Should only handle conversion from integer to float.");
10107 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10108
10109 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellardd40758b2013-01-02 22:13:01 +000010110
10111 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10112 return SDValue();
10113
Michael Liao1a5cc712012-10-24 04:14:18 +000010114 SmallVector<SDValue, 8> Opnds;
10115 for (unsigned i = 0; i != NumInScalars; ++i) {
10116 SDValue In = N->getOperand(i);
10117
10118 if (In.getOpcode() == ISD::UNDEF)
10119 Opnds.push_back(DAG.getUNDEF(SrcVT));
10120 else
10121 Opnds.push_back(In.getOperand(0));
10122 }
10123 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
10124 &Opnds[0], Opnds.size());
10125 AddToWorkList(BV.getNode());
10126
10127 return DAG.getNode(Opcode, dl, VT, BV);
10128}
10129
Michael Liaofac14ab2012-10-23 23:06:52 +000010130SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10131 unsigned NumInScalars = N->getNumOperands();
Andrew Trickac6d9be2013-05-25 02:42:55 +000010132 SDLoc dl(N);
Michael Liaofac14ab2012-10-23 23:06:52 +000010133 EVT VT = N->getValueType(0);
10134
10135 // A vector built entirely of undefs is undef.
10136 if (ISD::allOperandsUndef(N))
10137 return DAG.getUNDEF(VT);
10138
10139 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10140 if (V.getNode())
10141 return V;
10142
Michael Liao1a5cc712012-10-24 04:14:18 +000010143 V = reduceBuildVecConvertToConvertBuildVec(N);
10144 if (V.getNode())
10145 return V;
10146
Dan Gohman7f321562007-06-25 16:23:39 +000010147 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10148 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10149 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands00294ca2012-03-19 15:35:44 +000010150
10151 // May only combine to shuffle after legalize if shuffle is legal.
10152 if (LegalOperations &&
10153 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10154 return SDValue();
10155
Dan Gohman475871a2008-07-27 21:46:04 +000010156 SDValue VecIn1, VecIn2;
Chris Lattnerd7648c82006-03-28 20:28:38 +000010157 for (unsigned i = 0; i != NumInScalars; ++i) {
10158 // Ignore undef inputs.
10159 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
Scott Michelfdc40a02009-02-17 22:15:04 +000010160
Dan Gohman7f321562007-06-25 16:23:39 +000010161 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerd7648c82006-03-28 20:28:38 +000010162 // constant index, bail out.
Dan Gohman7f321562007-06-25 16:23:39 +000010163 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Chris Lattnerd7648c82006-03-28 20:28:38 +000010164 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
Dan Gohman475871a2008-07-27 21:46:04 +000010165 VecIn1 = VecIn2 = SDValue(0, 0);
Chris Lattnerd7648c82006-03-28 20:28:38 +000010166 break;
10167 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010168
Nadav Rotem2ee746b2012-02-12 15:05:31 +000010169 // We allow up to two distinct input vectors.
Dan Gohman475871a2008-07-27 21:46:04 +000010170 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
Chris Lattnerd7648c82006-03-28 20:28:38 +000010171 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10172 continue;
Scott Michelfdc40a02009-02-17 22:15:04 +000010173
Gabor Greifba36cb52008-08-28 21:40:38 +000010174 if (VecIn1.getNode() == 0) {
Chris Lattnerd7648c82006-03-28 20:28:38 +000010175 VecIn1 = ExtractedFromVec;
Gabor Greifba36cb52008-08-28 21:40:38 +000010176 } else if (VecIn2.getNode() == 0) {
Chris Lattnerd7648c82006-03-28 20:28:38 +000010177 VecIn2 = ExtractedFromVec;
10178 } else {
10179 // Too many inputs.
Dan Gohman475871a2008-07-27 21:46:04 +000010180 VecIn1 = VecIn2 = SDValue(0, 0);
Chris Lattnerd7648c82006-03-28 20:28:38 +000010181 break;
10182 }
10183 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010184
Nadav Rotem2ee746b2012-02-12 15:05:31 +000010185 // If everything is good, we can make a shuffle operation.
Gabor Greifba36cb52008-08-28 21:40:38 +000010186 if (VecIn1.getNode()) {
Nate Begeman9008ca62009-04-27 18:41:29 +000010187 SmallVector<int, 8> Mask;
Chris Lattnerd7648c82006-03-28 20:28:38 +000010188 for (unsigned i = 0; i != NumInScalars; ++i) {
10189 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
Nate Begeman9008ca62009-04-27 18:41:29 +000010190 Mask.push_back(-1);
Chris Lattnerd7648c82006-03-28 20:28:38 +000010191 continue;
10192 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010193
Rafael Espindola15684b22009-04-24 12:40:33 +000010194 // If extracting from the first vector, just use the index directly.
Nate Begeman9008ca62009-04-27 18:41:29 +000010195 SDValue Extract = N->getOperand(i);
Mon P Wang93b74152009-03-17 06:33:10 +000010196 SDValue ExtVal = Extract.getOperand(1);
Chris Lattnerd7648c82006-03-28 20:28:38 +000010197 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5a5ca152009-04-29 05:20:52 +000010198 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10199 if (ExtIndex > VT.getVectorNumElements())
10200 return SDValue();
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010201
Nate Begeman5a5ca152009-04-29 05:20:52 +000010202 Mask.push_back(ExtIndex);
Chris Lattnerd7648c82006-03-28 20:28:38 +000010203 continue;
10204 }
10205
10206 // Otherwise, use InIdx + VecSize
Mon P Wang93b74152009-03-17 06:33:10 +000010207 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Nate Begeman9008ca62009-04-27 18:41:29 +000010208 Mask.push_back(Idx+NumInScalars);
Chris Lattnerd7648c82006-03-28 20:28:38 +000010209 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010210
Nadav Rotem2ee746b2012-02-12 15:05:31 +000010211 // We can't generate a shuffle node with mismatched input and output types.
10212 // Attempt to transform a single input vector to the correct type.
10213 if ((VT != VecIn1.getValueType())) {
10214 // We don't support shuffeling between TWO values of different types.
10215 if (VecIn2.getNode() != 0)
10216 return SDValue();
10217
10218 // We only support widening of vectors which are half the size of the
10219 // output registers. For example XMM->YMM widening on X86 with AVX.
10220 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10221 return SDValue();
10222
James Molloy8cd08bf2012-09-10 14:01:21 +000010223 // If the input vector type has a different base type to the output
10224 // vector type, bail out.
10225 if (VecIn1.getValueType().getVectorElementType() !=
10226 VT.getVectorElementType())
10227 return SDValue();
10228
Stepan Dyatkovskiyfdeb9fe2012-08-22 09:33:55 +000010229 // Widen the input vector by adding undef values.
Michael Liaofac14ab2012-10-23 23:06:52 +000010230 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
Stepan Dyatkovskiyfdeb9fe2012-08-22 09:33:55 +000010231 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
Nadav Rotem2ee746b2012-02-12 15:05:31 +000010232 }
10233
10234 // If VecIn2 is unused then change it to undef.
10235 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10236
Nadav Rotem6dfabb62012-09-20 08:53:31 +000010237 // Check that we were able to transform all incoming values to the same
10238 // type.
Nadav Rotem0877fdf2012-02-13 12:42:26 +000010239 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10240 VecIn1.getValueType() != VT)
10241 return SDValue();
10242
Nadav Rotem2ee746b2012-02-12 15:05:31 +000010243 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
Nadav Rotem0877fdf2012-02-13 12:42:26 +000010244 if (!isTypeLegal(VT))
Duncan Sands25cf2272008-11-24 14:53:14 +000010245 return SDValue();
10246
Dan Gohman7f321562007-06-25 16:23:39 +000010247 // Return the new VECTOR_SHUFFLE node.
Nate Begeman9008ca62009-04-27 18:41:29 +000010248 SDValue Ops[2];
Chris Lattnerbd564bf2006-08-08 02:23:42 +000010249 Ops[0] = VecIn1;
Nadav Rotem2ee746b2012-02-12 15:05:31 +000010250 Ops[1] = VecIn2;
Michael Liaofac14ab2012-10-23 23:06:52 +000010251 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerd7648c82006-03-28 20:28:38 +000010252 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010253
Dan Gohman475871a2008-07-27 21:46:04 +000010254 return SDValue();
Chris Lattnerd7648c82006-03-28 20:28:38 +000010255}
10256
Dan Gohman475871a2008-07-27 21:46:04 +000010257SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohman7f321562007-06-25 16:23:39 +000010258 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10259 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10260 // inputs come from at most two distinct vectors, turn this into a shuffle
10261 // node.
10262
10263 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendlingc144a572009-01-30 23:36:47 +000010264 if (N->getNumOperands() == 1)
Dan Gohman7f321562007-06-25 16:23:39 +000010265 return N->getOperand(0);
Dan Gohman7f321562007-06-25 16:23:39 +000010266
Nadav Rotemb7e230d2012-07-14 21:30:27 +000010267 // Check if all of the operands are undefs.
Nadav Rotem97541d42013-10-25 06:41:18 +000010268 EVT VT = N->getValueType(0);
Nadav Rotemb87bdac2012-07-15 08:38:23 +000010269 if (ISD::allOperandsUndef(N))
Nadav Rotem97541d42013-10-25 06:41:18 +000010270 return DAG.getUNDEF(VT);
10271
10272 // Optimize concat_vectors where one of the vectors is undef.
10273 if (N->getNumOperands() == 2 &&
10274 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10275 SDValue In = N->getOperand(0);
Bill Wendlingb1eb9dd2013-12-10 06:42:24 +000010276 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotem97541d42013-10-25 06:41:18 +000010277
10278 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10279 if (In->getOpcode() == ISD::BITCAST &&
10280 !In->getOperand(0)->getValueType(0).isVector()) {
10281 SDValue Scalar = In->getOperand(0);
10282 EVT SclTy = Scalar->getValueType(0);
10283
10284 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10285 return SDValue();
10286
10287 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10288 VT.getSizeInBits() / SclTy.getSizeInBits());
10289 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10290 return SDValue();
10291
10292 SDLoc dl = SDLoc(N);
10293 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10294 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10295 }
10296 }
Nadav Rotemb7e230d2012-07-14 21:30:27 +000010297
Stephen Hines36b56882014-04-23 16:57:46 -070010298 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10299 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10300 if (N->getNumOperands() == 2 &&
10301 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10302 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10303 EVT VT = N->getValueType(0);
10304 SDValue N0 = N->getOperand(0);
10305 SDValue N1 = N->getOperand(1);
10306 SmallVector<SDValue, 8> Opnds;
10307 unsigned BuildVecNumElts = N0.getNumOperands();
10308
10309 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10310 Opnds.push_back(N0.getOperand(i));
10311 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10312 Opnds.push_back(N1.getOperand(i));
10313
10314 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
10315 Opnds.size());
10316 }
10317
Nadav Rotemb2ed5fa2013-05-01 19:18:51 +000010318 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10319 // nodes often generate nop CONCAT_VECTOR nodes.
10320 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10321 // place the incoming vectors at the exact same location.
10322 SDValue SingleSource = SDValue();
10323 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10324
10325 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10326 SDValue Op = N->getOperand(i);
10327
10328 if (Op.getOpcode() == ISD::UNDEF)
10329 continue;
10330
10331 // Check if this is the identity extract:
10332 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10333 return SDValue();
10334
10335 // Find the single incoming vector for the extract_subvector.
10336 if (SingleSource.getNode()) {
10337 if (Op.getOperand(0) != SingleSource)
10338 return SDValue();
10339 } else {
10340 SingleSource = Op.getOperand(0);
Michael Kuperstein27202482013-05-06 08:06:13 +000010341
10342 // Check the source type is the same as the type of the result.
10343 // If not, this concat may extend the vector, so we can not
10344 // optimize it away.
10345 if (SingleSource.getValueType() != N->getValueType(0))
10346 return SDValue();
Nadav Rotemb2ed5fa2013-05-01 19:18:51 +000010347 }
10348
10349 unsigned IdentityIndex = i * PartNumElem;
10350 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10351 // The extract index must be constant.
10352 if (!CS)
10353 return SDValue();
Stephen Lin155615d2013-07-08 00:37:03 +000010354
Nadav Rotemb2ed5fa2013-05-01 19:18:51 +000010355 // Check that we are reading from the identity index.
10356 if (CS->getZExtValue() != IdentityIndex)
10357 return SDValue();
10358 }
10359
10360 if (SingleSource.getNode())
10361 return SingleSource;
Stephen Lin155615d2013-07-08 00:37:03 +000010362
Dan Gohman475871a2008-07-27 21:46:04 +000010363 return SDValue();
Dan Gohman7f321562007-06-25 16:23:39 +000010364}
10365
Bruno Cardoso Lopese97190f2011-09-20 23:19:33 +000010366SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10367 EVT NVT = N->getValueType(0);
10368 SDValue V = N->getOperand(0);
10369
Michael Liao13429e22012-10-17 20:48:33 +000010370 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10371 // Combine:
10372 // (extract_subvec (concat V1, V2, ...), i)
10373 // Into:
10374 // Vi if possible
Jack Carteradbd3ae2013-10-17 01:34:33 +000010375 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10376 // type.
Michael Liao9aecdb52012-10-19 03:17:00 +000010377 if (V->getOperand(0).getValueType() != NVT)
10378 return SDValue();
Michael Liao13429e22012-10-17 20:48:33 +000010379 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10380 unsigned NumElems = NVT.getVectorNumElements();
10381 assert((Idx % NumElems) == 0 &&
10382 "IDX in concat is not a multiple of the result vector length.");
10383 return V->getOperand(Idx / NumElems);
10384 }
10385
Michael Liaob4f98ea2013-03-25 23:47:35 +000010386 // Skip bitcasting
10387 if (V->getOpcode() == ISD::BITCAST)
10388 V = V.getOperand(0);
10389
10390 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickac6d9be2013-05-25 02:42:55 +000010391 SDLoc dl(N);
Michael Liaob4f98ea2013-03-25 23:47:35 +000010392 // Handle only simple case where vector being inserted and vector
10393 // being extracted are of same type, and are half size of larger vectors.
10394 EVT BigVT = V->getOperand(0).getValueType();
10395 EVT SmallVT = V->getOperand(1).getValueType();
10396 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10397 return SDValue();
10398
10399 // Only handle cases where both indexes are constants with the same type.
10400 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10401 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10402
10403 if (InsIdx && ExtIdx &&
10404 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10405 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10406 // Combine:
10407 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10408 // Into:
10409 // indices are equal or bit offsets are equal => V1
10410 // otherwise => (extract_subvec V1, ExtIdx)
10411 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10412 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10413 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10414 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10415 DAG.getNode(ISD::BITCAST, dl,
10416 N->getOperand(0).getValueType(),
10417 V->getOperand(0)), N->getOperand(1));
10418 }
10419 }
10420
Bruno Cardoso Lopese97190f2011-09-20 23:19:33 +000010421 return SDValue();
10422}
10423
Benjamin Kramer6fac1fb2013-04-09 17:41:43 +000010424// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10425static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10426 EVT VT = N->getValueType(0);
10427 unsigned NumElts = VT.getVectorNumElements();
10428
10429 SDValue N0 = N->getOperand(0);
10430 SDValue N1 = N->getOperand(1);
10431 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10432
10433 SmallVector<SDValue, 4> Ops;
10434 EVT ConcatVT = N0.getOperand(0).getValueType();
10435 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10436 unsigned NumConcats = NumElts / NumElemsPerConcat;
10437
10438 // Look at every vector that's inserted. We're looking for exact
10439 // subvector-sized copies from a concatenated vector
10440 for (unsigned I = 0; I != NumConcats; ++I) {
10441 // Make sure we're dealing with a copy.
10442 unsigned Begin = I * NumElemsPerConcat;
Hao Liu3778c042013-05-13 02:07:05 +000010443 bool AllUndef = true, NoUndef = true;
10444 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10445 if (SVN->getMaskElt(J) >= 0)
10446 AllUndef = false;
10447 else
10448 NoUndef = false;
Benjamin Kramer6fac1fb2013-04-09 17:41:43 +000010449 }
10450
Hao Liu3778c042013-05-13 02:07:05 +000010451 if (NoUndef) {
Hao Liu3778c042013-05-13 02:07:05 +000010452 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10453 return SDValue();
10454
10455 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10456 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10457 return SDValue();
10458
10459 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10460 if (FirstElt < N0.getNumOperands())
10461 Ops.push_back(N0.getOperand(FirstElt));
10462 else
10463 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10464
10465 } else if (AllUndef) {
10466 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10467 } else { // Mixed with general masks and undefs, can't do optimization.
10468 return SDValue();
10469 }
Benjamin Kramer6fac1fb2013-04-09 17:41:43 +000010470 }
10471
Andrew Trickac6d9be2013-05-25 02:42:55 +000010472 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
Benjamin Kramer6fac1fb2013-04-09 17:41:43 +000010473 Ops.size());
10474}
10475
Dan Gohman475871a2008-07-27 21:46:04 +000010476SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Andersone50ed302009-08-10 22:56:29 +000010477 EVT VT = N->getValueType(0);
Nate Begeman9008ca62009-04-27 18:41:29 +000010478 unsigned NumElts = VT.getVectorNumElements();
Chris Lattnerf1d0c622006-03-31 22:16:43 +000010479
Mon P Wangaeb06d22008-11-10 04:46:22 +000010480 SDValue N0 = N->getOperand(0);
Craig Topper481b79c2012-01-04 08:07:43 +000010481 SDValue N1 = N->getOperand(1);
Mon P Wangaeb06d22008-11-10 04:46:22 +000010482
Craig Topperae1bec52012-04-09 05:16:56 +000010483 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wangaeb06d22008-11-10 04:46:22 +000010484
Craig Topper481b79c2012-01-04 08:07:43 +000010485 // Canonicalize shuffle undef, undef -> undef
10486 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10487 return DAG.getUNDEF(VT);
10488
10489 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10490
10491 // Canonicalize shuffle v, v -> v, undef
10492 if (N0 == N1) {
10493 SmallVector<int, 8> NewMask;
10494 for (unsigned i = 0; i != NumElts; ++i) {
10495 int Idx = SVN->getMaskElt(i);
10496 if (Idx >= (int)NumElts) Idx -= NumElts;
10497 NewMask.push_back(Idx);
10498 }
Andrew Trickac6d9be2013-05-25 02:42:55 +000010499 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper481b79c2012-01-04 08:07:43 +000010500 &NewMask[0]);
10501 }
10502
10503 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10504 if (N0.getOpcode() == ISD::UNDEF) {
10505 SmallVector<int, 8> NewMask;
10506 for (unsigned i = 0; i != NumElts; ++i) {
10507 int Idx = SVN->getMaskElt(i);
Craig Topper4b206bd2012-04-09 05:55:33 +000010508 if (Idx >= 0) {
Craig Topper01d22aa2013-08-08 07:38:55 +000010509 if (Idx >= (int)NumElts)
Craig Topper4b206bd2012-04-09 05:55:33 +000010510 Idx -= NumElts;
Craig Topper01d22aa2013-08-08 07:38:55 +000010511 else
10512 Idx = -1; // remove reference to lhs
Craig Topper4b206bd2012-04-09 05:55:33 +000010513 }
10514 NewMask.push_back(Idx);
Craig Topper481b79c2012-01-04 08:07:43 +000010515 }
Andrew Trickac6d9be2013-05-25 02:42:55 +000010516 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper481b79c2012-01-04 08:07:43 +000010517 &NewMask[0]);
10518 }
10519
10520 // Remove references to rhs if it is undef
10521 if (N1.getOpcode() == ISD::UNDEF) {
10522 bool Changed = false;
10523 SmallVector<int, 8> NewMask;
10524 for (unsigned i = 0; i != NumElts; ++i) {
10525 int Idx = SVN->getMaskElt(i);
10526 if (Idx >= (int)NumElts) {
10527 Idx = -1;
10528 Changed = true;
10529 }
10530 NewMask.push_back(Idx);
10531 }
10532 if (Changed)
Andrew Trickac6d9be2013-05-25 02:42:55 +000010533 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper481b79c2012-01-04 08:07:43 +000010534 }
Evan Chenge7bec0d2006-07-20 22:44:41 +000010535
Bob Wilson0f1db1a2010-10-28 17:06:14 +000010536 // If it is a splat, check if the argument vector is another splat or a
10537 // build_vector with all scalar elements the same.
Bob Wilson0f1db1a2010-10-28 17:06:14 +000010538 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greifba36cb52008-08-28 21:40:38 +000010539 SDNode *V = N0.getNode();
Evan Cheng917ec982006-07-21 08:25:53 +000010540
Dan Gohman7f321562007-06-25 16:23:39 +000010541 // If this is a bit convert that changes the element type of the vector but
Evan Cheng59569222006-10-16 22:49:37 +000010542 // not the number of vector elements, look through it. Be careful not to
10543 // look though conversions that change things like v4f32 to v2f64.
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010544 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman475871a2008-07-27 21:46:04 +000010545 SDValue ConvInput = V->getOperand(0);
Evan Cheng29257862008-07-22 20:42:56 +000010546 if (ConvInput.getValueType().isVector() &&
10547 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greifba36cb52008-08-28 21:40:38 +000010548 V = ConvInput.getNode();
Evan Cheng59569222006-10-16 22:49:37 +000010549 }
10550
Dan Gohman7f321562007-06-25 16:23:39 +000010551 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilson0f1db1a2010-10-28 17:06:14 +000010552 assert(V->getNumOperands() == NumElts &&
10553 "BUILD_VECTOR has wrong number of operands");
10554 SDValue Base;
10555 bool AllSame = true;
10556 for (unsigned i = 0; i != NumElts; ++i) {
10557 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10558 Base = V->getOperand(i);
10559 break;
Evan Cheng917ec982006-07-21 08:25:53 +000010560 }
Evan Cheng917ec982006-07-21 08:25:53 +000010561 }
Bob Wilson0f1db1a2010-10-28 17:06:14 +000010562 // Splat of <u, u, u, u>, return <u, u, u, u>
10563 if (!Base.getNode())
10564 return N0;
10565 for (unsigned i = 0; i != NumElts; ++i) {
10566 if (V->getOperand(i) != Base) {
10567 AllSame = false;
10568 break;
10569 }
10570 }
10571 // Splat of <x, x, x, x>, return <x, x, x, x>
10572 if (AllSame)
10573 return N0;
Evan Cheng917ec982006-07-21 08:25:53 +000010574 }
10575 }
Nadav Rotem4ac90812012-04-01 19:31:22 +000010576
Benjamin Kramer6fac1fb2013-04-09 17:41:43 +000010577 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10578 Level < AfterLegalizeVectorOps &&
10579 (N1.getOpcode() == ISD::UNDEF ||
10580 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10581 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10582 SDValue V = partitionShuffleOfConcats(N, DAG);
10583
10584 if (V.getNode())
10585 return V;
10586 }
10587
Nadav Rotem4ac90812012-04-01 19:31:22 +000010588 // If this shuffle node is simply a swizzle of another shuffle node,
Nadav Rotemd16c8d02012-04-07 21:19:08 +000010589 // and it reverses the swizzle of the previous shuffle then we can
10590 // optimize shuffle(shuffle(x, undef), undef) -> x.
Nadav Rotem4ac90812012-04-01 19:31:22 +000010591 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10592 N1.getOpcode() == ISD::UNDEF) {
10593
Nadav Rotem4ac90812012-04-01 19:31:22 +000010594 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10595
Nadav Rotemd16c8d02012-04-07 21:19:08 +000010596 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10597 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10598 return SDValue();
10599
Craig Topperae1bec52012-04-09 05:16:56 +000010600 // The incoming shuffle must be of the same type as the result of the
10601 // current shuffle.
10602 assert(OtherSV->getOperand(0).getValueType() == VT &&
10603 "Shuffle types don't match");
Nadav Rotem4ac90812012-04-01 19:31:22 +000010604
10605 for (unsigned i = 0; i != NumElts; ++i) {
10606 int Idx = SVN->getMaskElt(i);
Craig Topperae1bec52012-04-09 05:16:56 +000010607 assert(Idx < (int)NumElts && "Index references undef operand");
Nadav Rotem4ac90812012-04-01 19:31:22 +000010608 // Next, this index comes from the first value, which is the incoming
10609 // shuffle. Adopt the incoming index.
10610 if (Idx >= 0)
10611 Idx = OtherSV->getMaskElt(Idx);
10612
Nadav Rotemd16c8d02012-04-07 21:19:08 +000010613 // The combined shuffle must map each index to itself.
Craig Topperae1bec52012-04-09 05:16:56 +000010614 if (Idx >= 0 && (unsigned)Idx != i)
Nadav Rotemd16c8d02012-04-07 21:19:08 +000010615 return SDValue();
Nadav Rotem4ac90812012-04-01 19:31:22 +000010616 }
Nadav Rotemd16c8d02012-04-07 21:19:08 +000010617
10618 return OtherSV->getOperand(0);
Nadav Rotem4ac90812012-04-01 19:31:22 +000010619 }
10620
Dan Gohman475871a2008-07-27 21:46:04 +000010621 return SDValue();
Chris Lattnerf1d0c622006-03-31 22:16:43 +000010622}
10623
Stephen Hines36b56882014-04-23 16:57:46 -070010624SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10625 SDValue N0 = N->getOperand(0);
10626 SDValue N2 = N->getOperand(2);
10627
10628 // If the input vector is a concatenation, and the insert replaces
10629 // one of the halves, we can optimize into a single concat_vectors.
10630 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10631 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10632 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10633 EVT VT = N->getValueType(0);
10634
10635 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10636 // (concat_vectors Z, Y)
10637 if (InsIdx == 0)
10638 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10639 N->getOperand(1), N0.getOperand(1));
10640
10641 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10642 // (concat_vectors X, Z)
10643 if (InsIdx == VT.getVectorNumElements()/2)
10644 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10645 N0.getOperand(0), N->getOperand(1));
10646 }
10647
10648 return SDValue();
10649}
10650
Evan Cheng44f1f092006-04-20 08:56:16 +000010651/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
Dan Gohman7f321562007-06-25 16:23:39 +000010652/// an AND to a vector_shuffle with the destination vector and a zero vector.
10653/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Cheng44f1f092006-04-20 08:56:16 +000010654/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman475871a2008-07-27 21:46:04 +000010655SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Andersone50ed302009-08-10 22:56:29 +000010656 EVT VT = N->getValueType(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +000010657 SDLoc dl(N);
Dan Gohman475871a2008-07-27 21:46:04 +000010658 SDValue LHS = N->getOperand(0);
10659 SDValue RHS = N->getOperand(1);
Dan Gohman7f321562007-06-25 16:23:39 +000010660 if (N->getOpcode() == ISD::AND) {
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010661 if (RHS.getOpcode() == ISD::BITCAST)
Evan Cheng44f1f092006-04-20 08:56:16 +000010662 RHS = RHS.getOperand(0);
Dan Gohman7f321562007-06-25 16:23:39 +000010663 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman9008ca62009-04-27 18:41:29 +000010664 SmallVector<int, 8> Indices;
10665 unsigned NumElts = RHS.getNumOperands();
Evan Cheng44f1f092006-04-20 08:56:16 +000010666 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +000010667 SDValue Elt = RHS.getOperand(i);
Evan Cheng44f1f092006-04-20 08:56:16 +000010668 if (!isa<ConstantSDNode>(Elt))
Dan Gohman475871a2008-07-27 21:46:04 +000010669 return SDValue();
Craig Topperb7135e52012-04-09 05:59:53 +000010670
10671 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman9008ca62009-04-27 18:41:29 +000010672 Indices.push_back(i);
Evan Cheng44f1f092006-04-20 08:56:16 +000010673 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Nate Begeman9008ca62009-04-27 18:41:29 +000010674 Indices.push_back(NumElts);
Evan Cheng44f1f092006-04-20 08:56:16 +000010675 else
Dan Gohman475871a2008-07-27 21:46:04 +000010676 return SDValue();
Evan Cheng44f1f092006-04-20 08:56:16 +000010677 }
10678
10679 // Let's see if the target supports this vector_shuffle.
Owen Andersone50ed302009-08-10 22:56:29 +000010680 EVT RVT = RHS.getValueType();
Nate Begeman9008ca62009-04-27 18:41:29 +000010681 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman475871a2008-07-27 21:46:04 +000010682 return SDValue();
Evan Cheng44f1f092006-04-20 08:56:16 +000010683
Dan Gohman7f321562007-06-25 16:23:39 +000010684 // Return the new VECTOR_SHUFFLE node.
Dan Gohman8a55ce42009-09-23 21:02:20 +000010685 EVT EltVT = RVT.getVectorElementType();
Nate Begeman9008ca62009-04-27 18:41:29 +000010686 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman8a55ce42009-09-23 21:02:20 +000010687 DAG.getConstant(0, EltVT));
Andrew Trickac6d9be2013-05-25 02:42:55 +000010688 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Nate Begeman9008ca62009-04-27 18:41:29 +000010689 RVT, &ZeroOps[0], ZeroOps.size());
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010690 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman9008ca62009-04-27 18:41:29 +000010691 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010692 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Cheng44f1f092006-04-20 08:56:16 +000010693 }
10694 }
Bill Wendling836ca7d2009-01-30 23:59:18 +000010695
Dan Gohman475871a2008-07-27 21:46:04 +000010696 return SDValue();
Evan Cheng44f1f092006-04-20 08:56:16 +000010697}
10698
Dan Gohman7f321562007-06-25 16:23:39 +000010699/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
Dan Gohman475871a2008-07-27 21:46:04 +000010700SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilsond7273432010-12-17 23:06:49 +000010701 assert(N->getValueType(0).isVector() &&
10702 "SimplifyVBinOp only works on vectors!");
Dan Gohman7f321562007-06-25 16:23:39 +000010703
Dan Gohman475871a2008-07-27 21:46:04 +000010704 SDValue LHS = N->getOperand(0);
10705 SDValue RHS = N->getOperand(1);
10706 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greifba36cb52008-08-28 21:40:38 +000010707 if (Shuffle.getNode()) return Shuffle;
Evan Cheng44f1f092006-04-20 08:56:16 +000010708
Dan Gohman7f321562007-06-25 16:23:39 +000010709 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattneredab1b92006-04-02 03:25:57 +000010710 // this operation.
Scott Michelfdc40a02009-02-17 22:15:04 +000010711 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohman7f321562007-06-25 16:23:39 +000010712 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Stephen Hines36b56882014-04-23 16:57:46 -070010713 // Check if both vectors are constants. If not bail out.
10714 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10715 cast<BuildVectorSDNode>(RHS)->isConstant()))
10716 return SDValue();
10717
Dan Gohman475871a2008-07-27 21:46:04 +000010718 SmallVector<SDValue, 8> Ops;
Dan Gohman7f321562007-06-25 16:23:39 +000010719 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +000010720 SDValue LHSOp = LHS.getOperand(i);
10721 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling836ca7d2009-01-30 23:59:18 +000010722
Evan Cheng7b336a82006-05-31 06:08:35 +000010723 // Can't fold divide by zero.
Dan Gohman7f321562007-06-25 16:23:39 +000010724 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10725 N->getOpcode() == ISD::FDIV) {
Evan Cheng7b336a82006-05-31 06:08:35 +000010726 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greifba36cb52008-08-28 21:40:38 +000010727 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng7b336a82006-05-31 06:08:35 +000010728 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greifba36cb52008-08-28 21:40:38 +000010729 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng7b336a82006-05-31 06:08:35 +000010730 break;
10731 }
Bill Wendling836ca7d2009-01-30 23:59:18 +000010732
Bob Wilsond7273432010-12-17 23:06:49 +000010733 EVT VT = LHSOp.getValueType();
Bob Wilsondb2b18f2011-10-18 17:34:47 +000010734 EVT RVT = RHSOp.getValueType();
10735 if (RVT != VT) {
10736 // Integer BUILD_VECTOR operands may have types larger than the element
10737 // size (e.g., when the element type is not legal). Prior to type
10738 // legalization, the types may not match between the two BUILD_VECTORS.
10739 // Truncate one of the operands to make them match.
10740 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +000010741 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilsondb2b18f2011-10-18 17:34:47 +000010742 } else {
Andrew Trickac6d9be2013-05-25 02:42:55 +000010743 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilsondb2b18f2011-10-18 17:34:47 +000010744 VT = RVT;
10745 }
10746 }
Andrew Trickac6d9be2013-05-25 02:42:55 +000010747 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Chenga0839882010-05-18 00:03:40 +000010748 LHSOp, RHSOp);
10749 if (FoldOp.getOpcode() != ISD::UNDEF &&
10750 FoldOp.getOpcode() != ISD::Constant &&
10751 FoldOp.getOpcode() != ISD::ConstantFP)
10752 break;
10753 Ops.push_back(FoldOp);
10754 AddToWorkList(FoldOp.getNode());
Chris Lattneredab1b92006-04-02 03:25:57 +000010755 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010756
Bob Wilsond7273432010-12-17 23:06:49 +000010757 if (Ops.size() == LHS.getNumOperands())
Andrew Trickac6d9be2013-05-25 02:42:55 +000010758 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Bob Wilsond7273432010-12-17 23:06:49 +000010759 LHS.getValueType(), &Ops[0], Ops.size());
Chris Lattneredab1b92006-04-02 03:25:57 +000010760 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010761
Dan Gohman475871a2008-07-27 21:46:04 +000010762 return SDValue();
Chris Lattneredab1b92006-04-02 03:25:57 +000010763}
10764
Craig Topperdd201ff2012-09-11 01:45:21 +000010765/// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10766SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topperdd201ff2012-09-11 01:45:21 +000010767 assert(N->getValueType(0).isVector() &&
10768 "SimplifyVUnaryOp only works on vectors!");
10769
10770 SDValue N0 = N->getOperand(0);
10771
10772 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10773 return SDValue();
10774
10775 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10776 SmallVector<SDValue, 8> Ops;
10777 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10778 SDValue Op = N0.getOperand(i);
10779 if (Op.getOpcode() != ISD::UNDEF &&
10780 Op.getOpcode() != ISD::ConstantFP)
10781 break;
10782 EVT EltVT = Op.getValueType();
Andrew Trickac6d9be2013-05-25 02:42:55 +000010783 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topperdd201ff2012-09-11 01:45:21 +000010784 if (FoldOp.getOpcode() != ISD::UNDEF &&
10785 FoldOp.getOpcode() != ISD::ConstantFP)
10786 break;
10787 Ops.push_back(FoldOp);
10788 AddToWorkList(FoldOp.getNode());
10789 }
10790
10791 if (Ops.size() != N0.getNumOperands())
10792 return SDValue();
10793
Andrew Trickac6d9be2013-05-25 02:42:55 +000010794 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Craig Topperdd201ff2012-09-11 01:45:21 +000010795 N0.getValueType(), &Ops[0], Ops.size());
10796}
10797
Andrew Trickac6d9be2013-05-25 02:42:55 +000010798SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling836ca7d2009-01-30 23:59:18 +000010799 SDValue N1, SDValue N2){
Nate Begemanf845b452005-10-08 00:29:44 +000010800 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelfdc40a02009-02-17 22:15:04 +000010801
Bill Wendling836ca7d2009-01-30 23:59:18 +000010802 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begemanf845b452005-10-08 00:29:44 +000010803 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling836ca7d2009-01-30 23:59:18 +000010804
Nate Begemanf845b452005-10-08 00:29:44 +000010805 // If we got a simplified select_cc node back from SimplifySelectCC, then
10806 // break it down into a new SETCC node, and a new SELECT node, and then return
10807 // the SELECT node, since we were called with a SELECT node.
Gabor Greifba36cb52008-08-28 21:40:38 +000010808 if (SCC.getNode()) {
Nate Begemanf845b452005-10-08 00:29:44 +000010809 // Check to see if we got a select_cc back (to turn into setcc/select).
10810 // Otherwise, just return whatever node we got back, like fabs.
10811 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickac6d9be2013-05-25 02:42:55 +000010812 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling836ca7d2009-01-30 23:59:18 +000010813 N0.getValueType(),
Scott Michelfdc40a02009-02-17 22:15:04 +000010814 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling836ca7d2009-01-30 23:59:18 +000010815 SCC.getOperand(4));
Gabor Greifba36cb52008-08-28 21:40:38 +000010816 AddToWorkList(SETCC.getNode());
Matt Arsenaultb05e4772013-06-14 22:04:37 +000010817 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10818 SCC.getOperand(2), SCC.getOperand(3), SETCC);
Nate Begemanf845b452005-10-08 00:29:44 +000010819 }
Bill Wendling836ca7d2009-01-30 23:59:18 +000010820
Nate Begemanf845b452005-10-08 00:29:44 +000010821 return SCC;
10822 }
Dan Gohman475871a2008-07-27 21:46:04 +000010823 return SDValue();
Nate Begeman44728a72005-09-19 22:34:01 +000010824}
10825
Chris Lattner40c62d52005-10-18 06:04:22 +000010826/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10827/// are the two values being selected between, see if we can simplify the
Chris Lattner729c6d12006-05-27 00:43:02 +000010828/// select. Callers of this should assume that TheSelect is deleted if this
10829/// returns true. As such, they should return the appropriate thing (e.g. the
10830/// node) back to the top-level of the DAG combiner loop to avoid it being
10831/// looked at.
Scott Michelfdc40a02009-02-17 22:15:04 +000010832bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman475871a2008-07-27 21:46:04 +000010833 SDValue RHS) {
Scott Michelfdc40a02009-02-17 22:15:04 +000010834
Nadav Rotemf94fdb62011-02-11 19:57:47 +000010835 // Cannot simplify select with vector condition
10836 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10837
Chris Lattner40c62d52005-10-18 06:04:22 +000010838 // If this is a select from two identical things, try to pull the operation
10839 // through the select.
Chris Lattner18061612010-09-21 15:46:59 +000010840 if (LHS.getOpcode() != RHS.getOpcode() ||
10841 !LHS.hasOneUse() || !RHS.hasOneUse())
10842 return false;
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010843
Chris Lattner18061612010-09-21 15:46:59 +000010844 // If this is a load and the token chain is identical, replace the select
10845 // of two loads with a load through a select of the address to load from.
10846 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10847 // constants have been dropped into the constant pool.
10848 if (LHS.getOpcode() == ISD::LOAD) {
10849 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10850 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010851
Chris Lattner18061612010-09-21 15:46:59 +000010852 // Token chains must be identical.
10853 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sandsd4b9c172008-06-13 19:07:40 +000010854 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner18061612010-09-21 15:46:59 +000010855 LLD->isVolatile() || RLD->isVolatile() ||
10856 // If this is an EXTLOAD, the VT's must match.
10857 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sandsdcfd3a72010-11-18 20:05:18 +000010858 // If this is an EXTLOAD, the kind of extension must match.
10859 (LLD->getExtensionType() != RLD->getExtensionType() &&
10860 // The only exception is if one of the extensions is anyext.
10861 LLD->getExtensionType() != ISD::EXTLOAD &&
10862 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohman75832d72009-10-31 14:14:04 +000010863 // FIXME: this discards src value information. This is
10864 // over-conservative. It would be beneficial to be able to remember
Mon P Wangfe240b12010-01-11 20:12:49 +000010865 // both potential memory locations. Since we are discarding
10866 // src value info, don't do the transformation if the memory
10867 // locations are not in the default address space.
Chris Lattner18061612010-09-21 15:46:59 +000010868 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooperb0fde6d2013-02-12 03:14:50 +000010869 RLD->getPointerInfo().getAddrSpace() != 0 ||
10870 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10871 LLD->getBasePtr().getValueType()))
Chris Lattner18061612010-09-21 15:46:59 +000010872 return false;
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010873
Chris Lattnerf1658062010-09-21 15:58:55 +000010874 // Check that the select condition doesn't reach either load. If so,
10875 // folding this will induce a cycle into the DAG. If not, this is safe to
10876 // xform, so create a select of the addresses.
Chris Lattner18061612010-09-21 15:46:59 +000010877 SDValue Addr;
10878 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnerf1658062010-09-21 15:58:55 +000010879 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10880 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10881 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10882 return false;
Nadav Rotem1c5bf3f2012-10-18 18:06:48 +000010883 // The loads must not depend on one another.
10884 if (LLD->isPredecessorOf(RLD) ||
10885 RLD->isPredecessorOf(LLD))
10886 return false;
Matt Arsenaultb05e4772013-06-14 22:04:37 +000010887 Addr = DAG.getSelect(SDLoc(TheSelect),
10888 LLD->getBasePtr().getValueType(),
10889 TheSelect->getOperand(0), LLD->getBasePtr(),
10890 RLD->getBasePtr());
Chris Lattner18061612010-09-21 15:46:59 +000010891 } else { // Otherwise SELECT_CC
Chris Lattnerf1658062010-09-21 15:58:55 +000010892 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10893 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10894
10895 if ((LLD->hasAnyUseOfValue(1) &&
10896 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner77d95212012-03-27 16:27:21 +000010897 (RLD->hasAnyUseOfValue(1) &&
10898 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnerf1658062010-09-21 15:58:55 +000010899 return false;
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010900
Andrew Trickac6d9be2013-05-25 02:42:55 +000010901 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnerf1658062010-09-21 15:58:55 +000010902 LLD->getBasePtr().getValueType(),
10903 TheSelect->getOperand(0),
10904 TheSelect->getOperand(1),
10905 LLD->getBasePtr(), RLD->getBasePtr(),
10906 TheSelect->getOperand(4));
Chris Lattner18061612010-09-21 15:46:59 +000010907 }
10908
Chris Lattnerf1658062010-09-21 15:58:55 +000010909 SDValue Load;
10910 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10911 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickac6d9be2013-05-25 02:42:55 +000010912 SDLoc(TheSelect),
Richard Sandiford66589dc2013-10-28 11:17:59 +000010913 // FIXME: Discards pointer and TBAA info.
Chris Lattnerf1658062010-09-21 15:58:55 +000010914 LLD->getChain(), Addr, MachinePointerInfo(),
10915 LLD->isVolatile(), LLD->isNonTemporal(),
Pete Cooperd752e0f2011-11-08 18:42:53 +000010916 LLD->isInvariant(), LLD->getAlignment());
Chris Lattnerf1658062010-09-21 15:58:55 +000010917 } else {
Duncan Sandsb9064bb2010-11-18 21:16:28 +000010918 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10919 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickac6d9be2013-05-25 02:42:55 +000010920 SDLoc(TheSelect),
Stuart Hastingsa9011292011-02-16 16:23:55 +000010921 TheSelect->getValueType(0),
Richard Sandiford66589dc2013-10-28 11:17:59 +000010922 // FIXME: Discards pointer and TBAA info.
Chris Lattnerf1658062010-09-21 15:58:55 +000010923 LLD->getChain(), Addr, MachinePointerInfo(),
10924 LLD->getMemoryVT(), LLD->isVolatile(),
10925 LLD->isNonTemporal(), LLD->getAlignment());
Chris Lattner40c62d52005-10-18 06:04:22 +000010926 }
Chris Lattnerf1658062010-09-21 15:58:55 +000010927
10928 // Users of the select now use the result of the load.
10929 CombineTo(TheSelect, Load);
10930
10931 // Users of the old loads now use the new load's chain. We know the
10932 // old-load value is dead now.
10933 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10934 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10935 return true;
Chris Lattner40c62d52005-10-18 06:04:22 +000010936 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010937
Chris Lattner40c62d52005-10-18 06:04:22 +000010938 return false;
10939}
10940
Chris Lattner600fec32009-03-11 05:08:08 +000010941/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10942/// where 'cond' is the comparison specified by CC.
Andrew Trickac6d9be2013-05-25 02:42:55 +000010943SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman475871a2008-07-27 21:46:04 +000010944 SDValue N2, SDValue N3,
10945 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner600fec32009-03-11 05:08:08 +000010946 // (x ? y : y) -> y.
10947 if (N2 == N3) return N2;
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010948
Owen Andersone50ed302009-08-10 22:56:29 +000010949 EVT VT = N2.getValueType();
Gabor Greifba36cb52008-08-28 21:40:38 +000010950 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10951 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10952 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begemanf845b452005-10-08 00:29:44 +000010953
10954 // Determine if the condition we're dealing with is constant
Matt Arsenault225ed702013-05-18 00:21:46 +000010955 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenff97d4f2009-02-03 00:47:48 +000010956 N0, N1, CC, DL, false);
Gabor Greifba36cb52008-08-28 21:40:38 +000010957 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10958 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begemanf845b452005-10-08 00:29:44 +000010959
10960 // fold select_cc true, x, y -> x
Dan Gohman002e5d02008-03-13 22:13:53 +000010961 if (SCCC && !SCCC->isNullValue())
Nate Begemanf845b452005-10-08 00:29:44 +000010962 return N2;
10963 // fold select_cc false, x, y -> y
Dan Gohman002e5d02008-03-13 22:13:53 +000010964 if (SCCC && SCCC->isNullValue())
Nate Begemanf845b452005-10-08 00:29:44 +000010965 return N3;
Scott Michelfdc40a02009-02-17 22:15:04 +000010966
Nate Begemanf845b452005-10-08 00:29:44 +000010967 // Check to see if we can simplify the select into an fabs node
10968 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10969 // Allow either -0.0 or 0.0
Dale Johannesen87503a62007-08-25 22:10:57 +000010970 if (CFP->getValueAPF().isZero()) {
Nate Begemanf845b452005-10-08 00:29:44 +000010971 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10972 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10973 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10974 N2 == N3.getOperand(0))
Bill Wendling836ca7d2009-01-30 23:59:18 +000010975 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +000010976
Nate Begemanf845b452005-10-08 00:29:44 +000010977 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10978 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10979 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10980 N2.getOperand(0) == N3)
Bill Wendling836ca7d2009-01-30 23:59:18 +000010981 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begemanf845b452005-10-08 00:29:44 +000010982 }
10983 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010984
Chris Lattner600fec32009-03-11 05:08:08 +000010985 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10986 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10987 // in it. This is a win when the constant is not otherwise available because
10988 // it replaces two constant pool loads with one. We only do this if the FP
10989 // type is known to be legal, because if it isn't, then we are before legalize
10990 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wang0b7a7862009-03-14 00:25:19 +000010991 // messing with soft float) and if the ConstantFP is not legal, because if
10992 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner600fec32009-03-11 05:08:08 +000010993 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10994 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10995 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wang0b7a7862009-03-14 00:25:19 +000010996 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10997 TargetLowering::Legal) &&
Chris Lattner600fec32009-03-11 05:08:08 +000010998 // If both constants have multiple uses, then we won't need to do an
10999 // extra load, they are likely around in registers for other users.
11000 (TV->hasOneUse() || FV->hasOneUse())) {
11001 Constant *Elts[] = {
11002 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11003 const_cast<ConstantFP*>(TV->getConstantFPValue())
11004 };
Chris Lattnerdb125cf2011-07-18 04:54:35 +000011005 Type *FPTy = Elts[0]->getType();
Micah Villmow3574eca2012-10-08 16:38:25 +000011006 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011007
Chris Lattner600fec32009-03-11 05:08:08 +000011008 // Create a ConstantArray of the two constants.
Jay Foad26701082011-06-22 09:24:39 +000011009 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner600fec32009-03-11 05:08:08 +000011010 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11011 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1606e8e2009-03-13 07:51:59 +000011012 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner600fec32009-03-11 05:08:08 +000011013
11014 // Get the offsets to the 0 and 1 element of the array so that we can
11015 // select between them.
11016 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sands777d2302009-05-09 07:06:46 +000011017 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner600fec32009-03-11 05:08:08 +000011018 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011019
Chris Lattner600fec32009-03-11 05:08:08 +000011020 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault225ed702013-05-18 00:21:46 +000011021 getSetCCResultType(N0.getValueType()),
Chris Lattner600fec32009-03-11 05:08:08 +000011022 N0, N1, CC);
Dan Gohman7b316c92011-09-22 23:01:29 +000011023 AddToWorkList(Cond.getNode());
Matt Arsenaultb05e4772013-06-14 22:04:37 +000011024 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11025 Cond, One, Zero);
Dan Gohman7b316c92011-09-22 23:01:29 +000011026 AddToWorkList(CstOffset.getNode());
Tom Stellardedd08f72013-08-26 15:06:10 +000011027 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner600fec32009-03-11 05:08:08 +000011028 CstOffset);
Dan Gohman7b316c92011-09-22 23:01:29 +000011029 AddToWorkList(CPIdx.getNode());
Chris Lattner600fec32009-03-11 05:08:08 +000011030 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattner85ca1062010-09-21 07:32:19 +000011031 MachinePointerInfo::getConstantPool(), false,
Pete Cooperd752e0f2011-11-08 18:42:53 +000011032 false, false, Alignment);
Chris Lattner600fec32009-03-11 05:08:08 +000011033
11034 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011035 }
Scott Michelfdc40a02009-02-17 22:15:04 +000011036
Nate Begemanf845b452005-10-08 00:29:44 +000011037 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling836ca7d2009-01-30 23:59:18 +000011038 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnere3152e52006-09-20 06:41:35 +000011039 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohman002e5d02008-03-13 22:13:53 +000011040 (N1C->isNullValue() || // (a < 0) ? b : 0
11041 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Andersone50ed302009-08-10 22:56:29 +000011042 EVT XType = N0.getValueType();
11043 EVT AType = N2.getValueType();
Duncan Sands8e4eb092008-06-08 20:54:56 +000011044 if (XType.bitsGE(AType)) {
Sylvestre Ledru94c22712012-09-27 10:14:43 +000011045 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman07ed4172005-10-10 21:26:48 +000011046 // single-bit constant.
Dan Gohman002e5d02008-03-13 22:13:53 +000011047 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11048 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands83ec4b62008-06-06 12:08:01 +000011049 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Anderson95771af2011-02-25 21:41:48 +000011050 SDValue ShCt = DAG.getConstant(ShCtV,
11051 getShiftAmountTy(N0.getValueType()));
Andrew Trickac6d9be2013-05-25 02:42:55 +000011052 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling836ca7d2009-01-30 23:59:18 +000011053 XType, N0, ShCt);
Gabor Greifba36cb52008-08-28 21:40:38 +000011054 AddToWorkList(Shift.getNode());
Bill Wendling836ca7d2009-01-30 23:59:18 +000011055
Duncan Sands8e4eb092008-06-08 20:54:56 +000011056 if (XType.bitsGT(AType)) {
Bill Wendling9729c5a2009-01-31 03:12:48 +000011057 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greifba36cb52008-08-28 21:40:38 +000011058 AddToWorkList(Shift.getNode());
Nate Begemanf845b452005-10-08 00:29:44 +000011059 }
Bill Wendling836ca7d2009-01-30 23:59:18 +000011060
11061 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begemanf845b452005-10-08 00:29:44 +000011062 }
Bill Wendling836ca7d2009-01-30 23:59:18 +000011063
Andrew Trickac6d9be2013-05-25 02:42:55 +000011064 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling836ca7d2009-01-30 23:59:18 +000011065 XType, N0,
11066 DAG.getConstant(XType.getSizeInBits()-1,
Owen Anderson95771af2011-02-25 21:41:48 +000011067 getShiftAmountTy(N0.getValueType())));
Gabor Greifba36cb52008-08-28 21:40:38 +000011068 AddToWorkList(Shift.getNode());
Bill Wendling836ca7d2009-01-30 23:59:18 +000011069
Duncan Sands8e4eb092008-06-08 20:54:56 +000011070 if (XType.bitsGT(AType)) {
Bill Wendling9729c5a2009-01-31 03:12:48 +000011071 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greifba36cb52008-08-28 21:40:38 +000011072 AddToWorkList(Shift.getNode());
Nate Begemanf845b452005-10-08 00:29:44 +000011073 }
Bill Wendling836ca7d2009-01-30 23:59:18 +000011074
11075 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begemanf845b452005-10-08 00:29:44 +000011076 }
11077 }
Scott Michelfdc40a02009-02-17 22:15:04 +000011078
Owen Andersoned1088a2010-09-22 22:58:22 +000011079 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11080 // where y is has a single bit set.
11081 // A plaintext description would be, we can turn the SELECT_CC into an AND
11082 // when the condition can be materialized as an all-ones register. Any
11083 // single bit-test can be materialized as an all-ones register with
11084 // shift-left and shift-right-arith.
11085 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11086 N0->getValueType(0) == VT &&
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011087 N1C && N1C->isNullValue() &&
Owen Andersoned1088a2010-09-22 22:58:22 +000011088 N2C && N2C->isNullValue()) {
11089 SDValue AndLHS = N0->getOperand(0);
11090 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11091 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11092 // Shift the tested bit over the sign bit.
11093 APInt AndMask = ConstAndRHS->getAPIntValue();
11094 SDValue ShlAmt =
Owen Anderson95771af2011-02-25 21:41:48 +000011095 DAG.getConstant(AndMask.countLeadingZeros(),
11096 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickac6d9be2013-05-25 02:42:55 +000011097 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011098
Owen Andersoned1088a2010-09-22 22:58:22 +000011099 // Now arithmetic right shift it all the way over, so the result is either
11100 // all-ones, or zero.
11101 SDValue ShrAmt =
Owen Anderson95771af2011-02-25 21:41:48 +000011102 DAG.getConstant(AndMask.getBitWidth()-1,
11103 getShiftAmountTy(Shl.getValueType()));
Andrew Trickac6d9be2013-05-25 02:42:55 +000011104 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011105
Owen Andersoned1088a2010-09-22 22:58:22 +000011106 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11107 }
11108 }
11109
Nate Begeman07ed4172005-10-10 21:26:48 +000011110 // fold select C, 16, 0 -> shl C, 4
Dan Gohman002e5d02008-03-13 22:13:53 +000011111 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Duncan Sands28b77e92011-09-06 19:07:46 +000011112 TLI.getBooleanContents(N0.getValueType().isVector()) ==
11113 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelfdc40a02009-02-17 22:15:04 +000011114
Chris Lattner1eba01e2007-04-11 06:50:51 +000011115 // If the caller doesn't want us to simplify this into a zext of a compare,
11116 // don't do it.
Dan Gohman002e5d02008-03-13 22:13:53 +000011117 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman475871a2008-07-27 21:46:04 +000011118 return SDValue();
Scott Michelfdc40a02009-02-17 22:15:04 +000011119
Nate Begeman07ed4172005-10-10 21:26:48 +000011120 // Get a SetCC of the condition
Owen Andersonefcc1ae2012-11-03 00:17:26 +000011121 // NOTE: Don't create a SETCC if it's not legal on this target.
11122 if (!LegalOperations ||
11123 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault225ed702013-05-18 00:21:46 +000011124 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Andersonefcc1ae2012-11-03 00:17:26 +000011125 SDValue Temp, SCC;
11126 // cast from setcc result type to select result type
11127 if (LegalTypes) {
Matt Arsenault225ed702013-05-18 00:21:46 +000011128 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Andersonefcc1ae2012-11-03 00:17:26 +000011129 N0, N1, CC);
11130 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickac6d9be2013-05-25 02:42:55 +000011131 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Andersonefcc1ae2012-11-03 00:17:26 +000011132 N2.getValueType());
11133 else
Andrew Trickac6d9be2013-05-25 02:42:55 +000011134 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Andersonefcc1ae2012-11-03 00:17:26 +000011135 N2.getValueType(), SCC);
11136 } else {
Andrew Trickac6d9be2013-05-25 02:42:55 +000011137 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11138 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling836ca7d2009-01-30 23:59:18 +000011139 N2.getValueType(), SCC);
Owen Andersonefcc1ae2012-11-03 00:17:26 +000011140 }
11141
11142 AddToWorkList(SCC.getNode());
11143 AddToWorkList(Temp.getNode());
11144
11145 if (N2C->getAPIntValue() == 1)
11146 return Temp;
11147
11148 // shl setcc result by log2 n2c
Jack Carteradbd3ae2013-10-17 01:34:33 +000011149 return DAG.getNode(
11150 ISD::SHL, DL, N2.getValueType(), Temp,
11151 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11152 getShiftAmountTy(Temp.getValueType())));
Nate Begemanb0d04a72006-02-18 02:40:58 +000011153 }
Nate Begeman07ed4172005-10-10 21:26:48 +000011154 }
Scott Michelfdc40a02009-02-17 22:15:04 +000011155
Nate Begemanf845b452005-10-08 00:29:44 +000011156 // Check to see if this is the equivalent of setcc
11157 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11158 // otherwise, go ahead with the folds.
Dan Gohman002e5d02008-03-13 22:13:53 +000011159 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Andersone50ed302009-08-10 22:56:29 +000011160 EVT XType = N0.getValueType();
Duncan Sands25cf2272008-11-24 14:53:14 +000011161 if (!LegalOperations ||
Matt Arsenault225ed702013-05-18 00:21:46 +000011162 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11163 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begemanf845b452005-10-08 00:29:44 +000011164 if (Res.getValueType() != VT)
Bill Wendling836ca7d2009-01-30 23:59:18 +000011165 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begemanf845b452005-10-08 00:29:44 +000011166 return Res;
11167 }
Scott Michelfdc40a02009-02-17 22:15:04 +000011168
Bill Wendling836ca7d2009-01-30 23:59:18 +000011169 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelfdc40a02009-02-17 22:15:04 +000011170 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sands25cf2272008-11-24 14:53:14 +000011171 (!LegalOperations ||
Duncan Sands184a8762008-06-14 17:48:34 +000011172 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickac6d9be2013-05-25 02:42:55 +000011173 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +000011174 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands83ec4b62008-06-06 12:08:01 +000011175 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Anderson95771af2011-02-25 21:41:48 +000011176 getShiftAmountTy(Ctlz.getValueType())));
Nate Begemanf845b452005-10-08 00:29:44 +000011177 }
Bill Wendling836ca7d2009-01-30 23:59:18 +000011178 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelfdc40a02009-02-17 22:15:04 +000011179 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickac6d9be2013-05-25 02:42:55 +000011180 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling836ca7d2009-01-30 23:59:18 +000011181 XType, DAG.getConstant(0, XType), N0);
Andrew Trickac6d9be2013-05-25 02:42:55 +000011182 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling836ca7d2009-01-30 23:59:18 +000011183 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlingfc4b6772009-02-01 11:19:36 +000011184 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands83ec4b62008-06-06 12:08:01 +000011185 DAG.getConstant(XType.getSizeInBits()-1,
Owen Anderson95771af2011-02-25 21:41:48 +000011186 getShiftAmountTy(XType)));
Nate Begemanf845b452005-10-08 00:29:44 +000011187 }
Bill Wendling836ca7d2009-01-30 23:59:18 +000011188 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begemanf845b452005-10-08 00:29:44 +000011189 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickac6d9be2013-05-25 02:42:55 +000011190 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling836ca7d2009-01-30 23:59:18 +000011191 DAG.getConstant(XType.getSizeInBits()-1,
Owen Anderson95771af2011-02-25 21:41:48 +000011192 getShiftAmountTy(N0.getValueType())));
Bill Wendling836ca7d2009-01-30 23:59:18 +000011193 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begemanf845b452005-10-08 00:29:44 +000011194 }
11195 }
Scott Michelfdc40a02009-02-17 22:15:04 +000011196
Benjamin Kramercde51102010-07-08 12:09:56 +000011197 // Check to see if this is an integer abs.
11198 // select_cc setg[te] X, 0, X, -X ->
11199 // select_cc setgt X, -1, X, -X ->
11200 // select_cc setl[te] X, 0, -X, X ->
11201 // select_cc setlt X, 1, -X, X ->
Nate Begemanf845b452005-10-08 00:29:44 +000011202 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramercde51102010-07-08 12:09:56 +000011203 if (N1C) {
11204 ConstantSDNode *SubC = NULL;
11205 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11206 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11207 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11208 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11209 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11210 (N1C->isOne() && CC == ISD::SETLT)) &&
11211 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11212 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11213
Owen Andersone50ed302009-08-10 22:56:29 +000011214 EVT XType = N0.getValueType();
Benjamin Kramercde51102010-07-08 12:09:56 +000011215 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +000011216 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramercde51102010-07-08 12:09:56 +000011217 N0,
11218 DAG.getConstant(XType.getSizeInBits()-1,
Owen Anderson95771af2011-02-25 21:41:48 +000011219 getShiftAmountTy(N0.getValueType())));
Andrew Trickac6d9be2013-05-25 02:42:55 +000011220 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramercde51102010-07-08 12:09:56 +000011221 XType, N0, Shift);
11222 AddToWorkList(Shift.getNode());
11223 AddToWorkList(Add.getNode());
11224 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begemanf845b452005-10-08 00:29:44 +000011225 }
11226 }
Scott Michelfdc40a02009-02-17 22:15:04 +000011227
Dan Gohman475871a2008-07-27 21:46:04 +000011228 return SDValue();
Nate Begeman44728a72005-09-19 22:34:01 +000011229}
11230
Evan Chengfa1eb272007-02-08 22:13:59 +000011231/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
Owen Andersone50ed302009-08-10 22:56:29 +000011232SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman475871a2008-07-27 21:46:04 +000011233 SDValue N1, ISD::CondCode Cond,
Andrew Trickac6d9be2013-05-25 02:42:55 +000011234 SDLoc DL, bool foldBooleans) {
Scott Michelfdc40a02009-02-17 22:15:04 +000011235 TargetLowering::DAGCombinerInfo
Nadav Rotem444b4bf2012-12-27 06:47:41 +000011236 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenff97d4f2009-02-03 00:47:48 +000011237 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman452d7be2005-09-16 00:54:12 +000011238}
11239
Nate Begeman69575232005-10-20 02:15:44 +000011240/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11241/// return a DAG expression to select that will generate the same value by
11242/// multiplying by a magic number. See:
11243/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman475871a2008-07-27 21:46:04 +000011244SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Andrew Lenharth232c9102006-06-12 16:07:18 +000011245 std::vector<SDNode*> Built;
Richard Osborne19a4daf2011-11-07 17:09:05 +000011246 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
Andrew Lenharthdae9cbe2006-05-16 17:42:15 +000011247
Andrew Lenharth232c9102006-06-12 16:07:18 +000011248 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
Andrew Lenharthdae9cbe2006-05-16 17:42:15 +000011249 ii != ee; ++ii)
11250 AddToWorkList(*ii);
11251 return S;
Nate Begeman69575232005-10-20 02:15:44 +000011252}
11253
11254/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
11255/// return a DAG expression to select that will generate the same value by
11256/// multiplying by a magic number. See:
11257/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman475871a2008-07-27 21:46:04 +000011258SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Andrew Lenharth232c9102006-06-12 16:07:18 +000011259 std::vector<SDNode*> Built;
Richard Osborne19a4daf2011-11-07 17:09:05 +000011260 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
Nate Begeman69575232005-10-20 02:15:44 +000011261
Andrew Lenharth232c9102006-06-12 16:07:18 +000011262 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
Andrew Lenharthdae9cbe2006-05-16 17:42:15 +000011263 ii != ee; ++ii)
11264 AddToWorkList(*ii);
11265 return S;
Nate Begeman69575232005-10-20 02:15:44 +000011266}
11267
Nate Begemancc66cdd2009-09-25 06:05:26 +000011268/// FindBaseOffset - Return true if base is a frame index, which is known not
Eric Christopher503a64d2010-12-09 04:48:06 +000011269// to alias with anything but itself. Provides base object and offset as
11270// results.
Nate Begemancc66cdd2009-09-25 06:05:26 +000011271static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky2943e372012-09-05 22:15:49 +000011272 const GlobalValue *&GV, const void *&CV) {
Jim Laskey71382342006-10-07 23:37:56 +000011273 // Assume it is a primitive operation.
Nate Begemancc66cdd2009-09-25 06:05:26 +000011274 Base = Ptr; Offset = 0; GV = 0; CV = 0;
Scott Michelfdc40a02009-02-17 22:15:04 +000011275
Jim Laskey71382342006-10-07 23:37:56 +000011276 // If it's an adding a simple constant then integrate the offset.
11277 if (Base.getOpcode() == ISD::ADD) {
11278 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11279 Base = Base.getOperand(0);
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +000011280 Offset += C->getZExtValue();
Jim Laskey71382342006-10-07 23:37:56 +000011281 }
11282 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011283
Nate Begemancc66cdd2009-09-25 06:05:26 +000011284 // Return the underlying GlobalValue, and update the Offset. Return false
11285 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11286 // by multiple nodes with different offsets.
11287 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11288 GV = G->getGlobal();
11289 Offset += G->getOffset();
11290 return false;
11291 }
Scott Michelfdc40a02009-02-17 22:15:04 +000011292
Nate Begemancc66cdd2009-09-25 06:05:26 +000011293 // Return the underlying Constant value, and update the Offset. Return false
11294 // for ConstantSDNodes since the same constant pool entry may be represented
11295 // by multiple nodes with different offsets.
11296 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky2943e372012-09-05 22:15:49 +000011297 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11298 : (const void *)C->getConstVal();
Nate Begemancc66cdd2009-09-25 06:05:26 +000011299 Offset += C->getOffset();
11300 return false;
11301 }
Jim Laskey71382342006-10-07 23:37:56 +000011302 // If it's any of the following then it can't alias with anything but itself.
Nate Begemancc66cdd2009-09-25 06:05:26 +000011303 return isa<FrameIndexSDNode>(Base);
Jim Laskey71382342006-10-07 23:37:56 +000011304}
11305
11306/// isAlias - Return true if there is any possibility that the two addresses
11307/// overlap.
Richard Sandiforda7be36c2013-10-28 12:00:00 +000011308bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
Jim Laskey096c22e2006-10-18 12:29:57 +000011309 const Value *SrcValue1, int SrcValueOffset1,
Nate Begemanb6aef5c2009-09-15 00:18:30 +000011310 unsigned SrcValueAlign1,
Dan Gohmanf96e4bd2010-10-20 00:31:05 +000011311 const MDNode *TBAAInfo1,
Richard Sandiforda7be36c2013-10-28 12:00:00 +000011312 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
Nate Begemanb6aef5c2009-09-15 00:18:30 +000011313 const Value *SrcValue2, int SrcValueOffset2,
Dan Gohmanf96e4bd2010-10-20 00:31:05 +000011314 unsigned SrcValueAlign2,
11315 const MDNode *TBAAInfo2) const {
Jim Laskey71382342006-10-07 23:37:56 +000011316 // If they are the same then they must be aliases.
11317 if (Ptr1 == Ptr2) return true;
Scott Michelfdc40a02009-02-17 22:15:04 +000011318
Richard Sandiforda7be36c2013-10-28 12:00:00 +000011319 // If they are both volatile then they cannot be reordered.
11320 if (IsVolatile1 && IsVolatile2) return true;
11321
Jim Laskey71382342006-10-07 23:37:56 +000011322 // Gather base node and offset information.
Dan Gohman475871a2008-07-27 21:46:04 +000011323 SDValue Base1, Base2;
Jim Laskey71382342006-10-07 23:37:56 +000011324 int64_t Offset1, Offset2;
Dan Gohman46510a72010-04-15 01:51:59 +000011325 const GlobalValue *GV1, *GV2;
Roman Divacky2943e372012-09-05 22:15:49 +000011326 const void *CV1, *CV2;
Nate Begemancc66cdd2009-09-25 06:05:26 +000011327 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11328 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
Scott Michelfdc40a02009-02-17 22:15:04 +000011329
Nate Begemancc66cdd2009-09-25 06:05:26 +000011330 // If they have a same base address then check to see if they overlap.
11331 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Bill Wendling836ca7d2009-01-30 23:59:18 +000011332 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
Scott Michelfdc40a02009-02-17 22:15:04 +000011333
Owen Anderson4a9f1502010-09-20 20:39:59 +000011334 // It is possible for different frame indices to alias each other, mostly
11335 // when tail call optimization reuses return address slots for arguments.
11336 // To catch this case, look up the actual index of frame indices to compute
11337 // the real alias relationship.
11338 if (isFrameIndex1 && isFrameIndex2) {
11339 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11340 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11341 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11342 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11343 }
11344
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011345 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson4a9f1502010-09-20 20:39:59 +000011346 // we know they cannot alias.
Nate Begemancc66cdd2009-09-25 06:05:26 +000011347 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11348 return false;
Jim Laskey096c22e2006-10-18 12:29:57 +000011349
Nate Begemanb6aef5c2009-09-15 00:18:30 +000011350 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11351 // compared to the size and offset of the access, we may be able to prove they
11352 // do not alias. This check is conservative for now to catch cases created by
11353 // splitting vector types.
11354 if ((SrcValueAlign1 == SrcValueAlign2) &&
11355 (SrcValueOffset1 != SrcValueOffset2) &&
11356 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11357 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11358 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011359
Nate Begemanb6aef5c2009-09-15 00:18:30 +000011360 // There is no overlap between these relatively aligned accesses of similar
11361 // size, return no alias.
11362 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11363 return false;
11364 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011365
Hal Finkel253acef2013-08-29 03:29:55 +000011366 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11367 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Stephen Hines36b56882014-04-23 16:57:46 -070011368#ifndef NDEBUG
11369 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11370 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11371 UseAA = false;
11372#endif
Hal Finkel77364b72013-09-15 02:19:49 +000011373 if (UseAA && SrcValue1 && SrcValue2) {
Jim Laskey07a27092006-10-18 19:08:31 +000011374 // Use alias analysis information.
Dan Gohmane9c8fa02007-08-27 16:32:11 +000011375 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11376 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11377 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
Scott Michelfdc40a02009-02-17 22:15:04 +000011378 AliasAnalysis::AliasResult AAResult =
Stephen Hines36b56882014-04-23 16:57:46 -070011379 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1,
11380 UseTBAA ? TBAAInfo1 : 0),
11381 AliasAnalysis::Location(SrcValue2, Overlap2,
11382 UseTBAA ? TBAAInfo2 : 0));
Jim Laskey07a27092006-10-18 19:08:31 +000011383 if (AAResult == AliasAnalysis::NoAlias)
11384 return false;
11385 }
Jim Laskey096c22e2006-10-18 12:29:57 +000011386
11387 // Otherwise we have to assume they alias.
11388 return true;
Jim Laskey71382342006-10-07 23:37:56 +000011389}
11390
Nadav Rotem90e11dc2012-11-29 00:00:08 +000011391bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11392 SDValue Ptr0, Ptr1;
11393 int64_t Size0, Size1;
Richard Sandiforda7be36c2013-10-28 12:00:00 +000011394 bool IsVolatile0, IsVolatile1;
Nadav Rotem90e11dc2012-11-29 00:00:08 +000011395 const Value *SrcValue0, *SrcValue1;
11396 int SrcValueOffset0, SrcValueOffset1;
11397 unsigned SrcValueAlign0, SrcValueAlign1;
11398 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
Richard Sandiforda7be36c2013-10-28 12:00:00 +000011399 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
Nadav Rotem90e11dc2012-11-29 00:00:08 +000011400 SrcValueAlign0, SrcTBAAInfo0);
Richard Sandiforda7be36c2013-10-28 12:00:00 +000011401 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
Nadav Rotem90e11dc2012-11-29 00:00:08 +000011402 SrcValueAlign1, SrcTBAAInfo1);
Richard Sandiforda7be36c2013-10-28 12:00:00 +000011403 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
Nadav Rotemdde785c2012-12-06 17:34:13 +000011404 SrcValueAlign0, SrcTBAAInfo0,
Richard Sandiforda7be36c2013-10-28 12:00:00 +000011405 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
Nadav Rotemdde785c2012-12-06 17:34:13 +000011406 SrcValueAlign1, SrcTBAAInfo1);
Nadav Rotem90e11dc2012-11-29 00:00:08 +000011407}
11408
Jim Laskey71382342006-10-07 23:37:56 +000011409/// FindAliasInfo - Extracts the relevant alias information from the memory
Richard Sandiforda7be36c2013-10-28 12:00:00 +000011410/// node. Returns true if the operand was a nonvolatile load.
Jim Laskey7ca56af2006-10-11 13:47:09 +000011411bool DAGCombiner::FindAliasInfo(SDNode *N,
Richard Sandiforda7be36c2013-10-28 12:00:00 +000011412 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
Benjamin Kramerae4746b2012-01-15 11:50:43 +000011413 const Value *&SrcValue,
11414 int &SrcValueOffset,
11415 unsigned &SrcValueAlign,
11416 const MDNode *&TBAAInfo) const {
11417 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11418
11419 Ptr = LS->getBasePtr();
11420 Size = LS->getMemoryVT().getSizeInBits() >> 3;
Richard Sandiforda7be36c2013-10-28 12:00:00 +000011421 IsVolatile = LS->isVolatile();
Benjamin Kramerae4746b2012-01-15 11:50:43 +000011422 SrcValue = LS->getSrcValue();
11423 SrcValueOffset = LS->getSrcValueOffset();
11424 SrcValueAlign = LS->getOriginalAlignment();
11425 TBAAInfo = LS->getTBAAInfo();
Richard Sandiforda7be36c2013-10-28 12:00:00 +000011426 return isa<LoadSDNode>(LS) && !IsVolatile;
Jim Laskey71382342006-10-07 23:37:56 +000011427}
11428
Jim Laskey6ff23e52006-10-04 16:53:27 +000011429/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11430/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman475871a2008-07-27 21:46:04 +000011431void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Toppera0ec3f92013-07-14 04:42:23 +000011432 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman475871a2008-07-27 21:46:04 +000011433 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begemanb6aef5c2009-09-15 00:18:30 +000011434 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelfdc40a02009-02-17 22:15:04 +000011435
Jim Laskey279f0532006-09-25 16:29:54 +000011436 // Get alias information for node.
Dan Gohman475871a2008-07-27 21:46:04 +000011437 SDValue Ptr;
Nate Begemanb6aef5c2009-09-15 00:18:30 +000011438 int64_t Size;
Richard Sandiforda7be36c2013-10-28 12:00:00 +000011439 bool IsVolatile;
Nate Begemanb6aef5c2009-09-15 00:18:30 +000011440 const Value *SrcValue;
11441 int SrcValueOffset;
11442 unsigned SrcValueAlign;
Dan Gohmanf96e4bd2010-10-20 00:31:05 +000011443 const MDNode *SrcTBAAInfo;
Richard Sandiforda7be36c2013-10-28 12:00:00 +000011444 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11445 SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
Jim Laskey279f0532006-09-25 16:29:54 +000011446
Jim Laskey6ff23e52006-10-04 16:53:27 +000011447 // Starting off.
Jim Laskeybc588b82006-10-05 15:07:25 +000011448 Chains.push_back(OriginalChain);
Nate Begeman677c89d2009-10-12 05:53:58 +000011449 unsigned Depth = 0;
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011450
Jim Laskeybc588b82006-10-05 15:07:25 +000011451 // Look at each chain and determine if it is an alias. If so, add it to the
11452 // aliases list. If not, then continue up the chain looking for the next
Scott Michelfdc40a02009-02-17 22:15:04 +000011453 // candidate.
Jim Laskeybc588b82006-10-05 15:07:25 +000011454 while (!Chains.empty()) {
Dan Gohman475871a2008-07-27 21:46:04 +000011455 SDValue Chain = Chains.back();
Jim Laskeybc588b82006-10-05 15:07:25 +000011456 Chains.pop_back();
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011457
11458 // For TokenFactor nodes, look at each operand and only continue up the
11459 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begeman677c89d2009-10-12 05:53:58 +000011460 // find more and revert to original chain since the xform is unlikely to be
11461 // profitable.
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011462 //
11463 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begeman677c89d2009-10-12 05:53:58 +000011464 // chain we found before we hit a tokenfactor rather than the original
11465 // chain.
11466 if (Depth > 6 || Aliases.size() == 2) {
11467 Aliases.clear();
11468 Aliases.push_back(OriginalChain);
Stephen Hines36b56882014-04-23 16:57:46 -070011469 return;
Nate Begeman677c89d2009-10-12 05:53:58 +000011470 }
Scott Michelfdc40a02009-02-17 22:15:04 +000011471
Nate Begemanb6aef5c2009-09-15 00:18:30 +000011472 // Don't bother if we've been before.
11473 if (!Visited.insert(Chain.getNode()))
11474 continue;
Scott Michelfdc40a02009-02-17 22:15:04 +000011475
Jim Laskeybc588b82006-10-05 15:07:25 +000011476 switch (Chain.getOpcode()) {
11477 case ISD::EntryToken:
11478 // Entry token is ideal chain operand, but handled in FindBetterChain.
11479 break;
Scott Michelfdc40a02009-02-17 22:15:04 +000011480
Jim Laskeybc588b82006-10-05 15:07:25 +000011481 case ISD::LOAD:
11482 case ISD::STORE: {
11483 // Get alias information for Chain.
Dan Gohman475871a2008-07-27 21:46:04 +000011484 SDValue OpPtr;
Nate Begemanb6aef5c2009-09-15 00:18:30 +000011485 int64_t OpSize;
Richard Sandiforda7be36c2013-10-28 12:00:00 +000011486 bool OpIsVolatile;
Nate Begemanb6aef5c2009-09-15 00:18:30 +000011487 const Value *OpSrcValue;
11488 int OpSrcValueOffset;
11489 unsigned OpSrcValueAlign;
Dan Gohmanf96e4bd2010-10-20 00:31:05 +000011490 const MDNode *OpSrcTBAAInfo;
Gabor Greifba36cb52008-08-28 21:40:38 +000011491 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
Richard Sandiforda7be36c2013-10-28 12:00:00 +000011492 OpIsVolatile, OpSrcValue, OpSrcValueOffset,
Dan Gohmanf96e4bd2010-10-20 00:31:05 +000011493 OpSrcValueAlign,
11494 OpSrcTBAAInfo);
Scott Michelfdc40a02009-02-17 22:15:04 +000011495
Jim Laskeybc588b82006-10-05 15:07:25 +000011496 // If chain is alias then stop here.
11497 if (!(IsLoad && IsOpLoad) &&
Richard Sandiforda7be36c2013-10-28 12:00:00 +000011498 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11499 SrcValueAlign, SrcTBAAInfo,
11500 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
Dan Gohmanf96e4bd2010-10-20 00:31:05 +000011501 OpSrcValueAlign, OpSrcTBAAInfo)) {
Jim Laskeybc588b82006-10-05 15:07:25 +000011502 Aliases.push_back(Chain);
11503 } else {
11504 // Look further up the chain.
Scott Michelfdc40a02009-02-17 22:15:04 +000011505 Chains.push_back(Chain.getOperand(0));
Nate Begeman677c89d2009-10-12 05:53:58 +000011506 ++Depth;
Jim Laskey279f0532006-09-25 16:29:54 +000011507 }
Jim Laskeybc588b82006-10-05 15:07:25 +000011508 break;
11509 }
Scott Michelfdc40a02009-02-17 22:15:04 +000011510
Jim Laskeybc588b82006-10-05 15:07:25 +000011511 case ISD::TokenFactor:
Nate Begemanb6aef5c2009-09-15 00:18:30 +000011512 // We have to check each of the operands of the token factor for "small"
11513 // token factors, so we queue them up. Adding the operands to the queue
11514 // (stack) in reverse order maintains the original order and increases the
11515 // likelihood that getNode will find a matching token factor (CSE.)
11516 if (Chain.getNumOperands() > 16) {
11517 Aliases.push_back(Chain);
11518 break;
11519 }
Jim Laskeybc588b82006-10-05 15:07:25 +000011520 for (unsigned n = Chain.getNumOperands(); n;)
11521 Chains.push_back(Chain.getOperand(--n));
Nate Begeman677c89d2009-10-12 05:53:58 +000011522 ++Depth;
Jim Laskeybc588b82006-10-05 15:07:25 +000011523 break;
Scott Michelfdc40a02009-02-17 22:15:04 +000011524
Jim Laskeybc588b82006-10-05 15:07:25 +000011525 default:
11526 // For all other instructions we will just have to take what we can get.
11527 Aliases.push_back(Chain);
11528 break;
Jim Laskey279f0532006-09-25 16:29:54 +000011529 }
11530 }
Stephen Hines36b56882014-04-23 16:57:46 -070011531
11532 // We need to be careful here to also search for aliases through the
11533 // value operand of a store, etc. Consider the following situation:
11534 // Token1 = ...
11535 // L1 = load Token1, %52
11536 // S1 = store Token1, L1, %51
11537 // L2 = load Token1, %52+8
11538 // S2 = store Token1, L2, %51+8
11539 // Token2 = Token(S1, S2)
11540 // L3 = load Token2, %53
11541 // S3 = store Token2, L3, %52
11542 // L4 = load Token2, %53+8
11543 // S4 = store Token2, L4, %52+8
11544 // If we search for aliases of S3 (which loads address %52), and we look
11545 // only through the chain, then we'll miss the trivial dependence on L1
11546 // (which also loads from %52). We then might change all loads and
11547 // stores to use Token1 as their chain operand, which could result in
11548 // copying %53 into %52 before copying %52 into %51 (which should
11549 // happen first).
11550 //
11551 // The problem is, however, that searching for such data dependencies
11552 // can become expensive, and the cost is not directly related to the
11553 // chain depth. Instead, we'll rule out such configurations here by
11554 // insisting that we've visited all chain users (except for users
11555 // of the original chain, which is not necessary). When doing this,
11556 // we need to look through nodes we don't care about (otherwise, things
11557 // like register copies will interfere with trivial cases).
11558
11559 SmallVector<const SDNode *, 16> Worklist;
11560 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11561 IE = Visited.end(); I != IE; ++I)
11562 if (*I != OriginalChain.getNode())
11563 Worklist.push_back(*I);
11564
11565 while (!Worklist.empty()) {
11566 const SDNode *M = Worklist.pop_back_val();
11567
11568 // We have already visited M, and want to make sure we've visited any uses
11569 // of M that we care about. For uses that we've not visisted, and don't
11570 // care about, queue them to the worklist.
11571
11572 for (SDNode::use_iterator UI = M->use_begin(),
11573 UIE = M->use_end(); UI != UIE; ++UI)
11574 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11575 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11576 // We've not visited this use, and we care about it (it could have an
11577 // ordering dependency with the original node).
11578 Aliases.clear();
11579 Aliases.push_back(OriginalChain);
11580 return;
11581 }
11582
11583 // We've not visited this use, but we don't care about it. Mark it as
11584 // visited and enqueue it to the worklist.
11585 Worklist.push_back(*UI);
11586 }
11587 }
Jim Laskey6ff23e52006-10-04 16:53:27 +000011588}
11589
11590/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11591/// for a better chain (aliasing node.)
Dan Gohman475871a2008-07-27 21:46:04 +000011592SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11593 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelfdc40a02009-02-17 22:15:04 +000011594
Jim Laskey6ff23e52006-10-04 16:53:27 +000011595 // Accumulate all the aliases to this node.
11596 GatherAllAliases(N, OldChain, Aliases);
Scott Michelfdc40a02009-02-17 22:15:04 +000011597
Dan Gohman71dc7c92011-05-17 22:20:36 +000011598 // If no operands then chain to entry token.
11599 if (Aliases.size() == 0)
Jim Laskey6ff23e52006-10-04 16:53:27 +000011600 return DAG.getEntryNode();
Dan Gohman71dc7c92011-05-17 22:20:36 +000011601
11602 // If a single operand then chain to it. We don't need to revisit it.
11603 if (Aliases.size() == 1)
Jim Laskey6ff23e52006-10-04 16:53:27 +000011604 return Aliases[0];
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011605
Jim Laskey6ff23e52006-10-04 16:53:27 +000011606 // Construct a custom tailored token factor.
Andrew Trickac6d9be2013-05-25 02:42:55 +000011607 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Nate Begemanb6aef5c2009-09-15 00:18:30 +000011608 &Aliases[0], Aliases.size());
Jim Laskey279f0532006-09-25 16:29:54 +000011609}
11610
Nate Begeman1d4d4142005-09-01 00:19:25 +000011611// SelectionDAG::Combine - This is the entry point for the file.
11612//
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +000011613void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling98a366d2009-04-29 23:29:43 +000011614 CodeGenOpt::Level OptLevel) {
Nate Begeman1d4d4142005-09-01 00:19:25 +000011615 /// run - This is the main entry point to this class.
11616 ///
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +000011617 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman1d4d4142005-09-01 00:19:25 +000011618}