blob: 8650154c1a90358a7560ece2f5d128da2c652bd1 [file] [log] [blame]
Nate Begeman2504fe22005-09-01 23:24:04 +00001//===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
Nate Begeman21158fc2005-09-01 00:19:25 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Begeman21158fc2005-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 Michelcf0da6c2009-02-17 22:15:04 +000012//
Dan Gohman45399872009-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 Begeman21158fc2005-09-01 00:19:25 +000017//===----------------------------------------------------------------------===//
18
19#define DEBUG_TYPE "dagcombine"
Nate Begeman21158fc2005-09-01 00:19:25 +000020#include "llvm/CodeGen/SelectionDAG.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000021#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth9fb823b2013-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 Laskey5d19d592006-09-21 16:28:59 +000030#include "llvm/Support/CommandLine.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000031#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000032#include "llvm/Support/ErrorHandling.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000033#include "llvm/Support/MathExtras.h"
Chris Lattner4dc3edd2009-08-23 06:35:02 +000034#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Target/TargetLowering.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetOptions.h"
Quentin Colombetde0e0622013-10-11 18:29:42 +000038#include "llvm/Target/TargetRegisterInfo.h"
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000039#include "llvm/Target/TargetSubtargetInfo.h"
Chris Lattnerbd39c1a2005-09-09 23:53:39 +000040#include <algorithm>
Nate Begeman21158fc2005-09-01 00:19:25 +000041using namespace llvm;
42
Chris Lattneraee775a2006-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 Chenga9cda8a2009-05-28 00:35:15 +000046STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
Evan Chengd42641c2011-02-02 01:06:55 +000047STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
Quentin Colombetde0e0622013-10-11 18:29:42 +000048STATISTIC(SlicedLoads, "Number of load sliced");
Chris Lattneraee775a2006-12-19 22:41:21 +000049
Nate Begeman21158fc2005-09-01 00:19:25 +000050namespace {
Jim Laskey0463e082006-10-07 23:37:56 +000051 static cl::opt<bool>
Owen Anderson7b8d2ae2010-09-19 21:01:26 +000052 CombinerAA("combiner-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000053 cl::desc("Enable DAG combiner alias-analysis heuristics"));
Jim Laskeydf2ccc32006-10-12 15:22:24 +000054
Jim Laskey55e4dca2006-10-18 19:08:31 +000055 static cl::opt<bool>
56 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000057 cl::desc("Enable DAG combiner's use of IR alias analysis"));
Jim Laskey55e4dca2006-10-18 19:08:31 +000058
Hal Finkeldbebb522014-01-25 19:24:54 +000059// 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
Hal Finkel9b2617a2014-01-25 17:32:39 +000069#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
75
Quentin Colombetde0e0622013-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 Laskey6549d222006-10-05 15:07:25 +000084//------------------------------ DAGCombiner ---------------------------------//
85
Nick Lewycky02d5f772009-10-25 06:33:48 +000086 class DAGCombiner {
Nate Begeman21158fc2005-09-01 00:19:25 +000087 SelectionDAG &DAG;
Dan Gohman619ef482009-01-15 19:20:50 +000088 const TargetLowering &TLI;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000089 CombineLevel Level;
Bill Wendling026e5d72009-04-29 23:29:43 +000090 CodeGenOpt::Level OptLevel;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000091 bool LegalOperations;
92 bool LegalTypes;
Quentin Colombetde0e0622013-10-11 18:29:42 +000093 bool ForCodeSize;
Nate Begeman21158fc2005-09-01 00:19:25 +000094
95 // Worklist of all of the nodes that need to be simplified.
James Molloy67b6b112012-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 Kramere1e549d2012-03-10 00:23:58 +0000113 SmallVector<SDNode*, 64> WorkListOrder;
Nate Begeman21158fc2005-09-01 00:19:25 +0000114
Jim Laskeydcb2b832006-10-16 20:52:31 +0000115 // AA - Used for DAG load/store alias analysis.
116 AliasAnalysis &AA;
117
Nate Begeman21158fc2005-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 Begeman2504fe22005-09-01 23:24:04 +0000124 UI != UE; ++UI)
Dan Gohman91e5dcb2008-07-27 20:43:25 +0000125 AddToWorkList(*UI);
Nate Begeman21158fc2005-09-01 00:19:25 +0000126 }
127
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000128 /// visit - call the node-specific routine that knows how to fold each
129 /// particular type of node.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000130 SDValue visit(SDNode *N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000131
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000132 public:
James Molloy920ae8c2012-02-16 09:48:07 +0000133 /// AddToWorkList - Add to the work list making sure its instance is at the
James Molloy67b6b112012-02-16 09:17:04 +0000134 /// back (next to be processed.)
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000135 void AddToWorkList(SDNode *N) {
James Molloy67b6b112012-02-16 09:17:04 +0000136 WorkListContents.insert(N);
137 WorkListOrder.push_back(N);
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000138 }
Jim Laskey708d0db2006-10-04 16:53:27 +0000139
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000140 /// removeFromWorkList - remove all instances of N from the worklist.
141 ///
142 void removeFromWorkList(SDNode *N) {
James Molloy67b6b112012-02-16 09:17:04 +0000143 WorkListContents.erase(N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000144 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000145
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000146 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
Evan Chengfd81c732009-03-28 05:57:29 +0000147 bool AddTo = true);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000148
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000149 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
Jim Laskeydcf983c2006-10-13 23:32:28 +0000150 return CombineTo(N, &Res, 1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000151 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000152
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000153 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
Evan Chengfd81c732009-03-28 05:57:29 +0000154 bool AddTo = true) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000155 SDValue To[] = { Res0, Res1 };
Jim Laskeydcf983c2006-10-13 23:32:28 +0000156 return CombineTo(N, To, 2, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000157 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000158
159 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000160
161 private:
162
Chris Lattner375e1a72006-02-17 21:58:01 +0000163 /// SimplifyDemandedBits - Check the specified integer node value to see if
Chris Lattner232024e2006-03-01 19:55:35 +0000164 /// it can be simplified or if things it uses can be simplified by bit
Chris Lattner375e1a72006-02-17 21:58:01 +0000165 /// propagation. If so, return true.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000166 bool SimplifyDemandedBits(SDValue Op) {
Dan Gohman1d459e42009-12-11 21:31:27 +0000167 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
168 APInt Demanded = APInt::getAllOnesValue(BitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000169 return SimplifyDemandedBits(Op, Demanded);
170 }
171
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000172 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
Chris Lattner04c73702005-10-10 22:31:19 +0000173
Chris Lattnerffad2162006-11-11 00:39:41 +0000174 bool CombineToPreIndexedLoadStore(SDNode *N);
175 bool CombineToPostIndexedLoadStore(SDNode *N);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000176 bool SliceUpLoad(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000177
Evan Cheng0abb54d2010-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 Chengaf56fac2010-04-16 06:14:10 +0000182 SDValue PromoteIntBinOp(SDValue Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000183 SDValue PromoteIntShiftOp(SDValue Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +0000184 SDValue PromoteExtend(SDValue Op);
185 bool PromoteLoad(SDValue Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000186
Craig Toppere0b71182013-07-13 07:43:40 +0000187 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000188 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +0000189 ISD::NodeType ExtType);
190
Dan Gohman5c6d0c32007-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 Gohman2ce6f2a2008-07-27 21:46:04 +0000194 SDValue combine(SDNode *N);
Nate Begeman21158fc2005-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 Cheng5e7658c2008-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 Begeman21158fc2005-09-01 00:19:25 +0000202 //
Dan Gohman2ce6f2a2008-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 Topper43a1bd62012-01-07 09:06:39 +0000208 SDValue visitSUBC(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000209 SDValue visitADDE(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000210 SDValue visitSUBE(SDNode *N);
Dan Gohman2ce6f2a2008-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 Kramer2fd48f22011-05-21 18:31:55 +0000220 SDValue visitSMULO(SDNode *N);
221 SDValue visitUMULO(SDNode *N);
Dan Gohman2ce6f2a2008-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 Topper82384612012-09-11 01:45:21 +0000228 SDValue SimplifyVUnaryOp(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000229 SDValue visitSHL(SDNode *N);
230 SDValue visitSRA(SDNode *N);
231 SDValue visitSRL(SDNode *N);
232 SDValue visitCTLZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000233 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000234 SDValue visitCTTZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000235 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000236 SDValue visitCTPOP(SDNode *N);
237 SDValue visitSELECT(SDNode *N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +0000238 SDValue visitVSELECT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000239 SDValue visitSELECT_CC(SDNode *N);
240 SDValue visitSETCC(SDNode *N);
241 SDValue visitSIGN_EXTEND(SDNode *N);
242 SDValue visitZERO_EXTEND(SDNode *N);
243 SDValue visitANY_EXTEND(SDNode *N);
244 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
245 SDValue visitTRUNCATE(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000246 SDValue visitBITCAST(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000247 SDValue visitBUILD_PAIR(SDNode *N);
248 SDValue visitFADD(SDNode *N);
249 SDValue visitFSUB(SDNode *N);
250 SDValue visitFMUL(SDNode *N);
Owen Anderson41b06652012-05-02 22:17:40 +0000251 SDValue visitFMA(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000252 SDValue visitFDIV(SDNode *N);
253 SDValue visitFREM(SDNode *N);
254 SDValue visitFCOPYSIGN(SDNode *N);
255 SDValue visitSINT_TO_FP(SDNode *N);
256 SDValue visitUINT_TO_FP(SDNode *N);
257 SDValue visitFP_TO_SINT(SDNode *N);
258 SDValue visitFP_TO_UINT(SDNode *N);
259 SDValue visitFP_ROUND(SDNode *N);
260 SDValue visitFP_ROUND_INREG(SDNode *N);
261 SDValue visitFP_EXTEND(SDNode *N);
262 SDValue visitFNEG(SDNode *N);
263 SDValue visitFABS(SDNode *N);
Owen Andersona40319b2012-08-13 23:32:49 +0000264 SDValue visitFCEIL(SDNode *N);
265 SDValue visitFTRUNC(SDNode *N);
266 SDValue visitFFLOOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000267 SDValue visitBRCOND(SDNode *N);
268 SDValue visitBR_CC(SDNode *N);
269 SDValue visitLOAD(SDNode *N);
270 SDValue visitSTORE(SDNode *N);
271 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
272 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
273 SDValue visitBUILD_VECTOR(SDNode *N);
274 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +0000275 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000276 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Manman Ren413a6cb2014-01-31 01:10:35 +0000277 SDValue visitINSERT_SUBVECTOR(SDNode *N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000278
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000279 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000280 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000281
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000282 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
Chris Lattner7c709a52007-12-06 07:33:36 +0000283
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000284 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
285 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000286 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
287 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelcf0da6c2009-02-17 22:15:04 +0000288 SDValue N3, ISD::CondCode CC,
Bill Wendling31b50992009-01-30 23:59:18 +0000289 bool NotExtCompare = false);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000290 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000291 SDLoc DL, bool foldBooleans = true);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000292 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner31e9edc2008-01-26 01:09:19 +0000293 unsigned HiOp);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000294 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000295 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000296 SDValue BuildSDIV(SDNode *N);
297 SDValue BuildUDIV(SDNode *N);
Evan Cheng4c0bd962011-06-21 06:01:08 +0000298 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
299 bool DemandHighBits = true);
300 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Richard Sandiford95c864d2014-01-08 15:40:47 +0000301 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
302 SDValue InnerPos, SDValue InnerNeg,
303 unsigned PosOpcode, unsigned NegOpcode,
304 SDLoc DL);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000305 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000306 SDValue ReduceLoadWidth(SDNode *N);
Evan Chenga9cda8a2009-05-28 00:35:15 +0000307 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Chengd42641c2011-02-02 01:06:55 +0000308 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liao6d106b72012-10-23 23:06:52 +0000309 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao59229792012-10-24 04:14:18 +0000310 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000311
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000312 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000313
Jim Laskey708d0db2006-10-04 16:53:27 +0000314 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
315 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000316 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +0000317 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey708d0db2006-10-04 16:53:27 +0000318
Jim Laskeya15b0eb2006-10-18 12:29:57 +0000319 /// isAlias - Return true if there is any possibility that the two addresses
320 /// overlap.
Richard Sandiford981fdeb2013-10-28 12:00:00 +0000321 bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
Jim Laskeya15b0eb2006-10-18 12:29:57 +0000322 const Value *SrcValue1, int SrcValueOffset1,
Nate Begeman879d8f12009-09-15 00:18:30 +0000323 unsigned SrcValueAlign1,
Dan Gohmana94cc6d2010-10-20 00:31:05 +0000324 const MDNode *TBAAInfo1,
Richard Sandiford981fdeb2013-10-28 12:00:00 +0000325 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
Nate Begeman879d8f12009-09-15 00:18:30 +0000326 const Value *SrcValue2, int SrcValueOffset2,
Dan Gohmana94cc6d2010-10-20 00:31:05 +0000327 unsigned SrcValueAlign2,
328 const MDNode *TBAAInfo2) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000329
Nadav Rotem307d7672012-11-29 00:00:08 +0000330 /// isAlias - Return true if there is any possibility that the two addresses
331 /// overlap.
332 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
333
Jim Laskey08edf332006-10-11 13:47:09 +0000334 /// FindAliasInfo - Extracts the relevant alias information from the memory
335 /// node. Returns true if the operand was a load.
336 bool FindAliasInfo(SDNode *N,
Richard Sandiford981fdeb2013-10-28 12:00:00 +0000337 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
Nate Begeman879d8f12009-09-15 00:18:30 +0000338 const Value *&SrcValue, int &SrcValueOffset,
Dan Gohmana94cc6d2010-10-20 00:31:05 +0000339 unsigned &SrcValueAlignment,
340 const MDNode *&TBAAInfo) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000341
Jim Laskeyd07be232006-09-25 16:29:54 +0000342 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +0000343 /// looking for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000344 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands41826032009-01-31 15:50:11 +0000345
Nadav Rotem7cbc12a2012-10-03 16:11:15 +0000346 /// Merge consecutive store operations into a wide store.
347 /// This optimization uses wide integers or vectors when possible.
348 /// \return True if some memory operations were changed.
349 bool MergeConsecutiveStores(StoreSDNode *N);
350
Adam Nemet67483892014-03-04 23:28:31 +0000351 /// \brief Try to transform a truncation where C is a constant:
352 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
353 ///
354 /// \p N needs to be a truncation and its first operand an AND. Other
355 /// requirements are checked by the function (e.g. that trunc is
356 /// single-use) and if missed an empty SDValue is returned.
357 SDValue distributeTruncateThroughAnd(SDNode *N);
358
Chris Lattner4041ab62010-04-15 04:48:01 +0000359 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000360 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombetde0e0622013-10-11 18:29:42 +0000361 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
362 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
363 AttributeSet FnAttrs =
364 DAG.getMachineFunction().getFunction()->getAttributes();
365 ForCodeSize =
366 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
367 Attribute::OptimizeForSize) ||
368 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
369 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000370
Nate Begeman21158fc2005-09-01 00:19:25 +0000371 /// Run - runs the dag combiner on all nodes in the work list
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000372 void Run(CombineLevel AtLevel);
Wesley Peck527da1b2010-11-23 03:31:01 +0000373
Chris Lattner4041ab62010-04-15 04:48:01 +0000374 SelectionDAG &getDAG() const { return DAG; }
Wesley Peck527da1b2010-11-23 03:31:01 +0000375
Chris Lattner4041ab62010-04-15 04:48:01 +0000376 /// getShiftAmountTy - Returns a type large enough to hold any valid
377 /// shift amount - before type legalization these can be huge.
Owen Andersonb2c80da2011-02-25 21:41:48 +0000378 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +0000379 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
380 if (LHSTy.isVector())
381 return LHSTy;
Jack Carterd4e96152013-10-17 01:34:33 +0000382 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
383 : TLI.getPointerTy();
Chris Lattner4041ab62010-04-15 04:48:01 +0000384 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000385
Chris Lattner4041ab62010-04-15 04:48:01 +0000386 /// isTypeLegal - This method returns true if we are running before type
387 /// legalization or if the specified VT is legal.
388 bool isTypeLegal(const EVT &VT) {
389 if (!LegalTypes) return true;
390 return TLI.isTypeLegal(VT);
391 }
Matt Arsenault758659232013-05-18 00:21:46 +0000392
393 /// getSetCCResultType - Convenience wrapper around
394 /// TargetLowering::getSetCCResultType
395 EVT getSetCCResultType(EVT VT) const {
396 return TLI.getSetCCResultType(*DAG.getContext(), VT);
397 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000398 };
399}
400
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000401
402namespace {
403/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
404/// nodes from the worklist.
Nick Lewycky02d5f772009-10-25 06:33:48 +0000405class WorkListRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000406 DAGCombiner &DC;
407public:
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000408 explicit WorkListRemover(DAGCombiner &dc)
409 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000410
Duncan Sandsbf170802008-06-11 11:42:12 +0000411 virtual void NodeDeleted(SDNode *N, SDNode *E) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000412 DC.removeFromWorkList(N);
413 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000414};
415}
416
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000417//===----------------------------------------------------------------------===//
418// TargetLowering::DAGCombinerInfo implementation
419//===----------------------------------------------------------------------===//
420
421void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
422 ((DAGCombiner*)DC)->AddToWorkList(N);
423}
424
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000425void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
426 ((DAGCombiner*)DC)->removeFromWorkList(N);
427}
428
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000429SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000430CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
431 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000432}
433
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000434SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000435CombineTo(SDNode *N, SDValue Res, bool AddTo) {
436 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000437}
438
439
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000440SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000441CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
442 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000443}
444
Dan Gohmane58ab792009-01-29 01:59:02 +0000445void TargetLowering::DAGCombinerInfo::
446CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
447 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
448}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000449
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000450//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000451// Helper Functions
452//===----------------------------------------------------------------------===//
453
454/// isNegatibleForFree - Return 1 if we can compute the negated form of the
455/// specified expression for the same cost as the expression itself, or 2 if we
456/// can compute the negated form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000457static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000458 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000459 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000460 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000461 // fneg is removable even if it has multiple uses.
462 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000463
Chris Lattnere49c9742007-05-14 22:04:50 +0000464 // Don't allow anything with multiple uses.
465 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000466
Chris Lattner46980832007-05-25 02:19:06 +0000467 // Don't recurse exponentially.
468 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000469
Chris Lattnere49c9742007-05-14 22:04:50 +0000470 switch (Op.getOpcode()) {
471 default: return false;
472 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000473 // Don't invert constant FP values after legalize. The negated constant
474 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000475 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000476 case ISD::FADD:
477 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000478 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000479
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000480 // After operation legalization, it might not be legal to create new FSUBs.
481 if (LegalOperations &&
482 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
483 return 0;
484
Craig Topper03f39772012-09-09 22:58:45 +0000485 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000486 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
487 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000488 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000489 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000490 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000491 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000492 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000493 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000494 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000495
Bill Wendling6fbf5492009-01-30 23:10:18 +0000496 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000497 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000498
Chris Lattnere49c9742007-05-14 22:04:50 +0000499 case ISD::FMUL:
500 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000501 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000502
Bill Wendling6fbf5492009-01-30 23:10:18 +0000503 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000504 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
505 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000506 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000507
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000508 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000509 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000510
Chris Lattnere49c9742007-05-14 22:04:50 +0000511 case ISD::FP_EXTEND:
512 case ISD::FP_ROUND:
513 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000514 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000515 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000516 }
517}
518
519/// GetNegatedExpression - If isNegatibleForFree returns true, this function
520/// returns the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000521static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000522 bool LegalOperations, unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000523 // fneg is removable even if it has multiple uses.
524 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000525
Chris Lattnere49c9742007-05-14 22:04:50 +0000526 // Don't allow anything with multiple uses.
527 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000528
Chris Lattner46980832007-05-25 02:19:06 +0000529 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000530 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000531 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000532 case ISD::ConstantFP: {
533 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
534 V.changeSign();
535 return DAG.getConstantFP(V, Op.getValueType());
536 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000537 case ISD::FADD:
538 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000539 assert(DAG.getTarget().Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000540
Bill Wendling6fbf5492009-01-30 23:10:18 +0000541 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000542 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000543 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000544 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000545 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000546 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000547 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000548 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000549 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000550 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000551 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000552 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000553 Op.getOperand(0));
554 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000555 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000556 assert(DAG.getTarget().Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000557
Bill Wendling6fbf5492009-01-30 23:10:18 +0000558 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000559 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen446b9002007-08-31 23:34:27 +0000560 if (N0CFP->getValueAPF().isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000561 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000562
Bill Wendling6fbf5492009-01-30 23:10:18 +0000563 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000564 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000565 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000566
Chris Lattnere49c9742007-05-14 22:04:50 +0000567 case ISD::FMUL:
568 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000569 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000570
Bill Wendling6fbf5492009-01-30 23:10:18 +0000571 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000572 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000573 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000574 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000575 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000576 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000577 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000578 Op.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000579
Bill Wendling6fbf5492009-01-30 23:10:18 +0000580 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000581 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattnere49c9742007-05-14 22:04:50 +0000582 Op.getOperand(0),
Chris Lattnere7c14012008-02-26 07:04:54 +0000583 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000584 LegalOperations, Depth+1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000585
Chris Lattnere49c9742007-05-14 22:04:50 +0000586 case ISD::FP_EXTEND:
Chris Lattnere49c9742007-05-14 22:04:50 +0000587 case ISD::FSIN:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000588 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000589 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000590 LegalOperations, Depth+1));
Chris Lattner72733e52008-01-17 07:00:52 +0000591 case ISD::FP_ROUND:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000592 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000593 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000594 LegalOperations, Depth+1),
Chris Lattner72733e52008-01-17 07:00:52 +0000595 Op.getOperand(1));
Chris Lattnere49c9742007-05-14 22:04:50 +0000596 }
597}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000598
599
Nate Begeman2504fe22005-09-01 23:24:04 +0000600// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
601// that selects between the values 1 and 0, making it equivalent to a setcc.
Scott Michelcf0da6c2009-02-17 22:15:04 +0000602// Also, set the incoming LHS, RHS, and CC references to the appropriate
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000603// nodes based on the type of node we are checking. This simplifies life a
604// bit for the callers.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000605static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
606 SDValue &CC) {
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000607 if (N.getOpcode() == ISD::SETCC) {
608 LHS = N.getOperand(0);
609 RHS = N.getOperand(1);
610 CC = N.getOperand(2);
Nate Begeman2504fe22005-09-01 23:24:04 +0000611 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000612 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000613 if (N.getOpcode() == ISD::SELECT_CC &&
Nate Begeman21158fc2005-09-01 00:19:25 +0000614 N.getOperand(2).getOpcode() == ISD::Constant &&
615 N.getOperand(3).getOpcode() == ISD::Constant &&
Dan Gohmanb72127a2008-03-13 22:13:53 +0000616 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000617 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
618 LHS = N.getOperand(0);
619 RHS = N.getOperand(1);
620 CC = N.getOperand(4);
Nate Begeman21158fc2005-09-01 00:19:25 +0000621 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000622 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000623 return false;
624}
625
Nate Begeman2cc2c9a2005-09-07 23:25:52 +0000626// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
627// one use. If this is true, it allows the users to invert the operation for
628// free when it is profitable to do so.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000629static bool isOneUseSetCC(SDValue N) {
630 SDValue N0, N1, N2;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000631 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman2504fe22005-09-01 23:24:04 +0000632 return true;
633 return false;
634}
635
Juergen Ributzka68402822014-01-13 21:49:25 +0000636// \brief Returns the SDNode if it is a constant BuildVector or constant int.
637static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
638 if (isa<ConstantSDNode>(N))
639 return N.getNode();
640 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
641 if(BV && BV->isConstant())
642 return BV;
643 return NULL;
644}
645
Andrew Trickef9de2a2013-05-25 02:42:55 +0000646SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000647 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000648 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000649 if (N0.getOpcode() == Opc) {
650 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
651 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
652 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
653 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
654 if (!OpNode.getNode())
655 return SDValue();
656 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
Juergen Ributzka73844052014-01-13 20:51:35 +0000657 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000658 if (N0.hasOneUse()) {
659 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
660 // use
661 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
662 if (!OpNode.getNode())
663 return SDValue();
664 AddToWorkList(OpNode.getNode());
665 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000666 }
667 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000668 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000669
Juergen Ributzka68402822014-01-13 21:49:25 +0000670 if (N1.getOpcode() == Opc) {
671 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
672 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
673 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
674 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
675 if (!OpNode.getNode())
676 return SDValue();
677 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
678 }
679 if (N1.hasOneUse()) {
680 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
681 // use
682 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
683 if (!OpNode.getNode())
684 return SDValue();
685 AddToWorkList(OpNode.getNode());
686 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
687 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000688 }
689 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000690
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000691 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000692}
693
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000694SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
695 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000696 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
697 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000698 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000699 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000700 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000701 To[0].getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000702 dbgs() << " and " << NumTo-1 << " other values\n";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000703 for (unsigned i = 0, e = NumTo; i != e; ++i)
Jakob Stoklund Olesen32042f92009-12-03 05:15:35 +0000704 assert((!To[i].getNode() ||
705 N->getValueType(i) == To[i].getValueType()) &&
Dan Gohman7e6b9322009-01-21 15:17:51 +0000706 "Cannot combine value to value of different type!"));
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000707 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000708 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000709 if (AddTo) {
710 // Push the new nodes and any users onto the worklist
711 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000712 if (To[i].getNode()) {
713 AddToWorkList(To[i].getNode());
714 AddUsersToWorkList(To[i].getNode());
715 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000716 }
717 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000718
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000719 // Finally, if the node is now dead, remove it from the graph. The node
720 // may not be dead if the replacement process recursively simplified to
721 // something else needing this node.
722 if (N->use_empty()) {
723 // Nodes can be reintroduced into the worklist. Make sure we do not
724 // process a node that has been replaced.
725 removeFromWorkList(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000726
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000727 // Finally, since the node is now dead, remove it from the graph.
728 DAG.DeleteNode(N);
729 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000730 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000731}
732
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000733void DAGCombiner::
734CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000735 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000736 // are deleted, make sure to remove them from our worklist.
737 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000738 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000739
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000740 // Push the new node and any (possibly new) users onto the worklist.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000741 AddToWorkList(TLO.New.getNode());
742 AddUsersToWorkList(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000743
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000744 // Finally, if the node is now dead, remove it from the graph. The node
745 // may not be dead if the replacement process recursively simplified to
746 // something else needing this node.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000747 if (TLO.Old.getNode()->use_empty()) {
748 removeFromWorkList(TLO.Old.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000749
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000750 // If the operands of this node are only used by the node, they will now
751 // be dead. Make sure to visit them first to delete dead nodes early.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000752 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
753 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
754 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000755
Gabor Greiff304a7a2008-08-28 21:40:38 +0000756 DAG.DeleteNode(TLO.Old.getNode());
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000757 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000758}
759
760/// SimplifyDemandedBits - Check the specified integer node value to see if
761/// it can be simplified or if things it uses can be simplified by bit
762/// propagation. If so, return true.
763bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000764 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000765 APInt KnownZero, KnownOne;
766 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
767 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000768
Dan Gohmane58ab792009-01-29 01:59:02 +0000769 // Revisit the node.
770 AddToWorkList(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000771
Dan Gohmane58ab792009-01-29 01:59:02 +0000772 // Replace the old value with the new one.
773 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000774 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000775 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000776 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000777 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000778 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000779
Dan Gohmane58ab792009-01-29 01:59:02 +0000780 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000781 return true;
782}
783
Evan Cheng0abb54d2010-04-24 04:43:44 +0000784void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000785 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000786 EVT VT = Load->getValueType(0);
787 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000788
Evan Cheng0abb54d2010-04-24 04:43:44 +0000789 DEBUG(dbgs() << "\nReplacing.9 ";
790 Load->dump(&DAG);
791 dbgs() << "\nWith: ";
792 Trunc.getNode()->dump(&DAG);
793 dbgs() << '\n');
794 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000795 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
796 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Evan Cheng0abb54d2010-04-24 04:43:44 +0000797 removeFromWorkList(Load);
798 DAG.DeleteNode(Load);
Evan Chenge8136902010-04-27 19:48:13 +0000799 AddToWorkList(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000800}
801
802SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
803 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000804 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000805 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000806 EVT MemVT = LD->getMemoryVT();
807 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +0000808 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +0000809 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000810 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000811 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000812 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000813 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000814 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000815 }
816
Evan Chenge19aa5c2010-04-19 19:29:22 +0000817 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000818 switch (Opc) {
819 default: break;
820 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000821 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000822 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000823 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000824 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000825 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000826 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000827 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000828 case ISD::Constant: {
829 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000830 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000831 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000832 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000833 }
834
835 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000836 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000837 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000838}
839
Evan Cheng0abb54d2010-04-24 04:43:44 +0000840SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000841 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
842 return SDValue();
843 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000844 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000845 bool Replace = false;
846 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
847 if (NewOp.getNode() == 0)
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000848 return SDValue();
Evan Chenge8136902010-04-27 19:48:13 +0000849 AddToWorkList(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000850
851 if (Replace)
852 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
853 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000854 DAG.getValueType(OldVT));
855}
856
Evan Cheng0abb54d2010-04-24 04:43:44 +0000857SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000858 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000859 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000860 bool Replace = false;
861 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
862 if (NewOp.getNode() == 0)
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000863 return SDValue();
Evan Chenge8136902010-04-27 19:48:13 +0000864 AddToWorkList(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000865
866 if (Replace)
867 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
868 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000869}
870
Evan Chengaf56fac2010-04-16 06:14:10 +0000871/// PromoteIntBinOp - Promote the specified integer binary operation if the
872/// target indicates it is beneficial. e.g. On x86, it's usually better to
873/// promote i16 operations to i32 since i16 instructions are longer.
874SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
875 if (!LegalOperations)
876 return SDValue();
877
878 EVT VT = Op.getValueType();
879 if (VT.isVector() || !VT.isInteger())
880 return SDValue();
881
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000882 // If operation type is 'undesirable', e.g. i16 on x86, consider
883 // promoting it.
884 unsigned Opc = Op.getOpcode();
885 if (TLI.isTypeDesirableForOp(Opc, VT))
886 return SDValue();
887
Evan Chengaf56fac2010-04-16 06:14:10 +0000888 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000889 // Consult target whether it is a good idea to promote this operation and
890 // what's the right type to promote it to.
891 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +0000892 assert(PVT != VT && "Don't know what type to promote to!");
893
Evan Cheng0abb54d2010-04-24 04:43:44 +0000894 bool Replace0 = false;
895 SDValue N0 = Op.getOperand(0);
896 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
897 if (NN0.getNode() == 0)
Evan Chengf1223bd2010-04-22 20:19:46 +0000898 return SDValue();
899
Evan Cheng0abb54d2010-04-24 04:43:44 +0000900 bool Replace1 = false;
901 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +0000902 SDValue NN1;
903 if (N0 == N1)
904 NN1 = NN0;
905 else {
906 NN1 = PromoteOperand(N1, PVT, Replace1);
907 if (NN1.getNode() == 0)
908 return SDValue();
909 }
Evan Chengf1223bd2010-04-22 20:19:46 +0000910
Evan Cheng0abb54d2010-04-24 04:43:44 +0000911 AddToWorkList(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +0000912 if (NN1.getNode())
913 AddToWorkList(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000914
915 if (Replace0)
916 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
917 if (Replace1)
918 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +0000919
Evan Chenge8136902010-04-27 19:48:13 +0000920 DEBUG(dbgs() << "\nPromoting ";
921 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000922 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000923 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000924 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +0000925 }
926 return SDValue();
927}
928
929/// PromoteIntShiftOp - Promote the specified integer shift operation if the
930/// target indicates it is beneficial. e.g. On x86, it's usually better to
931/// promote i16 operations to i32 since i16 instructions are longer.
932SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
933 if (!LegalOperations)
934 return SDValue();
935
936 EVT VT = Op.getValueType();
937 if (VT.isVector() || !VT.isInteger())
938 return SDValue();
939
940 // If operation type is 'undesirable', e.g. i16 on x86, consider
941 // promoting it.
942 unsigned Opc = Op.getOpcode();
943 if (TLI.isTypeDesirableForOp(Opc, VT))
944 return SDValue();
945
946 EVT PVT = VT;
947 // Consult target whether it is a good idea to promote this operation and
948 // what's the right type to promote it to.
949 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
950 assert(PVT != VT && "Don't know what type to promote to!");
951
Evan Cheng0abb54d2010-04-24 04:43:44 +0000952 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000953 SDValue N0 = Op.getOperand(0);
954 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000955 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000956 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000957 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000958 else
Evan Cheng0abb54d2010-04-24 04:43:44 +0000959 N0 = PromoteOperand(N0, PVT, Replace);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000960 if (N0.getNode() == 0)
961 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000962
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000963 AddToWorkList(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000964 if (Replace)
965 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +0000966
Evan Chenge8136902010-04-27 19:48:13 +0000967 DEBUG(dbgs() << "\nPromoting ";
968 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000969 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000970 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +0000971 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +0000972 }
973 return SDValue();
974}
975
Evan Chenge19aa5c2010-04-19 19:29:22 +0000976SDValue DAGCombiner::PromoteExtend(SDValue Op) {
977 if (!LegalOperations)
978 return SDValue();
979
980 EVT VT = Op.getValueType();
981 if (VT.isVector() || !VT.isInteger())
982 return SDValue();
983
984 // If operation type is 'undesirable', e.g. i16 on x86, consider
985 // promoting it.
986 unsigned Opc = Op.getOpcode();
987 if (TLI.isTypeDesirableForOp(Opc, VT))
988 return SDValue();
989
990 EVT PVT = VT;
991 // Consult target whether it is a good idea to promote this operation and
992 // what's the right type to promote it to.
993 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
994 assert(PVT != VT && "Don't know what type to promote to!");
995 // fold (aext (aext x)) -> (aext x)
996 // fold (aext (zext x)) -> (zext x)
997 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +0000998 DEBUG(dbgs() << "\nPromoting ";
999 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001000 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001001 }
1002 return SDValue();
1003}
1004
1005bool DAGCombiner::PromoteLoad(SDValue Op) {
1006 if (!LegalOperations)
1007 return false;
1008
1009 EVT VT = Op.getValueType();
1010 if (VT.isVector() || !VT.isInteger())
1011 return false;
1012
1013 // If operation type is 'undesirable', e.g. i16 on x86, consider
1014 // promoting it.
1015 unsigned Opc = Op.getOpcode();
1016 if (TLI.isTypeDesirableForOp(Opc, VT))
1017 return false;
1018
1019 EVT PVT = VT;
1020 // Consult target whether it is a good idea to promote this operation and
1021 // what's the right type to promote it to.
1022 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1023 assert(PVT != VT && "Don't know what type to promote to!");
1024
Andrew Trickef9de2a2013-05-25 02:42:55 +00001025 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001026 SDNode *N = Op.getNode();
1027 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001028 EVT MemVT = LD->getMemoryVT();
1029 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +00001030 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +00001031 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001032 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001033 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001034 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001035 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001036 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1037
Evan Cheng0abb54d2010-04-24 04:43:44 +00001038 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001039 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001040 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001041 Result.getNode()->dump(&DAG);
1042 dbgs() << '\n');
1043 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001044 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1045 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001046 removeFromWorkList(N);
1047 DAG.DeleteNode(N);
Evan Chenge8136902010-04-27 19:48:13 +00001048 AddToWorkList(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001049 return true;
1050 }
1051 return false;
1052}
1053
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001054
Chris Lattnere49c9742007-05-14 22:04:50 +00001055//===----------------------------------------------------------------------===//
1056// Main DAG Combiner implementation
1057//===----------------------------------------------------------------------===//
1058
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001059void DAGCombiner::Run(CombineLevel AtLevel) {
1060 // set the instance variables, so that the various visit routines may use it.
1061 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001062 LegalOperations = Level >= AfterLegalizeVectorOps;
1063 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001064
Evan Cheng5e7658c2008-08-29 22:21:44 +00001065 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001066 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1067 E = DAG.allnodes_end(); I != E; ++I)
James Molloy67b6b112012-02-16 09:17:04 +00001068 AddToWorkList(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001069
Evan Cheng5e7658c2008-08-29 22:21:44 +00001070 // Create a dummy node (which is not added to allnodes), that adds a reference
1071 // to the root node, preventing it from being deleted, and tracking any
1072 // changes of the root.
1073 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001074
Jim Laskeye7d2c242006-10-17 19:33:52 +00001075 // The root of the dag may dangle to deleted nodes until the dag combiner is
1076 // done. Set it to null to avoid confusion.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001077 DAG.setRoot(SDValue());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001078
James Molloy67b6b112012-02-16 09:17:04 +00001079 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001080 // try and combine it.
James Molloy67b6b112012-02-16 09:17:04 +00001081 while (!WorkListContents.empty()) {
1082 SDNode *N;
Jack Carterd4e96152013-10-17 01:34:33 +00001083 // The WorkListOrder holds the SDNodes in order, but it may contain
1084 // duplicates.
James Molloy67b6b112012-02-16 09:17:04 +00001085 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1086 // worklist *should* contain, and check the node we want to visit is should
1087 // actually be visited.
1088 do {
Benjamin Kramere1e549d2012-03-10 00:23:58 +00001089 N = WorkListOrder.pop_back_val();
James Molloy67b6b112012-02-16 09:17:04 +00001090 } while (!WorkListContents.erase(N));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001091
Evan Cheng5e7658c2008-08-29 22:21:44 +00001092 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1093 // N is deleted from the DAG, since they too may now be dead or may have a
1094 // reduced number of uses, allowing other xforms.
1095 if (N->use_empty() && N != &Dummy) {
1096 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1097 AddToWorkList(N->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001098
Evan Cheng5e7658c2008-08-29 22:21:44 +00001099 DAG.DeleteNode(N);
1100 continue;
Nate Begeman21158fc2005-09-01 00:19:25 +00001101 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001102
Evan Cheng5e7658c2008-08-29 22:21:44 +00001103 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001104
Evan Cheng5e7658c2008-08-29 22:21:44 +00001105 if (RV.getNode() == 0)
1106 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001107
Evan Cheng5e7658c2008-08-29 22:21:44 +00001108 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001109
Evan Cheng5e7658c2008-08-29 22:21:44 +00001110 // If we get back the same node we passed in, rather than a new node or
1111 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001112 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001113 // mechanics for us, we have no work to do in this case.
1114 if (RV.getNode() == N)
1115 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001116
Evan Cheng5e7658c2008-08-29 22:21:44 +00001117 assert(N->getOpcode() != ISD::DELETED_NODE &&
1118 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1119 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001120
Wesley Peck527da1b2010-11-23 03:31:01 +00001121 DEBUG(dbgs() << "\nReplacing.3 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001122 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00001123 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001124 RV.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00001125 dbgs() << '\n');
Eric Christopherd6300d22011-07-14 01:12:15 +00001126
Devang Patelefec7712011-05-23 22:04:42 +00001127 // Transfer debug value.
1128 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001129 WorkListRemover DeadNodes(*this);
1130 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001131 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001132 else {
1133 assert(N->getValueType(0) == RV.getValueType() &&
1134 N->getNumValues() == 1 && "Type mismatch");
1135 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001136 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001137 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001138
Evan Cheng5e7658c2008-08-29 22:21:44 +00001139 // Push the new node and any users onto the worklist
1140 AddToWorkList(RV.getNode());
1141 AddUsersToWorkList(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001142
Evan Cheng5e7658c2008-08-29 22:21:44 +00001143 // Add any uses of the old node to the worklist in case this node is the
1144 // last one that uses them. They may become dead after this node is
1145 // deleted.
1146 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1147 AddToWorkList(N->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001148
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001149 // Finally, if the node is now dead, remove it from the graph. The node
1150 // may not be dead if the replacement process recursively simplified to
1151 // something else needing this node.
1152 if (N->use_empty()) {
1153 // Nodes can be reintroduced into the worklist. Make sure we do not
1154 // process a node that has been replaced.
1155 removeFromWorkList(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001156
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001157 // Finally, since the node is now dead, remove it from the graph.
1158 DAG.DeleteNode(N);
1159 }
Evan Cheng5e7658c2008-08-29 22:21:44 +00001160 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001161
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001162 // If the root changed (e.g. it was a dead load, update the root).
1163 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001164 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001165}
1166
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001167SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001168 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001169 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001170 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001171 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001172 case ISD::ADD: return visitADD(N);
1173 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001174 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001175 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001176 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001177 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001178 case ISD::MUL: return visitMUL(N);
1179 case ISD::SDIV: return visitSDIV(N);
1180 case ISD::UDIV: return visitUDIV(N);
1181 case ISD::SREM: return visitSREM(N);
1182 case ISD::UREM: return visitUREM(N);
1183 case ISD::MULHU: return visitMULHU(N);
1184 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001185 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1186 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001187 case ISD::SMULO: return visitSMULO(N);
1188 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001189 case ISD::SDIVREM: return visitSDIVREM(N);
1190 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001191 case ISD::AND: return visitAND(N);
1192 case ISD::OR: return visitOR(N);
1193 case ISD::XOR: return visitXOR(N);
1194 case ISD::SHL: return visitSHL(N);
1195 case ISD::SRA: return visitSRA(N);
1196 case ISD::SRL: return visitSRL(N);
1197 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001198 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001199 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001200 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001201 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001202 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001203 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001204 case ISD::SELECT_CC: return visitSELECT_CC(N);
1205 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001206 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1207 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001208 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001209 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1210 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001211 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001212 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001213 case ISD::FADD: return visitFADD(N);
1214 case ISD::FSUB: return visitFSUB(N);
1215 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001216 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001217 case ISD::FDIV: return visitFDIV(N);
1218 case ISD::FREM: return visitFREM(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001219 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001220 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1221 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1222 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1223 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1224 case ISD::FP_ROUND: return visitFP_ROUND(N);
1225 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1226 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1227 case ISD::FNEG: return visitFNEG(N);
1228 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001229 case ISD::FFLOOR: return visitFFLOOR(N);
1230 case ISD::FCEIL: return visitFCEIL(N);
1231 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001232 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001233 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001234 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001235 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001236 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001237 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001238 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1239 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001240 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001241 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001242 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001243 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001244 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001245}
1246
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001247SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001248 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001249
1250 // If nothing happened, try a target-specific DAG combine.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001251 if (RV.getNode() == 0) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001252 assert(N->getOpcode() != ISD::DELETED_NODE &&
1253 "Node was deleted but visit returned NULL!");
1254
1255 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1256 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1257
1258 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001259 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001260 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001261
1262 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1263 }
1264 }
1265
Evan Chengf1005572010-04-28 07:10:39 +00001266 // If nothing happened still, try promoting the operation.
1267 if (RV.getNode() == 0) {
1268 switch (N->getOpcode()) {
1269 default: break;
1270 case ISD::ADD:
1271 case ISD::SUB:
1272 case ISD::MUL:
1273 case ISD::AND:
1274 case ISD::OR:
1275 case ISD::XOR:
1276 RV = PromoteIntBinOp(SDValue(N, 0));
1277 break;
1278 case ISD::SHL:
1279 case ISD::SRA:
1280 case ISD::SRL:
1281 RV = PromoteIntShiftOp(SDValue(N, 0));
1282 break;
1283 case ISD::SIGN_EXTEND:
1284 case ISD::ZERO_EXTEND:
1285 case ISD::ANY_EXTEND:
1286 RV = PromoteExtend(SDValue(N, 0));
1287 break;
1288 case ISD::LOAD:
1289 if (PromoteLoad(SDValue(N, 0)))
1290 RV = SDValue(N, 0);
1291 break;
1292 }
1293 }
1294
Scott Michelcf0da6c2009-02-17 22:15:04 +00001295 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001296 // sdisel CSE.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001297 if (RV.getNode() == 0 &&
Evan Cheng31604a62008-03-22 01:55:50 +00001298 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1299 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001300 SDValue N0 = N->getOperand(0);
1301 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001302
Evan Cheng31604a62008-03-22 01:55:50 +00001303 // Constant operands are canonicalized to RHS.
1304 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001305 SDValue Ops[] = { N1, N0 };
Evan Cheng31604a62008-03-22 01:55:50 +00001306 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1307 Ops, 2);
Evan Chengfe7610f2008-03-24 23:55:16 +00001308 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001309 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001310 }
1311 }
1312
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001313 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001314}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001315
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001316/// getInputChainForNode - Given a node, return its input chain if it has one,
1317/// otherwise return a null sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001318static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001319 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001320 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001321 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001322 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001323 return N->getOperand(NumOps-1);
1324 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001325 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001326 return N->getOperand(i);
1327 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001328 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001329}
1330
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001331SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001332 // If N has two operands, where one has an input chain equal to the other,
1333 // the 'other' chain is redundant.
1334 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001335 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001336 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001337 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001338 return N->getOperand(1);
1339 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001340
Chris Lattner48fb92f2007-05-16 06:37:59 +00001341 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001342 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001343 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001344 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001345
Jim Laskey708d0db2006-10-04 16:53:27 +00001346 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001347 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001348
Jim Laskey0463e082006-10-07 23:37:56 +00001349 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001350 // encountered.
1351 for (unsigned i = 0; i < TFs.size(); ++i) {
1352 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001353
Jim Laskey708d0db2006-10-04 16:53:27 +00001354 // Check each of the operands.
1355 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001356 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001357
Jim Laskey708d0db2006-10-04 16:53:27 +00001358 switch (Op.getOpcode()) {
1359 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001360 // Entry tokens don't need to be added to the list. They are
1361 // rededundant.
1362 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001363 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001364
Jim Laskey708d0db2006-10-04 16:53:27 +00001365 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001366 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001367 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001368 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001369 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001370 // Clean up in case the token factor is removed.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001371 AddToWorkList(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001372 Changed = true;
1373 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001374 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001375 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001376
Jim Laskey708d0db2006-10-04 16:53:27 +00001377 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001378 // Only add if it isn't already in the list.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001379 if (SeenOps.insert(Op.getNode()))
Jim Laskey6549d222006-10-05 15:07:25 +00001380 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001381 else
1382 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001383 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001384 }
1385 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001386 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001387
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001388 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001389
1390 // If we've change things around then replace token factor.
1391 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001392 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001393 // The entry token is the only possible outcome.
1394 Result = DAG.getEntryNode();
1395 } else {
1396 // New and improved token factor.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001397 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00001398 MVT::Other, &Ops[0], Ops.size());
Nate Begeman02b23c62005-10-13 03:11:28 +00001399 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001400
Jim Laskeydcf983c2006-10-13 23:32:28 +00001401 // Don't add users to work list.
1402 return CombineTo(N, Result, false);
Nate Begeman02b23c62005-10-13 03:11:28 +00001403 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001404
Jim Laskey708d0db2006-10-04 16:53:27 +00001405 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001406}
1407
Chris Lattneree322b42008-02-13 07:25:05 +00001408/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001409SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chris Lattneree322b42008-02-13 07:25:05 +00001410 WorkListRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001411 // Replacing results may cause a different MERGE_VALUES to suddenly
1412 // be CSE'd with N, and carry its uses with it. Iterate until no
1413 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001414 // First add the users of this node to the work list so that they
1415 // can be tried again once they have new operands.
1416 AddUsersToWorkList(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001417 do {
1418 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001419 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001420 } while (!N->use_empty());
Chris Lattneree322b42008-02-13 07:25:05 +00001421 removeFromWorkList(N);
1422 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001423 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001424}
1425
Evan Cheng92011002007-01-19 17:51:44 +00001426static
Andrew Trickef9de2a2013-05-25 02:42:55 +00001427SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001428 SelectionDAG &DAG) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001429 EVT VT = N0.getValueType();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001430 SDValue N00 = N0.getOperand(0);
1431 SDValue N01 = N0.getOperand(1);
Evan Cheng92011002007-01-19 17:51:44 +00001432 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
Bill Wendlingcdd96132009-01-30 02:23:43 +00001433
Gabor Greiff304a7a2008-08-28 21:40:38 +00001434 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
Evan Cheng92011002007-01-19 17:51:44 +00001435 isa<ConstantSDNode>(N00.getOperand(1))) {
Bill Wendlingcdd96132009-01-30 02:23:43 +00001436 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Andrew Trickef9de2a2013-05-25 02:42:55 +00001437 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1438 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001439 N00.getOperand(0), N01),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001440 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001441 N00.getOperand(1), N01));
1442 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
Evan Cheng92011002007-01-19 17:51:44 +00001443 }
Bill Wendlingcdd96132009-01-30 02:23:43 +00001444
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001445 return SDValue();
Evan Cheng92011002007-01-19 17:51:44 +00001446}
1447
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001448SDValue DAGCombiner::visitADD(SDNode *N) {
1449 SDValue N0 = N->getOperand(0);
1450 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001451 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1452 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001453 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001454
1455 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001456 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001457 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001458 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001459
1460 // fold (add x, 0) -> x, vector edition
1461 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1462 return N0;
1463 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1464 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001465 }
Bill Wendling0864a752008-12-10 22:36:00 +00001466
Dan Gohman06563a82007-07-03 14:03:57 +00001467 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001468 if (N0.getOpcode() == ISD::UNDEF)
1469 return N0;
1470 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001471 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001472 // fold (add c1, c2) -> c1+c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001473 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001474 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001475 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00001476 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001477 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001478 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001479 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001480 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001481 // fold (add Sym, c) -> Sym+c
1482 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001483 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001484 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001485 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001486 GA->getOffset() +
1487 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001488 // fold ((c1-A)+c2) -> (c1+c2)-A
1489 if (N1C && N0.getOpcode() == ISD::SUB)
1490 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001491 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001492 DAG.getConstant(N1C->getAPIntValue()+
1493 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001494 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001495 // reassociate add
Andrew Trickef9de2a2013-05-25 02:42:55 +00001496 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001497 if (RADD.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00001498 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001499 // fold ((0-A) + B) -> B-A
1500 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1501 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001502 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001503 // fold (A + (0-B)) -> A-B
1504 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1505 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001506 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001507 // fold (A+(B-A)) -> B
1508 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001509 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001510 // fold ((B-A)+A) -> B
1511 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1512 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001513 // fold (A+(B-(A+C))) to (B-C)
1514 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001515 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001516 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001517 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001518 // fold (A+(B-(C+A))) to (B-C)
1519 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001520 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001521 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001522 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001523 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001524 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1525 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001526 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001527 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001528 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001529
Dale Johannesen8c766702008-12-02 01:30:54 +00001530 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1531 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1532 SDValue N00 = N0.getOperand(0);
1533 SDValue N01 = N0.getOperand(1);
1534 SDValue N10 = N1.getOperand(0);
1535 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001536
1537 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001538 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1539 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1540 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001541 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001542
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001543 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1544 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001545
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001546 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001547 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001548 APInt LHSZero, LHSOne;
1549 APInt RHSZero, RHSOne;
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001550 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001551
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001552 if (LHSZero.getBoolValue()) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001553 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001554
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001555 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1556 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001557 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1558 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1559 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1560 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001561 }
1562 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001563
Evan Cheng92011002007-01-19 17:51:44 +00001564 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Gabor Greiff304a7a2008-08-28 21:40:38 +00001565 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001566 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001567 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001568 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00001569 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001570 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001571 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001572 }
1573
Dan Gohman954f4902010-01-19 23:30:49 +00001574 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1575 if (N1.getOpcode() == ISD::SHL &&
1576 N1.getOperand(0).getOpcode() == ISD::SUB)
1577 if (ConstantSDNode *C =
1578 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1579 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001580 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1581 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001582 N1.getOperand(0).getOperand(1),
1583 N1.getOperand(1)));
1584 if (N0.getOpcode() == ISD::SHL &&
1585 N0.getOperand(0).getOpcode() == ISD::SUB)
1586 if (ConstantSDNode *C =
1587 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1588 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001589 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1590 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001591 N0.getOperand(0).getOperand(1),
1592 N0.getOperand(1)));
1593
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001594 if (N1.getOpcode() == ISD::AND) {
1595 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001596 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001597 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1598 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001599
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001600 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1601 // and similar xforms where the inner op is either ~0 or 0.
1602 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001603 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001604 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1605 }
1606 }
1607
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001608 // add (sext i1), X -> sub X, (zext i1)
1609 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1610 N0.getOperand(0).getValueType() == MVT::i1 &&
1611 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001612 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001613 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1614 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1615 }
1616
Evan Chengf1005572010-04-28 07:10:39 +00001617 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001618}
1619
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001620SDValue DAGCombiner::visitADDC(SDNode *N) {
1621 SDValue N0 = N->getOperand(0);
1622 SDValue N1 = N->getOperand(1);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001623 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1624 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001625 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001626
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001627 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001628 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001629 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001630 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001631 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001632
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001633 // canonicalize constant to RHS.
Dan Gohmanb4e26372008-06-23 15:29:14 +00001634 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001635 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001636
Chris Lattner47206662007-03-04 20:40:38 +00001637 // fold (addc x, 0) -> x + no carry out
1638 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001639 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001640 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001641
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001642 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001643 APInt LHSZero, LHSOne;
1644 APInt RHSZero, RHSOne;
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001645 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001646
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001647 if (LHSZero.getBoolValue()) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001648 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001649
Chris Lattner47206662007-03-04 20:40:38 +00001650 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1651 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001652 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001653 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001654 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001655 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001656 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001657
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001658 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001659}
1660
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001661SDValue DAGCombiner::visitADDE(SDNode *N) {
1662 SDValue N0 = N->getOperand(0);
1663 SDValue N1 = N->getOperand(1);
1664 SDValue CarryIn = N->getOperand(2);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001665 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1666 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001667
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001668 // canonicalize constant to RHS
Dan Gohmanb4e26372008-06-23 15:29:14 +00001669 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001670 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001671 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001672
Chris Lattner47206662007-03-04 20:40:38 +00001673 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001674 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001675 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001676
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001677 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001678}
1679
Eric Christophere5ca1e02011-02-16 04:50:12 +00001680// Since it may not be valid to emit a fold to zero for vector initializers
1681// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001682static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001683 SelectionDAG &DAG,
1684 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001685 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001686 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001687 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1688 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001689 return SDValue();
1690}
1691
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001692SDValue DAGCombiner::visitSUB(SDNode *N) {
1693 SDValue N0 = N->getOperand(0);
1694 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001695 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1696 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Eric Christopherd6300d22011-07-14 01:12:15 +00001697 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1698 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001699 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001700
Dan Gohmana8665142007-06-25 16:23:39 +00001701 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001702 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001703 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001704 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001705
1706 // fold (sub x, 0) -> x, vector edition
1707 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1708 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001709 }
Bill Wendling0864a752008-12-10 22:36:00 +00001710
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001711 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001712 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001713 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001714 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001715 // fold (sub c1, c2) -> c1-c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001716 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001717 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001718 // fold (sub x, c) -> (add x, -c)
1719 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001720 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001721 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001722 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1723 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001724 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001725 // fold A-(A-B) -> B
1726 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1727 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001728 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001729 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001730 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001731 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001732 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001733 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001734 // fold C2-(A+C1) -> (C2-C1)-A
1735 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001736 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1737 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001738 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001739 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001740 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001741 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001742 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001743 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1744 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001745 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001746 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001747 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001748 // fold ((A+(C+B))-B) -> A+C
1749 if (N0.getOpcode() == ISD::ADD &&
1750 N0.getOperand(1).getOpcode() == ISD::ADD &&
1751 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001752 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001753 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001754 // fold ((A-(B-C))-C) -> A-B
1755 if (N0.getOpcode() == ISD::SUB &&
1756 N0.getOperand(1).getOpcode() == ISD::SUB &&
1757 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001758 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001759 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001760
Dan Gohman06563a82007-07-03 14:03:57 +00001761 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001762 if (N0.getOpcode() == ISD::UNDEF)
1763 return N0;
1764 if (N1.getOpcode() == ISD::UNDEF)
1765 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001766
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001767 // If the relocation model supports it, consider symbol offsets.
1768 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001769 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001770 // fold (sub Sym, c) -> Sym-c
1771 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001772 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001773 GA->getOffset() -
1774 (uint64_t)N1C->getSExtValue());
1775 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1776 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1777 if (GA->getGlobal() == GB->getGlobal())
1778 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1779 VT);
1780 }
1781
Evan Chengf1005572010-04-28 07:10:39 +00001782 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001783}
1784
Craig Topper43a1bd62012-01-07 09:06:39 +00001785SDValue DAGCombiner::visitSUBC(SDNode *N) {
1786 SDValue N0 = N->getOperand(0);
1787 SDValue N1 = N->getOperand(1);
1788 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1789 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1790 EVT VT = N0.getValueType();
1791
1792 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001793 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001794 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1795 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001796 MVT::Glue));
1797
1798 // fold (subc x, x) -> 0 + no borrow
1799 if (N0 == N1)
1800 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001801 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001802 MVT::Glue));
1803
1804 // fold (subc x, 0) -> x + no borrow
1805 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001806 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001807 MVT::Glue));
1808
1809 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1810 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001811 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1812 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001813 MVT::Glue));
1814
1815 return SDValue();
1816}
1817
1818SDValue DAGCombiner::visitSUBE(SDNode *N) {
1819 SDValue N0 = N->getOperand(0);
1820 SDValue N1 = N->getOperand(1);
1821 SDValue CarryIn = N->getOperand(2);
1822
1823 // fold (sube x, y, false) -> (subc x, y)
1824 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001825 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001826
1827 return SDValue();
1828}
1829
Jack Carterd4e96152013-10-17 01:34:33 +00001830/// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
1831/// elements are all the same constant or undefined.
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001832static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1833 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1834 if (!C)
1835 return false;
1836
1837 APInt SplatUndef;
1838 unsigned SplatBitSize;
1839 bool HasAnyUndefs;
1840 EVT EltVT = N->getValueType(0).getVectorElementType();
1841 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1842 HasAnyUndefs) &&
1843 EltVT.getSizeInBits() >= SplatBitSize);
1844}
1845
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001846SDValue DAGCombiner::visitMUL(SDNode *N) {
1847 SDValue N0 = N->getOperand(0);
1848 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001849 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001850
Dan Gohman06563a82007-07-03 14:03:57 +00001851 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001852 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001853 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001854
1855 bool N0IsConst = false;
1856 bool N1IsConst = false;
1857 APInt ConstValue0, ConstValue1;
1858 // fold vector ops
1859 if (VT.isVector()) {
1860 SDValue FoldedVOp = SimplifyVBinOp(N);
1861 if (FoldedVOp.getNode()) return FoldedVOp;
1862
1863 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1864 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1865 } else {
1866 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
Jack Carterd4e96152013-10-17 01:34:33 +00001867 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1868 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001869 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
Jack Carterd4e96152013-10-17 01:34:33 +00001870 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1871 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001872 }
1873
Nate Begeman21158fc2005-09-01 00:19:25 +00001874 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001875 if (N0IsConst && N1IsConst)
1876 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1877
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001878 // canonicalize constant to RHS
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001879 if (N0IsConst && !N1IsConst)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001880 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001881 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001882 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00001883 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001884 // We require a splat of the entire scalar bit width for non-contiguous
1885 // bit patterns.
1886 bool IsFullSplat =
1887 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001888 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001889 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001890 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00001891 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001892 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001893 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001894 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001895 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001896 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001897 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001898 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00001899 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00001900 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001901 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001902 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001903 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00001904 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001905 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001906 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001907 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00001908 DAG.getConstant(Log2Val,
1909 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00001910 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001911
1912 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00001913 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00001914 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001915 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1916 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001917 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001918 N1, N0.getOperand(1));
Gabor Greiff304a7a2008-08-28 21:40:38 +00001919 AddToWorkList(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001920 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001921 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00001922 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001923
Chris Lattner324871e2006-03-01 03:44:24 +00001924 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1925 // use.
1926 {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001927 SDValue Sh(0,0), Y(0,0);
Chris Lattner324871e2006-03-01 03:44:24 +00001928 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00001929 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001930 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1931 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001932 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001933 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001934 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00001935 isa<ConstantSDNode>(N1.getOperand(1)) &&
1936 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001937 Sh = N1; Y = N0;
1938 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001939
Gabor Greiff304a7a2008-08-28 21:40:38 +00001940 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001941 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001942 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001943 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001944 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00001945 }
1946 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001947
Chris Lattnerf29f5202006-03-04 23:33:26 +00001948 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001949 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1950 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1951 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001952 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1953 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001954 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001955 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001956 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001957
Nate Begeman22e251a2006-02-03 06:46:56 +00001958 // reassociate mul
Andrew Trickef9de2a2013-05-25 02:42:55 +00001959 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001960 if (RMUL.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00001961 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00001962
Evan Chengf1005572010-04-28 07:10:39 +00001963 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001964}
1965
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001966SDValue DAGCombiner::visitSDIV(SDNode *N) {
1967 SDValue N0 = N->getOperand(0);
1968 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001969 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1970 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001971 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001972
Dan Gohmana8665142007-06-25 16:23:39 +00001973 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001974 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001975 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001976 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00001977 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001978
Nate Begeman21158fc2005-09-01 00:19:25 +00001979 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001980 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00001981 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00001982 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00001983 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00001984 return N0;
1985 // fold (sdiv X, -1) -> 0-X
1986 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001987 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00001988 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00001989 // If we know the sign bits of both operands are zero, strength reduce to a
1990 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00001991 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00001992 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001993 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00001994 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00001995 }
Nate Begeman57b35672006-02-17 07:26:20 +00001996 // fold (sdiv X, pow2) -> simple ops after legalize
Eli Friedmanf9081a82011-12-07 03:55:52 +00001997 if (N1C && !N1C->isNullValue() &&
Eli Friedmane9e356a2011-10-27 02:06:39 +00001998 (N1C->getAPIntValue().isPowerOf2() ||
1999 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00002000 // If dividing by powers of two is cheap, then don't perform the following
2001 // fold.
2002 if (TLI.isPow2DivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002003 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00002004
Eli Friedmane9e356a2011-10-27 02:06:39 +00002005 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00002006
Chris Lattner471627c2006-02-16 08:02:36 +00002007 // Splat the sign bit into the register
Andrew Trickef9de2a2013-05-25 02:42:55 +00002008 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
Bill Wendling5b663e72009-01-30 02:52:17 +00002009 DAG.getConstant(VT.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002010 getShiftAmountTy(N0.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002011 AddToWorkList(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002012
Chris Lattner471627c2006-02-16 08:02:36 +00002013 // Add (N0 < 0) ? abs2 - 1 : 0;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002014 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
Bill Wendling5b663e72009-01-30 02:52:17 +00002015 DAG.getConstant(VT.getSizeInBits() - lg2,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002016 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002017 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002018 AddToWorkList(SRL.getNode());
2019 AddToWorkList(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00002020 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002021 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002022
Nate Begeman4dd38312005-10-21 00:02:42 +00002023 // If we're dividing by a positive value, we're done. Otherwise, we must
2024 // negate the result.
Eli Friedmane9e356a2011-10-27 02:06:39 +00002025 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002026 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002027
Gabor Greiff304a7a2008-08-28 21:40:38 +00002028 AddToWorkList(SRA.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002029 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00002030 DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002031 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002032
Nate Begemanc6f067a2005-10-20 02:15:44 +00002033 // if integer divide is expensive and we satisfy the requirements, emit an
2034 // alternate sequence.
Eli Friedmane9e356a2011-10-27 02:06:39 +00002035 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002036 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002037 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002038 }
Dan Gohmana8665142007-06-25 16:23:39 +00002039
Dan Gohman06563a82007-07-03 14:03:57 +00002040 // undef / X -> 0
2041 if (N0.getOpcode() == ISD::UNDEF)
2042 return DAG.getConstant(0, VT);
2043 // X / undef -> undef
2044 if (N1.getOpcode() == ISD::UNDEF)
2045 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002046
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002047 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002048}
2049
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002050SDValue DAGCombiner::visitUDIV(SDNode *N) {
2051 SDValue N0 = N->getOperand(0);
2052 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002053 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2054 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00002055 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002056
Dan Gohmana8665142007-06-25 16:23:39 +00002057 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002058 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002059 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002060 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002061 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002062
Nate Begeman21158fc2005-09-01 00:19:25 +00002063 // fold (udiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002064 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002065 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002066 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002067 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002068 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002069 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002070 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002071 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002072 if (N1.getOpcode() == ISD::SHL) {
2073 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002074 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002075 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002076 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002077 N1.getOperand(1),
2078 DAG.getConstant(SHC->getAPIntValue()
2079 .logBase2(),
2080 ADDVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002081 AddToWorkList(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002082 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002083 }
2084 }
2085 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002086 // fold (udiv x, c) -> alternate
Dan Gohmanb72127a2008-03-13 22:13:53 +00002087 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002088 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002089 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002090 }
Dan Gohmana8665142007-06-25 16:23:39 +00002091
Dan Gohman06563a82007-07-03 14:03:57 +00002092 // undef / X -> 0
2093 if (N0.getOpcode() == ISD::UNDEF)
2094 return DAG.getConstant(0, VT);
2095 // X / undef -> undef
2096 if (N1.getOpcode() == ISD::UNDEF)
2097 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002098
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002099 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002100}
2101
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002102SDValue DAGCombiner::visitSREM(SDNode *N) {
2103 SDValue N0 = N->getOperand(0);
2104 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002105 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2106 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002107 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002108
Nate Begeman21158fc2005-09-01 00:19:25 +00002109 // fold (srem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002110 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002111 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002112 // If we know the sign bits of both operands are zero, strength reduce to a
2113 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002114 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002115 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002116 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002117 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002118
Dan Gohman9a693412007-11-26 23:46:11 +00002119 // If X/C can be simplified by the division-by-constant logic, lower
2120 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002121 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002122 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002123 AddToWorkList(Div.getNode());
2124 SDValue OptimizedDiv = combine(Div.getNode());
2125 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002126 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002127 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002128 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002129 AddToWorkList(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002130 return Sub;
2131 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002132 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002133
Dan Gohman06563a82007-07-03 14:03:57 +00002134 // undef % X -> 0
2135 if (N0.getOpcode() == ISD::UNDEF)
2136 return DAG.getConstant(0, VT);
2137 // X % undef -> undef
2138 if (N1.getOpcode() == ISD::UNDEF)
2139 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002140
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002141 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002142}
2143
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002144SDValue DAGCombiner::visitUREM(SDNode *N) {
2145 SDValue N0 = N->getOperand(0);
2146 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002147 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2148 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002149 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002150
Nate Begeman21158fc2005-09-01 00:19:25 +00002151 // fold (urem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002152 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002153 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002154 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002155 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002156 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002157 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002158 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2159 if (N1.getOpcode() == ISD::SHL) {
2160 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002161 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002162 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002163 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002164 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002165 VT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002166 AddToWorkList(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002167 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002168 }
2169 }
2170 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002171
Dan Gohman9a693412007-11-26 23:46:11 +00002172 // If X/C can be simplified by the division-by-constant logic, lower
2173 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002174 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002175 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Dan Gohman1df80f62008-09-08 16:59:01 +00002176 AddToWorkList(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002177 SDValue OptimizedDiv = combine(Div.getNode());
2178 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002179 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002180 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002181 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002182 AddToWorkList(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002183 return Sub;
2184 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002185 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002186
Dan Gohman06563a82007-07-03 14:03:57 +00002187 // undef % X -> 0
2188 if (N0.getOpcode() == ISD::UNDEF)
2189 return DAG.getConstant(0, VT);
2190 // X % undef -> undef
2191 if (N1.getOpcode() == ISD::UNDEF)
2192 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002193
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002194 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002195}
2196
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002197SDValue DAGCombiner::visitMULHS(SDNode *N) {
2198 SDValue N0 = N->getOperand(0);
2199 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002200 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002201 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002202 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002203
Nate Begeman21158fc2005-09-01 00:19:25 +00002204 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002205 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002206 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002207 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002208 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002209 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002210 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002211 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002212 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002213 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002214 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002215
Chris Lattner10bd29f2010-12-13 08:39:01 +00002216 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2217 // plus a shift.
2218 if (VT.isSimple() && !VT.isVector()) {
2219 MVT Simple = VT.getSimpleVT();
2220 unsigned SimpleSize = Simple.getSizeInBits();
2221 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2222 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2223 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2224 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2225 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002226 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002227 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002228 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2229 }
2230 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002231
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002232 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002233}
2234
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002235SDValue DAGCombiner::visitMULHU(SDNode *N) {
2236 SDValue N0 = N->getOperand(0);
2237 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002238 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002239 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002240 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002241
Nate Begeman21158fc2005-09-01 00:19:25 +00002242 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002243 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002244 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002245 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002246 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002247 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002248 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002249 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002250 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002251
Chris Lattner10bd29f2010-12-13 08:39:01 +00002252 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2253 // plus a shift.
2254 if (VT.isSimple() && !VT.isVector()) {
2255 MVT Simple = VT.getSimpleVT();
2256 unsigned SimpleSize = Simple.getSizeInBits();
2257 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2258 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2259 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2260 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2261 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2262 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002263 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002264 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2265 }
2266 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002267
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002268 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002269}
2270
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002271/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2272/// compute two values. LoOp and HiOp give the opcodes for the two computations
2273/// that are being performed. Return true if a simplification was made.
2274///
Scott Michelcf0da6c2009-02-17 22:15:04 +00002275SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002276 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002277 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002278 bool HiExists = N->hasAnyUseOfValue(1);
2279 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002280 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002281 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002282 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Bill Wendling9b3407e2009-01-30 03:08:40 +00002283 N->op_begin(), N->getNumOperands());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002284 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002285 }
2286
2287 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002288 bool LoExists = N->hasAnyUseOfValue(0);
2289 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002290 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002291 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002292 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Bill Wendling9b3407e2009-01-30 03:08:40 +00002293 N->op_begin(), N->getNumOperands());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002294 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002295 }
2296
Evan Chengece4c682007-11-08 09:25:29 +00002297 // If both halves are used, return as it is.
2298 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002299 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002300
2301 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002302 if (LoExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002303 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Bill Wendling9b3407e2009-01-30 03:08:40 +00002304 N->op_begin(), N->getNumOperands());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002305 AddToWorkList(Lo.getNode());
2306 SDValue LoOpt = combine(Lo.getNode());
2307 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002308 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002309 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002310 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002311 }
2312
Evan Chengece4c682007-11-08 09:25:29 +00002313 if (HiExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002314 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002315 N->op_begin(), N->getNumOperands());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002316 AddToWorkList(Hi.getNode());
2317 SDValue HiOpt = combine(Hi.getNode());
2318 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002319 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002320 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002321 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002322 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002323
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002324 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002325}
2326
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002327SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2328 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002329 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002330
Chris Lattner15090e12010-12-15 06:04:19 +00002331 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002332 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002333
2334 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2335 // plus a shift.
2336 if (VT.isSimple() && !VT.isVector()) {
2337 MVT Simple = VT.getSimpleVT();
2338 unsigned SimpleSize = Simple.getSizeInBits();
2339 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2340 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2341 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2342 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2343 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2344 // Compute the high part as N1.
2345 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002346 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002347 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2348 // Compute the low part as N0.
2349 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2350 return CombineTo(N, Lo, Hi);
2351 }
2352 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002353
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002354 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002355}
2356
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002357SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2358 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002359 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002360
Chris Lattner15090e12010-12-15 06:04:19 +00002361 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002362 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002363
Chris Lattner15090e12010-12-15 06:04:19 +00002364 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2365 // plus a shift.
2366 if (VT.isSimple() && !VT.isVector()) {
2367 MVT Simple = VT.getSimpleVT();
2368 unsigned SimpleSize = Simple.getSizeInBits();
2369 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2370 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2371 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2372 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2373 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2374 // Compute the high part as N1.
2375 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002376 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002377 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2378 // Compute the low part as N0.
2379 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2380 return CombineTo(N, Lo, Hi);
2381 }
2382 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002383
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002384 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002385}
2386
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002387SDValue DAGCombiner::visitSMULO(SDNode *N) {
2388 // (smulo x, 2) -> (saddo x, x)
2389 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2390 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002391 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002392 N->getOperand(0), N->getOperand(0));
2393
2394 return SDValue();
2395}
2396
2397SDValue DAGCombiner::visitUMULO(SDNode *N) {
2398 // (umulo x, 2) -> (uaddo x, x)
2399 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2400 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002401 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002402 N->getOperand(0), N->getOperand(0));
2403
2404 return SDValue();
2405}
2406
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002407SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2408 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002409 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002410
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002411 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002412}
2413
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002414SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2415 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002416 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002417
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002418 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002419}
2420
Chris Lattner8d6fc202006-05-05 05:51:50 +00002421/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2422/// two operands of the same opcode, try to simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002423SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2424 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002425 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002426 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002427
Dan Gohmandd5286d2010-01-14 03:08:49 +00002428 // Bail early if none of these transforms apply.
2429 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2430
Chris Lattner002ee912006-05-05 06:31:05 +00002431 // For each of OP in AND/OR/XOR:
2432 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2433 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2434 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002435 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002436 //
2437 // do not sink logical op inside of a vector extend, since it may combine
2438 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002439 EVT Op0VT = N0.getOperand(0).getValueType();
2440 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002441 N0.getOpcode() == ISD::SIGN_EXTEND ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002442 // Avoid infinite looping with PromoteIntBinOp.
2443 (N0.getOpcode() == ISD::ANY_EXTEND &&
2444 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002445 (N0.getOpcode() == ISD::TRUNCATE &&
2446 (!TLI.isZExtFree(VT, Op0VT) ||
2447 !TLI.isTruncateFree(Op0VT, VT)) &&
2448 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002449 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002450 Op0VT == N1.getOperand(0).getValueType() &&
2451 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002452 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002453 N0.getOperand(0).getValueType(),
2454 N0.getOperand(0), N1.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002455 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002456 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002457 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002458
Chris Lattner5ac42932006-05-05 06:10:43 +00002459 // For each of OP in SHL/SRL/SRA/AND...
2460 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2461 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2462 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002463 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002464 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002465 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002466 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002467 N0.getOperand(0).getValueType(),
2468 N0.getOperand(0), N1.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002469 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002470 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002471 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002472 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002473
Nadav Rotemb0783502012-04-01 19:31:22 +00002474 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2475 // Only perform this optimization after type legalization and before
2476 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2477 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2478 // we don't want to undo this promotion.
2479 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2480 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002481 if ((N0.getOpcode() == ISD::BITCAST ||
2482 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2483 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002484 SDValue In0 = N0.getOperand(0);
2485 SDValue In1 = N1.getOperand(0);
2486 EVT In0Ty = In0.getValueType();
2487 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002488 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002489 // If both incoming values are integers, and the original types are the
2490 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002491 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002492 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2493 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Nadav Rotemb0783502012-04-01 19:31:22 +00002494 AddToWorkList(Op.getNode());
2495 return BC;
2496 }
2497 }
2498
2499 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2500 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2501 // If both shuffles use the same mask, and both shuffle within a single
2502 // vector, then it is worthwhile to move the swizzle after the operation.
2503 // The type-legalizer generates this pattern when loading illegal
2504 // vector types from memory. In many cases this allows additional shuffle
2505 // optimizations.
Craig Topper9c3da312012-04-09 07:19:09 +00002506 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2507 N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2508 N1.getOperand(1).getOpcode() == ISD::UNDEF) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002509 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2510 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002511
2512 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2513 "Inputs to shuffles are not the same type");
Nadav Rotemb0783502012-04-01 19:31:22 +00002514
2515 unsigned NumElts = VT.getVectorNumElements();
Nadav Rotemb0783502012-04-01 19:31:22 +00002516
2517 // Check that both shuffles use the same mask. The masks are known to be of
2518 // the same length because the result vector type is the same.
2519 bool SameMask = true;
2520 for (unsigned i = 0; i != NumElts; ++i) {
2521 int Idx0 = SVN0->getMaskElt(i);
2522 int Idx1 = SVN1->getMaskElt(i);
2523 if (Idx0 != Idx1) {
2524 SameMask = false;
2525 break;
2526 }
2527 }
2528
Craig Topper9c3da312012-04-09 07:19:09 +00002529 if (SameMask) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002530 SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
Craig Topper9c3da312012-04-09 07:19:09 +00002531 N0.getOperand(0), N1.getOperand(0));
Nadav Rotemb0783502012-04-01 19:31:22 +00002532 AddToWorkList(Op.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002533 return DAG.getVectorShuffle(VT, SDLoc(N), Op,
Craig Topper9c3da312012-04-09 07:19:09 +00002534 DAG.getUNDEF(VT), &SVN0->getMask()[0]);
Nadav Rotemb0783502012-04-01 19:31:22 +00002535 }
2536 }
Craig Topper9c3da312012-04-09 07:19:09 +00002537
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002538 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002539}
2540
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002541SDValue DAGCombiner::visitAND(SDNode *N) {
2542 SDValue N0 = N->getOperand(0);
2543 SDValue N1 = N->getOperand(1);
2544 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002545 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2546 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002547 EVT VT = N1.getValueType();
Dan Gohmane14c4082010-03-04 00:23:16 +00002548 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002549
Dan Gohmana8665142007-06-25 16:23:39 +00002550 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002551 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002552 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002553 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002554
2555 // fold (and x, 0) -> 0, vector edition
2556 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2557 return N0;
2558 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2559 return N1;
2560
2561 // fold (and x, -1) -> x, vector edition
2562 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2563 return N1;
2564 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2565 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002566 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002567
Dan Gohman06563a82007-07-03 14:03:57 +00002568 // fold (and x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002569 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002570 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00002571 // fold (and c1, c2) -> c1&c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002572 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002573 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002574 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00002575 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002576 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002577 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002578 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002579 return N0;
2580 // if (and x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002581 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002582 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002583 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002584 // reassociate and
Andrew Trickef9de2a2013-05-25 02:42:55 +00002585 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002586 if (RAND.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00002587 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002588 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002589 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002590 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002591 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002592 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002593 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2594 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002595 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002596 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002597 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002598 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002599 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002600 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002601
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002602 // Replace uses of the AND with uses of the Zero extend node.
2603 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002604
Chris Lattner49beaf42006-02-02 07:17:31 +00002605 // We actually want to replace all uses of the any_extend with the
2606 // zero_extend, to avoid duplicating things. This will later cause this
2607 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002608 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002609 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002610 }
2611 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002612 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002613 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2614 // already be zero by virtue of the width of the base type of the load.
2615 //
2616 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2617 // more cases.
2618 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2619 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2620 N0.getOpcode() == ISD::LOAD) {
2621 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2622 N0 : N0.getOperand(0) );
2623
2624 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2625 // This can be a pure constant or a vector splat, in which case we treat the
2626 // vector as a scalar and use the splat value.
2627 APInt Constant = APInt::getNullValue(1);
2628 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2629 Constant = C->getAPIntValue();
2630 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2631 APInt SplatValue, SplatUndef;
2632 unsigned SplatBitSize;
2633 bool HasAnyUndefs;
2634 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2635 SplatBitSize, HasAnyUndefs);
2636 if (IsSplat) {
2637 // Undef bits can contribute to a possible optimisation if set, so
2638 // set them.
2639 SplatValue |= SplatUndef;
2640
2641 // The splat value may be something like "0x00FFFFFF", which means 0 for
2642 // the first vector value and FF for the rest, repeating. We need a mask
2643 // that will apply equally to all members of the vector, so AND all the
2644 // lanes of the constant together.
2645 EVT VT = Vector->getValueType(0);
2646 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002647
2648 // If the splat value has been compressed to a bitlength lower
2649 // than the size of the vector lane, we need to re-expand it to
2650 // the lane size.
2651 if (BitWidth > SplatBitSize)
2652 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2653 SplatBitSize < BitWidth;
2654 SplatBitSize = SplatBitSize * 2)
2655 SplatValue |= SplatValue.shl(SplatBitSize);
2656
James Molloy862fe492012-02-20 12:02:38 +00002657 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3f40d872012-09-05 08:57:21 +00002658 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy862fe492012-02-20 12:02:38 +00002659 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2660 }
2661 }
2662
2663 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2664 // actually legal and isn't going to get expanded, else this is a false
2665 // optimisation.
2666 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2667 Load->getMemoryVT());
2668
2669 // Resize the constant to the same size as the original memory access before
2670 // extension. If it is still the AllOnesValue then this AND is completely
2671 // unneeded.
2672 Constant =
2673 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2674
2675 bool B;
2676 switch (Load->getExtensionType()) {
2677 default: B = false; break;
2678 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2679 case ISD::ZEXTLOAD:
2680 case ISD::NON_EXTLOAD: B = true; break;
2681 }
2682
2683 if (B && Constant.isAllOnesValue()) {
2684 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2685 // preserve semantics once we get rid of the AND.
2686 SDValue NewLoad(Load, 0);
2687 if (Load->getExtensionType() == ISD::EXTLOAD) {
2688 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002689 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002690 Load->getChain(), Load->getBasePtr(),
2691 Load->getOffset(), Load->getMemoryVT(),
2692 Load->getMemOperand());
2693 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002694 if (Load->getNumValues() == 3) {
2695 // PRE/POST_INC loads have 3 values.
2696 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2697 NewLoad.getValue(2) };
2698 CombineTo(Load, To, 3, true);
2699 } else {
2700 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2701 }
James Molloy862fe492012-02-20 12:02:38 +00002702 }
2703
2704 // Fold the AND away, taking care not to fold to the old load node if we
2705 // replaced it.
2706 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2707
2708 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2709 }
2710 }
Nate Begeman049b7482005-09-09 19:49:52 +00002711 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2712 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2713 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2714 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002715
Nate Begeman049b7482005-09-09 19:49:52 +00002716 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002717 LL.getValueType().isInteger()) {
Bill Wendling86171912009-01-30 20:43:18 +00002718 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002719 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002720 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002721 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002722 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002723 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002724 }
Bill Wendling86171912009-01-30 20:43:18 +00002725 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Nate Begeman049b7482005-09-09 19:49:52 +00002726 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002727 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002728 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002729 AddToWorkList(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002730 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002731 }
Bill Wendling86171912009-01-30 20:43:18 +00002732 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Nate Begeman049b7482005-09-09 19:49:52 +00002733 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002734 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002735 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002736 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002737 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002738 }
2739 }
Jim Grosbach327ccc72013-08-13 21:30:58 +00002740 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2741 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2742 Op0 == Op1 && LL.getValueType().isInteger() &&
2743 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2744 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2745 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2746 cast<ConstantSDNode>(RR)->isNullValue()))) {
2747 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2748 LL, DAG.getConstant(1, LL.getValueType()));
2749 AddToWorkList(ADDNode.getNode());
2750 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2751 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2752 }
Nate Begeman049b7482005-09-09 19:49:52 +00002753 // canonicalize equivalent to ll == rl
2754 if (LL == RR && LR == RL) {
2755 Op1 = ISD::getSetCCSwappedOperands(Op1);
2756 std::swap(RL, RR);
2757 }
2758 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00002759 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00002760 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00002761 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002762 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00002763 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2764 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00002765 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002766 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling86171912009-01-30 20:43:18 +00002767 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00002768 }
2769 }
Chris Lattner8d6fc202006-05-05 05:51:50 +00002770
Bill Wendling86171912009-01-30 20:43:18 +00002771 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00002772 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002773 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002774 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00002775 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002776
Nate Begemandc7bba92006-02-03 22:24:05 +00002777 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2778 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands13237ac2008-06-06 12:08:01 +00002779 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002780 SimplifyDemandedBits(SDValue(N, 0)))
2781 return SDValue(N, 0);
Evan Cheng166a4e62010-01-06 19:38:29 +00002782
Nate Begeman02b23c62005-10-13 03:11:28 +00002783 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greiff304a7a2008-08-28 21:40:38 +00002784 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002785 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002786 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002787 // If we zero all the possible extended bits, then we can turn this into
2788 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002789 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002790 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002791 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002792 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002793 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002794 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling86171912009-01-30 20:43:18 +00002795 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002796 MemVT, LN0->getMemOperand());
Chris Lattnerfbcd62d2006-03-01 04:03:14 +00002797 AddToWorkList(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002798 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002799 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002800 }
2801 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002802 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00002803 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00002804 N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002805 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002806 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002807 // If we zero all the possible extended bits, then we can turn this into
2808 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002809 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002810 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002811 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002812 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002813 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002814 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002815 LN0->getChain(), LN0->getBasePtr(),
2816 MemVT, LN0->getMemOperand());
Chris Lattnerfbcd62d2006-03-01 04:03:14 +00002817 AddToWorkList(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002818 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002819 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002820 }
2821 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002822
Chris Lattnerf0032b32006-02-28 06:49:37 +00002823 // fold (and (load x), 255) -> (zextload x, i8)
2824 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002825 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2826 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2827 (N0.getOpcode() == ISD::ANY_EXTEND &&
2828 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2829 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2830 LoadSDNode *LN0 = HasAnyExt
2831 ? cast<LoadSDNode>(N0.getOperand(0))
2832 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002833 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002834 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002835 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002836 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2837 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2838 EVT LoadedVT = LN0->getMemoryVT();
Duncan Sands93b66092008-06-09 11:32:28 +00002839
Evan Cheng166a4e62010-01-06 19:38:29 +00002840 if (ExtVT == LoadedVT &&
2841 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00002842 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Wesley Peck527da1b2010-11-23 03:31:01 +00002843
2844 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002845 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002846 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2847 LN0->getMemOperand());
Chris Lattner88de3842010-01-07 21:53:27 +00002848 AddToWorkList(N);
2849 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2850 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2851 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002852
Chris Lattner88de3842010-01-07 21:53:27 +00002853 // Do not change the width of a volatile load.
2854 // Do not generate loads of non-round integer types since these can
2855 // be expensive (and would be wrong if the type is not byte sized).
2856 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2857 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2858 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00002859
Chris Lattner88de3842010-01-07 21:53:27 +00002860 unsigned Alignment = LN0->getAlignment();
2861 SDValue NewPtr = LN0->getBasePtr();
2862
2863 // For big endian targets, we need to add an offset to the pointer
2864 // to load the correct bytes. For little endian systems, we merely
2865 // need to read fewer bytes from the same pointer.
2866 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00002867 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2868 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2869 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002870 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00002871 NewPtr, DAG.getConstant(PtrOff, PtrType));
2872 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00002873 }
Chris Lattner88de3842010-01-07 21:53:27 +00002874
2875 AddToWorkList(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00002876
Chris Lattner88de3842010-01-07 21:53:27 +00002877 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2878 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002879 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00002880 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00002881 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00002882 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002883 Alignment, LN0->getTBAAInfo());
Chris Lattner88de3842010-01-07 21:53:27 +00002884 AddToWorkList(N);
2885 CombineTo(LN0, Load, Load.getValue(1));
2886 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00002887 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00002888 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00002889 }
2890 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002891
Evan Chenge6a3b032012-07-17 18:54:11 +00002892 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2893 VT.getSizeInBits() <= 64) {
2894 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2895 APInt ADDC = ADDI->getAPIntValue();
2896 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2897 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2898 // immediate for an add, but it is legal if its top c2 bits are set,
2899 // transform the ADD so the immediate doesn't need to be materialized
2900 // in a register.
2901 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2902 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2903 SRLI->getZExtValue());
2904 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2905 ADDC |= Mask;
2906 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2907 SDValue NewAdd =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002908 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenge6a3b032012-07-17 18:54:11 +00002909 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2910 CombineTo(N0.getNode(), NewAdd);
2911 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2912 }
2913 }
2914 }
2915 }
2916 }
2917 }
Evan Chenge6a3b032012-07-17 18:54:11 +00002918
Tim Northover819bfb52013-08-27 13:46:45 +00002919 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2920 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2921 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2922 N0.getOperand(1), false);
2923 if (BSwap.getNode())
2924 return BSwap;
2925 }
2926
Evan Chengf1005572010-04-28 07:10:39 +00002927 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002928}
2929
Evan Cheng4c0bd962011-06-21 06:01:08 +00002930/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2931///
2932SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2933 bool DemandHighBits) {
2934 if (!LegalOperations)
2935 return SDValue();
2936
2937 EVT VT = N->getValueType(0);
2938 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2939 return SDValue();
2940 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2941 return SDValue();
2942
2943 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2944 bool LookPassAnd0 = false;
2945 bool LookPassAnd1 = false;
2946 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2947 std::swap(N0, N1);
2948 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2949 std::swap(N0, N1);
2950 if (N0.getOpcode() == ISD::AND) {
2951 if (!N0.getNode()->hasOneUse())
2952 return SDValue();
2953 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2954 if (!N01C || N01C->getZExtValue() != 0xFF00)
2955 return SDValue();
2956 N0 = N0.getOperand(0);
2957 LookPassAnd0 = true;
2958 }
2959
2960 if (N1.getOpcode() == ISD::AND) {
2961 if (!N1.getNode()->hasOneUse())
2962 return SDValue();
2963 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2964 if (!N11C || N11C->getZExtValue() != 0xFF)
2965 return SDValue();
2966 N1 = N1.getOperand(0);
2967 LookPassAnd1 = true;
2968 }
2969
2970 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2971 std::swap(N0, N1);
2972 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2973 return SDValue();
2974 if (!N0.getNode()->hasOneUse() ||
2975 !N1.getNode()->hasOneUse())
2976 return SDValue();
2977
2978 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2979 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2980 if (!N01C || !N11C)
2981 return SDValue();
2982 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2983 return SDValue();
2984
2985 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2986 SDValue N00 = N0->getOperand(0);
2987 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2988 if (!N00.getNode()->hasOneUse())
2989 return SDValue();
2990 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2991 if (!N001C || N001C->getZExtValue() != 0xFF)
2992 return SDValue();
2993 N00 = N00.getOperand(0);
2994 LookPassAnd0 = true;
2995 }
2996
2997 SDValue N10 = N1->getOperand(0);
2998 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2999 if (!N10.getNode()->hasOneUse())
3000 return SDValue();
3001 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3002 if (!N101C || N101C->getZExtValue() != 0xFF00)
3003 return SDValue();
3004 N10 = N10.getOperand(0);
3005 LookPassAnd1 = true;
3006 }
3007
3008 if (N00 != N10)
3009 return SDValue();
3010
Tim Northover819bfb52013-08-27 13:46:45 +00003011 // Make sure everything beyond the low halfword gets set to zero since the SRL
3012 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003013 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003014 if (DemandHighBits && OpSizeInBits > 16) {
3015 // If the left-shift isn't masked out then the only way this is a bswap is
3016 // if all bits beyond the low 8 are 0. In that case the entire pattern
3017 // reduces to a left shift anyway: leave it for other parts of the combiner.
3018 if (!LookPassAnd0)
3019 return SDValue();
3020
3021 // However, if the right shift isn't masked out then it might be because
3022 // it's not needed. See if we can spot that too.
3023 if (!LookPassAnd1 &&
3024 !DAG.MaskedValueIsZero(
3025 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3026 return SDValue();
3027 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003028
Andrew Trickef9de2a2013-05-25 02:42:55 +00003029 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003030 if (OpSizeInBits > 16)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003031 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003032 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3033 return Res;
3034}
3035
3036/// isBSwapHWordElement - Return true if the specified node is an element
3037/// that makes up a 32-bit packed halfword byteswap. i.e.
3038/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
Craig Topperb94011f2013-07-14 04:42:23 +00003039static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003040 if (!N.getNode()->hasOneUse())
3041 return false;
3042
3043 unsigned Opc = N.getOpcode();
3044 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3045 return false;
3046
3047 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3048 if (!N1C)
3049 return false;
3050
3051 unsigned Num;
3052 switch (N1C->getZExtValue()) {
3053 default:
3054 return false;
3055 case 0xFF: Num = 0; break;
3056 case 0xFF00: Num = 1; break;
3057 case 0xFF0000: Num = 2; break;
3058 case 0xFF000000: Num = 3; break;
3059 }
3060
3061 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3062 SDValue N0 = N.getOperand(0);
3063 if (Opc == ISD::AND) {
3064 if (Num == 0 || Num == 2) {
3065 // (x >> 8) & 0xff
3066 // (x >> 8) & 0xff0000
3067 if (N0.getOpcode() != ISD::SRL)
3068 return false;
3069 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3070 if (!C || C->getZExtValue() != 8)
3071 return false;
3072 } else {
3073 // (x << 8) & 0xff00
3074 // (x << 8) & 0xff000000
3075 if (N0.getOpcode() != ISD::SHL)
3076 return false;
3077 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3078 if (!C || C->getZExtValue() != 8)
3079 return false;
3080 }
3081 } else if (Opc == ISD::SHL) {
3082 // (x & 0xff) << 8
3083 // (x & 0xff0000) << 8
3084 if (Num != 0 && Num != 2)
3085 return false;
3086 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3087 if (!C || C->getZExtValue() != 8)
3088 return false;
3089 } else { // Opc == ISD::SRL
3090 // (x & 0xff00) >> 8
3091 // (x & 0xff000000) >> 8
3092 if (Num != 1 && Num != 3)
3093 return false;
3094 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3095 if (!C || C->getZExtValue() != 8)
3096 return false;
3097 }
3098
3099 if (Parts[Num])
3100 return false;
3101
3102 Parts[Num] = N0.getOperand(0).getNode();
3103 return true;
3104}
3105
3106/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3107/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3108/// => (rotl (bswap x), 16)
3109SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3110 if (!LegalOperations)
3111 return SDValue();
3112
3113 EVT VT = N->getValueType(0);
3114 if (VT != MVT::i32)
3115 return SDValue();
3116 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3117 return SDValue();
3118
3119 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3120 // Look for either
3121 // (or (or (and), (and)), (or (and), (and)))
3122 // (or (or (or (and), (and)), (and)), (and))
3123 if (N0.getOpcode() != ISD::OR)
3124 return SDValue();
3125 SDValue N00 = N0.getOperand(0);
3126 SDValue N01 = N0.getOperand(1);
3127
Evan Chengbf0baa92012-12-13 01:34:32 +00003128 if (N1.getOpcode() == ISD::OR &&
3129 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003130 // (or (or (and), (and)), (or (and), (and)))
3131 SDValue N000 = N00.getOperand(0);
3132 if (!isBSwapHWordElement(N000, Parts))
3133 return SDValue();
3134
3135 SDValue N001 = N00.getOperand(1);
3136 if (!isBSwapHWordElement(N001, Parts))
3137 return SDValue();
3138 SDValue N010 = N01.getOperand(0);
3139 if (!isBSwapHWordElement(N010, Parts))
3140 return SDValue();
3141 SDValue N011 = N01.getOperand(1);
3142 if (!isBSwapHWordElement(N011, Parts))
3143 return SDValue();
3144 } else {
3145 // (or (or (or (and), (and)), (and)), (and))
3146 if (!isBSwapHWordElement(N1, Parts))
3147 return SDValue();
3148 if (!isBSwapHWordElement(N01, Parts))
3149 return SDValue();
3150 if (N00.getOpcode() != ISD::OR)
3151 return SDValue();
3152 SDValue N000 = N00.getOperand(0);
3153 if (!isBSwapHWordElement(N000, Parts))
3154 return SDValue();
3155 SDValue N001 = N00.getOperand(1);
3156 if (!isBSwapHWordElement(N001, Parts))
3157 return SDValue();
3158 }
3159
3160 // Make sure the parts are all coming from the same node.
3161 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3162 return SDValue();
3163
Andrew Trickef9de2a2013-05-25 02:42:55 +00003164 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003165 SDValue(Parts[0],0));
3166
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003167 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003168 // do (x << 16) | (x >> 16).
3169 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3170 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003171 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003172 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003173 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3174 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3175 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3176 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003177}
3178
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003179SDValue DAGCombiner::visitOR(SDNode *N) {
3180 SDValue N0 = N->getOperand(0);
3181 SDValue N1 = N->getOperand(1);
3182 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003183 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3184 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003185 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003186
Dan Gohmana8665142007-06-25 16:23:39 +00003187 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003188 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003189 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003190 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003191
3192 // fold (or x, 0) -> x, vector edition
3193 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3194 return N1;
3195 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3196 return N0;
3197
3198 // fold (or x, -1) -> -1, vector edition
3199 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3200 return N0;
3201 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3202 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00003203 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003204
Dan Gohman06563a82007-07-03 14:03:57 +00003205 // fold (or x, undef) -> -1
Bob Wilson269a89f2010-06-28 23:40:25 +00003206 if (!LegalOperations &&
3207 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman9655f842009-12-03 07:11:29 +00003208 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3209 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3210 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003211 // fold (or c1, c2) -> c1|c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003212 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003213 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003214 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003215 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003216 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003217 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003218 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003219 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003220 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003221 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003222 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003223 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003224 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003225 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003226
3227 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3228 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3229 if (BSwap.getNode() != 0)
3230 return BSwap;
3231 BSwap = MatchBSwapHWordLow(N, N0, N1);
3232 if (BSwap.getNode() != 0)
3233 return BSwap;
3234
Nate Begeman22e251a2006-02-03 06:46:56 +00003235 // reassociate or
Andrew Trickef9de2a2013-05-25 02:42:55 +00003236 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003237 if (ROR.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00003238 return ROR;
3239 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003240 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003241 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003242 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003243 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003244 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3245 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3246 if (!COR.getNode())
3247 return SDValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00003248 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3249 DAG.getNode(ISD::OR, SDLoc(N0), VT,
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003250 N0.getOperand(0), N1), COR);
3251 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003252 }
Nate Begeman049b7482005-09-09 19:49:52 +00003253 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3254 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3255 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3256 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003257
Nate Begeman049b7482005-09-09 19:49:52 +00003258 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00003259 LL.getValueType().isInteger()) {
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003260 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3261 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003262 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003263 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003264 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003265 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003266 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003267 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003268 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003269 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3270 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003271 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003272 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003273 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003274 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003275 AddToWorkList(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003276 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003277 }
3278 }
3279 // canonicalize equivalent to ll == rl
3280 if (LL == RR && LR == RL) {
3281 Op1 = ISD::getSetCCSwappedOperands(Op1);
3282 std::swap(RL, RR);
3283 }
3284 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003285 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00003286 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00003287 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003288 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00003289 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3290 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00003291 getSetCCResultType(N0.getValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003292 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003293 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00003294 }
3295 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003296
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003297 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003298 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003299 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003300 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003301 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003302
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003303 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner46d710e2006-09-14 21:11:37 +00003304 if (N0.getOpcode() == ISD::AND &&
3305 N1.getOpcode() == ISD::AND &&
3306 N0.getOperand(1).getOpcode() == ISD::Constant &&
3307 N1.getOperand(1).getOpcode() == ISD::Constant &&
3308 // Don't increase # computations.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003309 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner46d710e2006-09-14 21:11:37 +00003310 // We can only do this xform if we know that bits from X that are set in C2
3311 // but not in C1 are already zero. Likewise for Y.
Dan Gohman1f372ed2008-02-25 21:11:39 +00003312 const APInt &LHSMask =
3313 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3314 const APInt &RHSMask =
3315 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003316
Dan Gohman309d3d52007-06-22 14:59:07 +00003317 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3318 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003319 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003320 N0.getOperand(0), N1.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003321 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003322 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner46d710e2006-09-14 21:11:37 +00003323 }
3324 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003325
Chris Lattner97614c82006-09-14 20:50:57 +00003326 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003327 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003328 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003329
Dan Gohman600f62b2010-06-24 14:30:44 +00003330 // Simplify the operands using demanded-bits information.
3331 if (!VT.isVector() &&
3332 SimplifyDemandedBits(SDValue(N, 0)))
3333 return SDValue(N, 0);
3334
Evan Chengf1005572010-04-28 07:10:39 +00003335 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003336}
3337
Chris Lattner97614c82006-09-14 20:50:57 +00003338/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003339static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003340 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003341 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003342 Mask = Op.getOperand(1);
3343 Op = Op.getOperand(0);
3344 } else {
3345 return false;
3346 }
3347 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003348
Chris Lattner97614c82006-09-14 20:50:57 +00003349 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3350 Shift = Op;
3351 return true;
3352 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003353
Scott Michelcf0da6c2009-02-17 22:15:04 +00003354 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003355}
3356
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003357// Return true if we can prove that, whenever Neg and Pos are both in the
3358// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003359// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3360//
3361// (or (shift1 X, Neg), (shift2 X, Pos))
3362//
3363// reduces to a rotate in direction shift2 by Pos and a rotate in direction
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003364// shift1 by Neg. The range [0, OpSize) means that we only need to consider
3365// shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003366static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003367 // If OpSize is a power of 2 then:
3368 //
3369 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3370 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3371 //
3372 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3373 // for the stronger condition:
3374 //
3375 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3376 //
3377 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3378 // we can just replace Neg with Neg' for the rest of the function.
3379 //
3380 // In other cases we check for the even stronger condition:
3381 //
3382 // Neg == OpSize - Pos [B]
3383 //
3384 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3385 // behavior if Pos == 0 (and consequently Neg == OpSize).
3386 //
3387 // We could actually use [A] whenever OpSize is a power of 2, but the
3388 // only extra cases that it would match are those uninteresting ones
3389 // where Neg and Pos are never in range at the same time. E.g. for
3390 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3391 // as well as (sub 32, Pos), but:
3392 //
3393 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3394 //
3395 // always invokes undefined behavior for 32-bit X.
3396 //
3397 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3398 unsigned LoBits = 0;
3399 if (Neg.getOpcode() == ISD::AND &&
3400 isPowerOf2_64(OpSize) &&
3401 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3402 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3403 Neg = Neg.getOperand(0);
3404 LoBits = Log2_64(OpSize);
3405 }
3406
Richard Sandiford0f264db2014-01-09 10:49:40 +00003407 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3408 if (Neg.getOpcode() != ISD::SUB)
3409 return 0;
3410 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3411 if (!NegC)
3412 return 0;
3413 SDValue NegOp1 = Neg.getOperand(1);
3414
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003415 // The condition we need is now:
3416 //
3417 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3418 //
3419 // If NegOp1 == Pos then we need:
3420 //
3421 // OpSize & Mask == NegC & Mask
3422 //
3423 // (because "x & Mask" is a truncation and distributes through subtraction).
3424 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003425 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003426 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003427 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3428 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003429 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003430 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3431 //
3432 // which, again because "x & Mask" is a truncation, becomes:
3433 //
3434 // NegC & Mask == (OpSize - PosC) & Mask
3435 // OpSize & Mask == (NegC + PosC) & Mask
3436 else if (Pos.getOpcode() == ISD::ADD &&
3437 Pos.getOperand(0) == NegOp1 &&
3438 Pos.getOperand(1).getOpcode() == ISD::Constant)
3439 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3440 NegC->getAPIntValue());
3441 else
3442 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003443
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003444 // Now we just need to check that OpSize & Mask == Width & Mask.
3445 if (LoBits)
3446 return Width.getLoBits(LoBits) == 0;
3447 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003448}
3449
Richard Sandiford95c864d2014-01-08 15:40:47 +00003450// A subroutine of MatchRotate used once we have found an OR of two opposite
3451// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3452// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3453// former being preferred if supported. InnerPos and InnerNeg are Pos and
3454// Neg with outer conversions stripped away.
3455SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3456 SDValue Neg, SDValue InnerPos,
3457 SDValue InnerNeg, unsigned PosOpcode,
3458 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003459 // fold (or (shl x, (*ext y)),
3460 // (srl x, (*ext (sub 32, y)))) ->
3461 // (rotl x, y) or (rotr x, (sub 32, y))
3462 //
3463 // fold (or (shl x, (*ext (sub 32, y))),
3464 // (srl x, (*ext y))) ->
3465 // (rotr x, y) or (rotl x, (sub 32, y))
3466 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003467 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003468 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3469 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3470 HasPos ? Pos : Neg).getNode();
3471 }
3472
3473 // fold (or (shl (*ext x), (*ext y)),
3474 // (srl (*ext x), (*ext (sub 32, y)))) ->
3475 // (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3476 //
3477 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3478 // (srl (*ext x), (*ext y))) ->
3479 // (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3480 if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3481 Shifted.getOpcode() == ISD::ANY_EXTEND) {
3482 SDValue InnerShifted = Shifted.getOperand(0);
3483 EVT InnerVT = InnerShifted.getValueType();
3484 bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3485 if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
Richard Sandiford0f264db2014-01-09 10:49:40 +00003486 if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003487 SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3488 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3489 return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3490 }
3491 }
3492 }
3493
3494 return 0;
3495}
3496
Chris Lattner97614c82006-09-14 20:50:57 +00003497// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3498// idioms for rotate, and if the target supports rotation instructions, generate
3499// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003500SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003501 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003502 EVT VT = LHS.getValueType();
Chris Lattner97614c82006-09-14 20:50:57 +00003503 if (!TLI.isTypeLegal(VT)) return 0;
3504
3505 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003506 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3507 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Chris Lattner97614c82006-09-14 20:50:57 +00003508 if (!HasROTL && !HasROTR) return 0;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003509
Chris Lattner97614c82006-09-14 20:50:57 +00003510 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003511 SDValue LHSShift; // The shift.
3512 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003513 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3514 return 0; // Not part of a rotate.
3515
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003516 SDValue RHSShift; // The shift.
3517 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003518 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3519 return 0; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003520
Chris Lattner97614c82006-09-14 20:50:57 +00003521 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3522 return 0; // Not shifting the same value.
3523
3524 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3525 return 0; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003526
Chris Lattner97614c82006-09-14 20:50:57 +00003527 // Canonicalize shl to left side in a shl/srl pair.
3528 if (RHSShift.getOpcode() == ISD::SHL) {
3529 std::swap(LHS, RHS);
3530 std::swap(LHSShift, RHSShift);
3531 std::swap(LHSMask , RHSMask );
3532 }
3533
Duncan Sands13237ac2008-06-06 12:08:01 +00003534 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003535 SDValue LHSShiftArg = LHSShift.getOperand(0);
3536 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003537 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003538 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003539
3540 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3541 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003542 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3543 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003544 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3545 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003546 if ((LShVal + RShVal) != OpSizeInBits)
3547 return 0;
3548
Craig Topper65161fa2012-09-29 06:54:22 +00003549 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3550 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003551
Chris Lattner97614c82006-09-14 20:50:57 +00003552 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003553 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003554 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003555
Gabor Greiff304a7a2008-08-28 21:40:38 +00003556 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003557 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3558 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003559 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003560 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003561 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3562 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003563 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003564
Bill Wendling35972a92009-01-30 21:14:50 +00003565 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003566 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003567
Gabor Greiff304a7a2008-08-28 21:40:38 +00003568 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003569 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003570
Chris Lattner97614c82006-09-14 20:50:57 +00003571 // If there is a mask here, and we have a variable shift, we can't be sure
3572 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003573 if (LHSMask.getNode() || RHSMask.getNode())
Chris Lattner97614c82006-09-14 20:50:57 +00003574 return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003575
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003576 // If the shift amount is sign/zext/any-extended just peel it off.
3577 SDValue LExtOp0 = LHSShiftAmt;
3578 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003579 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3580 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3581 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3582 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3583 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3584 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3585 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3586 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003587 LExtOp0 = LHSShiftAmt.getOperand(0);
3588 RExtOp0 = RHSShiftAmt.getOperand(0);
3589 }
3590
Richard Sandiford95c864d2014-01-08 15:40:47 +00003591 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3592 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3593 if (TryL)
3594 return TryL;
3595
3596 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3597 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3598 if (TryR)
3599 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003600
Chris Lattner97614c82006-09-14 20:50:57 +00003601 return 0;
3602}
3603
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003604SDValue DAGCombiner::visitXOR(SDNode *N) {
3605 SDValue N0 = N->getOperand(0);
3606 SDValue N1 = N->getOperand(1);
3607 SDValue LHS, RHS, CC;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003608 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3609 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003610 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003611
Dan Gohmana8665142007-06-25 16:23:39 +00003612 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003613 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003614 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003615 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003616
3617 // fold (xor x, 0) -> x, vector edition
3618 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3619 return N1;
3620 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3621 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003622 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003623
Evan Chengdf1690d2008-03-25 20:08:07 +00003624 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3625 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3626 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003627 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003628 if (N0.getOpcode() == ISD::UNDEF)
3629 return N0;
3630 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003631 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003632 // fold (xor c1, c2) -> c1^c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003633 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003634 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003635 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003636 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003637 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003638 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003639 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003640 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003641 // reassociate xor
Andrew Trickef9de2a2013-05-25 02:42:55 +00003642 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003643 if (RXOR.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00003644 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003645
Nate Begeman21158fc2005-09-01 00:19:25 +00003646 // fold !(x cc y) -> (x !cc y)
Dan Gohmanb72127a2008-03-13 22:13:53 +00003647 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003648 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003649 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3650 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003651
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003652 if (!LegalOperations ||
3653 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003654 switch (N0.getOpcode()) {
3655 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003656 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003657 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003658 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003659 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003660 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003661 N0.getOperand(3), NotCC);
3662 }
3663 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003664 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003665
Chris Lattner58c227b2007-09-10 21:39:07 +00003666 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003667 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003668 N0.getNode()->hasOneUse() &&
3669 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003670 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003671 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003672 DAG.getConstant(1, V.getValueType()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00003673 AddToWorkList(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003674 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003675 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003676
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003677 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003678 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003679 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003680 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003681 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3682 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003683 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3684 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greiff304a7a2008-08-28 21:40:38 +00003685 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003686 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003687 }
3688 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003689 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003690 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003691 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003692 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003693 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3694 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003695 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3696 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greiff304a7a2008-08-28 21:40:38 +00003697 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003698 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003699 }
3700 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003701 // fold (xor (and x, y), y) -> (and (not x), y)
3702 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003703 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003704 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003705 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
David Majnemer386ab7f2013-05-08 06:44:42 +00003706 AddToWorkList(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003707 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003708 }
Bill Wendling35972a92009-01-30 21:14:50 +00003709 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003710 if (N1C && N0.getOpcode() == ISD::XOR) {
3711 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3712 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3713 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003714 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003715 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003716 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003717 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003718 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003719 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003720 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003721 }
3722 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003723 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003724 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003725
Chris Lattner8d6fc202006-05-05 05:51:50 +00003726 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3727 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003728 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003729 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003730 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003731
Chris Lattner098c01e2006-04-08 04:15:24 +00003732 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00003733 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003734 SimplifyDemandedBits(SDValue(N, 0)))
3735 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003736
Evan Chengf1005572010-04-28 07:10:39 +00003737 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003738}
3739
Chris Lattner7c709a52007-12-06 07:33:36 +00003740/// visitShiftByConstant - Handle transforms common to the three shifts, when
3741/// the shift amount is a constant.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003742SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003743 assert(isa<ConstantSDNode>(N->getOperand(1)) &&
3744 "Expected an ConstantSDNode operand.");
3745 // We can't and shouldn't fold opaque constants.
3746 if (cast<ConstantSDNode>(N->getOperand(1))->isOpaque())
3747 return SDValue();
3748
Gabor Greiff304a7a2008-08-28 21:40:38 +00003749 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003750 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003751
Chris Lattner7c709a52007-12-06 07:33:36 +00003752 // We want to pull some binops through shifts, so that we have (and (shift))
3753 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3754 // thing happens with address calculations, so it's important to canonicalize
3755 // it.
3756 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00003757
Chris Lattner7c709a52007-12-06 07:33:36 +00003758 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003759 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003760 case ISD::OR:
3761 case ISD::XOR:
3762 HighBitSet = false; // We can only transform sra if the high bit is clear.
3763 break;
3764 case ISD::AND:
3765 HighBitSet = true; // We can only transform sra if the high bit is set.
3766 break;
3767 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00003768 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003769 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00003770 HighBitSet = false; // We can only transform sra if the high bit is clear.
3771 break;
3772 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003773
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003774 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00003775 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003776 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003777
3778 // FIXME: disable this unless the input to the binop is a shift by a constant.
3779 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00003780 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003781 // void foo(int *X, int i) { X[i & 1235] = 1; }
3782 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003783 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003784 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00003785 BinOpLHSVal->getOpcode() != ISD::SRA &&
3786 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3787 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003788 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003789
Owen Anderson53aa7a92009-08-10 22:56:29 +00003790 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003791
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003792 // If this is a signed shift right, and the high bit is modified by the
3793 // logical operation, do not perform the transformation. The highBitSet
3794 // boolean indicates the value of the high bit of the constant which would
3795 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00003796 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003797 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3798 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003799 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003800 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003801
Chris Lattner7c709a52007-12-06 07:33:36 +00003802 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003803 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003804 N->getValueType(0),
3805 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003806 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00003807
3808 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00003809 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00003810 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003811 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00003812
3813 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003814 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00003815}
3816
Adam Nemet67483892014-03-04 23:28:31 +00003817SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3818 assert(N->getOpcode() == ISD::TRUNCATE);
3819 assert(N->getOperand(0).getOpcode() == ISD::AND);
3820
3821 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3822 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3823 SDValue N01 = N->getOperand(0).getOperand(1);
3824
3825 if (ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01)) {
3826 EVT TruncVT = N->getValueType(0);
3827 SDValue N00 = N->getOperand(0).getOperand(0);
3828 APInt TruncC = N01C->getAPIntValue();
3829 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3830
3831 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3832 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3833 DAG.getConstant(TruncC, TruncVT));
3834 }
3835 }
3836
3837 return SDValue();
3838}
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003839SDValue DAGCombiner::visitSHL(SDNode *N) {
3840 SDValue N0 = N->getOperand(0);
3841 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003842 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3843 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003844 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00003845 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003846
Daniel Sandersa1840d22013-11-11 17:23:41 +00003847 // fold vector ops
3848 if (VT.isVector()) {
3849 SDValue FoldedVOp = SimplifyVBinOp(N);
3850 if (FoldedVOp.getNode()) return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00003851
3852 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3853 // If setcc produces all-one true value then:
3854 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3855 if (N1CV && N1CV->isConstant() &&
3856 TLI.getBooleanContents(true) ==
3857 TargetLowering::ZeroOrNegativeOneBooleanContent &&
3858 N0.getOpcode() == ISD::AND) {
3859 SDValue N00 = N0->getOperand(0);
3860 SDValue N01 = N0->getOperand(1);
3861 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3862
3863 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3864 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3865 if (C.getNode())
3866 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3867 }
3868 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00003869 }
3870
Nate Begeman21158fc2005-09-01 00:19:25 +00003871 // fold (shl c1, c2) -> c1<<c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003872 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003873 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00003874 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003875 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003876 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003877 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00003878 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00003879 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00003880 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003881 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003882 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00003883 // fold (shl undef, x) -> 0
3884 if (N0.getOpcode() == ISD::UNDEF)
3885 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00003886 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003887 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00003888 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00003889 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00003890 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00003891 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00003892 N1.getOperand(0).getOpcode() == ISD::AND) {
3893 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3894 if (NewOp1.getNode())
3895 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00003896 }
3897
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003898 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3899 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003900
3901 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Scott Michelcf0da6c2009-02-17 22:15:04 +00003902 if (N1C && N0.getOpcode() == ISD::SHL &&
Nate Begeman21158fc2005-09-01 00:19:25 +00003903 N0.getOperand(1).getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003904 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3905 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00003906 if (c1 + c2 >= OpSizeInBits)
Nate Begemand23739d2005-09-06 04:43:02 +00003907 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003908 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
Nate Begemand23739d2005-09-06 04:43:02 +00003909 DAG.getConstant(c1 + c2, N1.getValueType()));
Nate Begeman21158fc2005-09-01 00:19:25 +00003910 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00003911
3912 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3913 // For this to be valid, the second form must not preserve any of the bits
3914 // that are shifted out by the inner shift in the first form. This means
3915 // the outer shift size must be >= the number of bits added by the ext.
3916 // As a corollary, we don't care what kind of ext it is.
3917 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3918 N0.getOpcode() == ISD::ANY_EXTEND ||
3919 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3920 N0.getOperand(0).getOpcode() == ISD::SHL &&
3921 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00003922 uint64_t c1 =
Dale Johannesena94e36b2010-12-21 21:55:50 +00003923 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3924 uint64_t c2 = N1C->getZExtValue();
3925 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3926 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3927 if (c2 >= OpSizeInBits - InnerShiftSize) {
3928 if (c1 + c2 >= OpSizeInBits)
3929 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003930 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3931 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
Dale Johannesena94e36b2010-12-21 21:55:50 +00003932 N0.getOperand(0)->getOperand(0)),
3933 DAG.getConstant(c1 + c2, N1.getValueType()));
3934 }
3935 }
3936
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00003937 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3938 // Only fold this if the inner zext has no other uses to avoid increasing
3939 // the total number of instructions.
3940 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3941 N0.getOperand(0).getOpcode() == ISD::SRL &&
3942 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3943 uint64_t c1 =
3944 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3945 if (c1 < VT.getSizeInBits()) {
3946 uint64_t c2 = N1C->getZExtValue();
3947 if (c1 == c2) {
3948 SDValue NewOp0 = N0.getOperand(0);
3949 EVT CountVT = NewOp0.getOperand(1).getValueType();
3950 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
3951 NewOp0, DAG.getConstant(c2, CountVT));
Andrea Di Biagio561badf2013-10-17 11:02:58 +00003952 AddToWorkList(NewSHL.getNode());
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00003953 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
3954 }
3955 }
3956 }
3957
Eli Friedman1877ac92011-06-09 22:14:44 +00003958 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3959 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00003960 // Only fold this if the inner shift has no other uses -- if it does, folding
3961 // this will increase the total number of instructions.
3962 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
Nate Begeman21158fc2005-09-01 00:19:25 +00003963 N0.getOperand(1).getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003964 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
Evan Chenga7bb55e2009-07-21 05:40:15 +00003965 if (c1 < VT.getSizeInBits()) {
3966 uint64_t c2 = N1C->getZExtValue();
Eli Friedman1877ac92011-06-09 22:14:44 +00003967 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3968 VT.getSizeInBits() - c1);
3969 SDValue Shift;
3970 if (c2 > c1) {
3971 Mask = Mask.shl(c2-c1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003972 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
Eli Friedman1877ac92011-06-09 22:14:44 +00003973 DAG.getConstant(c2-c1, N1.getValueType()));
3974 } else {
3975 Mask = Mask.lshr(c1-c2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003976 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
Eli Friedman1877ac92011-06-09 22:14:44 +00003977 DAG.getConstant(c1-c2, N1.getValueType()));
3978 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00003979 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
Eli Friedman1877ac92011-06-09 22:14:44 +00003980 DAG.getConstant(Mask, VT));
Evan Chenga7bb55e2009-07-21 05:40:15 +00003981 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003982 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003983 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00003984 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3985 SDValue HiBitsMask =
3986 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3987 VT.getSizeInBits() -
3988 N1C->getZExtValue()),
3989 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003990 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00003991 HiBitsMask);
3992 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003993
Evan Chengf1bd5fc2010-04-17 06:13:15 +00003994 if (N1C) {
3995 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3996 if (NewSHL.getNode())
3997 return NewSHL;
3998 }
3999
Evan Chengf1005572010-04-28 07:10:39 +00004000 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004001}
4002
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004003SDValue DAGCombiner::visitSRA(SDNode *N) {
4004 SDValue N0 = N->getOperand(0);
4005 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004006 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4007 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004008 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004009 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004010
Daniel Sandersa1840d22013-11-11 17:23:41 +00004011 // fold vector ops
4012 if (VT.isVector()) {
4013 SDValue FoldedVOp = SimplifyVBinOp(N);
4014 if (FoldedVOp.getNode()) return FoldedVOp;
4015 }
4016
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004017 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004018 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004019 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004020 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004021 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004022 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004023 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004024 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004025 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004026 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004027 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004028 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004029 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004030 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004031 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004032 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4033 // sext_inreg.
4034 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004035 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004036 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4037 if (VT.isVector())
4038 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4039 ExtVT, VT.getVectorNumElements());
4040 if ((!LegalOperations ||
4041 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004042 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004043 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004044 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004045
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004046 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004047 if (N1C && N0.getOpcode() == ISD::SRA) {
4048 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004049 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Dan Gohman1d459e42009-12-11 21:31:27 +00004050 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004051 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0f8a7272006-02-28 06:23:04 +00004052 DAG.getConstant(Sum, N1C->getValueType(0)));
4053 }
4054 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004055
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004056 // fold (sra (shl X, m), (sub result_size, n))
4057 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004058 // result_size - n != m.
4059 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004060 // code.
Christopher Lamb8fe91092008-03-19 08:30:06 +00004061 if (N0.getOpcode() == ISD::SHL) {
4062 // Get the two constanst of the shifts, CN0 = m, CN = n.
4063 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4064 if (N01C && N1C) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004065 // Determine what the truncate's result bitsize and type would be.
Owen Anderson53aa7a92009-08-10 22:56:29 +00004066 EVT TruncVT =
Eric Christopherd9e8eac2010-12-09 04:48:06 +00004067 EVT::getIntegerVT(*DAG.getContext(),
4068 OpSizeInBits - N1C->getZExtValue());
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004069 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004070 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004071
Scott Michelcf0da6c2009-02-17 22:15:04 +00004072 // If the shift is not a no-op (in which case this should be just a sign
4073 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004074 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004075 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004076 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004077 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4078 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004079 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004080
Owen Andersonb2c80da2011-02-25 21:41:48 +00004081 SDValue Amt = DAG.getConstant(ShiftAmt,
4082 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004083 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004084 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004085 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004086 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004087 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004088 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004089 }
4090 }
4091 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004092
Duncan Sands3ed76882009-02-01 18:06:53 +00004093 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004094 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004095 N1.getOperand(0).getOpcode() == ISD::AND) {
4096 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4097 if (NewOp1.getNode())
4098 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004099 }
4100
Benjamin Kramer946e1522011-01-30 16:38:43 +00004101 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
4102 // if c1 is equal to the number of bits the trunc removes
4103 if (N0.getOpcode() == ISD::TRUNCATE &&
4104 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4105 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4106 N0.getOperand(0).hasOneUse() &&
4107 N0.getOperand(0).getOperand(1).hasOneUse() &&
4108 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
4109 EVT LargeVT = N0.getOperand(0).getValueType();
4110 ConstantSDNode *LargeShiftAmt =
4111 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
4112
4113 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
4114 LargeShiftAmt->getZExtValue()) {
4115 SDValue Amt =
4116 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00004117 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004118 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
Benjamin Kramer946e1522011-01-30 16:38:43 +00004119 N0.getOperand(0).getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004120 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
Benjamin Kramer946e1522011-01-30 16:38:43 +00004121 }
4122 }
4123
Scott Michelcf0da6c2009-02-17 22:15:04 +00004124 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004125 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4126 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004127
4128
Nate Begeman21158fc2005-09-01 00:19:25 +00004129 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004130 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004131 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004132
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004133 if (N1C) {
4134 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
4135 if (NewSRA.getNode())
4136 return NewSRA;
4137 }
4138
Evan Chengf1005572010-04-28 07:10:39 +00004139 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004140}
4141
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004142SDValue DAGCombiner::visitSRL(SDNode *N) {
4143 SDValue N0 = N->getOperand(0);
4144 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004145 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4146 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004147 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004148 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004149
Daniel Sandersa1840d22013-11-11 17:23:41 +00004150 // fold vector ops
4151 if (VT.isVector()) {
4152 SDValue FoldedVOp = SimplifyVBinOp(N);
4153 if (FoldedVOp.getNode()) return FoldedVOp;
4154 }
4155
Nate Begeman21158fc2005-09-01 00:19:25 +00004156 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004157 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004158 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004159 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004160 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004161 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004162 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004163 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004164 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004165 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004166 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004167 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004168 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004169 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004170 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004171 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004172
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004173 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Scott Michelcf0da6c2009-02-17 22:15:04 +00004174 if (N1C && N0.getOpcode() == ISD::SRL &&
Nate Begeman21158fc2005-09-01 00:19:25 +00004175 N0.getOperand(1).getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004176 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4177 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004178 if (c1 + c2 >= OpSizeInBits)
Nate Begemand23739d2005-09-06 04:43:02 +00004179 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004180 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
Nate Begemand23739d2005-09-06 04:43:02 +00004181 DAG.getConstant(c1 + c2, N1.getValueType()));
Nate Begeman21158fc2005-09-01 00:19:25 +00004182 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004183
Dale Johannesencd538af2010-12-17 21:45:49 +00004184 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004185 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4186 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004187 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004188 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004189 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4190 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004191 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4192 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004193 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004194 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004195 if (c1 + OpSizeInBits == InnerShiftSize) {
4196 if (c1 + c2 >= InnerShiftSize)
4197 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004198 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4199 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004200 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004201 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004202 }
4203 }
4204
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004205 // fold (srl (shl x, c), c) -> (and x, cst2)
4206 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4207 N0.getValueSizeInBits() <= 64) {
4208 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004209 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004210 DAG.getConstant(~0ULL >> ShAmt, VT));
4211 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004212
Michael Liao62ebfd82013-06-21 18:45:27 +00004213 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004214 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4215 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004216 EVT SmallVT = N0.getOperand(0).getValueType();
Dan Gohmaneffb8942008-09-12 16:56:44 +00004217 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
Dale Johannesen84935752009-02-06 23:05:02 +00004218 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004219
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004220 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004221 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004222 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004223 N0.getOperand(0),
4224 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004225 AddToWorkList(SmallShift.getNode());
Michael Liao62ebfd82013-06-21 18:45:27 +00004226 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4227 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4228 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4229 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004230 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004231 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004232
Chris Lattner2e33fb42006-10-12 20:23:19 +00004233 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4234 // bit, which is unmodified by sra.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004235 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004236 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004237 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004238 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004239
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004240 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004241 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Duncan Sands13237ac2008-06-06 12:08:01 +00004242 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004243 APInt KnownZero, KnownOne;
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004244 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004245
Chris Lattner49932492006-04-02 06:11:11 +00004246 // If any of the input bits are KnownOne, then the input couldn't be all
4247 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004248 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004249
Chris Lattner49932492006-04-02 06:11:11 +00004250 // If all of the bits input the to ctlz node are known to be zero, then
4251 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004252 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004253 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004254
Chris Lattner49932492006-04-02 06:11:11 +00004255 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004256 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004257 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004258 // could be set on input to the CTLZ node. If this bit is set, the SRL
4259 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4260 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004261 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004262 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004263
Chris Lattner49932492006-04-02 06:11:11 +00004264 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004265 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004266 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +00004267 AddToWorkList(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004268 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004269
Andrew Trickef9de2a2013-05-25 02:42:55 +00004270 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004271 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004272 }
4273 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004274
Duncan Sands3ed76882009-02-01 18:06:53 +00004275 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004276 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004277 N1.getOperand(0).getOpcode() == ISD::AND) {
4278 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4279 if (NewOp1.getNode())
4280 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004281 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004282
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004283 // fold operands of srl based on knowledge that the low bits are not
4284 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004285 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4286 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004287
Evan Chengb175de62009-12-18 21:31:31 +00004288 if (N1C) {
4289 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4290 if (NewSRL.getNode())
4291 return NewSRL;
4292 }
4293
Dan Gohman600f62b2010-06-24 14:30:44 +00004294 // Attempt to convert a srl of a load into a narrower zero-extending load.
4295 SDValue NarrowLoad = ReduceLoadWidth(N);
4296 if (NarrowLoad.getNode())
4297 return NarrowLoad;
4298
Evan Chengb175de62009-12-18 21:31:31 +00004299 // Here is a common situation. We want to optimize:
4300 //
4301 // %a = ...
4302 // %b = and i32 %a, 2
4303 // %c = srl i32 %b, 1
4304 // brcond i32 %c ...
4305 //
4306 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004307 //
Evan Chengb175de62009-12-18 21:31:31 +00004308 // %a = ...
4309 // %b = and %a, 2
4310 // %c = setcc eq %b, 0
4311 // brcond %c ...
4312 //
4313 // However when after the source operand of SRL is optimized into AND, the SRL
4314 // itself may not be optimized further. Look for it and add the BRCOND into
4315 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004316 if (N->hasOneUse()) {
4317 SDNode *Use = *N->use_begin();
4318 if (Use->getOpcode() == ISD::BRCOND)
4319 AddToWorkList(Use);
4320 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4321 // Also look pass the truncate.
4322 Use = *Use->use_begin();
4323 if (Use->getOpcode() == ISD::BRCOND)
4324 AddToWorkList(Use);
4325 }
4326 }
Evan Chengb175de62009-12-18 21:31:31 +00004327
Evan Chengf1005572010-04-28 07:10:39 +00004328 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004329}
4330
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004331SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4332 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004333 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004334
4335 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004336 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004337 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004338 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004339}
4340
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004341SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4342 SDValue N0 = N->getOperand(0);
4343 EVT VT = N->getValueType(0);
4344
4345 // fold (ctlz_zero_undef c1) -> c2
4346 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004347 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004348 return SDValue();
4349}
4350
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004351SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4352 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004353 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004354
Nate Begeman21158fc2005-09-01 00:19:25 +00004355 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004356 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004357 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004358 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004359}
4360
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004361SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4362 SDValue N0 = N->getOperand(0);
4363 EVT VT = N->getValueType(0);
4364
4365 // fold (cttz_zero_undef c1) -> c2
4366 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004367 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004368 return SDValue();
4369}
4370
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004371SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4372 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004373 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004374
Nate Begeman21158fc2005-09-01 00:19:25 +00004375 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004376 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004377 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004378 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004379}
4380
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004381SDValue DAGCombiner::visitSELECT(SDNode *N) {
4382 SDValue N0 = N->getOperand(0);
4383 SDValue N1 = N->getOperand(1);
4384 SDValue N2 = N->getOperand(2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004385 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4386 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4387 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004388 EVT VT = N->getValueType(0);
4389 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004390
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004391 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004392 if (N1 == N2)
4393 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004394 // fold (select true, X, Y) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004395 if (N0C && !N0C->isNullValue())
4396 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004397 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004398 if (N0C && N0C->isNullValue())
4399 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004400 // fold (select C, 1, X) -> (or C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004401 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004402 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004403 // fold (select C, 0, 1) -> (xor C, 1)
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004404 if (VT.isInteger() &&
Owen Anderson9f944592009-08-11 20:47:22 +00004405 (VT0 == MVT::i1 ||
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004406 (VT0.isInteger() &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00004407 TLI.getBooleanContents(false) ==
4408 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004409 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004410 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004411 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004412 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004413 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004414 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004415 N0, DAG.getConstant(1, VT0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00004416 AddToWorkList(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004417 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004418 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4419 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004420 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004421 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004422 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004423 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilsonc5890052009-01-22 17:39:32 +00004424 AddToWorkList(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004425 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004426 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004427 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004428 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004429 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilsonc5890052009-01-22 17:39:32 +00004430 AddToWorkList(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004431 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004432 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004433 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004434 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004435 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004436 // fold (select X, X, Y) -> (or X, Y)
4437 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004438 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004439 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004440 // fold (select X, Y, X) -> (and X, Y)
4441 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004442 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004443 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004444
Chris Lattner6c14c352005-10-18 06:04:22 +00004445 // If we can fold this based on the true/false value, do so.
4446 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004447 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004448
Nate Begemanc760f802005-09-19 22:34:01 +00004449 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004450 if (N0.getOpcode() == ISD::SETCC) {
Nate Begeman7e7f4392006-02-01 07:19:44 +00004451 // FIXME:
Owen Anderson9f944592009-08-11 20:47:22 +00004452 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
Nate Begeman7e7f4392006-02-01 07:19:44 +00004453 // having to say they don't support SELECT_CC on every type the DAG knows
4454 // about, since there is no way to mark an opcode illegal at all value types
Owen Anderson9f944592009-08-11 20:47:22 +00004455 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
Dan Gohman3f323842009-08-02 16:19:38 +00004456 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004457 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004458 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004459 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004460 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004461 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004462
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004463 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004464}
4465
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004466static
4467std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4468 SDLoc DL(N);
4469 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004470 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004471
4472 // Split the inputs.
4473 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004474 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4475 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004476
4477 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4478 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4479
4480 return std::make_pair(Lo, Hi);
4481}
4482
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004483SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4484 SDValue N0 = N->getOperand(0);
4485 SDValue N1 = N->getOperand(1);
4486 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004487 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004488
4489 // Canonicalize integer abs.
4490 // vselect (setg[te] X, 0), X, -X ->
4491 // vselect (setgt X, -1), X, -X ->
4492 // vselect (setl[te] X, 0), -X, X ->
4493 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4494 if (N0.getOpcode() == ISD::SETCC) {
4495 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4496 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4497 bool isAbs = false;
4498 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4499
4500 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4501 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4502 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4503 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4504 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4505 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4506 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4507
4508 if (isAbs) {
4509 EVT VT = LHS.getValueType();
4510 SDValue Shift = DAG.getNode(
4511 ISD::SRA, DL, VT, LHS,
4512 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4513 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4514 AddToWorkList(Shift.getNode());
4515 AddToWorkList(Add.getNode());
4516 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4517 }
4518 }
4519
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004520 // If the VSELECT result requires splitting and the mask is provided by a
4521 // SETCC, then split both nodes and its operands before legalization. This
4522 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4523 // and enables future optimizations (e.g. min/max pattern matching on X86).
4524 if (N0.getOpcode() == ISD::SETCC) {
4525 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004526
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004527 // Check if any splitting is required.
4528 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4529 TargetLowering::TypeSplitVector)
4530 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004531
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004532 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004533 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4534 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4535 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004536
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004537 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4538 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004539
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004540 // Add the new VSELECT nodes to the work list in case they need to be split
4541 // again.
4542 AddToWorkList(Lo.getNode());
4543 AddToWorkList(Hi.getNode());
4544
4545 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004546 }
4547
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00004548 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4549 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4550 return N1;
4551 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4552 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4553 return N2;
4554
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004555 return SDValue();
4556}
4557
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004558SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4559 SDValue N0 = N->getOperand(0);
4560 SDValue N1 = N->getOperand(1);
4561 SDValue N2 = N->getOperand(2);
4562 SDValue N3 = N->getOperand(3);
4563 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00004564 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004565
Nate Begemanc760f802005-09-19 22:34:01 +00004566 // fold select_cc lhs, rhs, x, x, cc -> x
4567 if (N2 == N3)
4568 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00004569
Chris Lattner8b68dec2006-09-20 06:19:26 +00004570 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00004571 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004572 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00004573 if (SCC.getNode()) {
4574 AddToWorkList(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00004575
Stephen Lin605207f2013-06-15 04:03:33 +00004576 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4577 if (!SCCC->isNullValue())
4578 return N2; // cond always true -> true val
4579 else
4580 return N3; // cond always false -> false val
4581 }
4582
4583 // Fold to a simpler select_cc
4584 if (SCC.getOpcode() == ISD::SETCC)
4585 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4586 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4587 SCC.getOperand(2));
Chris Lattner8b68dec2006-09-20 06:19:26 +00004588 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004589
Chris Lattner6c14c352005-10-18 06:04:22 +00004590 // If we can fold this based on the true/false value, do so.
4591 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004592 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00004593
Nate Begemanc760f802005-09-19 22:34:01 +00004594 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00004595 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004596}
4597
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004598SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00004599 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00004600 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004601 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00004602}
4603
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004604// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4605// dag node into a ConstantSDNode or a build_vector of constants.
4606// This function is called by the DAGCombiner when visiting sext/zext/aext
4607// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4608// Vector extends are not folded if operations are legal; this is to
4609// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004610static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4611 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004612 bool LegalOperations) {
4613 unsigned Opcode = N->getOpcode();
4614 SDValue N0 = N->getOperand(0);
4615 EVT VT = N->getValueType(0);
4616
4617 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4618 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4619
4620 // fold (sext c1) -> c1
4621 // fold (zext c1) -> c1
4622 // fold (aext c1) -> c1
4623 if (isa<ConstantSDNode>(N0))
4624 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4625
4626 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4627 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4628 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004629 EVT SVT = VT.getScalarType();
4630 if (!(VT.isVector() &&
4631 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004632 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4633 return 0;
4634
4635 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004636 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004637 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4638 unsigned ShAmt = VTBits - EVTBits;
4639 SmallVector<SDValue, 8> Elts;
4640 unsigned NumElts = N0->getNumOperands();
4641 SDLoc DL(N);
4642
4643 for (unsigned i=0; i != NumElts; ++i) {
4644 SDValue Op = N0->getOperand(i);
4645 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004646 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004647 continue;
4648 }
4649
4650 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4651 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4652 if (Opcode == ISD::SIGN_EXTEND)
4653 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004654 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004655 else
4656 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004657 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004658 }
4659
4660 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode();
4661}
4662
Evan Chenge106e2f2007-10-29 19:58:20 +00004663// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00004664// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00004665// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00004666// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004667static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00004668 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00004669 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00004670 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004671 bool HasCopyToRegUses = false;
4672 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00004673 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4674 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00004675 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00004676 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00004677 if (User == N)
4678 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00004679 if (UI.getUse().getResNo() != N0.getResNo())
4680 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004681 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00004682 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004683 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4684 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4685 // Sign bits will be lost after a zext.
4686 return false;
4687 bool Add = false;
4688 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004689 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00004690 if (UseOp == N0)
4691 continue;
4692 if (!isa<ConstantSDNode>(UseOp))
4693 return false;
4694 Add = true;
4695 }
4696 if (Add)
4697 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00004698 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004699 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00004700 // If truncates aren't free and there are users we can't
4701 // extend, it isn't worthwhile.
4702 if (!isTruncFree)
4703 return false;
4704 // Remember if this value is live-out.
4705 if (User->getOpcode() == ISD::CopyToReg)
4706 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00004707 }
4708
4709 if (HasCopyToRegUses) {
4710 bool BothLiveOut = false;
4711 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4712 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00004713 SDUse &Use = UI.getUse();
4714 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4715 BothLiveOut = true;
4716 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00004717 }
4718 }
4719 if (BothLiveOut)
4720 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00004721 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00004722 return ExtendNodes.size();
4723 }
4724 return true;
4725}
4726
Craig Toppere0b71182013-07-13 07:43:40 +00004727void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004728 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004729 ISD::NodeType ExtType) {
4730 // Extend SetCC uses if necessary.
4731 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4732 SDNode *SetCC = SetCCs[i];
4733 SmallVector<SDValue, 4> Ops;
4734
4735 for (unsigned j = 0; j != 2; ++j) {
4736 SDValue SOp = SetCC->getOperand(j);
4737 if (SOp == Trunc)
4738 Ops.push_back(ExtLoad);
4739 else
4740 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4741 }
4742
4743 Ops.push_back(SetCC->getOperand(2));
4744 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4745 &Ops[0], Ops.size()));
4746 }
4747}
4748
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004749SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4750 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004751 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004752
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004753 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4754 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004755 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004756
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004757 // fold (sext (sext x)) -> (sext x)
4758 // fold (sext (aext x)) -> (sext x)
4759 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004760 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004761 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00004762
Chris Lattnerfce448f2007-02-26 03:13:59 +00004763 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004764 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4765 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00004766 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4767 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00004768 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4769 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00004770 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00004771 // CombineTo deleted the truncate, if needed, but not what's under it.
4772 AddToWorkList(oye);
4773 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00004774 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00004775 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00004776
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004777 // See if the value being truncated is already sign extended. If so, just
4778 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004779 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004780 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4781 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4782 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00004783 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004784
Chris Lattnerfce448f2007-02-26 03:13:59 +00004785 if (OpBits == DestBits) {
4786 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4787 // bits, it is already ready.
4788 if (NumSignBits > DestBits-MidBits)
4789 return Op;
4790 } else if (OpBits < DestBits) {
4791 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4792 // bits, just sext from i32.
4793 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004794 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00004795 } else {
4796 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4797 // bits, just truncate to i32.
4798 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004799 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00004800 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004801
Chris Lattnerfce448f2007-02-26 03:13:59 +00004802 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004803 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4804 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004805 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004806 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004807 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004808 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4809 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004810 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00004811 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00004812 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004813
Evan Chengbce7c472005-12-14 02:19:23 +00004814 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00004815 // None of the supported targets knows how to perform load and sign extend
Nadav Rotemb0091302011-02-27 07:40:43 +00004816 // on vectors in one instruction. We only perform this transformation on
4817 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00004818 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004819 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00004820 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004821 bool DoXform = true;
4822 SmallVector<SDNode*, 4> SetCCs;
4823 if (!N0.hasOneUse())
4824 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4825 if (DoXform) {
4826 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004827 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00004828 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004829 LN0->getBasePtr(), N0.getValueType(),
4830 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00004831 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004832 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00004833 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00004834 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004835 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004836 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004837 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00004838 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00004839 }
Chris Lattner7dac1082005-12-14 19:05:06 +00004840
4841 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4842 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00004843 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4844 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00004845 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00004846 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004847 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00004848 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004849 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00004850 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004851 LN0->getBasePtr(), MemVT,
4852 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00004853 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00004854 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004855 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00004856 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00004857 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004858 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00004859 }
Chris Lattner7dac1082005-12-14 19:05:06 +00004860 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004861
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004862 // fold (sext (and/or/xor (load x), cst)) ->
4863 // (and/or/xor (sextload x), (sext cst))
4864 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4865 N0.getOpcode() == ISD::XOR) &&
4866 isa<LoadSDNode>(N0.getOperand(0)) &&
4867 N0.getOperand(1).getOpcode() == ISD::Constant &&
4868 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4869 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4870 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4871 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4872 bool DoXform = true;
4873 SmallVector<SDNode*, 4> SetCCs;
4874 if (!N0.hasOneUse())
4875 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4876 SetCCs, TLI);
4877 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004878 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004879 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004880 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004881 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004882 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4883 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004884 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004885 ExtLoad, DAG.getConstant(Mask, VT));
4886 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004887 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004888 N0.getOperand(0).getValueType(), ExtLoad);
4889 CombineTo(N, And);
4890 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004891 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004892 ISD::SIGN_EXTEND);
4893 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4894 }
4895 }
4896 }
4897
Chris Lattner65786b02007-04-11 05:32:27 +00004898 if (N0.getOpcode() == ISD::SETCC) {
Chris Lattner4ac60732009-07-08 00:31:33 +00004899 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00004900 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00004901 if (VT.isVector() && !LegalOperations &&
Stephen Lincfe7f352013-07-08 00:37:03 +00004902 TLI.getBooleanContents(true) ==
Owen Anderson2d4cca32013-04-23 18:09:28 +00004903 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Dan Gohmane82c25e2010-04-30 17:19:19 +00004904 EVT N0VT = N0.getOperand(0).getValueType();
Nadav Rotem9d376b62012-04-11 08:26:11 +00004905 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4906 // of the same size as the compared operands. Only optimize sext(setcc())
4907 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00004908 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00004909
4910 // We know that the # elements of the results is the same as the
4911 // # elements of the compare (and the # elements of the compare result
4912 // for that matter). Check to see that they are the same size. If so,
4913 // we know that the element size of the sext'd result matches the
4914 // element size of the compare operands.
4915 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004916 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00004917 N0.getOperand(1),
4918 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00004919
Dan Gohmane82c25e2010-04-30 17:19:19 +00004920 // If the desired elements are smaller or larger than the source
4921 // elements we can use a matching integer vector type and then
4922 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00004923 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00004924 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004925 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00004926 N0.getOperand(0), N0.getOperand(1),
4927 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004928 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00004929 }
Chris Lattner4ac60732009-07-08 00:31:33 +00004930 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00004931
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00004932 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00004933 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004934 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00004935 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004936 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00004937 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004938 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00004939 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00004940 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00004941
4942 if (!VT.isVector()) {
4943 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
4944 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
4945 SDLoc DL(N);
4946 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4947 SDValue SetCC = DAG.getSetCC(DL,
4948 SetCCVT,
4949 N0.getOperand(0), N0.getOperand(1), CC);
4950 EVT SelectVT = getSetCCResultType(VT);
4951 return DAG.getSelect(DL, VT,
4952 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
4953 NegOne, DAG.getConstant(0, VT));
4954
4955 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00004956 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004957 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004958
Dan Gohman3eb10f72008-04-28 16:58:24 +00004959 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004960 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00004961 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004962 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004963
Evan Chengf1005572010-04-28 07:10:39 +00004964 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004965}
4966
Rafael Espindola8f62b322012-04-09 16:06:03 +00004967// isTruncateOf - If N is a truncate of some other value, return true, record
4968// the value being truncated in Op and which of Op's bits are zero in KnownZero.
4969// This function computes KnownZero to avoid a duplicated call to
4970// ComputeMaskedBits in the caller.
4971static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4972 APInt &KnownZero) {
4973 APInt KnownOne;
4974 if (N->getOpcode() == ISD::TRUNCATE) {
4975 Op = N->getOperand(0);
4976 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4977 return true;
4978 }
4979
4980 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4981 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4982 return false;
4983
4984 SDValue Op0 = N->getOperand(0);
4985 SDValue Op1 = N->getOperand(1);
4986 assert(Op0.getValueType() == Op1.getValueType());
4987
4988 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4989 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00004990 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00004991 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00004992 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00004993 Op = Op0;
4994 else
4995 return false;
4996
4997 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4998
4999 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5000 return false;
5001
5002 return true;
5003}
5004
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005005SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5006 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005007 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005008
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005009 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5010 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005011 return SDValue(Res, 0);
5012
Nate Begeman21158fc2005-09-01 00:19:25 +00005013 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005014 // fold (zext (aext x)) -> (zext x)
5015 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005016 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005017 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00005018
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005019 // fold (zext (truncate x)) -> (zext x) or
5020 // (zext (truncate x)) -> (truncate x)
5021 // This is valid when the truncated bits of x are already zero.
5022 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005023 SDValue Op;
5024 APInt KnownZero;
5025 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5026 APInt TruncatedBits =
5027 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5028 APInt(Op.getValueSizeInBits(), 0) :
5029 APInt::getBitsSet(Op.getValueSizeInBits(),
5030 N0.getValueSizeInBits(),
5031 std::min(Op.getValueSizeInBits(),
5032 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00005033 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005034 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005035 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005036 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005037 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005038
5039 return Op;
5040 }
5041 }
5042
Evan Cheng464dc9b2007-03-22 01:54:19 +00005043 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5044 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00005045 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005046 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5047 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005048 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5049 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005050 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005051 // CombineTo deleted the truncate, if needed, but not what's under it.
5052 AddToWorkList(oye);
5053 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005054 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005055 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005056 }
5057
Chris Lattnera31f0a62006-09-21 06:00:20 +00005058 // fold (zext (truncate x)) -> (and x, mask)
5059 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00005060 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005061
5062 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5063 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5064 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5065 if (NarrowLoad.getNode()) {
5066 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5067 if (NarrowLoad.getNode() != N0.getNode()) {
5068 CombineTo(N0.getNode(), NarrowLoad);
5069 // CombineTo deleted the truncate, if needed, but not what's under it.
5070 AddToWorkList(oye);
5071 }
5072 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5073 }
5074
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005075 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005076 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005077 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Elena Demikhovsky8d7e56c2012-04-22 09:39:03 +00005078 AddToWorkList(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00005079 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005080 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Elena Demikhovsky8d7e56c2012-04-22 09:39:03 +00005081 AddToWorkList(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005082 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005083 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00005084 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005085 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005086
Dan Gohmanad3e5492009-04-08 00:15:30 +00005087 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5088 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005089 if (N0.getOpcode() == ISD::AND &&
5090 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005091 N0.getOperand(1).getOpcode() == ISD::Constant &&
5092 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5093 N0.getValueType()) ||
5094 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005095 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005096 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005097 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005098 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005099 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005100 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005101 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005102 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005103 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005104 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005105 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005106
Evan Chengbce7c472005-12-14 02:19:23 +00005107 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005108 // None of the supported targets knows how to perform load and vector_zext
Nadav Rotemb0091302011-02-27 07:40:43 +00005109 // on vectors in one instruction. We only perform this transformation on
5110 // scalars.
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005111 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005112 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005113 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005114 bool DoXform = true;
5115 SmallVector<SDNode*, 4> SetCCs;
5116 if (!N0.hasOneUse())
5117 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5118 if (DoXform) {
5119 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005120 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005121 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005122 LN0->getBasePtr(), N0.getValueType(),
5123 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005124 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005125 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005126 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005127 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005128
Andrew Trickef9de2a2013-05-25 02:42:55 +00005129 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005130 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005131 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005132 }
Evan Chengbce7c472005-12-14 02:19:23 +00005133 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005134
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005135 // fold (zext (and/or/xor (load x), cst)) ->
5136 // (and/or/xor (zextload x), (zext cst))
5137 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5138 N0.getOpcode() == ISD::XOR) &&
5139 isa<LoadSDNode>(N0.getOperand(0)) &&
5140 N0.getOperand(1).getOpcode() == ISD::Constant &&
5141 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5142 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5143 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5144 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
5145 bool DoXform = true;
5146 SmallVector<SDNode*, 4> SetCCs;
5147 if (!N0.hasOneUse())
5148 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5149 SetCCs, TLI);
5150 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005151 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005152 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005153 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005154 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005155 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5156 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005157 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005158 ExtLoad, DAG.getConstant(Mask, VT));
5159 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005160 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005161 N0.getOperand(0).getValueType(), ExtLoad);
5162 CombineTo(N, And);
5163 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005164 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005165 ISD::ZERO_EXTEND);
5166 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5167 }
5168 }
5169 }
5170
Chris Lattner7dac1082005-12-14 19:05:06 +00005171 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5172 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005173 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5174 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005175 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005176 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005177 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005178 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005179 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005180 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005181 LN0->getBasePtr(), MemVT,
5182 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005183 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005184 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005185 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005186 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005187 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005188 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005189 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005190 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005191
Chris Lattner65786b02007-04-11 05:32:27 +00005192 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005193 if (!LegalOperations && VT.isVector() &&
5194 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005195 EVT N0VT = N0.getOperand(0).getValueType();
5196 if (getSetCCResultType(N0VT) == N0.getValueType())
5197 return SDValue();
5198
Evan Chengabd0ad52010-05-19 01:08:17 +00005199 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5200 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005201 EVT EltVT = VT.getVectorElementType();
5202 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5203 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00005204 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00005205 // We know that the # elements of the results is the same as the
5206 // # elements of the compare (and the # elements of the compare result
5207 // for that matter). Check to see that they are the same size. If so,
5208 // we know that the element size of the sext'd result matches the
5209 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005210 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5211 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00005212 N0.getOperand(1),
5213 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005214 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Evan Chengabd0ad52010-05-19 01:08:17 +00005215 &OneOps[0], OneOps.size()));
Dan Gohman4298df62011-05-17 22:20:36 +00005216
5217 // If the desired elements are smaller or larger than the source
5218 // elements we can use a matching integer vector type and then
5219 // truncate/sign extend
5220 EVT MatchingElementType =
5221 EVT::getIntegerVT(*DAG.getContext(),
5222 N0VT.getScalarType().getSizeInBits());
5223 EVT MatchingVectorType =
5224 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5225 N0VT.getVectorNumElements());
5226 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005227 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00005228 N0.getOperand(1),
5229 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005230 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5231 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5232 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Dan Gohman4298df62011-05-17 22:20:36 +00005233 &OneOps[0], OneOps.size()));
Evan Chengabd0ad52010-05-19 01:08:17 +00005234 }
5235
5236 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005237 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005238 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00005239 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005240 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005241 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005242 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005243
Evan Cheng852c4862009-12-15 03:00:32 +00005244 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00005245 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00005246 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00005247 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5248 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005249 SDValue ShAmt = N0.getOperand(1);
5250 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00005251 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005252 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00005253 // If the original shl may be shifting out bits, do not perform this
5254 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00005255 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5256 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5257 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00005258 return SDValue();
5259 }
Chris Lattnere95d1952011-02-13 19:09:16 +00005260
Andrew Trickef9de2a2013-05-25 02:42:55 +00005261 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005262
5263 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00005264 if (VT.getSizeInBits() >= 256)
5265 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005266
Chris Lattnere95d1952011-02-13 19:09:16 +00005267 return DAG.getNode(N0.getOpcode(), DL, VT,
5268 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5269 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00005270 }
5271
Evan Chengf1005572010-04-28 07:10:39 +00005272 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005273}
5274
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005275SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5276 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005277 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005278
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005279 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5280 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005281 return SDValue(Res, 0);
5282
Chris Lattner812646a2006-05-05 05:58:59 +00005283 // fold (aext (aext x)) -> (aext x)
5284 // fold (aext (zext x)) -> (zext x)
5285 // fold (aext (sext x)) -> (sext x)
5286 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5287 N0.getOpcode() == ISD::ZERO_EXTEND ||
5288 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005289 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005290
Evan Cheng464dc9b2007-03-22 01:54:19 +00005291 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5292 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5293 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005294 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5295 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005296 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5297 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005298 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005299 // CombineTo deleted the truncate, if needed, but not what's under it.
5300 AddToWorkList(oye);
5301 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005302 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005303 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005304 }
5305
Chris Lattner8746e2c2006-09-20 06:29:17 +00005306 // fold (aext (truncate x))
5307 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005308 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005309 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005310 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00005311 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005312 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5313 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005314 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005315
Dan Gohmanad3e5492009-04-08 00:15:30 +00005316 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5317 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00005318 if (N0.getOpcode() == ISD::AND &&
5319 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005320 N0.getOperand(1).getOpcode() == ISD::Constant &&
5321 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5322 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005323 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005324 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005325 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005326 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005327 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00005328 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005329 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005330 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005331 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005332 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00005333 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005334
Chris Lattner812646a2006-05-05 05:58:59 +00005335 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005336 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00005337 // on vectors in one instruction. We only perform this transformation on
5338 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005339 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005340 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005341 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005342 bool DoXform = true;
5343 SmallVector<SDNode*, 4> SetCCs;
5344 if (!N0.hasOneUse())
5345 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5346 if (DoXform) {
5347 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005348 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005349 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005350 LN0->getBasePtr(), N0.getValueType(),
5351 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00005352 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005353 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00005354 N0.getValueType(), ExtLoad);
5355 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005356 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005357 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005358 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5359 }
Chris Lattner812646a2006-05-05 05:58:59 +00005360 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005361
Chris Lattner812646a2006-05-05 05:58:59 +00005362 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5363 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5364 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005365 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005366 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00005367 N0.hasOneUse()) {
5368 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005369 EVT MemVT = LN0->getMemoryVT();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005370 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
Stuart Hastings81c43062011-02-16 16:23:55 +00005371 VT, LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005372 MemVT, LN0->getMemOperand());
Chris Lattner812646a2006-05-05 05:58:59 +00005373 CombineTo(N, ExtLoad);
Evan Cheng894be332008-08-29 23:20:46 +00005374 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005375 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005376 N0.getValueType(), ExtLoad),
Chris Lattner812646a2006-05-05 05:58:59 +00005377 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005378 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner812646a2006-05-05 05:58:59 +00005379 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005380
Chris Lattner65786b02007-04-11 05:32:27 +00005381 if (N0.getOpcode() == ISD::SETCC) {
Evan Chengabd0ad52010-05-19 01:08:17 +00005382 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5383 // Only do this before legalize for now.
5384 if (VT.isVector() && !LegalOperations) {
5385 EVT N0VT = N0.getOperand(0).getValueType();
5386 // We know that the # elements of the results is the same as the
5387 // # elements of the compare (and the # elements of the compare result
5388 // for that matter). Check to see that they are the same size. If so,
5389 // we know that the element size of the sext'd result matches the
5390 // element size of the compare operands.
5391 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005392 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005393 N0.getOperand(1),
5394 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00005395 // If the desired elements are smaller or larger than the source
5396 // elements we can use a matching integer vector type and then
5397 // truncate/sign extend
5398 else {
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005399 EVT MatchingElementType =
5400 EVT::getIntegerVT(*DAG.getContext(),
5401 N0VT.getScalarType().getSizeInBits());
5402 EVT MatchingVectorType =
5403 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5404 N0VT.getVectorNumElements());
5405 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005406 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005407 N0.getOperand(1),
5408 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005409 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00005410 }
5411 }
5412
5413 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005414 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005415 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005416 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00005417 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005418 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00005419 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005420 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005421
Evan Chengf1005572010-04-28 07:10:39 +00005422 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00005423}
5424
Chris Lattner5e6fe052007-10-13 06:35:54 +00005425/// GetDemandedBits - See if the specified operand can be simplified with the
5426/// knowledge that only the bits specified by Mask are used. If so, return the
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005427/// simpler operand, otherwise return a null SDValue.
5428SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00005429 switch (V.getOpcode()) {
5430 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00005431 case ISD::Constant: {
5432 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5433 assert(CV != 0 && "Const value should be ConstSDNode.");
5434 const APInt &CVal = CV->getAPIntValue();
5435 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00005436 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00005437 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00005438 break;
5439 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005440 case ISD::OR:
5441 case ISD::XOR:
5442 // If the LHS or RHS don't contribute bits to the or, drop them.
5443 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5444 return V.getOperand(1);
5445 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5446 return V.getOperand(0);
5447 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00005448 case ISD::SRL:
5449 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00005450 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00005451 break;
5452 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5453 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00005454 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005455
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00005456 // Watch out for shift count overflow though.
5457 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00005458 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005459 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005460 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005461 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00005462 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00005463 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005464 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005465 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00005466}
5467
Evan Cheng464dc9b2007-03-22 01:54:19 +00005468/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5469/// bits and then truncated to a narrower type and where N is a multiple
5470/// of number of bits of the narrower type, transform it to a narrower load
5471/// from address + N / num of bits of new type. If the result is to be
5472/// extended, also fold the extension to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005473SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005474 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00005475
Evan Cheng464dc9b2007-03-22 01:54:19 +00005476 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005477 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005478 EVT VT = N->getValueType(0);
5479 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005480
Dan Gohman550c9af2008-08-14 20:04:46 +00005481 // This transformation isn't valid for vector loads.
5482 if (VT.isVector())
5483 return SDValue();
5484
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005485 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00005486 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00005487 if (Opc == ISD::SIGN_EXTEND_INREG) {
5488 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00005489 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00005490 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00005491 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00005492 ExtType = ISD::ZEXTLOAD;
5493 N0 = SDValue(N, 0);
5494 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5495 if (!N01) return SDValue();
5496 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5497 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00005498 }
Richard Osborne272e0842011-01-31 17:41:44 +00005499 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5500 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005501
Owen Anderson53aa7a92009-08-10 22:56:29 +00005502 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005503
Chris Lattner9a499e92010-12-22 08:01:44 +00005504 // Do not generate loads of non-round integer types since these can
5505 // be expensive (and would be wrong if the type is not byte sized).
5506 if (!ExtVT.isRound())
5507 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005508
Evan Cheng464dc9b2007-03-22 01:54:19 +00005509 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00005510 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005511 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00005512 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005513 // Is the shift amount a multiple of size of VT?
5514 if ((ShAmt & (EVTBits-1)) == 0) {
5515 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00005516 // Is the load width a multiple of size of VT?
5517 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005518 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005519 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005520
Chris Lattnercafc1e62010-12-22 08:02:57 +00005521 // At this point, we must have a load or else we can't do the transform.
5522 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005523
Chandler Carruthb27041c2012-12-11 00:36:57 +00005524 // Because a SRL must be assumed to *need* to zero-extend the high bits
5525 // (as opposed to anyext the high bits), we can't combine the zextload
5526 // lowering of SRL and an sextload.
5527 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5528 return SDValue();
5529
Chris Lattnera2050552010-10-01 05:36:09 +00005530 // If the shift amount is larger than the input type then we're not
5531 // accessing any of the loaded bytes. If the load was a zextload/extload
5532 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00005533 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00005534 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005535 }
5536 }
5537
Dan Gohman68fb0042010-11-03 01:47:46 +00005538 // If the load is shifted left (and the result isn't shifted back right),
5539 // we can fold the truncate through the shift.
5540 unsigned ShLeftAmt = 0;
5541 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00005542 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005543 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5544 ShLeftAmt = N01->getZExtValue();
5545 N0 = N0.getOperand(0);
5546 }
5547 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00005548
Chris Lattner222374d2010-12-22 07:36:50 +00005549 // If we haven't found a load, we can't narrow it. Don't transform one with
5550 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00005551 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5552 return SDValue();
5553
5554 // Don't change the width of a volatile load.
5555 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5556 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00005557 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005558
Chris Lattner9a499e92010-12-22 08:01:44 +00005559 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00005560 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00005561 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005562
Bill Schmidtd006c692013-01-14 22:04:38 +00005563 // For the transform to be legal, the load must produce only two values
5564 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00005565 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00005566 // transformation is not equivalent, and the downstream logic to replace
5567 // uses gets things wrong.
5568 if (LN0->getNumValues() > 2)
5569 return SDValue();
5570
Benjamin Kramerc7332b22013-07-06 14:05:09 +00005571 // If the load that we're shrinking is an extload and we're not just
5572 // discarding the extension we can't simply shrink the load. Bail.
5573 // TODO: It would be possible to merge the extensions in some cases.
5574 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5575 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5576 return SDValue();
5577
Chris Lattner222374d2010-12-22 07:36:50 +00005578 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005579
Evan Cheng4c6f9172012-06-26 01:19:33 +00005580 if (PtrType == MVT::Untyped || PtrType.isExtended())
5581 // It's not possible to generate a constant of extended or untyped type.
5582 return SDValue();
5583
Chris Lattner222374d2010-12-22 07:36:50 +00005584 // For big endian targets, we need to adjust the offset to the pointer to
5585 // load the correct bytes.
5586 if (TLI.isBigEndian()) {
5587 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5588 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5589 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005590 }
5591
Chris Lattner222374d2010-12-22 07:36:50 +00005592 uint64_t PtrOff = ShAmt / 8;
5593 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005594 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00005595 PtrType, LN0->getBasePtr(),
5596 DAG.getConstant(PtrOff, PtrType));
5597 AddToWorkList(NewPtr.getNode());
5598
Chris Lattner9a499e92010-12-22 08:01:44 +00005599 SDValue Load;
5600 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005601 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005602 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00005603 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005604 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00005605 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005606 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005607 LN0->getPointerInfo().getWithOffset(PtrOff),
5608 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005609 NewAlign, LN0->getTBAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00005610
5611 // Replace the old load's chain with the new load's chain.
5612 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00005613 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00005614
5615 // Shift the result left, if we've swallowed a left shift.
5616 SDValue Result = Load;
5617 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00005618 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00005619 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5620 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00005621 // If the shift amount is as large as the result size (but, presumably,
5622 // no larger than the source) then the useful bits of the result are
5623 // zero; we can't simply return the shortened shift, because the result
5624 // of that operation is undefined.
5625 if (ShLeftAmt >= VT.getSizeInBits())
5626 Result = DAG.getConstant(0, VT);
5627 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005628 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00005629 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00005630 }
5631
5632 // Return the new loaded value.
5633 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005634}
5635
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005636SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5637 SDValue N0 = N->getOperand(0);
5638 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005639 EVT VT = N->getValueType(0);
5640 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00005641 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005642 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005643
Nate Begeman21158fc2005-09-01 00:19:25 +00005644 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00005645 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005646 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005647
Chris Lattner2a4d7b82006-05-06 22:43:44 +00005648 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00005649 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00005650 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005651
Nate Begeman7cea6ef2005-09-02 21:18:40 +00005652 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5653 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00005654 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005655 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005656 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00005657
Dan Gohman345d63c2008-07-31 00:50:31 +00005658 // fold (sext_in_reg (sext x)) -> (sext x)
5659 // fold (sext_in_reg (aext x)) -> (sext x)
5660 // if x is small enough.
5661 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5662 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00005663 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5664 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005665 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00005666 }
5667
Chris Lattner9ad59152007-04-17 19:03:21 +00005668 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00005669 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005670 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005671
Chris Lattner9ad59152007-04-17 19:03:21 +00005672 // fold operands of sext_in_reg based on knowledge that the top bits are not
5673 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005674 if (SimplifyDemandedBits(SDValue(N, 0)))
5675 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005676
Evan Cheng464dc9b2007-03-22 01:54:19 +00005677 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5678 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005679 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005680 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00005681 return NarrowLoad;
5682
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005683 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005684 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00005685 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5686 if (N0.getOpcode() == ISD::SRL) {
5687 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00005688 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005689 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00005690 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00005691 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00005692 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005693 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005694 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00005695 }
5696 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005697
Nate Begeman02b23c62005-10-13 03:11:28 +00005698 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00005699 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005700 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005701 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005702 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005703 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005704 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005705 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005706 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005707 LN0->getBasePtr(), EVT,
5708 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005709 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005710 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Elena Demikhovsky14a4af02012-12-19 07:50:20 +00005711 AddToWorkList(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005712 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005713 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005714 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00005715 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005716 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005717 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005718 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005719 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005720 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005721 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005722 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005723 LN0->getBasePtr(), EVT,
5724 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005725 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005726 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005727 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005728 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00005729
5730 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5731 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5732 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5733 N0.getOperand(1), false);
5734 if (BSwap.getNode() != 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005735 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00005736 BSwap, N1);
5737 }
5738
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005739 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5740 // into a build_vector.
5741 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5742 SmallVector<SDValue, 8> Elts;
5743 unsigned NumElts = N0->getNumOperands();
5744 unsigned ShAmt = VTBits - EVTBits;
5745
5746 for (unsigned i = 0; i != NumElts; ++i) {
5747 SDValue Op = N0->getOperand(i);
5748 if (Op->getOpcode() == ISD::UNDEF) {
5749 Elts.push_back(Op);
5750 continue;
5751 }
5752
5753 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00005754 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5755 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005756 Op.getValueType()));
5757 }
5758
5759 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5760 }
5761
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005762 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005763}
5764
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005765SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5766 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005767 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005768 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00005769
5770 // noop truncate
5771 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00005772 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00005773 // fold (truncate c1) -> c1
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005774 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005775 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005776 // fold (truncate (truncate x)) -> (truncate x)
5777 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005778 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00005779 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00005780 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5781 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00005782 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00005783 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005784 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00005785 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00005786 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00005787 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005788 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00005789 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00005790 // if the source and dest are the same type, we can drop both the extend
5791 // and the truncate.
5792 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005793 }
Evan Chengd63baea2007-03-21 20:14:05 +00005794
Nadav Rotem4f4546b2012-02-05 11:39:23 +00005795 // Fold extract-and-trunc into a narrow extract. For example:
5796 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5797 // i32 y = TRUNCATE(i64 x)
5798 // -- becomes --
5799 // v16i8 b = BITCAST (v2i64 val)
5800 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5801 //
5802 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005803 // creates this pattern) and before operation legalization after which
5804 // we need to be more careful about the vector instructions that we generate.
5805 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00005806 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005807
5808 EVT VecTy = N0.getOperand(0).getValueType();
5809 EVT ExTy = N0.getValueType();
5810 EVT TrTy = N->getValueType(0);
5811
5812 unsigned NumElem = VecTy.getVectorNumElements();
5813 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5814
5815 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5816 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5817
5818 SDValue EltNo = N0->getOperand(1);
5819 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5820 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00005821 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005822 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5823
Andrew Trickef9de2a2013-05-25 02:42:55 +00005824 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005825 NVT, N0.getOperand(0));
5826
5827 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005828 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00005829 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005830 }
5831 }
5832
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00005833 // Fold a series of buildvector, bitcast, and truncate if possible.
5834 // For example fold
5835 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5836 // (2xi32 (buildvector x, y)).
5837 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5838 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5839 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5840 N0.getOperand(0).hasOneUse()) {
5841
5842 SDValue BuildVect = N0.getOperand(0);
5843 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5844 EVT TruncVecEltTy = VT.getVectorElementType();
5845
5846 // Check that the element types match.
5847 if (BuildVectEltTy == TruncVecEltTy) {
5848 // Now we only need to compute the offset of the truncated elements.
5849 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5850 unsigned TruncVecNumElts = VT.getVectorNumElements();
5851 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5852
5853 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5854 "Invalid number of elements");
5855
5856 SmallVector<SDValue, 8> Opnds;
5857 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5858 Opnds.push_back(BuildVect.getOperand(i));
5859
Andrew Trickef9de2a2013-05-25 02:42:55 +00005860 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00005861 Opnds.size());
5862 }
5863 }
5864
Chris Lattner5e6fe052007-10-13 06:35:54 +00005865 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00005866 // only the low bits are being used.
5867 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00005868 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00005869 // may have different active low bits.
5870 if (!VT.isVector()) {
5871 SDValue Shorter =
5872 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5873 VT.getSizeInBits()));
5874 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005875 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00005876 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005877 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00005878 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00005879 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5880 SDValue Reduced = ReduceLoadWidth(N);
5881 if (Reduced.getNode())
5882 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00005883 // Handle the case where the load remains an extending load even
5884 // after truncation.
5885 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5886 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5887 if (!LN0->isVolatile() &&
5888 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5889 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5890 VT, LN0->getChain(), LN0->getBasePtr(),
5891 LN0->getMemoryVT(),
5892 LN0->getMemOperand());
5893 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5894 return NewLoad;
5895 }
5896 }
Dan Gohman600f62b2010-06-24 14:30:44 +00005897 }
Michael Liao3ac82012012-10-17 23:45:54 +00005898 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5899 // where ... are all 'undef'.
5900 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5901 SmallVector<EVT, 8> VTs;
5902 SDValue V;
5903 unsigned Idx = 0;
5904 unsigned NumDefs = 0;
5905
5906 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5907 SDValue X = N0.getOperand(i);
5908 if (X.getOpcode() != ISD::UNDEF) {
5909 V = X;
5910 Idx = i;
5911 NumDefs++;
5912 }
5913 // Stop if more than one members are non-undef.
5914 if (NumDefs > 1)
5915 break;
5916 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5917 VT.getVectorElementType(),
5918 X.getValueType().getVectorNumElements()));
5919 }
5920
5921 if (NumDefs == 0)
5922 return DAG.getUNDEF(VT);
5923
5924 if (NumDefs == 1) {
5925 assert(V.getNode() && "The single defined operand is empty!");
5926 SmallVector<SDValue, 8> Opnds;
5927 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5928 if (i != Idx) {
5929 Opnds.push_back(DAG.getUNDEF(VTs[i]));
5930 continue;
5931 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005932 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Michael Liao3ac82012012-10-17 23:45:54 +00005933 AddToWorkList(NV.getNode());
5934 Opnds.push_back(NV);
5935 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005936 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
Michael Liao3ac82012012-10-17 23:45:54 +00005937 &Opnds[0], Opnds.size());
5938 }
5939 }
Dan Gohman600f62b2010-06-24 14:30:44 +00005940
5941 // Simplify the operands using demanded-bits information.
5942 if (!VT.isVector() &&
5943 SimplifyDemandedBits(SDValue(N, 0)))
5944 return SDValue(N, 0);
5945
Evan Chengf1bd5fc2010-04-17 06:13:15 +00005946 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005947}
5948
Evan Chengb980f6f2008-05-12 23:04:07 +00005949static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005950 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00005951 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00005952 return Elt.getNode();
5953 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00005954}
5955
5956/// CombineConsecutiveLoads - build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00005957/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00005958SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00005959 assert(N->getOpcode() == ISD::BUILD_PAIR);
5960
Nate Begeman624690c2009-06-05 21:37:30 +00005961 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5962 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00005963 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00005964 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005965 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00005966 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00005967
Evan Chengb980f6f2008-05-12 23:04:07 +00005968 if (ISD::isNON_EXTLoad(LD2) &&
5969 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00005970 // If both are volatile this would reduce the number of volatile loads.
5971 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00005972 !LD1->isVolatile() &&
5973 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00005974 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00005975 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00005976 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00005977 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00005978
Duncan Sands8651e9c2008-06-13 19:07:40 +00005979 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005980 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005981 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00005982 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00005983 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00005984 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00005985
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005986 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00005987}
5988
Wesley Peck527da1b2010-11-23 03:31:01 +00005989SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005990 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005991 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00005992
Dan Gohmana8665142007-06-25 16:23:39 +00005993 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5994 // Only do this before legalize, since afterward the target may be depending
5995 // on the bitconvert.
5996 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005997 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005998 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00005999 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00006000 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006001
Owen Anderson53aa7a92009-08-10 22:56:29 +00006002 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006003 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00006004 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00006005 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00006006 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00006007 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006008
Dan Gohman921ddd62008-09-05 01:58:21 +00006009 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00006010 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006011 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Dan Gohman733a64d2009-08-10 23:15:10 +00006012 if (Res.getNode() != N) {
6013 if (!LegalOperations ||
6014 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6015 return Res;
6016
6017 // Folding it resulted in an illegal node, and it's too late to
6018 // do that. Clean up the old node and forego the transformation.
6019 // Ideally this won't happen very often, because instcombine
6020 // and the earlier dagcombine runs (where illegal nodes are
6021 // permitted) should have folded most of them already.
6022 DAG.DeleteNode(Res.getNode());
6023 }
Chris Lattnera1874602005-12-23 05:30:37 +00006024 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006025
Bill Wendling4e0a6152009-01-30 22:44:24 +00006026 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00006027 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006028 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006029 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006030
Chris Lattner54560f62005-12-23 05:44:41 +00006031 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00006032 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00006033 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006034 // Do not change the width of a volatile load.
6035 !cast<LoadSDNode>(N0)->isVolatile() &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00006036 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6037 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006038 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006039 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006040 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006041 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00006042
Evan Chenga4cf58a2007-05-07 21:27:48 +00006043 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006044 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006045 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00006046 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006047 LN0->isInvariant(), OrigAlign,
6048 LN0->getTBAAInfo());
Evan Chenga4cf58a2007-05-07 21:27:48 +00006049 AddToWorkList(N);
Gabor Greife12264b2008-08-30 19:29:20 +00006050 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00006051 DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006052 N0.getValueType(), Load),
Evan Chenga4cf58a2007-05-07 21:27:48 +00006053 Load.getValue(1));
6054 return Load;
6055 }
Chris Lattner54560f62005-12-23 05:44:41 +00006056 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006057
Bill Wendling4e0a6152009-01-30 22:44:24 +00006058 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6059 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00006060 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00006061 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6062 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00006063 N0.getNode()->hasOneUse() && VT.isInteger() &&
6064 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006065 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006066 N0.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00006067 AddToWorkList(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00006068
Duncan Sands13237ac2008-06-06 12:08:01 +00006069 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00006070 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006071 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006072 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006073 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006074 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006075 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006076 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006077
Bill Wendling4e0a6152009-01-30 22:44:24 +00006078 // fold (bitconvert (fcopysign cst, x)) ->
6079 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6080 // Note that we don't handle (copysign x, cst) because this can always be
6081 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006082 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00006083 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006084 VT.isInteger() && !VT.isVector()) {
6085 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00006086 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00006087 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006088 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006089 IntXVT, N0.getOperand(1));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006090 AddToWorkList(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006091
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006092 // If X has a different width than the result/lhs, sext it or truncate it.
6093 unsigned VTWidth = VT.getSizeInBits();
6094 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006095 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006096 AddToWorkList(X.getNode());
6097 } else if (OrigXWidth > VTWidth) {
6098 // To get the sign bit in the right place, we have to shift it right
6099 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006100 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006101 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006102 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6103 AddToWorkList(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006104 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006105 AddToWorkList(X.getNode());
6106 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006107
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006108 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006109 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006110 X, DAG.getConstant(SignBit, VT));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006111 AddToWorkList(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006112
Andrew Trickef9de2a2013-05-25 02:42:55 +00006113 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006114 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006115 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006116 Cst, DAG.getConstant(~SignBit, VT));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006117 AddToWorkList(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006118
Andrew Trickef9de2a2013-05-25 02:42:55 +00006119 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006120 }
Chris Lattner888560d2008-01-27 17:42:27 +00006121 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006122
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006123 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006124 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006125 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6126 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006127 return CombineLD;
6128 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006129
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006130 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006131}
6132
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006133SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006134 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006135 return CombineConsecutiveLoads(N, VT);
6136}
6137
Wesley Peck527da1b2010-11-23 03:31:01 +00006138/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
Scott Michelcf0da6c2009-02-17 22:15:04 +00006139/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
Chris Lattnere4e64b62006-04-02 02:53:43 +00006140/// destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006141SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006142ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006143 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006144
Chris Lattnere4e64b62006-04-02 02:53:43 +00006145 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006146 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006147
Duncan Sands13237ac2008-06-06 12:08:01 +00006148 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6149 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006150
Chris Lattnere4e64b62006-04-02 02:53:43 +00006151 // If this is a conversion of N elements of one type to N elements of another
6152 // type, convert each element. This handles FP<->INT cases.
6153 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006154 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6155 BV->getValueType(0).getVectorNumElements());
6156
6157 // Due to the FP element handling below calling this routine recursively,
6158 // we can end up with a scalar-to-vector node here.
6159 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006160 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6161 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006162 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006163
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006164 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006165 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006166 SDValue Op = BV->getOperand(i);
6167 // If the vector element type is not legal, the BUILD_VECTOR operands
6168 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006169 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006170 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6171 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006172 DstEltVT, Op));
Gabor Greiff304a7a2008-08-28 21:40:38 +00006173 AddToWorkList(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006174 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006175 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga49de9d2009-02-25 22:49:59 +00006176 &Ops[0], Ops.size());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006177 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006178
Chris Lattnere4e64b62006-04-02 02:53:43 +00006179 // Otherwise, we're growing or shrinking the elements. To avoid having to
6180 // handle annoying details of growing/shrinking FP values, we convert them to
6181 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006182 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006183 // Convert the input float vector to a int vector where the elements are the
6184 // same sizes.
Owen Anderson9f944592009-08-11 20:47:22 +00006185 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006186 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006187 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006188 SrcEltVT = IntVT;
6189 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006190
Chris Lattnere4e64b62006-04-02 02:53:43 +00006191 // Now we know the input is an integer vector. If the output is a FP type,
6192 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006193 if (DstEltVT.isFloatingPoint()) {
Owen Anderson9f944592009-08-11 20:47:22 +00006194 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006195 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006196 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006197
Chris Lattnere4e64b62006-04-02 02:53:43 +00006198 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00006199 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006200 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006201
Chris Lattnere4e64b62006-04-02 02:53:43 +00006202 // Okay, we know the src/dst types are both integers of differing types.
6203 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006204 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006205 if (SrcBitSize < DstBitSize) {
6206 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006207
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006208 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006209 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00006210 i += NumInputsPerOutput) {
6211 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00006212 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006213 bool EltIsUndef = true;
6214 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6215 // Shift the previously computed bits over.
6216 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006217 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006218 if (Op.getOpcode() == ISD::UNDEF) continue;
6219 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006220
Jay Foad583abbc2010-12-07 08:25:19 +00006221 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00006222 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006223 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006224
Chris Lattnere4e64b62006-04-02 02:53:43 +00006225 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00006226 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006227 else
6228 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6229 }
6230
Owen Anderson117c9e82009-08-12 00:36:31 +00006231 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006232 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga49de9d2009-02-25 22:49:59 +00006233 &Ops[0], Ops.size());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006234 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006235
Chris Lattnere4e64b62006-04-02 02:53:43 +00006236 // Finally, this must be the case where we are shrinking elements: each input
6237 // turns into multiple outputs.
Evan Cheng6200c222008-02-18 23:04:32 +00006238 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006239 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00006240 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6241 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006242 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006243
Dan Gohmana8665142007-06-25 16:23:39 +00006244 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006245 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6246 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesen84935752009-02-06 23:05:02 +00006247 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006248 continue;
6249 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006250
Jay Foad583abbc2010-12-07 08:25:19 +00006251 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6252 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006253
Chris Lattnere4e64b62006-04-02 02:53:43 +00006254 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00006255 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006256 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad583abbc2010-12-07 08:25:19 +00006257 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Cheng6200c222008-02-18 23:04:32 +00006258 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006259 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006260 Ops[0]);
Dan Gohmane1c4f992008-03-03 23:51:38 +00006261 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006262 }
6263
6264 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00006265 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00006266 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6267 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006268
Andrew Trickef9de2a2013-05-25 02:42:55 +00006269 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga49de9d2009-02-25 22:49:59 +00006270 &Ops[0], Ops.size());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006271}
6272
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006273SDValue DAGCombiner::visitFADD(SDNode *N) {
6274 SDValue N0 = N->getOperand(0);
6275 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006276 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6277 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006278 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006279
Dan Gohmana8665142007-06-25 16:23:39 +00006280 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006281 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006282 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006283 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006284 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006285
Lang Hamesa33db652012-06-14 20:37:15 +00006286 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006287 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006288 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006289 // canonicalize constant to RHS
6290 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006291 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006292 // fold (fadd A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006293 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6294 N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006295 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006296 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006297 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006298 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006299 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006300 GetNegatedExpression(N1, DAG, LegalOperations));
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006301 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006302 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006303 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006304 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006305 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006306
Chris Lattner0199fd62007-01-08 23:04:05 +00006307 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006308 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6309 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6310 isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006311 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6312 DAG.getNode(ISD::FADD, SDLoc(N), VT,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +00006313 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006314
Shuxin Yang93b1f122013-03-25 22:52:29 +00006315 // No FP constant should be created after legalization as Instruction
6316 // Selection pass has hard time in dealing with FP constant.
6317 //
6318 // We don't need test this condition for transformation like following, as
6319 // the DAG being transformed implies it is legal to take FP constant as
6320 // operand.
Stephen Lincfe7f352013-07-08 00:37:03 +00006321 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006322 // (fadd (fmul c, x), x) -> (fmul c+1, x)
Stephen Lincfe7f352013-07-08 00:37:03 +00006323 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006324 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6325
Owen Andersonb351c8d2012-11-01 02:00:53 +00006326 // If allow, fold (fadd (fneg x), x) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006327 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006328 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006329 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006330
6331 // If allow, fold (fadd x, (fneg x)) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006332 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006333 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006334 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006335
Owen Andersoncc61f872012-08-30 23:35:16 +00006336 // In unsafe math mode, we can fold chains of FADD's of the same value
6337 // into multiplications. This transform is not safe in general because
6338 // we are reducing the number of rounding steps.
6339 if (DAG.getTarget().Options.UnsafeFPMath &&
6340 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6341 !N0CFP && !N1CFP) {
6342 if (N0.getOpcode() == ISD::FMUL) {
6343 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6344 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6345
Stephen Line31f2d22013-06-14 18:17:35 +00006346 // (fadd (fmul c, x), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006347 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006348 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006349 SDValue(CFP00, 0),
6350 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006351 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006352 N1, NewCFP);
6353 }
6354
Stephen Line31f2d22013-06-14 18:17:35 +00006355 // (fadd (fmul x, c), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006356 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006357 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006358 SDValue(CFP01, 0),
6359 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006360 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006361 N1, NewCFP);
6362 }
6363
Stephen Line31f2d22013-06-14 18:17:35 +00006364 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006365 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6366 N1.getOperand(0) == N1.getOperand(1) &&
6367 N0.getOperand(1) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006368 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006369 SDValue(CFP00, 0),
6370 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006371 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006372 N0.getOperand(1), NewCFP);
6373 }
6374
Stephen Line31f2d22013-06-14 18:17:35 +00006375 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006376 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6377 N1.getOperand(0) == N1.getOperand(1) &&
6378 N0.getOperand(0) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006379 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006380 SDValue(CFP01, 0),
6381 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006382 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006383 N0.getOperand(0), NewCFP);
6384 }
6385 }
6386
6387 if (N1.getOpcode() == ISD::FMUL) {
6388 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6389 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6390
Stephen Line31f2d22013-06-14 18:17:35 +00006391 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006392 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006393 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006394 SDValue(CFP10, 0),
6395 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006396 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006397 N0, NewCFP);
6398 }
6399
Stephen Line31f2d22013-06-14 18:17:35 +00006400 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006401 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006402 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006403 SDValue(CFP11, 0),
6404 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006405 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006406 N0, NewCFP);
6407 }
6408
Owen Andersoncc61f872012-08-30 23:35:16 +00006409
Stephen Line31f2d22013-06-14 18:17:35 +00006410 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6411 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6412 N0.getOperand(0) == N0.getOperand(1) &&
6413 N1.getOperand(1) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006414 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006415 SDValue(CFP10, 0),
6416 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006417 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006418 N1.getOperand(1), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006419 }
6420
Stephen Line31f2d22013-06-14 18:17:35 +00006421 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6422 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6423 N0.getOperand(0) == N0.getOperand(1) &&
6424 N1.getOperand(0) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006425 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006426 SDValue(CFP11, 0),
6427 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006428 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006429 N1.getOperand(0), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006430 }
6431 }
6432
Shuxin Yang93b1f122013-03-25 22:52:29 +00006433 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006434 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006435 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006436 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006437 (N0.getOperand(0) == N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006438 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006439 N1, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006440 }
6441
Shuxin Yang93b1f122013-03-25 22:52:29 +00006442 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006443 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006444 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006445 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006446 N1.getOperand(0) == N0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006447 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006448 N0, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006449 }
6450
Stephen Lin4e69d012013-06-14 21:33:58 +00006451 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
Shuxin Yang93b1f122013-03-25 22:52:29 +00006452 if (AllowNewFpConst &&
6453 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Owen Andersoncc61f872012-08-30 23:35:16 +00006454 N0.getOperand(0) == N0.getOperand(1) &&
6455 N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006456 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006457 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006458 N0.getOperand(0),
6459 DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006460 }
6461
Lang Hames39fb1d02012-06-19 22:51:23 +00006462 // FADD -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006463 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006464 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006465 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6466 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006467
6468 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Stephen Lin8e8424e2013-07-09 00:44:49 +00006469 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006470 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006471 N0.getOperand(0), N0.getOperand(1), N1);
Owen Andersoncc61f872012-08-30 23:35:16 +00006472
Michael Liaoec3850122012-09-01 04:09:16 +00006473 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hames39fb1d02012-06-19 22:51:23 +00006474 // Note: Commutes FADD operands.
Stephen Lin8e8424e2013-07-09 00:44:49 +00006475 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006476 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006477 N1.getOperand(0), N1.getOperand(1), N0);
Lang Hames39fb1d02012-06-19 22:51:23 +00006478 }
6479
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006480 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006481}
6482
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006483SDValue DAGCombiner::visitFSUB(SDNode *N) {
6484 SDValue N0 = N->getOperand(0);
6485 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006486 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6487 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006488 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006489 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006490
Dan Gohmana8665142007-06-25 16:23:39 +00006491 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006492 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006493 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006494 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006495 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006496
Nate Begeman418c6e42005-10-18 00:28:13 +00006497 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006498 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006499 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006500 // fold (fsub A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006501 if (DAG.getTarget().Options.UnsafeFPMath &&
6502 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1275e282009-01-23 19:10:37 +00006503 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006504 // fold (fsub 0, B) -> -B
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006505 if (DAG.getTarget().Options.UnsafeFPMath &&
6506 N0CFP && N0CFP->getValueAPF().isZero()) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006507 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006508 return GetNegatedExpression(N1, DAG, LegalOperations);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006509 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006510 return DAG.getNode(ISD::FNEG, dl, VT, N1);
Dan Gohman9a708232007-07-02 15:48:56 +00006511 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006512 // fold (fsub A, (fneg B)) -> (fadd A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006513 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006514 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006515 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006516
Bill Wendlingdf170db2012-03-15 05:12:00 +00006517 // If 'unsafe math' is enabled, fold
Owen Andersonab63d842012-05-07 20:51:25 +00006518 // (fsub x, x) -> 0.0 &
Bill Wendlingdf170db2012-03-15 05:12:00 +00006519 // (fsub x, (fadd x, y)) -> (fneg y) &
6520 // (fsub x, (fadd y, x)) -> (fneg y)
6521 if (DAG.getTarget().Options.UnsafeFPMath) {
Owen Andersonab63d842012-05-07 20:51:25 +00006522 if (N0 == N1)
6523 return DAG.getConstantFP(0.0f, VT);
6524
Bill Wendlingdf170db2012-03-15 05:12:00 +00006525 if (N1.getOpcode() == ISD::FADD) {
6526 SDValue N10 = N1->getOperand(0);
6527 SDValue N11 = N1->getOperand(1);
6528
6529 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6530 &DAG.getTarget().Options))
6531 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00006532
Stephen Lin8e8424e2013-07-09 00:44:49 +00006533 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6534 &DAG.getTarget().Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006535 return GetNegatedExpression(N10, DAG, LegalOperations);
6536 }
6537 }
6538
Lang Hames39fb1d02012-06-19 22:51:23 +00006539 // FSUB -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006540 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006541 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006542 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6543 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006544
6545 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006546 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006547 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006548 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006549 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hames39fb1d02012-06-19 22:51:23 +00006550
6551 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6552 // Note: Commutes FSUB operands.
Stephen Lin10947502013-07-10 20:47:39 +00006553 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006554 return DAG.getNode(ISD::FMA, dl, VT,
6555 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006556 N1.getOperand(0)),
6557 N1.getOperand(1), N0);
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006558
Stephen Lin8e8424e2013-07-09 00:44:49 +00006559 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lincfe7f352013-07-08 00:37:03 +00006560 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006561 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6562 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6563 SDValue N00 = N0.getOperand(0).getOperand(0);
6564 SDValue N01 = N0.getOperand(0).getOperand(1);
6565 return DAG.getNode(ISD::FMA, dl, VT,
6566 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6567 DAG.getNode(ISD::FNEG, dl, VT, N1));
6568 }
Lang Hames39fb1d02012-06-19 22:51:23 +00006569 }
6570
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006571 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006572}
6573
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006574SDValue DAGCombiner::visitFMUL(SDNode *N) {
6575 SDValue N0 = N->getOperand(0);
6576 SDValue N1 = N->getOperand(1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006577 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6578 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006579 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006580 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006581
Dan Gohmana8665142007-06-25 16:23:39 +00006582 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006583 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006584 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006585 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006586 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006587
Nate Begemanec48a1b2005-10-17 20:40:11 +00006588 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006589 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006590 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006591 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00006592 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006593 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Bill Wendling3dc5d242009-01-30 22:57:07 +00006594 // fold (fmul A, 0) -> 0
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006595 if (DAG.getTarget().Options.UnsafeFPMath &&
6596 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006597 return N1;
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006598 // fold (fmul A, 0) -> 0, vector edition.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006599 if (DAG.getTarget().Options.UnsafeFPMath &&
6600 ISD::isBuildVectorAllZeros(N1.getNode()))
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006601 return N1;
Owen Andersonb5f167c2012-05-02 21:32:35 +00006602 // fold (fmul A, 1.0) -> A
6603 if (N1CFP && N1CFP->isExactlyValue(1.0))
6604 return N0;
Nate Begemanec48a1b2005-10-17 20:40:11 +00006605 // fold (fmul X, 2.0) -> (fadd X, X)
6606 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006607 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Dan Gohmanb7170912009-08-10 16:50:32 +00006608 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00006609 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00006610 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006611 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006612
Bill Wendling3dc5d242009-01-30 22:57:07 +00006613 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006614 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006615 &DAG.getTarget().Options)) {
Stephen Lincfe7f352013-07-08 00:37:03 +00006616 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006617 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006618 // Both can be negated for free, check to see if at least one is cheaper
6619 // negated.
6620 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006621 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006622 GetNegatedExpression(N0, DAG, LegalOperations),
6623 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006624 }
6625 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006626
Chris Lattner0199fd62007-01-08 23:04:05 +00006627 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006628 if (DAG.getTarget().Options.UnsafeFPMath &&
6629 N1CFP && N0.getOpcode() == ISD::FMUL &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006630 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006631 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6632 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Dale Johannesen400dc2e2009-02-06 21:50:26 +00006633 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006634
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006635 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006636}
6637
Owen Anderson41b06652012-05-02 22:17:40 +00006638SDValue DAGCombiner::visitFMA(SDNode *N) {
6639 SDValue N0 = N->getOperand(0);
6640 SDValue N1 = N->getOperand(1);
6641 SDValue N2 = N->getOperand(2);
6642 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6643 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6644 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006645 SDLoc dl(N);
Owen Anderson41b06652012-05-02 22:17:40 +00006646
Owen Andersonb351c8d2012-11-01 02:00:53 +00006647 if (DAG.getTarget().Options.UnsafeFPMath) {
6648 if (N0CFP && N0CFP->isZero())
6649 return N2;
6650 if (N1CFP && N1CFP->isZero())
6651 return N2;
6652 }
Owen Anderson41b06652012-05-02 22:17:40 +00006653 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006654 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006655 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006656 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006657
Owen Andersonc7aaf522012-05-30 18:50:39 +00006658 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00006659 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006660 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00006661
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006662 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6663 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6664 N2.getOpcode() == ISD::FMUL &&
6665 N0 == N2.getOperand(0) &&
6666 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6667 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6668 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6669 }
6670
6671
6672 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6673 if (DAG.getTarget().Options.UnsafeFPMath &&
6674 N0.getOpcode() == ISD::FMUL && N1CFP &&
6675 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6676 return DAG.getNode(ISD::FMA, dl, VT,
6677 N0.getOperand(0),
6678 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6679 N2);
6680 }
6681
6682 // (fma x, 1, y) -> (fadd x, y)
6683 // (fma x, -1, y) -> (fadd (fneg x), y)
6684 if (N1CFP) {
6685 if (N1CFP->isExactlyValue(1.0))
6686 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6687
6688 if (N1CFP->isExactlyValue(-1.0) &&
6689 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6690 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6691 AddToWorkList(RHSNeg.getNode());
6692 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6693 }
6694 }
6695
6696 // (fma x, c, x) -> (fmul x, (c+1))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006697 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6698 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006699 DAG.getNode(ISD::FADD, dl, VT,
6700 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006701
6702 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6703 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006704 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6705 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006706 DAG.getNode(ISD::FADD, dl, VT,
6707 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006708
6709
Owen Anderson41b06652012-05-02 22:17:40 +00006710 return SDValue();
6711}
6712
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006713SDValue DAGCombiner::visitFDIV(SDNode *N) {
6714 SDValue N0 = N->getOperand(0);
6715 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006716 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6717 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006718 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006719 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006720
Dan Gohmana8665142007-06-25 16:23:39 +00006721 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006722 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006723 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006724 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006725 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006726
Nate Begeman569c4392006-01-18 22:35:16 +00006727 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006728 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006729 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006730
Duncan Sands2f1dc382012-04-08 18:08:12 +00006731 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006732 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
Duncan Sands5f8397a2012-04-07 20:04:00 +00006733 // Compute the reciprocal 1.0 / c2.
6734 APFloat N1APF = N1CFP->getValueAPF();
6735 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6736 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
Duncan Sands4f530742012-04-10 20:35:27 +00006737 // Only do the transform if the reciprocal is a legal fp immediate that
6738 // isn't too nasty (eg NaN, denormal, ...).
6739 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
Anton Korobeynikov4d1220d2012-04-10 13:22:49 +00006740 (!LegalOperations ||
6741 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6742 // backend)... we should handle this gracefully after Legalize.
6743 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6744 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6745 TLI.isFPImmLegal(Recip, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006746 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
Duncan Sands5f8397a2012-04-07 20:04:00 +00006747 DAG.getConstantFP(Recip, VT));
6748 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006749
Bill Wendling3dc5d242009-01-30 22:57:07 +00006750 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006751 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006752 &DAG.getTarget().Options)) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006753 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006754 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006755 // Both can be negated for free, check to see if at least one is cheaper
6756 // negated.
6757 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006758 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006759 GetNegatedExpression(N0, DAG, LegalOperations),
6760 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006761 }
6762 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006763
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006764 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006765}
6766
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006767SDValue DAGCombiner::visitFREM(SDNode *N) {
6768 SDValue N0 = N->getOperand(0);
6769 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006770 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6771 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006772 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00006773
Nate Begeman569c4392006-01-18 22:35:16 +00006774 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006775 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006776 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00006777
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006778 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006779}
6780
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006781SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6782 SDValue N0 = N->getOperand(0);
6783 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00006784 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6785 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006786 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00006787
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006788 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00006789 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006790
Chris Lattner3bc40502006-03-05 05:30:57 +00006791 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00006792 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006793 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6794 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00006795 if (!V.isNegative()) {
6796 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006797 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006798 } else {
6799 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006800 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6801 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00006802 }
Chris Lattner3bc40502006-03-05 05:30:57 +00006803 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006804
Chris Lattner3bc40502006-03-05 05:30:57 +00006805 // copysign(fabs(x), y) -> copysign(x, y)
6806 // copysign(fneg(x), y) -> copysign(x, y)
6807 // copysign(copysign(x,z), y) -> copysign(x, y)
6808 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6809 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006810 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006811 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00006812
6813 // copysign(x, abs(y)) -> abs(x)
6814 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006815 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006816
Chris Lattner3bc40502006-03-05 05:30:57 +00006817 // copysign(x, copysign(y,z)) -> copysign(x, z)
6818 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006819 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006820 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006821
Chris Lattner3bc40502006-03-05 05:30:57 +00006822 // copysign(x, fp_extend(y)) -> copysign(x, y)
6823 // copysign(x, fp_round(y)) -> copysign(x, y)
6824 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006825 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006826 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006827
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006828 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00006829}
6830
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006831SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6832 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006833 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006834 EVT VT = N->getValueType(0);
6835 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006836
Nate Begeman21158fc2005-09-01 00:19:25 +00006837 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006838 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00006839 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00006840 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00006841 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006842 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006843
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006844 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6845 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00006846 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6847 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00006848 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006849 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006850 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006851 }
Bill Wendling0bd29742009-01-30 23:15:49 +00006852
Alp Tokercb402912014-01-24 17:20:08 +00006853 // The next optimizations are desirable only if SELECT_CC can be lowered.
Nadav Rotem90560762012-07-23 07:59:50 +00006854 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6855 // having to say they don't support SELECT_CC on every type the DAG knows
6856 // about, since there is no way to mark an opcode illegal at all value types
6857 // (See also visitSELECT)
6858 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6859 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6860 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6861 !VT.isVector() &&
6862 (!LegalOperations ||
6863 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6864 SDValue Ops[] =
6865 { N0.getOperand(0), N0.getOperand(1),
6866 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6867 N0.getOperand(2) };
Andrew Trickef9de2a2013-05-25 02:42:55 +00006868 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotem90560762012-07-23 07:59:50 +00006869 }
Owen Andersond4b841f2012-07-09 20:31:12 +00006870
Nadav Rotem90560762012-07-23 07:59:50 +00006871 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6872 // (select_cc x, y, 1.0, 0.0,, cc)
6873 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6874 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6875 (!LegalOperations ||
6876 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6877 SDValue Ops[] =
6878 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6879 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6880 N0.getOperand(0).getOperand(2) };
Andrew Trickef9de2a2013-05-25 02:42:55 +00006881 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotem90560762012-07-23 07:59:50 +00006882 }
Owen Andersond4b841f2012-07-09 20:31:12 +00006883 }
6884
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006885 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006886}
6887
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006888SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6889 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006890 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006891 EVT VT = N->getValueType(0);
6892 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00006893
Nate Begeman21158fc2005-09-01 00:19:25 +00006894 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006895 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00006896 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00006897 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00006898 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006899 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006900
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006901 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6902 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00006903 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6904 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00006905 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006906 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006907 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006908 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006909
Alp Tokercb402912014-01-24 17:20:08 +00006910 // The next optimizations are desirable only if SELECT_CC can be lowered.
Nadav Rotem90560762012-07-23 07:59:50 +00006911 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6912 // having to say they don't support SELECT_CC on every type the DAG knows
6913 // about, since there is no way to mark an opcode illegal at all value types
6914 // (See also visitSELECT)
6915 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6916 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00006917
Nadav Rotem90560762012-07-23 07:59:50 +00006918 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6919 (!LegalOperations ||
6920 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6921 SDValue Ops[] =
6922 { N0.getOperand(0), N0.getOperand(1),
6923 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
6924 N0.getOperand(2) };
Andrew Trickef9de2a2013-05-25 02:42:55 +00006925 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotem90560762012-07-23 07:59:50 +00006926 }
6927 }
Owen Andersond4b841f2012-07-09 20:31:12 +00006928
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006929 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006930}
6931
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006932SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6933 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00006934 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006935 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006936
Nate Begeman21158fc2005-09-01 00:19:25 +00006937 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006938 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006939 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00006940
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006941 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006942}
6943
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006944SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6945 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00006946 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006947 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006948
Nate Begeman21158fc2005-09-01 00:19:25 +00006949 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006950 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006951 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00006952
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006953 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006954}
6955
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006956SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6957 SDValue N0 = N->getOperand(0);
6958 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006959 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006960 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006961
Nate Begeman21158fc2005-09-01 00:19:25 +00006962 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006963 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006964 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006965
Chris Lattner8bb6cb72006-03-13 06:26:26 +00006966 // fold (fp_round (fp_extend x)) -> x
6967 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6968 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006969
Chris Lattner0feb1b02008-01-24 06:45:35 +00006970 // fold (fp_round (fp_round x)) -> (fp_round x)
6971 if (N0.getOpcode() == ISD::FP_ROUND) {
6972 // This is a value preserving truncation if both round's are.
6973 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006974 N0.getNode()->getConstantOperandVal(1) == 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00006975 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0feb1b02008-01-24 06:45:35 +00006976 DAG.getIntPtrConstant(IsTrunc));
6977 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006978
Chris Lattner8bb6cb72006-03-13 06:26:26 +00006979 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006980 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006981 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006982 N0.getOperand(0), N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006983 AddToWorkList(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006984 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006985 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00006986 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006987
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006988 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006989}
6990
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006991SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6992 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006993 EVT VT = N->getValueType(0);
6994 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006995 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006996
Nate Begeman21158fc2005-09-01 00:19:25 +00006997 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00006998 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00006999 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007000 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00007001 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007002
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007003 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007004}
7005
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007006SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7007 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007008 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007009 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007010
Chris Lattner5919b482007-12-29 06:55:23 +00007011 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007012 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00007013 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007014 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00007015
Nate Begeman21158fc2005-09-01 00:19:25 +00007016 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007017 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007018 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00007019
7020 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7021 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00007022 if (N0.getOpcode() == ISD::FP_ROUND
7023 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007024 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00007025 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00007026 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007027 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007028 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00007029 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00007030 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007031
Chris Lattner72733e52008-01-17 07:00:52 +00007032 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00007033 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007034 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00007035 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007036 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007037 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007038 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007039 LN0->getBasePtr(), N0.getValueType(),
7040 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00007041 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00007042 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007043 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00007044 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00007045 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007046 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00007047 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00007048
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007049 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007050}
7051
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007052SDValue DAGCombiner::visitFNEG(SDNode *N) {
7053 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007054 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007055
Craig Topper82384612012-09-11 01:45:21 +00007056 if (VT.isVector()) {
7057 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7058 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper03f39772012-09-09 22:58:45 +00007059 }
7060
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007061 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7062 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007063 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00007064
Chris Lattner888560d2008-01-27 17:42:27 +00007065 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7066 // constant pool values.
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007067 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007068 !VT.isVector() &&
7069 N0.getNode()->hasOneUse() &&
7070 N0.getOperand(0).getValueType().isInteger()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007071 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007072 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007073 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007074 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007075 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007076 AddToWorkList(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007077 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007078 VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007079 }
7080 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007081
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007082 // (fneg (fmul c, x)) -> (fmul -c, x)
7083 if (N0.getOpcode() == ISD::FMUL) {
7084 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Stephen Lin8e8424e2013-07-09 00:44:49 +00007085 if (CFP1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007086 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007087 N0.getOperand(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007088 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007089 N0.getOperand(1)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007090 }
7091
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007092 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007093}
7094
Owen Andersona40319b2012-08-13 23:32:49 +00007095SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7096 SDValue N0 = N->getOperand(0);
7097 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7098 EVT VT = N->getValueType(0);
7099
7100 // fold (fceil c1) -> fceil(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007101 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007102 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007103
7104 return SDValue();
7105}
7106
7107SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7108 SDValue N0 = N->getOperand(0);
7109 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7110 EVT VT = N->getValueType(0);
7111
7112 // fold (ftrunc c1) -> ftrunc(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007113 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007114 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007115
7116 return SDValue();
7117}
7118
7119SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7120 SDValue N0 = N->getOperand(0);
7121 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7122 EVT VT = N->getValueType(0);
7123
7124 // fold (ffloor c1) -> ffloor(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007125 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007126 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007127
7128 return SDValue();
7129}
7130
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007131SDValue DAGCombiner::visitFABS(SDNode *N) {
7132 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007133 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007134 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007135
Craig Topper82384612012-09-11 01:45:21 +00007136 if (VT.isVector()) {
7137 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7138 if (FoldedVOp.getNode()) return FoldedVOp;
7139 }
7140
Nate Begeman21158fc2005-09-01 00:19:25 +00007141 // fold (fabs c1) -> fabs(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007142 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007143 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007144 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007145 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00007146 return N->getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007147 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007148 // fold (fabs (fcopysign x, y)) -> (fabs x)
7149 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007150 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007151
Chris Lattner888560d2008-01-27 17:42:27 +00007152 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7153 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00007154 if (!TLI.isFAbsFree(VT) &&
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007155 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00007156 N0.getOperand(0).getValueType().isInteger() &&
7157 !N0.getOperand(0).getValueType().isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007158 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007159 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007160 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007161 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007162 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007163 AddToWorkList(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007164 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007165 N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007166 }
7167 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007168
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007169 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007170}
7171
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007172SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7173 SDValue Chain = N->getOperand(0);
7174 SDValue N1 = N->getOperand(1);
7175 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007176
Dan Gohman82e80012009-11-17 00:47:23 +00007177 // If N is a constant we could fold this into a fallthrough or unconditional
7178 // branch. However that doesn't happen very often in normal code, because
7179 // Instcombine/SimplifyCFG should have handled the available opportunities.
7180 // If we did this folding here, it would be necessary to update the
7181 // MachineBasicBlock CFG, which is awkward.
7182
Nate Begeman7e7f4392006-02-01 07:19:44 +00007183 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7184 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007185 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00007186 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7187 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007188 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007189 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00007190 N1.getOperand(0), N1.getOperand(1), N2);
7191 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007192
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007193 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7194 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7195 (N1.getOperand(0).hasOneUse() &&
7196 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7197 SDNode *Trunc = 0;
7198 if (N1.getOpcode() == ISD::TRUNCATE) {
7199 // Look pass the truncate.
7200 Trunc = N1.getNode();
7201 N1 = N1.getOperand(0);
7202 }
Evan Cheng166a4e62010-01-06 19:38:29 +00007203
Bill Wendlingaa28be62009-03-26 06:14:09 +00007204 // Match this pattern so that we can generate simpler code:
7205 //
7206 // %a = ...
7207 // %b = and i32 %a, 2
7208 // %c = srl i32 %b, 1
7209 // brcond i32 %c ...
7210 //
7211 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00007212 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00007213 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00007214 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00007215 // %c = setcc eq %b, 0
7216 // brcond %c ...
7217 //
7218 // This applies only when the AND constant value has one bit set and the
7219 // SRL constant is equal to the log2 of the AND constant. The back-end is
7220 // smart enough to convert the result into a TEST/JMP sequence.
7221 SDValue Op0 = N1.getOperand(0);
7222 SDValue Op1 = N1.getOperand(1);
7223
7224 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00007225 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00007226 SDValue AndOp1 = Op0.getOperand(1);
7227
7228 if (AndOp1.getOpcode() == ISD::Constant) {
7229 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7230
7231 if (AndConst.isPowerOf2() &&
7232 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7233 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007234 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00007235 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00007236 Op0, DAG.getConstant(0, Op0.getValueType()),
7237 ISD::SETNE);
7238
Andrew Trickef9de2a2013-05-25 02:42:55 +00007239 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00007240 MVT::Other, Chain, SetCC, N2);
7241 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7242 // will convert it back to (X & C1) >> C2.
7243 CombineTo(N, NewBRCond, false);
7244 // Truncate is dead.
7245 if (Trunc) {
7246 removeFromWorkList(Trunc);
7247 DAG.DeleteNode(Trunc);
7248 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007249 // Replace the uses of SRL with SETCC
Evan Cheng228c31f2010-02-27 07:36:59 +00007250 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007251 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007252 removeFromWorkList(N1.getNode());
7253 DAG.DeleteNode(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00007254 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00007255 }
7256 }
7257 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007258
7259 if (Trunc)
7260 // Restore N1 if the above transformation doesn't match.
7261 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007262 }
Wesley Peck527da1b2010-11-23 03:31:01 +00007263
Evan Cheng228c31f2010-02-27 07:36:59 +00007264 // Transform br(xor(x, y)) -> br(x != y)
7265 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7266 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7267 SDNode *TheXor = N1.getNode();
7268 SDValue Op0 = TheXor->getOperand(0);
7269 SDValue Op1 = TheXor->getOperand(1);
7270 if (Op0.getOpcode() == Op1.getOpcode()) {
7271 // Avoid missing important xor optimizations.
7272 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007273 if (Tmp.getNode()) {
7274 if (Tmp.getNode() != TheXor) {
7275 DEBUG(dbgs() << "\nReplacing.8 ";
7276 TheXor->dump(&DAG);
7277 dbgs() << "\nWith: ";
7278 Tmp.getNode()->dump(&DAG);
7279 dbgs() << '\n');
7280 WorkListRemover DeadNodes(*this);
7281 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7282 removeFromWorkList(TheXor);
7283 DAG.DeleteNode(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007284 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00007285 MVT::Other, Chain, Tmp, N2);
7286 }
7287
Benjamin Kramer93354432013-03-30 21:28:18 +00007288 // visitXOR has changed XOR's operands or replaced the XOR completely,
7289 // bail out.
7290 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00007291 }
7292 }
7293
7294 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7295 bool Equal = false;
7296 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7297 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7298 Op0.getOpcode() == ISD::XOR) {
7299 TheXor = Op0.getNode();
7300 Equal = true;
7301 }
7302
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007303 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00007304 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00007305 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007306 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00007307 SetCCVT,
7308 Op0, Op1,
7309 Equal ? ISD::SETEQ : ISD::SETNE);
7310 // Replace the uses of XOR with SETCC
7311 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007312 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007313 removeFromWorkList(N1.getNode());
7314 DAG.DeleteNode(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007315 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00007316 MVT::Other, Chain, SetCC, N2);
7317 }
7318 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007319
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007320 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007321}
7322
Chris Lattnera49e16f2005-10-05 06:47:48 +00007323// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7324//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007325SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00007326 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007327 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007328
Dan Gohman82e80012009-11-17 00:47:23 +00007329 // If N is a constant we could fold this into a fallthrough or unconditional
7330 // branch. However that doesn't happen very often in normal code, because
7331 // Instcombine/SimplifyCFG should have handled the available opportunities.
7332 // If we did this folding here, it would be necessary to update the
7333 // MachineBasicBlock CFG, which is awkward.
7334
Duncan Sands93b66092008-06-09 11:32:28 +00007335 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00007336 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007337 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00007338 false);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007339 if (Simp.getNode()) AddToWorkList(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00007340
Nate Begemanbd7df032005-10-05 21:43:42 +00007341 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00007342 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007343 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007344 N->getOperand(0), Simp.getOperand(2),
7345 Simp.getOperand(0), Simp.getOperand(1),
7346 N->getOperand(4));
7347
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007348 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007349}
7350
Evan Chengfa832632012-01-13 01:37:24 +00007351/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7352/// uses N as its base pointer and that N may be folded in the load / store
Evan Cheng80893ce2012-03-06 23:33:32 +00007353/// addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00007354static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7355 SelectionDAG &DAG,
7356 const TargetLowering &TLI) {
7357 EVT VT;
7358 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7359 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7360 return false;
7361 VT = Use->getValueType(0);
7362 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7363 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7364 return false;
7365 VT = ST->getValue().getValueType();
7366 } else
7367 return false;
7368
Chandler Carruth95f83e02013-01-07 15:14:13 +00007369 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00007370 if (N->getOpcode() == ISD::ADD) {
7371 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7372 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007373 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007374 AM.BaseOffs = Offset->getSExtValue();
7375 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007376 // [reg +/- reg]
7377 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007378 } else if (N->getOpcode() == ISD::SUB) {
7379 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7380 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007381 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007382 AM.BaseOffs = -Offset->getSExtValue();
7383 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007384 // [reg +/- reg]
7385 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007386 } else
7387 return false;
7388
7389 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7390}
7391
Duncan Sands075293f2008-06-15 20:12:31 +00007392/// CombineToPreIndexedLoadStore - Try turning a load / store into a
7393/// pre-indexed load / store when the base pointer is an add or subtract
Chris Lattnerffad2162006-11-11 00:39:41 +00007394/// and it has other uses besides the load / store. After the
7395/// transformation, the new indexed load / store has effectively folded
7396/// the add / subtract in and all of its other uses are redirected to the
7397/// new load / store.
7398bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007399 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007400 return false;
7401
7402 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007403 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007404 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007405 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007406 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007407 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007408 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00007409 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00007410 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7411 return false;
7412 Ptr = LD->getBasePtr();
7413 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007414 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007415 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007416 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007417 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7418 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7419 return false;
7420 Ptr = ST->getBasePtr();
7421 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007422 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007423 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007424 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007425
Chris Lattnereabc15c2006-11-11 00:56:29 +00007426 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7427 // out. There is no reason to make this a preinc/predec.
7428 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00007429 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007430 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007431
Chris Lattnereabc15c2006-11-11 00:56:29 +00007432 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007433 SDValue BasePtr;
7434 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007435 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7436 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7437 return false;
Hal Finkel25819052013-02-08 21:35:47 +00007438
7439 // Backends without true r+i pre-indexed forms may need to pass a
7440 // constant base with a variable offset so that constant coercion
7441 // will work with the patterns in canonical form.
7442 bool Swapped = false;
7443 if (isa<ConstantSDNode>(BasePtr)) {
7444 std::swap(BasePtr, Offset);
7445 Swapped = true;
7446 }
7447
Evan Cheng044a0a82007-05-03 23:52:19 +00007448 // Don't create a indexed load / store with zero offset.
7449 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007450 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007451 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007452
Chris Lattnera0a80032006-11-11 01:00:15 +00007453 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00007454 // 1) The new base ptr is a frame index.
7455 // 2) If N is a store and the new base ptr is either the same as or is a
Chris Lattnereabc15c2006-11-11 00:56:29 +00007456 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00007457 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00007458 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00007459 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00007460
Chris Lattnera0a80032006-11-11 01:00:15 +00007461 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7462 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00007463 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00007464 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007465
Chris Lattnera0a80032006-11-11 01:00:15 +00007466 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007467 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007468 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00007469 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007470 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007471 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007472
Hal Finkel25819052013-02-08 21:35:47 +00007473 // If the offset is a constant, there may be other adds of constants that
7474 // can be folded with this one. We should do this to avoid having to keep
7475 // a copy of the original base pointer.
7476 SmallVector<SDNode *, 16> OtherUses;
7477 if (isa<ConstantSDNode>(Offset))
7478 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7479 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7480 SDNode *Use = *I;
7481 if (Use == Ptr.getNode())
7482 continue;
7483
7484 if (Use->isPredecessorOf(N))
7485 continue;
7486
7487 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7488 OtherUses.clear();
7489 break;
7490 }
7491
7492 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7493 if (Op1.getNode() == BasePtr.getNode())
7494 std::swap(Op0, Op1);
7495 assert(Op0.getNode() == BasePtr.getNode() &&
7496 "Use of ADD/SUB but not an operand");
7497
7498 if (!isa<ConstantSDNode>(Op1)) {
7499 OtherUses.clear();
7500 break;
7501 }
7502
7503 // FIXME: In some cases, we can be smarter about this.
7504 if (Op1.getValueType() != Offset.getValueType()) {
7505 OtherUses.clear();
7506 break;
7507 }
7508
7509 OtherUses.push_back(Use);
7510 }
7511
7512 if (Swapped)
7513 std::swap(BasePtr, Offset);
7514
Evan Chenga4d187b2007-05-24 02:35:39 +00007515 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007516 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00007517
7518 // Caches for hasPredecessorHelper
7519 SmallPtrSet<const SDNode *, 32> Visited;
7520 SmallVector<const SDNode *, 16> Worklist;
7521
Gabor Greiff304a7a2008-08-28 21:40:38 +00007522 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7523 E = Ptr.getNode()->use_end(); I != E; ++I) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00007524 SDNode *Use = *I;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007525 if (Use == N)
7526 continue;
Lang Hames5a004992011-07-07 04:31:51 +00007527 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007528 return false;
7529
Evan Chengfa832632012-01-13 01:37:24 +00007530 // If Ptr may be folded in addressing mode of other use, then it's
7531 // not profitable to do this transformation.
7532 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007533 RealUse = true;
7534 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007535
Chris Lattnereabc15c2006-11-11 00:56:29 +00007536 if (!RealUse)
7537 return false;
7538
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007539 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007540 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007541 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007542 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007543 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00007544 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007545 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007546 ++PreIndexedNodes;
7547 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007548 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007549 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007550 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007551 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007552 dbgs() << '\n');
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007553 WorkListRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007554 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007555 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7556 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007557 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007558 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007559 }
7560
Chris Lattnereabc15c2006-11-11 00:56:29 +00007561 // Finally, since the node is now dead, remove it from the graph.
7562 DAG.DeleteNode(N);
7563
Hal Finkel25819052013-02-08 21:35:47 +00007564 if (Swapped)
7565 std::swap(BasePtr, Offset);
7566
7567 // Replace other uses of BasePtr that can be updated to use Ptr
7568 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7569 unsigned OffsetIdx = 1;
7570 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7571 OffsetIdx = 0;
7572 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7573 BasePtr.getNode() && "Expected BasePtr operand");
7574
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007575 // We need to replace ptr0 in the following expression:
7576 // x0 * offset0 + y0 * ptr0 = t0
7577 // knowing that
7578 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00007579 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007580 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7581 // indexed load/store and the expresion that needs to be re-written.
7582 //
7583 // Therefore, we have:
7584 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00007585
7586 ConstantSDNode *CN =
7587 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007588 int X0, X1, Y0, Y1;
7589 APInt Offset0 = CN->getAPIntValue();
7590 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00007591
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007592 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7593 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7594 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7595 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00007596
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007597 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7598
7599 APInt CNV = Offset0;
7600 if (X0 < 0) CNV = -CNV;
7601 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7602 else CNV = CNV - Offset1;
7603
7604 // We can now generate the new expression.
7605 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7606 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7607
7608 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00007609 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00007610 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7611 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7612 removeFromWorkList(OtherUses[i]);
7613 DAG.DeleteNode(OtherUses[i]);
7614 }
7615
Chris Lattnereabc15c2006-11-11 00:56:29 +00007616 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007617 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007618 removeFromWorkList(Ptr.getNode());
7619 DAG.DeleteNode(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00007620
7621 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007622}
7623
Duncan Sands075293f2008-06-15 20:12:31 +00007624/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
Chris Lattnerffad2162006-11-11 00:39:41 +00007625/// add / sub of the base pointer node into a post-indexed load / store.
7626/// The transformation folded the add / subtract into the new indexed
7627/// load / store effectively and all of its uses are redirected to the
7628/// new load / store.
7629bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007630 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007631 return false;
7632
7633 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007634 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007635 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007636 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007637 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007638 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007639 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007640 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7641 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7642 return false;
7643 Ptr = LD->getBasePtr();
7644 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007645 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007646 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007647 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007648 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7649 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7650 return false;
7651 Ptr = ST->getBasePtr();
7652 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007653 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007654 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007655 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007656
Gabor Greiff304a7a2008-08-28 21:40:38 +00007657 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007658 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007659
Gabor Greiff304a7a2008-08-28 21:40:38 +00007660 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7661 E = Ptr.getNode()->use_end(); I != E; ++I) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00007662 SDNode *Op = *I;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007663 if (Op == N ||
7664 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7665 continue;
7666
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007667 SDValue BasePtr;
7668 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007669 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7670 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00007671 // Don't create a indexed load / store with zero offset.
7672 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007673 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007674 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007675
Chris Lattnereabc15c2006-11-11 00:56:29 +00007676 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00007677 // 1) All uses are load / store ops that use it as base ptr (and
7678 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00007679 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7680 // nor a successor of N. Otherwise, if Op is folded that would
7681 // create a cycle.
7682
Evan Chengcfc05132009-05-06 18:25:01 +00007683 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7684 continue;
7685
Chris Lattnereabc15c2006-11-11 00:56:29 +00007686 // Check for #1.
7687 bool TryNext = false;
Gabor Greiff304a7a2008-08-28 21:40:38 +00007688 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7689 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00007690 SDNode *Use = *II;
Gabor Greiff304a7a2008-08-28 21:40:38 +00007691 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00007692 continue;
7693
Chris Lattnereabc15c2006-11-11 00:56:29 +00007694 // If all the uses are load / store addresses, then don't do the
7695 // transformation.
7696 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7697 bool RealUse = false;
7698 for (SDNode::use_iterator III = Use->use_begin(),
7699 EEE = Use->use_end(); III != EEE; ++III) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00007700 SDNode *UseUse = *III;
Stephen Lincfe7f352013-07-08 00:37:03 +00007701 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007702 RealUse = true;
7703 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007704
Chris Lattnereabc15c2006-11-11 00:56:29 +00007705 if (!RealUse) {
7706 TryNext = true;
7707 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00007708 }
7709 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007710 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007711
Chris Lattnereabc15c2006-11-11 00:56:29 +00007712 if (TryNext)
7713 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007714
Chris Lattnereabc15c2006-11-11 00:56:29 +00007715 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00007716 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007717 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00007718 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007719 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007720 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007721 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007722 ++PostIndexedNodes;
7723 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007724 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007725 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007726 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007727 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007728 dbgs() << '\n');
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007729 WorkListRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007730 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007731 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7732 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007733 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007734 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00007735 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007736
Chris Lattnereabc15c2006-11-11 00:56:29 +00007737 // Finally, since the node is now dead, remove it from the graph.
7738 DAG.DeleteNode(N);
7739
7740 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007741 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007742 Result.getValue(isLoad ? 1 : 0));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007743 removeFromWorkList(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007744 DAG.DeleteNode(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007745 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007746 }
7747 }
7748 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007749
Chris Lattnerffad2162006-11-11 00:39:41 +00007750 return false;
7751}
7752
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007753SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007754 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007755 SDValue Chain = LD->getChain();
7756 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00007757
Evan Chenga684cd22007-05-01 00:38:21 +00007758 // If load is not volatile and there are no uses of the loaded value (and
7759 // the updated indexed value in case of indexed loads), change uses of the
7760 // chain value into uses of the chain input (i.e. delete the dead load).
7761 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00007762 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00007763 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00007764 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00007765 // It's not safe to use the two value CombineTo variant here. e.g.
7766 // v1, chain2 = load chain1, loc
7767 // v2, chain3 = load chain2, loc
7768 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007769 // Now we replace use of chain2 with chain1. This makes the second load
7770 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00007771 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007772 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007773 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007774 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007775 dbgs() << "\n");
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007776 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007777 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00007778
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007779 if (N->use_empty()) {
7780 removeFromWorkList(N);
7781 DAG.DeleteNode(N);
7782 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007783
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007784 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00007785 }
Evan Chengb68343c2007-05-01 08:53:39 +00007786 } else {
7787 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00007788 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Craig Topper0515cd42012-01-07 18:31:09 +00007789 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
Dale Johannesen84935752009-02-06 23:05:02 +00007790 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Evan Cheng228c31f2010-02-27 07:36:59 +00007791 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007792 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007793 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007794 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007795 dbgs() << " and 2 other values\n");
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007796 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007797 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007798 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007799 DAG.getUNDEF(N->getValueType(1)));
7800 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Evan Cheng7be15282008-01-16 23:11:54 +00007801 removeFromWorkList(N);
Evan Cheng7be15282008-01-16 23:11:54 +00007802 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007803 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00007804 }
Evan Chenga684cd22007-05-01 00:38:21 +00007805 }
7806 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007807
Chris Lattnere260ed82005-10-10 22:04:48 +00007808 // If this load is directly stored, replace the load value with the stored
7809 // value.
7810 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00007811 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00007812 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007813 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00007814 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7815 if (PrevST->getBasePtr() == Ptr &&
7816 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00007817 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00007818 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00007819 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007820
Evan Cheng43cd9e32010-04-01 06:04:33 +00007821 // Try to infer better alignment information than the load already has.
7822 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00007823 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00007824 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7825 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007826 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00007827 LD->getValueType(0),
7828 Chain, Ptr, LD->getPointerInfo(),
7829 LD->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007830 LD->isVolatile(), LD->isNonTemporal(), Align,
7831 LD->getTBAAInfo());
Owen Andersonde89ecf2013-02-05 19:24:39 +00007832 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7833 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00007834 }
7835 }
7836
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00007837 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7838 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00007839#ifndef NDEBUG
7840 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7841 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7842 UseAA = false;
7843#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00007844 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00007845 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007846 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007847
Jim Laskey708d0db2006-10-04 16:53:27 +00007848 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00007849 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007850 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00007851
Jim Laskeyd07be232006-09-25 16:29:54 +00007852 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00007853 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007854 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007855 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00007856 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007857 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00007858 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007859 BetterChain, Ptr, LD->getMemoryVT(),
7860 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00007861 }
Jim Laskeyd07be232006-09-25 16:29:54 +00007862
Jim Laskey708d0db2006-10-04 16:53:27 +00007863 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00007864 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00007865 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00007866
Nate Begeman879d8f12009-09-15 00:18:30 +00007867 // Make sure the new and old chains are cleaned up.
7868 AddToWorkList(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00007869
Jim Laskeydcf983c2006-10-13 23:32:28 +00007870 // Replace uses with load result and token factor. Don't add users
7871 // to work list.
7872 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00007873 }
7874 }
7875
Evan Cheng357017f2006-11-03 03:06:21 +00007876 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00007877 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007878 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00007879
Quentin Colombetde0e0622013-10-11 18:29:42 +00007880 // Try to slice up N to more direct loads if the slices are mapped to
7881 // different register banks or pairing can take place.
7882 if (SliceUpLoad(N))
7883 return SDValue(N, 0);
7884
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007885 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00007886}
7887
Quentin Colombetde0e0622013-10-11 18:29:42 +00007888namespace {
7889/// \brief Helper structure used to slice a load in smaller loads.
7890/// Basically a slice is obtained from the following sequence:
7891/// Origin = load Ty1, Base
7892/// Shift = srl Ty1 Origin, CstTy Amount
7893/// Inst = trunc Shift to Ty2
7894///
7895/// Then, it will be rewriten into:
7896/// Slice = load SliceTy, Base + SliceOffset
7897/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7898///
7899/// SliceTy is deduced from the number of bits that are actually used to
7900/// build Inst.
7901struct LoadedSlice {
7902 /// \brief Helper structure used to compute the cost of a slice.
7903 struct Cost {
7904 /// Are we optimizing for code size.
7905 bool ForCodeSize;
7906 /// Various cost.
7907 unsigned Loads;
7908 unsigned Truncates;
7909 unsigned CrossRegisterBanksCopies;
7910 unsigned ZExts;
7911 unsigned Shift;
7912
7913 Cost(bool ForCodeSize = false)
7914 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7915 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7916
7917 /// \brief Get the cost of one isolated slice.
7918 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7919 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7920 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7921 EVT TruncType = LS.Inst->getValueType(0);
7922 EVT LoadedType = LS.getLoadedType();
7923 if (TruncType != LoadedType &&
7924 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7925 ZExts = 1;
7926 }
7927
7928 /// \brief Account for slicing gain in the current cost.
7929 /// Slicing provide a few gains like removing a shift or a
7930 /// truncate. This method allows to grow the cost of the original
7931 /// load with the gain from this slice.
7932 void addSliceGain(const LoadedSlice &LS) {
7933 // Each slice saves a truncate.
7934 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7935 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7936 LS.Inst->getOperand(0).getValueType()))
7937 ++Truncates;
7938 // If there is a shift amount, this slice gets rid of it.
7939 if (LS.Shift)
7940 ++Shift;
7941 // If this slice can merge a cross register bank copy, account for it.
7942 if (LS.canMergeExpensiveCrossRegisterBankCopy())
7943 ++CrossRegisterBanksCopies;
7944 }
7945
7946 Cost &operator+=(const Cost &RHS) {
7947 Loads += RHS.Loads;
7948 Truncates += RHS.Truncates;
7949 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
7950 ZExts += RHS.ZExts;
7951 Shift += RHS.Shift;
7952 return *this;
7953 }
7954
7955 bool operator==(const Cost &RHS) const {
7956 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
7957 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
7958 ZExts == RHS.ZExts && Shift == RHS.Shift;
7959 }
7960
7961 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
7962
7963 bool operator<(const Cost &RHS) const {
7964 // Assume cross register banks copies are as expensive as loads.
7965 // FIXME: Do we want some more target hooks?
7966 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
7967 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
7968 // Unless we are optimizing for code size, consider the
7969 // expensive operation first.
7970 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
7971 return ExpensiveOpsLHS < ExpensiveOpsRHS;
7972 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
7973 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
7974 }
7975
7976 bool operator>(const Cost &RHS) const { return RHS < *this; }
7977
7978 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
7979
7980 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
7981 };
7982 // The last instruction that represent the slice. This should be a
7983 // truncate instruction.
7984 SDNode *Inst;
7985 // The original load instruction.
7986 LoadSDNode *Origin;
7987 // The right shift amount in bits from the original load.
7988 unsigned Shift;
7989 // The DAG from which Origin came from.
7990 // This is used to get some contextual information about legal types, etc.
7991 SelectionDAG *DAG;
7992
7993 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
7994 unsigned Shift = 0, SelectionDAG *DAG = NULL)
7995 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
7996
7997 LoadedSlice(const LoadedSlice &LS)
7998 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
7999
8000 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8001 /// \return Result is \p BitWidth and has used bits set to 1 and
8002 /// not used bits set to 0.
8003 APInt getUsedBits() const {
8004 // Reproduce the trunc(lshr) sequence:
8005 // - Start from the truncated value.
8006 // - Zero extend to the desired bit width.
8007 // - Shift left.
8008 assert(Origin && "No original load to compare against.");
8009 unsigned BitWidth = Origin->getValueSizeInBits(0);
8010 assert(Inst && "This slice is not bound to an instruction");
8011 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8012 "Extracted slice is bigger than the whole type!");
8013 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8014 UsedBits.setAllBits();
8015 UsedBits = UsedBits.zext(BitWidth);
8016 UsedBits <<= Shift;
8017 return UsedBits;
8018 }
8019
8020 /// \brief Get the size of the slice to be loaded in bytes.
8021 unsigned getLoadedSize() const {
8022 unsigned SliceSize = getUsedBits().countPopulation();
8023 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8024 return SliceSize / 8;
8025 }
8026
8027 /// \brief Get the type that will be loaded for this slice.
8028 /// Note: This may not be the final type for the slice.
8029 EVT getLoadedType() const {
8030 assert(DAG && "Missing context");
8031 LLVMContext &Ctxt = *DAG->getContext();
8032 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8033 }
8034
8035 /// \brief Get the alignment of the load used for this slice.
8036 unsigned getAlignment() const {
8037 unsigned Alignment = Origin->getAlignment();
8038 unsigned Offset = getOffsetFromBase();
8039 if (Offset != 0)
8040 Alignment = MinAlign(Alignment, Alignment + Offset);
8041 return Alignment;
8042 }
8043
8044 /// \brief Check if this slice can be rewritten with legal operations.
8045 bool isLegal() const {
8046 // An invalid slice is not legal.
8047 if (!Origin || !Inst || !DAG)
8048 return false;
8049
8050 // Offsets are for indexed load only, we do not handle that.
8051 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8052 return false;
8053
8054 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8055
8056 // Check that the type is legal.
8057 EVT SliceType = getLoadedType();
8058 if (!TLI.isTypeLegal(SliceType))
8059 return false;
8060
8061 // Check that the load is legal for this type.
8062 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8063 return false;
8064
8065 // Check that the offset can be computed.
8066 // 1. Check its type.
8067 EVT PtrType = Origin->getBasePtr().getValueType();
8068 if (PtrType == MVT::Untyped || PtrType.isExtended())
8069 return false;
8070
8071 // 2. Check that it fits in the immediate.
8072 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8073 return false;
8074
8075 // 3. Check that the computation is legal.
8076 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8077 return false;
8078
8079 // Check that the zext is legal if it needs one.
8080 EVT TruncateType = Inst->getValueType(0);
8081 if (TruncateType != SliceType &&
8082 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8083 return false;
8084
8085 return true;
8086 }
8087
8088 /// \brief Get the offset in bytes of this slice in the original chunk of
8089 /// bits.
8090 /// \pre DAG != NULL.
8091 uint64_t getOffsetFromBase() const {
8092 assert(DAG && "Missing context.");
8093 bool IsBigEndian =
8094 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8095 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8096 uint64_t Offset = Shift / 8;
8097 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8098 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8099 "The size of the original loaded type is not a multiple of a"
8100 " byte.");
8101 // If Offset is bigger than TySizeInBytes, it means we are loading all
8102 // zeros. This should have been optimized before in the process.
8103 assert(TySizeInBytes > Offset &&
8104 "Invalid shift amount for given loaded size");
8105 if (IsBigEndian)
8106 Offset = TySizeInBytes - Offset - getLoadedSize();
8107 return Offset;
8108 }
8109
8110 /// \brief Generate the sequence of instructions to load the slice
8111 /// represented by this object and redirect the uses of this slice to
8112 /// this new sequence of instructions.
8113 /// \pre this->Inst && this->Origin are valid Instructions and this
8114 /// object passed the legal check: LoadedSlice::isLegal returned true.
8115 /// \return The last instruction of the sequence used to load the slice.
8116 SDValue loadSlice() const {
8117 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8118 const SDValue &OldBaseAddr = Origin->getBasePtr();
8119 SDValue BaseAddr = OldBaseAddr;
8120 // Get the offset in that chunk of bytes w.r.t. the endianess.
8121 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8122 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8123 if (Offset) {
8124 // BaseAddr = BaseAddr + Offset.
8125 EVT ArithType = BaseAddr.getValueType();
8126 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8127 DAG->getConstant(Offset, ArithType));
8128 }
8129
8130 // Create the type of the loaded slice according to its size.
8131 EVT SliceType = getLoadedType();
8132
8133 // Create the load for the slice.
8134 SDValue LastInst = DAG->getLoad(
8135 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8136 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8137 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8138 // If the final type is not the same as the loaded type, this means that
8139 // we have to pad with zero. Create a zero extend for that.
8140 EVT FinalType = Inst->getValueType(0);
8141 if (SliceType != FinalType)
8142 LastInst =
8143 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8144 return LastInst;
8145 }
8146
8147 /// \brief Check if this slice can be merged with an expensive cross register
8148 /// bank copy. E.g.,
8149 /// i = load i32
8150 /// f = bitcast i32 i to float
8151 bool canMergeExpensiveCrossRegisterBankCopy() const {
8152 if (!Inst || !Inst->hasOneUse())
8153 return false;
8154 SDNode *Use = *Inst->use_begin();
8155 if (Use->getOpcode() != ISD::BITCAST)
8156 return false;
8157 assert(DAG && "Missing context");
8158 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8159 EVT ResVT = Use->getValueType(0);
8160 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8161 const TargetRegisterClass *ArgRC =
8162 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8163 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8164 return false;
8165
8166 // At this point, we know that we perform a cross-register-bank copy.
8167 // Check if it is expensive.
8168 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8169 // Assume bitcasts are cheap, unless both register classes do not
8170 // explicitly share a common sub class.
8171 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8172 return false;
8173
8174 // Check if it will be merged with the load.
8175 // 1. Check the alignment constraint.
8176 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8177 ResVT.getTypeForEVT(*DAG->getContext()));
8178
8179 if (RequiredAlignment > getAlignment())
8180 return false;
8181
8182 // 2. Check that the load is a legal operation for that type.
8183 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8184 return false;
8185
8186 // 3. Check that we do not have a zext in the way.
8187 if (Inst->getValueType(0) != getLoadedType())
8188 return false;
8189
8190 return true;
8191 }
8192};
8193}
8194
Quentin Colombetde0e0622013-10-11 18:29:42 +00008195/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8196/// \p UsedBits looks like 0..0 1..1 0..0.
8197static bool areUsedBitsDense(const APInt &UsedBits) {
8198 // If all the bits are one, this is dense!
8199 if (UsedBits.isAllOnesValue())
8200 return true;
8201
8202 // Get rid of the unused bits on the right.
8203 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8204 // Get rid of the unused bits on the left.
8205 if (NarrowedUsedBits.countLeadingZeros())
8206 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8207 // Check that the chunk of bits is completely used.
8208 return NarrowedUsedBits.isAllOnesValue();
8209}
8210
8211/// \brief Check whether or not \p First and \p Second are next to each other
8212/// in memory. This means that there is no hole between the bits loaded
8213/// by \p First and the bits loaded by \p Second.
8214static bool areSlicesNextToEachOther(const LoadedSlice &First,
8215 const LoadedSlice &Second) {
8216 assert(First.Origin == Second.Origin && First.Origin &&
8217 "Unable to match different memory origins.");
8218 APInt UsedBits = First.getUsedBits();
8219 assert((UsedBits & Second.getUsedBits()) == 0 &&
8220 "Slices are not supposed to overlap.");
8221 UsedBits |= Second.getUsedBits();
8222 return areUsedBitsDense(UsedBits);
8223}
8224
8225/// \brief Adjust the \p GlobalLSCost according to the target
8226/// paring capabilities and the layout of the slices.
8227/// \pre \p GlobalLSCost should account for at least as many loads as
8228/// there is in the slices in \p LoadedSlices.
8229static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8230 LoadedSlice::Cost &GlobalLSCost) {
8231 unsigned NumberOfSlices = LoadedSlices.size();
8232 // If there is less than 2 elements, no pairing is possible.
8233 if (NumberOfSlices < 2)
8234 return;
8235
8236 // Sort the slices so that elements that are likely to be next to each
8237 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00008238 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8239 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8240 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8241 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8242 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00008243 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8244 // First (resp. Second) is the first (resp. Second) potentially candidate
8245 // to be placed in a paired load.
8246 const LoadedSlice *First = NULL;
8247 const LoadedSlice *Second = NULL;
8248 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8249 // Set the beginning of the pair.
8250 First = Second) {
8251
8252 Second = &LoadedSlices[CurrSlice];
8253
8254 // If First is NULL, it means we start a new pair.
8255 // Get to the next slice.
8256 if (!First)
8257 continue;
8258
8259 EVT LoadedType = First->getLoadedType();
8260
8261 // If the types of the slices are different, we cannot pair them.
8262 if (LoadedType != Second->getLoadedType())
8263 continue;
8264
8265 // Check if the target supplies paired loads for this type.
8266 unsigned RequiredAlignment = 0;
8267 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8268 // move to the next pair, this type is hopeless.
8269 Second = NULL;
8270 continue;
8271 }
8272 // Check if we meet the alignment requirement.
8273 if (RequiredAlignment > First->getAlignment())
8274 continue;
8275
8276 // Check that both loads are next to each other in memory.
8277 if (!areSlicesNextToEachOther(*First, *Second))
8278 continue;
8279
8280 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8281 --GlobalLSCost.Loads;
8282 // Move to the next pair.
8283 Second = NULL;
8284 }
8285}
8286
8287/// \brief Check the profitability of all involved LoadedSlice.
8288/// Currently, it is considered profitable if there is exactly two
8289/// involved slices (1) which are (2) next to each other in memory, and
8290/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8291///
8292/// Note: The order of the elements in \p LoadedSlices may be modified, but not
8293/// the elements themselves.
8294///
8295/// FIXME: When the cost model will be mature enough, we can relax
8296/// constraints (1) and (2).
8297static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8298 const APInt &UsedBits, bool ForCodeSize) {
8299 unsigned NumberOfSlices = LoadedSlices.size();
8300 if (StressLoadSlicing)
8301 return NumberOfSlices > 1;
8302
8303 // Check (1).
8304 if (NumberOfSlices != 2)
8305 return false;
8306
8307 // Check (2).
8308 if (!areUsedBitsDense(UsedBits))
8309 return false;
8310
8311 // Check (3).
8312 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8313 // The original code has one big load.
8314 OrigCost.Loads = 1;
8315 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8316 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8317 // Accumulate the cost of all the slices.
8318 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8319 GlobalSlicingCost += SliceCost;
8320
8321 // Account as cost in the original configuration the gain obtained
8322 // with the current slices.
8323 OrigCost.addSliceGain(LS);
8324 }
8325
8326 // If the target supports paired load, adjust the cost accordingly.
8327 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8328 return OrigCost > GlobalSlicingCost;
8329}
8330
8331/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8332/// operations, split it in the various pieces being extracted.
8333///
8334/// This sort of thing is introduced by SROA.
8335/// This slicing takes care not to insert overlapping loads.
8336/// \pre LI is a simple load (i.e., not an atomic or volatile load).
8337bool DAGCombiner::SliceUpLoad(SDNode *N) {
8338 if (Level < AfterLegalizeDAG)
8339 return false;
8340
8341 LoadSDNode *LD = cast<LoadSDNode>(N);
8342 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8343 !LD->getValueType(0).isInteger())
8344 return false;
8345
8346 // Keep track of already used bits to detect overlapping values.
8347 // In that case, we will just abort the transformation.
8348 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8349
8350 SmallVector<LoadedSlice, 4> LoadedSlices;
8351
8352 // Check if this load is used as several smaller chunks of bits.
8353 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8354 // of computation for each trunc.
8355 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8356 UI != UIEnd; ++UI) {
8357 // Skip the uses of the chain.
8358 if (UI.getUse().getResNo() != 0)
8359 continue;
8360
8361 SDNode *User = *UI;
8362 unsigned Shift = 0;
8363
8364 // Check if this is a trunc(lshr).
8365 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8366 isa<ConstantSDNode>(User->getOperand(1))) {
8367 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8368 User = *User->use_begin();
8369 }
8370
8371 // At this point, User is a Truncate, iff we encountered, trunc or
8372 // trunc(lshr).
8373 if (User->getOpcode() != ISD::TRUNCATE)
8374 return false;
8375
8376 // The width of the type must be a power of 2 and greater than 8-bits.
8377 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00008378 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00008379 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008380 unsigned Width = User->getValueSizeInBits(0);
8381 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8382 return 0;
8383
8384 // Build the slice for this chain of computations.
8385 LoadedSlice LS(User, LD, Shift, &DAG);
8386 APInt CurrentUsedBits = LS.getUsedBits();
8387
8388 // Check if this slice overlaps with another.
8389 if ((CurrentUsedBits & UsedBits) != 0)
8390 return false;
8391 // Update the bits used globally.
8392 UsedBits |= CurrentUsedBits;
8393
8394 // Check if the new slice would be legal.
8395 if (!LS.isLegal())
8396 return false;
8397
8398 // Record the slice.
8399 LoadedSlices.push_back(LS);
8400 }
8401
8402 // Abort slicing if it does not seem to be profitable.
8403 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8404 return false;
8405
8406 ++SlicedLoads;
8407
8408 // Rewrite each chain to use an independent load.
8409 // By construction, each chain can be represented by a unique load.
8410
8411 // Prepare the argument for the new token factor for all the slices.
8412 SmallVector<SDValue, 8> ArgChains;
8413 for (SmallVectorImpl<LoadedSlice>::const_iterator
8414 LSIt = LoadedSlices.begin(),
8415 LSItEnd = LoadedSlices.end();
8416 LSIt != LSItEnd; ++LSIt) {
8417 SDValue SliceInst = LSIt->loadSlice();
8418 CombineTo(LSIt->Inst, SliceInst, true);
8419 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8420 SliceInst = SliceInst.getOperand(0);
8421 assert(SliceInst->getOpcode() == ISD::LOAD &&
8422 "It takes more than a zext to get to the loaded slice!!");
8423 ArgChains.push_back(SliceInst.getValue(1));
8424 }
8425
8426 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8427 &ArgChains[0], ArgChains.size());
8428 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8429 return true;
8430}
8431
Chris Lattner4041ab62010-04-15 04:48:01 +00008432/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8433/// load is having specific bytes cleared out. If so, return the byte size
8434/// being masked out and the shift amount.
8435static std::pair<unsigned, unsigned>
8436CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8437 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008438
Chris Lattner4041ab62010-04-15 04:48:01 +00008439 // Check for the structure we're looking for.
8440 if (V->getOpcode() != ISD::AND ||
8441 !isa<ConstantSDNode>(V->getOperand(1)) ||
8442 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8443 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008444
Chris Lattner3245afd2010-04-15 06:10:49 +00008445 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00008446 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00008447 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00008448
Chris Lattner3245afd2010-04-15 06:10:49 +00008449 // The store should be chained directly to the load or be an operand of a
8450 // tokenfactor.
8451 if (LD == Chain.getNode())
8452 ; // ok.
8453 else if (Chain->getOpcode() != ISD::TokenFactor)
8454 return Result; // Fail.
8455 else {
8456 bool isOk = false;
8457 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8458 if (Chain->getOperand(i).getNode() == LD) {
8459 isOk = true;
8460 break;
8461 }
8462 if (!isOk) return Result;
8463 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008464
Chris Lattner4041ab62010-04-15 04:48:01 +00008465 // This only handles simple types.
8466 if (V.getValueType() != MVT::i16 &&
8467 V.getValueType() != MVT::i32 &&
8468 V.getValueType() != MVT::i64)
8469 return Result;
8470
8471 // Check the constant mask. Invert it so that the bits being masked out are
8472 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8473 // follow the sign bit for uniformity.
8474 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008475 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008476 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008477 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008478 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8479 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00008480
Chris Lattner4041ab62010-04-15 04:48:01 +00008481 // See if we have a continuous run of bits. If so, we have 0*1+0*
8482 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8483 return Result;
8484
8485 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8486 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8487 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00008488
Chris Lattner4041ab62010-04-15 04:48:01 +00008489 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8490 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00008491 case 1:
8492 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00008493 case 4: break;
8494 default: return Result; // All one mask, or 5-byte mask.
8495 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008496
Chris Lattner4041ab62010-04-15 04:48:01 +00008497 // Verify that the first bit starts at a multiple of mask so that the access
8498 // is aligned the same as the access width.
8499 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008500
Chris Lattner4041ab62010-04-15 04:48:01 +00008501 Result.first = MaskedBytes;
8502 Result.second = NotMaskTZ/8;
8503 return Result;
8504}
8505
8506
8507/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8508/// provides a value as specified by MaskInfo. If so, replace the specified
8509/// store with a narrower store of truncated IVal.
8510static SDNode *
8511ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8512 SDValue IVal, StoreSDNode *St,
8513 DAGCombiner *DC) {
8514 unsigned NumBytes = MaskInfo.first;
8515 unsigned ByteShift = MaskInfo.second;
8516 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00008517
Chris Lattner4041ab62010-04-15 04:48:01 +00008518 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8519 // that uses this. If not, this is not a replacement.
8520 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8521 ByteShift*8, (ByteShift+NumBytes)*8);
8522 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
Wesley Peck527da1b2010-11-23 03:31:01 +00008523
Chris Lattner4041ab62010-04-15 04:48:01 +00008524 // Check that it is legal on the target to do this. It is legal if the new
8525 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8526 // legalization.
8527 MVT VT = MVT::getIntegerVT(NumBytes*8);
8528 if (!DC->isTypeLegal(VT))
8529 return 0;
Wesley Peck527da1b2010-11-23 03:31:01 +00008530
Chris Lattner4041ab62010-04-15 04:48:01 +00008531 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8532 // shifted by ByteShift and truncated down to NumBytes.
8533 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008534 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00008535 DAG.getConstant(ByteShift*8,
8536 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00008537
8538 // Figure out the offset for the store and the alignment of the access.
8539 unsigned StOffset;
8540 unsigned NewAlign = St->getAlignment();
8541
8542 if (DAG.getTargetLoweringInfo().isLittleEndian())
8543 StOffset = ByteShift;
8544 else
8545 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00008546
Chris Lattner4041ab62010-04-15 04:48:01 +00008547 SDValue Ptr = St->getBasePtr();
8548 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008549 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00008550 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8551 NewAlign = MinAlign(NewAlign, StOffset);
8552 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008553
Chris Lattner4041ab62010-04-15 04:48:01 +00008554 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008555 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00008556
Chris Lattner4041ab62010-04-15 04:48:01 +00008557 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00008558 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00008559 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00008560 false, false, NewAlign).getNode();
8561}
8562
Evan Chenga9cda8a2009-05-28 00:35:15 +00008563
8564/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8565/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8566/// of the loaded bits, try narrowing the load and store if it would end up
8567/// being a win for performance or code size.
8568SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8569 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00008570 if (ST->isVolatile())
8571 return SDValue();
8572
Evan Chenga9cda8a2009-05-28 00:35:15 +00008573 SDValue Chain = ST->getChain();
8574 SDValue Value = ST->getValue();
8575 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00008576 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008577
8578 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +00008579 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008580
8581 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +00008582
Chris Lattner4041ab62010-04-15 04:48:01 +00008583 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8584 // is a byte mask indicating a consecutive number of bytes, check to see if
8585 // Y is known to provide just those bytes. If so, we try to replace the
8586 // load + replace + store sequence with a single (narrower) store, which makes
8587 // the load dead.
8588 if (Opc == ISD::OR) {
8589 std::pair<unsigned, unsigned> MaskedLoad;
8590 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8591 if (MaskedLoad.first)
8592 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8593 Value.getOperand(1), ST,this))
8594 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008595
Chris Lattner4041ab62010-04-15 04:48:01 +00008596 // Or is commutative, so try swapping X and Y.
8597 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8598 if (MaskedLoad.first)
8599 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8600 Value.getOperand(0), ST,this))
8601 return SDValue(NewST, 0);
8602 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008603
Evan Chenga9cda8a2009-05-28 00:35:15 +00008604 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8605 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +00008606 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008607
8608 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +00008609 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8610 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00008611 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008612 if (LD->getBasePtr() != Ptr ||
8613 LD->getPointerInfo().getAddrSpace() !=
8614 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +00008615 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008616
8617 // Find the type to narrow it the load / op / store to.
8618 SDValue N1 = Value.getOperand(1);
8619 unsigned BitWidth = N1.getValueSizeInBits();
8620 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8621 if (Opc == ISD::AND)
8622 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +00008623 if (Imm == 0 || Imm.isAllOnesValue())
8624 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008625 unsigned ShAmt = Imm.countTrailingZeros();
8626 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8627 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +00008628 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008629 while (NewBW < BitWidth &&
Evan Cheng6673ff02009-05-28 18:41:02 +00008630 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
Evan Chenga9cda8a2009-05-28 00:35:15 +00008631 TLI.isNarrowingProfitable(VT, NewVT))) {
8632 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +00008633 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008634 }
Evan Cheng6673ff02009-05-28 18:41:02 +00008635 if (NewBW >= BitWidth)
8636 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008637
8638 // If the lsb changed does not start at the type bitwidth boundary,
8639 // start at the previous one.
8640 if (ShAmt % NewBW)
8641 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +00008642 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8643 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008644 if ((Imm & Mask) == Imm) {
8645 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8646 if (Opc == ISD::AND)
8647 NewImm ^= APInt::getAllOnesValue(NewBW);
8648 uint64_t PtrOff = ShAmt / 8;
8649 // For big endian targets, we need to adjust the offset to the pointer to
8650 // load the correct bytes.
8651 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +00008652 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +00008653
8654 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +00008655 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008656 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +00008657 return SDValue();
8658
Andrew Trickef9de2a2013-05-25 02:42:55 +00008659 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008660 Ptr.getValueType(), Ptr,
8661 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008662 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008663 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008664 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008665 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008666 LD->isInvariant(), NewAlign,
8667 LD->getTBAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008668 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +00008669 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008670 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008671 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008672 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008673 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008674
8675 AddToWorkList(NewPtr.getNode());
8676 AddToWorkList(NewLD.getNode());
8677 AddToWorkList(NewVal.getNode());
8678 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008679 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008680 ++OpsNarrowed;
8681 return NewST;
8682 }
8683 }
8684
Evan Cheng6673ff02009-05-28 18:41:02 +00008685 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008686}
8687
Evan Chengd42641c2011-02-02 01:06:55 +00008688/// TransformFPLoadStorePair - For a given floating point load / store pair,
8689/// if the load value isn't used by any other operations, then consider
8690/// transforming the pair to integer load / store operations if the target
8691/// deems the transformation profitable.
8692SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8693 StoreSDNode *ST = cast<StoreSDNode>(N);
8694 SDValue Chain = ST->getChain();
8695 SDValue Value = ST->getValue();
8696 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8697 Value.hasOneUse() &&
8698 Chain == SDValue(Value.getNode(), 1)) {
8699 LoadSDNode *LD = cast<LoadSDNode>(Value);
8700 EVT VT = LD->getMemoryVT();
8701 if (!VT.isFloatingPoint() ||
8702 VT != ST->getMemoryVT() ||
8703 LD->isNonTemporal() ||
8704 ST->isNonTemporal() ||
8705 LD->getPointerInfo().getAddrSpace() != 0 ||
8706 ST->getPointerInfo().getAddrSpace() != 0)
8707 return SDValue();
8708
8709 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8710 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8711 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8712 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8713 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8714 return SDValue();
8715
8716 unsigned LDAlign = LD->getAlignment();
8717 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +00008718 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008719 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +00008720 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8721 return SDValue();
8722
Andrew Trickef9de2a2013-05-25 02:42:55 +00008723 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +00008724 LD->getChain(), LD->getBasePtr(),
8725 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00008726 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +00008727
Andrew Trickef9de2a2013-05-25 02:42:55 +00008728 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +00008729 NewLD, ST->getBasePtr(),
8730 ST->getPointerInfo(),
8731 false, false, STAlign);
8732
8733 AddToWorkList(NewLD.getNode());
8734 AddToWorkList(NewST.getNode());
8735 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008736 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +00008737 ++LdStFP2Int;
8738 return NewST;
8739 }
8740
8741 return SDValue();
8742}
8743
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008744/// Helper struct to parse and store a memory address as base + index + offset.
8745/// We ignore sign extensions when it is safe to do so.
8746/// The following two expressions are not equivalent. To differentiate we need
8747/// to store whether there was a sign extension involved in the index
8748/// computation.
8749/// (load (i64 add (i64 copyfromreg %c)
8750/// (i64 signextend (add (i8 load %index)
8751/// (i8 1))))
8752/// vs
8753///
8754/// (load (i64 add (i64 copyfromreg %c)
8755/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8756/// (i32 1)))))
8757struct BaseIndexOffset {
8758 SDValue Base;
8759 SDValue Index;
8760 int64_t Offset;
8761 bool IsIndexSignExt;
8762
8763 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8764
8765 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8766 bool IsIndexSignExt) :
8767 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8768
8769 bool equalBaseIndex(const BaseIndexOffset &Other) {
8770 return Other.Base == Base && Other.Index == Index &&
8771 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008772 }
8773
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008774 /// Parses tree in Ptr for base, index, offset addresses.
8775 static BaseIndexOffset match(SDValue Ptr) {
8776 bool IsIndexSignExt = false;
8777
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008778 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8779 // instruction, then it could be just the BASE or everything else we don't
8780 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008781 if (Ptr->getOpcode() != ISD::ADD)
8782 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8783
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008784 // We know that we have at least an ADD instruction. Try to pattern match
8785 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008786 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8787 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8788 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8789 IsIndexSignExt);
8790 }
8791
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008792 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +00008793 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008794 // (i64 add (i64 %array_ptr)
8795 // (i64 mul (i64 %induction_var)
8796 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +00008797 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008798 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008799
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008800 // Look at Base + Index + Offset cases.
8801 SDValue Base = Ptr->getOperand(0);
8802 SDValue IndexOffset = Ptr->getOperand(1);
8803
8804 // Skip signextends.
8805 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8806 IndexOffset = IndexOffset->getOperand(0);
8807 IsIndexSignExt = true;
8808 }
8809
8810 // Either the case of Base + Index (no offset) or something else.
8811 if (IndexOffset->getOpcode() != ISD::ADD)
8812 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8813
8814 // Now we have the case of Base + Index + offset.
8815 SDValue Index = IndexOffset->getOperand(0);
8816 SDValue Offset = IndexOffset->getOperand(1);
8817
8818 if (!isa<ConstantSDNode>(Offset))
8819 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8820
8821 // Ignore signextends.
8822 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8823 Index = Index->getOperand(0);
8824 IsIndexSignExt = true;
8825 } else IsIndexSignExt = false;
8826
8827 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8828 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8829 }
8830};
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008831
8832/// Holds a pointer to an LSBaseSDNode as well as information on where it
8833/// is located in a sequence of memory operations connected by a chain.
8834struct MemOpLink {
8835 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8836 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8837 // Ptr to the mem node.
8838 LSBaseSDNode *MemNode;
8839 // Offset from the base ptr.
8840 int64_t OffsetFromBase;
8841 // What is the sequence number of this mem node.
8842 // Lowest mem operand in the DAG starts at zero.
8843 unsigned SequenceNum;
8844};
8845
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008846bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8847 EVT MemVT = St->getMemoryVT();
8848 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Nadav Rotem495b1a42013-02-14 18:28:52 +00008849 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8850 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008851
8852 // Don't merge vectors into wider inputs.
8853 if (MemVT.isVector() || !MemVT.isSimple())
8854 return false;
8855
8856 // Perform an early exit check. Do not bother looking at stored values that
8857 // are not constants or loads.
8858 SDValue StoredVal = St->getValue();
8859 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8860 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8861 !IsLoadSrc)
8862 return false;
8863
8864 // Only look at ends of store sequences.
8865 SDValue Chain = SDValue(St, 1);
8866 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8867 return false;
8868
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008869 // This holds the base pointer, index, and the offset in bytes from the base
8870 // pointer.
8871 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008872
8873 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008874 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008875 return false;
8876
8877 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008878 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008879 return false;
8880
Nadav Rotem307d7672012-11-29 00:00:08 +00008881 // Save the LoadSDNodes that we find in the chain.
8882 // We need to make sure that these nodes do not interfere with
8883 // any of the store nodes.
8884 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8885
8886 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008887 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +00008888
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008889 // Walk up the chain and look for nodes with offsets from the same
8890 // base pointer. Stop when reaching an instruction with a different kind
8891 // or instruction which has a different base pointer.
8892 unsigned Seq = 0;
8893 StoreSDNode *Index = St;
8894 while (Index) {
8895 // If the chain has more than one use, then we can't reorder the mem ops.
8896 if (Index != St && !SDValue(Index, 1)->hasOneUse())
8897 break;
8898
8899 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008900 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008901
8902 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008903 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008904 break;
8905
8906 // Check that the alignment is the same.
8907 if (Index->getAlignment() != St->getAlignment())
8908 break;
8909
8910 // The memory operands must not be volatile.
8911 if (Index->isVolatile() || Index->isIndexed())
8912 break;
8913
8914 // No truncation.
8915 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8916 if (St->isTruncatingStore())
8917 break;
8918
8919 // The stored memory type must be the same.
8920 if (Index->getMemoryVT() != MemVT)
8921 break;
8922
8923 // We do not allow unaligned stores because we want to prevent overriding
8924 // stores.
8925 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8926 break;
8927
8928 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008929 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008930
Nadav Rotem307d7672012-11-29 00:00:08 +00008931 // Find the next memory operand in the chain. If the next operand in the
8932 // chain is a store then move up and continue the scan with the next
8933 // memory operand. If the next operand is a load save it and use alias
8934 // information to check if it interferes with anything.
8935 SDNode *NextInChain = Index->getChain().getNode();
8936 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +00008937 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +00008938 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +00008939 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +00008940 break;
8941 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +00008942 if (Ldn->isVolatile()) {
8943 Index = NULL;
8944 break;
8945 }
8946
Nadav Rotem307d7672012-11-29 00:00:08 +00008947 // Save the load node for later. Continue the scan.
8948 AliasLoadNodes.push_back(Ldn);
8949 NextInChain = Ldn->getChain().getNode();
8950 continue;
8951 } else {
8952 Index = NULL;
8953 break;
8954 }
8955 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008956 }
8957
8958 // Check if there is anything to merge.
8959 if (StoreNodes.size() < 2)
8960 return false;
8961
8962 // Sort the memory operands according to their distance from the base pointer.
8963 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00008964 [](MemOpLink LHS, MemOpLink RHS) {
8965 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
8966 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
8967 LHS.SequenceNum > RHS.SequenceNum);
8968 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008969
8970 // Scan the memory operations on the chain and find the first non-consecutive
8971 // store memory address.
8972 unsigned LastConsecutiveStore = 0;
8973 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +00008974 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8975
8976 // Check that the addresses are consecutive starting from the second
8977 // element in the list of stores.
8978 if (i > 0) {
8979 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8980 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8981 break;
8982 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008983
Nadav Rotem307d7672012-11-29 00:00:08 +00008984 bool Alias = false;
8985 // Check if this store interferes with any of the loads that we found.
8986 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8987 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8988 Alias = true;
8989 break;
8990 }
Nadav Rotem307d7672012-11-29 00:00:08 +00008991 // We found a load that alias with this store. Stop the sequence.
8992 if (Alias)
8993 break;
8994
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008995 // Mark this node as useful.
8996 LastConsecutiveStore = i;
8997 }
8998
8999 // The node with the lowest store address.
9000 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9001
9002 // Store the constants into memory as one consecutive store.
9003 if (!IsLoadSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009004 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009005 unsigned LastLegalVectorType = 0;
9006 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009007 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9008 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9009 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009010
9011 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009012 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009013 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009014 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009015 } else {
Alp Tokerf907b892013-12-05 05:44:44 +00009016 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009017 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009018 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009019
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009020 // Find a legal type for the constant store.
9021 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9022 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9023 if (TLI.isTypeLegal(StoreTy))
9024 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009025 // Or check whether a truncstore is legal.
9026 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9027 TargetLowering::TypePromoteInteger) {
9028 EVT LegalizedStoredValueTy =
9029 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9030 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9031 LastLegalType = i+1;
9032 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009033
9034 // Find a legal type for the vector store.
9035 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9036 if (TLI.isTypeLegal(Ty))
9037 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009038 }
9039
Bob Wilson3365b802012-12-20 01:36:20 +00009040 // We only use vectors if the constant is known to be zero and the
9041 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009042 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +00009043 LastLegalVectorType = 0;
9044
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009045 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +00009046 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009047 return false;
9048
Nadav Rotem495b1a42013-02-14 18:28:52 +00009049 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009050 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9051
9052 // Make sure we have something to merge.
9053 if (NumElem < 2)
9054 return false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009055
9056 unsigned EarliestNodeUsed = 0;
9057 for (unsigned i=0; i < NumElem; ++i) {
9058 // Find a chain for the new wide-store operand. Notice that some
9059 // of the store nodes that we found may not be selected for inclusion
9060 // in the wide store. The chain we use needs to be the chain of the
9061 // earliest store node which is *used* and replaced by the wide store.
9062 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9063 EarliestNodeUsed = i;
9064 }
9065
9066 // The earliest Node in the DAG.
9067 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009068 SDLoc DL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009069
Nadav Rotemb27777f2012-10-04 22:35:15 +00009070 SDValue StoredVal;
9071 if (UseVector) {
9072 // Find a legal type for the vector store.
9073 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9074 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9075 StoredVal = DAG.getConstant(0, Ty);
9076 } else {
9077 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9078 APInt StoreInt(StoreBW, 0);
9079
9080 // Construct a single integer constant which is made of the smaller
9081 // constant inputs.
9082 bool IsLE = TLI.isLittleEndian();
9083 for (unsigned i = 0; i < NumElem ; ++i) {
9084 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9085 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9086 SDValue Val = St->getValue();
9087 StoreInt<<=ElementSizeBytes*8;
9088 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9089 StoreInt|=C->getAPIntValue().zext(StoreBW);
9090 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9091 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9092 } else {
9093 assert(false && "Invalid constant element type");
9094 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009095 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009096
9097 // Create the new Load and Store operations.
9098 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9099 StoredVal = DAG.getConstant(StoreInt, StoreTy);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009100 }
9101
Nadav Rotemb27777f2012-10-04 22:35:15 +00009102 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009103 FirstInChain->getBasePtr(),
9104 FirstInChain->getPointerInfo(),
9105 false, false,
9106 FirstInChain->getAlignment());
9107
9108 // Replace the first store with the new store
9109 CombineTo(EarliestOp, NewStore);
9110 // Erase all other stores.
9111 for (unsigned i = 0; i < NumElem ; ++i) {
9112 if (StoreNodes[i].MemNode == EarliestOp)
9113 continue;
9114 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Rafael Espindolac79532d2012-11-14 05:08:56 +00009115 // ReplaceAllUsesWith will replace all uses that existed when it was
9116 // called, but graph optimizations may cause new ones to appear. For
9117 // example, the case in pr14333 looks like
9118 //
9119 // St's chain -> St -> another store -> X
9120 //
9121 // And the only difference from St to the other store is the chain.
9122 // When we change it's chain to be St's chain they become identical,
9123 // get CSEed and the net result is that X is now a use of St.
9124 // Since we know that St is redundant, just iterate.
9125 while (!St->use_empty())
9126 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009127 removeFromWorkList(St);
9128 DAG.DeleteNode(St);
9129 }
9130
9131 return true;
9132 }
9133
9134 // Below we handle the case of multiple consecutive stores that
9135 // come from multiple consecutive loads. We merge them into a single
9136 // wide load and a single wide store.
9137
9138 // Look for load nodes which are used by the stored values.
9139 SmallVector<MemOpLink, 8> LoadNodes;
9140
9141 // Find acceptable loads. Loads need to have the same chain (token factor),
9142 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009143 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009144 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9145 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9146 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9147 if (!Ld) break;
9148
9149 // Loads must only have one use.
9150 if (!Ld->hasNUsesOfValue(1, 0))
9151 break;
9152
9153 // Check that the alignment is the same as the stores.
9154 if (Ld->getAlignment() != St->getAlignment())
9155 break;
9156
9157 // The memory operands must not be volatile.
9158 if (Ld->isVolatile() || Ld->isIndexed())
9159 break;
9160
9161 // We do not accept ext loads.
9162 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9163 break;
9164
9165 // The stored memory type must be the same.
9166 if (Ld->getMemoryVT() != MemVT)
9167 break;
9168
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009169 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009170 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009171 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009172 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009173 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009174 break;
9175 } else {
9176 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009177 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009178 }
9179
9180 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009181 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009182 }
9183
9184 if (LoadNodes.size() < 2)
9185 return false;
9186
9187 // Scan the memory operations on the chain and find the first non-consecutive
9188 // load memory address. These variables hold the index in the store node
9189 // array.
9190 unsigned LastConsecutiveLoad = 0;
9191 // This variable refers to the size and not index in the array.
9192 unsigned LastLegalVectorType = 0;
9193 unsigned LastLegalIntegerType = 0;
9194 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +00009195 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9196 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9197 // All loads much share the same chain.
9198 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9199 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009200
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009201 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9202 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9203 break;
9204 LastConsecutiveLoad = i;
9205
9206 // Find a legal type for the vector store.
9207 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9208 if (TLI.isTypeLegal(StoreTy))
9209 LastLegalVectorType = i + 1;
9210
9211 // Find a legal type for the integer store.
9212 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9213 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9214 if (TLI.isTypeLegal(StoreTy))
9215 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009216 // Or check whether a truncstore and extload is legal.
9217 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9218 TargetLowering::TypePromoteInteger) {
9219 EVT LegalizedStoredValueTy =
9220 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9221 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9222 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9223 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9224 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9225 LastLegalIntegerType = i+1;
9226 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009227 }
9228
9229 // Only use vector types if the vector type is larger than the integer type.
9230 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009231 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009232 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9233
9234 // We add +1 here because the LastXXX variables refer to location while
9235 // the NumElem refers to array/index size.
9236 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9237 NumElem = std::min(LastLegalType, NumElem);
9238
9239 if (NumElem < 2)
9240 return false;
9241
9242 // The earliest Node in the DAG.
9243 unsigned EarliestNodeUsed = 0;
9244 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9245 for (unsigned i=1; i<NumElem; ++i) {
9246 // Find a chain for the new wide-store operand. Notice that some
9247 // of the store nodes that we found may not be selected for inclusion
9248 // in the wide store. The chain we use needs to be the chain of the
9249 // earliest store node which is *used* and replaced by the wide store.
9250 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9251 EarliestNodeUsed = i;
9252 }
9253
9254 // Find if it is better to use vectors or integers to load and store
9255 // to memory.
9256 EVT JointMemOpVT;
9257 if (UseVectorTy) {
9258 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9259 } else {
9260 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9261 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9262 }
9263
Andrew Trickef9de2a2013-05-25 02:42:55 +00009264 SDLoc LoadDL(LoadNodes[0].MemNode);
9265 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009266
9267 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9268 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9269 FirstLoad->getChain(),
9270 FirstLoad->getBasePtr(),
9271 FirstLoad->getPointerInfo(),
9272 false, false, false,
9273 FirstLoad->getAlignment());
9274
9275 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9276 FirstInChain->getBasePtr(),
9277 FirstInChain->getPointerInfo(), false, false,
9278 FirstInChain->getAlignment());
9279
Nadav Rotemac920662012-10-03 19:30:31 +00009280 // Replace one of the loads with the new load.
9281 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9282 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9283 SDValue(NewLoad.getNode(), 1));
9284
9285 // Remove the rest of the load chains.
9286 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009287 // Replace all chain users of the old load nodes with the chain of the new
9288 // load node.
9289 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +00009290 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9291 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009292
Nadav Rotemac920662012-10-03 19:30:31 +00009293 // Replace the first store with the new store.
9294 CombineTo(EarliestOp, NewStore);
9295 // Erase all other stores.
9296 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009297 // Remove all Store nodes.
9298 if (StoreNodes[i].MemNode == EarliestOp)
9299 continue;
9300 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9301 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9302 removeFromWorkList(St);
9303 DAG.DeleteNode(St);
9304 }
9305
9306 return true;
9307}
9308
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009309SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +00009310 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009311 SDValue Chain = ST->getChain();
9312 SDValue Value = ST->getValue();
9313 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009314
Evan Chenga4cf58a2007-05-07 21:27:48 +00009315 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +00009316 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +00009317 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009318 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +00009319 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009320 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009321 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00009322 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +00009323 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009324 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +00009325 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009326 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +00009327 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009328 ST->isNonTemporal(), OrigAlign,
9329 ST->getTBAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +00009330 }
Owen Andersona5192842011-04-14 17:30:49 +00009331
Chris Lattner41c80e82011-04-09 02:32:02 +00009332 // Turn 'store undef, Ptr' -> nothing.
9333 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9334 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +00009335
Nate Begeman8e20c762006-12-11 02:23:46 +00009336 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +00009337 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00009338 // NOTE: If the original store is volatile, this transform must not increase
9339 // the number of stores. For example, on x86-32 an f64 can be stored in one
9340 // processor operation but an i64 (which is not legal) requires two. So the
9341 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +00009342 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009343 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +00009344 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00009345 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +00009346 case MVT::f16: // We don't do this for these yet.
9347 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +00009348 case MVT::f128:
9349 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +00009350 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009351 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +00009352 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009353 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +00009354 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +00009355 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009356 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009357 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +00009358 }
9359 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009360 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +00009361 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +00009362 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009363 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00009364 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +00009365 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009366 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009367 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +00009368 }
Owen Andersona5192842011-04-14 17:30:49 +00009369
Chris Lattner41c80e82011-04-09 02:32:02 +00009370 if (!ST->isVolatile() &&
9371 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +00009372 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +00009373 // argument passing. Since this is so common, custom legalize the
9374 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +00009375 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +00009376 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9377 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +00009378 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009379
Dan Gohman2af30632007-07-09 22:18:38 +00009380 unsigned Alignment = ST->getAlignment();
9381 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +00009382 bool isNonTemporal = ST->isNonTemporal();
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009383 const MDNode *TBAAInfo = ST->getTBAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +00009384
Andrew Trickef9de2a2013-05-25 02:42:55 +00009385 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +00009386 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00009387 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009388 ST->getAlignment(), TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009389 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +00009390 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +00009391 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009392 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +00009393 Ptr, ST->getPointerInfo().getWithOffset(4),
9394 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009395 Alignment, TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009396 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +00009397 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009398 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009399
Chris Lattnerb7524b62006-12-12 04:16:14 +00009400 break;
Evan Cheng21836982006-12-11 17:25:19 +00009401 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009402 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009403 }
9404
Evan Cheng43cd9e32010-04-01 06:04:33 +00009405 // Try to infer better alignment information than the store already has.
9406 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009407 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9408 if (Align > ST->getAlignment())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009409 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +00009410 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009411 ST->isVolatile(), ST->isNonTemporal(), Align,
9412 ST->getTBAAInfo());
Evan Cheng43cd9e32010-04-01 06:04:33 +00009413 }
9414 }
9415
Evan Chengd42641c2011-02-02 01:06:55 +00009416 // Try transforming a pair floating point load / store ops to integer
9417 // load / store ops.
9418 SDValue NewST = TransformFPLoadStorePair(N);
9419 if (NewST.getNode())
9420 return NewST;
9421
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00009422 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9423 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00009424#ifndef NDEBUG
9425 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9426 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9427 UseAA = false;
9428#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00009429 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009430 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009431 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009432
Jim Laskey708d0db2006-10-04 16:53:27 +00009433 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009434 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009435 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +00009436
9437 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009438 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009439 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009440 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009441 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009442 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009443 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009444 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009445
Jim Laskeyd07be232006-09-25 16:29:54 +00009446 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009447 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009448 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009449
Nate Begeman879d8f12009-09-15 00:18:30 +00009450 // Make sure the new and old chains are cleaned up.
9451 AddToWorkList(Token.getNode());
9452
Jim Laskeydcf983c2006-10-13 23:32:28 +00009453 // Don't add users to work list.
9454 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009455 }
Jim Laskey5d19d592006-09-21 16:28:59 +00009456 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009457
Evan Cheng33157702006-11-05 09:31:14 +00009458 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +00009459 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009460 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +00009461
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009462 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009463 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009464 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00009465 // See if we can simplify the input to this truncstore with knowledge that
9466 // only the low bits are being used. For example:
9467 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +00009468 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +00009469 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009470 APInt::getLowBitsSet(
9471 Value.getValueType().getScalarType().getSizeInBits(),
9472 ST->getMemoryVT().getScalarType().getSizeInBits()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00009473 AddToWorkList(Value.getNode());
9474 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009475 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009476 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +00009477
Chris Lattnerf47e3062007-10-13 06:58:48 +00009478 // Otherwise, see if we can simplify the operation with
9479 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00009480 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009481 APInt::getLowBitsSet(
9482 Value.getValueType().getScalarType().getSizeInBits(),
9483 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009484 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +00009485 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009486
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009487 // If this is a load followed by a store to the same location, then the store
9488 // is dead/noop.
9489 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009490 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009491 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +00009492 // There can't be any side effects between the load and store, such as
9493 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009494 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009495 // The store is dead, remove it.
9496 return Chain;
9497 }
9498 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009499
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009500 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9501 // truncating store. We can do this even if this is already a truncstore.
9502 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +00009503 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009504 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009505 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009506 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009507 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009508 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009509
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009510 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +00009511 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +00009512 if (!LegalTypes) {
9513 bool EverChanged = false;
9514
9515 do {
9516 // There can be multiple store sequences on the same chain.
9517 // Keep trying to merge store sequences until we are unable to do so
9518 // or until we merge the last store on the chain.
9519 bool Changed = MergeConsecutiveStores(ST);
9520 EverChanged |= Changed;
9521 if (!Changed) break;
9522 } while (ST->getOpcode() != ISD::DELETED_NODE);
9523
9524 if (EverChanged)
9525 return SDValue(N, 0);
9526 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009527
Evan Chenga9cda8a2009-05-28 00:35:15 +00009528 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +00009529}
9530
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009531SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9532 SDValue InVec = N->getOperand(0);
9533 SDValue InVal = N->getOperand(1);
9534 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009535 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009536
Bob Wilson42603952010-05-19 23:42:58 +00009537 // If the inserted element is an UNDEF, just use the input vector.
9538 if (InVal.getOpcode() == ISD::UNDEF)
9539 return InVec;
9540
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009541 EVT VT = InVec.getValueType();
9542
Owen Andersonb2c80da2011-02-25 21:41:48 +00009543 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009544 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9545 return SDValue();
9546
Eli Friedmanb7910b72011-09-09 21:04:06 +00009547 // Check that we know which element is being inserted
9548 if (!isa<ConstantSDNode>(EltNo))
9549 return SDValue();
9550 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009551
Eli Friedmanb7910b72011-09-09 21:04:06 +00009552 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9553 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9554 // vector elements.
9555 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +00009556 // Do not combine these two vectors if the output vector will not replace
9557 // the input vector.
9558 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +00009559 Ops.append(InVec.getNode()->op_begin(),
9560 InVec.getNode()->op_end());
9561 } else if (InVec.getOpcode() == ISD::UNDEF) {
9562 unsigned NElts = VT.getVectorNumElements();
9563 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9564 } else {
9565 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +00009566 }
Eli Friedmanb7910b72011-09-09 21:04:06 +00009567
9568 // Insert the element
9569 if (Elt < Ops.size()) {
9570 // All the operands of BUILD_VECTOR must have the same type;
9571 // we enforce that here.
9572 EVT OpVT = Ops[0].getValueType();
9573 if (InVal.getValueType() != OpVT)
9574 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9575 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9576 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9577 Ops[Elt] = InVal;
9578 }
9579
9580 // Return the new vector
9581 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9582 VT, &Ops[0], Ops.size());
Chris Lattner5336a592006-03-19 01:27:56 +00009583}
9584
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009585SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +00009586 // (vextract (scalar_to_vector val, 0) -> val
9587 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009588 EVT VT = InVec.getValueType();
9589 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +00009590
Duncan Sands6be291a2011-05-09 08:03:33 +00009591 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9592 // Check if the result type doesn't match the inserted element type. A
9593 // SCALAR_TO_VECTOR may truncate the inserted element and the
9594 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9595 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +00009596 if (InOp.getValueType() != NVT) {
9597 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +00009598 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +00009599 }
9600 return InOp;
9601 }
Evan Cheng1120279a2008-05-13 08:35:03 +00009602
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009603 SDValue EltNo = N->getOperand(1);
9604 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9605
9606 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9607 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +00009608 // we may introduce new vector instructions which are not backed by TD
9609 // patterns. For example on AVX, extracting elements from a wide vector
9610 // without using extract_subvector.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009611 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9612 && ConstEltNo && !LegalOperations) {
9613 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9614 int NumElem = VT.getVectorNumElements();
9615 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9616 // Find the new index to extract from.
9617 int OrigElt = SVOp->getMaskElt(Elt);
9618
9619 // Extracting an undef index is undef.
9620 if (OrigElt == -1)
9621 return DAG.getUNDEF(NVT);
9622
9623 // Select the right vector half to extract from.
9624 if (OrigElt < NumElem) {
9625 InVec = InVec->getOperand(0);
9626 } else {
9627 InVec = InVec->getOperand(1);
9628 OrigElt -= NumElem;
9629 }
9630
Tom Stellardd42c5942013-08-05 22:22:01 +00009631 EVT IndexTy = TLI.getVectorIdxTy();
Andrew Trickef9de2a2013-05-25 02:42:55 +00009632 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00009633 InVec, DAG.getConstant(OrigElt, IndexTy));
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009634 }
9635
Evan Cheng1120279a2008-05-13 08:35:03 +00009636 // Perform only after legalization to ensure build_vector / vector_shuffle
9637 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009638 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009639
Mon P Wangca6d6de2009-01-17 00:07:25 +00009640 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9641 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9642 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +00009643
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009644 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +00009645 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +00009646 bool NewLoad = false;
Mon P Wangb5eb7202008-12-11 00:26:16 +00009647 bool BCNumEltsChanged = false;
Owen Anderson53aa7a92009-08-10 22:56:29 +00009648 EVT ExtVT = VT.getVectorElementType();
9649 EVT LVT = ExtVT;
Bill Wendling27d9dd42009-01-30 23:36:47 +00009650
Evan Cheng7bf83092012-03-13 22:00:52 +00009651 // If the result of load has to be truncated, then it's not necessarily
9652 // profitable.
Evan Chengd5f8e572012-03-13 22:16:11 +00009653 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
Evan Cheng7bf83092012-03-13 22:00:52 +00009654 return SDValue();
9655
Wesley Peck527da1b2010-11-23 03:31:01 +00009656 if (InVec.getOpcode() == ISD::BITCAST) {
Eli Friedmane96286c2011-12-26 22:49:32 +00009657 // Don't duplicate a load with other uses.
9658 if (!InVec.hasOneUse())
9659 return SDValue();
9660
Owen Anderson53aa7a92009-08-10 22:56:29 +00009661 EVT BCVT = InVec.getOperand(0).getValueType();
9662 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009663 return SDValue();
Mon P Wangb5eb7202008-12-11 00:26:16 +00009664 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9665 BCNumEltsChanged = true;
Evan Cheng1120279a2008-05-13 08:35:03 +00009666 InVec = InVec.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00009667 ExtVT = BCVT.getVectorElementType();
Evan Cheng1120279a2008-05-13 08:35:03 +00009668 NewLoad = true;
9669 }
Evan Cheng0de312d2007-10-06 08:19:55 +00009670
Evan Cheng1120279a2008-05-13 08:35:03 +00009671 LoadSDNode *LN0 = NULL;
Nate Begeman5f829d82009-04-29 05:20:52 +00009672 const ShuffleVectorSDNode *SVN = NULL;
Bill Wendling27d9dd42009-01-30 23:36:47 +00009673 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009674 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009675 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +00009676 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +00009677 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +00009678 // Don't duplicate a load with other uses.
9679 if (!InVec.hasOneUse())
9680 return SDValue();
9681
Evan Cheng1120279a2008-05-13 08:35:03 +00009682 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +00009683 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009684 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9685 // =>
9686 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +00009687
Eli Friedmane96286c2011-12-26 22:49:32 +00009688 // Don't duplicate a load with other uses.
9689 if (!InVec.hasOneUse())
9690 return SDValue();
9691
Mon P Wangb5eb7202008-12-11 00:26:16 +00009692 // If the bit convert changed the number of elements, it is unsafe
9693 // to examine the mask.
9694 if (BCNumEltsChanged)
9695 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +00009696
9697 // Select the input vector, guarding against out of range extract vector.
9698 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +00009699 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +00009700 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9701
Eli Friedmane96286c2011-12-26 22:49:32 +00009702 if (InVec.getOpcode() == ISD::BITCAST) {
9703 // Don't duplicate a load with other uses.
9704 if (!InVec.hasOneUse())
9705 return SDValue();
9706
Evan Cheng1120279a2008-05-13 08:35:03 +00009707 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +00009708 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00009709 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009710 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +00009711 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Evan Cheng0de312d2007-10-06 08:19:55 +00009712 }
9713 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009714
Eli Friedmane96286c2011-12-26 22:49:32 +00009715 // Make sure we found a non-volatile load and the extractelement is
9716 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +00009717 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009718 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009719
Eric Christopherc6418b12010-11-03 20:44:42 +00009720 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9721 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +00009722 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +00009723
Evan Cheng1120279a2008-05-13 08:35:03 +00009724 unsigned Align = LN0->getAlignment();
9725 if (NewLoad) {
9726 // Check the resultant load doesn't need a higher alignment than the
9727 // original load.
Bill Wendling27d9dd42009-01-30 23:36:47 +00009728 unsigned NewAlign =
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009729 TLI.getDataLayout()
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009730 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
Bill Wendling27d9dd42009-01-30 23:36:47 +00009731
Dan Gohman4aa18462009-01-28 17:46:25 +00009732 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009733 return SDValue();
Bill Wendling27d9dd42009-01-30 23:36:47 +00009734
Evan Cheng1120279a2008-05-13 08:35:03 +00009735 Align = NewAlign;
9736 }
9737
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009738 SDValue NewPtr = LN0->getBasePtr();
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009739 unsigned PtrOff = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +00009740
Eric Christopherc6418b12010-11-03 20:44:42 +00009741 if (Elt) {
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009742 PtrOff = LVT.getSizeInBits() * Elt / 8;
Owen Anderson53aa7a92009-08-10 22:56:29 +00009743 EVT PtrType = NewPtr.getValueType();
Evan Cheng1120279a2008-05-13 08:35:03 +00009744 if (TLI.isBigEndian())
Duncan Sands13237ac2008-06-06 12:08:01 +00009745 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009746 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
Evan Cheng1120279a2008-05-13 08:35:03 +00009747 DAG.getConstant(PtrOff, PtrType));
9748 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009749
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009750 // The replacement we need to do here is a little tricky: we need to
9751 // replace an extractelement of a load with a load.
9752 // Use ReplaceAllUsesOfValuesWith to do the replacement.
Eli Friedmane96286c2011-12-26 22:49:32 +00009753 // Note that this replacement assumes that the extractvalue is the only
9754 // use of the load; that's okay because we don't want to perform this
9755 // transformation in other cases anyway.
Evan Cheng7bf83092012-03-13 22:00:52 +00009756 SDValue Load;
Evan Chengd5f8e572012-03-13 22:16:11 +00009757 SDValue Chain;
Evan Cheng7bf83092012-03-13 22:00:52 +00009758 if (NVT.bitsGT(LVT)) {
9759 // If the result type of vextract is wider than the load, then issue an
9760 // extending load instead.
9761 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9762 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009763 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
Evan Cheng7bf83092012-03-13 22:00:52 +00009764 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009765 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9766 Align, LN0->getTBAAInfo());
Evan Chengd5f8e572012-03-13 22:16:11 +00009767 Chain = Load.getValue(1);
9768 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009769 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
Evan Cheng7bf83092012-03-13 22:00:52 +00009770 LN0->getPointerInfo().getWithOffset(PtrOff),
Stephen Lincfe7f352013-07-08 00:37:03 +00009771 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009772 LN0->isInvariant(), Align, LN0->getTBAAInfo());
Evan Chengd5f8e572012-03-13 22:16:11 +00009773 Chain = Load.getValue(1);
9774 if (NVT.bitsLT(LVT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009775 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
Evan Chengd5f8e572012-03-13 22:16:11 +00009776 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00009777 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
Evan Chengd5f8e572012-03-13 22:16:11 +00009778 }
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009779 WorkListRemover DeadNodes(*this);
9780 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
Evan Chengd5f8e572012-03-13 22:16:11 +00009781 SDValue To[] = { Load, Chain };
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009782 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009783 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9784 // worklist explicitly as well.
9785 AddToWorkList(Load.getNode());
Craig Topperaaeae982012-03-20 05:28:39 +00009786 AddUsersToWorkList(Load.getNode()); // Add users too
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009787 // Make sure to revisit this node to clean it up; it will usually be dead.
9788 AddToWorkList(N);
9789 return SDValue(N, 0);
Evan Cheng0de312d2007-10-06 08:19:55 +00009790 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009791
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009792 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +00009793}
Evan Cheng0de312d2007-10-06 08:19:55 +00009794
Michael Liao6d106b72012-10-23 23:06:52 +00009795// Simplify (build_vec (ext )) to (bitcast (build_vec ))
9796SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9797 // We perform this optimization post type-legalization because
9798 // the type-legalizer often scalarizes integer-promoted vectors.
9799 // Performing this optimization before may create bit-casts which
9800 // will be type-legalized to complex code sequences.
9801 // We perform this optimization only before the operation legalizer because we
9802 // may introduce illegal operations.
9803 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9804 return SDValue();
9805
Dan Gohmana8665142007-06-25 16:23:39 +00009806 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +00009807 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +00009808 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +00009809
Nadav Rotembf6568b2011-10-29 21:23:04 +00009810 // Check to see if this is a BUILD_VECTOR of a bunch of values
9811 // which come from any_extend or zero_extend nodes. If so, we can create
9812 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +00009813 // optimizations. We do not handle sign-extend because we can't fill the sign
9814 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009815 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +00009816 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +00009817
Craig Topper02cb0fb2012-01-17 09:09:48 +00009818 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +00009819 SDValue In = N->getOperand(i);
9820 // Ignore undef inputs.
9821 if (In.getOpcode() == ISD::UNDEF) continue;
9822
9823 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9824 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9825
Nadav Rotemf3103612011-10-31 20:08:25 +00009826 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009827 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +00009828 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009829 break;
9830 }
9831
9832 // The input is a ZeroExt or AnyExt. Check the original type.
9833 EVT InTy = In.getOperand(0).getValueType();
9834
9835 // Check that all of the widened source types are the same.
9836 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +00009837 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009838 SourceType = InTy;
9839 else if (InTy != SourceType) {
9840 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +00009841 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009842 break;
9843 }
9844
9845 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +00009846 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009847 }
9848
Nadav Rotemf3103612011-10-31 20:08:25 +00009849 // In order to have valid types, all of the inputs must be extended from the
9850 // same source type and all of the inputs must be any or zero extend.
9851 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +00009852 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +00009853 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +00009854 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9855 isPowerOf2_32(SourceType.getSizeInBits());
9856
Nadav Rotem6fd1d322012-03-15 08:49:06 +00009857 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9858 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +00009859 if (!ValidTypes)
9860 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +00009861
Michael Liao6d106b72012-10-23 23:06:52 +00009862 bool isLE = TLI.isLittleEndian();
9863 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9864 assert(ElemRatio > 1 && "Invalid element size ratio");
9865 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9866 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +00009867
Michael Liao6d106b72012-10-23 23:06:52 +00009868 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9869 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +00009870
Michael Liao6d106b72012-10-23 23:06:52 +00009871 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +00009872 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +00009873 SDValue Cast = N->getOperand(i);
9874 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9875 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9876 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9877 SDValue In;
9878 if (Cast.getOpcode() == ISD::UNDEF)
9879 In = DAG.getUNDEF(SourceType);
9880 else
9881 In = Cast->getOperand(0);
9882 unsigned Index = isLE ? (i * ElemRatio) :
9883 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +00009884
Michael Liao6d106b72012-10-23 23:06:52 +00009885 assert(Index < Ops.size() && "Invalid index");
9886 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009887 }
Chris Lattner5336a592006-03-19 01:27:56 +00009888
Michael Liao6d106b72012-10-23 23:06:52 +00009889 // The type of the new BUILD_VECTOR node.
9890 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9891 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9892 "Invalid vector size");
9893 // Check if the new vector type is legal.
9894 if (!isTypeLegal(VecVT)) return SDValue();
9895
9896 // Make the new BUILD_VECTOR.
9897 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9898
9899 // The new BUILD_VECTOR node has the potential to be further optimized.
9900 AddToWorkList(BV.getNode());
9901 // Bitcast to the desired type.
9902 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9903}
9904
Michael Liao59229792012-10-24 04:14:18 +00009905SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9906 EVT VT = N->getValueType(0);
9907
9908 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +00009909 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +00009910
9911 EVT SrcVT = MVT::Other;
9912 unsigned Opcode = ISD::DELETED_NODE;
9913 unsigned NumDefs = 0;
9914
9915 for (unsigned i = 0; i != NumInScalars; ++i) {
9916 SDValue In = N->getOperand(i);
9917 unsigned Opc = In.getOpcode();
9918
9919 if (Opc == ISD::UNDEF)
9920 continue;
9921
9922 // If all scalar values are floats and converted from integers.
9923 if (Opcode == ISD::DELETED_NODE &&
9924 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9925 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +00009926 }
Tom Stellard567f8862013-01-02 22:13:01 +00009927
Michael Liao59229792012-10-24 04:14:18 +00009928 if (Opc != Opcode)
9929 return SDValue();
9930
9931 EVT InVT = In.getOperand(0).getValueType();
9932
9933 // If all scalar values are typed differently, bail out. It's chosen to
9934 // simplify BUILD_VECTOR of integer types.
9935 if (SrcVT == MVT::Other)
9936 SrcVT = InVT;
9937 if (SrcVT != InVT)
9938 return SDValue();
9939 NumDefs++;
9940 }
9941
9942 // If the vector has just one element defined, it's not worth to fold it into
9943 // a vectorized one.
9944 if (NumDefs < 2)
9945 return SDValue();
9946
9947 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9948 && "Should only handle conversion from integer to float.");
9949 assert(SrcVT != MVT::Other && "Cannot determine source type!");
9950
9951 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +00009952
9953 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9954 return SDValue();
9955
Michael Liao59229792012-10-24 04:14:18 +00009956 SmallVector<SDValue, 8> Opnds;
9957 for (unsigned i = 0; i != NumInScalars; ++i) {
9958 SDValue In = N->getOperand(i);
9959
9960 if (In.getOpcode() == ISD::UNDEF)
9961 Opnds.push_back(DAG.getUNDEF(SrcVT));
9962 else
9963 Opnds.push_back(In.getOperand(0));
9964 }
9965 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9966 &Opnds[0], Opnds.size());
9967 AddToWorkList(BV.getNode());
9968
9969 return DAG.getNode(Opcode, dl, VT, BV);
9970}
9971
Michael Liao6d106b72012-10-23 23:06:52 +00009972SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9973 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +00009974 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +00009975 EVT VT = N->getValueType(0);
9976
9977 // A vector built entirely of undefs is undef.
9978 if (ISD::allOperandsUndef(N))
9979 return DAG.getUNDEF(VT);
9980
9981 SDValue V = reduceBuildVecExtToExtBuildVec(N);
9982 if (V.getNode())
9983 return V;
9984
Michael Liao59229792012-10-24 04:14:18 +00009985 V = reduceBuildVecConvertToConvertBuildVec(N);
9986 if (V.getNode())
9987 return V;
9988
Dan Gohmana8665142007-06-25 16:23:39 +00009989 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9990 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9991 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +00009992
9993 // May only combine to shuffle after legalize if shuffle is legal.
9994 if (LegalOperations &&
9995 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9996 return SDValue();
9997
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009998 SDValue VecIn1, VecIn2;
Chris Lattnerc9992542006-03-28 20:28:38 +00009999 for (unsigned i = 0; i != NumInScalars; ++i) {
10000 // Ignore undef inputs.
10001 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010002
Dan Gohmana8665142007-06-25 16:23:39 +000010003 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000010004 // constant index, bail out.
Dan Gohmana8665142007-06-25 16:23:39 +000010005 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Chris Lattnerc9992542006-03-28 20:28:38 +000010006 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010007 VecIn1 = VecIn2 = SDValue(0, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010008 break;
10009 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010010
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010011 // We allow up to two distinct input vectors.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010012 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010013 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10014 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010015
Gabor Greiff304a7a2008-08-28 21:40:38 +000010016 if (VecIn1.getNode() == 0) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010017 VecIn1 = ExtractedFromVec;
Gabor Greiff304a7a2008-08-28 21:40:38 +000010018 } else if (VecIn2.getNode() == 0) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010019 VecIn2 = ExtractedFromVec;
10020 } else {
10021 // Too many inputs.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010022 VecIn1 = VecIn2 = SDValue(0, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010023 break;
10024 }
10025 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010026
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010027 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010028 if (VecIn1.getNode()) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010029 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000010030 for (unsigned i = 0; i != NumInScalars; ++i) {
10031 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010032 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010033 continue;
10034 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010035
Rafael Espindolab93db662009-04-24 12:40:33 +000010036 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010037 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000010038 SDValue ExtVal = Extract.getOperand(1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010039 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000010040 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10041 if (ExtIndex > VT.getVectorNumElements())
10042 return SDValue();
Wesley Peck527da1b2010-11-23 03:31:01 +000010043
Nate Begeman5f829d82009-04-29 05:20:52 +000010044 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000010045 continue;
10046 }
10047
10048 // Otherwise, use InIdx + VecSize
Mon P Wang523c0852009-03-17 06:33:10 +000010049 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010050 Mask.push_back(Idx+NumInScalars);
Chris Lattnerc9992542006-03-28 20:28:38 +000010051 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010052
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010053 // We can't generate a shuffle node with mismatched input and output types.
10054 // Attempt to transform a single input vector to the correct type.
10055 if ((VT != VecIn1.getValueType())) {
10056 // We don't support shuffeling between TWO values of different types.
10057 if (VecIn2.getNode() != 0)
10058 return SDValue();
10059
10060 // We only support widening of vectors which are half the size of the
10061 // output registers. For example XMM->YMM widening on X86 with AVX.
10062 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10063 return SDValue();
10064
James Molloy1e5c6112012-09-10 14:01:21 +000010065 // If the input vector type has a different base type to the output
10066 // vector type, bail out.
10067 if (VecIn1.getValueType().getVectorElementType() !=
10068 VT.getVectorElementType())
10069 return SDValue();
10070
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010071 // Widen the input vector by adding undef values.
Michael Liao6d106b72012-10-23 23:06:52 +000010072 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010073 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010074 }
10075
10076 // If VecIn2 is unused then change it to undef.
10077 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10078
Nadav Rotem841c9a82012-09-20 08:53:31 +000010079 // Check that we were able to transform all incoming values to the same
10080 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000010081 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10082 VecIn1.getValueType() != VT)
10083 return SDValue();
10084
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010085 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
Nadav Rotem0c650642012-02-13 12:42:26 +000010086 if (!isTypeLegal(VT))
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010087 return SDValue();
10088
Dan Gohmana8665142007-06-25 16:23:39 +000010089 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010090 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000010091 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010092 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000010093 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000010094 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010095
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010096 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000010097}
10098
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010099SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000010100 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10101 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10102 // inputs come from at most two distinct vectors, turn this into a shuffle
10103 // node.
10104
10105 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000010106 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000010107 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010108
Nadav Rotem01892102012-07-14 21:30:27 +000010109 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010110 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010111 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010112 return DAG.getUNDEF(VT);
10113
10114 // Optimize concat_vectors where one of the vectors is undef.
10115 if (N->getNumOperands() == 2 &&
10116 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10117 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000010118 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010119
10120 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10121 if (In->getOpcode() == ISD::BITCAST &&
10122 !In->getOperand(0)->getValueType(0).isVector()) {
10123 SDValue Scalar = In->getOperand(0);
10124 EVT SclTy = Scalar->getValueType(0);
10125
10126 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10127 return SDValue();
10128
10129 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10130 VT.getSizeInBits() / SclTy.getSizeInBits());
10131 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10132 return SDValue();
10133
10134 SDLoc dl = SDLoc(N);
10135 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10136 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10137 }
10138 }
Nadav Rotem01892102012-07-14 21:30:27 +000010139
Robert Lougher7d9084f2014-02-11 15:42:46 +000010140 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10141 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10142 if (N->getNumOperands() == 2 &&
10143 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10144 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10145 EVT VT = N->getValueType(0);
10146 SDValue N0 = N->getOperand(0);
10147 SDValue N1 = N->getOperand(1);
10148 SmallVector<SDValue, 8> Opnds;
10149 unsigned BuildVecNumElts = N0.getNumOperands();
10150
10151 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10152 Opnds.push_back(N0.getOperand(i));
10153 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10154 Opnds.push_back(N1.getOperand(i));
10155
10156 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
10157 Opnds.size());
10158 }
10159
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010160 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10161 // nodes often generate nop CONCAT_VECTOR nodes.
10162 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10163 // place the incoming vectors at the exact same location.
10164 SDValue SingleSource = SDValue();
10165 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10166
10167 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10168 SDValue Op = N->getOperand(i);
10169
10170 if (Op.getOpcode() == ISD::UNDEF)
10171 continue;
10172
10173 // Check if this is the identity extract:
10174 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10175 return SDValue();
10176
10177 // Find the single incoming vector for the extract_subvector.
10178 if (SingleSource.getNode()) {
10179 if (Op.getOperand(0) != SingleSource)
10180 return SDValue();
10181 } else {
10182 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000010183
10184 // Check the source type is the same as the type of the result.
10185 // If not, this concat may extend the vector, so we can not
10186 // optimize it away.
10187 if (SingleSource.getValueType() != N->getValueType(0))
10188 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010189 }
10190
10191 unsigned IdentityIndex = i * PartNumElem;
10192 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10193 // The extract index must be constant.
10194 if (!CS)
10195 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000010196
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010197 // Check that we are reading from the identity index.
10198 if (CS->getZExtValue() != IdentityIndex)
10199 return SDValue();
10200 }
10201
10202 if (SingleSource.getNode())
10203 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000010204
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010205 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000010206}
10207
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010208SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10209 EVT NVT = N->getValueType(0);
10210 SDValue V = N->getOperand(0);
10211
Michael Liao7a442c802012-10-17 20:48:33 +000010212 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10213 // Combine:
10214 // (extract_subvec (concat V1, V2, ...), i)
10215 // Into:
10216 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000010217 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10218 // type.
Michael Liao2c235802012-10-19 03:17:00 +000010219 if (V->getOperand(0).getValueType() != NVT)
10220 return SDValue();
Michael Liao7a442c802012-10-17 20:48:33 +000010221 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10222 unsigned NumElems = NVT.getVectorNumElements();
10223 assert((Idx % NumElems) == 0 &&
10224 "IDX in concat is not a multiple of the result vector length.");
10225 return V->getOperand(Idx / NumElems);
10226 }
10227
Michael Liaobb05a1d2013-03-25 23:47:35 +000010228 // Skip bitcasting
10229 if (V->getOpcode() == ISD::BITCAST)
10230 V = V.getOperand(0);
10231
10232 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010233 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000010234 // Handle only simple case where vector being inserted and vector
10235 // being extracted are of same type, and are half size of larger vectors.
10236 EVT BigVT = V->getOperand(0).getValueType();
10237 EVT SmallVT = V->getOperand(1).getValueType();
10238 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10239 return SDValue();
10240
10241 // Only handle cases where both indexes are constants with the same type.
10242 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10243 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10244
10245 if (InsIdx && ExtIdx &&
10246 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10247 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10248 // Combine:
10249 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10250 // Into:
10251 // indices are equal or bit offsets are equal => V1
10252 // otherwise => (extract_subvec V1, ExtIdx)
10253 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10254 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10255 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10256 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10257 DAG.getNode(ISD::BITCAST, dl,
10258 N->getOperand(0).getValueType(),
10259 V->getOperand(0)), N->getOperand(1));
10260 }
10261 }
10262
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010263 return SDValue();
10264}
10265
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010266// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10267static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10268 EVT VT = N->getValueType(0);
10269 unsigned NumElts = VT.getVectorNumElements();
10270
10271 SDValue N0 = N->getOperand(0);
10272 SDValue N1 = N->getOperand(1);
10273 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10274
10275 SmallVector<SDValue, 4> Ops;
10276 EVT ConcatVT = N0.getOperand(0).getValueType();
10277 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10278 unsigned NumConcats = NumElts / NumElemsPerConcat;
10279
10280 // Look at every vector that's inserted. We're looking for exact
10281 // subvector-sized copies from a concatenated vector
10282 for (unsigned I = 0; I != NumConcats; ++I) {
10283 // Make sure we're dealing with a copy.
10284 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000010285 bool AllUndef = true, NoUndef = true;
10286 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10287 if (SVN->getMaskElt(J) >= 0)
10288 AllUndef = false;
10289 else
10290 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010291 }
10292
Hao Liubc601962013-05-13 02:07:05 +000010293 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000010294 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10295 return SDValue();
10296
10297 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10298 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10299 return SDValue();
10300
10301 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10302 if (FirstElt < N0.getNumOperands())
10303 Ops.push_back(N0.getOperand(FirstElt));
10304 else
10305 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10306
10307 } else if (AllUndef) {
10308 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10309 } else { // Mixed with general masks and undefs, can't do optimization.
10310 return SDValue();
10311 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010312 }
10313
Andrew Trickef9de2a2013-05-25 02:42:55 +000010314 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010315 Ops.size());
10316}
10317
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010318SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010319 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010320 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010321
Mon P Wang25f01062008-11-10 04:46:22 +000010322 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000010323 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000010324
Craig Topper5894fe42012-04-09 05:16:56 +000010325 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000010326
Craig Topper279c77b2012-01-04 08:07:43 +000010327 // Canonicalize shuffle undef, undef -> undef
10328 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10329 return DAG.getUNDEF(VT);
10330
10331 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10332
10333 // Canonicalize shuffle v, v -> v, undef
10334 if (N0 == N1) {
10335 SmallVector<int, 8> NewMask;
10336 for (unsigned i = 0; i != NumElts; ++i) {
10337 int Idx = SVN->getMaskElt(i);
10338 if (Idx >= (int)NumElts) Idx -= NumElts;
10339 NewMask.push_back(Idx);
10340 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010341 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010342 &NewMask[0]);
10343 }
10344
10345 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10346 if (N0.getOpcode() == ISD::UNDEF) {
10347 SmallVector<int, 8> NewMask;
10348 for (unsigned i = 0; i != NumElts; ++i) {
10349 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000010350 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000010351 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000010352 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000010353 else
10354 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000010355 }
10356 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000010357 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010358 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010359 &NewMask[0]);
10360 }
10361
10362 // Remove references to rhs if it is undef
10363 if (N1.getOpcode() == ISD::UNDEF) {
10364 bool Changed = false;
10365 SmallVector<int, 8> NewMask;
10366 for (unsigned i = 0; i != NumElts; ++i) {
10367 int Idx = SVN->getMaskElt(i);
10368 if (Idx >= (int)NumElts) {
10369 Idx = -1;
10370 Changed = true;
10371 }
10372 NewMask.push_back(Idx);
10373 }
10374 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000010375 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000010376 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000010377
Bob Wilsonf63da122010-10-28 17:06:14 +000010378 // If it is a splat, check if the argument vector is another splat or a
10379 // build_vector with all scalar elements the same.
Bob Wilsonf63da122010-10-28 17:06:14 +000010380 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000010381 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000010382
Dan Gohmana8665142007-06-25 16:23:39 +000010383 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000010384 // not the number of vector elements, look through it. Be careful not to
10385 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000010386 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010387 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000010388 if (ConvInput.getValueType().isVector() &&
10389 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000010390 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000010391 }
10392
Dan Gohmana8665142007-06-25 16:23:39 +000010393 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000010394 assert(V->getNumOperands() == NumElts &&
10395 "BUILD_VECTOR has wrong number of operands");
10396 SDValue Base;
10397 bool AllSame = true;
10398 for (unsigned i = 0; i != NumElts; ++i) {
10399 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10400 Base = V->getOperand(i);
10401 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000010402 }
Evan Cheng7c970b92006-07-21 08:25:53 +000010403 }
Bob Wilsonf63da122010-10-28 17:06:14 +000010404 // Splat of <u, u, u, u>, return <u, u, u, u>
10405 if (!Base.getNode())
10406 return N0;
10407 for (unsigned i = 0; i != NumElts; ++i) {
10408 if (V->getOperand(i) != Base) {
10409 AllSame = false;
10410 break;
10411 }
10412 }
10413 // Splat of <x, x, x, x>, return <x, x, x, x>
10414 if (AllSame)
10415 return N0;
Evan Cheng7c970b92006-07-21 08:25:53 +000010416 }
10417 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010418
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010419 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10420 Level < AfterLegalizeVectorOps &&
10421 (N1.getOpcode() == ISD::UNDEF ||
10422 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10423 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10424 SDValue V = partitionShuffleOfConcats(N, DAG);
10425
10426 if (V.getNode())
10427 return V;
10428 }
10429
Nadav Rotemb0783502012-04-01 19:31:22 +000010430 // If this shuffle node is simply a swizzle of another shuffle node,
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010431 // and it reverses the swizzle of the previous shuffle then we can
10432 // optimize shuffle(shuffle(x, undef), undef) -> x.
Nadav Rotemb0783502012-04-01 19:31:22 +000010433 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10434 N1.getOpcode() == ISD::UNDEF) {
10435
Nadav Rotemb0783502012-04-01 19:31:22 +000010436 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10437
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010438 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10439 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10440 return SDValue();
10441
Craig Topper5894fe42012-04-09 05:16:56 +000010442 // The incoming shuffle must be of the same type as the result of the
10443 // current shuffle.
10444 assert(OtherSV->getOperand(0).getValueType() == VT &&
10445 "Shuffle types don't match");
Nadav Rotemb0783502012-04-01 19:31:22 +000010446
10447 for (unsigned i = 0; i != NumElts; ++i) {
10448 int Idx = SVN->getMaskElt(i);
Craig Topper5894fe42012-04-09 05:16:56 +000010449 assert(Idx < (int)NumElts && "Index references undef operand");
Nadav Rotemb0783502012-04-01 19:31:22 +000010450 // Next, this index comes from the first value, which is the incoming
10451 // shuffle. Adopt the incoming index.
10452 if (Idx >= 0)
10453 Idx = OtherSV->getMaskElt(Idx);
10454
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010455 // The combined shuffle must map each index to itself.
Craig Topper5894fe42012-04-09 05:16:56 +000010456 if (Idx >= 0 && (unsigned)Idx != i)
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010457 return SDValue();
Nadav Rotemb0783502012-04-01 19:31:22 +000010458 }
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010459
10460 return OtherSV->getOperand(0);
Nadav Rotemb0783502012-04-01 19:31:22 +000010461 }
10462
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010463 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010464}
10465
Manman Ren413a6cb2014-01-31 01:10:35 +000010466SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10467 SDValue N0 = N->getOperand(0);
10468 SDValue N2 = N->getOperand(2);
10469
10470 // If the input vector is a concatenation, and the insert replaces
10471 // one of the halves, we can optimize into a single concat_vectors.
10472 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10473 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10474 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10475 EVT VT = N->getValueType(0);
10476
10477 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10478 // (concat_vectors Z, Y)
10479 if (InsIdx == 0)
10480 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10481 N->getOperand(1), N0.getOperand(1));
10482
10483 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10484 // (concat_vectors X, Z)
10485 if (InsIdx == VT.getVectorNumElements()/2)
10486 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10487 N0.getOperand(0), N->getOperand(1));
10488 }
10489
10490 return SDValue();
10491}
10492
Evan Chenga320abc2006-04-20 08:56:16 +000010493/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
Dan Gohmana8665142007-06-25 16:23:39 +000010494/// an AND to a vector_shuffle with the destination vector and a zero vector.
10495/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000010496/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010497SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010498 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010499 SDLoc dl(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010500 SDValue LHS = N->getOperand(0);
10501 SDValue RHS = N->getOperand(1);
Dan Gohmana8665142007-06-25 16:23:39 +000010502 if (N->getOpcode() == ISD::AND) {
Wesley Peck527da1b2010-11-23 03:31:01 +000010503 if (RHS.getOpcode() == ISD::BITCAST)
Evan Chenga320abc2006-04-20 08:56:16 +000010504 RHS = RHS.getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010505 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010506 SmallVector<int, 8> Indices;
10507 unsigned NumElts = RHS.getNumOperands();
Evan Chenga320abc2006-04-20 08:56:16 +000010508 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010509 SDValue Elt = RHS.getOperand(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010510 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010511 return SDValue();
Craig Toppere5893f62012-04-09 05:59:53 +000010512
10513 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010514 Indices.push_back(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010515 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010516 Indices.push_back(NumElts);
Evan Chenga320abc2006-04-20 08:56:16 +000010517 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010518 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010519 }
10520
10521 // Let's see if the target supports this vector_shuffle.
Owen Anderson53aa7a92009-08-10 22:56:29 +000010522 EVT RVT = RHS.getValueType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010523 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010524 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010525
Dan Gohmana8665142007-06-25 16:23:39 +000010526 // Return the new VECTOR_SHUFFLE node.
Dan Gohman08c0a952009-09-23 21:02:20 +000010527 EVT EltVT = RVT.getVectorElementType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010528 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman08c0a952009-09-23 21:02:20 +000010529 DAG.getConstant(0, EltVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010530 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010531 RVT, &ZeroOps[0], ZeroOps.size());
Wesley Peck527da1b2010-11-23 03:31:01 +000010532 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010533 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peck527da1b2010-11-23 03:31:01 +000010534 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000010535 }
10536 }
Bill Wendling31b50992009-01-30 23:59:18 +000010537
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010538 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010539}
10540
Dan Gohmana8665142007-06-25 16:23:39 +000010541/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010542SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000010543 assert(N->getValueType(0).isVector() &&
10544 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000010545
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010546 SDValue LHS = N->getOperand(0);
10547 SDValue RHS = N->getOperand(1);
10548 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010549 if (Shuffle.getNode()) return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000010550
Dan Gohmana8665142007-06-25 16:23:39 +000010551 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000010552 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010553 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000010554 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000010555 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000010556 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10557 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000010558 return SDValue();
10559
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010560 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000010561 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010562 SDValue LHSOp = LHS.getOperand(i);
10563 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000010564
Evan Cheng64d28462006-05-31 06:08:35 +000010565 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000010566 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10567 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000010568 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010569 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000010570 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010571 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000010572 break;
10573 }
Bill Wendling31b50992009-01-30 23:59:18 +000010574
Bob Wilson54081442010-12-17 23:06:49 +000010575 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000010576 EVT RVT = RHSOp.getValueType();
10577 if (RVT != VT) {
10578 // Integer BUILD_VECTOR operands may have types larger than the element
10579 // size (e.g., when the element type is not legal). Prior to type
10580 // legalization, the types may not match between the two BUILD_VECTORS.
10581 // Truncate one of the operands to make them match.
10582 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010583 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010584 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010585 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010586 VT = RVT;
10587 }
10588 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010589 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000010590 LHSOp, RHSOp);
10591 if (FoldOp.getOpcode() != ISD::UNDEF &&
10592 FoldOp.getOpcode() != ISD::Constant &&
10593 FoldOp.getOpcode() != ISD::ConstantFP)
10594 break;
10595 Ops.push_back(FoldOp);
10596 AddToWorkList(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000010597 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010598
Bob Wilson54081442010-12-17 23:06:49 +000010599 if (Ops.size() == LHS.getNumOperands())
Andrew Trickef9de2a2013-05-25 02:42:55 +000010600 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Bob Wilson54081442010-12-17 23:06:49 +000010601 LHS.getValueType(), &Ops[0], Ops.size());
Chris Lattner0442a182006-04-02 03:25:57 +000010602 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010603
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010604 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000010605}
10606
Craig Topper82384612012-09-11 01:45:21 +000010607/// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10608SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topper82384612012-09-11 01:45:21 +000010609 assert(N->getValueType(0).isVector() &&
10610 "SimplifyVUnaryOp only works on vectors!");
10611
10612 SDValue N0 = N->getOperand(0);
10613
10614 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10615 return SDValue();
10616
10617 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10618 SmallVector<SDValue, 8> Ops;
10619 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10620 SDValue Op = N0.getOperand(i);
10621 if (Op.getOpcode() != ISD::UNDEF &&
10622 Op.getOpcode() != ISD::ConstantFP)
10623 break;
10624 EVT EltVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010625 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topper82384612012-09-11 01:45:21 +000010626 if (FoldOp.getOpcode() != ISD::UNDEF &&
10627 FoldOp.getOpcode() != ISD::ConstantFP)
10628 break;
10629 Ops.push_back(FoldOp);
10630 AddToWorkList(FoldOp.getNode());
10631 }
10632
10633 if (Ops.size() != N0.getNumOperands())
10634 return SDValue();
10635
Andrew Trickef9de2a2013-05-25 02:42:55 +000010636 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Craig Topper82384612012-09-11 01:45:21 +000010637 N0.getValueType(), &Ops[0], Ops.size());
10638}
10639
Andrew Trickef9de2a2013-05-25 02:42:55 +000010640SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000010641 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000010642 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000010643
Bill Wendling31b50992009-01-30 23:59:18 +000010644 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000010645 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000010646
Nate Begeman2042aa52005-10-08 00:29:44 +000010647 // If we got a simplified select_cc node back from SimplifySelectCC, then
10648 // break it down into a new SETCC node, and a new SELECT node, and then return
10649 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010650 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000010651 // Check to see if we got a select_cc back (to turn into setcc/select).
10652 // Otherwise, just return whatever node we got back, like fabs.
10653 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010654 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000010655 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000010656 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000010657 SCC.getOperand(4));
Gabor Greiff304a7a2008-08-28 21:40:38 +000010658 AddToWorkList(SETCC.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010659 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10660 SCC.getOperand(2), SCC.getOperand(3), SETCC);
Nate Begeman2042aa52005-10-08 00:29:44 +000010661 }
Bill Wendling31b50992009-01-30 23:59:18 +000010662
Nate Begeman2042aa52005-10-08 00:29:44 +000010663 return SCC;
10664 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010665 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000010666}
10667
Chris Lattner6c14c352005-10-18 06:04:22 +000010668/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10669/// are the two values being selected between, see if we can simplify the
Chris Lattner8f872d22006-05-27 00:43:02 +000010670/// select. Callers of this should assume that TheSelect is deleted if this
10671/// returns true. As such, they should return the appropriate thing (e.g. the
10672/// node) back to the top-level of the DAG combiner loop to avoid it being
10673/// looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010674bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010675 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000010676
Nadav Rotema49a02a2011-02-11 19:57:47 +000010677 // Cannot simplify select with vector condition
10678 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10679
Chris Lattner6c14c352005-10-18 06:04:22 +000010680 // If this is a select from two identical things, try to pull the operation
10681 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000010682 if (LHS.getOpcode() != RHS.getOpcode() ||
10683 !LHS.hasOneUse() || !RHS.hasOneUse())
10684 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010685
Chris Lattner254c4452010-09-21 15:46:59 +000010686 // If this is a load and the token chain is identical, replace the select
10687 // of two loads with a load through a select of the address to load from.
10688 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10689 // constants have been dropped into the constant pool.
10690 if (LHS.getOpcode() == ISD::LOAD) {
10691 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10692 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000010693
Chris Lattner254c4452010-09-21 15:46:59 +000010694 // Token chains must be identical.
10695 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000010696 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000010697 LLD->isVolatile() || RLD->isVolatile() ||
10698 // If this is an EXTLOAD, the VT's must match.
10699 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000010700 // If this is an EXTLOAD, the kind of extension must match.
10701 (LLD->getExtensionType() != RLD->getExtensionType() &&
10702 // The only exception is if one of the extensions is anyext.
10703 LLD->getExtensionType() != ISD::EXTLOAD &&
10704 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000010705 // FIXME: this discards src value information. This is
10706 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000010707 // both potential memory locations. Since we are discarding
10708 // src value info, don't do the transformation if the memory
10709 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000010710 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000010711 RLD->getPointerInfo().getAddrSpace() != 0 ||
10712 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10713 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000010714 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010715
Chris Lattnere3267522010-09-21 15:58:55 +000010716 // Check that the select condition doesn't reach either load. If so,
10717 // folding this will induce a cycle into the DAG. If not, this is safe to
10718 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000010719 SDValue Addr;
10720 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000010721 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10722 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10723 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10724 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000010725 // The loads must not depend on one another.
10726 if (LLD->isPredecessorOf(RLD) ||
10727 RLD->isPredecessorOf(LLD))
10728 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010729 Addr = DAG.getSelect(SDLoc(TheSelect),
10730 LLD->getBasePtr().getValueType(),
10731 TheSelect->getOperand(0), LLD->getBasePtr(),
10732 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000010733 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000010734 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10735 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10736
10737 if ((LLD->hasAnyUseOfValue(1) &&
10738 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000010739 (RLD->hasAnyUseOfValue(1) &&
10740 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000010741 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010742
Andrew Trickef9de2a2013-05-25 02:42:55 +000010743 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000010744 LLD->getBasePtr().getValueType(),
10745 TheSelect->getOperand(0),
10746 TheSelect->getOperand(1),
10747 LLD->getBasePtr(), RLD->getBasePtr(),
10748 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000010749 }
10750
Chris Lattnere3267522010-09-21 15:58:55 +000010751 SDValue Load;
10752 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10753 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000010754 SDLoc(TheSelect),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010755 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000010756 LLD->getChain(), Addr, MachinePointerInfo(),
10757 LLD->isVolatile(), LLD->isNonTemporal(),
Pete Cooper82cd9e82011-11-08 18:42:53 +000010758 LLD->isInvariant(), LLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000010759 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000010760 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10761 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000010762 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000010763 TheSelect->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010764 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000010765 LLD->getChain(), Addr, MachinePointerInfo(),
10766 LLD->getMemoryVT(), LLD->isVolatile(),
10767 LLD->isNonTemporal(), LLD->getAlignment());
Chris Lattner6c14c352005-10-18 06:04:22 +000010768 }
Chris Lattnere3267522010-09-21 15:58:55 +000010769
10770 // Users of the select now use the result of the load.
10771 CombineTo(TheSelect, Load);
10772
10773 // Users of the old loads now use the new load's chain. We know the
10774 // old-load value is dead now.
10775 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10776 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10777 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000010778 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010779
Chris Lattner6c14c352005-10-18 06:04:22 +000010780 return false;
10781}
10782
Chris Lattner43d63772009-03-11 05:08:08 +000010783/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10784/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000010785SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010786 SDValue N2, SDValue N3,
10787 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000010788 // (x ? y : y) -> y.
10789 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000010790
Owen Anderson53aa7a92009-08-10 22:56:29 +000010791 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000010792 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10793 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10794 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010795
10796 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000010797 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000010798 N0, N1, CC, DL, false);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010799 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10800 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010801
10802 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000010803 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000010804 return N2;
10805 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000010806 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000010807 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010808
Nate Begeman2042aa52005-10-08 00:29:44 +000010809 // Check to see if we can simplify the select into an fabs node
10810 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10811 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000010812 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000010813 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10814 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10815 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10816 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000010817 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000010818
Nate Begeman2042aa52005-10-08 00:29:44 +000010819 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10820 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10821 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10822 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000010823 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000010824 }
10825 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010826
Chris Lattner43d63772009-03-11 05:08:08 +000010827 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10828 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10829 // in it. This is a win when the constant is not otherwise available because
10830 // it replaces two constant pool loads with one. We only do this if the FP
10831 // type is known to be legal, because if it isn't, then we are before legalize
10832 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000010833 // messing with soft float) and if the ConstantFP is not legal, because if
10834 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000010835 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10836 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10837 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000010838 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10839 TargetLowering::Legal) &&
Chris Lattner43d63772009-03-11 05:08:08 +000010840 // If both constants have multiple uses, then we won't need to do an
10841 // extra load, they are likely around in registers for other users.
10842 (TV->hasOneUse() || FV->hasOneUse())) {
10843 Constant *Elts[] = {
10844 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10845 const_cast<ConstantFP*>(TV->getConstantFPValue())
10846 };
Chris Lattner229907c2011-07-18 04:54:35 +000010847 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000010848 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000010849
Chris Lattner43d63772009-03-11 05:08:08 +000010850 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000010851 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000010852 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10853 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000010854 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000010855
10856 // Get the offsets to the 0 and 1 element of the array so that we can
10857 // select between them.
10858 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000010859 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000010860 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000010861
Chris Lattner43d63772009-03-11 05:08:08 +000010862 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000010863 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000010864 N0, N1, CC);
Dan Gohmane83e1b22011-09-22 23:01:29 +000010865 AddToWorkList(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010866 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10867 Cond, One, Zero);
Dan Gohmane83e1b22011-09-22 23:01:29 +000010868 AddToWorkList(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000010869 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000010870 CstOffset);
Dan Gohmane83e1b22011-09-22 23:01:29 +000010871 AddToWorkList(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000010872 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000010873 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000010874 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000010875
10876 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010877 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010878
Nate Begeman2042aa52005-10-08 00:29:44 +000010879 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000010880 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000010881 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000010882 (N1C->isNullValue() || // (a < 0) ? b : 0
10883 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000010884 EVT XType = N0.getValueType();
10885 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000010886 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000010887 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000010888 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000010889 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10890 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000010891 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000010892 SDValue ShCt = DAG.getConstant(ShCtV,
10893 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010894 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000010895 XType, N0, ShCt);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010896 AddToWorkList(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000010897
Duncan Sands11dd4242008-06-08 20:54:56 +000010898 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000010899 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010900 AddToWorkList(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010901 }
Bill Wendling31b50992009-01-30 23:59:18 +000010902
10903 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000010904 }
Bill Wendling31b50992009-01-30 23:59:18 +000010905
Andrew Trickef9de2a2013-05-25 02:42:55 +000010906 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000010907 XType, N0,
10908 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000010909 getShiftAmountTy(N0.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +000010910 AddToWorkList(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000010911
Duncan Sands11dd4242008-06-08 20:54:56 +000010912 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000010913 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010914 AddToWorkList(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010915 }
Bill Wendling31b50992009-01-30 23:59:18 +000010916
10917 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000010918 }
10919 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010920
Owen Anderson3231d132010-09-22 22:58:22 +000010921 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10922 // where y is has a single bit set.
10923 // A plaintext description would be, we can turn the SELECT_CC into an AND
10924 // when the condition can be materialized as an all-ones register. Any
10925 // single bit-test can be materialized as an all-ones register with
10926 // shift-left and shift-right-arith.
10927 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10928 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000010929 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000010930 N2C && N2C->isNullValue()) {
10931 SDValue AndLHS = N0->getOperand(0);
10932 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10933 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10934 // Shift the tested bit over the sign bit.
10935 APInt AndMask = ConstAndRHS->getAPIntValue();
10936 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000010937 DAG.getConstant(AndMask.countLeadingZeros(),
10938 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010939 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000010940
Owen Anderson3231d132010-09-22 22:58:22 +000010941 // Now arithmetic right shift it all the way over, so the result is either
10942 // all-ones, or zero.
10943 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000010944 DAG.getConstant(AndMask.getBitWidth()-1,
10945 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010946 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000010947
Owen Anderson3231d132010-09-22 22:58:22 +000010948 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10949 }
10950 }
10951
Nate Begeman6828ed92005-10-10 21:26:48 +000010952 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000010953 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Duncan Sandsf2641e12011-09-06 19:07:46 +000010954 TLI.getBooleanContents(N0.getValueType().isVector()) ==
10955 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000010956
Chris Lattnera083ffc2007-04-11 06:50:51 +000010957 // If the caller doesn't want us to simplify this into a zext of a compare,
10958 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000010959 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010960 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000010961
Nate Begeman6828ed92005-10-10 21:26:48 +000010962 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000010963 // NOTE: Don't create a SETCC if it's not legal on this target.
10964 if (!LegalOperations ||
10965 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000010966 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000010967 SDValue Temp, SCC;
10968 // cast from setcc result type to select result type
10969 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000010970 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000010971 N0, N1, CC);
10972 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000010973 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000010974 N2.getValueType());
10975 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000010976 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000010977 N2.getValueType(), SCC);
10978 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010979 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10980 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000010981 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000010982 }
10983
10984 AddToWorkList(SCC.getNode());
10985 AddToWorkList(Temp.getNode());
10986
10987 if (N2C->getAPIntValue() == 1)
10988 return Temp;
10989
10990 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000010991 return DAG.getNode(
10992 ISD::SHL, DL, N2.getValueType(), Temp,
10993 DAG.getConstant(N2C->getAPIntValue().logBase2(),
10994 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000010995 }
Nate Begeman6828ed92005-10-10 21:26:48 +000010996 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010997
Nate Begeman2042aa52005-10-08 00:29:44 +000010998 // Check to see if this is the equivalent of setcc
10999 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11000 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011001 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011002 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011003 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000011004 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11005 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000011006 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000011007 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000011008 return Res;
11009 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011010
Bill Wendling31b50992009-01-30 23:59:18 +000011011 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011012 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011013 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000011014 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011015 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011016 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000011017 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000011018 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000011019 }
Bill Wendling31b50992009-01-30 23:59:18 +000011020 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011021 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011022 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011023 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011024 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000011025 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000011026 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000011027 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011028 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000011029 }
Bill Wendling31b50992009-01-30 23:59:18 +000011030 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000011031 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011032 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011033 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011034 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000011035 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000011036 }
11037 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011038
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011039 // Check to see if this is an integer abs.
11040 // select_cc setg[te] X, 0, X, -X ->
11041 // select_cc setgt X, -1, X, -X ->
11042 // select_cc setl[te] X, 0, -X, X ->
11043 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000011044 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011045 if (N1C) {
11046 ConstantSDNode *SubC = NULL;
11047 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11048 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11049 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11050 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11051 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11052 (N1C->isOne() && CC == ISD::SETLT)) &&
11053 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11054 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11055
Owen Anderson53aa7a92009-08-10 22:56:29 +000011056 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011057 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011058 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011059 N0,
11060 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011061 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011062 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011063 XType, N0, Shift);
11064 AddToWorkList(Shift.getNode());
11065 AddToWorkList(Add.getNode());
11066 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000011067 }
11068 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011069
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011070 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011071}
11072
Evan Cheng92658d52007-02-08 22:13:59 +000011073/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011074SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011075 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000011076 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011077 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000011078 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000011079 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000011080}
11081
Nate Begemanc6f067a2005-10-20 02:15:44 +000011082/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11083/// return a DAG expression to select that will generate the same value by
11084/// multiplying by a magic number. See:
11085/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011086SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011087 std::vector<SDNode*> Built;
Richard Osborne561fac42011-11-07 17:09:05 +000011088 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011089
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011090 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011091 ii != ee; ++ii)
11092 AddToWorkList(*ii);
11093 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011094}
11095
11096/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
11097/// return a DAG expression to select that will generate the same value by
11098/// multiplying by a magic number. See:
11099/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011100SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011101 std::vector<SDNode*> Built;
Richard Osborne561fac42011-11-07 17:09:05 +000011102 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000011103
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011104 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011105 ii != ee; ++ii)
11106 AddToWorkList(*ii);
11107 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011108}
11109
Nate Begeman18150d52009-09-25 06:05:26 +000011110/// FindBaseOffset - Return true if base is a frame index, which is known not
Eric Christopherd9e8eac2010-12-09 04:48:06 +000011111// to alias with anything but itself. Provides base object and offset as
11112// results.
Nate Begeman18150d52009-09-25 06:05:26 +000011113static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000011114 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000011115 // Assume it is a primitive operation.
Nate Begeman18150d52009-09-25 06:05:26 +000011116 Base = Ptr; Offset = 0; GV = 0; CV = 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011117
Jim Laskey0463e082006-10-07 23:37:56 +000011118 // If it's an adding a simple constant then integrate the offset.
11119 if (Base.getOpcode() == ISD::ADD) {
11120 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11121 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000011122 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000011123 }
11124 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011125
Nate Begeman18150d52009-09-25 06:05:26 +000011126 // Return the underlying GlobalValue, and update the Offset. Return false
11127 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11128 // by multiple nodes with different offsets.
11129 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11130 GV = G->getGlobal();
11131 Offset += G->getOffset();
11132 return false;
11133 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011134
Nate Begeman18150d52009-09-25 06:05:26 +000011135 // Return the underlying Constant value, and update the Offset. Return false
11136 // for ConstantSDNodes since the same constant pool entry may be represented
11137 // by multiple nodes with different offsets.
11138 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000011139 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11140 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000011141 Offset += C->getOffset();
11142 return false;
11143 }
Jim Laskey0463e082006-10-07 23:37:56 +000011144 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000011145 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000011146}
11147
11148/// isAlias - Return true if there is any possibility that the two addresses
11149/// overlap.
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011150bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011151 const Value *SrcValue1, int SrcValueOffset1,
Nate Begeman879d8f12009-09-15 00:18:30 +000011152 unsigned SrcValueAlign1,
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011153 const MDNode *TBAAInfo1,
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011154 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
Nate Begeman879d8f12009-09-15 00:18:30 +000011155 const Value *SrcValue2, int SrcValueOffset2,
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011156 unsigned SrcValueAlign2,
11157 const MDNode *TBAAInfo2) const {
Jim Laskey0463e082006-10-07 23:37:56 +000011158 // If they are the same then they must be aliases.
11159 if (Ptr1 == Ptr2) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011160
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011161 // If they are both volatile then they cannot be reordered.
11162 if (IsVolatile1 && IsVolatile2) return true;
11163
Jim Laskey0463e082006-10-07 23:37:56 +000011164 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011165 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000011166 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000011167 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000011168 const void *CV1, *CV2;
Nate Begeman18150d52009-09-25 06:05:26 +000011169 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11170 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011171
Nate Begeman18150d52009-09-25 06:05:26 +000011172 // If they have a same base address then check to see if they overlap.
11173 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Bill Wendling31b50992009-01-30 23:59:18 +000011174 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011175
Owen Anderson272ff942010-09-20 20:39:59 +000011176 // It is possible for different frame indices to alias each other, mostly
11177 // when tail call optimization reuses return address slots for arguments.
11178 // To catch this case, look up the actual index of frame indices to compute
11179 // the real alias relationship.
11180 if (isFrameIndex1 && isFrameIndex2) {
11181 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11182 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11183 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11184 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11185 }
11186
Wesley Peck527da1b2010-11-23 03:31:01 +000011187 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000011188 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000011189 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11190 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011191
Nate Begeman879d8f12009-09-15 00:18:30 +000011192 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11193 // compared to the size and offset of the access, we may be able to prove they
11194 // do not alias. This check is conservative for now to catch cases created by
11195 // splitting vector types.
11196 if ((SrcValueAlign1 == SrcValueAlign2) &&
11197 (SrcValueOffset1 != SrcValueOffset2) &&
11198 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11199 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11200 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
Wesley Peck527da1b2010-11-23 03:31:01 +000011201
Nate Begeman879d8f12009-09-15 00:18:30 +000011202 // There is no overlap between these relatively aligned accesses of similar
11203 // size, return no alias.
11204 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11205 return false;
11206 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011207
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000011208 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11209 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000011210#ifndef NDEBUG
11211 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11212 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11213 UseAA = false;
11214#endif
Hal Finkel31658832013-09-15 02:19:49 +000011215 if (UseAA && SrcValue1 && SrcValue2) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000011216 // Use alias analysis information.
Dan Gohman9625d812007-08-27 16:32:11 +000011217 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11218 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11219 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011220 AliasAnalysis::AliasResult AAResult =
Hal Finkeldbebb522014-01-25 19:24:54 +000011221 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1,
11222 UseTBAA ? TBAAInfo1 : 0),
11223 AliasAnalysis::Location(SrcValue2, Overlap2,
11224 UseTBAA ? TBAAInfo2 : 0));
Jim Laskey55e4dca2006-10-18 19:08:31 +000011225 if (AAResult == AliasAnalysis::NoAlias)
11226 return false;
11227 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011228
11229 // Otherwise we have to assume they alias.
11230 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000011231}
11232
Nadav Rotem307d7672012-11-29 00:00:08 +000011233bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11234 SDValue Ptr0, Ptr1;
11235 int64_t Size0, Size1;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011236 bool IsVolatile0, IsVolatile1;
Nadav Rotem307d7672012-11-29 00:00:08 +000011237 const Value *SrcValue0, *SrcValue1;
11238 int SrcValueOffset0, SrcValueOffset1;
11239 unsigned SrcValueAlign0, SrcValueAlign1;
11240 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011241 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
Nadav Rotem307d7672012-11-29 00:00:08 +000011242 SrcValueAlign0, SrcTBAAInfo0);
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011243 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
Nadav Rotem307d7672012-11-29 00:00:08 +000011244 SrcValueAlign1, SrcTBAAInfo1);
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011245 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
Nadav Rotemac450eb2012-12-06 17:34:13 +000011246 SrcValueAlign0, SrcTBAAInfo0,
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011247 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
Nadav Rotemac450eb2012-12-06 17:34:13 +000011248 SrcValueAlign1, SrcTBAAInfo1);
Nadav Rotem307d7672012-11-29 00:00:08 +000011249}
11250
Jim Laskey0463e082006-10-07 23:37:56 +000011251/// FindAliasInfo - Extracts the relevant alias information from the memory
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011252/// node. Returns true if the operand was a nonvolatile load.
Jim Laskey08edf332006-10-11 13:47:09 +000011253bool DAGCombiner::FindAliasInfo(SDNode *N,
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011254 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
Benjamin Kramer5a377e22012-01-15 11:50:43 +000011255 const Value *&SrcValue,
11256 int &SrcValueOffset,
11257 unsigned &SrcValueAlign,
11258 const MDNode *&TBAAInfo) const {
11259 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11260
11261 Ptr = LS->getBasePtr();
11262 Size = LS->getMemoryVT().getSizeInBits() >> 3;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011263 IsVolatile = LS->isVolatile();
Benjamin Kramer5a377e22012-01-15 11:50:43 +000011264 SrcValue = LS->getSrcValue();
11265 SrcValueOffset = LS->getSrcValueOffset();
11266 SrcValueAlign = LS->getOriginalAlignment();
11267 TBAAInfo = LS->getTBAAInfo();
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011268 return isa<LoadSDNode>(LS) && !IsVolatile;
Jim Laskey0463e082006-10-07 23:37:56 +000011269}
11270
Jim Laskey708d0db2006-10-04 16:53:27 +000011271/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11272/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011273void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000011274 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011275 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000011276 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011277
Jim Laskeyd07be232006-09-25 16:29:54 +000011278 // Get alias information for node.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011279 SDValue Ptr;
Nate Begeman879d8f12009-09-15 00:18:30 +000011280 int64_t Size;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011281 bool IsVolatile;
Nate Begeman879d8f12009-09-15 00:18:30 +000011282 const Value *SrcValue;
11283 int SrcValueOffset;
11284 unsigned SrcValueAlign;
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011285 const MDNode *SrcTBAAInfo;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011286 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11287 SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
Jim Laskeyd07be232006-09-25 16:29:54 +000011288
Jim Laskey708d0db2006-10-04 16:53:27 +000011289 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000011290 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011291 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000011292
Jim Laskey6549d222006-10-05 15:07:25 +000011293 // Look at each chain and determine if it is an alias. If so, add it to the
11294 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000011295 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000011296 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011297 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000011298 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000011299
11300 // For TokenFactor nodes, look at each operand and only continue up the
11301 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011302 // find more and revert to original chain since the xform is unlikely to be
11303 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000011304 //
11305 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011306 // chain we found before we hit a tokenfactor rather than the original
11307 // chain.
11308 if (Depth > 6 || Aliases.size() == 2) {
11309 Aliases.clear();
11310 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000011311 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011312 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011313
Nate Begeman879d8f12009-09-15 00:18:30 +000011314 // Don't bother if we've been before.
11315 if (!Visited.insert(Chain.getNode()))
11316 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011317
Jim Laskey6549d222006-10-05 15:07:25 +000011318 switch (Chain.getOpcode()) {
11319 case ISD::EntryToken:
11320 // Entry token is ideal chain operand, but handled in FindBetterChain.
11321 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011322
Jim Laskey6549d222006-10-05 15:07:25 +000011323 case ISD::LOAD:
11324 case ISD::STORE: {
11325 // Get alias information for Chain.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011326 SDValue OpPtr;
Nate Begeman879d8f12009-09-15 00:18:30 +000011327 int64_t OpSize;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011328 bool OpIsVolatile;
Nate Begeman879d8f12009-09-15 00:18:30 +000011329 const Value *OpSrcValue;
11330 int OpSrcValueOffset;
11331 unsigned OpSrcValueAlign;
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011332 const MDNode *OpSrcTBAAInfo;
Gabor Greiff304a7a2008-08-28 21:40:38 +000011333 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011334 OpIsVolatile, OpSrcValue, OpSrcValueOffset,
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011335 OpSrcValueAlign,
11336 OpSrcTBAAInfo);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011337
Jim Laskey6549d222006-10-05 15:07:25 +000011338 // If chain is alias then stop here.
11339 if (!(IsLoad && IsOpLoad) &&
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011340 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11341 SrcValueAlign, SrcTBAAInfo,
11342 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011343 OpSrcValueAlign, OpSrcTBAAInfo)) {
Jim Laskey6549d222006-10-05 15:07:25 +000011344 Aliases.push_back(Chain);
11345 } else {
11346 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011347 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011348 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000011349 }
Jim Laskey6549d222006-10-05 15:07:25 +000011350 break;
11351 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011352
Jim Laskey6549d222006-10-05 15:07:25 +000011353 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000011354 // We have to check each of the operands of the token factor for "small"
11355 // token factors, so we queue them up. Adding the operands to the queue
11356 // (stack) in reverse order maintains the original order and increases the
11357 // likelihood that getNode will find a matching token factor (CSE.)
11358 if (Chain.getNumOperands() > 16) {
11359 Aliases.push_back(Chain);
11360 break;
11361 }
Jim Laskey6549d222006-10-05 15:07:25 +000011362 for (unsigned n = Chain.getNumOperands(); n;)
11363 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011364 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000011365 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011366
Jim Laskey6549d222006-10-05 15:07:25 +000011367 default:
11368 // For all other instructions we will just have to take what we can get.
11369 Aliases.push_back(Chain);
11370 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000011371 }
11372 }
Hal Finkel51a98382014-01-24 20:12:02 +000011373
11374 // We need to be careful here to also search for aliases through the
11375 // value operand of a store, etc. Consider the following situation:
11376 // Token1 = ...
11377 // L1 = load Token1, %52
11378 // S1 = store Token1, L1, %51
11379 // L2 = load Token1, %52+8
11380 // S2 = store Token1, L2, %51+8
11381 // Token2 = Token(S1, S2)
11382 // L3 = load Token2, %53
11383 // S3 = store Token2, L3, %52
11384 // L4 = load Token2, %53+8
11385 // S4 = store Token2, L4, %52+8
11386 // If we search for aliases of S3 (which loads address %52), and we look
11387 // only through the chain, then we'll miss the trivial dependence on L1
11388 // (which also loads from %52). We then might change all loads and
11389 // stores to use Token1 as their chain operand, which could result in
11390 // copying %53 into %52 before copying %52 into %51 (which should
11391 // happen first).
11392 //
11393 // The problem is, however, that searching for such data dependencies
11394 // can become expensive, and the cost is not directly related to the
11395 // chain depth. Instead, we'll rule out such configurations here by
11396 // insisting that we've visited all chain users (except for users
11397 // of the original chain, which is not necessary). When doing this,
11398 // we need to look through nodes we don't care about (otherwise, things
11399 // like register copies will interfere with trivial cases).
11400
11401 SmallVector<const SDNode *, 16> Worklist;
11402 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11403 IE = Visited.end(); I != IE; ++I)
11404 if (*I != OriginalChain.getNode())
11405 Worklist.push_back(*I);
11406
11407 while (!Worklist.empty()) {
11408 const SDNode *M = Worklist.pop_back_val();
11409
11410 // We have already visited M, and want to make sure we've visited any uses
11411 // of M that we care about. For uses that we've not visisted, and don't
11412 // care about, queue them to the worklist.
11413
11414 for (SDNode::use_iterator UI = M->use_begin(),
11415 UIE = M->use_end(); UI != UIE; ++UI)
11416 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11417 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11418 // We've not visited this use, and we care about it (it could have an
11419 // ordering dependency with the original node).
11420 Aliases.clear();
11421 Aliases.push_back(OriginalChain);
11422 return;
11423 }
11424
11425 // We've not visited this use, but we don't care about it. Mark it as
11426 // visited and enqueue it to the worklist.
11427 Worklist.push_back(*UI);
11428 }
11429 }
Jim Laskey708d0db2006-10-04 16:53:27 +000011430}
11431
11432/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11433/// for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011434SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11435 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011436
Jim Laskey708d0db2006-10-04 16:53:27 +000011437 // Accumulate all the aliases to this node.
11438 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011439
Dan Gohman4298df62011-05-17 22:20:36 +000011440 // If no operands then chain to entry token.
11441 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000011442 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000011443
11444 // If a single operand then chain to it. We don't need to revisit it.
11445 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000011446 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000011447
Jim Laskey708d0db2006-10-04 16:53:27 +000011448 // Construct a custom tailored token factor.
Andrew Trickef9de2a2013-05-25 02:42:55 +000011449 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Nate Begeman879d8f12009-09-15 00:18:30 +000011450 &Aliases[0], Aliases.size());
Jim Laskeyd07be232006-09-25 16:29:54 +000011451}
11452
Nate Begeman21158fc2005-09-01 00:19:25 +000011453// SelectionDAG::Combine - This is the entry point for the file.
11454//
Bill Wendling084669a2009-04-29 00:15:41 +000011455void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000011456 CodeGenOpt::Level OptLevel) {
Nate Begeman21158fc2005-09-01 00:19:25 +000011457 /// run - This is the main entry point to this class.
11458 ///
Bill Wendling084669a2009-04-29 00:15:41 +000011459 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000011460}