blob: d8d3380e92834a528fb34c525292677f7d36c49e [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
Nate Begeman21158fc2005-09-01 00:19:25 +000019#include "llvm/CodeGen/SelectionDAG.h"
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000020#include "llvm/ADT/SmallBitVector.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000021#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth9a0051c2014-07-23 07:08:53 +000022#include "llvm/ADT/SetVector.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000023#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/AliasAnalysis.h"
25#include "llvm/CodeGen/MachineFrameInfo.h"
26#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/LLVMContext.h"
Jim Laskey5d19d592006-09-21 16:28:59 +000031#include "llvm/Support/CommandLine.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000032#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000033#include "llvm/Support/ErrorHandling.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000034#include "llvm/Support/MathExtras.h"
Chris Lattner4dc3edd2009-08-23 06:35:02 +000035#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Target/TargetLowering.h"
37#include "llvm/Target/TargetMachine.h"
38#include "llvm/Target/TargetOptions.h"
Quentin Colombetde0e0622013-10-11 18:29:42 +000039#include "llvm/Target/TargetRegisterInfo.h"
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000040#include "llvm/Target/TargetSubtargetInfo.h"
Chris Lattnerbd39c1a2005-09-09 23:53:39 +000041#include <algorithm>
Nate Begeman21158fc2005-09-01 00:19:25 +000042using namespace llvm;
43
Chandler Carruth1b9dde02014-04-22 02:02:50 +000044#define DEBUG_TYPE "dagcombine"
45
Chris Lattneraee775a2006-12-19 22:41:21 +000046STATISTIC(NodesCombined , "Number of dag nodes combined");
47STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
48STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
Evan Chenga9cda8a2009-05-28 00:35:15 +000049STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
Evan Chengd42641c2011-02-02 01:06:55 +000050STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
Quentin Colombetde0e0622013-10-11 18:29:42 +000051STATISTIC(SlicedLoads, "Number of load sliced");
Chris Lattneraee775a2006-12-19 22:41:21 +000052
Nate Begeman21158fc2005-09-01 00:19:25 +000053namespace {
Jim Laskey0463e082006-10-07 23:37:56 +000054 static cl::opt<bool>
Owen Anderson7b8d2ae2010-09-19 21:01:26 +000055 CombinerAA("combiner-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000056 cl::desc("Enable DAG combiner alias-analysis heuristics"));
Jim Laskeydf2ccc32006-10-12 15:22:24 +000057
Jim Laskey55e4dca2006-10-18 19:08:31 +000058 static cl::opt<bool>
59 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000060 cl::desc("Enable DAG combiner's use of IR alias analysis"));
Jim Laskey55e4dca2006-10-18 19:08:31 +000061
Hal Finkeldbebb522014-01-25 19:24:54 +000062 static cl::opt<bool>
Hal Finkel3b48d082014-04-12 01:26:00 +000063 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
Hal Finkeldbebb522014-01-25 19:24:54 +000064 cl::desc("Enable DAG combiner's use of TBAA"));
65
Hal Finkel9b2617a2014-01-25 17:32:39 +000066#ifndef NDEBUG
67 static cl::opt<std::string>
68 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
69 cl::desc("Only use DAG-combiner alias analysis in this"
70 " function"));
71#endif
72
Quentin Colombetde0e0622013-10-11 18:29:42 +000073 /// Hidden option to stress test load slicing, i.e., when this option
74 /// is enabled, load slicing bypasses most of its profitability guards.
75 static cl::opt<bool>
76 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
77 cl::desc("Bypass the profitability model of load "
78 "slicing"),
79 cl::init(false));
80
Hal Finkel51e6fa22014-09-02 06:24:04 +000081 static cl::opt<bool>
82 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
83 cl::desc("DAG combiner may split indexing from loads"));
84
Jim Laskey6549d222006-10-05 15:07:25 +000085//------------------------------ DAGCombiner ---------------------------------//
86
Nick Lewycky02d5f772009-10-25 06:33:48 +000087 class DAGCombiner {
Nate Begeman21158fc2005-09-01 00:19:25 +000088 SelectionDAG &DAG;
Dan Gohman619ef482009-01-15 19:20:50 +000089 const TargetLowering &TLI;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000090 CombineLevel Level;
Bill Wendling026e5d72009-04-29 23:29:43 +000091 CodeGenOpt::Level OptLevel;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000092 bool LegalOperations;
93 bool LegalTypes;
Quentin Colombetde0e0622013-10-11 18:29:42 +000094 bool ForCodeSize;
Nate Begeman21158fc2005-09-01 00:19:25 +000095
Chandler Carruth9a0051c2014-07-23 07:08:53 +000096 /// \brief Worklist of all of the nodes that need to be simplified.
97 ///
98 /// This must behave as a stack -- new nodes to process are pushed onto the
99 /// back and when processing we pop off of the back.
100 ///
101 /// The worklist will not contain duplicates but may contain null entries
102 /// due to nodes being deleted from the underlying DAG.
103 SmallVector<SDNode *, 64> Worklist;
104
105 /// \brief Mapping from an SDNode to its position on the worklist.
106 ///
107 /// This is used to find and remove nodes from the worklist (by nulling
108 /// them) when they are deleted from the underlying DAG. It relies on
109 /// stable indices of nodes within the worklist.
110 DenseMap<SDNode *, unsigned> WorklistMap;
Nate Begeman21158fc2005-09-01 00:19:25 +0000111
Chandler Carruth9f4530b2014-07-24 22:15:28 +0000112 /// \brief Set of nodes which have been combined (at least once).
113 ///
114 /// This is used to allow us to reliably add any operands of a DAG node
115 /// which have not yet been combined to the worklist.
116 SmallPtrSet<SDNode *, 64> CombinedNodes;
117
Jim Laskeydcb2b832006-10-16 20:52:31 +0000118 // AA - Used for DAG load/store alias analysis.
119 AliasAnalysis &AA;
120
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000121 /// When an instruction is simplified, add all users of the instruction to
122 /// the work lists because they might get more simplified now.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000123 void AddUsersToWorklist(SDNode *N) {
Jim Grosbache8160032014-04-11 01:13:13 +0000124 for (SDNode *Node : N->uses())
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000125 AddToWorklist(Node);
Nate Begeman21158fc2005-09-01 00:19:25 +0000126 }
127
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000128 /// Call the node-specific routine that folds each particular type of node.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000129 SDValue visit(SDNode *N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000130
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000131 public:
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000132 /// Add to the worklist making sure its instance is at the back (next to be
133 /// processed.)
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000134 void AddToWorklist(SDNode *N) {
Chandler Carruth24ceb0c2014-07-21 08:32:31 +0000135 // Skip handle nodes as they can't usefully be combined and confuse the
136 // zero-use deletion strategy.
137 if (N->getOpcode() == ISD::HANDLENODE)
138 return;
139
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000140 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
141 Worklist.push_back(N);
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000142 }
Jim Laskey708d0db2006-10-04 16:53:27 +0000143
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000144 /// Remove all instances of N from the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000145 void removeFromWorklist(SDNode *N) {
Chandler Carruth9f4530b2014-07-24 22:15:28 +0000146 CombinedNodes.erase(N);
147
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000148 auto It = WorklistMap.find(N);
149 if (It == WorklistMap.end())
150 return; // Not in the worklist.
151
152 // Null out the entry rather than erasing it to avoid a linear operation.
153 Worklist[It->second] = nullptr;
154 WorklistMap.erase(It);
Chris Lattnere260ed82005-10-10 22:04:48 +0000155 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000156
Chandler Carruth18066972014-08-02 10:02:07 +0000157 void deleteAndRecombine(SDNode *N);
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000158 bool recursivelyDeleteUnusedNodes(SDNode *N);
159
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000160 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
Evan Chengfd81c732009-03-28 05:57:29 +0000161 bool AddTo = true);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000162
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000163 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
Jim Laskeydcf983c2006-10-13 23:32:28 +0000164 return CombineTo(N, &Res, 1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000165 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000166
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000167 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
Evan Chengfd81c732009-03-28 05:57:29 +0000168 bool AddTo = true) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000169 SDValue To[] = { Res0, Res1 };
Jim Laskeydcf983c2006-10-13 23:32:28 +0000170 return CombineTo(N, To, 2, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000171 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000172
173 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000174
175 private:
176
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000177 /// Check the specified integer node value to see if it can be simplified or
178 /// if things it uses can be simplified by bit propagation.
179 /// If so, return true.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000180 bool SimplifyDemandedBits(SDValue Op) {
Dan Gohman1d459e42009-12-11 21:31:27 +0000181 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
182 APInt Demanded = APInt::getAllOnesValue(BitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000183 return SimplifyDemandedBits(Op, Demanded);
184 }
185
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000186 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
Chris Lattner04c73702005-10-10 22:31:19 +0000187
Chris Lattnerffad2162006-11-11 00:39:41 +0000188 bool CombineToPreIndexedLoadStore(SDNode *N);
189 bool CombineToPostIndexedLoadStore(SDNode *N);
Hal Finkel51e6fa22014-09-02 06:24:04 +0000190 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000191 bool SliceUpLoad(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000192
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +0000193 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
194 /// load.
195 ///
196 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
197 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
198 /// \param EltNo index of the vector element to load.
199 /// \param OriginalLoad load that EVE came from to be replaced.
200 /// \returns EVE on success SDValue() on failure.
201 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
202 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000203 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
204 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
205 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
206 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
Evan Chengaf56fac2010-04-16 06:14:10 +0000207 SDValue PromoteIntBinOp(SDValue Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000208 SDValue PromoteIntShiftOp(SDValue Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +0000209 SDValue PromoteExtend(SDValue Op);
210 bool PromoteLoad(SDValue Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000211
Craig Toppere0b71182013-07-13 07:43:40 +0000212 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000213 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +0000214 ISD::NodeType ExtType);
215
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000216 /// Call the node-specific routine that knows how to fold each
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000217 /// particular type of node. If that doesn't do anything, try the
218 /// target-specific DAG combines.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000219 SDValue combine(SDNode *N);
Nate Begeman21158fc2005-09-01 00:19:25 +0000220
221 // Visitation implementation - Implement dag node combining for different
222 // node types. The semantics are as follows:
223 // Return Value:
Evan Cheng5e7658c2008-08-29 22:21:44 +0000224 // SDValue.getNode() == 0 - No change was made
225 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
226 // otherwise - N should be replaced by the returned Operand.
Nate Begeman21158fc2005-09-01 00:19:25 +0000227 //
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000228 SDValue visitTokenFactor(SDNode *N);
229 SDValue visitMERGE_VALUES(SDNode *N);
230 SDValue visitADD(SDNode *N);
231 SDValue visitSUB(SDNode *N);
232 SDValue visitADDC(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000233 SDValue visitSUBC(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000234 SDValue visitADDE(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000235 SDValue visitSUBE(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000236 SDValue visitMUL(SDNode *N);
237 SDValue visitSDIV(SDNode *N);
238 SDValue visitUDIV(SDNode *N);
239 SDValue visitSREM(SDNode *N);
240 SDValue visitUREM(SDNode *N);
241 SDValue visitMULHU(SDNode *N);
242 SDValue visitMULHS(SDNode *N);
243 SDValue visitSMUL_LOHI(SDNode *N);
244 SDValue visitUMUL_LOHI(SDNode *N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +0000245 SDValue visitSMULO(SDNode *N);
246 SDValue visitUMULO(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000247 SDValue visitSDIVREM(SDNode *N);
248 SDValue visitUDIVREM(SDNode *N);
249 SDValue visitAND(SDNode *N);
250 SDValue visitOR(SDNode *N);
251 SDValue visitXOR(SDNode *N);
252 SDValue SimplifyVBinOp(SDNode *N);
Craig Topper82384612012-09-11 01:45:21 +0000253 SDValue SimplifyVUnaryOp(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000254 SDValue visitSHL(SDNode *N);
255 SDValue visitSRA(SDNode *N);
256 SDValue visitSRL(SDNode *N);
Adam Nemet7f928f12014-03-07 23:56:30 +0000257 SDValue visitRotate(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000258 SDValue visitCTLZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000259 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000260 SDValue visitCTTZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000261 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000262 SDValue visitCTPOP(SDNode *N);
263 SDValue visitSELECT(SDNode *N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +0000264 SDValue visitVSELECT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000265 SDValue visitSELECT_CC(SDNode *N);
266 SDValue visitSETCC(SDNode *N);
267 SDValue visitSIGN_EXTEND(SDNode *N);
268 SDValue visitZERO_EXTEND(SDNode *N);
269 SDValue visitANY_EXTEND(SDNode *N);
270 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
271 SDValue visitTRUNCATE(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000272 SDValue visitBITCAST(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000273 SDValue visitBUILD_PAIR(SDNode *N);
274 SDValue visitFADD(SDNode *N);
275 SDValue visitFSUB(SDNode *N);
276 SDValue visitFMUL(SDNode *N);
Owen Anderson41b06652012-05-02 22:17:40 +0000277 SDValue visitFMA(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000278 SDValue visitFDIV(SDNode *N);
279 SDValue visitFREM(SDNode *N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +0000280 SDValue visitFSQRT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000281 SDValue visitFCOPYSIGN(SDNode *N);
282 SDValue visitSINT_TO_FP(SDNode *N);
283 SDValue visitUINT_TO_FP(SDNode *N);
284 SDValue visitFP_TO_SINT(SDNode *N);
285 SDValue visitFP_TO_UINT(SDNode *N);
286 SDValue visitFP_ROUND(SDNode *N);
287 SDValue visitFP_ROUND_INREG(SDNode *N);
288 SDValue visitFP_EXTEND(SDNode *N);
289 SDValue visitFNEG(SDNode *N);
290 SDValue visitFABS(SDNode *N);
Owen Andersona40319b2012-08-13 23:32:49 +0000291 SDValue visitFCEIL(SDNode *N);
292 SDValue visitFTRUNC(SDNode *N);
293 SDValue visitFFLOOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000294 SDValue visitBRCOND(SDNode *N);
295 SDValue visitBR_CC(SDNode *N);
296 SDValue visitLOAD(SDNode *N);
297 SDValue visitSTORE(SDNode *N);
298 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
299 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
300 SDValue visitBUILD_VECTOR(SDNode *N);
301 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +0000302 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000303 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Manman Ren413a6cb2014-01-31 01:10:35 +0000304 SDValue visitINSERT_SUBVECTOR(SDNode *N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000305
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000306 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000307 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000308
Matt Arsenault985b9de2014-03-17 18:58:01 +0000309 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
Chris Lattner7c709a52007-12-06 07:33:36 +0000310
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000311 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
312 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000313 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
314 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelcf0da6c2009-02-17 22:15:04 +0000315 SDValue N3, ISD::CondCode CC,
Bill Wendling31b50992009-01-30 23:59:18 +0000316 bool NotExtCompare = false);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000317 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000318 SDLoc DL, bool foldBooleans = true);
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000319
320 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
321 SDValue &CC) const;
322 bool isOneUseSetCC(SDValue N) const;
323
Scott Michelcf0da6c2009-02-17 22:15:04 +0000324 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner31e9edc2008-01-26 01:09:19 +0000325 unsigned HiOp);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000326 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000327 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000328 SDValue BuildSDIV(SDNode *N);
Chad Rosier17020f92014-07-23 14:57:52 +0000329 SDValue BuildSDIVPow2(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000330 SDValue BuildUDIV(SDNode *N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +0000331 SDValue BuildReciprocalEstimate(SDValue Op);
332 SDValue BuildRsqrtEstimate(SDValue Op);
Evan Cheng4c0bd962011-06-21 06:01:08 +0000333 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
334 bool DemandHighBits = true);
335 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Richard Sandiford95c864d2014-01-08 15:40:47 +0000336 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
337 SDValue InnerPos, SDValue InnerNeg,
338 unsigned PosOpcode, unsigned NegOpcode,
339 SDLoc DL);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000340 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000341 SDValue ReduceLoadWidth(SDNode *N);
Evan Chenga9cda8a2009-05-28 00:35:15 +0000342 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Chengd42641c2011-02-02 01:06:55 +0000343 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liao6d106b72012-10-23 23:06:52 +0000344 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao59229792012-10-24 04:14:18 +0000345 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000346
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000347 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000348
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000349 /// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +0000350 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000351 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +0000352 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey708d0db2006-10-04 16:53:27 +0000353
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000354 /// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000355 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000356
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000357 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
358 /// chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000359 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands41826032009-01-31 15:50:11 +0000360
Nadav Rotem7cbc12a2012-10-03 16:11:15 +0000361 /// Merge consecutive store operations into a wide store.
362 /// This optimization uses wide integers or vectors when possible.
363 /// \return True if some memory operations were changed.
364 bool MergeConsecutiveStores(StoreSDNode *N);
365
Adam Nemet67483892014-03-04 23:28:31 +0000366 /// \brief Try to transform a truncation where C is a constant:
367 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
368 ///
369 /// \p N needs to be a truncation and its first operand an AND. Other
370 /// requirements are checked by the function (e.g. that trunc is
371 /// single-use) and if missed an empty SDValue is returned.
372 SDValue distributeTruncateThroughAnd(SDNode *N);
373
Chris Lattner4041ab62010-04-15 04:48:01 +0000374 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000375 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombetde0e0622013-10-11 18:29:42 +0000376 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
377 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
378 AttributeSet FnAttrs =
379 DAG.getMachineFunction().getFunction()->getAttributes();
380 ForCodeSize =
381 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
382 Attribute::OptimizeForSize) ||
383 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
384 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000385
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000386 /// Runs the dag combiner on all nodes in the work list
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000387 void Run(CombineLevel AtLevel);
Wesley Peck527da1b2010-11-23 03:31:01 +0000388
Chris Lattner4041ab62010-04-15 04:48:01 +0000389 SelectionDAG &getDAG() const { return DAG; }
Wesley Peck527da1b2010-11-23 03:31:01 +0000390
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000391 /// Returns a type large enough to hold any valid shift amount - before type
392 /// legalization these can be huge.
Owen Andersonb2c80da2011-02-25 21:41:48 +0000393 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +0000394 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
395 if (LHSTy.isVector())
396 return LHSTy;
Jack Carterd4e96152013-10-17 01:34:33 +0000397 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
398 : TLI.getPointerTy();
Chris Lattner4041ab62010-04-15 04:48:01 +0000399 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000400
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000401 /// This method returns true if we are running before type legalization or
402 /// if the specified VT is legal.
Chris Lattner4041ab62010-04-15 04:48:01 +0000403 bool isTypeLegal(const EVT &VT) {
404 if (!LegalTypes) return true;
405 return TLI.isTypeLegal(VT);
406 }
Matt Arsenault758659232013-05-18 00:21:46 +0000407
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000408 /// Convenience wrapper around TargetLowering::getSetCCResultType
Matt Arsenault758659232013-05-18 00:21:46 +0000409 EVT getSetCCResultType(EVT VT) const {
410 return TLI.getSetCCResultType(*DAG.getContext(), VT);
411 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000412 };
413}
414
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000415
416namespace {
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000417/// This class is a DAGUpdateListener that removes any deleted
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000418/// nodes from the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000419class WorklistRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000420 DAGCombiner &DC;
421public:
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000422 explicit WorklistRemover(DAGCombiner &dc)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000423 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000424
Craig Topper7b883b32014-03-08 06:31:39 +0000425 void NodeDeleted(SDNode *N, SDNode *E) override {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000426 DC.removeFromWorklist(N);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000427 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000428};
429}
430
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000431//===----------------------------------------------------------------------===//
432// TargetLowering::DAGCombinerInfo implementation
433//===----------------------------------------------------------------------===//
434
435void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000436 ((DAGCombiner*)DC)->AddToWorklist(N);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000437}
438
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000439void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000440 ((DAGCombiner*)DC)->removeFromWorklist(N);
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000441}
442
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000443SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000444CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
445 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000446}
447
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000448SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000449CombineTo(SDNode *N, SDValue Res, bool AddTo) {
450 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000451}
452
453
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000454SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000455CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
456 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000457}
458
Dan Gohmane58ab792009-01-29 01:59:02 +0000459void TargetLowering::DAGCombinerInfo::
460CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
461 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
462}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000463
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000464//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000465// Helper Functions
466//===----------------------------------------------------------------------===//
467
Chandler Carruth18066972014-08-02 10:02:07 +0000468void DAGCombiner::deleteAndRecombine(SDNode *N) {
469 removeFromWorklist(N);
470
471 // If the operands of this node are only used by the node, they will now be
472 // dead. Make sure to re-visit them and recursively delete dead nodes.
473 for (const SDValue &Op : N->ops())
Hal Finkel51e6fa22014-09-02 06:24:04 +0000474 // For an operand generating multiple values, one of the values may
475 // become dead allowing further simplification (e.g. split index
476 // arithmetic from an indexed load).
477 if (Op->hasOneUse() || Op->getNumValues() > 1)
Chandler Carruth18066972014-08-02 10:02:07 +0000478 AddToWorklist(Op.getNode());
479
480 DAG.DeleteNode(N);
481}
482
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000483/// Return 1 if we can compute the negated form of the specified expression for
484/// the same cost as the expression itself, or 2 if we can compute the negated
485/// form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000486static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000487 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000488 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000489 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000490 // fneg is removable even if it has multiple uses.
491 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000492
Chris Lattnere49c9742007-05-14 22:04:50 +0000493 // Don't allow anything with multiple uses.
494 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000495
Chris Lattner46980832007-05-25 02:19:06 +0000496 // Don't recurse exponentially.
497 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000498
Chris Lattnere49c9742007-05-14 22:04:50 +0000499 switch (Op.getOpcode()) {
500 default: return false;
501 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000502 // Don't invert constant FP values after legalize. The negated constant
503 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000504 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000505 case ISD::FADD:
506 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000507 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000508
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000509 // After operation legalization, it might not be legal to create new FSUBs.
510 if (LegalOperations &&
511 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
512 return 0;
513
Craig Topper03f39772012-09-09 22:58:45 +0000514 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000515 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
516 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000517 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000518 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000519 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000520 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000521 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000522 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000523 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000524
Bill Wendling6fbf5492009-01-30 23:10:18 +0000525 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000526 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000527
Chris Lattnere49c9742007-05-14 22:04:50 +0000528 case ISD::FMUL:
529 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000530 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000531
Bill Wendling6fbf5492009-01-30 23:10:18 +0000532 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000533 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
534 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000535 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000536
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000537 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000538 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000539
Chris Lattnere49c9742007-05-14 22:04:50 +0000540 case ISD::FP_EXTEND:
541 case ISD::FP_ROUND:
542 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000543 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000544 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000545 }
546}
547
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000548/// If isNegatibleForFree returns true, return the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000549static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000550 bool LegalOperations, unsigned Depth = 0) {
Sanjay Patel78614bf2014-08-28 15:53:16 +0000551 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattnere49c9742007-05-14 22:04:50 +0000552 // fneg is removable even if it has multiple uses.
553 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000554
Chris Lattnere49c9742007-05-14 22:04:50 +0000555 // Don't allow anything with multiple uses.
556 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000557
Chris Lattner46980832007-05-25 02:19:06 +0000558 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000559 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000560 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000561 case ISD::ConstantFP: {
562 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
563 V.changeSign();
564 return DAG.getConstantFP(V, Op.getValueType());
565 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000566 case ISD::FADD:
567 // FIXME: determine better conditions for this xform.
Sanjay Patel78614bf2014-08-28 15:53:16 +0000568 assert(Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000569
Bill Wendling6fbf5492009-01-30 23:10:18 +0000570 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000571 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Sanjay Patel78614bf2014-08-28 15:53:16 +0000572 DAG.getTargetLoweringInfo(), &Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000573 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000574 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000575 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000576 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000577 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000578 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000579 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000580 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000581 Op.getOperand(0));
582 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000583 // We can't turn -(A-B) into B-A when we honor signed zeros.
Sanjay Patel78614bf2014-08-28 15:53:16 +0000584 assert(Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000585
Bill Wendling6fbf5492009-01-30 23:10:18 +0000586 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000587 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen446b9002007-08-31 23:34:27 +0000588 if (N0CFP->getValueAPF().isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000589 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000590
Bill Wendling6fbf5492009-01-30 23:10:18 +0000591 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000592 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000593 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000594
Chris Lattnere49c9742007-05-14 22:04:50 +0000595 case ISD::FMUL:
596 case ISD::FDIV:
Sanjay Patel78614bf2014-08-28 15:53:16 +0000597 assert(!Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000598
Bill Wendling6fbf5492009-01-30 23:10:18 +0000599 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000600 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Sanjay Patel78614bf2014-08-28 15:53:16 +0000601 DAG.getTargetLoweringInfo(), &Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000602 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000603 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000604 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000605 Op.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000606
Bill Wendling6fbf5492009-01-30 23:10:18 +0000607 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000608 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattnere49c9742007-05-14 22:04:50 +0000609 Op.getOperand(0),
Chris Lattnere7c14012008-02-26 07:04:54 +0000610 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000611 LegalOperations, Depth+1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000612
Chris Lattnere49c9742007-05-14 22:04:50 +0000613 case ISD::FP_EXTEND:
Chris Lattnere49c9742007-05-14 22:04:50 +0000614 case ISD::FSIN:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000615 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000616 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000617 LegalOperations, Depth+1));
Chris Lattner72733e52008-01-17 07:00:52 +0000618 case ISD::FP_ROUND:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000619 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000620 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000621 LegalOperations, Depth+1),
Chris Lattner72733e52008-01-17 07:00:52 +0000622 Op.getOperand(1));
Chris Lattnere49c9742007-05-14 22:04:50 +0000623 }
624}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000625
Sanjay Patelf4b8deb2014-09-05 20:55:46 +0000626// Return true if this node is a setcc, or is a select_cc
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000627// that selects between the target values used for true and false, making it
628// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
629// the appropriate nodes based on the type of node we are checking. This
630// simplifies life a bit for the callers.
631bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
632 SDValue &CC) const {
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000633 if (N.getOpcode() == ISD::SETCC) {
634 LHS = N.getOperand(0);
635 RHS = N.getOperand(1);
636 CC = N.getOperand(2);
Nate Begeman2504fe22005-09-01 23:24:04 +0000637 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000638 }
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000639
640 if (N.getOpcode() != ISD::SELECT_CC ||
641 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
642 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
643 return false;
644
645 LHS = N.getOperand(0);
646 RHS = N.getOperand(1);
647 CC = N.getOperand(4);
648 return true;
Nate Begeman21158fc2005-09-01 00:19:25 +0000649}
650
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000651/// Return true if this is a SetCC-equivalent operation with only one use.
652/// If this is true, it allows the users to invert the operation for free when
653/// it is profitable to do so.
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000654bool DAGCombiner::isOneUseSetCC(SDValue N) const {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000655 SDValue N0, N1, N2;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000656 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman2504fe22005-09-01 23:24:04 +0000657 return true;
658 return false;
659}
660
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000661/// Returns true if N is a BUILD_VECTOR node whose
Matt Arsenault985b9de2014-03-17 18:58:01 +0000662/// elements are all the same constant or undefined.
663static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
664 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
665 if (!C)
666 return false;
667
668 APInt SplatUndef;
669 unsigned SplatBitSize;
670 bool HasAnyUndefs;
671 EVT EltVT = N->getValueType(0).getVectorElementType();
672 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
673 HasAnyUndefs) &&
674 EltVT.getSizeInBits() >= SplatBitSize);
675}
676
677// \brief Returns the SDNode if it is a constant BuildVector or constant.
Juergen Ributzka68402822014-01-13 21:49:25 +0000678static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
679 if (isa<ConstantSDNode>(N))
680 return N.getNode();
681 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
Sanjay Patelf4b8deb2014-09-05 20:55:46 +0000682 if (BV && BV->isConstant())
Juergen Ributzka68402822014-01-13 21:49:25 +0000683 return BV;
Craig Topperc0196b12014-04-14 00:51:57 +0000684 return nullptr;
Juergen Ributzka68402822014-01-13 21:49:25 +0000685}
686
Matt Arsenault985b9de2014-03-17 18:58:01 +0000687// \brief Returns the SDNode if it is a constant splat BuildVector or constant
688// int.
689static ConstantSDNode *isConstOrConstSplat(SDValue N) {
690 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
691 return CN;
692
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000693 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000694 BitVector UndefElements;
695 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000696
697 // BuildVectors can truncate their operands. Ignore that case here.
Chandler Carruthb844e722014-07-08 07:19:55 +0000698 // FIXME: We blindly ignore splats which include undef which is overly
699 // pessimistic.
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000700 if (CN && UndefElements.none() &&
Chandler Carruthb844e722014-07-08 07:19:55 +0000701 CN->getValueType(0) == N.getValueType().getScalarType())
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000702 return CN;
703 }
Matt Arsenault985b9de2014-03-17 18:58:01 +0000704
705 return nullptr;
706}
707
Matt Arsenault6cc00422014-08-16 10:14:19 +0000708// \brief Returns the SDNode if it is a constant splat BuildVector or constant
709// float.
710static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
711 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
712 return CN;
713
714 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
715 BitVector UndefElements;
716 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
717
Matt Arsenault965de302014-09-02 18:33:51 +0000718 if (CN && UndefElements.none())
Matt Arsenault6cc00422014-08-16 10:14:19 +0000719 return CN;
720 }
721
722 return nullptr;
723}
724
Andrew Trickef9de2a2013-05-25 02:42:55 +0000725SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000726 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000727 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000728 if (N0.getOpcode() == Opc) {
729 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
730 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
731 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
732 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
733 if (!OpNode.getNode())
734 return SDValue();
735 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
Juergen Ributzka73844052014-01-13 20:51:35 +0000736 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000737 if (N0.hasOneUse()) {
738 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
739 // use
740 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
741 if (!OpNode.getNode())
742 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000743 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000744 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000745 }
746 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000747 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000748
Juergen Ributzka68402822014-01-13 21:49:25 +0000749 if (N1.getOpcode() == Opc) {
750 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
751 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
752 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
753 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
754 if (!OpNode.getNode())
755 return SDValue();
756 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
757 }
758 if (N1.hasOneUse()) {
759 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
760 // use
761 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
762 if (!OpNode.getNode())
763 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000764 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000765 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
766 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000767 }
768 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000769
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000770 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000771}
772
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000773SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
774 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000775 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
776 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000777 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000778 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000779 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000780 To[0].getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000781 dbgs() << " and " << NumTo-1 << " other values\n";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000782 for (unsigned i = 0, e = NumTo; i != e; ++i)
Jakob Stoklund Olesen32042f92009-12-03 05:15:35 +0000783 assert((!To[i].getNode() ||
784 N->getValueType(i) == To[i].getValueType()) &&
Dan Gohman7e6b9322009-01-21 15:17:51 +0000785 "Cannot combine value to value of different type!"));
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000786 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000787 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000788 if (AddTo) {
789 // Push the new nodes and any users onto the worklist
790 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000791 if (To[i].getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000792 AddToWorklist(To[i].getNode());
793 AddUsersToWorklist(To[i].getNode());
Chris Lattner4147f082009-03-12 06:52:53 +0000794 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000795 }
796 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000797
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000798 // Finally, if the node is now dead, remove it from the graph. The node
799 // may not be dead if the replacement process recursively simplified to
800 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000801 if (N->use_empty())
802 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000803 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000804}
805
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000806void DAGCombiner::
807CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000808 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000809 // are deleted, make sure to remove them from our worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000810 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000811 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000812
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000813 // Push the new node and any (possibly new) users onto the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000814 AddToWorklist(TLO.New.getNode());
815 AddUsersToWorklist(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000816
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000817 // Finally, if the node is now dead, remove it from the graph. The node
818 // may not be dead if the replacement process recursively simplified to
819 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000820 if (TLO.Old.getNode()->use_empty())
821 deleteAndRecombine(TLO.Old.getNode());
Dan Gohmane58ab792009-01-29 01:59:02 +0000822}
823
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000824/// Check the specified integer node value to see if it can be simplified or if
825/// things it uses can be simplified by bit propagation. If so, return true.
Dan Gohmane58ab792009-01-29 01:59:02 +0000826bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000827 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000828 APInt KnownZero, KnownOne;
829 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
830 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000831
Dan Gohmane58ab792009-01-29 01:59:02 +0000832 // Revisit the node.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000833 AddToWorklist(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000834
Dan Gohmane58ab792009-01-29 01:59:02 +0000835 // Replace the old value with the new one.
836 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000837 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000838 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000839 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000840 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000841 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000842
Dan Gohmane58ab792009-01-29 01:59:02 +0000843 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000844 return true;
845}
846
Evan Cheng0abb54d2010-04-24 04:43:44 +0000847void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000848 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000849 EVT VT = Load->getValueType(0);
850 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000851
Evan Cheng0abb54d2010-04-24 04:43:44 +0000852 DEBUG(dbgs() << "\nReplacing.9 ";
853 Load->dump(&DAG);
854 dbgs() << "\nWith: ";
855 Trunc.getNode()->dump(&DAG);
856 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000857 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000858 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
859 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Chandler Carruth18066972014-08-02 10:02:07 +0000860 deleteAndRecombine(Load);
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000861 AddToWorklist(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000862}
863
864SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
865 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000866 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000867 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000868 EVT MemVT = LD->getMemoryVT();
869 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +0000870 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +0000871 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000872 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000873 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000874 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000875 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000876 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000877 }
878
Evan Chenge19aa5c2010-04-19 19:29:22 +0000879 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000880 switch (Opc) {
881 default: break;
882 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000883 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000884 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000885 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000886 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000887 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000888 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000889 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000890 case ISD::Constant: {
891 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000892 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000893 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000894 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000895 }
896
897 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000898 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000899 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000900}
901
Evan Cheng0abb54d2010-04-24 04:43:44 +0000902SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000903 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
904 return SDValue();
905 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000906 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000907 bool Replace = false;
908 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000909 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000910 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000911 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000912
913 if (Replace)
914 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
915 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000916 DAG.getValueType(OldVT));
917}
918
Evan Cheng0abb54d2010-04-24 04:43:44 +0000919SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000920 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000921 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000922 bool Replace = false;
923 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000924 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000925 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000926 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000927
928 if (Replace)
929 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
930 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000931}
932
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000933/// Promote the specified integer binary operation if the target indicates it is
934/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
935/// i32 since i16 instructions are longer.
Evan Chengaf56fac2010-04-16 06:14:10 +0000936SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
937 if (!LegalOperations)
938 return SDValue();
939
940 EVT VT = Op.getValueType();
941 if (VT.isVector() || !VT.isInteger())
942 return SDValue();
943
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000944 // If operation type is 'undesirable', e.g. i16 on x86, consider
945 // promoting it.
946 unsigned Opc = Op.getOpcode();
947 if (TLI.isTypeDesirableForOp(Opc, VT))
948 return SDValue();
949
Evan Chengaf56fac2010-04-16 06:14:10 +0000950 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000951 // Consult target whether it is a good idea to promote this operation and
952 // what's the right type to promote it to.
953 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +0000954 assert(PVT != VT && "Don't know what type to promote to!");
955
Evan Cheng0abb54d2010-04-24 04:43:44 +0000956 bool Replace0 = false;
957 SDValue N0 = Op.getOperand(0);
958 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
Craig Topperc0196b12014-04-14 00:51:57 +0000959 if (!NN0.getNode())
Evan Chengf1223bd2010-04-22 20:19:46 +0000960 return SDValue();
961
Evan Cheng0abb54d2010-04-24 04:43:44 +0000962 bool Replace1 = false;
963 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +0000964 SDValue NN1;
965 if (N0 == N1)
966 NN1 = NN0;
967 else {
968 NN1 = PromoteOperand(N1, PVT, Replace1);
Craig Topperc0196b12014-04-14 00:51:57 +0000969 if (!NN1.getNode())
Evan Cheng02947a42010-05-10 19:03:57 +0000970 return SDValue();
971 }
Evan Chengf1223bd2010-04-22 20:19:46 +0000972
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000973 AddToWorklist(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +0000974 if (NN1.getNode())
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000975 AddToWorklist(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000976
977 if (Replace0)
978 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
979 if (Replace1)
980 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +0000981
Evan Chenge8136902010-04-27 19:48:13 +0000982 DEBUG(dbgs() << "\nPromoting ";
983 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000984 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000985 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000986 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +0000987 }
988 return SDValue();
989}
990
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000991/// Promote the specified integer shift operation if the target indicates it is
992/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
993/// i32 since i16 instructions are longer.
Evan Chengf1223bd2010-04-22 20:19:46 +0000994SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
995 if (!LegalOperations)
996 return SDValue();
997
998 EVT VT = Op.getValueType();
999 if (VT.isVector() || !VT.isInteger())
1000 return SDValue();
1001
1002 // If operation type is 'undesirable', e.g. i16 on x86, consider
1003 // promoting it.
1004 unsigned Opc = Op.getOpcode();
1005 if (TLI.isTypeDesirableForOp(Opc, VT))
1006 return SDValue();
1007
1008 EVT PVT = VT;
1009 // Consult target whether it is a good idea to promote this operation and
1010 // what's the right type to promote it to.
1011 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1012 assert(PVT != VT && "Don't know what type to promote to!");
1013
Evan Cheng0abb54d2010-04-24 04:43:44 +00001014 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001015 SDValue N0 = Op.getOperand(0);
1016 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +00001017 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001018 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +00001019 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001020 else
Evan Cheng0abb54d2010-04-24 04:43:44 +00001021 N0 = PromoteOperand(N0, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +00001022 if (!N0.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001023 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +00001024
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001025 AddToWorklist(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +00001026 if (Replace)
1027 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +00001028
Evan Chenge8136902010-04-27 19:48:13 +00001029 DEBUG(dbgs() << "\nPromoting ";
1030 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001031 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +00001032 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +00001033 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +00001034 }
1035 return SDValue();
1036}
1037
Evan Chenge19aa5c2010-04-19 19:29:22 +00001038SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1039 if (!LegalOperations)
1040 return SDValue();
1041
1042 EVT VT = Op.getValueType();
1043 if (VT.isVector() || !VT.isInteger())
1044 return SDValue();
1045
1046 // If operation type is 'undesirable', e.g. i16 on x86, consider
1047 // promoting it.
1048 unsigned Opc = Op.getOpcode();
1049 if (TLI.isTypeDesirableForOp(Opc, VT))
1050 return SDValue();
1051
1052 EVT PVT = VT;
1053 // Consult target whether it is a good idea to promote this operation and
1054 // what's the right type to promote it to.
1055 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1056 assert(PVT != VT && "Don't know what type to promote to!");
1057 // fold (aext (aext x)) -> (aext x)
1058 // fold (aext (zext x)) -> (zext x)
1059 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +00001060 DEBUG(dbgs() << "\nPromoting ";
1061 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001062 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001063 }
1064 return SDValue();
1065}
1066
1067bool DAGCombiner::PromoteLoad(SDValue Op) {
1068 if (!LegalOperations)
1069 return false;
1070
1071 EVT VT = Op.getValueType();
1072 if (VT.isVector() || !VT.isInteger())
1073 return false;
1074
1075 // If operation type is 'undesirable', e.g. i16 on x86, consider
1076 // promoting it.
1077 unsigned Opc = Op.getOpcode();
1078 if (TLI.isTypeDesirableForOp(Opc, VT))
1079 return false;
1080
1081 EVT PVT = VT;
1082 // Consult target whether it is a good idea to promote this operation and
1083 // what's the right type to promote it to.
1084 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1085 assert(PVT != VT && "Don't know what type to promote to!");
1086
Andrew Trickef9de2a2013-05-25 02:42:55 +00001087 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001088 SDNode *N = Op.getNode();
1089 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001090 EVT MemVT = LD->getMemoryVT();
1091 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +00001092 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +00001093 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001094 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001095 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001096 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001097 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001098 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1099
Evan Cheng0abb54d2010-04-24 04:43:44 +00001100 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001101 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001102 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001103 Result.getNode()->dump(&DAG);
1104 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001105 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001106 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1107 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Chandler Carruth18066972014-08-02 10:02:07 +00001108 deleteAndRecombine(N);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001109 AddToWorklist(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001110 return true;
1111 }
1112 return false;
1113}
1114
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001115/// \brief Recursively delete a node which has no uses and any operands for
1116/// which it is the only use.
1117///
1118/// Note that this both deletes the nodes and removes them from the worklist.
1119/// It also adds any nodes who have had a user deleted to the worklist as they
1120/// may now have only one use and subject to other combines.
1121bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1122 if (!N->use_empty())
1123 return false;
1124
1125 SmallSetVector<SDNode *, 16> Nodes;
1126 Nodes.insert(N);
1127 do {
1128 N = Nodes.pop_back_val();
1129 if (!N)
1130 continue;
1131
1132 if (N->use_empty()) {
1133 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1134 Nodes.insert(N->getOperand(i).getNode());
1135
1136 removeFromWorklist(N);
1137 DAG.DeleteNode(N);
1138 } else {
1139 AddToWorklist(N);
1140 }
1141 } while (!Nodes.empty());
1142 return true;
1143}
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001144
Chris Lattnere49c9742007-05-14 22:04:50 +00001145//===----------------------------------------------------------------------===//
1146// Main DAG Combiner implementation
1147//===----------------------------------------------------------------------===//
1148
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001149void DAGCombiner::Run(CombineLevel AtLevel) {
1150 // set the instance variables, so that the various visit routines may use it.
1151 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001152 LegalOperations = Level >= AfterLegalizeVectorOps;
1153 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001154
Evan Cheng5e7658c2008-08-29 22:21:44 +00001155 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001156 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1157 E = DAG.allnodes_end(); I != E; ++I)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001158 AddToWorklist(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001159
Evan Cheng5e7658c2008-08-29 22:21:44 +00001160 // Create a dummy node (which is not added to allnodes), that adds a reference
1161 // to the root node, preventing it from being deleted, and tracking any
1162 // changes of the root.
1163 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001164
James Molloy67b6b112012-02-16 09:17:04 +00001165 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001166 // try and combine it.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001167 while (!WorklistMap.empty()) {
James Molloy67b6b112012-02-16 09:17:04 +00001168 SDNode *N;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001169 // The Worklist holds the SDNodes in order, but it may contain null entries.
James Molloy67b6b112012-02-16 09:17:04 +00001170 do {
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001171 N = Worklist.pop_back_val();
1172 } while (!N);
1173
1174 bool GoodWorklistEntry = WorklistMap.erase(N);
1175 (void)GoodWorklistEntry;
1176 assert(GoodWorklistEntry &&
1177 "Found a worklist entry without a corresponding map entry!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00001178
Evan Cheng5e7658c2008-08-29 22:21:44 +00001179 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1180 // N is deleted from the DAG, since they too may now be dead or may have a
1181 // reduced number of uses, allowing other xforms.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001182 if (recursivelyDeleteUnusedNodes(N))
Evan Cheng5e7658c2008-08-29 22:21:44 +00001183 continue;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001184
1185 WorklistRemover DeadNodes(*this);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001186
Chandler Carruth411fb402014-07-26 05:49:40 +00001187 // If this combine is running after legalizing the DAG, re-legalize any
1188 // nodes pulled off the worklist.
1189 if (Level == AfterLegalizeDAG) {
1190 SmallSetVector<SDNode *, 16> UpdatedNodes;
1191 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1192
1193 for (SDNode *LN : UpdatedNodes) {
1194 AddToWorklist(LN);
1195 AddUsersToWorklist(LN);
1196 }
1197 if (!NIsValid)
1198 continue;
1199 }
1200
Chandler Carruthb1432742014-07-28 17:55:07 +00001201 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1202
Chandler Carruthcde4eb52014-08-03 23:10:59 +00001203 // Add any operands of the new node which have not yet been combined to the
1204 // worklist as well. Because the worklist uniques things already, this
1205 // won't repeatedly process the same operand.
1206 CombinedNodes.insert(N);
1207 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1208 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1209 AddToWorklist(N->getOperand(i).getNode());
1210
Evan Cheng5e7658c2008-08-29 22:21:44 +00001211 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001212
Craig Topperc0196b12014-04-14 00:51:57 +00001213 if (!RV.getNode())
Evan Cheng5e7658c2008-08-29 22:21:44 +00001214 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001215
Evan Cheng5e7658c2008-08-29 22:21:44 +00001216 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001217
Evan Cheng5e7658c2008-08-29 22:21:44 +00001218 // If we get back the same node we passed in, rather than a new node or
1219 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001220 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001221 // mechanics for us, we have no work to do in this case.
1222 if (RV.getNode() == N)
1223 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001224
Evan Cheng5e7658c2008-08-29 22:21:44 +00001225 assert(N->getOpcode() != ISD::DELETED_NODE &&
1226 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1227 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001228
Chandler Carruth9f4530b2014-07-24 22:15:28 +00001229 DEBUG(dbgs() << " ... into: ";
1230 RV.getNode()->dump(&DAG));
Eric Christopherd6300d22011-07-14 01:12:15 +00001231
Devang Patelefec7712011-05-23 22:04:42 +00001232 // Transfer debug value.
1233 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001234 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001235 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001236 else {
1237 assert(N->getValueType(0) == RV.getValueType() &&
1238 N->getNumValues() == 1 && "Type mismatch");
1239 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001240 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001241 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001242
Evan Cheng5e7658c2008-08-29 22:21:44 +00001243 // Push the new node and any users onto the worklist
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001244 AddToWorklist(RV.getNode());
1245 AddUsersToWorklist(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001246
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001247 // Finally, if the node is now dead, remove it from the graph. The node
1248 // may not be dead if the replacement process recursively simplified to
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001249 // something else needing this node. This will also take care of adding any
1250 // operands which have lost a user to the worklist.
1251 recursivelyDeleteUnusedNodes(N);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001252 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001253
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001254 // If the root changed (e.g. it was a dead load, update the root).
1255 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001256 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001257}
1258
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001259SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001260 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001261 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001262 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001263 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001264 case ISD::ADD: return visitADD(N);
1265 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001266 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001267 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001268 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001269 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001270 case ISD::MUL: return visitMUL(N);
1271 case ISD::SDIV: return visitSDIV(N);
1272 case ISD::UDIV: return visitUDIV(N);
1273 case ISD::SREM: return visitSREM(N);
1274 case ISD::UREM: return visitUREM(N);
1275 case ISD::MULHU: return visitMULHU(N);
1276 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001277 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1278 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001279 case ISD::SMULO: return visitSMULO(N);
1280 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001281 case ISD::SDIVREM: return visitSDIVREM(N);
1282 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001283 case ISD::AND: return visitAND(N);
1284 case ISD::OR: return visitOR(N);
1285 case ISD::XOR: return visitXOR(N);
1286 case ISD::SHL: return visitSHL(N);
1287 case ISD::SRA: return visitSRA(N);
1288 case ISD::SRL: return visitSRL(N);
Adam Nemet7f928f12014-03-07 23:56:30 +00001289 case ISD::ROTR:
1290 case ISD::ROTL: return visitRotate(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001291 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001292 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001293 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001294 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001295 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001296 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001297 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001298 case ISD::SELECT_CC: return visitSELECT_CC(N);
1299 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001300 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1301 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001302 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001303 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1304 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001305 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001306 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001307 case ISD::FADD: return visitFADD(N);
1308 case ISD::FSUB: return visitFSUB(N);
1309 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001310 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001311 case ISD::FDIV: return visitFDIV(N);
1312 case ISD::FREM: return visitFREM(N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +00001313 case ISD::FSQRT: return visitFSQRT(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001314 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001315 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1316 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1317 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1318 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1319 case ISD::FP_ROUND: return visitFP_ROUND(N);
1320 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1321 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1322 case ISD::FNEG: return visitFNEG(N);
1323 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001324 case ISD::FFLOOR: return visitFFLOOR(N);
1325 case ISD::FCEIL: return visitFCEIL(N);
1326 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001327 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001328 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001329 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001330 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001331 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001332 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001333 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1334 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001335 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001336 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001337 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001338 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001339 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001340}
1341
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001342SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001343 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001344
1345 // If nothing happened, try a target-specific DAG combine.
Craig Topperc0196b12014-04-14 00:51:57 +00001346 if (!RV.getNode()) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001347 assert(N->getOpcode() != ISD::DELETED_NODE &&
1348 "Node was deleted but visit returned NULL!");
1349
1350 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1351 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1352
1353 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001354 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001355 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001356
1357 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1358 }
1359 }
1360
Evan Chengf1005572010-04-28 07:10:39 +00001361 // If nothing happened still, try promoting the operation.
Craig Topperc0196b12014-04-14 00:51:57 +00001362 if (!RV.getNode()) {
Evan Chengf1005572010-04-28 07:10:39 +00001363 switch (N->getOpcode()) {
1364 default: break;
1365 case ISD::ADD:
1366 case ISD::SUB:
1367 case ISD::MUL:
1368 case ISD::AND:
1369 case ISD::OR:
1370 case ISD::XOR:
1371 RV = PromoteIntBinOp(SDValue(N, 0));
1372 break;
1373 case ISD::SHL:
1374 case ISD::SRA:
1375 case ISD::SRL:
1376 RV = PromoteIntShiftOp(SDValue(N, 0));
1377 break;
1378 case ISD::SIGN_EXTEND:
1379 case ISD::ZERO_EXTEND:
1380 case ISD::ANY_EXTEND:
1381 RV = PromoteExtend(SDValue(N, 0));
1382 break;
1383 case ISD::LOAD:
1384 if (PromoteLoad(SDValue(N, 0)))
1385 RV = SDValue(N, 0);
1386 break;
1387 }
1388 }
1389
Scott Michelcf0da6c2009-02-17 22:15:04 +00001390 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001391 // sdisel CSE.
Craig Topperc0196b12014-04-14 00:51:57 +00001392 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
Evan Cheng31604a62008-03-22 01:55:50 +00001393 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001394 SDValue N0 = N->getOperand(0);
1395 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001396
Evan Cheng31604a62008-03-22 01:55:50 +00001397 // Constant operands are canonicalized to RHS.
1398 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00001399 SDValue Ops[] = {N1, N0};
1400 SDNode *CSENode;
1401 if (const BinaryWithFlagsSDNode *BinNode =
1402 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1403 CSENode = DAG.getNodeIfExists(
1404 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1405 BinNode->hasNoSignedWrap(), BinNode->isExact());
1406 } else {
1407 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1408 }
Evan Chengfe7610f2008-03-24 23:55:16 +00001409 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001410 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001411 }
1412 }
1413
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001414 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001415}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001416
Sanjay Patel50cbfc52014-08-28 16:29:51 +00001417/// Given a node, return its input chain if it has one, otherwise return a null
1418/// sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001419static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001420 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001421 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001422 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001423 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001424 return N->getOperand(NumOps-1);
1425 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001426 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001427 return N->getOperand(i);
1428 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001429 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001430}
1431
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001432SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001433 // If N has two operands, where one has an input chain equal to the other,
1434 // the 'other' chain is redundant.
1435 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001436 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001437 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001438 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001439 return N->getOperand(1);
1440 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001441
Chris Lattner48fb92f2007-05-16 06:37:59 +00001442 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001443 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001444 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001445 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001446
Jim Laskey708d0db2006-10-04 16:53:27 +00001447 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001448 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001449
Jim Laskey0463e082006-10-07 23:37:56 +00001450 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001451 // encountered.
1452 for (unsigned i = 0; i < TFs.size(); ++i) {
1453 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001454
Jim Laskey708d0db2006-10-04 16:53:27 +00001455 // Check each of the operands.
1456 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001457 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001458
Jim Laskey708d0db2006-10-04 16:53:27 +00001459 switch (Op.getOpcode()) {
1460 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001461 // Entry tokens don't need to be added to the list. They are
1462 // rededundant.
1463 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001464 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001465
Jim Laskey708d0db2006-10-04 16:53:27 +00001466 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001467 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001468 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001469 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001470 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001471 // Clean up in case the token factor is removed.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001472 AddToWorklist(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001473 Changed = true;
1474 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001475 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001476 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001477
Jim Laskey708d0db2006-10-04 16:53:27 +00001478 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001479 // Only add if it isn't already in the list.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001480 if (SeenOps.insert(Op.getNode()))
Jim Laskey6549d222006-10-05 15:07:25 +00001481 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001482 else
1483 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001484 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001485 }
1486 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001487 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001488
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001489 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001490
1491 // If we've change things around then replace token factor.
1492 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001493 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001494 // The entry token is the only possible outcome.
1495 Result = DAG.getEntryNode();
1496 } else {
1497 // New and improved token factor.
Craig Topper48d114b2014-04-26 18:35:24 +00001498 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
Nate Begeman02b23c62005-10-13 03:11:28 +00001499 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001500
Jim Laskeydcf983c2006-10-13 23:32:28 +00001501 // Don't add users to work list.
1502 return CombineTo(N, Result, false);
Nate Begeman02b23c62005-10-13 03:11:28 +00001503 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001504
Jim Laskey708d0db2006-10-04 16:53:27 +00001505 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001506}
1507
Chris Lattneree322b42008-02-13 07:25:05 +00001508/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001509SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001510 WorklistRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001511 // Replacing results may cause a different MERGE_VALUES to suddenly
1512 // be CSE'd with N, and carry its uses with it. Iterate until no
1513 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001514 // First add the users of this node to the work list so that they
1515 // can be tried again once they have new operands.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001516 AddUsersToWorklist(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001517 do {
1518 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001519 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001520 } while (!N->use_empty());
Chandler Carruth18066972014-08-02 10:02:07 +00001521 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001522 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001523}
1524
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001525SDValue DAGCombiner::visitADD(SDNode *N) {
1526 SDValue N0 = N->getOperand(0);
1527 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001528 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1529 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001530 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001531
1532 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001533 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001534 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001535 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001536
1537 // fold (add x, 0) -> x, vector edition
1538 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1539 return N0;
1540 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1541 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001542 }
Bill Wendling0864a752008-12-10 22:36:00 +00001543
Dan Gohman06563a82007-07-03 14:03:57 +00001544 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001545 if (N0.getOpcode() == ISD::UNDEF)
1546 return N0;
1547 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001548 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001549 // fold (add c1, c2) -> c1+c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001550 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001551 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001552 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00001553 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001554 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001555 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001556 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001557 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001558 // fold (add Sym, c) -> Sym+c
1559 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001560 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001561 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001562 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001563 GA->getOffset() +
1564 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001565 // fold ((c1-A)+c2) -> (c1+c2)-A
1566 if (N1C && N0.getOpcode() == ISD::SUB)
1567 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001568 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001569 DAG.getConstant(N1C->getAPIntValue()+
1570 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001571 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001572 // reassociate add
Andrew Trickef9de2a2013-05-25 02:42:55 +00001573 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001574 if (RADD.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001575 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001576 // fold ((0-A) + B) -> B-A
1577 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1578 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001579 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001580 // fold (A + (0-B)) -> A-B
1581 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1582 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001583 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001584 // fold (A+(B-A)) -> B
1585 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001586 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001587 // fold ((B-A)+A) -> B
1588 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1589 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001590 // fold (A+(B-(A+C))) to (B-C)
1591 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001592 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001593 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001594 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001595 // fold (A+(B-(C+A))) to (B-C)
1596 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001597 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001598 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001599 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001600 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001601 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1602 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001603 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001604 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001605 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001606
Dale Johannesen8c766702008-12-02 01:30:54 +00001607 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1608 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1609 SDValue N00 = N0.getOperand(0);
1610 SDValue N01 = N0.getOperand(1);
1611 SDValue N10 = N1.getOperand(0);
1612 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001613
1614 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001615 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1616 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1617 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001618 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001619
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001620 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1621 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001622
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001623 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001624 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001625 APInt LHSZero, LHSOne;
1626 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001627 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001628
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001629 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001630 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001631
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001632 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1633 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001634 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1635 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1636 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1637 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001638 }
1639 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001640
Dan Gohman954f4902010-01-19 23:30:49 +00001641 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1642 if (N1.getOpcode() == ISD::SHL &&
1643 N1.getOperand(0).getOpcode() == ISD::SUB)
1644 if (ConstantSDNode *C =
1645 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1646 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001647 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1648 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001649 N1.getOperand(0).getOperand(1),
1650 N1.getOperand(1)));
1651 if (N0.getOpcode() == ISD::SHL &&
1652 N0.getOperand(0).getOpcode() == ISD::SUB)
1653 if (ConstantSDNode *C =
1654 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1655 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001656 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1657 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001658 N0.getOperand(0).getOperand(1),
1659 N0.getOperand(1)));
1660
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001661 if (N1.getOpcode() == ISD::AND) {
1662 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001663 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001664 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1665 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001666
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001667 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1668 // and similar xforms where the inner op is either ~0 or 0.
1669 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001670 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001671 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1672 }
1673 }
1674
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001675 // add (sext i1), X -> sub X, (zext i1)
1676 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1677 N0.getOperand(0).getValueType() == MVT::i1 &&
1678 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001679 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001680 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1681 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1682 }
1683
Evan Chengf1005572010-04-28 07:10:39 +00001684 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001685}
1686
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001687SDValue DAGCombiner::visitADDC(SDNode *N) {
1688 SDValue N0 = N->getOperand(0);
1689 SDValue N1 = N->getOperand(1);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001690 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1691 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001692 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001693
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001694 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001695 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001696 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001697 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001698 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001699
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001700 // canonicalize constant to RHS.
Dan Gohmanb4e26372008-06-23 15:29:14 +00001701 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001702 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001703
Chris Lattner47206662007-03-04 20:40:38 +00001704 // fold (addc x, 0) -> x + no carry out
1705 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001706 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001707 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001708
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001709 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001710 APInt LHSZero, LHSOne;
1711 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001712 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001713
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001714 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001715 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001716
Chris Lattner47206662007-03-04 20:40:38 +00001717 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1718 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001719 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001720 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001721 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001722 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001723 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001724
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001725 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001726}
1727
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001728SDValue DAGCombiner::visitADDE(SDNode *N) {
1729 SDValue N0 = N->getOperand(0);
1730 SDValue N1 = N->getOperand(1);
1731 SDValue CarryIn = N->getOperand(2);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001732 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1733 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001734
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001735 // canonicalize constant to RHS
Dan Gohmanb4e26372008-06-23 15:29:14 +00001736 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001737 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001738 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001739
Chris Lattner47206662007-03-04 20:40:38 +00001740 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001741 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001742 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001743
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001744 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001745}
1746
Eric Christophere5ca1e02011-02-16 04:50:12 +00001747// Since it may not be valid to emit a fold to zero for vector initializers
1748// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001749static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001750 SelectionDAG &DAG,
1751 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001752 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001753 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001754 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1755 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001756 return SDValue();
1757}
1758
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001759SDValue DAGCombiner::visitSUB(SDNode *N) {
1760 SDValue N0 = N->getOperand(0);
1761 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001762 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1763 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00001764 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
Eric Christopherd6300d22011-07-14 01:12:15 +00001765 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001766 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001767
Dan Gohmana8665142007-06-25 16:23:39 +00001768 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001769 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001770 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001771 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001772
1773 // fold (sub x, 0) -> x, vector edition
1774 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1775 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001776 }
Bill Wendling0864a752008-12-10 22:36:00 +00001777
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001778 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001779 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001780 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001781 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001782 // fold (sub c1, c2) -> c1-c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001783 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001784 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001785 // fold (sub x, c) -> (add x, -c)
1786 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001787 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001788 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001789 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1790 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001791 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001792 // fold A-(A-B) -> B
1793 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1794 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001795 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001796 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001797 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001798 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001799 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001800 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001801 // fold C2-(A+C1) -> (C2-C1)-A
1802 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001803 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1804 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001805 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001806 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001807 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001808 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001809 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001810 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1811 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001812 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001813 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001814 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001815 // fold ((A+(C+B))-B) -> A+C
1816 if (N0.getOpcode() == ISD::ADD &&
1817 N0.getOperand(1).getOpcode() == ISD::ADD &&
1818 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001819 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001820 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001821 // fold ((A-(B-C))-C) -> A-B
1822 if (N0.getOpcode() == ISD::SUB &&
1823 N0.getOperand(1).getOpcode() == ISD::SUB &&
1824 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001825 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001826 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001827
Dan Gohman06563a82007-07-03 14:03:57 +00001828 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001829 if (N0.getOpcode() == ISD::UNDEF)
1830 return N0;
1831 if (N1.getOpcode() == ISD::UNDEF)
1832 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001833
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001834 // If the relocation model supports it, consider symbol offsets.
1835 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001836 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001837 // fold (sub Sym, c) -> Sym-c
1838 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001839 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001840 GA->getOffset() -
1841 (uint64_t)N1C->getSExtValue());
1842 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1843 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1844 if (GA->getGlobal() == GB->getGlobal())
1845 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1846 VT);
1847 }
1848
Evan Chengf1005572010-04-28 07:10:39 +00001849 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001850}
1851
Craig Topper43a1bd62012-01-07 09:06:39 +00001852SDValue DAGCombiner::visitSUBC(SDNode *N) {
1853 SDValue N0 = N->getOperand(0);
1854 SDValue N1 = N->getOperand(1);
1855 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1856 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1857 EVT VT = N0.getValueType();
1858
1859 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001860 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001861 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1862 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001863 MVT::Glue));
1864
1865 // fold (subc x, x) -> 0 + no borrow
1866 if (N0 == N1)
1867 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001868 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001869 MVT::Glue));
1870
1871 // fold (subc x, 0) -> x + no borrow
1872 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001873 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001874 MVT::Glue));
1875
1876 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1877 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001878 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1879 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001880 MVT::Glue));
1881
1882 return SDValue();
1883}
1884
1885SDValue DAGCombiner::visitSUBE(SDNode *N) {
1886 SDValue N0 = N->getOperand(0);
1887 SDValue N1 = N->getOperand(1);
1888 SDValue CarryIn = N->getOperand(2);
1889
1890 // fold (sube x, y, false) -> (subc x, y)
1891 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001892 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001893
1894 return SDValue();
1895}
1896
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001897SDValue DAGCombiner::visitMUL(SDNode *N) {
1898 SDValue N0 = N->getOperand(0);
1899 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001900 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001901
Dan Gohman06563a82007-07-03 14:03:57 +00001902 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001903 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001904 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001905
1906 bool N0IsConst = false;
1907 bool N1IsConst = false;
1908 APInt ConstValue0, ConstValue1;
1909 // fold vector ops
1910 if (VT.isVector()) {
1911 SDValue FoldedVOp = SimplifyVBinOp(N);
1912 if (FoldedVOp.getNode()) return FoldedVOp;
1913
1914 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1915 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1916 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00001917 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001918 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1919 : APInt();
Craig Topperc0196b12014-04-14 00:51:57 +00001920 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001921 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1922 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001923 }
1924
Nate Begeman21158fc2005-09-01 00:19:25 +00001925 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001926 if (N0IsConst && N1IsConst)
1927 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1928
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001929 // canonicalize constant to RHS
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001930 if (N0IsConst && !N1IsConst)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001931 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001932 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001933 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00001934 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001935 // We require a splat of the entire scalar bit width for non-contiguous
1936 // bit patterns.
1937 bool IsFullSplat =
1938 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001939 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001940 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001941 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00001942 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001943 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001944 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001945 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001946 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001947 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001948 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001949 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00001950 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00001951 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001952 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001953 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001954 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00001955 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001956 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001957 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001958 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00001959 DAG.getConstant(Log2Val,
1960 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00001961 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001962
1963 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00001964 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00001965 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001966 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1967 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001968 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001969 N1, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001970 AddToWorklist(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001971 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001972 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00001973 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001974
Chris Lattner324871e2006-03-01 03:44:24 +00001975 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1976 // use.
1977 {
Craig Topperc0196b12014-04-14 00:51:57 +00001978 SDValue Sh(nullptr,0), Y(nullptr,0);
Chris Lattner324871e2006-03-01 03:44:24 +00001979 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00001980 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001981 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1982 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001983 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001984 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001985 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00001986 isa<ConstantSDNode>(N1.getOperand(1)) &&
1987 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001988 Sh = N1; Y = N0;
1989 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001990
Gabor Greiff304a7a2008-08-28 21:40:38 +00001991 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001992 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001993 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001994 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001995 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00001996 }
1997 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001998
Chris Lattnerf29f5202006-03-04 23:33:26 +00001999 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002000 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2001 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2002 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002003 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2004 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002005 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00002006 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002007 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00002008
Nate Begeman22e251a2006-02-03 06:46:56 +00002009 // reassociate mul
Andrew Trickef9de2a2013-05-25 02:42:55 +00002010 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002011 if (RMUL.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002012 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00002013
Evan Chengf1005572010-04-28 07:10:39 +00002014 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002015}
2016
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002017SDValue DAGCombiner::visitSDIV(SDNode *N) {
2018 SDValue N0 = N->getOperand(0);
2019 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002020 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2021 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002022 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002023
Dan Gohmana8665142007-06-25 16:23:39 +00002024 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002025 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002026 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002027 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002028 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002029
Nate Begeman21158fc2005-09-01 00:19:25 +00002030 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002031 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002032 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00002033 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00002034 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00002035 return N0;
2036 // fold (sdiv X, -1) -> 0-X
2037 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002038 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00002039 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00002040 // If we know the sign bits of both operands are zero, strength reduce to a
2041 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00002042 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002043 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002044 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00002045 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00002046 }
Benjamin Kramerad016872014-04-26 13:00:53 +00002047
Nate Begeman57b35672006-02-17 07:26:20 +00002048 // fold (sdiv X, pow2) -> simple ops after legalize
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002049 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2050 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00002051 // If dividing by powers of two is cheap, then don't perform the following
2052 // fold.
Sanjay Patel2cdea4c2014-08-21 22:31:48 +00002053 if (TLI.isPow2SDivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002054 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00002055
Chad Rosier17020f92014-07-23 14:57:52 +00002056 // Target-specific implementation of sdiv x, pow2.
2057 SDValue Res = BuildSDIVPow2(N);
2058 if (Res.getNode())
2059 return Res;
2060
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002061 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00002062
Chris Lattner471627c2006-02-16 08:02:36 +00002063 // Splat the sign bit into the register
Benjamin Kramerad016872014-04-26 13:00:53 +00002064 SDValue SGN =
2065 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2066 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2067 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002068 AddToWorklist(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002069
Chris Lattner471627c2006-02-16 08:02:36 +00002070 // Add (N0 < 0) ? abs2 - 1 : 0;
Benjamin Kramerad016872014-04-26 13:00:53 +00002071 SDValue SRL =
2072 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2073 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2074 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002075 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002076 AddToWorklist(SRL.getNode());
2077 AddToWorklist(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00002078 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002079 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002080
Nate Begeman4dd38312005-10-21 00:02:42 +00002081 // If we're dividing by a positive value, we're done. Otherwise, we must
2082 // negate the result.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002083 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002084 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002085
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002086 AddToWorklist(SRA.getNode());
Benjamin Kramerad016872014-04-26 13:00:53 +00002087 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002088 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002089
Nate Begemanc6f067a2005-10-20 02:15:44 +00002090 // if integer divide is expensive and we satisfy the requirements, emit an
2091 // alternate sequence.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002092 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002093 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002094 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002095 }
Dan Gohmana8665142007-06-25 16:23:39 +00002096
Dan Gohman06563a82007-07-03 14:03:57 +00002097 // undef / X -> 0
2098 if (N0.getOpcode() == ISD::UNDEF)
2099 return DAG.getConstant(0, VT);
2100 // X / undef -> undef
2101 if (N1.getOpcode() == ISD::UNDEF)
2102 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002103
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002104 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002105}
2106
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002107SDValue DAGCombiner::visitUDIV(SDNode *N) {
2108 SDValue N0 = N->getOperand(0);
2109 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002110 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2111 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002112 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002113
Dan Gohmana8665142007-06-25 16:23:39 +00002114 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002115 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002116 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002117 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002118 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002119
Nate Begeman21158fc2005-09-01 00:19:25 +00002120 // fold (udiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002121 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002122 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002123 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002124 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002125 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002126 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002127 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002128 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002129 if (N1.getOpcode() == ISD::SHL) {
2130 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002131 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002132 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002133 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002134 N1.getOperand(1),
2135 DAG.getConstant(SHC->getAPIntValue()
2136 .logBase2(),
2137 ADDVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002138 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002139 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002140 }
2141 }
2142 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002143 // fold (udiv x, c) -> alternate
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002144 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002145 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002146 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002147 }
Dan Gohmana8665142007-06-25 16:23:39 +00002148
Dan Gohman06563a82007-07-03 14:03:57 +00002149 // undef / X -> 0
2150 if (N0.getOpcode() == ISD::UNDEF)
2151 return DAG.getConstant(0, VT);
2152 // X / undef -> undef
2153 if (N1.getOpcode() == ISD::UNDEF)
2154 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002155
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002156 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002157}
2158
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002159SDValue DAGCombiner::visitSREM(SDNode *N) {
2160 SDValue N0 = N->getOperand(0);
2161 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002162 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2163 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002164 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002165
Nate Begeman21158fc2005-09-01 00:19:25 +00002166 // fold (srem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002167 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002168 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002169 // If we know the sign bits of both operands are zero, strength reduce to a
2170 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002171 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002172 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002173 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002174 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002175
Dan Gohman9a693412007-11-26 23:46:11 +00002176 // If X/C can be simplified by the division-by-constant logic, lower
2177 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002178 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002179 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002180 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002181 SDValue OptimizedDiv = combine(Div.getNode());
2182 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002183 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002184 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002185 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002186 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002187 return Sub;
2188 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002189 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002190
Dan Gohman06563a82007-07-03 14:03:57 +00002191 // undef % X -> 0
2192 if (N0.getOpcode() == ISD::UNDEF)
2193 return DAG.getConstant(0, VT);
2194 // X % undef -> undef
2195 if (N1.getOpcode() == ISD::UNDEF)
2196 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002197
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002198 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002199}
2200
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002201SDValue DAGCombiner::visitUREM(SDNode *N) {
2202 SDValue N0 = N->getOperand(0);
2203 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002204 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2205 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002206 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002207
Nate Begeman21158fc2005-09-01 00:19:25 +00002208 // fold (urem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002209 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002210 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002211 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002212 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002213 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002214 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002215 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2216 if (N1.getOpcode() == ISD::SHL) {
2217 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002218 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002219 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002220 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002221 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002222 VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002223 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002224 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002225 }
2226 }
2227 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002228
Dan Gohman9a693412007-11-26 23:46:11 +00002229 // If X/C can be simplified by the division-by-constant logic, lower
2230 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002231 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002232 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002233 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002234 SDValue OptimizedDiv = combine(Div.getNode());
2235 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002236 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002237 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002238 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002239 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002240 return Sub;
2241 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002242 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002243
Dan Gohman06563a82007-07-03 14:03:57 +00002244 // undef % X -> 0
2245 if (N0.getOpcode() == ISD::UNDEF)
2246 return DAG.getConstant(0, VT);
2247 // X % undef -> undef
2248 if (N1.getOpcode() == ISD::UNDEF)
2249 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002250
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002251 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002252}
2253
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002254SDValue DAGCombiner::visitMULHS(SDNode *N) {
2255 SDValue N0 = N->getOperand(0);
2256 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002257 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002258 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002259 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002260
Nate Begeman21158fc2005-09-01 00:19:25 +00002261 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002262 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002263 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002264 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002265 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002266 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002267 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002268 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002269 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002270 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002271 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002272
Chris Lattner10bd29f2010-12-13 08:39:01 +00002273 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2274 // plus a shift.
2275 if (VT.isSimple() && !VT.isVector()) {
2276 MVT Simple = VT.getSimpleVT();
2277 unsigned SimpleSize = Simple.getSizeInBits();
2278 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2279 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2280 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2281 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2282 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002283 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002284 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002285 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2286 }
2287 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002288
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002289 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002290}
2291
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002292SDValue DAGCombiner::visitMULHU(SDNode *N) {
2293 SDValue N0 = N->getOperand(0);
2294 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002295 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002296 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002297 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002298
Nate Begeman21158fc2005-09-01 00:19:25 +00002299 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002300 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002301 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002302 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002303 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002304 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002305 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002306 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002307 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002308
Chris Lattner10bd29f2010-12-13 08:39:01 +00002309 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2310 // plus a shift.
2311 if (VT.isSimple() && !VT.isVector()) {
2312 MVT Simple = VT.getSimpleVT();
2313 unsigned SimpleSize = Simple.getSizeInBits();
2314 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2315 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2316 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2317 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2318 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2319 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002320 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002321 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2322 }
2323 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002324
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002325 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002326}
2327
Sanjay Patel50cbfc52014-08-28 16:29:51 +00002328/// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2329/// give the opcodes for the two computations that are being performed. Return
2330/// true if a simplification was made.
Scott Michelcf0da6c2009-02-17 22:15:04 +00002331SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002332 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002333 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002334 bool HiExists = N->hasAnyUseOfValue(1);
2335 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002336 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002337 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Craig Toppere1d12942014-08-27 05:25:25 +00002338 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002339 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002340 }
2341
2342 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002343 bool LoExists = N->hasAnyUseOfValue(0);
2344 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002345 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002346 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Craig Toppere1d12942014-08-27 05:25:25 +00002347 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002348 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002349 }
2350
Evan Chengece4c682007-11-08 09:25:29 +00002351 // If both halves are used, return as it is.
2352 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002353 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002354
2355 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002356 if (LoExists) {
Craig Toppere1d12942014-08-27 05:25:25 +00002357 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002358 AddToWorklist(Lo.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002359 SDValue LoOpt = combine(Lo.getNode());
2360 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002361 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002362 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002363 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002364 }
2365
Evan Chengece4c682007-11-08 09:25:29 +00002366 if (HiExists) {
Craig Toppere1d12942014-08-27 05:25:25 +00002367 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002368 AddToWorklist(Hi.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002369 SDValue HiOpt = combine(Hi.getNode());
2370 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002371 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002372 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002373 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002374 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002375
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002376 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002377}
2378
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002379SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2380 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002381 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002382
Chris Lattner15090e12010-12-15 06:04:19 +00002383 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002384 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002385
2386 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2387 // plus a shift.
2388 if (VT.isSimple() && !VT.isVector()) {
2389 MVT Simple = VT.getSimpleVT();
2390 unsigned SimpleSize = Simple.getSizeInBits();
2391 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2392 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2393 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2394 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2395 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2396 // Compute the high part as N1.
2397 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002398 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002399 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2400 // Compute the low part as N0.
2401 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2402 return CombineTo(N, Lo, Hi);
2403 }
2404 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002405
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002406 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002407}
2408
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002409SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2410 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002411 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002412
Chris Lattner15090e12010-12-15 06:04:19 +00002413 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002414 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002415
Chris Lattner15090e12010-12-15 06:04:19 +00002416 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2417 // plus a shift.
2418 if (VT.isSimple() && !VT.isVector()) {
2419 MVT Simple = VT.getSimpleVT();
2420 unsigned SimpleSize = Simple.getSizeInBits();
2421 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2422 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2423 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2424 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2425 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2426 // Compute the high part as N1.
2427 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002428 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002429 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2430 // Compute the low part as N0.
2431 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2432 return CombineTo(N, Lo, Hi);
2433 }
2434 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002435
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002436 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002437}
2438
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002439SDValue DAGCombiner::visitSMULO(SDNode *N) {
2440 // (smulo x, 2) -> (saddo x, x)
2441 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2442 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002443 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002444 N->getOperand(0), N->getOperand(0));
2445
2446 return SDValue();
2447}
2448
2449SDValue DAGCombiner::visitUMULO(SDNode *N) {
2450 // (umulo x, 2) -> (uaddo x, x)
2451 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2452 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002453 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002454 N->getOperand(0), N->getOperand(0));
2455
2456 return SDValue();
2457}
2458
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002459SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2460 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002461 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002462
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002463 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002464}
2465
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002466SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2467 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002468 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002469
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002470 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002471}
2472
Sanjay Patel50cbfc52014-08-28 16:29:51 +00002473/// If this is a binary operator with two operands of the same opcode, try to
2474/// simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002475SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2476 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002477 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002478 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002479
Dan Gohmandd5286d2010-01-14 03:08:49 +00002480 // Bail early if none of these transforms apply.
2481 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2482
Chris Lattner002ee912006-05-05 06:31:05 +00002483 // For each of OP in AND/OR/XOR:
2484 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2485 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2486 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002487 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002488 //
2489 // do not sink logical op inside of a vector extend, since it may combine
2490 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002491 EVT Op0VT = N0.getOperand(0).getValueType();
2492 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002493 N0.getOpcode() == ISD::SIGN_EXTEND ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002494 // Avoid infinite looping with PromoteIntBinOp.
2495 (N0.getOpcode() == ISD::ANY_EXTEND &&
2496 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002497 (N0.getOpcode() == ISD::TRUNCATE &&
2498 (!TLI.isZExtFree(VT, Op0VT) ||
2499 !TLI.isTruncateFree(Op0VT, VT)) &&
2500 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002501 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002502 Op0VT == N1.getOperand(0).getValueType() &&
2503 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002504 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002505 N0.getOperand(0).getValueType(),
2506 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002507 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002508 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002509 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002510
Chris Lattner5ac42932006-05-05 06:10:43 +00002511 // For each of OP in SHL/SRL/SRA/AND...
2512 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2513 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2514 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002515 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002516 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002517 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002518 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002519 N0.getOperand(0).getValueType(),
2520 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002521 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002522 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002523 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002524 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002525
Nadav Rotemb0783502012-04-01 19:31:22 +00002526 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2527 // Only perform this optimization after type legalization and before
2528 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2529 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2530 // we don't want to undo this promotion.
2531 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2532 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002533 if ((N0.getOpcode() == ISD::BITCAST ||
2534 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2535 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002536 SDValue In0 = N0.getOperand(0);
2537 SDValue In1 = N1.getOperand(0);
2538 EVT In0Ty = In0.getValueType();
2539 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002540 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002541 // If both incoming values are integers, and the original types are the
2542 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002543 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002544 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2545 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002546 AddToWorklist(Op.getNode());
Nadav Rotemb0783502012-04-01 19:31:22 +00002547 return BC;
2548 }
2549 }
2550
2551 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2552 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2553 // If both shuffles use the same mask, and both shuffle within a single
2554 // vector, then it is worthwhile to move the swizzle after the operation.
2555 // The type-legalizer generates this pattern when loading illegal
2556 // vector types from memory. In many cases this allows additional shuffle
2557 // optimizations.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002558 // There are other cases where moving the shuffle after the xor/and/or
2559 // is profitable even if shuffles don't perform a swizzle.
2560 // If both shuffles use the same mask, and both shuffles have the same first
2561 // or second operand, then it might still be profitable to move the shuffle
2562 // after the xor/and/or operation.
2563 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002564 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2565 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002566
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002567 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
Craig Topper9c3da312012-04-09 07:19:09 +00002568 "Inputs to shuffles are not the same type");
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00002569
Nadav Rotemb0783502012-04-01 19:31:22 +00002570 // Check that both shuffles use the same mask. The masks are known to be of
2571 // the same length because the result vector type is the same.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002572 // Check also that shuffles have only one use to avoid introducing extra
2573 // instructions.
2574 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2575 SVN0->getMask().equals(SVN1->getMask())) {
2576 SDValue ShOp = N0->getOperand(1);
Nadav Rotemb0783502012-04-01 19:31:22 +00002577
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002578 // Don't try to fold this node if it requires introducing a
2579 // build vector of all zeros that might be illegal at this stage.
2580 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2581 if (!LegalTypes)
2582 ShOp = DAG.getConstant(0, VT);
2583 else
2584 ShOp = SDValue();
2585 }
2586
2587 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2588 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2589 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2590 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2591 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2592 N0->getOperand(0), N1->getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002593 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002594 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2595 &SVN0->getMask()[0]);
2596 }
2597
2598 // Don't try to fold this node if it requires introducing a
2599 // build vector of all zeros that might be illegal at this stage.
2600 ShOp = N0->getOperand(0);
2601 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2602 if (!LegalTypes)
2603 ShOp = DAG.getConstant(0, VT);
2604 else
2605 ShOp = SDValue();
2606 }
2607
2608 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2609 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2610 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2611 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2612 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2613 N0->getOperand(1), N1->getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002614 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002615 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2616 &SVN0->getMask()[0]);
2617 }
Nadav Rotemb0783502012-04-01 19:31:22 +00002618 }
2619 }
Craig Topper9c3da312012-04-09 07:19:09 +00002620
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002621 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002622}
2623
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002624SDValue DAGCombiner::visitAND(SDNode *N) {
2625 SDValue N0 = N->getOperand(0);
2626 SDValue N1 = N->getOperand(1);
2627 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002628 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2629 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002630 EVT VT = N1.getValueType();
Dan Gohmane14c4082010-03-04 00:23:16 +00002631 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002632
Dan Gohmana8665142007-06-25 16:23:39 +00002633 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002634 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002635 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002636 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002637
2638 // fold (and x, 0) -> 0, vector edition
2639 if (ISD::isBuildVectorAllZeros(N0.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00002640 // do not return N0, because undef node may exist in N0
2641 return DAG.getConstant(
2642 APInt::getNullValue(
2643 N0.getValueType().getScalarType().getSizeInBits()),
2644 N0.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00002645 if (ISD::isBuildVectorAllZeros(N1.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00002646 // do not return N1, because undef node may exist in N1
2647 return DAG.getConstant(
2648 APInt::getNullValue(
2649 N1.getValueType().getScalarType().getSizeInBits()),
2650 N1.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00002651
2652 // fold (and x, -1) -> x, vector edition
2653 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2654 return N1;
2655 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2656 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002657 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002658
Dan Gohman06563a82007-07-03 14:03:57 +00002659 // fold (and x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002660 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002661 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00002662 // fold (and c1, c2) -> c1&c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002663 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002664 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002665 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00002666 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002667 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002668 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002669 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002670 return N0;
2671 // if (and x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002672 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002673 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002674 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002675 // reassociate and
Andrew Trickef9de2a2013-05-25 02:42:55 +00002676 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002677 if (RAND.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002678 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002679 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002680 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002681 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002682 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002683 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002684 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2685 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002686 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002687 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002688 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002689 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002690 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002691 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002692
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002693 // Replace uses of the AND with uses of the Zero extend node.
2694 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002695
Chris Lattner49beaf42006-02-02 07:17:31 +00002696 // We actually want to replace all uses of the any_extend with the
2697 // zero_extend, to avoid duplicating things. This will later cause this
2698 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002699 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002700 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002701 }
2702 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002703 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002704 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2705 // already be zero by virtue of the width of the base type of the load.
2706 //
2707 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2708 // more cases.
2709 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2710 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2711 N0.getOpcode() == ISD::LOAD) {
2712 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2713 N0 : N0.getOperand(0) );
2714
2715 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2716 // This can be a pure constant or a vector splat, in which case we treat the
2717 // vector as a scalar and use the splat value.
2718 APInt Constant = APInt::getNullValue(1);
2719 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2720 Constant = C->getAPIntValue();
2721 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2722 APInt SplatValue, SplatUndef;
2723 unsigned SplatBitSize;
2724 bool HasAnyUndefs;
2725 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2726 SplatBitSize, HasAnyUndefs);
2727 if (IsSplat) {
2728 // Undef bits can contribute to a possible optimisation if set, so
2729 // set them.
2730 SplatValue |= SplatUndef;
2731
2732 // The splat value may be something like "0x00FFFFFF", which means 0 for
2733 // the first vector value and FF for the rest, repeating. We need a mask
2734 // that will apply equally to all members of the vector, so AND all the
2735 // lanes of the constant together.
2736 EVT VT = Vector->getValueType(0);
2737 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002738
2739 // If the splat value has been compressed to a bitlength lower
2740 // than the size of the vector lane, we need to re-expand it to
2741 // the lane size.
2742 if (BitWidth > SplatBitSize)
2743 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2744 SplatBitSize < BitWidth;
2745 SplatBitSize = SplatBitSize * 2)
2746 SplatValue |= SplatValue.shl(SplatBitSize);
2747
James Molloy862fe492012-02-20 12:02:38 +00002748 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3f40d872012-09-05 08:57:21 +00002749 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy862fe492012-02-20 12:02:38 +00002750 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2751 }
2752 }
2753
2754 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2755 // actually legal and isn't going to get expanded, else this is a false
2756 // optimisation.
2757 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2758 Load->getMemoryVT());
2759
2760 // Resize the constant to the same size as the original memory access before
2761 // extension. If it is still the AllOnesValue then this AND is completely
2762 // unneeded.
2763 Constant =
2764 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2765
2766 bool B;
2767 switch (Load->getExtensionType()) {
2768 default: B = false; break;
2769 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2770 case ISD::ZEXTLOAD:
2771 case ISD::NON_EXTLOAD: B = true; break;
2772 }
2773
2774 if (B && Constant.isAllOnesValue()) {
2775 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2776 // preserve semantics once we get rid of the AND.
2777 SDValue NewLoad(Load, 0);
2778 if (Load->getExtensionType() == ISD::EXTLOAD) {
2779 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002780 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002781 Load->getChain(), Load->getBasePtr(),
2782 Load->getOffset(), Load->getMemoryVT(),
2783 Load->getMemOperand());
2784 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002785 if (Load->getNumValues() == 3) {
2786 // PRE/POST_INC loads have 3 values.
2787 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2788 NewLoad.getValue(2) };
2789 CombineTo(Load, To, 3, true);
2790 } else {
2791 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2792 }
James Molloy862fe492012-02-20 12:02:38 +00002793 }
2794
2795 // Fold the AND away, taking care not to fold to the old load node if we
2796 // replaced it.
2797 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2798
2799 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2800 }
2801 }
Nate Begeman049b7482005-09-09 19:49:52 +00002802 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2803 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2804 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2805 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002806
Tom Stellard7783b0a2014-06-12 16:04:47 +00002807 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002808 LL.getValueType().isInteger()) {
Bill Wendling86171912009-01-30 20:43:18 +00002809 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002810 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002811 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002812 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002813 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002814 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002815 }
Bill Wendling86171912009-01-30 20:43:18 +00002816 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002817 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002818 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002819 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002820 AddToWorklist(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002821 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002822 }
Bill Wendling86171912009-01-30 20:43:18 +00002823 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002824 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002825 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002826 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002827 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002828 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002829 }
2830 }
Jim Grosbach327ccc72013-08-13 21:30:58 +00002831 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2832 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2833 Op0 == Op1 && LL.getValueType().isInteger() &&
2834 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2835 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2836 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2837 cast<ConstantSDNode>(RR)->isNullValue()))) {
2838 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2839 LL, DAG.getConstant(1, LL.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002840 AddToWorklist(ADDNode.getNode());
Jim Grosbach327ccc72013-08-13 21:30:58 +00002841 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2842 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2843 }
Nate Begeman049b7482005-09-09 19:49:52 +00002844 // canonicalize equivalent to ll == rl
2845 if (LL == RR && LR == RL) {
2846 Op1 = ISD::getSetCCSwappedOperands(Op1);
2847 std::swap(RL, RR);
2848 }
2849 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00002850 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00002851 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00002852 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002853 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00002854 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2855 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00002856 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002857 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling86171912009-01-30 20:43:18 +00002858 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00002859 }
2860 }
Chris Lattner8d6fc202006-05-05 05:51:50 +00002861
Bill Wendling86171912009-01-30 20:43:18 +00002862 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00002863 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002864 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002865 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00002866 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002867
Nate Begemandc7bba92006-02-03 22:24:05 +00002868 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2869 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands13237ac2008-06-06 12:08:01 +00002870 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002871 SimplifyDemandedBits(SDValue(N, 0)))
2872 return SDValue(N, 0);
Evan Cheng166a4e62010-01-06 19:38:29 +00002873
Nate Begeman02b23c62005-10-13 03:11:28 +00002874 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greiff304a7a2008-08-28 21:40:38 +00002875 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002876 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002877 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002878 // If we zero all the possible extended bits, then we can turn this into
2879 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002880 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002881 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002882 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002883 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002884 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002885 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling86171912009-01-30 20:43:18 +00002886 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002887 MemVT, LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002888 AddToWorklist(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002889 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002890 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002891 }
2892 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002893 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00002894 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00002895 N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002896 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002897 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002898 // If we zero all the possible extended bits, then we can turn this into
2899 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002900 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002901 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002902 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002903 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002904 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002905 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002906 LN0->getChain(), LN0->getBasePtr(),
2907 MemVT, LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002908 AddToWorklist(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002909 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002910 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002911 }
2912 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002913
Chris Lattnerf0032b32006-02-28 06:49:37 +00002914 // fold (and (load x), 255) -> (zextload x, i8)
2915 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002916 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2917 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2918 (N0.getOpcode() == ISD::ANY_EXTEND &&
2919 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2920 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2921 LoadSDNode *LN0 = HasAnyExt
2922 ? cast<LoadSDNode>(N0.getOperand(0))
2923 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002924 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002925 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002926 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002927 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2928 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2929 EVT LoadedVT = LN0->getMemoryVT();
Duncan Sands93b66092008-06-09 11:32:28 +00002930
Evan Cheng166a4e62010-01-06 19:38:29 +00002931 if (ExtVT == LoadedVT &&
2932 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00002933 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Wesley Peck527da1b2010-11-23 03:31:01 +00002934
2935 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002936 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002937 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2938 LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002939 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00002940 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2941 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2942 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002943
Chris Lattner88de3842010-01-07 21:53:27 +00002944 // Do not change the width of a volatile load.
2945 // Do not generate loads of non-round integer types since these can
2946 // be expensive (and would be wrong if the type is not byte sized).
2947 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2948 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2949 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00002950
Chris Lattner88de3842010-01-07 21:53:27 +00002951 unsigned Alignment = LN0->getAlignment();
2952 SDValue NewPtr = LN0->getBasePtr();
2953
2954 // For big endian targets, we need to add an offset to the pointer
2955 // to load the correct bytes. For little endian systems, we merely
2956 // need to read fewer bytes from the same pointer.
2957 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00002958 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2959 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2960 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002961 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00002962 NewPtr, DAG.getConstant(PtrOff, PtrType));
2963 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00002964 }
Chris Lattner88de3842010-01-07 21:53:27 +00002965
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002966 AddToWorklist(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00002967
Chris Lattner88de3842010-01-07 21:53:27 +00002968 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2969 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002970 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00002971 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00002972 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00002973 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00002974 LN0->isInvariant(), Alignment, LN0->getAAInfo());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002975 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00002976 CombineTo(LN0, Load, Load.getValue(1));
2977 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00002978 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00002979 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00002980 }
2981 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002982
Evan Chenge6a3b032012-07-17 18:54:11 +00002983 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2984 VT.getSizeInBits() <= 64) {
2985 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2986 APInt ADDC = ADDI->getAPIntValue();
2987 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2988 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2989 // immediate for an add, but it is legal if its top c2 bits are set,
2990 // transform the ADD so the immediate doesn't need to be materialized
2991 // in a register.
2992 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2993 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2994 SRLI->getZExtValue());
2995 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2996 ADDC |= Mask;
2997 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2998 SDValue NewAdd =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002999 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenge6a3b032012-07-17 18:54:11 +00003000 N0.getOperand(0), DAG.getConstant(ADDC, VT));
3001 CombineTo(N0.getNode(), NewAdd);
3002 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3003 }
3004 }
3005 }
3006 }
3007 }
3008 }
Evan Chenge6a3b032012-07-17 18:54:11 +00003009
Tim Northover819bfb52013-08-27 13:46:45 +00003010 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3011 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3012 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3013 N0.getOperand(1), false);
3014 if (BSwap.getNode())
3015 return BSwap;
3016 }
3017
Evan Chengf1005572010-04-28 07:10:39 +00003018 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003019}
3020
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003021/// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003022SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3023 bool DemandHighBits) {
3024 if (!LegalOperations)
3025 return SDValue();
3026
3027 EVT VT = N->getValueType(0);
3028 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3029 return SDValue();
3030 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3031 return SDValue();
3032
3033 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3034 bool LookPassAnd0 = false;
3035 bool LookPassAnd1 = false;
3036 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3037 std::swap(N0, N1);
3038 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3039 std::swap(N0, N1);
3040 if (N0.getOpcode() == ISD::AND) {
3041 if (!N0.getNode()->hasOneUse())
3042 return SDValue();
3043 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3044 if (!N01C || N01C->getZExtValue() != 0xFF00)
3045 return SDValue();
3046 N0 = N0.getOperand(0);
3047 LookPassAnd0 = true;
3048 }
3049
3050 if (N1.getOpcode() == ISD::AND) {
3051 if (!N1.getNode()->hasOneUse())
3052 return SDValue();
3053 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3054 if (!N11C || N11C->getZExtValue() != 0xFF)
3055 return SDValue();
3056 N1 = N1.getOperand(0);
3057 LookPassAnd1 = true;
3058 }
3059
3060 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3061 std::swap(N0, N1);
3062 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3063 return SDValue();
3064 if (!N0.getNode()->hasOneUse() ||
3065 !N1.getNode()->hasOneUse())
3066 return SDValue();
3067
3068 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3069 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3070 if (!N01C || !N11C)
3071 return SDValue();
3072 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3073 return SDValue();
3074
3075 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3076 SDValue N00 = N0->getOperand(0);
3077 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3078 if (!N00.getNode()->hasOneUse())
3079 return SDValue();
3080 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3081 if (!N001C || N001C->getZExtValue() != 0xFF)
3082 return SDValue();
3083 N00 = N00.getOperand(0);
3084 LookPassAnd0 = true;
3085 }
3086
3087 SDValue N10 = N1->getOperand(0);
3088 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3089 if (!N10.getNode()->hasOneUse())
3090 return SDValue();
3091 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3092 if (!N101C || N101C->getZExtValue() != 0xFF00)
3093 return SDValue();
3094 N10 = N10.getOperand(0);
3095 LookPassAnd1 = true;
3096 }
3097
3098 if (N00 != N10)
3099 return SDValue();
3100
Tim Northover819bfb52013-08-27 13:46:45 +00003101 // Make sure everything beyond the low halfword gets set to zero since the SRL
3102 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003103 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003104 if (DemandHighBits && OpSizeInBits > 16) {
3105 // If the left-shift isn't masked out then the only way this is a bswap is
3106 // if all bits beyond the low 8 are 0. In that case the entire pattern
3107 // reduces to a left shift anyway: leave it for other parts of the combiner.
3108 if (!LookPassAnd0)
3109 return SDValue();
3110
3111 // However, if the right shift isn't masked out then it might be because
3112 // it's not needed. See if we can spot that too.
3113 if (!LookPassAnd1 &&
3114 !DAG.MaskedValueIsZero(
3115 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3116 return SDValue();
3117 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003118
Andrew Trickef9de2a2013-05-25 02:42:55 +00003119 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003120 if (OpSizeInBits > 16)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003121 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003122 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3123 return Res;
3124}
3125
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003126/// Return true if the specified node is an element that makes up a 32-bit
3127/// packed halfword byteswap.
3128/// ((x & 0x000000ff) << 8) |
3129/// ((x & 0x0000ff00) >> 8) |
3130/// ((x & 0x00ff0000) << 8) |
3131/// ((x & 0xff000000) >> 8)
Craig Topperb94011f2013-07-14 04:42:23 +00003132static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003133 if (!N.getNode()->hasOneUse())
3134 return false;
3135
3136 unsigned Opc = N.getOpcode();
3137 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3138 return false;
3139
3140 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3141 if (!N1C)
3142 return false;
3143
3144 unsigned Num;
3145 switch (N1C->getZExtValue()) {
3146 default:
3147 return false;
3148 case 0xFF: Num = 0; break;
3149 case 0xFF00: Num = 1; break;
3150 case 0xFF0000: Num = 2; break;
3151 case 0xFF000000: Num = 3; break;
3152 }
3153
3154 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3155 SDValue N0 = N.getOperand(0);
3156 if (Opc == ISD::AND) {
3157 if (Num == 0 || Num == 2) {
3158 // (x >> 8) & 0xff
3159 // (x >> 8) & 0xff0000
3160 if (N0.getOpcode() != ISD::SRL)
3161 return false;
3162 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3163 if (!C || C->getZExtValue() != 8)
3164 return false;
3165 } else {
3166 // (x << 8) & 0xff00
3167 // (x << 8) & 0xff000000
3168 if (N0.getOpcode() != ISD::SHL)
3169 return false;
3170 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3171 if (!C || C->getZExtValue() != 8)
3172 return false;
3173 }
3174 } else if (Opc == ISD::SHL) {
3175 // (x & 0xff) << 8
3176 // (x & 0xff0000) << 8
3177 if (Num != 0 && Num != 2)
3178 return false;
3179 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3180 if (!C || C->getZExtValue() != 8)
3181 return false;
3182 } else { // Opc == ISD::SRL
3183 // (x & 0xff00) >> 8
3184 // (x & 0xff000000) >> 8
3185 if (Num != 1 && Num != 3)
3186 return false;
3187 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3188 if (!C || C->getZExtValue() != 8)
3189 return false;
3190 }
3191
3192 if (Parts[Num])
3193 return false;
3194
3195 Parts[Num] = N0.getOperand(0).getNode();
3196 return true;
3197}
3198
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003199/// Match a 32-bit packed halfword bswap. That is
3200/// ((x & 0x000000ff) << 8) |
3201/// ((x & 0x0000ff00) >> 8) |
3202/// ((x & 0x00ff0000) << 8) |
3203/// ((x & 0xff000000) >> 8)
Evan Cheng4c0bd962011-06-21 06:01:08 +00003204/// => (rotl (bswap x), 16)
3205SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3206 if (!LegalOperations)
3207 return SDValue();
3208
3209 EVT VT = N->getValueType(0);
3210 if (VT != MVT::i32)
3211 return SDValue();
3212 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3213 return SDValue();
3214
Craig Topperc0196b12014-04-14 00:51:57 +00003215 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003216 // Look for either
3217 // (or (or (and), (and)), (or (and), (and)))
3218 // (or (or (or (and), (and)), (and)), (and))
3219 if (N0.getOpcode() != ISD::OR)
3220 return SDValue();
3221 SDValue N00 = N0.getOperand(0);
3222 SDValue N01 = N0.getOperand(1);
3223
Evan Chengbf0baa92012-12-13 01:34:32 +00003224 if (N1.getOpcode() == ISD::OR &&
3225 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003226 // (or (or (and), (and)), (or (and), (and)))
3227 SDValue N000 = N00.getOperand(0);
3228 if (!isBSwapHWordElement(N000, Parts))
3229 return SDValue();
3230
3231 SDValue N001 = N00.getOperand(1);
3232 if (!isBSwapHWordElement(N001, Parts))
3233 return SDValue();
3234 SDValue N010 = N01.getOperand(0);
3235 if (!isBSwapHWordElement(N010, Parts))
3236 return SDValue();
3237 SDValue N011 = N01.getOperand(1);
3238 if (!isBSwapHWordElement(N011, Parts))
3239 return SDValue();
3240 } else {
3241 // (or (or (or (and), (and)), (and)), (and))
3242 if (!isBSwapHWordElement(N1, Parts))
3243 return SDValue();
3244 if (!isBSwapHWordElement(N01, Parts))
3245 return SDValue();
3246 if (N00.getOpcode() != ISD::OR)
3247 return SDValue();
3248 SDValue N000 = N00.getOperand(0);
3249 if (!isBSwapHWordElement(N000, Parts))
3250 return SDValue();
3251 SDValue N001 = N00.getOperand(1);
3252 if (!isBSwapHWordElement(N001, Parts))
3253 return SDValue();
3254 }
3255
3256 // Make sure the parts are all coming from the same node.
3257 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3258 return SDValue();
3259
Andrew Trickef9de2a2013-05-25 02:42:55 +00003260 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003261 SDValue(Parts[0],0));
3262
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003263 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003264 // do (x << 16) | (x >> 16).
3265 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3266 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003267 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003268 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003269 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3270 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3271 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3272 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003273}
3274
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003275SDValue DAGCombiner::visitOR(SDNode *N) {
3276 SDValue N0 = N->getOperand(0);
3277 SDValue N1 = N->getOperand(1);
3278 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003279 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3280 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003281 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003282
Dan Gohmana8665142007-06-25 16:23:39 +00003283 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003284 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003285 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003286 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003287
3288 // fold (or x, 0) -> x, vector edition
3289 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3290 return N1;
3291 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3292 return N0;
3293
3294 // fold (or x, -1) -> -1, vector edition
3295 if (ISD::isBuildVectorAllOnes(N0.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00003296 // do not return N0, because undef node may exist in N0
3297 return DAG.getConstant(
3298 APInt::getAllOnesValue(
3299 N0.getValueType().getScalarType().getSizeInBits()),
3300 N0.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00003301 if (ISD::isBuildVectorAllOnes(N1.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00003302 // do not return N1, because undef node may exist in N1
3303 return DAG.getConstant(
3304 APInt::getAllOnesValue(
3305 N1.getValueType().getScalarType().getSizeInBits()),
3306 N1.getValueType());
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003307
3308 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3309 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3310 // Do this only if the resulting shuffle is legal.
3311 if (isa<ShuffleVectorSDNode>(N0) &&
3312 isa<ShuffleVectorSDNode>(N1) &&
Andrea Di Biagio2152a6c2014-07-15 00:02:32 +00003313 // Avoid folding a node with illegal type.
3314 TLI.isTypeLegal(VT) &&
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003315 N0->getOperand(1) == N1->getOperand(1) &&
3316 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3317 bool CanFold = true;
3318 unsigned NumElts = VT.getVectorNumElements();
3319 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3320 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3321 // We construct two shuffle masks:
3322 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3323 // and N1 as the second operand.
3324 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3325 // and N0 as the second operand.
3326 // We do this because OR is commutable and therefore there might be
3327 // two ways to fold this node into a shuffle.
3328 SmallVector<int,4> Mask1;
3329 SmallVector<int,4> Mask2;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003330
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003331 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3332 int M0 = SV0->getMaskElt(i);
3333 int M1 = SV1->getMaskElt(i);
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003334
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003335 // Both shuffle indexes are undef. Propagate Undef.
3336 if (M0 < 0 && M1 < 0) {
3337 Mask1.push_back(M0);
3338 Mask2.push_back(M0);
3339 continue;
3340 }
3341
3342 if (M0 < 0 || M1 < 0 ||
3343 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3344 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3345 CanFold = false;
3346 break;
3347 }
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003348
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003349 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3350 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3351 }
3352
3353 if (CanFold) {
3354 // Fold this sequence only if the resulting shuffle is 'legal'.
3355 if (TLI.isShuffleMaskLegal(Mask1, VT))
3356 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3357 N1->getOperand(0), &Mask1[0]);
3358 if (TLI.isShuffleMaskLegal(Mask2, VT))
3359 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3360 N0->getOperand(0), &Mask2[0]);
3361 }
3362 }
Dan Gohman80f9f072007-07-13 20:03:40 +00003363 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003364
Dan Gohman06563a82007-07-03 14:03:57 +00003365 // fold (or x, undef) -> -1
Bob Wilson269a89f2010-06-28 23:40:25 +00003366 if (!LegalOperations &&
3367 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman9655f842009-12-03 07:11:29 +00003368 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3369 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3370 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003371 // fold (or c1, c2) -> c1|c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003372 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003373 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003374 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003375 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003376 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003377 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003378 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003379 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003380 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003381 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003382 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003383 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003384 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003385 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003386
3387 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3388 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003389 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003390 return BSwap;
3391 BSwap = MatchBSwapHWordLow(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003392 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003393 return BSwap;
3394
Nate Begeman22e251a2006-02-03 06:46:56 +00003395 // reassociate or
Andrew Trickef9de2a2013-05-25 02:42:55 +00003396 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003397 if (ROR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003398 return ROR;
3399 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003400 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003401 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003402 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003403 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003404 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3405 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3406 if (!COR.getNode())
3407 return SDValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00003408 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3409 DAG.getNode(ISD::OR, SDLoc(N0), VT,
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003410 N0.getOperand(0), N1), COR);
3411 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003412 }
Nate Begeman049b7482005-09-09 19:49:52 +00003413 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3414 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3415 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3416 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003417
Nate Begeman049b7482005-09-09 19:49:52 +00003418 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00003419 LL.getValueType().isInteger()) {
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003420 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3421 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003422 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003423 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003424 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003425 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003426 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003427 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003428 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003429 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3430 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003431 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003432 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003433 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003434 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003435 AddToWorklist(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003436 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003437 }
3438 }
3439 // canonicalize equivalent to ll == rl
3440 if (LL == RR && LR == RL) {
3441 Op1 = ISD::getSetCCSwappedOperands(Op1);
3442 std::swap(RL, RR);
3443 }
3444 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003445 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00003446 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00003447 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003448 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00003449 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3450 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00003451 getSetCCResultType(N0.getValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003452 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003453 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00003454 }
3455 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003456
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003457 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003458 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003459 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003460 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003461 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003462
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003463 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner46d710e2006-09-14 21:11:37 +00003464 if (N0.getOpcode() == ISD::AND &&
3465 N1.getOpcode() == ISD::AND &&
3466 N0.getOperand(1).getOpcode() == ISD::Constant &&
3467 N1.getOperand(1).getOpcode() == ISD::Constant &&
3468 // Don't increase # computations.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003469 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner46d710e2006-09-14 21:11:37 +00003470 // We can only do this xform if we know that bits from X that are set in C2
3471 // but not in C1 are already zero. Likewise for Y.
Dan Gohman1f372ed2008-02-25 21:11:39 +00003472 const APInt &LHSMask =
3473 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3474 const APInt &RHSMask =
3475 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003476
Dan Gohman309d3d52007-06-22 14:59:07 +00003477 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3478 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003479 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003480 N0.getOperand(0), N1.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003481 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003482 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner46d710e2006-09-14 21:11:37 +00003483 }
3484 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003485
Chris Lattner97614c82006-09-14 20:50:57 +00003486 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003487 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003488 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003489
Dan Gohman600f62b2010-06-24 14:30:44 +00003490 // Simplify the operands using demanded-bits information.
3491 if (!VT.isVector() &&
3492 SimplifyDemandedBits(SDValue(N, 0)))
3493 return SDValue(N, 0);
3494
Evan Chengf1005572010-04-28 07:10:39 +00003495 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003496}
3497
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003498/// Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003499static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003500 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003501 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003502 Mask = Op.getOperand(1);
3503 Op = Op.getOperand(0);
3504 } else {
3505 return false;
3506 }
3507 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003508
Chris Lattner97614c82006-09-14 20:50:57 +00003509 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3510 Shift = Op;
3511 return true;
3512 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003513
Scott Michelcf0da6c2009-02-17 22:15:04 +00003514 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003515}
3516
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003517// Return true if we can prove that, whenever Neg and Pos are both in the
3518// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003519// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3520//
3521// (or (shift1 X, Neg), (shift2 X, Pos))
3522//
Adam Nemetc6553a82014-03-07 23:56:24 +00003523// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3524// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3525// to consider shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003526static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003527 // If OpSize is a power of 2 then:
3528 //
3529 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3530 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3531 //
3532 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3533 // for the stronger condition:
3534 //
3535 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3536 //
3537 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3538 // we can just replace Neg with Neg' for the rest of the function.
3539 //
3540 // In other cases we check for the even stronger condition:
3541 //
3542 // Neg == OpSize - Pos [B]
3543 //
3544 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3545 // behavior if Pos == 0 (and consequently Neg == OpSize).
Adam Nemetc6553a82014-03-07 23:56:24 +00003546 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003547 // We could actually use [A] whenever OpSize is a power of 2, but the
3548 // only extra cases that it would match are those uninteresting ones
3549 // where Neg and Pos are never in range at the same time. E.g. for
3550 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3551 // as well as (sub 32, Pos), but:
3552 //
3553 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3554 //
3555 // always invokes undefined behavior for 32-bit X.
3556 //
3557 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
Adam Nemetc6553a82014-03-07 23:56:24 +00003558 unsigned MaskLoBits = 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003559 if (Neg.getOpcode() == ISD::AND &&
3560 isPowerOf2_64(OpSize) &&
3561 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3562 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3563 Neg = Neg.getOperand(0);
Adam Nemetc6553a82014-03-07 23:56:24 +00003564 MaskLoBits = Log2_64(OpSize);
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003565 }
3566
Richard Sandiford0f264db2014-01-09 10:49:40 +00003567 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3568 if (Neg.getOpcode() != ISD::SUB)
3569 return 0;
3570 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3571 if (!NegC)
3572 return 0;
3573 SDValue NegOp1 = Neg.getOperand(1);
3574
Adam Nemet5117f5d2014-03-07 23:56:28 +00003575 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3576 // Pos'. The truncation is redundant for the purpose of the equality.
3577 if (MaskLoBits &&
3578 Pos.getOpcode() == ISD::AND &&
3579 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3580 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3581 Pos = Pos.getOperand(0);
3582
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003583 // The condition we need is now:
3584 //
3585 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3586 //
3587 // If NegOp1 == Pos then we need:
3588 //
3589 // OpSize & Mask == NegC & Mask
3590 //
3591 // (because "x & Mask" is a truncation and distributes through subtraction).
3592 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003593 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003594 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003595 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3596 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003597 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003598 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3599 //
3600 // which, again because "x & Mask" is a truncation, becomes:
3601 //
3602 // NegC & Mask == (OpSize - PosC) & Mask
3603 // OpSize & Mask == (NegC + PosC) & Mask
3604 else if (Pos.getOpcode() == ISD::ADD &&
3605 Pos.getOperand(0) == NegOp1 &&
3606 Pos.getOperand(1).getOpcode() == ISD::Constant)
3607 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3608 NegC->getAPIntValue());
3609 else
3610 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003611
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003612 // Now we just need to check that OpSize & Mask == Width & Mask.
Adam Nemetc6553a82014-03-07 23:56:24 +00003613 if (MaskLoBits)
3614 // Opsize & Mask is 0 since Mask is Opsize - 1.
3615 return Width.getLoBits(MaskLoBits) == 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003616 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003617}
3618
Richard Sandiford95c864d2014-01-08 15:40:47 +00003619// A subroutine of MatchRotate used once we have found an OR of two opposite
3620// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3621// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3622// former being preferred if supported. InnerPos and InnerNeg are Pos and
3623// Neg with outer conversions stripped away.
3624SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3625 SDValue Neg, SDValue InnerPos,
3626 SDValue InnerNeg, unsigned PosOpcode,
3627 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003628 // fold (or (shl x, (*ext y)),
3629 // (srl x, (*ext (sub 32, y)))) ->
3630 // (rotl x, y) or (rotr x, (sub 32, y))
3631 //
3632 // fold (or (shl x, (*ext (sub 32, y))),
3633 // (srl x, (*ext y))) ->
3634 // (rotr x, y) or (rotl x, (sub 32, y))
3635 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003636 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003637 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3638 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3639 HasPos ? Pos : Neg).getNode();
3640 }
3641
Craig Topperc0196b12014-04-14 00:51:57 +00003642 return nullptr;
Richard Sandiford95c864d2014-01-08 15:40:47 +00003643}
3644
Chris Lattner97614c82006-09-14 20:50:57 +00003645// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3646// idioms for rotate, and if the target supports rotation instructions, generate
3647// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003648SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003649 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003650 EVT VT = LHS.getValueType();
Craig Topperc0196b12014-04-14 00:51:57 +00003651 if (!TLI.isTypeLegal(VT)) return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003652
3653 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003654 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3655 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Craig Topperc0196b12014-04-14 00:51:57 +00003656 if (!HasROTL && !HasROTR) return nullptr;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003657
Chris Lattner97614c82006-09-14 20:50:57 +00003658 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003659 SDValue LHSShift; // The shift.
3660 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003661 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003662 return nullptr; // Not part of a rotate.
Chris Lattner97614c82006-09-14 20:50:57 +00003663
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003664 SDValue RHSShift; // The shift.
3665 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003666 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003667 return nullptr; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003668
Chris Lattner97614c82006-09-14 20:50:57 +00003669 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
Craig Topperc0196b12014-04-14 00:51:57 +00003670 return nullptr; // Not shifting the same value.
Chris Lattner97614c82006-09-14 20:50:57 +00003671
3672 if (LHSShift.getOpcode() == RHSShift.getOpcode())
Craig Topperc0196b12014-04-14 00:51:57 +00003673 return nullptr; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003674
Chris Lattner97614c82006-09-14 20:50:57 +00003675 // Canonicalize shl to left side in a shl/srl pair.
3676 if (RHSShift.getOpcode() == ISD::SHL) {
3677 std::swap(LHS, RHS);
3678 std::swap(LHSShift, RHSShift);
3679 std::swap(LHSMask , RHSMask );
3680 }
3681
Duncan Sands13237ac2008-06-06 12:08:01 +00003682 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003683 SDValue LHSShiftArg = LHSShift.getOperand(0);
3684 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003685 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003686 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003687
3688 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3689 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003690 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3691 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003692 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3693 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003694 if ((LShVal + RShVal) != OpSizeInBits)
Craig Topperc0196b12014-04-14 00:51:57 +00003695 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003696
Craig Topper65161fa2012-09-29 06:54:22 +00003697 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3698 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003699
Chris Lattner97614c82006-09-14 20:50:57 +00003700 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003701 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003702 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003703
Gabor Greiff304a7a2008-08-28 21:40:38 +00003704 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003705 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3706 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003707 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003708 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003709 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3710 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003711 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003712
Bill Wendling35972a92009-01-30 21:14:50 +00003713 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003714 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003715
Gabor Greiff304a7a2008-08-28 21:40:38 +00003716 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003717 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003718
Chris Lattner97614c82006-09-14 20:50:57 +00003719 // If there is a mask here, and we have a variable shift, we can't be sure
3720 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003721 if (LHSMask.getNode() || RHSMask.getNode())
Craig Topperc0196b12014-04-14 00:51:57 +00003722 return nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003723
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003724 // If the shift amount is sign/zext/any-extended just peel it off.
3725 SDValue LExtOp0 = LHSShiftAmt;
3726 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003727 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3728 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3729 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3730 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3731 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3732 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3733 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3734 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003735 LExtOp0 = LHSShiftAmt.getOperand(0);
3736 RExtOp0 = RHSShiftAmt.getOperand(0);
3737 }
3738
Richard Sandiford95c864d2014-01-08 15:40:47 +00003739 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3740 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3741 if (TryL)
3742 return TryL;
3743
3744 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3745 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3746 if (TryR)
3747 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003748
Craig Topperc0196b12014-04-14 00:51:57 +00003749 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003750}
3751
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003752SDValue DAGCombiner::visitXOR(SDNode *N) {
3753 SDValue N0 = N->getOperand(0);
3754 SDValue N1 = N->getOperand(1);
3755 SDValue LHS, RHS, CC;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003756 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3757 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003758 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003759
Dan Gohmana8665142007-06-25 16:23:39 +00003760 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003761 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003762 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003763 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003764
3765 // fold (xor x, 0) -> x, vector edition
3766 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3767 return N1;
3768 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3769 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003770 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003771
Evan Chengdf1690d2008-03-25 20:08:07 +00003772 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3773 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3774 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003775 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003776 if (N0.getOpcode() == ISD::UNDEF)
3777 return N0;
3778 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003779 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003780 // fold (xor c1, c2) -> c1^c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003781 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003782 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003783 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003784 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003785 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003786 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003787 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003788 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003789 // reassociate xor
Andrew Trickef9de2a2013-05-25 02:42:55 +00003790 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003791 if (RXOR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003792 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003793
Nate Begeman21158fc2005-09-01 00:19:25 +00003794 // fold !(x cc y) -> (x !cc y)
Dan Gohmanb72127a2008-03-13 22:13:53 +00003795 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003796 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003797 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3798 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003799
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003800 if (!LegalOperations ||
3801 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003802 switch (N0.getOpcode()) {
3803 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003804 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003805 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003806 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003807 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003808 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003809 N0.getOperand(3), NotCC);
3810 }
3811 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003812 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003813
Chris Lattner58c227b2007-09-10 21:39:07 +00003814 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003815 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003816 N0.getNode()->hasOneUse() &&
3817 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003818 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003819 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003820 DAG.getConstant(1, V.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003821 AddToWorklist(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003822 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003823 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003824
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003825 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003826 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003827 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003828 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003829 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3830 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003831 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3832 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003833 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003834 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003835 }
3836 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003837 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003838 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003839 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003840 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003841 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3842 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003843 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3844 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003845 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003846 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003847 }
3848 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003849 // fold (xor (and x, y), y) -> (and (not x), y)
3850 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003851 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003852 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003853 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003854 AddToWorklist(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003855 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003856 }
Bill Wendling35972a92009-01-30 21:14:50 +00003857 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003858 if (N1C && N0.getOpcode() == ISD::XOR) {
3859 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3860 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3861 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003862 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003863 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003864 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003865 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003866 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003867 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003868 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003869 }
3870 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003871 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003872 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003873
Chris Lattner8d6fc202006-05-05 05:51:50 +00003874 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3875 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003876 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003877 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003878 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003879
Chris Lattner098c01e2006-04-08 04:15:24 +00003880 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00003881 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003882 SimplifyDemandedBits(SDValue(N, 0)))
3883 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003884
Evan Chengf1005572010-04-28 07:10:39 +00003885 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003886}
3887
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003888/// Handle transforms common to the three shifts, when the shift amount is a
3889/// constant.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003890SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003891 // We can't and shouldn't fold opaque constants.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003892 if (Amt->isOpaque())
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003893 return SDValue();
3894
Gabor Greiff304a7a2008-08-28 21:40:38 +00003895 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003896 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003897
Chris Lattner7c709a52007-12-06 07:33:36 +00003898 // We want to pull some binops through shifts, so that we have (and (shift))
3899 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3900 // thing happens with address calculations, so it's important to canonicalize
3901 // it.
3902 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00003903
Chris Lattner7c709a52007-12-06 07:33:36 +00003904 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003905 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003906 case ISD::OR:
3907 case ISD::XOR:
3908 HighBitSet = false; // We can only transform sra if the high bit is clear.
3909 break;
3910 case ISD::AND:
3911 HighBitSet = true; // We can only transform sra if the high bit is set.
3912 break;
3913 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00003914 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003915 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00003916 HighBitSet = false; // We can only transform sra if the high bit is clear.
3917 break;
3918 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003919
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003920 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00003921 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003922 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003923
3924 // FIXME: disable this unless the input to the binop is a shift by a constant.
3925 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00003926 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003927 // void foo(int *X, int i) { X[i & 1235] = 1; }
3928 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003929 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003930 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00003931 BinOpLHSVal->getOpcode() != ISD::SRA &&
3932 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3933 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003934 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003935
Owen Anderson53aa7a92009-08-10 22:56:29 +00003936 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003937
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003938 // If this is a signed shift right, and the high bit is modified by the
3939 // logical operation, do not perform the transformation. The highBitSet
3940 // boolean indicates the value of the high bit of the constant which would
3941 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00003942 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003943 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3944 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003945 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003946 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003947
Weiming Zhao7f6daf12014-04-30 21:07:24 +00003948 if (!TLI.isDesirableToCommuteWithShift(LHS))
3949 return SDValue();
3950
Chris Lattner7c709a52007-12-06 07:33:36 +00003951 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003952 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003953 N->getValueType(0),
3954 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003955 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00003956
3957 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00003958 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00003959 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003960 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00003961
3962 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003963 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00003964}
3965
Adam Nemet67483892014-03-04 23:28:31 +00003966SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3967 assert(N->getOpcode() == ISD::TRUNCATE);
3968 assert(N->getOperand(0).getOpcode() == ISD::AND);
3969
3970 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3971 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3972 SDValue N01 = N->getOperand(0).getOperand(1);
3973
Matt Arsenault985b9de2014-03-17 18:58:01 +00003974 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
Adam Nemet67483892014-03-04 23:28:31 +00003975 EVT TruncVT = N->getValueType(0);
3976 SDValue N00 = N->getOperand(0).getOperand(0);
3977 APInt TruncC = N01C->getAPIntValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003978 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
Adam Nemet67483892014-03-04 23:28:31 +00003979
3980 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3981 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3982 DAG.getConstant(TruncC, TruncVT));
3983 }
3984 }
3985
3986 return SDValue();
3987}
Adam Nemet7f928f12014-03-07 23:56:30 +00003988
3989SDValue DAGCombiner::visitRotate(SDNode *N) {
3990 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3991 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3992 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3993 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3994 if (NewOp1.getNode())
3995 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3996 N->getOperand(0), NewOp1);
3997 }
3998 return SDValue();
3999}
4000
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004001SDValue DAGCombiner::visitSHL(SDNode *N) {
4002 SDValue N0 = N->getOperand(0);
4003 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004004 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4005 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004006 EVT VT = N0.getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004007 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004008
Daniel Sandersa1840d22013-11-11 17:23:41 +00004009 // fold vector ops
4010 if (VT.isVector()) {
4011 SDValue FoldedVOp = SimplifyVBinOp(N);
4012 if (FoldedVOp.getNode()) return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00004013
4014 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4015 // If setcc produces all-one true value then:
4016 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004017 if (N1CV && N1CV->isConstant()) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004018 if (N0.getOpcode() == ISD::AND) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004019 SDValue N00 = N0->getOperand(0);
4020 SDValue N01 = N0->getOperand(1);
4021 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004022
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004023 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4024 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4025 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004026 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4027 if (C.getNode())
4028 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4029 }
4030 } else {
4031 N1C = isConstOrConstSplat(N1);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004032 }
4033 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00004034 }
4035
Nate Begeman21158fc2005-09-01 00:19:25 +00004036 // fold (shl c1, c2) -> c1<<c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004037 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004038 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004039 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004040 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004041 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004042 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004043 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004044 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004045 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004046 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004047 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00004048 // fold (shl undef, x) -> 0
4049 if (N0.getOpcode() == ISD::UNDEF)
4050 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004051 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004052 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00004053 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004054 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00004055 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004056 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004057 N1.getOperand(0).getOpcode() == ISD::AND) {
4058 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4059 if (NewOp1.getNode())
4060 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004061 }
4062
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004063 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4064 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004065
4066 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004067 if (N1C && N0.getOpcode() == ISD::SHL) {
4068 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4069 uint64_t c1 = N0C1->getZExtValue();
4070 uint64_t c2 = N1C->getZExtValue();
4071 if (c1 + c2 >= OpSizeInBits)
4072 return DAG.getConstant(0, VT);
4073 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4074 DAG.getConstant(c1 + c2, N1.getValueType()));
4075 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004076 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004077
4078 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4079 // For this to be valid, the second form must not preserve any of the bits
4080 // that are shifted out by the inner shift in the first form. This means
4081 // the outer shift size must be >= the number of bits added by the ext.
4082 // As a corollary, we don't care what kind of ext it is.
4083 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4084 N0.getOpcode() == ISD::ANY_EXTEND ||
4085 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004086 N0.getOperand(0).getOpcode() == ISD::SHL) {
4087 SDValue N0Op0 = N0.getOperand(0);
4088 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4089 uint64_t c1 = N0Op0C1->getZExtValue();
4090 uint64_t c2 = N1C->getZExtValue();
4091 EVT InnerShiftVT = N0Op0.getValueType();
4092 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4093 if (c2 >= OpSizeInBits - InnerShiftSize) {
4094 if (c1 + c2 >= OpSizeInBits)
4095 return DAG.getConstant(0, VT);
4096 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4097 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4098 N0Op0->getOperand(0)),
4099 DAG.getConstant(c1 + c2, N1.getValueType()));
4100 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004101 }
4102 }
4103
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004104 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4105 // Only fold this if the inner zext has no other uses to avoid increasing
4106 // the total number of instructions.
4107 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004108 N0.getOperand(0).getOpcode() == ISD::SRL) {
4109 SDValue N0Op0 = N0.getOperand(0);
4110 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4111 uint64_t c1 = N0Op0C1->getZExtValue();
4112 if (c1 < VT.getScalarSizeInBits()) {
4113 uint64_t c2 = N1C->getZExtValue();
4114 if (c1 == c2) {
4115 SDValue NewOp0 = N0.getOperand(0);
4116 EVT CountVT = NewOp0.getOperand(1).getValueType();
4117 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4118 NewOp0, DAG.getConstant(c2, CountVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004119 AddToWorklist(NewSHL.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004120 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4121 }
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004122 }
4123 }
4124 }
4125
Eli Friedman1877ac92011-06-09 22:14:44 +00004126 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4127 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00004128 // Only fold this if the inner shift has no other uses -- if it does, folding
4129 // this will increase the total number of instructions.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004130 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4131 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4132 uint64_t c1 = N0C1->getZExtValue();
4133 if (c1 < OpSizeInBits) {
4134 uint64_t c2 = N1C->getZExtValue();
4135 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4136 SDValue Shift;
4137 if (c2 > c1) {
4138 Mask = Mask.shl(c2 - c1);
4139 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4140 DAG.getConstant(c2 - c1, N1.getValueType()));
4141 } else {
4142 Mask = Mask.lshr(c1 - c2);
4143 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4144 DAG.getConstant(c1 - c2, N1.getValueType()));
4145 }
4146 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4147 DAG.getConstant(Mask, VT));
Eli Friedman1877ac92011-06-09 22:14:44 +00004148 }
Evan Chenga7bb55e2009-07-21 05:40:15 +00004149 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004150 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004151 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00004152 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004153 unsigned BitSize = VT.getScalarSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004154 SDValue HiBitsMask =
Matt Arsenault985b9de2014-03-17 18:58:01 +00004155 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4156 BitSize - N1C->getZExtValue()), VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004157 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004158 HiBitsMask);
4159 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004160
Matt Arsenault8239eaa2014-09-11 17:34:19 +00004161 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4162 // Variant of version done on multiply, except mul by a power of 2 is turned
4163 // into a shift.
4164 APInt Val;
4165 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4166 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4167 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4168 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4169 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4170 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4171 }
4172
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004173 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004174 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004175 if (NewSHL.getNode())
4176 return NewSHL;
4177 }
4178
Evan Chengf1005572010-04-28 07:10:39 +00004179 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004180}
4181
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004182SDValue DAGCombiner::visitSRA(SDNode *N) {
4183 SDValue N0 = N->getOperand(0);
4184 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004185 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4186 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004187 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004188 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004189
Daniel Sandersa1840d22013-11-11 17:23:41 +00004190 // fold vector ops
4191 if (VT.isVector()) {
4192 SDValue FoldedVOp = SimplifyVBinOp(N);
4193 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004194
4195 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004196 }
4197
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004198 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004199 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004200 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004201 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004202 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004203 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004204 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004205 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004206 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004207 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004208 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004209 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004210 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004211 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004212 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004213 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4214 // sext_inreg.
4215 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004216 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004217 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4218 if (VT.isVector())
4219 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4220 ExtVT, VT.getVectorNumElements());
4221 if ((!LegalOperations ||
4222 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004223 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004224 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004225 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004226
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004227 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004228 if (N1C && N0.getOpcode() == ISD::SRA) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004229 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004230 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004231 if (Sum >= OpSizeInBits)
4232 Sum = OpSizeInBits - 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004233 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Matt Arsenault985b9de2014-03-17 18:58:01 +00004234 DAG.getConstant(Sum, N1.getValueType()));
Chris Lattner0f8a7272006-02-28 06:23:04 +00004235 }
4236 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004237
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004238 // fold (sra (shl X, m), (sub result_size, n))
4239 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004240 // result_size - n != m.
4241 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004242 // code.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004243 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb8fe91092008-03-19 08:30:06 +00004244 // Get the two constanst of the shifts, CN0 = m, CN = n.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004245 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4246 if (N01C) {
4247 LLVMContext &Ctx = *DAG.getContext();
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004248 // Determine what the truncate's result bitsize and type would be.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004249 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4250
4251 if (VT.isVector())
4252 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4253
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004254 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004255 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004256
Scott Michelcf0da6c2009-02-17 22:15:04 +00004257 // If the shift is not a no-op (in which case this should be just a sign
4258 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004259 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004260 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004261 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004262 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4263 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004264 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004265
Owen Andersonb2c80da2011-02-25 21:41:48 +00004266 SDValue Amt = DAG.getConstant(ShiftAmt,
4267 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004268 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004269 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004270 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004271 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004272 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004273 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004274 }
4275 }
4276 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004277
Duncan Sands3ed76882009-02-01 18:06:53 +00004278 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004279 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004280 N1.getOperand(0).getOpcode() == ISD::AND) {
4281 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4282 if (NewOp1.getNode())
4283 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004284 }
4285
Matt Arsenault985b9de2014-03-17 18:58:01 +00004286 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer946e1522011-01-30 16:38:43 +00004287 // if c1 is equal to the number of bits the trunc removes
4288 if (N0.getOpcode() == ISD::TRUNCATE &&
4289 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4290 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4291 N0.getOperand(0).hasOneUse() &&
4292 N0.getOperand(0).getOperand(1).hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004293 N1C) {
4294 SDValue N0Op0 = N0.getOperand(0);
4295 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4296 unsigned LargeShiftVal = LargeShift->getZExtValue();
4297 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer946e1522011-01-30 16:38:43 +00004298
Matt Arsenault985b9de2014-03-17 18:58:01 +00004299 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4300 SDValue Amt =
4301 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4302 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4303 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4304 N0Op0.getOperand(0), Amt);
4305 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4306 }
Benjamin Kramer946e1522011-01-30 16:38:43 +00004307 }
4308 }
4309
Scott Michelcf0da6c2009-02-17 22:15:04 +00004310 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004311 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4312 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004313
4314
Nate Begeman21158fc2005-09-01 00:19:25 +00004315 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004316 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004317 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004318
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004319 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004320 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004321 if (NewSRA.getNode())
4322 return NewSRA;
4323 }
4324
Evan Chengf1005572010-04-28 07:10:39 +00004325 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004326}
4327
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004328SDValue DAGCombiner::visitSRL(SDNode *N) {
4329 SDValue N0 = N->getOperand(0);
4330 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004331 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4332 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004333 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004334 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004335
Daniel Sandersa1840d22013-11-11 17:23:41 +00004336 // fold vector ops
4337 if (VT.isVector()) {
4338 SDValue FoldedVOp = SimplifyVBinOp(N);
4339 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004340
4341 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004342 }
4343
Nate Begeman21158fc2005-09-01 00:19:25 +00004344 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004345 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004346 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004347 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004348 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004349 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004350 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004351 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004352 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004353 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004354 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004355 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004356 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004357 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004358 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004359 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004360
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004361 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004362 if (N1C && N0.getOpcode() == ISD::SRL) {
4363 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4364 uint64_t c1 = N01C->getZExtValue();
4365 uint64_t c2 = N1C->getZExtValue();
4366 if (c1 + c2 >= OpSizeInBits)
4367 return DAG.getConstant(0, VT);
4368 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4369 DAG.getConstant(c1 + c2, N1.getValueType()));
4370 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004371 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004372
Dale Johannesencd538af2010-12-17 21:45:49 +00004373 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004374 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4375 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004376 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004377 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004378 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4379 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004380 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4381 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004382 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004383 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004384 if (c1 + OpSizeInBits == InnerShiftSize) {
4385 if (c1 + c2 >= InnerShiftSize)
4386 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004387 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4388 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004389 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004390 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004391 }
4392 }
4393
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004394 // fold (srl (shl x, c), c) -> (and x, cst2)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004395 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4396 unsigned BitSize = N0.getScalarValueSizeInBits();
4397 if (BitSize <= 64) {
4398 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4399 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4400 DAG.getConstant(~0ULL >> ShAmt, VT));
4401 }
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004402 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004403
Michael Liao62ebfd82013-06-21 18:45:27 +00004404 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004405 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4406 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004407 EVT SmallVT = N0.getOperand(0).getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004408 unsigned BitSize = SmallVT.getScalarSizeInBits();
4409 if (N1C->getZExtValue() >= BitSize)
Dale Johannesen84935752009-02-06 23:05:02 +00004410 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004411
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004412 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004413 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004414 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004415 N0.getOperand(0),
4416 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004417 AddToWorklist(SmallShift.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004418 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Michael Liao62ebfd82013-06-21 18:45:27 +00004419 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4420 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4421 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004422 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004423 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004424
Chris Lattner2e33fb42006-10-12 20:23:19 +00004425 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4426 // bit, which is unmodified by sra.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004427 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004428 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004429 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004430 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004431
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004432 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004433 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004434 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004435 APInt KnownZero, KnownOne;
Jay Foada0653a32014-05-14 21:14:37 +00004436 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004437
Chris Lattner49932492006-04-02 06:11:11 +00004438 // If any of the input bits are KnownOne, then the input couldn't be all
4439 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004440 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004441
Chris Lattner49932492006-04-02 06:11:11 +00004442 // If all of the bits input the to ctlz node are known to be zero, then
4443 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004444 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004445 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004446
Chris Lattner49932492006-04-02 06:11:11 +00004447 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004448 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004449 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004450 // could be set on input to the CTLZ node. If this bit is set, the SRL
4451 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4452 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004453 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004454 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004455
Chris Lattner49932492006-04-02 06:11:11 +00004456 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004457 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004458 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004459 AddToWorklist(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004460 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004461
Andrew Trickef9de2a2013-05-25 02:42:55 +00004462 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004463 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004464 }
4465 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004466
Duncan Sands3ed76882009-02-01 18:06:53 +00004467 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004468 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004469 N1.getOperand(0).getOpcode() == ISD::AND) {
4470 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4471 if (NewOp1.getNode())
4472 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004473 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004474
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004475 // fold operands of srl based on knowledge that the low bits are not
4476 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004477 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4478 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004479
Evan Chengb175de62009-12-18 21:31:31 +00004480 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004481 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Chengb175de62009-12-18 21:31:31 +00004482 if (NewSRL.getNode())
4483 return NewSRL;
4484 }
4485
Dan Gohman600f62b2010-06-24 14:30:44 +00004486 // Attempt to convert a srl of a load into a narrower zero-extending load.
4487 SDValue NarrowLoad = ReduceLoadWidth(N);
4488 if (NarrowLoad.getNode())
4489 return NarrowLoad;
4490
Evan Chengb175de62009-12-18 21:31:31 +00004491 // Here is a common situation. We want to optimize:
4492 //
4493 // %a = ...
4494 // %b = and i32 %a, 2
4495 // %c = srl i32 %b, 1
4496 // brcond i32 %c ...
4497 //
4498 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004499 //
Evan Chengb175de62009-12-18 21:31:31 +00004500 // %a = ...
4501 // %b = and %a, 2
4502 // %c = setcc eq %b, 0
4503 // brcond %c ...
4504 //
4505 // However when after the source operand of SRL is optimized into AND, the SRL
4506 // itself may not be optimized further. Look for it and add the BRCOND into
4507 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004508 if (N->hasOneUse()) {
4509 SDNode *Use = *N->use_begin();
4510 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004511 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004512 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4513 // Also look pass the truncate.
4514 Use = *Use->use_begin();
4515 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004516 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004517 }
4518 }
Evan Chengb175de62009-12-18 21:31:31 +00004519
Evan Chengf1005572010-04-28 07:10:39 +00004520 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004521}
4522
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004523SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4524 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004525 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004526
4527 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004528 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004529 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004530 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004531}
4532
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004533SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4534 SDValue N0 = N->getOperand(0);
4535 EVT VT = N->getValueType(0);
4536
4537 // fold (ctlz_zero_undef c1) -> c2
4538 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004539 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004540 return SDValue();
4541}
4542
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004543SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4544 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004545 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004546
Nate Begeman21158fc2005-09-01 00:19:25 +00004547 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004548 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004549 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004550 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004551}
4552
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004553SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4554 SDValue N0 = N->getOperand(0);
4555 EVT VT = N->getValueType(0);
4556
4557 // fold (cttz_zero_undef c1) -> c2
4558 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004559 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004560 return SDValue();
4561}
4562
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004563SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4564 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004565 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004566
Nate Begeman21158fc2005-09-01 00:19:25 +00004567 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004568 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004569 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004570 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004571}
4572
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004573SDValue DAGCombiner::visitSELECT(SDNode *N) {
4574 SDValue N0 = N->getOperand(0);
4575 SDValue N1 = N->getOperand(1);
4576 SDValue N2 = N->getOperand(2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004577 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4578 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4579 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004580 EVT VT = N->getValueType(0);
4581 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004582
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004583 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004584 if (N1 == N2)
4585 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004586 // fold (select true, X, Y) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004587 if (N0C && !N0C->isNullValue())
4588 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004589 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004590 if (N0C && N0C->isNullValue())
4591 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004592 // fold (select C, 1, X) -> (or C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004593 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004594 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004595 // fold (select C, 0, 1) -> (xor C, 1)
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004596 // We can't do this reliably if integer based booleans have different contents
4597 // to floating point based booleans. This is because we can't tell whether we
4598 // have an integer-based boolean or a floating-point-based boolean unless we
4599 // can find the SETCC that produced it and inspect its operands. This is
4600 // fairly easy if C is the SETCC node, but it can potentially be
4601 // undiscoverable (or not reasonably discoverable). For example, it could be
4602 // in another basic block or it could require searching a complicated
4603 // expression.
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004604 if (VT.isInteger() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004605 (VT0 == MVT::i1 || (VT0.isInteger() &&
4606 TLI.getBooleanContents(false, false) ==
4607 TLI.getBooleanContents(false, true) &&
4608 TLI.getBooleanContents(false, false) ==
4609 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004610 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004611 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004612 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004613 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004614 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004615 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004616 N0, DAG.getConstant(1, VT0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004617 AddToWorklist(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004618 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004619 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4620 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004621 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004622 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004623 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004624 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004625 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004626 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004627 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004628 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004629 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004630 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004631 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004632 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004633 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004634 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004635 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004636 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004637 // fold (select X, X, Y) -> (or X, Y)
4638 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004639 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004640 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004641 // fold (select X, Y, X) -> (and X, Y)
4642 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004643 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004644 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004645
Chris Lattner6c14c352005-10-18 06:04:22 +00004646 // If we can fold this based on the true/false value, do so.
4647 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004648 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004649
Nate Begemanc760f802005-09-19 22:34:01 +00004650 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004651 if (N0.getOpcode() == ISD::SETCC) {
Tom Stellard3787b122014-06-10 16:01:29 +00004652 if ((!LegalOperations &&
4653 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4654 TLI.isOperationLegal(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004655 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004656 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004657 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004658 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004659 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004660
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004661 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004662}
4663
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004664static
4665std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4666 SDLoc DL(N);
4667 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004668 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004669
4670 // Split the inputs.
4671 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004672 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4673 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004674
4675 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4676 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4677
4678 return std::make_pair(Lo, Hi);
4679}
4680
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004681// This function assumes all the vselect's arguments are CONCAT_VECTOR
4682// nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4683static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4684 SDLoc dl(N);
4685 SDValue Cond = N->getOperand(0);
4686 SDValue LHS = N->getOperand(1);
4687 SDValue RHS = N->getOperand(2);
Benjamin Kramerff8b8832014-08-21 13:28:02 +00004688 EVT VT = N->getValueType(0);
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004689 int NumElems = VT.getVectorNumElements();
4690 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4691 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4692 Cond.getOpcode() == ISD::BUILD_VECTOR);
4693
Benjamin Kramerff8b8832014-08-21 13:28:02 +00004694 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4695 // binary ones here.
4696 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4697 return SDValue();
4698
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004699 // We're sure we have an even number of elements due to the
4700 // concat_vectors we have as arguments to vselect.
4701 // Skip BV elements until we find one that's not an UNDEF
4702 // After we find an UNDEF element, keep looping until we get to half the
4703 // length of the BV and see if all the non-undef nodes are the same.
4704 ConstantSDNode *BottomHalf = nullptr;
4705 for (int i = 0; i < NumElems / 2; ++i) {
4706 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4707 continue;
4708
4709 if (BottomHalf == nullptr)
4710 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4711 else if (Cond->getOperand(i).getNode() != BottomHalf)
4712 return SDValue();
4713 }
4714
4715 // Do the same for the second half of the BuildVector
4716 ConstantSDNode *TopHalf = nullptr;
4717 for (int i = NumElems / 2; i < NumElems; ++i) {
4718 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4719 continue;
4720
4721 if (TopHalf == nullptr)
4722 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4723 else if (Cond->getOperand(i).getNode() != TopHalf)
4724 return SDValue();
4725 }
4726
4727 assert(TopHalf && BottomHalf &&
4728 "One half of the selector was all UNDEFs and the other was all the "
4729 "same value. This should have been addressed before this function.");
4730 return DAG.getNode(
4731 ISD::CONCAT_VECTORS, dl, VT,
4732 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4733 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4734}
4735
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004736SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4737 SDValue N0 = N->getOperand(0);
4738 SDValue N1 = N->getOperand(1);
4739 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004740 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004741
4742 // Canonicalize integer abs.
4743 // vselect (setg[te] X, 0), X, -X ->
4744 // vselect (setgt X, -1), X, -X ->
4745 // vselect (setl[te] X, 0), -X, X ->
4746 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4747 if (N0.getOpcode() == ISD::SETCC) {
4748 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4749 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4750 bool isAbs = false;
4751 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4752
4753 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4754 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4755 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4756 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4757 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4758 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4759 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4760
4761 if (isAbs) {
4762 EVT VT = LHS.getValueType();
4763 SDValue Shift = DAG.getNode(
4764 ISD::SRA, DL, VT, LHS,
4765 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4766 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004767 AddToWorklist(Shift.getNode());
4768 AddToWorklist(Add.getNode());
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004769 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4770 }
4771 }
4772
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004773 // If the VSELECT result requires splitting and the mask is provided by a
4774 // SETCC, then split both nodes and its operands before legalization. This
4775 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4776 // and enables future optimizations (e.g. min/max pattern matching on X86).
4777 if (N0.getOpcode() == ISD::SETCC) {
4778 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004779
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004780 // Check if any splitting is required.
4781 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4782 TargetLowering::TypeSplitVector)
4783 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004784
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004785 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004786 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4787 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4788 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004789
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004790 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4791 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004792
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004793 // Add the new VSELECT nodes to the work list in case they need to be split
4794 // again.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004795 AddToWorklist(Lo.getNode());
4796 AddToWorklist(Hi.getNode());
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004797
4798 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004799 }
4800
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00004801 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4802 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4803 return N1;
4804 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4805 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4806 return N2;
4807
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004808 // The ConvertSelectToConcatVector function is assuming both the above
4809 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4810 // and addressed.
4811 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4812 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4813 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4814 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4815 if (CV.getNode())
4816 return CV;
4817 }
4818
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004819 return SDValue();
4820}
4821
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004822SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4823 SDValue N0 = N->getOperand(0);
4824 SDValue N1 = N->getOperand(1);
4825 SDValue N2 = N->getOperand(2);
4826 SDValue N3 = N->getOperand(3);
4827 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00004828 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004829
Nate Begemanc760f802005-09-19 22:34:01 +00004830 // fold select_cc lhs, rhs, x, x, cc -> x
4831 if (N2 == N3)
4832 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00004833
Chris Lattner8b68dec2006-09-20 06:19:26 +00004834 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00004835 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004836 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00004837 if (SCC.getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004838 AddToWorklist(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00004839
Stephen Lin605207f2013-06-15 04:03:33 +00004840 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4841 if (!SCCC->isNullValue())
4842 return N2; // cond always true -> true val
4843 else
4844 return N3; // cond always false -> false val
4845 }
4846
4847 // Fold to a simpler select_cc
4848 if (SCC.getOpcode() == ISD::SETCC)
4849 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4850 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4851 SCC.getOperand(2));
Chris Lattner8b68dec2006-09-20 06:19:26 +00004852 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004853
Chris Lattner6c14c352005-10-18 06:04:22 +00004854 // If we can fold this based on the true/false value, do so.
4855 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004856 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00004857
Nate Begemanc760f802005-09-19 22:34:01 +00004858 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00004859 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004860}
4861
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004862SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00004863 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00004864 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004865 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00004866}
4867
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004868// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4869// dag node into a ConstantSDNode or a build_vector of constants.
4870// This function is called by the DAGCombiner when visiting sext/zext/aext
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00004871// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004872// Vector extends are not folded if operations are legal; this is to
4873// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004874static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4875 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004876 bool LegalOperations) {
4877 unsigned Opcode = N->getOpcode();
4878 SDValue N0 = N->getOperand(0);
4879 EVT VT = N->getValueType(0);
4880
4881 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4882 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4883
4884 // fold (sext c1) -> c1
4885 // fold (zext c1) -> c1
4886 // fold (aext c1) -> c1
4887 if (isa<ConstantSDNode>(N0))
4888 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4889
4890 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4891 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4892 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004893 EVT SVT = VT.getScalarType();
4894 if (!(VT.isVector() &&
4895 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004896 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
Craig Topperc0196b12014-04-14 00:51:57 +00004897 return nullptr;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00004898
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004899 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004900 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004901 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4902 unsigned ShAmt = VTBits - EVTBits;
4903 SmallVector<SDValue, 8> Elts;
4904 unsigned NumElts = N0->getNumOperands();
4905 SDLoc DL(N);
4906
4907 for (unsigned i=0; i != NumElts; ++i) {
4908 SDValue Op = N0->getOperand(i);
4909 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004910 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004911 continue;
4912 }
4913
4914 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4915 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4916 if (Opcode == ISD::SIGN_EXTEND)
4917 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004918 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004919 else
4920 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004921 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004922 }
4923
Craig Topper48d114b2014-04-26 18:35:24 +00004924 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004925}
4926
Evan Chenge106e2f2007-10-29 19:58:20 +00004927// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00004928// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00004929// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00004930// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004931static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00004932 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00004933 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00004934 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004935 bool HasCopyToRegUses = false;
4936 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00004937 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4938 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00004939 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00004940 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00004941 if (User == N)
4942 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00004943 if (UI.getUse().getResNo() != N0.getResNo())
4944 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004945 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00004946 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004947 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4948 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4949 // Sign bits will be lost after a zext.
4950 return false;
4951 bool Add = false;
4952 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004953 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00004954 if (UseOp == N0)
4955 continue;
4956 if (!isa<ConstantSDNode>(UseOp))
4957 return false;
4958 Add = true;
4959 }
4960 if (Add)
4961 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00004962 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004963 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00004964 // If truncates aren't free and there are users we can't
4965 // extend, it isn't worthwhile.
4966 if (!isTruncFree)
4967 return false;
4968 // Remember if this value is live-out.
4969 if (User->getOpcode() == ISD::CopyToReg)
4970 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00004971 }
4972
4973 if (HasCopyToRegUses) {
4974 bool BothLiveOut = false;
4975 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4976 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00004977 SDUse &Use = UI.getUse();
4978 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4979 BothLiveOut = true;
4980 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00004981 }
4982 }
4983 if (BothLiveOut)
4984 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00004985 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00004986 return ExtendNodes.size();
4987 }
4988 return true;
4989}
4990
Craig Toppere0b71182013-07-13 07:43:40 +00004991void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004992 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004993 ISD::NodeType ExtType) {
4994 // Extend SetCC uses if necessary.
4995 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4996 SDNode *SetCC = SetCCs[i];
4997 SmallVector<SDValue, 4> Ops;
4998
4999 for (unsigned j = 0; j != 2; ++j) {
5000 SDValue SOp = SetCC->getOperand(j);
5001 if (SOp == Trunc)
5002 Ops.push_back(ExtLoad);
5003 else
5004 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5005 }
5006
5007 Ops.push_back(SetCC->getOperand(2));
Craig Topper48d114b2014-04-26 18:35:24 +00005008 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005009 }
5010}
5011
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005012SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5013 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005014 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005015
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005016 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5017 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005018 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005019
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005020 // fold (sext (sext x)) -> (sext x)
5021 // fold (sext (aext x)) -> (sext x)
5022 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005023 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005024 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005025
Chris Lattnerfce448f2007-02-26 03:13:59 +00005026 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005027 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5028 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005029 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5030 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005031 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5032 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005033 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005034 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005035 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005036 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00005037 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005038 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005039
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005040 // See if the value being truncated is already sign extended. If so, just
5041 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005042 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005043 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5044 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5045 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00005046 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005047
Chris Lattnerfce448f2007-02-26 03:13:59 +00005048 if (OpBits == DestBits) {
5049 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5050 // bits, it is already ready.
5051 if (NumSignBits > DestBits-MidBits)
5052 return Op;
5053 } else if (OpBits < DestBits) {
5054 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5055 // bits, just sext from i32.
5056 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005057 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00005058 } else {
5059 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5060 // bits, just truncate to i32.
5061 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005062 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00005063 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005064
Chris Lattnerfce448f2007-02-26 03:13:59 +00005065 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005066 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5067 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005068 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005069 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005070 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005071 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5072 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005073 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00005074 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00005075 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005076
Evan Chengbce7c472005-12-14 02:19:23 +00005077 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005078 // None of the supported targets knows how to perform load and sign extend
Nadav Rotemb0091302011-02-27 07:40:43 +00005079 // on vectors in one instruction. We only perform this transformation on
5080 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005081 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005082 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005083 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005084 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005085 bool DoXform = true;
5086 SmallVector<SDNode*, 4> SetCCs;
5087 if (!N0.hasOneUse())
5088 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5089 if (DoXform) {
5090 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005091 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005092 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005093 LN0->getBasePtr(), N0.getValueType(),
5094 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005095 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005096 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005097 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005098 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005099 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005100 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005101 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005102 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005103 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005104
5105 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5106 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005107 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5108 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005109 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005110 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005111 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005112 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005113 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005114 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005115 LN0->getBasePtr(), MemVT,
5116 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00005117 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005118 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005119 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005120 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00005121 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005122 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00005123 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005124 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005125
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005126 // fold (sext (and/or/xor (load x), cst)) ->
5127 // (and/or/xor (sextload x), (sext cst))
5128 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5129 N0.getOpcode() == ISD::XOR) &&
5130 isa<LoadSDNode>(N0.getOperand(0)) &&
5131 N0.getOperand(1).getOpcode() == ISD::Constant &&
5132 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5133 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5134 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005135 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005136 bool DoXform = true;
5137 SmallVector<SDNode*, 4> SetCCs;
5138 if (!N0.hasOneUse())
5139 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5140 SetCCs, TLI);
5141 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005142 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005143 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005144 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005145 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005146 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5147 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005148 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005149 ExtLoad, DAG.getConstant(Mask, VT));
5150 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005151 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005152 N0.getOperand(0).getValueType(), ExtLoad);
5153 CombineTo(N, And);
5154 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005155 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005156 ISD::SIGN_EXTEND);
5157 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5158 }
5159 }
5160 }
5161
Chris Lattner65786b02007-04-11 05:32:27 +00005162 if (N0.getOpcode() == ISD::SETCC) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005163 EVT N0VT = N0.getOperand(0).getValueType();
Chris Lattner4ac60732009-07-08 00:31:33 +00005164 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00005165 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00005166 if (VT.isVector() && !LegalOperations &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005167 TLI.getBooleanContents(N0VT) ==
5168 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Nadav Rotem9d376b62012-04-11 08:26:11 +00005169 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5170 // of the same size as the compared operands. Only optimize sext(setcc())
5171 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00005172 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00005173
5174 // We know that the # elements of the results is the same as the
5175 // # elements of the compare (and the # elements of the compare result
5176 // for that matter). Check to see that they are the same size. If so,
5177 // we know that the element size of the sext'd result matches the
5178 // element size of the compare operands.
5179 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005180 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005181 N0.getOperand(1),
5182 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00005183
Dan Gohmane82c25e2010-04-30 17:19:19 +00005184 // If the desired elements are smaller or larger than the source
5185 // elements we can use a matching integer vector type and then
5186 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00005187 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00005188 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005189 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00005190 N0.getOperand(0), N0.getOperand(1),
5191 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005192 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00005193 }
Chris Lattner4ac60732009-07-08 00:31:33 +00005194 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00005195
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005196 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00005197 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00005198 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00005199 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005200 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005201 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00005202 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005203 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005204 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005205
5206 if (!VT.isVector()) {
5207 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5208 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5209 SDLoc DL(N);
5210 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5211 SDValue SetCC = DAG.getSetCC(DL,
5212 SetCCVT,
5213 N0.getOperand(0), N0.getOperand(1), CC);
5214 EVT SelectVT = getSetCCResultType(VT);
5215 return DAG.getSelect(DL, VT,
5216 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5217 NegOne, DAG.getConstant(0, VT));
5218
5219 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00005220 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005221 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005222
Dan Gohman3eb10f72008-04-28 16:58:24 +00005223 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005224 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00005225 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005226 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005227
Evan Chengf1005572010-04-28 07:10:39 +00005228 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005229}
5230
Rafael Espindola8f62b322012-04-09 16:06:03 +00005231// isTruncateOf - If N is a truncate of some other value, return true, record
5232// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5233// This function computes KnownZero to avoid a duplicated call to
Jay Foada0653a32014-05-14 21:14:37 +00005234// computeKnownBits in the caller.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005235static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5236 APInt &KnownZero) {
5237 APInt KnownOne;
5238 if (N->getOpcode() == ISD::TRUNCATE) {
5239 Op = N->getOperand(0);
Jay Foada0653a32014-05-14 21:14:37 +00005240 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005241 return true;
5242 }
5243
5244 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5245 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5246 return false;
5247
5248 SDValue Op0 = N->getOperand(0);
5249 SDValue Op1 = N->getOperand(1);
5250 assert(Op0.getValueType() == Op1.getValueType());
5251
5252 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5253 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005254 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005255 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005256 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005257 Op = Op0;
5258 else
5259 return false;
5260
Jay Foada0653a32014-05-14 21:14:37 +00005261 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005262
5263 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5264 return false;
5265
5266 return true;
5267}
5268
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005269SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5270 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005271 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005272
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005273 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5274 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005275 return SDValue(Res, 0);
5276
Nate Begeman21158fc2005-09-01 00:19:25 +00005277 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005278 // fold (zext (aext x)) -> (zext x)
5279 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005280 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005281 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00005282
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005283 // fold (zext (truncate x)) -> (zext x) or
5284 // (zext (truncate x)) -> (truncate x)
5285 // This is valid when the truncated bits of x are already zero.
5286 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005287 SDValue Op;
5288 APInt KnownZero;
5289 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5290 APInt TruncatedBits =
5291 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5292 APInt(Op.getValueSizeInBits(), 0) :
5293 APInt::getBitsSet(Op.getValueSizeInBits(),
5294 N0.getValueSizeInBits(),
5295 std::min(Op.getValueSizeInBits(),
5296 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00005297 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005298 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005299 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005300 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005301 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005302
5303 return Op;
5304 }
5305 }
5306
Evan Cheng464dc9b2007-03-22 01:54:19 +00005307 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5308 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00005309 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005310 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5311 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005312 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5313 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005314 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005315 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005316 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005317 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005318 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005319 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005320 }
5321
Chris Lattnera31f0a62006-09-21 06:00:20 +00005322 // fold (zext (truncate x)) -> (and x, mask)
5323 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00005324 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005325
5326 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5327 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5328 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5329 if (NarrowLoad.getNode()) {
5330 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5331 if (NarrowLoad.getNode() != N0.getNode()) {
5332 CombineTo(N0.getNode(), NarrowLoad);
5333 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005334 AddToWorklist(oye);
Dan Gohman68fb0042010-11-03 01:47:46 +00005335 }
5336 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5337 }
5338
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005339 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005340 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005341 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005342 AddToWorklist(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00005343 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005344 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005345 AddToWorklist(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005346 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005347 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00005348 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005349 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005350
Dan Gohmanad3e5492009-04-08 00:15:30 +00005351 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5352 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005353 if (N0.getOpcode() == ISD::AND &&
5354 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005355 N0.getOperand(1).getOpcode() == ISD::Constant &&
5356 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5357 N0.getValueType()) ||
5358 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005359 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005360 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005361 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005362 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005363 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005364 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005365 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005366 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005367 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005368 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005369 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005370
Evan Chengbce7c472005-12-14 02:19:23 +00005371 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005372 // None of the supported targets knows how to perform load and vector_zext
Nadav Rotemb0091302011-02-27 07:40:43 +00005373 // on vectors in one instruction. We only perform this transformation on
5374 // scalars.
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005375 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005376 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005377 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005378 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005379 bool DoXform = true;
5380 SmallVector<SDNode*, 4> SetCCs;
5381 if (!N0.hasOneUse())
5382 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5383 if (DoXform) {
5384 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005385 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005386 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005387 LN0->getBasePtr(), N0.getValueType(),
5388 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005389 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005390 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005391 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005392 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005393
Andrew Trickef9de2a2013-05-25 02:42:55 +00005394 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005395 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005396 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005397 }
Evan Chengbce7c472005-12-14 02:19:23 +00005398 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005399
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005400 // fold (zext (and/or/xor (load x), cst)) ->
5401 // (and/or/xor (zextload x), (zext cst))
5402 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5403 N0.getOpcode() == ISD::XOR) &&
5404 isa<LoadSDNode>(N0.getOperand(0)) &&
5405 N0.getOperand(1).getOpcode() == ISD::Constant &&
5406 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5407 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5408 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005409 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005410 bool DoXform = true;
5411 SmallVector<SDNode*, 4> SetCCs;
5412 if (!N0.hasOneUse())
5413 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5414 SetCCs, TLI);
5415 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005416 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005417 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005418 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005419 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005420 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5421 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005422 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005423 ExtLoad, DAG.getConstant(Mask, VT));
5424 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005425 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005426 N0.getOperand(0).getValueType(), ExtLoad);
5427 CombineTo(N, And);
5428 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005429 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005430 ISD::ZERO_EXTEND);
5431 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5432 }
5433 }
5434 }
5435
Chris Lattner7dac1082005-12-14 19:05:06 +00005436 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5437 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005438 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5439 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005440 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005441 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005442 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005443 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005444 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005445 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005446 LN0->getBasePtr(), MemVT,
5447 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005448 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005449 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005450 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005451 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005452 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005453 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005454 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005455 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005456
Chris Lattner65786b02007-04-11 05:32:27 +00005457 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005458 if (!LegalOperations && VT.isVector() &&
5459 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005460 EVT N0VT = N0.getOperand(0).getValueType();
5461 if (getSetCCResultType(N0VT) == N0.getValueType())
5462 return SDValue();
5463
Evan Chengabd0ad52010-05-19 01:08:17 +00005464 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5465 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005466 EVT EltVT = VT.getVectorElementType();
5467 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5468 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00005469 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00005470 // We know that the # elements of the results is the same as the
5471 // # elements of the compare (and the # elements of the compare result
5472 // for that matter). Check to see that they are the same size. If so,
5473 // we know that the element size of the sext'd result matches the
5474 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005475 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5476 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00005477 N0.getOperand(1),
5478 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005479 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Craig Topper48d114b2014-04-26 18:35:24 +00005480 OneOps));
Dan Gohman4298df62011-05-17 22:20:36 +00005481
5482 // If the desired elements are smaller or larger than the source
5483 // elements we can use a matching integer vector type and then
5484 // truncate/sign extend
5485 EVT MatchingElementType =
5486 EVT::getIntegerVT(*DAG.getContext(),
5487 N0VT.getScalarType().getSizeInBits());
5488 EVT MatchingVectorType =
5489 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5490 N0VT.getVectorNumElements());
5491 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005492 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00005493 N0.getOperand(1),
5494 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005495 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5496 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
Craig Topper48d114b2014-04-26 18:35:24 +00005497 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
Evan Chengabd0ad52010-05-19 01:08:17 +00005498 }
5499
5500 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005501 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005502 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00005503 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005504 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005505 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005506 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005507
Evan Cheng852c4862009-12-15 03:00:32 +00005508 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00005509 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00005510 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00005511 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5512 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005513 SDValue ShAmt = N0.getOperand(1);
5514 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00005515 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005516 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00005517 // If the original shl may be shifting out bits, do not perform this
5518 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00005519 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5520 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5521 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00005522 return SDValue();
5523 }
Chris Lattnere95d1952011-02-13 19:09:16 +00005524
Andrew Trickef9de2a2013-05-25 02:42:55 +00005525 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005526
5527 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00005528 if (VT.getSizeInBits() >= 256)
5529 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005530
Chris Lattnere95d1952011-02-13 19:09:16 +00005531 return DAG.getNode(N0.getOpcode(), DL, VT,
5532 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5533 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00005534 }
5535
Evan Chengf1005572010-04-28 07:10:39 +00005536 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005537}
5538
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005539SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5540 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005541 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005542
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005543 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5544 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005545 return SDValue(Res, 0);
5546
Chris Lattner812646a2006-05-05 05:58:59 +00005547 // fold (aext (aext x)) -> (aext x)
5548 // fold (aext (zext x)) -> (zext x)
5549 // fold (aext (sext x)) -> (sext x)
5550 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5551 N0.getOpcode() == ISD::ZERO_EXTEND ||
5552 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005553 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005554
Evan Cheng464dc9b2007-03-22 01:54:19 +00005555 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5556 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5557 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005558 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5559 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005560 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5561 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005562 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005563 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005564 AddToWorklist(oye);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005565 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005566 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005567 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005568 }
5569
Chris Lattner8746e2c2006-09-20 06:29:17 +00005570 // fold (aext (truncate x))
5571 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005572 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005573 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005574 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00005575 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005576 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5577 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005578 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005579
Dan Gohmanad3e5492009-04-08 00:15:30 +00005580 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5581 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00005582 if (N0.getOpcode() == ISD::AND &&
5583 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005584 N0.getOperand(1).getOpcode() == ISD::Constant &&
5585 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5586 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005587 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005588 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005589 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005590 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005591 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00005592 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005593 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005594 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005595 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005596 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00005597 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005598
Chris Lattner812646a2006-05-05 05:58:59 +00005599 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005600 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00005601 // on vectors in one instruction. We only perform this transformation on
5602 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005603 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005604 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Tim Northover7f3e11e2014-07-16 15:37:24 +00005605 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005606 bool DoXform = true;
5607 SmallVector<SDNode*, 4> SetCCs;
5608 if (!N0.hasOneUse())
5609 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5610 if (DoXform) {
5611 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005612 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005613 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005614 LN0->getBasePtr(), N0.getValueType(),
5615 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00005616 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005617 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00005618 N0.getValueType(), ExtLoad);
5619 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005620 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005621 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005622 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5623 }
Chris Lattner812646a2006-05-05 05:58:59 +00005624 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005625
Chris Lattner812646a2006-05-05 05:58:59 +00005626 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5627 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5628 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005629 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005630 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00005631 N0.hasOneUse()) {
5632 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005633 ISD::LoadExtType ExtType = LN0->getExtensionType();
Dan Gohman08c0a952009-09-23 21:02:20 +00005634 EVT MemVT = LN0->getMemoryVT();
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005635 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5636 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5637 VT, LN0->getChain(), LN0->getBasePtr(),
5638 MemVT, LN0->getMemOperand());
5639 CombineTo(N, ExtLoad);
5640 CombineTo(N0.getNode(),
5641 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5642 N0.getValueType(), ExtLoad),
5643 ExtLoad.getValue(1));
5644 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5645 }
Chris Lattner812646a2006-05-05 05:58:59 +00005646 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005647
Chris Lattner65786b02007-04-11 05:32:27 +00005648 if (N0.getOpcode() == ISD::SETCC) {
Hao Liuc636d152014-04-22 09:57:06 +00005649 // For vectors:
5650 // aext(setcc) -> vsetcc
5651 // aext(setcc) -> truncate(vsetcc)
5652 // aext(setcc) -> aext(vsetcc)
Evan Chengabd0ad52010-05-19 01:08:17 +00005653 // Only do this before legalize for now.
5654 if (VT.isVector() && !LegalOperations) {
5655 EVT N0VT = N0.getOperand(0).getValueType();
5656 // We know that the # elements of the results is the same as the
5657 // # elements of the compare (and the # elements of the compare result
5658 // for that matter). Check to see that they are the same size. If so,
5659 // we know that the element size of the sext'd result matches the
5660 // element size of the compare operands.
5661 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005662 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005663 N0.getOperand(1),
5664 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00005665 // If the desired elements are smaller or larger than the source
5666 // elements we can use a matching integer vector type and then
Hao Liuc636d152014-04-22 09:57:06 +00005667 // truncate/any extend
Evan Chengabd0ad52010-05-19 01:08:17 +00005668 else {
Hao Liuc636d152014-04-22 09:57:06 +00005669 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005670 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005671 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005672 N0.getOperand(1),
5673 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Hao Liuc636d152014-04-22 09:57:06 +00005674 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00005675 }
5676 }
5677
5678 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005679 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005680 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005681 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00005682 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005683 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00005684 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005685 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005686
Evan Chengf1005572010-04-28 07:10:39 +00005687 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00005688}
5689
Sanjay Patel50cbfc52014-08-28 16:29:51 +00005690/// See if the specified operand can be simplified with the knowledge that only
5691/// the bits specified by Mask are used. If so, return the simpler operand,
5692/// otherwise return a null SDValue.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005693SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00005694 switch (V.getOpcode()) {
5695 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00005696 case ISD::Constant: {
5697 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00005698 assert(CV && "Const value should be ConstSDNode.");
Lang Hamesb85fcd02011-11-08 18:56:23 +00005699 const APInt &CVal = CV->getAPIntValue();
5700 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00005701 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00005702 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00005703 break;
5704 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005705 case ISD::OR:
5706 case ISD::XOR:
5707 // If the LHS or RHS don't contribute bits to the or, drop them.
5708 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5709 return V.getOperand(1);
5710 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5711 return V.getOperand(0);
5712 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00005713 case ISD::SRL:
5714 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00005715 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00005716 break;
5717 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5718 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00005719 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005720
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00005721 // Watch out for shift count overflow though.
5722 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00005723 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005724 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005725 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005726 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00005727 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00005728 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005729 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005730 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00005731}
5732
Sanjay Patel50cbfc52014-08-28 16:29:51 +00005733/// If the result of a wider load is shifted to right of N bits and then
5734/// truncated to a narrower type and where N is a multiple of number of bits of
5735/// the narrower type, transform it to a narrower load from address + N / num of
5736/// bits of new type. If the result is to be extended, also fold the extension
5737/// to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005738SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005739 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00005740
Evan Cheng464dc9b2007-03-22 01:54:19 +00005741 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005742 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005743 EVT VT = N->getValueType(0);
5744 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005745
Dan Gohman550c9af2008-08-14 20:04:46 +00005746 // This transformation isn't valid for vector loads.
5747 if (VT.isVector())
5748 return SDValue();
5749
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005750 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00005751 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00005752 if (Opc == ISD::SIGN_EXTEND_INREG) {
5753 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00005754 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00005755 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00005756 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00005757 ExtType = ISD::ZEXTLOAD;
5758 N0 = SDValue(N, 0);
5759 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5760 if (!N01) return SDValue();
5761 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5762 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00005763 }
Richard Osborne272e0842011-01-31 17:41:44 +00005764 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5765 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005766
Owen Anderson53aa7a92009-08-10 22:56:29 +00005767 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005768
Chris Lattner9a499e92010-12-22 08:01:44 +00005769 // Do not generate loads of non-round integer types since these can
5770 // be expensive (and would be wrong if the type is not byte sized).
5771 if (!ExtVT.isRound())
5772 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005773
Evan Cheng464dc9b2007-03-22 01:54:19 +00005774 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00005775 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005776 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00005777 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005778 // Is the shift amount a multiple of size of VT?
5779 if ((ShAmt & (EVTBits-1)) == 0) {
5780 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00005781 // Is the load width a multiple of size of VT?
5782 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005783 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005784 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005785
Chris Lattnercafc1e62010-12-22 08:02:57 +00005786 // At this point, we must have a load or else we can't do the transform.
5787 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005788
Chandler Carruthb27041c2012-12-11 00:36:57 +00005789 // Because a SRL must be assumed to *need* to zero-extend the high bits
5790 // (as opposed to anyext the high bits), we can't combine the zextload
5791 // lowering of SRL and an sextload.
5792 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5793 return SDValue();
5794
Chris Lattnera2050552010-10-01 05:36:09 +00005795 // If the shift amount is larger than the input type then we're not
5796 // accessing any of the loaded bytes. If the load was a zextload/extload
5797 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00005798 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00005799 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005800 }
5801 }
5802
Dan Gohman68fb0042010-11-03 01:47:46 +00005803 // If the load is shifted left (and the result isn't shifted back right),
5804 // we can fold the truncate through the shift.
5805 unsigned ShLeftAmt = 0;
5806 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00005807 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005808 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5809 ShLeftAmt = N01->getZExtValue();
5810 N0 = N0.getOperand(0);
5811 }
5812 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00005813
Chris Lattner222374d2010-12-22 07:36:50 +00005814 // If we haven't found a load, we can't narrow it. Don't transform one with
5815 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00005816 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5817 return SDValue();
5818
5819 // Don't change the width of a volatile load.
5820 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5821 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00005822 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005823
Chris Lattner9a499e92010-12-22 08:01:44 +00005824 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00005825 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00005826 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005827
Bill Schmidtd006c692013-01-14 22:04:38 +00005828 // For the transform to be legal, the load must produce only two values
5829 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00005830 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00005831 // transformation is not equivalent, and the downstream logic to replace
5832 // uses gets things wrong.
5833 if (LN0->getNumValues() > 2)
5834 return SDValue();
5835
Benjamin Kramerc7332b22013-07-06 14:05:09 +00005836 // If the load that we're shrinking is an extload and we're not just
5837 // discarding the extension we can't simply shrink the load. Bail.
5838 // TODO: It would be possible to merge the extensions in some cases.
5839 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5840 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5841 return SDValue();
5842
Chris Lattner222374d2010-12-22 07:36:50 +00005843 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005844
Evan Cheng4c6f9172012-06-26 01:19:33 +00005845 if (PtrType == MVT::Untyped || PtrType.isExtended())
5846 // It's not possible to generate a constant of extended or untyped type.
5847 return SDValue();
5848
Chris Lattner222374d2010-12-22 07:36:50 +00005849 // For big endian targets, we need to adjust the offset to the pointer to
5850 // load the correct bytes.
5851 if (TLI.isBigEndian()) {
5852 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5853 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5854 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005855 }
5856
Chris Lattner222374d2010-12-22 07:36:50 +00005857 uint64_t PtrOff = ShAmt / 8;
5858 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005859 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00005860 PtrType, LN0->getBasePtr(),
5861 DAG.getConstant(PtrOff, PtrType));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005862 AddToWorklist(NewPtr.getNode());
Chris Lattner222374d2010-12-22 07:36:50 +00005863
Chris Lattner9a499e92010-12-22 08:01:44 +00005864 SDValue Load;
5865 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005866 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005867 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00005868 LN0->isVolatile(), LN0->isNonTemporal(),
Hal Finkelcc39b672014-07-24 12:16:19 +00005869 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00005870 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005871 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005872 LN0->getPointerInfo().getWithOffset(PtrOff),
5873 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00005874 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00005875
5876 // Replace the old load's chain with the new load's chain.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005877 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00005878 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00005879
5880 // Shift the result left, if we've swallowed a left shift.
5881 SDValue Result = Load;
5882 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00005883 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00005884 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5885 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00005886 // If the shift amount is as large as the result size (but, presumably,
5887 // no larger than the source) then the useful bits of the result are
5888 // zero; we can't simply return the shortened shift, because the result
5889 // of that operation is undefined.
5890 if (ShLeftAmt >= VT.getSizeInBits())
5891 Result = DAG.getConstant(0, VT);
5892 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005893 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00005894 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00005895 }
5896
5897 // Return the new loaded value.
5898 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005899}
5900
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005901SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5902 SDValue N0 = N->getOperand(0);
5903 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005904 EVT VT = N->getValueType(0);
5905 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00005906 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005907 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005908
Nate Begeman21158fc2005-09-01 00:19:25 +00005909 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00005910 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005911 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005912
Chris Lattner2a4d7b82006-05-06 22:43:44 +00005913 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00005914 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00005915 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005916
Nate Begeman7cea6ef2005-09-02 21:18:40 +00005917 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5918 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00005919 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005920 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005921 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00005922
Dan Gohman345d63c2008-07-31 00:50:31 +00005923 // fold (sext_in_reg (sext x)) -> (sext x)
5924 // fold (sext_in_reg (aext x)) -> (sext x)
5925 // if x is small enough.
5926 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5927 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00005928 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5929 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005930 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00005931 }
5932
Chris Lattner9ad59152007-04-17 19:03:21 +00005933 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00005934 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005935 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005936
Chris Lattner9ad59152007-04-17 19:03:21 +00005937 // fold operands of sext_in_reg based on knowledge that the top bits are not
5938 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005939 if (SimplifyDemandedBits(SDValue(N, 0)))
5940 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005941
Evan Cheng464dc9b2007-03-22 01:54:19 +00005942 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5943 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005944 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005945 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00005946 return NarrowLoad;
5947
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005948 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005949 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00005950 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5951 if (N0.getOpcode() == ISD::SRL) {
5952 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00005953 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005954 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00005955 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00005956 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00005957 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005958 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005959 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00005960 }
5961 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005962
Nate Begeman02b23c62005-10-13 03:11:28 +00005963 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00005964 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005965 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005966 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005967 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005968 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005969 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005970 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005971 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005972 LN0->getBasePtr(), EVT,
5973 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005974 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005975 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005976 AddToWorklist(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005977 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005978 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005979 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00005980 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005981 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005982 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005983 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005984 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005985 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005986 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005987 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005988 LN0->getBasePtr(), EVT,
5989 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005990 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005991 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005992 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005993 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00005994
5995 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5996 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5997 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5998 N0.getOperand(1), false);
Craig Topperc0196b12014-04-14 00:51:57 +00005999 if (BSwap.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006000 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00006001 BSwap, N1);
6002 }
6003
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006004 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6005 // into a build_vector.
6006 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6007 SmallVector<SDValue, 8> Elts;
6008 unsigned NumElts = N0->getNumOperands();
6009 unsigned ShAmt = VTBits - EVTBits;
6010
6011 for (unsigned i = 0; i != NumElts; ++i) {
6012 SDValue Op = N0->getOperand(i);
6013 if (Op->getOpcode() == ISD::UNDEF) {
6014 Elts.push_back(Op);
6015 continue;
6016 }
6017
6018 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00006019 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6020 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006021 Op.getValueType()));
6022 }
6023
Craig Topper48d114b2014-04-26 18:35:24 +00006024 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006025 }
6026
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006027 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006028}
6029
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006030SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6031 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006032 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006033 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00006034
6035 // noop truncate
6036 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00006037 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00006038 // fold (truncate c1) -> c1
Chris Lattner7e7bcf32006-05-06 23:06:26 +00006039 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006040 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006041 // fold (truncate (truncate x)) -> (truncate x)
6042 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006043 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00006044 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00006045 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6046 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00006047 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00006048 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006049 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00006050 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006051 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006052 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006053 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00006054 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006055 // if the source and dest are the same type, we can drop both the extend
6056 // and the truncate.
6057 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006058 }
Evan Chengd63baea2007-03-21 20:14:05 +00006059
Nadav Rotem4f4546b2012-02-05 11:39:23 +00006060 // Fold extract-and-trunc into a narrow extract. For example:
6061 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6062 // i32 y = TRUNCATE(i64 x)
6063 // -- becomes --
6064 // v16i8 b = BITCAST (v2i64 val)
6065 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6066 //
6067 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006068 // creates this pattern) and before operation legalization after which
6069 // we need to be more careful about the vector instructions that we generate.
6070 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00006071 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006072
6073 EVT VecTy = N0.getOperand(0).getValueType();
6074 EVT ExTy = N0.getValueType();
6075 EVT TrTy = N->getValueType(0);
6076
6077 unsigned NumElem = VecTy.getVectorNumElements();
6078 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6079
6080 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6081 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6082
6083 SDValue EltNo = N0->getOperand(1);
6084 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6085 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00006086 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006087 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6088
Andrew Trickef9de2a2013-05-25 02:42:55 +00006089 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006090 NVT, N0.getOperand(0));
6091
6092 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00006093 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00006094 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006095 }
6096 }
6097
Matt Arsenault3332b702014-07-10 18:21:04 +00006098 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6099 if (N0.getOpcode() == ISD::SELECT) {
6100 EVT SrcVT = N0.getValueType();
6101 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6102 TLI.isTruncateFree(SrcVT, VT)) {
6103 SDLoc SL(N0);
6104 SDValue Cond = N0.getOperand(0);
6105 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6106 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6107 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6108 }
6109 }
6110
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006111 // Fold a series of buildvector, bitcast, and truncate if possible.
6112 // For example fold
6113 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6114 // (2xi32 (buildvector x, y)).
6115 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6116 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6117 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6118 N0.getOperand(0).hasOneUse()) {
6119
6120 SDValue BuildVect = N0.getOperand(0);
6121 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6122 EVT TruncVecEltTy = VT.getVectorElementType();
6123
6124 // Check that the element types match.
6125 if (BuildVectEltTy == TruncVecEltTy) {
6126 // Now we only need to compute the offset of the truncated elements.
6127 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6128 unsigned TruncVecNumElts = VT.getVectorNumElements();
6129 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6130
6131 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6132 "Invalid number of elements");
6133
6134 SmallVector<SDValue, 8> Opnds;
6135 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6136 Opnds.push_back(BuildVect.getOperand(i));
6137
Craig Topper48d114b2014-04-26 18:35:24 +00006138 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006139 }
6140 }
6141
Chris Lattner5e6fe052007-10-13 06:35:54 +00006142 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00006143 // only the low bits are being used.
6144 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00006145 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00006146 // may have different active low bits.
6147 if (!VT.isVector()) {
6148 SDValue Shorter =
6149 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6150 VT.getSizeInBits()));
6151 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006152 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00006153 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00006154 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00006155 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00006156 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6157 SDValue Reduced = ReduceLoadWidth(N);
6158 if (Reduced.getNode())
6159 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00006160 // Handle the case where the load remains an extending load even
6161 // after truncation.
6162 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6163 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6164 if (!LN0->isVolatile() &&
6165 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6166 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6167 VT, LN0->getChain(), LN0->getBasePtr(),
6168 LN0->getMemoryVT(),
6169 LN0->getMemOperand());
6170 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6171 return NewLoad;
6172 }
6173 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006174 }
Michael Liao3ac82012012-10-17 23:45:54 +00006175 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6176 // where ... are all 'undef'.
6177 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6178 SmallVector<EVT, 8> VTs;
6179 SDValue V;
6180 unsigned Idx = 0;
6181 unsigned NumDefs = 0;
6182
6183 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6184 SDValue X = N0.getOperand(i);
6185 if (X.getOpcode() != ISD::UNDEF) {
6186 V = X;
6187 Idx = i;
6188 NumDefs++;
6189 }
6190 // Stop if more than one members are non-undef.
6191 if (NumDefs > 1)
6192 break;
6193 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6194 VT.getVectorElementType(),
6195 X.getValueType().getVectorNumElements()));
6196 }
6197
6198 if (NumDefs == 0)
6199 return DAG.getUNDEF(VT);
6200
6201 if (NumDefs == 1) {
6202 assert(V.getNode() && "The single defined operand is empty!");
6203 SmallVector<SDValue, 8> Opnds;
6204 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6205 if (i != Idx) {
6206 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6207 continue;
6208 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006209 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006210 AddToWorklist(NV.getNode());
Michael Liao3ac82012012-10-17 23:45:54 +00006211 Opnds.push_back(NV);
6212 }
Craig Topper48d114b2014-04-26 18:35:24 +00006213 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
Michael Liao3ac82012012-10-17 23:45:54 +00006214 }
6215 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006216
6217 // Simplify the operands using demanded-bits information.
6218 if (!VT.isVector() &&
6219 SimplifyDemandedBits(SDValue(N, 0)))
6220 return SDValue(N, 0);
6221
Evan Chengf1bd5fc2010-04-17 06:13:15 +00006222 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006223}
6224
Evan Chengb980f6f2008-05-12 23:04:07 +00006225static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006226 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00006227 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006228 return Elt.getNode();
6229 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00006230}
6231
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006232/// build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00006233/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00006234SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00006235 assert(N->getOpcode() == ISD::BUILD_PAIR);
6236
Nate Begeman624690c2009-06-05 21:37:30 +00006237 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6238 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006239 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00006240 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006241 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00006242 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00006243
Evan Chengb980f6f2008-05-12 23:04:07 +00006244 if (ISD::isNON_EXTLoad(LD2) &&
6245 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006246 // If both are volatile this would reduce the number of volatile loads.
6247 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00006248 !LD1->isVolatile() &&
6249 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00006250 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00006251 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006252 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006253 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00006254
Duncan Sands8651e9c2008-06-13 19:07:40 +00006255 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006256 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006257 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006258 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006259 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00006260 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00006261
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006262 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00006263}
6264
Wesley Peck527da1b2010-11-23 03:31:01 +00006265SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006266 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006267 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00006268
Dan Gohmana8665142007-06-25 16:23:39 +00006269 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6270 // Only do this before legalize, since afterward the target may be depending
6271 // on the bitconvert.
6272 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006273 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006274 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006275 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00006276 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006277
Owen Anderson53aa7a92009-08-10 22:56:29 +00006278 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006279 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00006280 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00006281 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00006282 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00006283 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006284
Dan Gohman921ddd62008-09-05 01:58:21 +00006285 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00006286 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006287 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Dan Gohman733a64d2009-08-10 23:15:10 +00006288 if (Res.getNode() != N) {
6289 if (!LegalOperations ||
6290 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6291 return Res;
6292
6293 // Folding it resulted in an illegal node, and it's too late to
6294 // do that. Clean up the old node and forego the transformation.
6295 // Ideally this won't happen very often, because instcombine
6296 // and the earlier dagcombine runs (where illegal nodes are
6297 // permitted) should have folded most of them already.
Chandler Carruth18066972014-08-02 10:02:07 +00006298 deleteAndRecombine(Res.getNode());
Dan Gohman733a64d2009-08-10 23:15:10 +00006299 }
Chris Lattnera1874602005-12-23 05:30:37 +00006300 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006301
Bill Wendling4e0a6152009-01-30 22:44:24 +00006302 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00006303 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006304 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006305 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006306
Chris Lattner54560f62005-12-23 05:44:41 +00006307 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00006308 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00006309 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006310 // Do not change the width of a volatile load.
6311 !cast<LoadSDNode>(N0)->isVolatile() &&
Ulrich Weigandf236bb12014-07-03 15:06:47 +00006312 // Do not remove the cast if the types differ in endian layout.
6313 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6314 TLI.hasBigEndianPartOrdering(VT) &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00006315 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6316 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006317 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006318 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006319 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006320 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00006321
Evan Chenga4cf58a2007-05-07 21:27:48 +00006322 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006323 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006324 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00006325 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006326 LN0->isInvariant(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00006327 LN0->getAAInfo());
Chandler Carruth7cd15be2014-08-14 08:18:34 +00006328 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006329 return Load;
6330 }
Chris Lattner54560f62005-12-23 05:44:41 +00006331 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006332
Bill Wendling4e0a6152009-01-30 22:44:24 +00006333 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6334 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00006335 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00006336 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6337 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00006338 N0.getNode()->hasOneUse() && VT.isInteger() &&
6339 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006340 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006341 N0.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006342 AddToWorklist(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00006343
Duncan Sands13237ac2008-06-06 12:08:01 +00006344 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00006345 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006346 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006347 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006348 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006349 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006350 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006351 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006352
Bill Wendling4e0a6152009-01-30 22:44:24 +00006353 // fold (bitconvert (fcopysign cst, x)) ->
6354 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6355 // Note that we don't handle (copysign x, cst) because this can always be
6356 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006357 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00006358 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006359 VT.isInteger() && !VT.isVector()) {
6360 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00006361 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00006362 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006363 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006364 IntXVT, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006365 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006366
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006367 // If X has a different width than the result/lhs, sext it or truncate it.
6368 unsigned VTWidth = VT.getSizeInBits();
6369 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006370 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006371 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006372 } else if (OrigXWidth > VTWidth) {
6373 // To get the sign bit in the right place, we have to shift it right
6374 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006375 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006376 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006377 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006378 AddToWorklist(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006379 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006380 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006381 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006382
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006383 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006384 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006385 X, DAG.getConstant(SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006386 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006387
Andrew Trickef9de2a2013-05-25 02:42:55 +00006388 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006389 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006390 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006391 Cst, DAG.getConstant(~SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006392 AddToWorklist(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006393
Andrew Trickef9de2a2013-05-25 02:42:55 +00006394 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006395 }
Chris Lattner888560d2008-01-27 17:42:27 +00006396 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006397
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006398 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006399 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006400 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6401 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006402 return CombineLD;
6403 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006404
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006405 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006406}
6407
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006408SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006409 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006410 return CombineConsecutiveLoads(N, VT);
6411}
6412
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006413/// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6414/// operands. DstEltVT indicates the destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006415SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006416ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006417 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006418
Chris Lattnere4e64b62006-04-02 02:53:43 +00006419 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006420 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006421
Duncan Sands13237ac2008-06-06 12:08:01 +00006422 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6423 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006424
Chris Lattnere4e64b62006-04-02 02:53:43 +00006425 // If this is a conversion of N elements of one type to N elements of another
6426 // type, convert each element. This handles FP<->INT cases.
6427 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006428 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6429 BV->getValueType(0).getVectorNumElements());
6430
6431 // Due to the FP element handling below calling this routine recursively,
6432 // we can end up with a scalar-to-vector node here.
6433 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006434 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6435 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006436 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006437
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006438 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006439 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006440 SDValue Op = BV->getOperand(i);
6441 // If the vector element type is not legal, the BUILD_VECTOR operands
6442 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006443 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006444 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6445 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006446 DstEltVT, Op));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006447 AddToWorklist(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006448 }
Craig Topper48d114b2014-04-26 18:35:24 +00006449 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006450 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006451
Chris Lattnere4e64b62006-04-02 02:53:43 +00006452 // Otherwise, we're growing or shrinking the elements. To avoid having to
6453 // handle annoying details of growing/shrinking FP values, we convert them to
6454 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006455 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006456 // Convert the input float vector to a int vector where the elements are the
6457 // same sizes.
Owen Anderson9f944592009-08-11 20:47:22 +00006458 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006459 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006460 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006461 SrcEltVT = IntVT;
6462 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006463
Chris Lattnere4e64b62006-04-02 02:53:43 +00006464 // Now we know the input is an integer vector. If the output is a FP type,
6465 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006466 if (DstEltVT.isFloatingPoint()) {
Owen Anderson9f944592009-08-11 20:47:22 +00006467 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006468 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006469 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006470
Chris Lattnere4e64b62006-04-02 02:53:43 +00006471 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00006472 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006473 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006474
Chris Lattnere4e64b62006-04-02 02:53:43 +00006475 // Okay, we know the src/dst types are both integers of differing types.
6476 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006477 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006478 if (SrcBitSize < DstBitSize) {
6479 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006480
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006481 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006482 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00006483 i += NumInputsPerOutput) {
6484 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00006485 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006486 bool EltIsUndef = true;
6487 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6488 // Shift the previously computed bits over.
6489 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006490 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006491 if (Op.getOpcode() == ISD::UNDEF) continue;
6492 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006493
Jay Foad583abbc2010-12-07 08:25:19 +00006494 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00006495 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006496 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006497
Chris Lattnere4e64b62006-04-02 02:53:43 +00006498 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00006499 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006500 else
6501 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6502 }
6503
Owen Anderson117c9e82009-08-12 00:36:31 +00006504 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Craig Topper48d114b2014-04-26 18:35:24 +00006505 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006506 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006507
Chris Lattnere4e64b62006-04-02 02:53:43 +00006508 // Finally, this must be the case where we are shrinking elements: each input
6509 // turns into multiple outputs.
Evan Cheng6200c222008-02-18 23:04:32 +00006510 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006511 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00006512 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6513 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006514 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006515
Dan Gohmana8665142007-06-25 16:23:39 +00006516 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006517 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6518 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesen84935752009-02-06 23:05:02 +00006519 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006520 continue;
6521 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006522
Jay Foad583abbc2010-12-07 08:25:19 +00006523 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6524 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006525
Chris Lattnere4e64b62006-04-02 02:53:43 +00006526 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00006527 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006528 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad583abbc2010-12-07 08:25:19 +00006529 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Cheng6200c222008-02-18 23:04:32 +00006530 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006531 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006532 Ops[0]);
Dan Gohmane1c4f992008-03-03 23:51:38 +00006533 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006534 }
6535
6536 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00006537 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00006538 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6539 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006540
Craig Topper48d114b2014-04-26 18:35:24 +00006541 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006542}
6543
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006544SDValue DAGCombiner::visitFADD(SDNode *N) {
6545 SDValue N0 = N->getOperand(0);
6546 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006547 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6548 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006549 EVT VT = N->getValueType(0);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006550 const TargetOptions &Options = DAG.getTarget().Options;
Sanjay Patel159f1272014-08-27 21:42:42 +00006551
Dan Gohmana8665142007-06-25 16:23:39 +00006552 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006553 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006554 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006555 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006556 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006557
Lang Hamesa33db652012-06-14 20:37:15 +00006558 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006559 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006560 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Sanjay Patel8170dea2014-09-08 17:32:19 +00006561
Nate Begeman418c6e42005-10-18 00:28:13 +00006562 // canonicalize constant to RHS
6563 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006564 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Sanjay Patel8170dea2014-09-08 17:32:19 +00006565
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006566 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006567 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00006568 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006569 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006570 GetNegatedExpression(N1, DAG, LegalOperations));
Sanjay Patel8170dea2014-09-08 17:32:19 +00006571
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006572 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006573 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00006574 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006575 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006576 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006577
Sanjay Patel8170dea2014-09-08 17:32:19 +00006578 // If 'unsafe math' is enabled, fold lots of things.
6579 if (Options.UnsafeFPMath) {
6580 // No FP constant should be created after legalization as Instruction
6581 // Selection pass has a hard time dealing with FP constants.
6582 bool AllowNewConst = (Level < AfterLegalizeDAG);
6583
6584 // fold (fadd A, 0) -> A
6585 if (N1CFP && N1CFP->getValueAPF().isZero())
6586 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006587
Sanjay Patel8170dea2014-09-08 17:32:19 +00006588 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6589 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6590 isa<ConstantFPSDNode>(N0.getOperand(1)))
6591 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6592 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6593 N0.getOperand(1), N1));
6594
6595 // If allowed, fold (fadd (fneg x), x) -> 0.0
6596 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6597 return DAG.getConstantFP(0.0, VT);
6598
6599 // If allowed, fold (fadd x, (fneg x)) -> 0.0
6600 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6601 return DAG.getConstantFP(0.0, VT);
6602
6603 // We can fold chains of FADD's of the same value into multiplications.
6604 // This transform is not safe in general because we are reducing the number
6605 // of rounding steps.
Sanjay Patel8170dea2014-09-08 17:32:19 +00006606 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6607 if (N0.getOpcode() == ISD::FMUL) {
6608 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6609 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6610
Sanjay Patel8170dea2014-09-08 17:32:19 +00006611 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6612 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6613 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6614 SDValue(CFP01, 0),
6615 DAG.getConstantFP(1.0, VT));
6616 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6617 }
Sanjay Patel8170dea2014-09-08 17:32:19 +00006618
6619 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6620 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6621 N1.getOperand(0) == N1.getOperand(1) &&
6622 N0.getOperand(0) == N1.getOperand(0)) {
6623 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6624 SDValue(CFP01, 0),
6625 DAG.getConstantFP(2.0, VT));
6626 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6627 N0.getOperand(0), NewCFP);
6628 }
Owen Andersoncc61f872012-08-30 23:35:16 +00006629 }
Sanjay Patel8170dea2014-09-08 17:32:19 +00006630
6631 if (N1.getOpcode() == ISD::FMUL) {
6632 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6633 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6634
Sanjay Patel8170dea2014-09-08 17:32:19 +00006635 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6636 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6637 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6638 SDValue(CFP11, 0),
6639 DAG.getConstantFP(1.0, VT));
6640 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6641 }
Sanjay Patelf4b7a6b2014-09-08 18:22:51 +00006642
Sanjay Patel8170dea2014-09-08 17:32:19 +00006643 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6644 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6645 N0.getOperand(0) == N0.getOperand(1) &&
6646 N1.getOperand(0) == N0.getOperand(0)) {
6647 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6648 SDValue(CFP11, 0),
6649 DAG.getConstantFP(2.0, VT));
6650 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6651 }
Owen Andersoncc61f872012-08-30 23:35:16 +00006652 }
Sanjay Patelf4b7a6b2014-09-08 18:22:51 +00006653
Sanjay Patel8170dea2014-09-08 17:32:19 +00006654 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6655 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6656 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6657 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6658 (N0.getOperand(0) == N1))
6659 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6660 N1, DAG.getConstantFP(3.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006661 }
Sanjay Patel8170dea2014-09-08 17:32:19 +00006662
6663 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6664 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6665 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6666 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6667 N1.getOperand(0) == N0)
6668 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6669 N0, DAG.getConstantFP(3.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006670 }
Sanjay Patel8170dea2014-09-08 17:32:19 +00006671
6672 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6673 if (AllowNewConst &&
6674 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Stephen Line31f2d22013-06-14 18:17:35 +00006675 N0.getOperand(0) == N0.getOperand(1) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00006676 N1.getOperand(0) == N1.getOperand(1) &&
6677 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006678 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Sanjay Patel8170dea2014-09-08 17:32:19 +00006679 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006680 }
Sanjay Patel8170dea2014-09-08 17:32:19 +00006681 } // enable-unsafe-fp-math
6682
Lang Hames39fb1d02012-06-19 22:51:23 +00006683 // FADD -> FMA combines:
Sanjay Patel78614bf2014-08-28 15:53:16 +00006684 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
Eric Christopherd9134482014-08-04 21:25:23 +00006685 DAG.getTarget()
6686 .getSubtargetImpl()
6687 ->getTargetLowering()
6688 ->isFMAFasterThanFMulAndFAdd(VT) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006689 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006690
6691 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Hal Finkel62ac7362014-09-19 11:42:56 +00006692 if (N0.getOpcode() == ISD::FMUL &&
6693 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006694 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006695 N0.getOperand(0), N0.getOperand(1), N1);
Owen Andersoncc61f872012-08-30 23:35:16 +00006696
Michael Liaoec3850122012-09-01 04:09:16 +00006697 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hames39fb1d02012-06-19 22:51:23 +00006698 // Note: Commutes FADD operands.
Hal Finkel62ac7362014-09-19 11:42:56 +00006699 if (N1.getOpcode() == ISD::FMUL &&
6700 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006701 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006702 N1.getOperand(0), N1.getOperand(1), N0);
Lang Hames39fb1d02012-06-19 22:51:23 +00006703 }
6704
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006705 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006706}
6707
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006708SDValue DAGCombiner::visitFSUB(SDNode *N) {
6709 SDValue N0 = N->getOperand(0);
6710 SDValue N1 = N->getOperand(1);
Sanjay Patel75cc90e2014-09-05 22:26:22 +00006711 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6712 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006713 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006714 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006715 const TargetOptions &Options = DAG.getTarget().Options;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006716
Dan Gohmana8665142007-06-25 16:23:39 +00006717 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006718 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006719 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006720 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006721 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006722
Nate Begeman418c6e42005-10-18 00:28:13 +00006723 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006724 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006725 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Sanjay Patelae402a32014-08-27 20:57:52 +00006726
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006727 // fold (fsub A, (fneg B)) -> (fadd A, B)
Sanjay Patel78614bf2014-08-28 15:53:16 +00006728 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006729 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006730 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006731
Sanjay Patelae402a32014-08-27 20:57:52 +00006732 // If 'unsafe math' is enabled, fold lots of things.
Sanjay Patel78614bf2014-08-28 15:53:16 +00006733 if (Options.UnsafeFPMath) {
Sanjay Patelae402a32014-08-27 20:57:52 +00006734 // (fsub A, 0) -> A
6735 if (N1CFP && N1CFP->getValueAPF().isZero())
6736 return N0;
6737
6738 // (fsub 0, B) -> -B
6739 if (N0CFP && N0CFP->getValueAPF().isZero()) {
Sanjay Patel78614bf2014-08-28 15:53:16 +00006740 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Sanjay Patelae402a32014-08-27 20:57:52 +00006741 return GetNegatedExpression(N1, DAG, LegalOperations);
6742 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6743 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6744 }
6745
6746 // (fsub x, x) -> 0.0
Owen Andersonab63d842012-05-07 20:51:25 +00006747 if (N0 == N1)
6748 return DAG.getConstantFP(0.0f, VT);
6749
Sanjay Patelae402a32014-08-27 20:57:52 +00006750 // (fsub x, (fadd x, y)) -> (fneg y)
6751 // (fsub x, (fadd y, x)) -> (fneg y)
Bill Wendlingdf170db2012-03-15 05:12:00 +00006752 if (N1.getOpcode() == ISD::FADD) {
6753 SDValue N10 = N1->getOperand(0);
6754 SDValue N11 = N1->getOperand(1);
6755
Sanjay Patel78614bf2014-08-28 15:53:16 +00006756 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006757 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00006758
Sanjay Patel78614bf2014-08-28 15:53:16 +00006759 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006760 return GetNegatedExpression(N10, DAG, LegalOperations);
6761 }
6762 }
6763
Lang Hames39fb1d02012-06-19 22:51:23 +00006764 // FSUB -> FMA combines:
Sanjay Patel78614bf2014-08-28 15:53:16 +00006765 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
Sanjay Patela828f2b2014-08-27 20:40:31 +00006766 DAG.getTarget().getSubtargetImpl()
Eric Christopherd9134482014-08-04 21:25:23 +00006767 ->getTargetLowering()
6768 ->isFMAFasterThanFMulAndFAdd(VT) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006769 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006770
6771 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Hal Finkel62ac7362014-09-19 11:42:56 +00006772 if (N0.getOpcode() == ISD::FMUL &&
6773 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006774 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006775 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006776 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hames39fb1d02012-06-19 22:51:23 +00006777
6778 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6779 // Note: Commutes FSUB operands.
Hal Finkel62ac7362014-09-19 11:42:56 +00006780 if (N1.getOpcode() == ISD::FMUL &&
6781 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006782 return DAG.getNode(ISD::FMA, dl, VT,
6783 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006784 N1.getOperand(0)),
6785 N1.getOperand(1), N0);
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006786
Stephen Lin8e8424e2013-07-09 00:44:49 +00006787 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lincfe7f352013-07-08 00:37:03 +00006788 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006789 N0.getOperand(0).getOpcode() == ISD::FMUL &&
Hal Finkel62ac7362014-09-19 11:42:56 +00006790 ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
6791 TLI.enableAggressiveFMAFusion(VT))) {
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006792 SDValue N00 = N0.getOperand(0).getOperand(0);
6793 SDValue N01 = N0.getOperand(0).getOperand(1);
6794 return DAG.getNode(ISD::FMA, dl, VT,
6795 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6796 DAG.getNode(ISD::FNEG, dl, VT, N1));
6797 }
Lang Hames39fb1d02012-06-19 22:51:23 +00006798 }
6799
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006800 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006801}
6802
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006803SDValue DAGCombiner::visitFMUL(SDNode *N) {
6804 SDValue N0 = N->getOperand(0);
6805 SDValue N1 = N->getOperand(1);
Matt Arsenault6cc00422014-08-16 10:14:19 +00006806 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6807 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006808 EVT VT = N->getValueType(0);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006809 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00006810
Dan Gohmana8665142007-06-25 16:23:39 +00006811 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006812 if (VT.isVector()) {
Sanjay Patel7bd228a2014-09-11 15:45:27 +00006813 // This just handles C1 * C2 for vectors. Other vector folds are below.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006814 SDValue FoldedVOp = SimplifyVBinOp(N);
Sanjay Patel7bd228a2014-09-11 15:45:27 +00006815 if (FoldedVOp.getNode())
6816 return FoldedVOp;
6817 // Canonicalize vector constant to RHS.
6818 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
6819 N1.getOpcode() != ISD::BUILD_VECTOR)
6820 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
6821 if (BV0->isConstant())
6822 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
Dan Gohman80f9f072007-07-13 20:03:40 +00006823 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006824
Nate Begemanec48a1b2005-10-17 20:40:11 +00006825 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006826 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006827 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Sanjay Patel394c3332014-09-08 20:16:42 +00006828
Nate Begemanec48a1b2005-10-17 20:40:11 +00006829 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00006830 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006831 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Sanjay Patel394c3332014-09-08 20:16:42 +00006832
Owen Andersonb5f167c2012-05-02 21:32:35 +00006833 // fold (fmul A, 1.0) -> A
6834 if (N1CFP && N1CFP->isExactlyValue(1.0))
6835 return N0;
Matt Arsenault6cc00422014-08-16 10:14:19 +00006836
Sanjay Patel394c3332014-09-08 20:16:42 +00006837 if (Options.UnsafeFPMath) {
6838 // fold (fmul A, 0) -> 0
6839 if (N1CFP && N1CFP->getValueAPF().isZero())
6840 return N1;
6841
6842 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Sanjay Patel7bd228a2014-09-11 15:45:27 +00006843 if (N0.getOpcode() == ISD::FMUL) {
6844 // Fold scalars or any vector constants (not just splats).
6845 // This fold is done in general by InstCombine, but extra fmul insts
6846 // may have been generated during lowering.
6847 SDValue N01 = N0.getOperand(1);
6848 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
6849 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
6850 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
6851 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
6852 SDLoc SL(N);
6853 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
6854 return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
6855 }
Matt Arsenaultc1a71212014-09-02 19:02:53 +00006856 }
6857
Sanjay Patel394c3332014-09-08 20:16:42 +00006858 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
Matt Arsenaultc1a71212014-09-02 19:02:53 +00006859 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
6860 // during an early run of DAGCombiner can prevent folding with fmuls
6861 // inserted during lowering.
6862 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
6863 SDLoc SL(N);
6864 const SDValue Two = DAG.getConstantFP(2.0, VT);
6865 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
6866 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
6867 }
6868 }
6869
Nate Begemanec48a1b2005-10-17 20:40:11 +00006870 // fold (fmul X, 2.0) -> (fadd X, X)
6871 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006872 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Sanjay Patel394c3332014-09-08 20:16:42 +00006873
Dan Gohmanb7170912009-08-10 16:50:32 +00006874 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00006875 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00006876 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006877 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006878
Bill Wendling3dc5d242009-01-30 22:57:07 +00006879 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00006880 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
6881 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006882 // Both can be negated for free, check to see if at least one is cheaper
6883 // negated.
6884 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006885 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006886 GetNegatedExpression(N0, DAG, LegalOperations),
6887 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006888 }
6889 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006890
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006891 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006892}
6893
Owen Anderson41b06652012-05-02 22:17:40 +00006894SDValue DAGCombiner::visitFMA(SDNode *N) {
6895 SDValue N0 = N->getOperand(0);
6896 SDValue N1 = N->getOperand(1);
6897 SDValue N2 = N->getOperand(2);
6898 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6899 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6900 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006901 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006902 const TargetOptions &Options = DAG.getTarget().Options;
Owen Anderson9d5a8c22014-08-02 08:45:33 +00006903
6904 // Constant fold FMA.
6905 if (isa<ConstantFPSDNode>(N0) &&
6906 isa<ConstantFPSDNode>(N1) &&
6907 isa<ConstantFPSDNode>(N2)) {
6908 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6909 }
6910
Sanjay Patel78614bf2014-08-28 15:53:16 +00006911 if (Options.UnsafeFPMath) {
Owen Andersonb351c8d2012-11-01 02:00:53 +00006912 if (N0CFP && N0CFP->isZero())
6913 return N2;
6914 if (N1CFP && N1CFP->isZero())
6915 return N2;
6916 }
Owen Anderson41b06652012-05-02 22:17:40 +00006917 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006918 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006919 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006920 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006921
Owen Andersonc7aaf522012-05-30 18:50:39 +00006922 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00006923 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006924 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00006925
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006926 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
Sanjay Patel78614bf2014-08-28 15:53:16 +00006927 if (Options.UnsafeFPMath && N1CFP &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006928 N2.getOpcode() == ISD::FMUL &&
6929 N0 == N2.getOperand(0) &&
6930 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6931 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6932 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6933 }
6934
6935
6936 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00006937 if (Options.UnsafeFPMath &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006938 N0.getOpcode() == ISD::FMUL && N1CFP &&
6939 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6940 return DAG.getNode(ISD::FMA, dl, VT,
6941 N0.getOperand(0),
6942 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6943 N2);
6944 }
6945
6946 // (fma x, 1, y) -> (fadd x, y)
6947 // (fma x, -1, y) -> (fadd (fneg x), y)
6948 if (N1CFP) {
6949 if (N1CFP->isExactlyValue(1.0))
6950 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6951
6952 if (N1CFP->isExactlyValue(-1.0) &&
6953 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6954 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006955 AddToWorklist(RHSNeg.getNode());
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006956 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6957 }
6958 }
6959
6960 // (fma x, c, x) -> (fmul x, (c+1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00006961 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
Stephen Lin8e8424e2013-07-09 00:44:49 +00006962 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006963 DAG.getNode(ISD::FADD, dl, VT,
6964 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006965
6966 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00006967 if (Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006968 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6969 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006970 DAG.getNode(ISD::FADD, dl, VT,
6971 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006972
6973
Owen Anderson41b06652012-05-02 22:17:40 +00006974 return SDValue();
6975}
6976
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006977SDValue DAGCombiner::visitFDIV(SDNode *N) {
6978 SDValue N0 = N->getOperand(0);
6979 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006980 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6981 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006982 EVT VT = N->getValueType(0);
Sanjay Patelbdf1e382014-09-26 23:01:47 +00006983 SDLoc DL(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006984 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00006985
Dan Gohmana8665142007-06-25 16:23:39 +00006986 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006987 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006988 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006989 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006990 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006991
Nate Begeman569c4392006-01-18 22:35:16 +00006992 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006993 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006994 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006995
Sanjay Patelb67bd262014-09-21 15:19:15 +00006996 if (Options.UnsafeFPMath) {
6997 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6998 if (N1CFP) {
6999 // Compute the reciprocal 1.0 / c2.
7000 APFloat N1APF = N1CFP->getValueAPF();
7001 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7002 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7003 // Only do the transform if the reciprocal is a legal fp immediate that
7004 // isn't too nasty (eg NaN, denormal, ...).
7005 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7006 (!LegalOperations ||
7007 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7008 // backend)... we should handle this gracefully after Legalize.
7009 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7010 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7011 TLI.isFPImmLegal(Recip, VT)))
7012 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7013 DAG.getConstantFP(Recip, VT));
7014 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007015
Sanjay Patelb67bd262014-09-21 15:19:15 +00007016 // If this FDIV is part of a reciprocal square root, it may be folded
7017 // into a target-specific square root estimate instruction.
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007018 if (N1.getOpcode() == ISD::FSQRT) {
7019 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7020 AddToWorklist(RV.getNode());
7021 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7022 }
7023 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7024 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7025 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7026 AddToWorklist(RV.getNode());
7027 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7028 AddToWorklist(RV.getNode());
7029 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7030 }
7031 } else if (N1.getOpcode() == ISD::FP_ROUND &&
7032 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7033 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7034 AddToWorklist(RV.getNode());
7035 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7036 AddToWorklist(RV.getNode());
7037 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7038 }
7039 }
7040
7041 // Fold into a reciprocal estimate and multiply instead of a real divide.
7042 if (SDValue RV = BuildReciprocalEstimate(N1)) {
7043 AddToWorklist(RV.getNode());
7044 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7045 }
Duncan Sands5f8397a2012-04-07 20:04:00 +00007046 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007047
Bill Wendling3dc5d242009-01-30 22:57:07 +00007048 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007049 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7050 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00007051 // Both can be negated for free, check to see if at least one is cheaper
7052 // negated.
7053 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007054 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007055 GetNegatedExpression(N0, DAG, LegalOperations),
7056 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00007057 }
7058 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007059
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007060 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007061}
7062
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007063SDValue DAGCombiner::visitFREM(SDNode *N) {
7064 SDValue N0 = N->getOperand(0);
7065 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007066 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7067 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007068 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00007069
Nate Begeman569c4392006-01-18 22:35:16 +00007070 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007071 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007072 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00007073
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007074 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007075}
7076
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007077SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7078 if (DAG.getTarget().Options.UnsafeFPMath) {
7079 // Compute this as 1/(1/sqrt(X)): the reciprocal of the reciprocal sqrt.
7080 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7081 AddToWorklist(RV.getNode());
7082 RV = BuildReciprocalEstimate(RV);
7083 if (RV.getNode()) {
7084 // Unfortunately, RV is now NaN if the input was exactly 0.
7085 // Select out this case and force the answer to 0.
7086 EVT VT = RV.getValueType();
7087
7088 SDValue Zero = DAG.getConstantFP(0.0, VT);
7089 SDValue ZeroCmp =
7090 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7091 N->getOperand(0), Zero, ISD::SETEQ);
7092 AddToWorklist(ZeroCmp.getNode());
7093 AddToWorklist(RV.getNode());
7094
7095 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7096 SDLoc(N), VT, ZeroCmp, Zero, RV);
7097 return RV;
7098 }
7099 }
7100 }
7101 return SDValue();
7102}
7103
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007104SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7105 SDValue N0 = N->getOperand(0);
7106 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007107 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7108 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007109 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00007110
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007111 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00007112 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007113
Chris Lattner3bc40502006-03-05 05:30:57 +00007114 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00007115 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00007116 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7117 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00007118 if (!V.isNegative()) {
7119 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007120 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00007121 } else {
7122 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007123 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7124 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00007125 }
Chris Lattner3bc40502006-03-05 05:30:57 +00007126 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007127
Chris Lattner3bc40502006-03-05 05:30:57 +00007128 // copysign(fabs(x), y) -> copysign(x, y)
7129 // copysign(fneg(x), y) -> copysign(x, y)
7130 // copysign(copysign(x,z), y) -> copysign(x, y)
7131 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7132 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007133 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007134 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007135
7136 // copysign(x, abs(y)) -> abs(x)
7137 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007138 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007139
Chris Lattner3bc40502006-03-05 05:30:57 +00007140 // copysign(x, copysign(y,z)) -> copysign(x, z)
7141 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007142 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007143 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007144
Chris Lattner3bc40502006-03-05 05:30:57 +00007145 // copysign(x, fp_extend(y)) -> copysign(x, y)
7146 // copysign(x, fp_round(y)) -> copysign(x, y)
7147 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007148 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007149 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007150
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007151 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00007152}
7153
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007154SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7155 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007156 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007157 EVT VT = N->getValueType(0);
7158 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007159
Nate Begeman21158fc2005-09-01 00:19:25 +00007160 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007161 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007162 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007163 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007164 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007165 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007166
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007167 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7168 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007169 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7170 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007171 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007172 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007173 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007174 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007175
Alp Tokercb402912014-01-24 17:20:08 +00007176 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007177 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007178 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7179 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7180 !VT.isVector() &&
7181 (!LegalOperations ||
7182 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7183 SDValue Ops[] =
7184 { N0.getOperand(0), N0.getOperand(1),
7185 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7186 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007187 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007188 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007189
Nadav Rotem90560762012-07-23 07:59:50 +00007190 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7191 // (select_cc x, y, 1.0, 0.0,, cc)
7192 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7193 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7194 (!LegalOperations ||
7195 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7196 SDValue Ops[] =
7197 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7198 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7199 N0.getOperand(0).getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007200 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007201 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007202 }
7203
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007204 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007205}
7206
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007207SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7208 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007209 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007210 EVT VT = N->getValueType(0);
7211 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00007212
Nate Begeman21158fc2005-09-01 00:19:25 +00007213 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007214 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007215 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007216 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007217 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007218 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007219
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007220 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7221 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007222 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7223 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007224 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007225 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007226 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007227 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007228
Alp Tokercb402912014-01-24 17:20:08 +00007229 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007230 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007231 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00007232
Nadav Rotem90560762012-07-23 07:59:50 +00007233 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7234 (!LegalOperations ||
7235 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7236 SDValue Ops[] =
7237 { N0.getOperand(0), N0.getOperand(1),
7238 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7239 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007240 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007241 }
7242 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007243
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007244 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007245}
7246
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007247SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7248 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007249 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007250 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007251
Nate Begeman21158fc2005-09-01 00:19:25 +00007252 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007253 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007254 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007255
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007256 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007257}
7258
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007259SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7260 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007261 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007262 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007263
Nate Begeman21158fc2005-09-01 00:19:25 +00007264 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007265 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007266 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007267
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007268 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007269}
7270
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007271SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7272 SDValue N0 = N->getOperand(0);
7273 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007274 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007275 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007276
Nate Begeman21158fc2005-09-01 00:19:25 +00007277 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007278 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007279 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007280
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007281 // fold (fp_round (fp_extend x)) -> x
7282 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7283 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007284
Chris Lattner0feb1b02008-01-24 06:45:35 +00007285 // fold (fp_round (fp_round x)) -> (fp_round x)
7286 if (N0.getOpcode() == ISD::FP_ROUND) {
7287 // This is a value preserving truncation if both round's are.
7288 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00007289 N0.getNode()->getConstantOperandVal(1) == 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00007290 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0feb1b02008-01-24 06:45:35 +00007291 DAG.getIntPtrConstant(IsTrunc));
7292 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007293
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007294 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00007295 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007296 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007297 N0.getOperand(0), N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007298 AddToWorklist(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007299 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007300 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007301 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007302
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007303 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007304}
7305
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007306SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7307 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007308 EVT VT = N->getValueType(0);
7309 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007310 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007311
Nate Begeman21158fc2005-09-01 00:19:25 +00007312 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00007313 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00007314 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007315 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00007316 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007317
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007318 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007319}
7320
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007321SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7322 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007323 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007324 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007325
Chris Lattner5919b482007-12-29 06:55:23 +00007326 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007327 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00007328 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007329 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00007330
Nate Begeman21158fc2005-09-01 00:19:25 +00007331 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007332 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007333 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00007334
7335 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7336 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00007337 if (N0.getOpcode() == ISD::FP_ROUND
7338 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007339 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00007340 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00007341 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007342 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007343 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00007344 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00007345 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007346
Chris Lattner72733e52008-01-17 07:00:52 +00007347 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00007348 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover7f3e11e2014-07-16 15:37:24 +00007349 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007350 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007351 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007352 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007353 LN0->getBasePtr(), N0.getValueType(),
7354 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00007355 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00007356 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007357 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00007358 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00007359 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007360 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00007361 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00007362
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007363 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007364}
7365
Sanjay Patelccd26762014-08-28 21:51:37 +00007366SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7367 SDValue N0 = N->getOperand(0);
7368 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7369 EVT VT = N->getValueType(0);
7370
7371 // fold (fceil c1) -> fceil(c1)
7372 if (N0CFP)
7373 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7374
7375 return SDValue();
7376}
7377
7378SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7379 SDValue N0 = N->getOperand(0);
7380 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7381 EVT VT = N->getValueType(0);
7382
7383 // fold (ftrunc c1) -> ftrunc(c1)
7384 if (N0CFP)
7385 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7386
7387 return SDValue();
7388}
7389
7390SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7391 SDValue N0 = N->getOperand(0);
7392 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7393 EVT VT = N->getValueType(0);
7394
7395 // fold (ffloor c1) -> ffloor(c1)
7396 if (N0CFP)
7397 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7398
7399 return SDValue();
7400}
7401
7402// FIXME: FNEG and FABS have a lot in common; refactor.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007403SDValue DAGCombiner::visitFNEG(SDNode *N) {
7404 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007405 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007406
Craig Topper82384612012-09-11 01:45:21 +00007407 if (VT.isVector()) {
7408 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7409 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper03f39772012-09-09 22:58:45 +00007410 }
7411
Sanjay Patelccd26762014-08-28 21:51:37 +00007412 // Constant fold FNEG.
7413 if (isa<ConstantFPSDNode>(N0))
7414 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7415
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007416 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7417 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007418 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00007419
Sanjay Patel35d31332014-08-14 15:15:28 +00007420 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00007421 // constant pool values.
Sanjay Patelccd26762014-08-28 21:51:37 +00007422 if (!TLI.isFNegFree(VT) &&
7423 N0.getOpcode() == ISD::BITCAST &&
Sanjay Patel35d31332014-08-14 15:15:28 +00007424 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007425 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007426 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007427 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel35d31332014-08-14 15:15:28 +00007428 APInt SignMask;
7429 if (N0.getValueType().isVector()) {
7430 // For a vector, get a mask such as 0x80... per scalar element
7431 // and splat it.
7432 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7433 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7434 } else {
7435 // For a scalar, just generate 0x80...
7436 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7437 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00007438 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Sanjay Patel35d31332014-08-14 15:15:28 +00007439 DAG.getConstant(SignMask, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007440 AddToWorklist(Int.getNode());
Sanjay Patel35d31332014-08-14 15:15:28 +00007441 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007442 }
7443 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007444
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007445 // (fneg (fmul c, x)) -> (fmul -c, x)
7446 if (N0.getOpcode() == ISD::FMUL) {
7447 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Tim Northover820e0412014-05-02 17:25:02 +00007448 if (CFP1) {
7449 APFloat CVal = CFP1->getValueAPF();
7450 CVal.changeSign();
7451 if (Level >= AfterLegalizeDAG &&
7452 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7453 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7454 return DAG.getNode(
7455 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7456 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7457 }
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007458 }
7459
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007460 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007461}
7462
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007463SDValue DAGCombiner::visitFABS(SDNode *N) {
7464 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007465 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007466
Craig Topper82384612012-09-11 01:45:21 +00007467 if (VT.isVector()) {
7468 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7469 if (FoldedVOp.getNode()) return FoldedVOp;
7470 }
7471
Nate Begeman21158fc2005-09-01 00:19:25 +00007472 // fold (fabs c1) -> fabs(c1)
Sanjay Patelccd26762014-08-28 21:51:37 +00007473 if (isa<ConstantFPSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007474 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Sanjay Patelccd26762014-08-28 21:51:37 +00007475
Nate Begeman21158fc2005-09-01 00:19:25 +00007476 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007477 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00007478 return N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00007479
Nate Begeman21158fc2005-09-01 00:19:25 +00007480 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007481 // fold (fabs (fcopysign x, y)) -> (fabs x)
7482 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007483 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007484
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007485 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00007486 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00007487 if (!TLI.isFAbsFree(VT) &&
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007488 N0.getOpcode() == ISD::BITCAST &&
7489 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007490 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007491 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007492 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007493 APInt SignMask;
7494 if (N0.getValueType().isVector()) {
7495 // For a vector, get a mask such as 0x7f... per scalar element
7496 // and splat it.
7497 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7498 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7499 } else {
7500 // For a scalar, just generate 0x7f...
7501 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7502 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00007503 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007504 DAG.getConstant(SignMask, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007505 AddToWorklist(Int.getNode());
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007506 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007507 }
7508 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007509
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007510 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007511}
7512
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007513SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7514 SDValue Chain = N->getOperand(0);
7515 SDValue N1 = N->getOperand(1);
7516 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007517
Dan Gohman82e80012009-11-17 00:47:23 +00007518 // If N is a constant we could fold this into a fallthrough or unconditional
7519 // branch. However that doesn't happen very often in normal code, because
7520 // Instcombine/SimplifyCFG should have handled the available opportunities.
7521 // If we did this folding here, it would be necessary to update the
7522 // MachineBasicBlock CFG, which is awkward.
7523
Nate Begeman7e7f4392006-02-01 07:19:44 +00007524 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7525 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007526 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00007527 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7528 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007529 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007530 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00007531 N1.getOperand(0), N1.getOperand(1), N2);
7532 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007533
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007534 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7535 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7536 (N1.getOperand(0).hasOneUse() &&
7537 N1.getOperand(0).getOpcode() == ISD::SRL))) {
Craig Topperc0196b12014-04-14 00:51:57 +00007538 SDNode *Trunc = nullptr;
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007539 if (N1.getOpcode() == ISD::TRUNCATE) {
7540 // Look pass the truncate.
7541 Trunc = N1.getNode();
7542 N1 = N1.getOperand(0);
7543 }
Evan Cheng166a4e62010-01-06 19:38:29 +00007544
Bill Wendlingaa28be62009-03-26 06:14:09 +00007545 // Match this pattern so that we can generate simpler code:
7546 //
7547 // %a = ...
7548 // %b = and i32 %a, 2
7549 // %c = srl i32 %b, 1
7550 // brcond i32 %c ...
7551 //
7552 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00007553 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00007554 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00007555 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00007556 // %c = setcc eq %b, 0
7557 // brcond %c ...
7558 //
7559 // This applies only when the AND constant value has one bit set and the
7560 // SRL constant is equal to the log2 of the AND constant. The back-end is
7561 // smart enough to convert the result into a TEST/JMP sequence.
7562 SDValue Op0 = N1.getOperand(0);
7563 SDValue Op1 = N1.getOperand(1);
7564
7565 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00007566 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00007567 SDValue AndOp1 = Op0.getOperand(1);
7568
7569 if (AndOp1.getOpcode() == ISD::Constant) {
7570 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7571
7572 if (AndConst.isPowerOf2() &&
7573 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7574 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007575 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00007576 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00007577 Op0, DAG.getConstant(0, Op0.getValueType()),
7578 ISD::SETNE);
7579
Andrew Trickef9de2a2013-05-25 02:42:55 +00007580 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00007581 MVT::Other, Chain, SetCC, N2);
7582 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7583 // will convert it back to (X & C1) >> C2.
7584 CombineTo(N, NewBRCond, false);
7585 // Truncate is dead.
Chandler Carruth18066972014-08-02 10:02:07 +00007586 if (Trunc)
7587 deleteAndRecombine(Trunc);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007588 // Replace the uses of SRL with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007589 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007590 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00007591 deleteAndRecombine(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00007592 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00007593 }
7594 }
7595 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007596
7597 if (Trunc)
7598 // Restore N1 if the above transformation doesn't match.
7599 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007600 }
Wesley Peck527da1b2010-11-23 03:31:01 +00007601
Evan Cheng228c31f2010-02-27 07:36:59 +00007602 // Transform br(xor(x, y)) -> br(x != y)
7603 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7604 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7605 SDNode *TheXor = N1.getNode();
7606 SDValue Op0 = TheXor->getOperand(0);
7607 SDValue Op1 = TheXor->getOperand(1);
7608 if (Op0.getOpcode() == Op1.getOpcode()) {
7609 // Avoid missing important xor optimizations.
7610 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007611 if (Tmp.getNode()) {
7612 if (Tmp.getNode() != TheXor) {
7613 DEBUG(dbgs() << "\nReplacing.8 ";
7614 TheXor->dump(&DAG);
7615 dbgs() << "\nWith: ";
7616 Tmp.getNode()->dump(&DAG);
7617 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007618 WorklistRemover DeadNodes(*this);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007619 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
Chandler Carruth18066972014-08-02 10:02:07 +00007620 deleteAndRecombine(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007621 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00007622 MVT::Other, Chain, Tmp, N2);
7623 }
7624
Benjamin Kramer93354432013-03-30 21:28:18 +00007625 // visitXOR has changed XOR's operands or replaced the XOR completely,
7626 // bail out.
7627 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00007628 }
7629 }
7630
7631 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7632 bool Equal = false;
7633 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7634 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7635 Op0.getOpcode() == ISD::XOR) {
7636 TheXor = Op0.getNode();
7637 Equal = true;
7638 }
7639
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007640 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00007641 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00007642 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007643 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00007644 SetCCVT,
7645 Op0, Op1,
7646 Equal ? ISD::SETEQ : ISD::SETNE);
7647 // Replace the uses of XOR with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007648 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007649 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00007650 deleteAndRecombine(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007651 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00007652 MVT::Other, Chain, SetCC, N2);
7653 }
7654 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007655
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007656 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007657}
7658
Chris Lattnera49e16f2005-10-05 06:47:48 +00007659// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7660//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007661SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00007662 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007663 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007664
Dan Gohman82e80012009-11-17 00:47:23 +00007665 // If N is a constant we could fold this into a fallthrough or unconditional
7666 // branch. However that doesn't happen very often in normal code, because
7667 // Instcombine/SimplifyCFG should have handled the available opportunities.
7668 // If we did this folding here, it would be necessary to update the
7669 // MachineBasicBlock CFG, which is awkward.
7670
Duncan Sands93b66092008-06-09 11:32:28 +00007671 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00007672 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007673 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00007674 false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007675 if (Simp.getNode()) AddToWorklist(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00007676
Nate Begemanbd7df032005-10-05 21:43:42 +00007677 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00007678 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007679 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007680 N->getOperand(0), Simp.getOperand(2),
7681 Simp.getOperand(0), Simp.getOperand(1),
7682 N->getOperand(4));
7683
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007684 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007685}
7686
Sanjay Patel50cbfc52014-08-28 16:29:51 +00007687/// Return true if 'Use' is a load or a store that uses N as its base pointer
7688/// and that N may be folded in the load / store addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00007689static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7690 SelectionDAG &DAG,
7691 const TargetLowering &TLI) {
7692 EVT VT;
7693 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7694 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7695 return false;
7696 VT = Use->getValueType(0);
7697 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7698 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7699 return false;
7700 VT = ST->getValue().getValueType();
7701 } else
7702 return false;
7703
Chandler Carruth95f83e02013-01-07 15:14:13 +00007704 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00007705 if (N->getOpcode() == ISD::ADD) {
7706 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7707 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007708 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007709 AM.BaseOffs = Offset->getSExtValue();
7710 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007711 // [reg +/- reg]
7712 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007713 } else if (N->getOpcode() == ISD::SUB) {
7714 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7715 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007716 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007717 AM.BaseOffs = -Offset->getSExtValue();
7718 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007719 // [reg +/- reg]
7720 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007721 } else
7722 return false;
7723
7724 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7725}
7726
Sanjay Patel50cbfc52014-08-28 16:29:51 +00007727/// Try turning a load/store into a pre-indexed load/store when the base
7728/// pointer is an add or subtract and it has other uses besides the load/store.
7729/// After the transformation, the new indexed load/store has effectively folded
7730/// the add/subtract in and all of its other uses are redirected to the
7731/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00007732bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007733 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007734 return false;
7735
7736 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007737 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007738 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007739 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007740 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007741 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007742 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00007743 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00007744 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7745 return false;
7746 Ptr = LD->getBasePtr();
7747 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007748 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007749 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007750 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007751 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7752 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7753 return false;
7754 Ptr = ST->getBasePtr();
7755 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007756 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007757 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007758 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007759
Chris Lattnereabc15c2006-11-11 00:56:29 +00007760 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7761 // out. There is no reason to make this a preinc/predec.
7762 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00007763 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007764 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007765
Chris Lattnereabc15c2006-11-11 00:56:29 +00007766 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007767 SDValue BasePtr;
7768 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007769 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7770 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7771 return false;
Hal Finkel25819052013-02-08 21:35:47 +00007772
7773 // Backends without true r+i pre-indexed forms may need to pass a
7774 // constant base with a variable offset so that constant coercion
7775 // will work with the patterns in canonical form.
7776 bool Swapped = false;
7777 if (isa<ConstantSDNode>(BasePtr)) {
7778 std::swap(BasePtr, Offset);
7779 Swapped = true;
7780 }
7781
Evan Cheng044a0a82007-05-03 23:52:19 +00007782 // Don't create a indexed load / store with zero offset.
7783 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007784 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007785 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007786
Chris Lattnera0a80032006-11-11 01:00:15 +00007787 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00007788 // 1) The new base ptr is a frame index.
7789 // 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 +00007790 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00007791 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00007792 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00007793 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00007794
Chris Lattnera0a80032006-11-11 01:00:15 +00007795 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7796 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00007797 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00007798 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007799
Chris Lattnera0a80032006-11-11 01:00:15 +00007800 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007801 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007802 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00007803 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007804 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007805 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007806
Hal Finkel25819052013-02-08 21:35:47 +00007807 // If the offset is a constant, there may be other adds of constants that
7808 // can be folded with this one. We should do this to avoid having to keep
7809 // a copy of the original base pointer.
7810 SmallVector<SDNode *, 16> OtherUses;
7811 if (isa<ConstantSDNode>(Offset))
Jim Grosbache8160032014-04-11 01:13:13 +00007812 for (SDNode *Use : BasePtr.getNode()->uses()) {
Hal Finkel25819052013-02-08 21:35:47 +00007813 if (Use == Ptr.getNode())
7814 continue;
7815
7816 if (Use->isPredecessorOf(N))
7817 continue;
7818
7819 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7820 OtherUses.clear();
7821 break;
7822 }
7823
7824 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7825 if (Op1.getNode() == BasePtr.getNode())
7826 std::swap(Op0, Op1);
7827 assert(Op0.getNode() == BasePtr.getNode() &&
7828 "Use of ADD/SUB but not an operand");
7829
7830 if (!isa<ConstantSDNode>(Op1)) {
7831 OtherUses.clear();
7832 break;
7833 }
7834
7835 // FIXME: In some cases, we can be smarter about this.
7836 if (Op1.getValueType() != Offset.getValueType()) {
7837 OtherUses.clear();
7838 break;
7839 }
7840
7841 OtherUses.push_back(Use);
7842 }
7843
7844 if (Swapped)
7845 std::swap(BasePtr, Offset);
7846
Evan Chenga4d187b2007-05-24 02:35:39 +00007847 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007848 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00007849
7850 // Caches for hasPredecessorHelper
7851 SmallPtrSet<const SDNode *, 32> Visited;
7852 SmallVector<const SDNode *, 16> Worklist;
7853
Jim Grosbache8160032014-04-11 01:13:13 +00007854 for (SDNode *Use : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007855 if (Use == N)
7856 continue;
Lang Hames5a004992011-07-07 04:31:51 +00007857 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007858 return false;
7859
Evan Chengfa832632012-01-13 01:37:24 +00007860 // If Ptr may be folded in addressing mode of other use, then it's
7861 // not profitable to do this transformation.
7862 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007863 RealUse = true;
7864 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007865
Chris Lattnereabc15c2006-11-11 00:56:29 +00007866 if (!RealUse)
7867 return false;
7868
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007869 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007870 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007871 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007872 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007873 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00007874 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007875 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007876 ++PreIndexedNodes;
7877 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007878 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007879 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007880 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007881 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007882 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007883 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007884 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007885 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7886 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007887 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007888 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007889 }
7890
Chris Lattnereabc15c2006-11-11 00:56:29 +00007891 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00007892 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007893
Hal Finkel25819052013-02-08 21:35:47 +00007894 if (Swapped)
7895 std::swap(BasePtr, Offset);
7896
7897 // Replace other uses of BasePtr that can be updated to use Ptr
7898 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7899 unsigned OffsetIdx = 1;
7900 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7901 OffsetIdx = 0;
7902 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7903 BasePtr.getNode() && "Expected BasePtr operand");
7904
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007905 // We need to replace ptr0 in the following expression:
7906 // x0 * offset0 + y0 * ptr0 = t0
7907 // knowing that
7908 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00007909 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007910 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7911 // indexed load/store and the expresion that needs to be re-written.
7912 //
7913 // Therefore, we have:
7914 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00007915
7916 ConstantSDNode *CN =
7917 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007918 int X0, X1, Y0, Y1;
7919 APInt Offset0 = CN->getAPIntValue();
7920 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00007921
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007922 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7923 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7924 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7925 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00007926
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007927 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7928
7929 APInt CNV = Offset0;
7930 if (X0 < 0) CNV = -CNV;
7931 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7932 else CNV = CNV - Offset1;
7933
7934 // We can now generate the new expression.
7935 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7936 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7937
7938 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00007939 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00007940 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7941 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
Chandler Carruth18066972014-08-02 10:02:07 +00007942 deleteAndRecombine(OtherUses[i]);
Hal Finkel25819052013-02-08 21:35:47 +00007943 }
7944
Chris Lattnereabc15c2006-11-11 00:56:29 +00007945 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007946 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00007947 deleteAndRecombine(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00007948
7949 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007950}
7951
Sanjay Patel50cbfc52014-08-28 16:29:51 +00007952/// Try to combine a load/store with a add/sub of the base pointer node into a
7953/// post-indexed load/store. The transformation folded the add/subtract into the
7954/// new indexed load/store effectively and all of its uses are redirected to the
7955/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00007956bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007957 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007958 return false;
7959
7960 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007961 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007962 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007963 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007964 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007965 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007966 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007967 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7968 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7969 return false;
7970 Ptr = LD->getBasePtr();
7971 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007972 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007973 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007974 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007975 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7976 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7977 return false;
7978 Ptr = ST->getBasePtr();
7979 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007980 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007981 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007982 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007983
Gabor Greiff304a7a2008-08-28 21:40:38 +00007984 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007985 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007986
Jim Grosbache8160032014-04-11 01:13:13 +00007987 for (SDNode *Op : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007988 if (Op == N ||
7989 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7990 continue;
7991
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007992 SDValue BasePtr;
7993 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007994 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7995 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00007996 // Don't create a indexed load / store with zero offset.
7997 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007998 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007999 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00008000
Chris Lattnereabc15c2006-11-11 00:56:29 +00008001 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00008002 // 1) All uses are load / store ops that use it as base ptr (and
8003 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00008004 // 2) Op must be independent of N, i.e. Op is neither a predecessor
8005 // nor a successor of N. Otherwise, if Op is folded that would
8006 // create a cycle.
8007
Evan Chengcfc05132009-05-06 18:25:01 +00008008 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8009 continue;
8010
Chris Lattnereabc15c2006-11-11 00:56:29 +00008011 // Check for #1.
8012 bool TryNext = false;
Jim Grosbache8160032014-04-11 01:13:13 +00008013 for (SDNode *Use : BasePtr.getNode()->uses()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00008014 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00008015 continue;
8016
Chris Lattnereabc15c2006-11-11 00:56:29 +00008017 // If all the uses are load / store addresses, then don't do the
8018 // transformation.
8019 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8020 bool RealUse = false;
Jim Grosbache8160032014-04-11 01:13:13 +00008021 for (SDNode *UseUse : Use->uses()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00008022 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008023 RealUse = true;
8024 }
Chris Lattnerffad2162006-11-11 00:39:41 +00008025
Chris Lattnereabc15c2006-11-11 00:56:29 +00008026 if (!RealUse) {
8027 TryNext = true;
8028 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00008029 }
8030 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00008031 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008032
Chris Lattnereabc15c2006-11-11 00:56:29 +00008033 if (TryNext)
8034 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00008035
Chris Lattnereabc15c2006-11-11 00:56:29 +00008036 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00008037 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008038 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00008039 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008040 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008041 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008042 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008043 ++PostIndexedNodes;
8044 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00008045 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008046 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008047 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008048 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008049 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008050 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008051 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008052 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8053 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00008054 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008055 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00008056 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00008057
Chris Lattnereabc15c2006-11-11 00:56:29 +00008058 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00008059 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008060
8061 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008062 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008063 Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00008064 deleteAndRecombine(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008065 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00008066 }
8067 }
8068 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008069
Chris Lattnerffad2162006-11-11 00:39:41 +00008070 return false;
8071}
8072
Hal Finkel51e6fa22014-09-02 06:24:04 +00008073/// \brief Return the base-pointer arithmetic from an indexed \p LD.
8074SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8075 ISD::MemIndexedMode AM = LD->getAddressingMode();
8076 assert(AM != ISD::UNINDEXED);
8077 SDValue BP = LD->getOperand(1);
8078 SDValue Inc = LD->getOperand(2);
Hal Finkele19006e2014-09-02 16:05:23 +00008079
8080 // Some backends use TargetConstants for load offsets, but don't expect
8081 // TargetConstants in general ADD nodes. We can convert these constants into
8082 // regular Constants (if the constant is not opaque).
8083 assert((Inc.getOpcode() != ISD::TargetConstant ||
8084 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8085 "Cannot split out indexing using opaque target constants");
8086 if (Inc.getOpcode() == ISD::TargetConstant) {
8087 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8088 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8089 ConstInc->getValueType(0));
8090 }
8091
Hal Finkel51e6fa22014-09-02 06:24:04 +00008092 unsigned Opc =
8093 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8094 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8095}
8096
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008097SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00008098 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008099 SDValue Chain = LD->getChain();
8100 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00008101
Evan Chenga684cd22007-05-01 00:38:21 +00008102 // If load is not volatile and there are no uses of the loaded value (and
8103 // the updated indexed value in case of indexed loads), change uses of the
8104 // chain value into uses of the chain input (i.e. delete the dead load).
8105 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00008106 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00008107 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00008108 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00008109 // It's not safe to use the two value CombineTo variant here. e.g.
8110 // v1, chain2 = load chain1, loc
8111 // v2, chain3 = load chain2, loc
8112 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00008113 // Now we replace use of chain2 with chain1. This makes the second load
8114 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00008115 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008116 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008117 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008118 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008119 dbgs() << "\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008120 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008121 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00008122
Chandler Carruth18066972014-08-02 10:02:07 +00008123 if (N->use_empty())
8124 deleteAndRecombine(N);
Bill Wendling306bfc22009-01-30 23:27:35 +00008125
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008126 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00008127 }
Evan Chengb68343c2007-05-01 08:53:39 +00008128 } else {
8129 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00008130 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Hal Finkel51e6fa22014-09-02 06:24:04 +00008131
Hal Finkele19006e2014-09-02 16:05:23 +00008132 // If this load has an opaque TargetConstant offset, then we cannot split
8133 // the indexing into an add/sub directly (that TargetConstant may not be
8134 // valid for a different type of node, and we cannot convert an opaque
8135 // target constant into a regular constant).
8136 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8137 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
Hal Finkel51e6fa22014-09-02 06:24:04 +00008138
8139 if (!N->hasAnyUseOfValue(0) &&
Hal Finkele19006e2014-09-02 16:05:23 +00008140 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
Dale Johannesen84935752009-02-06 23:05:02 +00008141 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Hal Finkel51e6fa22014-09-02 06:24:04 +00008142 SDValue Index;
Hal Finkele19006e2014-09-02 16:05:23 +00008143 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
Hal Finkel51e6fa22014-09-02 06:24:04 +00008144 Index = SplitIndexingFromLoad(LD);
8145 // Try to fold the base pointer arithmetic into subsequent loads and
8146 // stores.
8147 AddUsersToWorklist(N);
8148 } else
8149 Index = DAG.getUNDEF(N->getValueType(1));
Evan Cheng228c31f2010-02-27 07:36:59 +00008150 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008151 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008152 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008153 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008154 dbgs() << " and 2 other values\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008155 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008156 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Hal Finkel51e6fa22014-09-02 06:24:04 +00008157 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008158 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Chandler Carruth18066972014-08-02 10:02:07 +00008159 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008160 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00008161 }
Evan Chenga684cd22007-05-01 00:38:21 +00008162 }
8163 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008164
Chris Lattnere260ed82005-10-10 22:04:48 +00008165 // If this load is directly stored, replace the load value with the stored
8166 // value.
8167 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00008168 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00008169 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00008170 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00008171 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8172 if (PrevST->getBasePtr() == Ptr &&
8173 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00008174 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00008175 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00008176 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008177
Evan Cheng43cd9e32010-04-01 06:04:33 +00008178 // Try to infer better alignment information than the load already has.
8179 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00008180 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00008181 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8182 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00008183 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00008184 LD->getValueType(0),
8185 Chain, Ptr, LD->getPointerInfo(),
8186 LD->getMemoryVT(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00008187 LD->isVolatile(), LD->isNonTemporal(),
8188 LD->isInvariant(), Align, LD->getAAInfo());
Owen Andersonde89ecf2013-02-05 19:24:39 +00008189 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8190 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00008191 }
8192 }
8193
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00008194 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8195 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00008196#ifndef NDEBUG
8197 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8198 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8199 UseAA = false;
8200#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00008201 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00008202 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008203 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008204
Jim Laskey708d0db2006-10-04 16:53:27 +00008205 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00008206 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008207 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00008208
Jim Laskeyd07be232006-09-25 16:29:54 +00008209 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00008210 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008211 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008212 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008213 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008214 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00008215 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008216 BetterChain, Ptr, LD->getMemoryVT(),
8217 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008218 }
Jim Laskeyd07be232006-09-25 16:29:54 +00008219
Jim Laskey708d0db2006-10-04 16:53:27 +00008220 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008221 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00008222 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00008223
Nate Begeman879d8f12009-09-15 00:18:30 +00008224 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008225 AddToWorklist(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00008226
Jim Laskeydcf983c2006-10-13 23:32:28 +00008227 // Replace uses with load result and token factor. Don't add users
8228 // to work list.
8229 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00008230 }
8231 }
8232
Evan Cheng357017f2006-11-03 03:06:21 +00008233 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00008234 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008235 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00008236
Quentin Colombetde0e0622013-10-11 18:29:42 +00008237 // Try to slice up N to more direct loads if the slices are mapped to
8238 // different register banks or pairing can take place.
8239 if (SliceUpLoad(N))
8240 return SDValue(N, 0);
8241
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008242 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00008243}
8244
Quentin Colombetde0e0622013-10-11 18:29:42 +00008245namespace {
8246/// \brief Helper structure used to slice a load in smaller loads.
8247/// Basically a slice is obtained from the following sequence:
8248/// Origin = load Ty1, Base
8249/// Shift = srl Ty1 Origin, CstTy Amount
8250/// Inst = trunc Shift to Ty2
8251///
8252/// Then, it will be rewriten into:
8253/// Slice = load SliceTy, Base + SliceOffset
8254/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8255///
8256/// SliceTy is deduced from the number of bits that are actually used to
8257/// build Inst.
8258struct LoadedSlice {
8259 /// \brief Helper structure used to compute the cost of a slice.
8260 struct Cost {
8261 /// Are we optimizing for code size.
8262 bool ForCodeSize;
8263 /// Various cost.
8264 unsigned Loads;
8265 unsigned Truncates;
8266 unsigned CrossRegisterBanksCopies;
8267 unsigned ZExts;
8268 unsigned Shift;
8269
8270 Cost(bool ForCodeSize = false)
8271 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8272 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8273
8274 /// \brief Get the cost of one isolated slice.
8275 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8276 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8277 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8278 EVT TruncType = LS.Inst->getValueType(0);
8279 EVT LoadedType = LS.getLoadedType();
8280 if (TruncType != LoadedType &&
8281 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8282 ZExts = 1;
8283 }
8284
8285 /// \brief Account for slicing gain in the current cost.
8286 /// Slicing provide a few gains like removing a shift or a
8287 /// truncate. This method allows to grow the cost of the original
8288 /// load with the gain from this slice.
8289 void addSliceGain(const LoadedSlice &LS) {
8290 // Each slice saves a truncate.
8291 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8292 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8293 LS.Inst->getOperand(0).getValueType()))
8294 ++Truncates;
8295 // If there is a shift amount, this slice gets rid of it.
8296 if (LS.Shift)
8297 ++Shift;
8298 // If this slice can merge a cross register bank copy, account for it.
8299 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8300 ++CrossRegisterBanksCopies;
8301 }
8302
8303 Cost &operator+=(const Cost &RHS) {
8304 Loads += RHS.Loads;
8305 Truncates += RHS.Truncates;
8306 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8307 ZExts += RHS.ZExts;
8308 Shift += RHS.Shift;
8309 return *this;
8310 }
8311
8312 bool operator==(const Cost &RHS) const {
8313 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8314 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8315 ZExts == RHS.ZExts && Shift == RHS.Shift;
8316 }
8317
8318 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8319
8320 bool operator<(const Cost &RHS) const {
8321 // Assume cross register banks copies are as expensive as loads.
8322 // FIXME: Do we want some more target hooks?
8323 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8324 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8325 // Unless we are optimizing for code size, consider the
8326 // expensive operation first.
8327 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8328 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8329 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8330 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8331 }
8332
8333 bool operator>(const Cost &RHS) const { return RHS < *this; }
8334
8335 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8336
8337 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8338 };
8339 // The last instruction that represent the slice. This should be a
8340 // truncate instruction.
8341 SDNode *Inst;
8342 // The original load instruction.
8343 LoadSDNode *Origin;
8344 // The right shift amount in bits from the original load.
8345 unsigned Shift;
8346 // The DAG from which Origin came from.
8347 // This is used to get some contextual information about legal types, etc.
8348 SelectionDAG *DAG;
8349
Craig Topperc0196b12014-04-14 00:51:57 +00008350 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8351 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
Quentin Colombetde0e0622013-10-11 18:29:42 +00008352 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8353
8354 LoadedSlice(const LoadedSlice &LS)
8355 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8356
8357 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8358 /// \return Result is \p BitWidth and has used bits set to 1 and
8359 /// not used bits set to 0.
8360 APInt getUsedBits() const {
8361 // Reproduce the trunc(lshr) sequence:
8362 // - Start from the truncated value.
8363 // - Zero extend to the desired bit width.
8364 // - Shift left.
8365 assert(Origin && "No original load to compare against.");
8366 unsigned BitWidth = Origin->getValueSizeInBits(0);
8367 assert(Inst && "This slice is not bound to an instruction");
8368 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8369 "Extracted slice is bigger than the whole type!");
8370 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8371 UsedBits.setAllBits();
8372 UsedBits = UsedBits.zext(BitWidth);
8373 UsedBits <<= Shift;
8374 return UsedBits;
8375 }
8376
8377 /// \brief Get the size of the slice to be loaded in bytes.
8378 unsigned getLoadedSize() const {
8379 unsigned SliceSize = getUsedBits().countPopulation();
8380 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8381 return SliceSize / 8;
8382 }
8383
8384 /// \brief Get the type that will be loaded for this slice.
8385 /// Note: This may not be the final type for the slice.
8386 EVT getLoadedType() const {
8387 assert(DAG && "Missing context");
8388 LLVMContext &Ctxt = *DAG->getContext();
8389 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8390 }
8391
8392 /// \brief Get the alignment of the load used for this slice.
8393 unsigned getAlignment() const {
8394 unsigned Alignment = Origin->getAlignment();
8395 unsigned Offset = getOffsetFromBase();
8396 if (Offset != 0)
8397 Alignment = MinAlign(Alignment, Alignment + Offset);
8398 return Alignment;
8399 }
8400
8401 /// \brief Check if this slice can be rewritten with legal operations.
8402 bool isLegal() const {
8403 // An invalid slice is not legal.
8404 if (!Origin || !Inst || !DAG)
8405 return false;
8406
8407 // Offsets are for indexed load only, we do not handle that.
8408 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8409 return false;
8410
8411 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8412
8413 // Check that the type is legal.
8414 EVT SliceType = getLoadedType();
8415 if (!TLI.isTypeLegal(SliceType))
8416 return false;
8417
8418 // Check that the load is legal for this type.
8419 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8420 return false;
8421
8422 // Check that the offset can be computed.
8423 // 1. Check its type.
8424 EVT PtrType = Origin->getBasePtr().getValueType();
8425 if (PtrType == MVT::Untyped || PtrType.isExtended())
8426 return false;
8427
8428 // 2. Check that it fits in the immediate.
8429 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8430 return false;
8431
8432 // 3. Check that the computation is legal.
8433 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8434 return false;
8435
8436 // Check that the zext is legal if it needs one.
8437 EVT TruncateType = Inst->getValueType(0);
8438 if (TruncateType != SliceType &&
8439 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8440 return false;
8441
8442 return true;
8443 }
8444
8445 /// \brief Get the offset in bytes of this slice in the original chunk of
8446 /// bits.
Craig Topperc0196b12014-04-14 00:51:57 +00008447 /// \pre DAG != nullptr.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008448 uint64_t getOffsetFromBase() const {
8449 assert(DAG && "Missing context.");
8450 bool IsBigEndian =
8451 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8452 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8453 uint64_t Offset = Shift / 8;
8454 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8455 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8456 "The size of the original loaded type is not a multiple of a"
8457 " byte.");
8458 // If Offset is bigger than TySizeInBytes, it means we are loading all
8459 // zeros. This should have been optimized before in the process.
8460 assert(TySizeInBytes > Offset &&
8461 "Invalid shift amount for given loaded size");
8462 if (IsBigEndian)
8463 Offset = TySizeInBytes - Offset - getLoadedSize();
8464 return Offset;
8465 }
8466
8467 /// \brief Generate the sequence of instructions to load the slice
8468 /// represented by this object and redirect the uses of this slice to
8469 /// this new sequence of instructions.
8470 /// \pre this->Inst && this->Origin are valid Instructions and this
8471 /// object passed the legal check: LoadedSlice::isLegal returned true.
8472 /// \return The last instruction of the sequence used to load the slice.
8473 SDValue loadSlice() const {
8474 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8475 const SDValue &OldBaseAddr = Origin->getBasePtr();
8476 SDValue BaseAddr = OldBaseAddr;
8477 // Get the offset in that chunk of bytes w.r.t. the endianess.
8478 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8479 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8480 if (Offset) {
8481 // BaseAddr = BaseAddr + Offset.
8482 EVT ArithType = BaseAddr.getValueType();
8483 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8484 DAG->getConstant(Offset, ArithType));
8485 }
8486
8487 // Create the type of the loaded slice according to its size.
8488 EVT SliceType = getLoadedType();
8489
8490 // Create the load for the slice.
8491 SDValue LastInst = DAG->getLoad(
8492 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8493 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8494 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8495 // If the final type is not the same as the loaded type, this means that
8496 // we have to pad with zero. Create a zero extend for that.
8497 EVT FinalType = Inst->getValueType(0);
8498 if (SliceType != FinalType)
8499 LastInst =
8500 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8501 return LastInst;
8502 }
8503
8504 /// \brief Check if this slice can be merged with an expensive cross register
8505 /// bank copy. E.g.,
8506 /// i = load i32
8507 /// f = bitcast i32 i to float
8508 bool canMergeExpensiveCrossRegisterBankCopy() const {
8509 if (!Inst || !Inst->hasOneUse())
8510 return false;
8511 SDNode *Use = *Inst->use_begin();
8512 if (Use->getOpcode() != ISD::BITCAST)
8513 return false;
8514 assert(DAG && "Missing context");
8515 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8516 EVT ResVT = Use->getValueType(0);
8517 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8518 const TargetRegisterClass *ArgRC =
8519 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8520 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8521 return false;
8522
8523 // At this point, we know that we perform a cross-register-bank copy.
8524 // Check if it is expensive.
Eric Christopherd9134482014-08-04 21:25:23 +00008525 const TargetRegisterInfo *TRI =
8526 TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo();
Quentin Colombetde0e0622013-10-11 18:29:42 +00008527 // Assume bitcasts are cheap, unless both register classes do not
8528 // explicitly share a common sub class.
8529 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8530 return false;
8531
8532 // Check if it will be merged with the load.
8533 // 1. Check the alignment constraint.
8534 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8535 ResVT.getTypeForEVT(*DAG->getContext()));
8536
8537 if (RequiredAlignment > getAlignment())
8538 return false;
8539
8540 // 2. Check that the load is a legal operation for that type.
8541 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8542 return false;
8543
8544 // 3. Check that we do not have a zext in the way.
8545 if (Inst->getValueType(0) != getLoadedType())
8546 return false;
8547
8548 return true;
8549 }
8550};
8551}
8552
Quentin Colombetde0e0622013-10-11 18:29:42 +00008553/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8554/// \p UsedBits looks like 0..0 1..1 0..0.
8555static bool areUsedBitsDense(const APInt &UsedBits) {
8556 // If all the bits are one, this is dense!
8557 if (UsedBits.isAllOnesValue())
8558 return true;
8559
8560 // Get rid of the unused bits on the right.
8561 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8562 // Get rid of the unused bits on the left.
8563 if (NarrowedUsedBits.countLeadingZeros())
8564 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8565 // Check that the chunk of bits is completely used.
8566 return NarrowedUsedBits.isAllOnesValue();
8567}
8568
8569/// \brief Check whether or not \p First and \p Second are next to each other
8570/// in memory. This means that there is no hole between the bits loaded
8571/// by \p First and the bits loaded by \p Second.
8572static bool areSlicesNextToEachOther(const LoadedSlice &First,
8573 const LoadedSlice &Second) {
8574 assert(First.Origin == Second.Origin && First.Origin &&
8575 "Unable to match different memory origins.");
8576 APInt UsedBits = First.getUsedBits();
8577 assert((UsedBits & Second.getUsedBits()) == 0 &&
8578 "Slices are not supposed to overlap.");
8579 UsedBits |= Second.getUsedBits();
8580 return areUsedBitsDense(UsedBits);
8581}
8582
8583/// \brief Adjust the \p GlobalLSCost according to the target
8584/// paring capabilities and the layout of the slices.
8585/// \pre \p GlobalLSCost should account for at least as many loads as
8586/// there is in the slices in \p LoadedSlices.
8587static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8588 LoadedSlice::Cost &GlobalLSCost) {
8589 unsigned NumberOfSlices = LoadedSlices.size();
8590 // If there is less than 2 elements, no pairing is possible.
8591 if (NumberOfSlices < 2)
8592 return;
8593
8594 // Sort the slices so that elements that are likely to be next to each
8595 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00008596 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8597 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8598 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8599 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8600 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00008601 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8602 // First (resp. Second) is the first (resp. Second) potentially candidate
8603 // to be placed in a paired load.
Craig Topperc0196b12014-04-14 00:51:57 +00008604 const LoadedSlice *First = nullptr;
8605 const LoadedSlice *Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008606 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8607 // Set the beginning of the pair.
8608 First = Second) {
8609
8610 Second = &LoadedSlices[CurrSlice];
8611
8612 // If First is NULL, it means we start a new pair.
8613 // Get to the next slice.
8614 if (!First)
8615 continue;
8616
8617 EVT LoadedType = First->getLoadedType();
8618
8619 // If the types of the slices are different, we cannot pair them.
8620 if (LoadedType != Second->getLoadedType())
8621 continue;
8622
8623 // Check if the target supplies paired loads for this type.
8624 unsigned RequiredAlignment = 0;
8625 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8626 // move to the next pair, this type is hopeless.
Craig Topperc0196b12014-04-14 00:51:57 +00008627 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008628 continue;
8629 }
8630 // Check if we meet the alignment requirement.
8631 if (RequiredAlignment > First->getAlignment())
8632 continue;
8633
8634 // Check that both loads are next to each other in memory.
8635 if (!areSlicesNextToEachOther(*First, *Second))
8636 continue;
8637
8638 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8639 --GlobalLSCost.Loads;
8640 // Move to the next pair.
Craig Topperc0196b12014-04-14 00:51:57 +00008641 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008642 }
8643}
8644
8645/// \brief Check the profitability of all involved LoadedSlice.
8646/// Currently, it is considered profitable if there is exactly two
8647/// involved slices (1) which are (2) next to each other in memory, and
8648/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8649///
8650/// Note: The order of the elements in \p LoadedSlices may be modified, but not
8651/// the elements themselves.
8652///
8653/// FIXME: When the cost model will be mature enough, we can relax
8654/// constraints (1) and (2).
8655static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8656 const APInt &UsedBits, bool ForCodeSize) {
8657 unsigned NumberOfSlices = LoadedSlices.size();
8658 if (StressLoadSlicing)
8659 return NumberOfSlices > 1;
8660
8661 // Check (1).
8662 if (NumberOfSlices != 2)
8663 return false;
8664
8665 // Check (2).
8666 if (!areUsedBitsDense(UsedBits))
8667 return false;
8668
8669 // Check (3).
8670 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8671 // The original code has one big load.
8672 OrigCost.Loads = 1;
8673 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8674 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8675 // Accumulate the cost of all the slices.
8676 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8677 GlobalSlicingCost += SliceCost;
8678
8679 // Account as cost in the original configuration the gain obtained
8680 // with the current slices.
8681 OrigCost.addSliceGain(LS);
8682 }
8683
8684 // If the target supports paired load, adjust the cost accordingly.
8685 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8686 return OrigCost > GlobalSlicingCost;
8687}
8688
8689/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8690/// operations, split it in the various pieces being extracted.
8691///
8692/// This sort of thing is introduced by SROA.
8693/// This slicing takes care not to insert overlapping loads.
8694/// \pre LI is a simple load (i.e., not an atomic or volatile load).
8695bool DAGCombiner::SliceUpLoad(SDNode *N) {
8696 if (Level < AfterLegalizeDAG)
8697 return false;
8698
8699 LoadSDNode *LD = cast<LoadSDNode>(N);
8700 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8701 !LD->getValueType(0).isInteger())
8702 return false;
8703
8704 // Keep track of already used bits to detect overlapping values.
8705 // In that case, we will just abort the transformation.
8706 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8707
8708 SmallVector<LoadedSlice, 4> LoadedSlices;
8709
8710 // Check if this load is used as several smaller chunks of bits.
8711 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8712 // of computation for each trunc.
8713 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8714 UI != UIEnd; ++UI) {
8715 // Skip the uses of the chain.
8716 if (UI.getUse().getResNo() != 0)
8717 continue;
8718
8719 SDNode *User = *UI;
8720 unsigned Shift = 0;
8721
8722 // Check if this is a trunc(lshr).
8723 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8724 isa<ConstantSDNode>(User->getOperand(1))) {
8725 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8726 User = *User->use_begin();
8727 }
8728
8729 // At this point, User is a Truncate, iff we encountered, trunc or
8730 // trunc(lshr).
8731 if (User->getOpcode() != ISD::TRUNCATE)
8732 return false;
8733
8734 // The width of the type must be a power of 2 and greater than 8-bits.
8735 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00008736 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00008737 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008738 unsigned Width = User->getValueSizeInBits(0);
8739 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8740 return 0;
8741
8742 // Build the slice for this chain of computations.
8743 LoadedSlice LS(User, LD, Shift, &DAG);
8744 APInt CurrentUsedBits = LS.getUsedBits();
8745
8746 // Check if this slice overlaps with another.
8747 if ((CurrentUsedBits & UsedBits) != 0)
8748 return false;
8749 // Update the bits used globally.
8750 UsedBits |= CurrentUsedBits;
8751
8752 // Check if the new slice would be legal.
8753 if (!LS.isLegal())
8754 return false;
8755
8756 // Record the slice.
8757 LoadedSlices.push_back(LS);
8758 }
8759
8760 // Abort slicing if it does not seem to be profitable.
8761 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8762 return false;
8763
8764 ++SlicedLoads;
8765
8766 // Rewrite each chain to use an independent load.
8767 // By construction, each chain can be represented by a unique load.
8768
8769 // Prepare the argument for the new token factor for all the slices.
8770 SmallVector<SDValue, 8> ArgChains;
8771 for (SmallVectorImpl<LoadedSlice>::const_iterator
8772 LSIt = LoadedSlices.begin(),
8773 LSItEnd = LoadedSlices.end();
8774 LSIt != LSItEnd; ++LSIt) {
8775 SDValue SliceInst = LSIt->loadSlice();
8776 CombineTo(LSIt->Inst, SliceInst, true);
8777 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8778 SliceInst = SliceInst.getOperand(0);
8779 assert(SliceInst->getOpcode() == ISD::LOAD &&
8780 "It takes more than a zext to get to the loaded slice!!");
8781 ArgChains.push_back(SliceInst.getValue(1));
8782 }
8783
8784 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +00008785 ArgChains);
Quentin Colombetde0e0622013-10-11 18:29:42 +00008786 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8787 return true;
8788}
8789
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008790/// Check to see if V is (and load (ptr), imm), where the load is having
8791/// specific bytes cleared out. If so, return the byte size being masked out
8792/// and the shift amount.
Chris Lattner4041ab62010-04-15 04:48:01 +00008793static std::pair<unsigned, unsigned>
8794CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8795 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008796
Chris Lattner4041ab62010-04-15 04:48:01 +00008797 // Check for the structure we're looking for.
8798 if (V->getOpcode() != ISD::AND ||
8799 !isa<ConstantSDNode>(V->getOperand(1)) ||
8800 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8801 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008802
Chris Lattner3245afd2010-04-15 06:10:49 +00008803 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00008804 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00008805 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00008806
Chris Lattner3245afd2010-04-15 06:10:49 +00008807 // The store should be chained directly to the load or be an operand of a
8808 // tokenfactor.
8809 if (LD == Chain.getNode())
8810 ; // ok.
8811 else if (Chain->getOpcode() != ISD::TokenFactor)
8812 return Result; // Fail.
8813 else {
8814 bool isOk = false;
8815 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8816 if (Chain->getOperand(i).getNode() == LD) {
8817 isOk = true;
8818 break;
8819 }
8820 if (!isOk) return Result;
8821 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008822
Chris Lattner4041ab62010-04-15 04:48:01 +00008823 // This only handles simple types.
8824 if (V.getValueType() != MVT::i16 &&
8825 V.getValueType() != MVT::i32 &&
8826 V.getValueType() != MVT::i64)
8827 return Result;
8828
8829 // Check the constant mask. Invert it so that the bits being masked out are
8830 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8831 // follow the sign bit for uniformity.
8832 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008833 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008834 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008835 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008836 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8837 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00008838
Chris Lattner4041ab62010-04-15 04:48:01 +00008839 // See if we have a continuous run of bits. If so, we have 0*1+0*
8840 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8841 return Result;
8842
8843 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8844 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8845 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00008846
Chris Lattner4041ab62010-04-15 04:48:01 +00008847 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8848 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00008849 case 1:
8850 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00008851 case 4: break;
8852 default: return Result; // All one mask, or 5-byte mask.
8853 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008854
Chris Lattner4041ab62010-04-15 04:48:01 +00008855 // Verify that the first bit starts at a multiple of mask so that the access
8856 // is aligned the same as the access width.
8857 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008858
Chris Lattner4041ab62010-04-15 04:48:01 +00008859 Result.first = MaskedBytes;
8860 Result.second = NotMaskTZ/8;
8861 return Result;
8862}
8863
8864
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008865/// Check to see if IVal is something that provides a value as specified by
8866/// MaskInfo. If so, replace the specified store with a narrower store of
8867/// truncated IVal.
Chris Lattner4041ab62010-04-15 04:48:01 +00008868static SDNode *
8869ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8870 SDValue IVal, StoreSDNode *St,
8871 DAGCombiner *DC) {
8872 unsigned NumBytes = MaskInfo.first;
8873 unsigned ByteShift = MaskInfo.second;
8874 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00008875
Chris Lattner4041ab62010-04-15 04:48:01 +00008876 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8877 // that uses this. If not, this is not a replacement.
8878 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8879 ByteShift*8, (ByteShift+NumBytes)*8);
Craig Topperc0196b12014-04-14 00:51:57 +00008880 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008881
Chris Lattner4041ab62010-04-15 04:48:01 +00008882 // Check that it is legal on the target to do this. It is legal if the new
8883 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8884 // legalization.
8885 MVT VT = MVT::getIntegerVT(NumBytes*8);
8886 if (!DC->isTypeLegal(VT))
Craig Topperc0196b12014-04-14 00:51:57 +00008887 return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008888
Chris Lattner4041ab62010-04-15 04:48:01 +00008889 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8890 // shifted by ByteShift and truncated down to NumBytes.
8891 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008892 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00008893 DAG.getConstant(ByteShift*8,
8894 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00008895
8896 // Figure out the offset for the store and the alignment of the access.
8897 unsigned StOffset;
8898 unsigned NewAlign = St->getAlignment();
8899
8900 if (DAG.getTargetLoweringInfo().isLittleEndian())
8901 StOffset = ByteShift;
8902 else
8903 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00008904
Chris Lattner4041ab62010-04-15 04:48:01 +00008905 SDValue Ptr = St->getBasePtr();
8906 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008907 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00008908 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8909 NewAlign = MinAlign(NewAlign, StOffset);
8910 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008911
Chris Lattner4041ab62010-04-15 04:48:01 +00008912 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008913 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00008914
Chris Lattner4041ab62010-04-15 04:48:01 +00008915 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00008916 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00008917 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00008918 false, false, NewAlign).getNode();
8919}
8920
Evan Chenga9cda8a2009-05-28 00:35:15 +00008921
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008922/// Look for sequence of load / op / store where op is one of 'or', 'xor', and
8923/// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
8924/// narrowing the load and store if it would end up being a win for performance
8925/// or code size.
Evan Chenga9cda8a2009-05-28 00:35:15 +00008926SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8927 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00008928 if (ST->isVolatile())
8929 return SDValue();
8930
Evan Chenga9cda8a2009-05-28 00:35:15 +00008931 SDValue Chain = ST->getChain();
8932 SDValue Value = ST->getValue();
8933 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00008934 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008935
8936 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +00008937 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008938
8939 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +00008940
Chris Lattner4041ab62010-04-15 04:48:01 +00008941 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8942 // is a byte mask indicating a consecutive number of bytes, check to see if
8943 // Y is known to provide just those bytes. If so, we try to replace the
8944 // load + replace + store sequence with a single (narrower) store, which makes
8945 // the load dead.
8946 if (Opc == ISD::OR) {
8947 std::pair<unsigned, unsigned> MaskedLoad;
8948 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8949 if (MaskedLoad.first)
8950 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8951 Value.getOperand(1), ST,this))
8952 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008953
Chris Lattner4041ab62010-04-15 04:48:01 +00008954 // Or is commutative, so try swapping X and Y.
8955 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8956 if (MaskedLoad.first)
8957 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8958 Value.getOperand(0), ST,this))
8959 return SDValue(NewST, 0);
8960 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008961
Evan Chenga9cda8a2009-05-28 00:35:15 +00008962 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8963 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +00008964 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008965
8966 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +00008967 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8968 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00008969 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008970 if (LD->getBasePtr() != Ptr ||
8971 LD->getPointerInfo().getAddrSpace() !=
8972 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +00008973 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008974
8975 // Find the type to narrow it the load / op / store to.
8976 SDValue N1 = Value.getOperand(1);
8977 unsigned BitWidth = N1.getValueSizeInBits();
8978 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8979 if (Opc == ISD::AND)
8980 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +00008981 if (Imm == 0 || Imm.isAllOnesValue())
8982 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008983 unsigned ShAmt = Imm.countTrailingZeros();
8984 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8985 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +00008986 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008987 while (NewBW < BitWidth &&
Evan Cheng6673ff02009-05-28 18:41:02 +00008988 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
Evan Chenga9cda8a2009-05-28 00:35:15 +00008989 TLI.isNarrowingProfitable(VT, NewVT))) {
8990 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +00008991 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008992 }
Evan Cheng6673ff02009-05-28 18:41:02 +00008993 if (NewBW >= BitWidth)
8994 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008995
8996 // If the lsb changed does not start at the type bitwidth boundary,
8997 // start at the previous one.
8998 if (ShAmt % NewBW)
8999 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +00009000 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9001 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +00009002 if ((Imm & Mask) == Imm) {
9003 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9004 if (Opc == ISD::AND)
9005 NewImm ^= APInt::getAllOnesValue(NewBW);
9006 uint64_t PtrOff = ShAmt / 8;
9007 // For big endian targets, we need to adjust the offset to the pointer to
9008 // load the correct bytes.
9009 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +00009010 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +00009011
9012 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +00009013 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009014 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +00009015 return SDValue();
9016
Andrew Trickef9de2a2013-05-25 02:42:55 +00009017 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +00009018 Ptr.getValueType(), Ptr,
9019 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00009020 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +00009021 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009022 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00009023 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009024 LD->isInvariant(), NewAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00009025 LD->getAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +00009026 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +00009027 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00009028 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +00009029 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009030 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00009031 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +00009032
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009033 AddToWorklist(NewPtr.getNode());
9034 AddToWorklist(NewLD.getNode());
9035 AddToWorklist(NewVal.getNode());
9036 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009037 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +00009038 ++OpsNarrowed;
9039 return NewST;
9040 }
9041 }
9042
Evan Cheng6673ff02009-05-28 18:41:02 +00009043 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009044}
9045
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009046/// For a given floating point load / store pair, if the load value isn't used
9047/// by any other operations, then consider transforming the pair to integer
9048/// load / store operations if the target deems the transformation profitable.
Evan Chengd42641c2011-02-02 01:06:55 +00009049SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9050 StoreSDNode *ST = cast<StoreSDNode>(N);
9051 SDValue Chain = ST->getChain();
9052 SDValue Value = ST->getValue();
9053 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9054 Value.hasOneUse() &&
9055 Chain == SDValue(Value.getNode(), 1)) {
9056 LoadSDNode *LD = cast<LoadSDNode>(Value);
9057 EVT VT = LD->getMemoryVT();
9058 if (!VT.isFloatingPoint() ||
9059 VT != ST->getMemoryVT() ||
9060 LD->isNonTemporal() ||
9061 ST->isNonTemporal() ||
9062 LD->getPointerInfo().getAddrSpace() != 0 ||
9063 ST->getPointerInfo().getAddrSpace() != 0)
9064 return SDValue();
9065
9066 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9067 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9068 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9069 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9070 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9071 return SDValue();
9072
9073 unsigned LDAlign = LD->getAlignment();
9074 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +00009075 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009076 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +00009077 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9078 return SDValue();
9079
Andrew Trickef9de2a2013-05-25 02:42:55 +00009080 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +00009081 LD->getChain(), LD->getBasePtr(),
9082 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00009083 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +00009084
Andrew Trickef9de2a2013-05-25 02:42:55 +00009085 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +00009086 NewLD, ST->getBasePtr(),
9087 ST->getPointerInfo(),
9088 false, false, STAlign);
9089
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009090 AddToWorklist(NewLD.getNode());
9091 AddToWorklist(NewST.getNode());
9092 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009093 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +00009094 ++LdStFP2Int;
9095 return NewST;
9096 }
9097
9098 return SDValue();
9099}
9100
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009101/// Helper struct to parse and store a memory address as base + index + offset.
9102/// We ignore sign extensions when it is safe to do so.
9103/// The following two expressions are not equivalent. To differentiate we need
9104/// to store whether there was a sign extension involved in the index
9105/// computation.
9106/// (load (i64 add (i64 copyfromreg %c)
9107/// (i64 signextend (add (i8 load %index)
9108/// (i8 1))))
9109/// vs
9110///
9111/// (load (i64 add (i64 copyfromreg %c)
9112/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9113/// (i32 1)))))
9114struct BaseIndexOffset {
9115 SDValue Base;
9116 SDValue Index;
9117 int64_t Offset;
9118 bool IsIndexSignExt;
9119
9120 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9121
9122 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9123 bool IsIndexSignExt) :
9124 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9125
9126 bool equalBaseIndex(const BaseIndexOffset &Other) {
9127 return Other.Base == Base && Other.Index == Index &&
9128 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009129 }
9130
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009131 /// Parses tree in Ptr for base, index, offset addresses.
9132 static BaseIndexOffset match(SDValue Ptr) {
9133 bool IsIndexSignExt = false;
9134
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009135 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9136 // instruction, then it could be just the BASE or everything else we don't
9137 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009138 if (Ptr->getOpcode() != ISD::ADD)
9139 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9140
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009141 // We know that we have at least an ADD instruction. Try to pattern match
9142 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009143 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9144 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9145 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9146 IsIndexSignExt);
9147 }
9148
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009149 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +00009150 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009151 // (i64 add (i64 %array_ptr)
9152 // (i64 mul (i64 %induction_var)
9153 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +00009154 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009155 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009156
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009157 // Look at Base + Index + Offset cases.
9158 SDValue Base = Ptr->getOperand(0);
9159 SDValue IndexOffset = Ptr->getOperand(1);
9160
9161 // Skip signextends.
9162 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9163 IndexOffset = IndexOffset->getOperand(0);
9164 IsIndexSignExt = true;
9165 }
9166
9167 // Either the case of Base + Index (no offset) or something else.
9168 if (IndexOffset->getOpcode() != ISD::ADD)
9169 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9170
9171 // Now we have the case of Base + Index + offset.
9172 SDValue Index = IndexOffset->getOperand(0);
9173 SDValue Offset = IndexOffset->getOperand(1);
9174
9175 if (!isa<ConstantSDNode>(Offset))
9176 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9177
9178 // Ignore signextends.
9179 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9180 Index = Index->getOperand(0);
9181 IsIndexSignExt = true;
9182 } else IsIndexSignExt = false;
9183
9184 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9185 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9186 }
9187};
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009188
9189/// Holds a pointer to an LSBaseSDNode as well as information on where it
9190/// is located in a sequence of memory operations connected by a chain.
9191struct MemOpLink {
9192 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9193 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9194 // Ptr to the mem node.
9195 LSBaseSDNode *MemNode;
9196 // Offset from the base ptr.
9197 int64_t OffsetFromBase;
9198 // What is the sequence number of this mem node.
9199 // Lowest mem operand in the DAG starts at zero.
9200 unsigned SequenceNum;
9201};
9202
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009203bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9204 EVT MemVT = St->getMemoryVT();
9205 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009206 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9207 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009208
9209 // Don't merge vectors into wider inputs.
9210 if (MemVT.isVector() || !MemVT.isSimple())
9211 return false;
9212
9213 // Perform an early exit check. Do not bother looking at stored values that
9214 // are not constants or loads.
9215 SDValue StoredVal = St->getValue();
9216 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9217 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9218 !IsLoadSrc)
9219 return false;
9220
9221 // Only look at ends of store sequences.
Chandler Carruth94bd5532014-07-25 07:23:23 +00009222 SDValue Chain = SDValue(St, 0);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009223 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9224 return false;
9225
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009226 // This holds the base pointer, index, and the offset in bytes from the base
9227 // pointer.
9228 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009229
9230 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009231 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009232 return false;
9233
9234 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009235 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009236 return false;
9237
Nadav Rotem307d7672012-11-29 00:00:08 +00009238 // Save the LoadSDNodes that we find in the chain.
9239 // We need to make sure that these nodes do not interfere with
9240 // any of the store nodes.
9241 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9242
9243 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009244 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +00009245
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009246 // Walk up the chain and look for nodes with offsets from the same
9247 // base pointer. Stop when reaching an instruction with a different kind
9248 // or instruction which has a different base pointer.
9249 unsigned Seq = 0;
9250 StoreSDNode *Index = St;
9251 while (Index) {
9252 // If the chain has more than one use, then we can't reorder the mem ops.
Matt Arsenault197a1e22014-07-25 07:56:42 +00009253 if (Index != St && !SDValue(Index, 0)->hasOneUse())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009254 break;
9255
9256 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009257 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009258
9259 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009260 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009261 break;
9262
9263 // Check that the alignment is the same.
9264 if (Index->getAlignment() != St->getAlignment())
9265 break;
9266
9267 // The memory operands must not be volatile.
9268 if (Index->isVolatile() || Index->isIndexed())
9269 break;
9270
9271 // No truncation.
9272 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9273 if (St->isTruncatingStore())
9274 break;
9275
9276 // The stored memory type must be the same.
9277 if (Index->getMemoryVT() != MemVT)
9278 break;
9279
9280 // We do not allow unaligned stores because we want to prevent overriding
9281 // stores.
9282 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9283 break;
9284
9285 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009286 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009287
Nadav Rotem307d7672012-11-29 00:00:08 +00009288 // Find the next memory operand in the chain. If the next operand in the
9289 // chain is a store then move up and continue the scan with the next
9290 // memory operand. If the next operand is a load save it and use alias
9291 // information to check if it interferes with anything.
9292 SDNode *NextInChain = Index->getChain().getNode();
9293 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +00009294 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +00009295 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +00009296 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +00009297 break;
9298 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +00009299 if (Ldn->isVolatile()) {
Craig Topperc0196b12014-04-14 00:51:57 +00009300 Index = nullptr;
Bill Wendling9200bb02013-11-25 18:05:22 +00009301 break;
9302 }
9303
Nadav Rotem307d7672012-11-29 00:00:08 +00009304 // Save the load node for later. Continue the scan.
9305 AliasLoadNodes.push_back(Ldn);
9306 NextInChain = Ldn->getChain().getNode();
9307 continue;
9308 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00009309 Index = nullptr;
Nadav Rotem307d7672012-11-29 00:00:08 +00009310 break;
9311 }
9312 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009313 }
9314
9315 // Check if there is anything to merge.
9316 if (StoreNodes.size() < 2)
9317 return false;
9318
9319 // Sort the memory operands according to their distance from the base pointer.
9320 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009321 [](MemOpLink LHS, MemOpLink RHS) {
9322 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9323 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9324 LHS.SequenceNum > RHS.SequenceNum);
9325 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009326
9327 // Scan the memory operations on the chain and find the first non-consecutive
9328 // store memory address.
9329 unsigned LastConsecutiveStore = 0;
9330 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +00009331 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9332
9333 // Check that the addresses are consecutive starting from the second
9334 // element in the list of stores.
9335 if (i > 0) {
9336 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9337 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9338 break;
9339 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009340
Nadav Rotem307d7672012-11-29 00:00:08 +00009341 bool Alias = false;
9342 // Check if this store interferes with any of the loads that we found.
9343 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9344 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9345 Alias = true;
9346 break;
9347 }
Nadav Rotem307d7672012-11-29 00:00:08 +00009348 // We found a load that alias with this store. Stop the sequence.
9349 if (Alias)
9350 break;
9351
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009352 // Mark this node as useful.
9353 LastConsecutiveStore = i;
9354 }
9355
9356 // The node with the lowest store address.
9357 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9358
9359 // Store the constants into memory as one consecutive store.
9360 if (!IsLoadSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009361 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009362 unsigned LastLegalVectorType = 0;
9363 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009364 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9365 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9366 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009367
9368 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009369 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009370 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009371 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009372 } else {
Alp Tokerf907b892013-12-05 05:44:44 +00009373 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009374 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009375 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009376
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009377 // Find a legal type for the constant store.
9378 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9379 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9380 if (TLI.isTypeLegal(StoreTy))
9381 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009382 // Or check whether a truncstore is legal.
9383 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9384 TargetLowering::TypePromoteInteger) {
9385 EVT LegalizedStoredValueTy =
9386 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9387 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9388 LastLegalType = i+1;
9389 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009390
9391 // Find a legal type for the vector store.
9392 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9393 if (TLI.isTypeLegal(Ty))
9394 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009395 }
9396
Bob Wilson3365b802012-12-20 01:36:20 +00009397 // We only use vectors if the constant is known to be zero and the
9398 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009399 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +00009400 LastLegalVectorType = 0;
9401
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009402 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +00009403 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009404 return false;
9405
Nadav Rotem495b1a42013-02-14 18:28:52 +00009406 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009407 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9408
9409 // Make sure we have something to merge.
9410 if (NumElem < 2)
9411 return false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009412
9413 unsigned EarliestNodeUsed = 0;
9414 for (unsigned i=0; i < NumElem; ++i) {
9415 // Find a chain for the new wide-store operand. Notice that some
9416 // of the store nodes that we found may not be selected for inclusion
9417 // in the wide store. The chain we use needs to be the chain of the
9418 // earliest store node which is *used* and replaced by the wide store.
9419 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9420 EarliestNodeUsed = i;
9421 }
9422
9423 // The earliest Node in the DAG.
9424 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009425 SDLoc DL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009426
Nadav Rotemb27777f2012-10-04 22:35:15 +00009427 SDValue StoredVal;
9428 if (UseVector) {
9429 // Find a legal type for the vector store.
9430 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9431 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9432 StoredVal = DAG.getConstant(0, Ty);
9433 } else {
9434 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9435 APInt StoreInt(StoreBW, 0);
9436
9437 // Construct a single integer constant which is made of the smaller
9438 // constant inputs.
9439 bool IsLE = TLI.isLittleEndian();
9440 for (unsigned i = 0; i < NumElem ; ++i) {
9441 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9442 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9443 SDValue Val = St->getValue();
9444 StoreInt<<=ElementSizeBytes*8;
9445 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9446 StoreInt|=C->getAPIntValue().zext(StoreBW);
9447 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9448 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9449 } else {
9450 assert(false && "Invalid constant element type");
9451 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009452 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009453
9454 // Create the new Load and Store operations.
9455 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9456 StoredVal = DAG.getConstant(StoreInt, StoreTy);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009457 }
9458
Nadav Rotemb27777f2012-10-04 22:35:15 +00009459 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009460 FirstInChain->getBasePtr(),
9461 FirstInChain->getPointerInfo(),
9462 false, false,
9463 FirstInChain->getAlignment());
9464
9465 // Replace the first store with the new store
9466 CombineTo(EarliestOp, NewStore);
9467 // Erase all other stores.
9468 for (unsigned i = 0; i < NumElem ; ++i) {
9469 if (StoreNodes[i].MemNode == EarliestOp)
9470 continue;
9471 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Rafael Espindolac79532d2012-11-14 05:08:56 +00009472 // ReplaceAllUsesWith will replace all uses that existed when it was
9473 // called, but graph optimizations may cause new ones to appear. For
9474 // example, the case in pr14333 looks like
9475 //
9476 // St's chain -> St -> another store -> X
9477 //
9478 // And the only difference from St to the other store is the chain.
9479 // When we change it's chain to be St's chain they become identical,
9480 // get CSEed and the net result is that X is now a use of St.
9481 // Since we know that St is redundant, just iterate.
9482 while (!St->use_empty())
9483 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
Chandler Carruth18066972014-08-02 10:02:07 +00009484 deleteAndRecombine(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009485 }
9486
9487 return true;
9488 }
9489
9490 // Below we handle the case of multiple consecutive stores that
9491 // come from multiple consecutive loads. We merge them into a single
9492 // wide load and a single wide store.
9493
9494 // Look for load nodes which are used by the stored values.
9495 SmallVector<MemOpLink, 8> LoadNodes;
9496
9497 // Find acceptable loads. Loads need to have the same chain (token factor),
9498 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009499 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009500 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9501 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9502 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9503 if (!Ld) break;
9504
9505 // Loads must only have one use.
9506 if (!Ld->hasNUsesOfValue(1, 0))
9507 break;
9508
9509 // Check that the alignment is the same as the stores.
9510 if (Ld->getAlignment() != St->getAlignment())
9511 break;
9512
9513 // The memory operands must not be volatile.
9514 if (Ld->isVolatile() || Ld->isIndexed())
9515 break;
9516
9517 // We do not accept ext loads.
9518 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9519 break;
9520
9521 // The stored memory type must be the same.
9522 if (Ld->getMemoryVT() != MemVT)
9523 break;
9524
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009525 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009526 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009527 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009528 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009529 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009530 break;
9531 } else {
9532 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009533 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009534 }
9535
9536 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009537 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009538 }
9539
9540 if (LoadNodes.size() < 2)
9541 return false;
9542
James Molloyce45be02014-08-02 14:51:24 +00009543 // If we have load/store pair instructions and we only have two values,
9544 // don't bother.
9545 unsigned RequiredAlignment;
9546 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9547 St->getAlignment() >= RequiredAlignment)
9548 return false;
9549
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009550 // Scan the memory operations on the chain and find the first non-consecutive
9551 // load memory address. These variables hold the index in the store node
9552 // array.
9553 unsigned LastConsecutiveLoad = 0;
9554 // This variable refers to the size and not index in the array.
9555 unsigned LastLegalVectorType = 0;
9556 unsigned LastLegalIntegerType = 0;
9557 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +00009558 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9559 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9560 // All loads much share the same chain.
9561 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9562 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009563
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009564 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9565 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9566 break;
9567 LastConsecutiveLoad = i;
9568
9569 // Find a legal type for the vector store.
9570 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9571 if (TLI.isTypeLegal(StoreTy))
9572 LastLegalVectorType = i + 1;
9573
9574 // Find a legal type for the integer store.
9575 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9576 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9577 if (TLI.isTypeLegal(StoreTy))
9578 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009579 // Or check whether a truncstore and extload is legal.
9580 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9581 TargetLowering::TypePromoteInteger) {
9582 EVT LegalizedStoredValueTy =
9583 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9584 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9585 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9586 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9587 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9588 LastLegalIntegerType = i+1;
9589 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009590 }
9591
9592 // Only use vector types if the vector type is larger than the integer type.
9593 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009594 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009595 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9596
9597 // We add +1 here because the LastXXX variables refer to location while
9598 // the NumElem refers to array/index size.
9599 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9600 NumElem = std::min(LastLegalType, NumElem);
9601
9602 if (NumElem < 2)
9603 return false;
9604
9605 // The earliest Node in the DAG.
9606 unsigned EarliestNodeUsed = 0;
9607 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9608 for (unsigned i=1; i<NumElem; ++i) {
9609 // Find a chain for the new wide-store operand. Notice that some
9610 // of the store nodes that we found may not be selected for inclusion
9611 // in the wide store. The chain we use needs to be the chain of the
9612 // earliest store node which is *used* and replaced by the wide store.
9613 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9614 EarliestNodeUsed = i;
9615 }
9616
9617 // Find if it is better to use vectors or integers to load and store
9618 // to memory.
9619 EVT JointMemOpVT;
9620 if (UseVectorTy) {
9621 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9622 } else {
9623 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9624 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9625 }
9626
Andrew Trickef9de2a2013-05-25 02:42:55 +00009627 SDLoc LoadDL(LoadNodes[0].MemNode);
9628 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009629
9630 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9631 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9632 FirstLoad->getChain(),
9633 FirstLoad->getBasePtr(),
9634 FirstLoad->getPointerInfo(),
9635 false, false, false,
9636 FirstLoad->getAlignment());
9637
9638 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9639 FirstInChain->getBasePtr(),
9640 FirstInChain->getPointerInfo(), false, false,
9641 FirstInChain->getAlignment());
9642
Nadav Rotemac920662012-10-03 19:30:31 +00009643 // Replace one of the loads with the new load.
9644 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9645 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9646 SDValue(NewLoad.getNode(), 1));
9647
9648 // Remove the rest of the load chains.
9649 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009650 // Replace all chain users of the old load nodes with the chain of the new
9651 // load node.
9652 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +00009653 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9654 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009655
Nadav Rotemac920662012-10-03 19:30:31 +00009656 // Replace the first store with the new store.
9657 CombineTo(EarliestOp, NewStore);
9658 // Erase all other stores.
9659 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009660 // Remove all Store nodes.
9661 if (StoreNodes[i].MemNode == EarliestOp)
9662 continue;
9663 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9664 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
Chandler Carruth18066972014-08-02 10:02:07 +00009665 deleteAndRecombine(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009666 }
9667
9668 return true;
9669}
9670
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009671SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +00009672 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009673 SDValue Chain = ST->getChain();
9674 SDValue Value = ST->getValue();
9675 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009676
Evan Chenga4cf58a2007-05-07 21:27:48 +00009677 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +00009678 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +00009679 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009680 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +00009681 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009682 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009683 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00009684 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +00009685 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009686 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +00009687 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009688 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +00009689 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009690 ST->isNonTemporal(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00009691 ST->getAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +00009692 }
Owen Andersona5192842011-04-14 17:30:49 +00009693
Chris Lattner41c80e82011-04-09 02:32:02 +00009694 // Turn 'store undef, Ptr' -> nothing.
9695 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9696 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +00009697
Nate Begeman8e20c762006-12-11 02:23:46 +00009698 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +00009699 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00009700 // NOTE: If the original store is volatile, this transform must not increase
9701 // the number of stores. For example, on x86-32 an f64 can be stored in one
9702 // processor operation but an i64 (which is not legal) requires two. So the
9703 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +00009704 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009705 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +00009706 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00009707 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +00009708 case MVT::f16: // We don't do this for these yet.
9709 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +00009710 case MVT::f128:
9711 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +00009712 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009713 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +00009714 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009715 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +00009716 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +00009717 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009718 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009719 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +00009720 }
9721 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009722 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +00009723 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +00009724 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009725 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00009726 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +00009727 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009728 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009729 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +00009730 }
Owen Andersona5192842011-04-14 17:30:49 +00009731
Chris Lattner41c80e82011-04-09 02:32:02 +00009732 if (!ST->isVolatile() &&
9733 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +00009734 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +00009735 // argument passing. Since this is so common, custom legalize the
9736 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +00009737 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +00009738 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9739 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +00009740 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009741
Dan Gohman2af30632007-07-09 22:18:38 +00009742 unsigned Alignment = ST->getAlignment();
9743 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +00009744 bool isNonTemporal = ST->isNonTemporal();
Hal Finkelcc39b672014-07-24 12:16:19 +00009745 AAMDNodes AAInfo = ST->getAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +00009746
Andrew Trickef9de2a2013-05-25 02:42:55 +00009747 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +00009748 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00009749 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +00009750 ST->getAlignment(), AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009751 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +00009752 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +00009753 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009754 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +00009755 Ptr, ST->getPointerInfo().getWithOffset(4),
9756 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +00009757 Alignment, AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009758 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +00009759 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009760 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009761
Chris Lattnerb7524b62006-12-12 04:16:14 +00009762 break;
Evan Cheng21836982006-12-11 17:25:19 +00009763 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009764 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009765 }
9766
Evan Cheng43cd9e32010-04-01 06:04:33 +00009767 // Try to infer better alignment information than the store already has.
9768 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009769 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9770 if (Align > ST->getAlignment())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009771 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +00009772 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009773 ST->isVolatile(), ST->isNonTemporal(), Align,
Hal Finkelcc39b672014-07-24 12:16:19 +00009774 ST->getAAInfo());
Evan Cheng43cd9e32010-04-01 06:04:33 +00009775 }
9776 }
9777
Evan Chengd42641c2011-02-02 01:06:55 +00009778 // Try transforming a pair floating point load / store ops to integer
9779 // load / store ops.
9780 SDValue NewST = TransformFPLoadStorePair(N);
9781 if (NewST.getNode())
9782 return NewST;
9783
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00009784 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9785 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00009786#ifndef NDEBUG
9787 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9788 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9789 UseAA = false;
9790#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00009791 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009792 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009793 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009794
Jim Laskey708d0db2006-10-04 16:53:27 +00009795 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009796 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009797 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +00009798
9799 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009800 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009801 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009802 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009803 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009804 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009805 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009806 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009807
Jim Laskeyd07be232006-09-25 16:29:54 +00009808 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009809 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009810 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009811
Nate Begeman879d8f12009-09-15 00:18:30 +00009812 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009813 AddToWorklist(Token.getNode());
Nate Begeman879d8f12009-09-15 00:18:30 +00009814
Jim Laskeydcf983c2006-10-13 23:32:28 +00009815 // Don't add users to work list.
9816 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009817 }
Jim Laskey5d19d592006-09-21 16:28:59 +00009818 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009819
Evan Cheng33157702006-11-05 09:31:14 +00009820 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +00009821 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009822 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +00009823
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009824 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009825 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009826 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00009827 // See if we can simplify the input to this truncstore with knowledge that
9828 // only the low bits are being used. For example:
9829 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +00009830 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +00009831 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009832 APInt::getLowBitsSet(
9833 Value.getValueType().getScalarType().getSizeInBits(),
9834 ST->getMemoryVT().getScalarType().getSizeInBits()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009835 AddToWorklist(Value.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00009836 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009837 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009838 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +00009839
Chris Lattnerf47e3062007-10-13 06:58:48 +00009840 // Otherwise, see if we can simplify the operation with
9841 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00009842 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009843 APInt::getLowBitsSet(
9844 Value.getValueType().getScalarType().getSizeInBits(),
9845 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009846 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +00009847 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009848
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009849 // If this is a load followed by a store to the same location, then the store
9850 // is dead/noop.
9851 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009852 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009853 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +00009854 // There can't be any side effects between the load and store, such as
9855 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009856 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009857 // The store is dead, remove it.
9858 return Chain;
9859 }
9860 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009861
James Molloy463db9a2014-09-27 17:02:54 +00009862 // If this is a store followed by a store with the same value to the same
9863 // location, then the store is dead/noop.
9864 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
9865 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
9866 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
9867 ST1->isUnindexed() && !ST1->isVolatile()) {
9868 // The store is dead, remove it.
9869 return Chain;
9870 }
9871 }
9872
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009873 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9874 // truncating store. We can do this even if this is already a truncstore.
9875 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +00009876 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009877 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009878 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009879 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009880 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009881 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009882
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009883 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +00009884 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +00009885 if (!LegalTypes) {
9886 bool EverChanged = false;
9887
9888 do {
9889 // There can be multiple store sequences on the same chain.
9890 // Keep trying to merge store sequences until we are unable to do so
9891 // or until we merge the last store on the chain.
9892 bool Changed = MergeConsecutiveStores(ST);
9893 EverChanged |= Changed;
9894 if (!Changed) break;
9895 } while (ST->getOpcode() != ISD::DELETED_NODE);
9896
9897 if (EverChanged)
9898 return SDValue(N, 0);
9899 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009900
Evan Chenga9cda8a2009-05-28 00:35:15 +00009901 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +00009902}
9903
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009904SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9905 SDValue InVec = N->getOperand(0);
9906 SDValue InVal = N->getOperand(1);
9907 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009908 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009909
Bob Wilson42603952010-05-19 23:42:58 +00009910 // If the inserted element is an UNDEF, just use the input vector.
9911 if (InVal.getOpcode() == ISD::UNDEF)
9912 return InVec;
9913
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009914 EVT VT = InVec.getValueType();
9915
Owen Andersonb2c80da2011-02-25 21:41:48 +00009916 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009917 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9918 return SDValue();
9919
Eli Friedmanb7910b72011-09-09 21:04:06 +00009920 // Check that we know which element is being inserted
9921 if (!isa<ConstantSDNode>(EltNo))
9922 return SDValue();
9923 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009924
Andrea Di Biagiof99dd642014-06-09 16:54:41 +00009925 // Canonicalize insert_vector_elt dag nodes.
9926 // Example:
9927 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9928 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9929 //
9930 // Do this only if the child insert_vector node has one use; also
9931 // do this only if indices are both constants and Idx1 < Idx0.
9932 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9933 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9934 unsigned OtherElt =
9935 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9936 if (Elt < OtherElt) {
9937 // Swap nodes.
9938 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9939 InVec.getOperand(0), InVal, EltNo);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009940 AddToWorklist(NewOp.getNode());
Andrea Di Biagiof99dd642014-06-09 16:54:41 +00009941 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9942 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9943 }
9944 }
9945
Eli Friedmanb7910b72011-09-09 21:04:06 +00009946 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9947 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9948 // vector elements.
9949 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +00009950 // Do not combine these two vectors if the output vector will not replace
9951 // the input vector.
9952 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +00009953 Ops.append(InVec.getNode()->op_begin(),
9954 InVec.getNode()->op_end());
9955 } else if (InVec.getOpcode() == ISD::UNDEF) {
9956 unsigned NElts = VT.getVectorNumElements();
9957 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9958 } else {
9959 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +00009960 }
Eli Friedmanb7910b72011-09-09 21:04:06 +00009961
9962 // Insert the element
9963 if (Elt < Ops.size()) {
9964 // All the operands of BUILD_VECTOR must have the same type;
9965 // we enforce that here.
9966 EVT OpVT = Ops[0].getValueType();
9967 if (InVal.getValueType() != OpVT)
9968 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9969 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9970 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9971 Ops[Elt] = InVal;
9972 }
9973
9974 // Return the new vector
Craig Topper48d114b2014-04-26 18:35:24 +00009975 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
Chris Lattner5336a592006-03-19 01:27:56 +00009976}
9977
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +00009978SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9979 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9980 EVT ResultVT = EVE->getValueType(0);
9981 EVT VecEltVT = InVecVT.getVectorElementType();
9982 unsigned Align = OriginalLoad->getAlignment();
9983 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9984 VecEltVT.getTypeForEVT(*DAG.getContext()));
9985
9986 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9987 return SDValue();
9988
9989 Align = NewAlign;
9990
9991 SDValue NewPtr = OriginalLoad->getBasePtr();
9992 SDValue Offset;
9993 EVT PtrType = NewPtr.getValueType();
9994 MachinePointerInfo MPI;
9995 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9996 int Elt = ConstEltNo->getZExtValue();
9997 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9998 if (TLI.isBigEndian())
9999 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10000 Offset = DAG.getConstant(PtrOff, PtrType);
10001 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10002 } else {
10003 Offset = DAG.getNode(
10004 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10005 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10006 if (TLI.isBigEndian())
10007 Offset = DAG.getNode(
10008 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10009 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10010 MPI = OriginalLoad->getPointerInfo();
10011 }
10012 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10013
10014 // The replacement we need to do here is a little tricky: we need to
10015 // replace an extractelement of a load with a load.
10016 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10017 // Note that this replacement assumes that the extractvalue is the only
10018 // use of the load; that's okay because we don't want to perform this
10019 // transformation in other cases anyway.
10020 SDValue Load;
10021 SDValue Chain;
10022 if (ResultVT.bitsGT(VecEltVT)) {
10023 // If the result type of vextract is wider than the load, then issue an
10024 // extending load instead.
10025 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
10026 ? ISD::ZEXTLOAD
10027 : ISD::EXTLOAD;
10028 Load = DAG.getExtLoad(
10029 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10030 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10031 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10032 Chain = Load.getValue(1);
10033 } else {
10034 Load = DAG.getLoad(
10035 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10036 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10037 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10038 Chain = Load.getValue(1);
10039 if (ResultVT.bitsLT(VecEltVT))
10040 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10041 else
10042 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10043 }
10044 WorklistRemover DeadNodes(*this);
10045 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10046 SDValue To[] = { Load, Chain };
10047 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10048 // Since we're explicitly calling ReplaceAllUses, add the new node to the
10049 // worklist explicitly as well.
10050 AddToWorklist(Load.getNode());
10051 AddUsersToWorklist(Load.getNode()); // Add users too
10052 // Make sure to revisit this node to clean it up; it will usually be dead.
10053 AddToWorklist(EVE);
10054 ++OpsNarrowed;
10055 return SDValue(EVE, 0);
10056}
10057
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010058SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +000010059 // (vextract (scalar_to_vector val, 0) -> val
10060 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010061 EVT VT = InVec.getValueType();
10062 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +000010063
Duncan Sands6be291a2011-05-09 08:03:33 +000010064 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10065 // Check if the result type doesn't match the inserted element type. A
10066 // SCALAR_TO_VECTOR may truncate the inserted element and the
10067 // EXTRACT_VECTOR_ELT may widen the extracted vector.
10068 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +000010069 if (InOp.getValueType() != NVT) {
10070 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +000010071 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +000010072 }
10073 return InOp;
10074 }
Evan Cheng1120279a2008-05-13 08:35:03 +000010075
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010076 SDValue EltNo = N->getOperand(1);
10077 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10078
10079 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10080 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +000010081 // we may introduce new vector instructions which are not backed by TD
10082 // patterns. For example on AVX, extracting elements from a wide vector
Hal Finkel02807592014-03-31 11:43:19 +000010083 // without using extract_subvector. However, if we can find an underlying
10084 // scalar value, then we can always use that.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010085 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Hal Finkel02807592014-03-31 11:43:19 +000010086 && ConstEltNo) {
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010087 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10088 int NumElem = VT.getVectorNumElements();
10089 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10090 // Find the new index to extract from.
10091 int OrigElt = SVOp->getMaskElt(Elt);
10092
10093 // Extracting an undef index is undef.
10094 if (OrigElt == -1)
10095 return DAG.getUNDEF(NVT);
10096
10097 // Select the right vector half to extract from.
Hal Finkel02807592014-03-31 11:43:19 +000010098 SDValue SVInVec;
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010099 if (OrigElt < NumElem) {
Hal Finkel02807592014-03-31 11:43:19 +000010100 SVInVec = InVec->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010101 } else {
Hal Finkel02807592014-03-31 11:43:19 +000010102 SVInVec = InVec->getOperand(1);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010103 OrigElt -= NumElem;
10104 }
10105
Hal Finkel02807592014-03-31 11:43:19 +000010106 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10107 SDValue InOp = SVInVec.getOperand(OrigElt);
10108 if (InOp.getValueType() != NVT) {
10109 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10110 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10111 }
10112
10113 return InOp;
10114 }
10115
10116 // FIXME: We should handle recursing on other vector shuffles and
10117 // scalar_to_vector here as well.
10118
10119 if (!LegalOperations) {
10120 EVT IndexTy = TLI.getVectorIdxTy();
10121 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10122 SVInVec, DAG.getConstant(OrigElt, IndexTy));
10123 }
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010124 }
10125
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010126 bool BCNumEltsChanged = false;
10127 EVT ExtVT = VT.getVectorElementType();
10128 EVT LVT = ExtVT;
10129
10130 // If the result of load has to be truncated, then it's not necessarily
10131 // profitable.
10132 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10133 return SDValue();
10134
10135 if (InVec.getOpcode() == ISD::BITCAST) {
10136 // Don't duplicate a load with other uses.
10137 if (!InVec.hasOneUse())
10138 return SDValue();
10139
10140 EVT BCVT = InVec.getOperand(0).getValueType();
10141 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10142 return SDValue();
10143 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10144 BCNumEltsChanged = true;
10145 InVec = InVec.getOperand(0);
10146 ExtVT = BCVT.getVectorElementType();
10147 }
10148
10149 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10150 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10151 ISD::isNormalLoad(InVec.getNode()) &&
10152 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10153 SDValue Index = N->getOperand(1);
10154 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10155 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10156 OrigLoad);
10157 }
10158
Evan Cheng1120279a2008-05-13 08:35:03 +000010159 // Perform only after legalization to ensure build_vector / vector_shuffle
10160 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010161 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000010162
Mon P Wangca6d6de2009-01-17 00:07:25 +000010163 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10164 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10165 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +000010166
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010167 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +000010168 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000010169
Craig Topperc0196b12014-04-14 00:51:57 +000010170 LoadSDNode *LN0 = nullptr;
10171 const ShuffleVectorSDNode *SVN = nullptr;
Bill Wendling27d9dd42009-01-30 23:36:47 +000010172 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010173 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +000010174 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +000010175 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +000010176 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +000010177 // Don't duplicate a load with other uses.
10178 if (!InVec.hasOneUse())
10179 return SDValue();
10180
Evan Cheng1120279a2008-05-13 08:35:03 +000010181 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +000010182 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010183 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10184 // =>
10185 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +000010186
Eli Friedmane96286c2011-12-26 22:49:32 +000010187 // Don't duplicate a load with other uses.
10188 if (!InVec.hasOneUse())
10189 return SDValue();
10190
Mon P Wangb5eb7202008-12-11 00:26:16 +000010191 // If the bit convert changed the number of elements, it is unsafe
10192 // to examine the mask.
10193 if (BCNumEltsChanged)
10194 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +000010195
10196 // Select the input vector, guarding against out of range extract vector.
10197 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +000010198 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +000010199 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10200
Eli Friedmane96286c2011-12-26 22:49:32 +000010201 if (InVec.getOpcode() == ISD::BITCAST) {
10202 // Don't duplicate a load with other uses.
10203 if (!InVec.hasOneUse())
10204 return SDValue();
10205
Evan Cheng1120279a2008-05-13 08:35:03 +000010206 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +000010207 }
Gabor Greiff304a7a2008-08-28 21:40:38 +000010208 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010209 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +000010210 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010211 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
Evan Cheng0de312d2007-10-06 08:19:55 +000010212 }
10213 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010214
Eli Friedmane96286c2011-12-26 22:49:32 +000010215 // Make sure we found a non-volatile load and the extractelement is
10216 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +000010217 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010218 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000010219
Eric Christopherc6418b12010-11-03 20:44:42 +000010220 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10221 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +000010222 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +000010223
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010224 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
Evan Cheng0de312d2007-10-06 08:19:55 +000010225 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010226
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010227 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000010228}
Evan Cheng0de312d2007-10-06 08:19:55 +000010229
Michael Liao6d106b72012-10-23 23:06:52 +000010230// Simplify (build_vec (ext )) to (bitcast (build_vec ))
10231SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10232 // We perform this optimization post type-legalization because
10233 // the type-legalizer often scalarizes integer-promoted vectors.
10234 // Performing this optimization before may create bit-casts which
10235 // will be type-legalized to complex code sequences.
10236 // We perform this optimization only before the operation legalizer because we
10237 // may introduce illegal operations.
10238 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10239 return SDValue();
10240
Dan Gohmana8665142007-06-25 16:23:39 +000010241 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010242 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +000010243 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010244
Nadav Rotembf6568b2011-10-29 21:23:04 +000010245 // Check to see if this is a BUILD_VECTOR of a bunch of values
10246 // which come from any_extend or zero_extend nodes. If so, we can create
10247 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +000010248 // optimizations. We do not handle sign-extend because we can't fill the sign
10249 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010250 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +000010251 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +000010252
Craig Topper02cb0fb2012-01-17 09:09:48 +000010253 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +000010254 SDValue In = N->getOperand(i);
10255 // Ignore undef inputs.
10256 if (In.getOpcode() == ISD::UNDEF) continue;
10257
10258 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10259 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10260
Nadav Rotemf3103612011-10-31 20:08:25 +000010261 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010262 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +000010263 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010264 break;
10265 }
10266
10267 // The input is a ZeroExt or AnyExt. Check the original type.
10268 EVT InTy = In.getOperand(0).getValueType();
10269
10270 // Check that all of the widened source types are the same.
10271 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +000010272 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010273 SourceType = InTy;
10274 else if (InTy != SourceType) {
10275 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +000010276 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010277 break;
10278 }
10279
10280 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +000010281 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010282 }
10283
Nadav Rotemf3103612011-10-31 20:08:25 +000010284 // In order to have valid types, all of the inputs must be extended from the
10285 // same source type and all of the inputs must be any or zero extend.
10286 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +000010287 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010288 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +000010289 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10290 isPowerOf2_32(SourceType.getSizeInBits());
10291
Nadav Rotem6fd1d322012-03-15 08:49:06 +000010292 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10293 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +000010294 if (!ValidTypes)
10295 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +000010296
Michael Liao6d106b72012-10-23 23:06:52 +000010297 bool isLE = TLI.isLittleEndian();
10298 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10299 assert(ElemRatio > 1 && "Invalid element size ratio");
10300 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10301 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010302
Michael Liao6d106b72012-10-23 23:06:52 +000010303 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10304 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010305
Michael Liao6d106b72012-10-23 23:06:52 +000010306 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +000010307 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +000010308 SDValue Cast = N->getOperand(i);
10309 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10310 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10311 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10312 SDValue In;
10313 if (Cast.getOpcode() == ISD::UNDEF)
10314 In = DAG.getUNDEF(SourceType);
10315 else
10316 In = Cast->getOperand(0);
10317 unsigned Index = isLE ? (i * ElemRatio) :
10318 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +000010319
Michael Liao6d106b72012-10-23 23:06:52 +000010320 assert(Index < Ops.size() && "Invalid index");
10321 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010322 }
Chris Lattner5336a592006-03-19 01:27:56 +000010323
Michael Liao6d106b72012-10-23 23:06:52 +000010324 // The type of the new BUILD_VECTOR node.
10325 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10326 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10327 "Invalid vector size");
10328 // Check if the new vector type is legal.
10329 if (!isTypeLegal(VecVT)) return SDValue();
10330
10331 // Make the new BUILD_VECTOR.
Craig Topper48d114b2014-04-26 18:35:24 +000010332 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
Michael Liao6d106b72012-10-23 23:06:52 +000010333
10334 // The new BUILD_VECTOR node has the potential to be further optimized.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010335 AddToWorklist(BV.getNode());
Michael Liao6d106b72012-10-23 23:06:52 +000010336 // Bitcast to the desired type.
10337 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10338}
10339
Michael Liao59229792012-10-24 04:14:18 +000010340SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10341 EVT VT = N->getValueType(0);
10342
10343 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010344 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +000010345
10346 EVT SrcVT = MVT::Other;
10347 unsigned Opcode = ISD::DELETED_NODE;
10348 unsigned NumDefs = 0;
10349
10350 for (unsigned i = 0; i != NumInScalars; ++i) {
10351 SDValue In = N->getOperand(i);
10352 unsigned Opc = In.getOpcode();
10353
10354 if (Opc == ISD::UNDEF)
10355 continue;
10356
10357 // If all scalar values are floats and converted from integers.
10358 if (Opcode == ISD::DELETED_NODE &&
10359 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10360 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +000010361 }
Tom Stellard567f8862013-01-02 22:13:01 +000010362
Michael Liao59229792012-10-24 04:14:18 +000010363 if (Opc != Opcode)
10364 return SDValue();
10365
10366 EVT InVT = In.getOperand(0).getValueType();
10367
10368 // If all scalar values are typed differently, bail out. It's chosen to
10369 // simplify BUILD_VECTOR of integer types.
10370 if (SrcVT == MVT::Other)
10371 SrcVT = InVT;
10372 if (SrcVT != InVT)
10373 return SDValue();
10374 NumDefs++;
10375 }
10376
10377 // If the vector has just one element defined, it's not worth to fold it into
10378 // a vectorized one.
10379 if (NumDefs < 2)
10380 return SDValue();
10381
10382 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10383 && "Should only handle conversion from integer to float.");
10384 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10385
10386 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000010387
10388 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10389 return SDValue();
10390
Michael Liao59229792012-10-24 04:14:18 +000010391 SmallVector<SDValue, 8> Opnds;
10392 for (unsigned i = 0; i != NumInScalars; ++i) {
10393 SDValue In = N->getOperand(i);
10394
10395 if (In.getOpcode() == ISD::UNDEF)
10396 Opnds.push_back(DAG.getUNDEF(SrcVT));
10397 else
10398 Opnds.push_back(In.getOperand(0));
10399 }
Craig Topper48d114b2014-04-26 18:35:24 +000010400 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010401 AddToWorklist(BV.getNode());
Michael Liao59229792012-10-24 04:14:18 +000010402
10403 return DAG.getNode(Opcode, dl, VT, BV);
10404}
10405
Michael Liao6d106b72012-10-23 23:06:52 +000010406SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10407 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010408 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000010409 EVT VT = N->getValueType(0);
10410
10411 // A vector built entirely of undefs is undef.
10412 if (ISD::allOperandsUndef(N))
10413 return DAG.getUNDEF(VT);
10414
10415 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10416 if (V.getNode())
10417 return V;
10418
Michael Liao59229792012-10-24 04:14:18 +000010419 V = reduceBuildVecConvertToConvertBuildVec(N);
10420 if (V.getNode())
10421 return V;
10422
Dan Gohmana8665142007-06-25 16:23:39 +000010423 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10424 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10425 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010426
Andrea Di Biagioc7c52412014-09-30 15:30:22 +000010427 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10428 if (!isTypeLegal(VT))
10429 return SDValue();
10430
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010431 // May only combine to shuffle after legalize if shuffle is legal.
Owen Anderson3eb910b2014-08-28 17:49:58 +000010432 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010433 return SDValue();
10434
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010435 SDValue VecIn1, VecIn2;
Chris Lattnerc9992542006-03-28 20:28:38 +000010436 for (unsigned i = 0; i != NumInScalars; ++i) {
10437 // Ignore undef inputs.
10438 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010439
Dan Gohmana8665142007-06-25 16:23:39 +000010440 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000010441 // constant index, bail out.
Dan Gohmana8665142007-06-25 16:23:39 +000010442 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Chris Lattnerc9992542006-03-28 20:28:38 +000010443 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
Craig Topperc0196b12014-04-14 00:51:57 +000010444 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010445 break;
10446 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010447
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010448 // We allow up to two distinct input vectors.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010449 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010450 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10451 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010452
Craig Topperc0196b12014-04-14 00:51:57 +000010453 if (!VecIn1.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010454 VecIn1 = ExtractedFromVec;
Craig Topperc0196b12014-04-14 00:51:57 +000010455 } else if (!VecIn2.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010456 VecIn2 = ExtractedFromVec;
10457 } else {
10458 // Too many inputs.
Craig Topperc0196b12014-04-14 00:51:57 +000010459 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010460 break;
10461 }
10462 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010463
Jim Grosbach2eb60fd2014-04-29 22:41:50 +000010464 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010465 if (VecIn1.getNode()) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010466 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000010467 for (unsigned i = 0; i != NumInScalars; ++i) {
10468 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010469 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010470 continue;
10471 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010472
Rafael Espindolab93db662009-04-24 12:40:33 +000010473 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010474 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000010475 SDValue ExtVal = Extract.getOperand(1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010476 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000010477 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10478 if (ExtIndex > VT.getVectorNumElements())
10479 return SDValue();
Wesley Peck527da1b2010-11-23 03:31:01 +000010480
Nate Begeman5f829d82009-04-29 05:20:52 +000010481 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000010482 continue;
10483 }
10484
10485 // Otherwise, use InIdx + VecSize
Mon P Wang523c0852009-03-17 06:33:10 +000010486 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010487 Mask.push_back(Idx+NumInScalars);
Chris Lattnerc9992542006-03-28 20:28:38 +000010488 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010489
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010490 // We can't generate a shuffle node with mismatched input and output types.
10491 // Attempt to transform a single input vector to the correct type.
10492 if ((VT != VecIn1.getValueType())) {
10493 // We don't support shuffeling between TWO values of different types.
Craig Topperc0196b12014-04-14 00:51:57 +000010494 if (VecIn2.getNode())
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010495 return SDValue();
10496
10497 // We only support widening of vectors which are half the size of the
10498 // output registers. For example XMM->YMM widening on X86 with AVX.
10499 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10500 return SDValue();
10501
James Molloy1e5c6112012-09-10 14:01:21 +000010502 // If the input vector type has a different base type to the output
10503 // vector type, bail out.
10504 if (VecIn1.getValueType().getVectorElementType() !=
10505 VT.getVectorElementType())
10506 return SDValue();
10507
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010508 // Widen the input vector by adding undef values.
Michael Liao6d106b72012-10-23 23:06:52 +000010509 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010510 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010511 }
10512
10513 // If VecIn2 is unused then change it to undef.
10514 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10515
Nadav Rotem841c9a82012-09-20 08:53:31 +000010516 // Check that we were able to transform all incoming values to the same
10517 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000010518 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10519 VecIn1.getValueType() != VT)
10520 return SDValue();
10521
Dan Gohmana8665142007-06-25 16:23:39 +000010522 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010523 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000010524 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010525 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000010526 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000010527 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010528
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010529 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000010530}
10531
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010532SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000010533 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10534 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10535 // inputs come from at most two distinct vectors, turn this into a shuffle
10536 // node.
10537
10538 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000010539 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000010540 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010541
Nadav Rotem01892102012-07-14 21:30:27 +000010542 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010543 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010544 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010545 return DAG.getUNDEF(VT);
10546
10547 // Optimize concat_vectors where one of the vectors is undef.
10548 if (N->getNumOperands() == 2 &&
10549 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10550 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000010551 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010552
10553 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10554 if (In->getOpcode() == ISD::BITCAST &&
10555 !In->getOperand(0)->getValueType(0).isVector()) {
10556 SDValue Scalar = In->getOperand(0);
10557 EVT SclTy = Scalar->getValueType(0);
10558
10559 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10560 return SDValue();
10561
10562 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10563 VT.getSizeInBits() / SclTy.getSizeInBits());
10564 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10565 return SDValue();
10566
10567 SDLoc dl = SDLoc(N);
10568 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10569 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10570 }
10571 }
Nadav Rotem01892102012-07-14 21:30:27 +000010572
Robert Lougher7d9084f2014-02-11 15:42:46 +000010573 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10574 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10575 if (N->getNumOperands() == 2 &&
10576 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10577 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10578 EVT VT = N->getValueType(0);
10579 SDValue N0 = N->getOperand(0);
10580 SDValue N1 = N->getOperand(1);
10581 SmallVector<SDValue, 8> Opnds;
10582 unsigned BuildVecNumElts = N0.getNumOperands();
10583
Hao Liu71224b02014-07-10 03:41:50 +000010584 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10585 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10586 if (SclTy0.isFloatingPoint()) {
10587 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10588 Opnds.push_back(N0.getOperand(i));
10589 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10590 Opnds.push_back(N1.getOperand(i));
10591 } else {
10592 // If BUILD_VECTOR are from built from integer, they may have different
10593 // operand types. Get the smaller type and truncate all operands to it.
10594 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10595 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10596 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10597 N0.getOperand(i)));
10598 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10599 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10600 N1.getOperand(i)));
10601 }
Robert Lougher7d9084f2014-02-11 15:42:46 +000010602
Craig Topper48d114b2014-04-26 18:35:24 +000010603 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Robert Lougher7d9084f2014-02-11 15:42:46 +000010604 }
10605
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010606 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10607 // nodes often generate nop CONCAT_VECTOR nodes.
10608 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10609 // place the incoming vectors at the exact same location.
10610 SDValue SingleSource = SDValue();
10611 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10612
10613 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10614 SDValue Op = N->getOperand(i);
10615
10616 if (Op.getOpcode() == ISD::UNDEF)
10617 continue;
10618
10619 // Check if this is the identity extract:
10620 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10621 return SDValue();
10622
10623 // Find the single incoming vector for the extract_subvector.
10624 if (SingleSource.getNode()) {
10625 if (Op.getOperand(0) != SingleSource)
10626 return SDValue();
10627 } else {
10628 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000010629
10630 // Check the source type is the same as the type of the result.
10631 // If not, this concat may extend the vector, so we can not
10632 // optimize it away.
10633 if (SingleSource.getValueType() != N->getValueType(0))
10634 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010635 }
10636
10637 unsigned IdentityIndex = i * PartNumElem;
10638 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10639 // The extract index must be constant.
10640 if (!CS)
10641 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000010642
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010643 // Check that we are reading from the identity index.
10644 if (CS->getZExtValue() != IdentityIndex)
10645 return SDValue();
10646 }
10647
10648 if (SingleSource.getNode())
10649 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000010650
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010651 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000010652}
10653
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010654SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10655 EVT NVT = N->getValueType(0);
10656 SDValue V = N->getOperand(0);
10657
Michael Liao7a442c802012-10-17 20:48:33 +000010658 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10659 // Combine:
10660 // (extract_subvec (concat V1, V2, ...), i)
10661 // Into:
10662 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000010663 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10664 // type.
Michael Liao2c235802012-10-19 03:17:00 +000010665 if (V->getOperand(0).getValueType() != NVT)
10666 return SDValue();
Michael Liao7a442c802012-10-17 20:48:33 +000010667 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10668 unsigned NumElems = NVT.getVectorNumElements();
10669 assert((Idx % NumElems) == 0 &&
10670 "IDX in concat is not a multiple of the result vector length.");
10671 return V->getOperand(Idx / NumElems);
10672 }
10673
Michael Liaobb05a1d2013-03-25 23:47:35 +000010674 // Skip bitcasting
10675 if (V->getOpcode() == ISD::BITCAST)
10676 V = V.getOperand(0);
10677
10678 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010679 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000010680 // Handle only simple case where vector being inserted and vector
10681 // being extracted are of same type, and are half size of larger vectors.
10682 EVT BigVT = V->getOperand(0).getValueType();
10683 EVT SmallVT = V->getOperand(1).getValueType();
10684 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10685 return SDValue();
10686
10687 // Only handle cases where both indexes are constants with the same type.
10688 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10689 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10690
10691 if (InsIdx && ExtIdx &&
10692 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10693 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10694 // Combine:
10695 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10696 // Into:
10697 // indices are equal or bit offsets are equal => V1
10698 // otherwise => (extract_subvec V1, ExtIdx)
10699 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10700 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10701 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10702 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10703 DAG.getNode(ISD::BITCAST, dl,
10704 N->getOperand(0).getValueType(),
10705 V->getOperand(0)), N->getOperand(1));
10706 }
10707 }
10708
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010709 return SDValue();
10710}
10711
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000010712static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
10713 SDValue V, SelectionDAG &DAG) {
10714 SDLoc DL(V);
10715 EVT VT = V.getValueType();
10716
10717 switch (V.getOpcode()) {
10718 default:
10719 return V;
10720
10721 case ISD::CONCAT_VECTORS: {
10722 EVT OpVT = V->getOperand(0).getValueType();
10723 int OpSize = OpVT.getVectorNumElements();
10724 SmallBitVector OpUsedElements(OpSize, false);
10725 bool FoundSimplification = false;
10726 SmallVector<SDValue, 4> NewOps;
10727 NewOps.reserve(V->getNumOperands());
10728 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
10729 SDValue Op = V->getOperand(i);
10730 bool OpUsed = false;
10731 for (int j = 0; j < OpSize; ++j)
10732 if (UsedElements[i * OpSize + j]) {
10733 OpUsedElements[j] = true;
10734 OpUsed = true;
10735 }
10736 NewOps.push_back(
10737 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
10738 : DAG.getUNDEF(OpVT));
10739 FoundSimplification |= Op == NewOps.back();
10740 OpUsedElements.reset();
10741 }
10742 if (FoundSimplification)
10743 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
10744 return V;
10745 }
10746
10747 case ISD::INSERT_SUBVECTOR: {
10748 SDValue BaseV = V->getOperand(0);
10749 SDValue SubV = V->getOperand(1);
10750 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
10751 if (!IdxN)
10752 return V;
10753
10754 int SubSize = SubV.getValueType().getVectorNumElements();
10755 int Idx = IdxN->getZExtValue();
10756 bool SubVectorUsed = false;
10757 SmallBitVector SubUsedElements(SubSize, false);
10758 for (int i = 0; i < SubSize; ++i)
10759 if (UsedElements[i + Idx]) {
10760 SubVectorUsed = true;
10761 SubUsedElements[i] = true;
10762 UsedElements[i + Idx] = false;
10763 }
10764
10765 // Now recurse on both the base and sub vectors.
10766 SDValue SimplifiedSubV =
10767 SubVectorUsed
10768 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
10769 : DAG.getUNDEF(SubV.getValueType());
10770 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
10771 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
10772 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
10773 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
10774 return V;
10775 }
10776 }
10777}
10778
10779static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
10780 SDValue N1, SelectionDAG &DAG) {
10781 EVT VT = SVN->getValueType(0);
10782 int NumElts = VT.getVectorNumElements();
10783 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
10784 for (int M : SVN->getMask())
10785 if (M >= 0 && M < NumElts)
10786 N0UsedElements[M] = true;
10787 else if (M >= NumElts)
10788 N1UsedElements[M - NumElts] = true;
10789
10790 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
10791 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
10792 if (S0 == N0 && S1 == N1)
10793 return SDValue();
10794
10795 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
10796}
10797
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010798// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10799static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10800 EVT VT = N->getValueType(0);
10801 unsigned NumElts = VT.getVectorNumElements();
10802
10803 SDValue N0 = N->getOperand(0);
10804 SDValue N1 = N->getOperand(1);
10805 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10806
10807 SmallVector<SDValue, 4> Ops;
10808 EVT ConcatVT = N0.getOperand(0).getValueType();
10809 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10810 unsigned NumConcats = NumElts / NumElemsPerConcat;
10811
10812 // Look at every vector that's inserted. We're looking for exact
10813 // subvector-sized copies from a concatenated vector
10814 for (unsigned I = 0; I != NumConcats; ++I) {
10815 // Make sure we're dealing with a copy.
10816 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000010817 bool AllUndef = true, NoUndef = true;
10818 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10819 if (SVN->getMaskElt(J) >= 0)
10820 AllUndef = false;
10821 else
10822 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010823 }
10824
Hao Liubc601962013-05-13 02:07:05 +000010825 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000010826 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10827 return SDValue();
10828
10829 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10830 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10831 return SDValue();
10832
10833 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10834 if (FirstElt < N0.getNumOperands())
10835 Ops.push_back(N0.getOperand(FirstElt));
10836 else
10837 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10838
10839 } else if (AllUndef) {
10840 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10841 } else { // Mixed with general masks and undefs, can't do optimization.
10842 return SDValue();
10843 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010844 }
10845
Craig Topper48d114b2014-04-26 18:35:24 +000010846 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010847}
10848
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010849SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010850 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010851 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010852
Mon P Wang25f01062008-11-10 04:46:22 +000010853 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000010854 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000010855
Craig Topper5894fe42012-04-09 05:16:56 +000010856 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000010857
Craig Topper279c77b2012-01-04 08:07:43 +000010858 // Canonicalize shuffle undef, undef -> undef
10859 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10860 return DAG.getUNDEF(VT);
10861
10862 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10863
10864 // Canonicalize shuffle v, v -> v, undef
10865 if (N0 == N1) {
10866 SmallVector<int, 8> NewMask;
10867 for (unsigned i = 0; i != NumElts; ++i) {
10868 int Idx = SVN->getMaskElt(i);
10869 if (Idx >= (int)NumElts) Idx -= NumElts;
10870 NewMask.push_back(Idx);
10871 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010872 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010873 &NewMask[0]);
10874 }
10875
10876 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10877 if (N0.getOpcode() == ISD::UNDEF) {
10878 SmallVector<int, 8> NewMask;
10879 for (unsigned i = 0; i != NumElts; ++i) {
10880 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000010881 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000010882 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000010883 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000010884 else
10885 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000010886 }
10887 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000010888 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010889 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010890 &NewMask[0]);
10891 }
10892
10893 // Remove references to rhs if it is undef
10894 if (N1.getOpcode() == ISD::UNDEF) {
10895 bool Changed = false;
10896 SmallVector<int, 8> NewMask;
10897 for (unsigned i = 0; i != NumElts; ++i) {
10898 int Idx = SVN->getMaskElt(i);
10899 if (Idx >= (int)NumElts) {
10900 Idx = -1;
10901 Changed = true;
10902 }
10903 NewMask.push_back(Idx);
10904 }
10905 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000010906 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000010907 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000010908
Bob Wilsonf63da122010-10-28 17:06:14 +000010909 // If it is a splat, check if the argument vector is another splat or a
10910 // build_vector with all scalar elements the same.
Bob Wilsonf63da122010-10-28 17:06:14 +000010911 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000010912 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000010913
Dan Gohmana8665142007-06-25 16:23:39 +000010914 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000010915 // not the number of vector elements, look through it. Be careful not to
10916 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000010917 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010918 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000010919 if (ConvInput.getValueType().isVector() &&
10920 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000010921 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000010922 }
10923
Dan Gohmana8665142007-06-25 16:23:39 +000010924 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000010925 assert(V->getNumOperands() == NumElts &&
10926 "BUILD_VECTOR has wrong number of operands");
10927 SDValue Base;
10928 bool AllSame = true;
10929 for (unsigned i = 0; i != NumElts; ++i) {
10930 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10931 Base = V->getOperand(i);
10932 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000010933 }
Evan Cheng7c970b92006-07-21 08:25:53 +000010934 }
Bob Wilsonf63da122010-10-28 17:06:14 +000010935 // Splat of <u, u, u, u>, return <u, u, u, u>
10936 if (!Base.getNode())
10937 return N0;
10938 for (unsigned i = 0; i != NumElts; ++i) {
10939 if (V->getOperand(i) != Base) {
10940 AllSame = false;
10941 break;
10942 }
10943 }
10944 // Splat of <x, x, x, x>, return <x, x, x, x>
10945 if (AllSame)
10946 return N0;
Evan Cheng7c970b92006-07-21 08:25:53 +000010947 }
10948 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010949
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000010950 // There are various patterns used to build up a vector from smaller vectors,
10951 // subvectors, or elements. Scan chains of these and replace unused insertions
10952 // or components with undef.
10953 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
10954 return S;
10955
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010956 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10957 Level < AfterLegalizeVectorOps &&
10958 (N1.getOpcode() == ISD::UNDEF ||
10959 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10960 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10961 SDValue V = partitionShuffleOfConcats(N, DAG);
10962
10963 if (V.getNode())
10964 return V;
10965 }
10966
Nadav Rotemb0783502012-04-01 19:31:22 +000010967 // If this shuffle node is simply a swizzle of another shuffle node,
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010968 // then try to simplify it.
Nadav Rotemb0783502012-04-01 19:31:22 +000010969 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10970 N1.getOpcode() == ISD::UNDEF) {
10971
Nadav Rotemb0783502012-04-01 19:31:22 +000010972 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10973
Craig Topper5894fe42012-04-09 05:16:56 +000010974 // The incoming shuffle must be of the same type as the result of the
10975 // current shuffle.
10976 assert(OtherSV->getOperand(0).getValueType() == VT &&
10977 "Shuffle types don't match");
Nadav Rotemb0783502012-04-01 19:31:22 +000010978
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010979 SmallVector<int, 4> Mask;
10980 // Compute the combined shuffle mask.
Nadav Rotemb0783502012-04-01 19:31:22 +000010981 for (unsigned i = 0; i != NumElts; ++i) {
10982 int Idx = SVN->getMaskElt(i);
Craig Topper5894fe42012-04-09 05:16:56 +000010983 assert(Idx < (int)NumElts && "Index references undef operand");
Nadav Rotemb0783502012-04-01 19:31:22 +000010984 // Next, this index comes from the first value, which is the incoming
10985 // shuffle. Adopt the incoming index.
10986 if (Idx >= 0)
10987 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010988 Mask.push_back(Idx);
Nadav Rotemb0783502012-04-01 19:31:22 +000010989 }
Andrea Di Biagiob23bad12014-08-16 00:29:44 +000010990
10991 // Check if all indices in Mask are Undef. In case, propagate Undef.
10992 bool isUndefMask = true;
10993 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10994 isUndefMask &= Mask[i] < 0;
10995
10996 if (isUndefMask)
10997 return DAG.getUNDEF(VT);
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010998
10999 bool CommuteOperands = false;
11000 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
11001 // To be valid, the combine shuffle mask should only reference elements
11002 // from one of the two vectors in input to the inner shufflevector.
11003 bool IsValidMask = true;
11004 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
11005 // See if the combined mask only reference undefs or elements coming
11006 // from the first shufflevector operand.
11007 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
Nadav Rotem71d07ae2012-04-07 21:19:08 +000011008
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000011009 if (!IsValidMask) {
11010 IsValidMask = true;
11011 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
11012 // Check that all the elements come from the second shuffle operand.
11013 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
11014 CommuteOperands = IsValidMask;
11015 }
11016
11017 // Early exit if the combined shuffle mask is not valid.
11018 if (!IsValidMask)
11019 return SDValue();
11020 }
11021
11022 // See if this pair of shuffles can be safely folded according to either
11023 // of the following rules:
11024 // shuffle(shuffle(x, y), undef) -> x
11025 // shuffle(shuffle(x, undef), undef) -> x
11026 // shuffle(shuffle(x, y), undef) -> y
Andrea Di Biagiod261e982014-07-08 15:22:29 +000011027 bool IsIdentityMask = true;
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000011028 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
Andrea Di Biagiod261e982014-07-08 15:22:29 +000011029 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
11030 // Skip Undefs.
11031 if (Mask[i] < 0)
11032 continue;
11033
11034 // The combined shuffle must map each index to itself.
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000011035 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
Andrea Di Biagiod261e982014-07-08 15:22:29 +000011036 }
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000011037
11038 if (IsIdentityMask) {
11039 if (CommuteOperands)
11040 // optimize shuffle(shuffle(x, y), undef) -> y.
11041 return OtherSV->getOperand(1);
11042
11043 // optimize shuffle(shuffle(x, undef), undef) -> x
11044 // optimize shuffle(shuffle(x, y), undef) -> x
Andrea Di Biagiod261e982014-07-08 15:22:29 +000011045 return OtherSV->getOperand(0);
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000011046 }
Andrea Di Biagiod261e982014-07-08 15:22:29 +000011047
11048 // It may still be beneficial to combine the two shuffles if the
11049 // resulting shuffle is legal.
Andrea Di Biagioace8e1e2014-08-13 16:09:40 +000011050 if (TLI.isTypeLegal(VT)) {
11051 if (!CommuteOperands) {
11052 if (TLI.isShuffleMaskLegal(Mask, VT))
11053 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
11054 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
11055 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
11056 &Mask[0]);
11057 } else {
11058 // Compute the commuted shuffle mask.
11059 for (unsigned i = 0; i != NumElts; ++i) {
11060 int idx = Mask[i];
11061 if (idx < 0)
11062 continue;
11063 else if (idx < (int)NumElts)
11064 Mask[i] = idx + NumElts;
11065 else
11066 Mask[i] = idx - NumElts;
11067 }
11068
11069 if (TLI.isShuffleMaskLegal(Mask, VT))
11070 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
11071 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
11072 &Mask[0]);
11073 }
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000011074 }
Nadav Rotemb0783502012-04-01 19:31:22 +000011075 }
11076
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000011077 // Canonicalize shuffles according to rules:
11078 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11079 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11080 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11081 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
11082 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11083 TLI.isTypeLegal(VT)) {
11084 // The incoming shuffle must be of the same type as the result of the
11085 // current shuffle.
11086 assert(N1->getOperand(0).getValueType() == VT &&
11087 "Shuffle types don't match");
11088
11089 SDValue SV0 = N1->getOperand(0);
11090 SDValue SV1 = N1->getOperand(1);
11091 bool HasSameOp0 = N0 == SV0;
11092 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11093 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11094 // Commute the operands of this shuffle so that next rule
11095 // will trigger.
11096 return DAG.getCommutedVectorShuffle(*SVN);
11097 }
11098
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011099 // Try to fold according to rules:
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000011100 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
11101 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
11102 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11103 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011104 // Don't try to fold shuffles with illegal type.
11105 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000011106 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011107 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11108
11109 // The incoming shuffle must be of the same type as the result of the
11110 // current shuffle.
11111 assert(OtherSV->getOperand(0).getValueType() == VT &&
11112 "Shuffle types don't match");
11113
11114 SDValue SV0 = OtherSV->getOperand(0);
11115 SDValue SV1 = OtherSV->getOperand(1);
11116 bool HasSameOp0 = N1 == SV0;
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000011117 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11118 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011119 // Early exit.
11120 return SDValue();
11121
11122 SmallVector<int, 4> Mask;
11123 // Compute the combined shuffle mask for a shuffle with SV0 as the first
11124 // operand, and SV1 as the second operand.
11125 for (unsigned i = 0; i != NumElts; ++i) {
11126 int Idx = SVN->getMaskElt(i);
11127 if (Idx < 0) {
11128 // Propagate Undef.
11129 Mask.push_back(Idx);
11130 continue;
11131 }
11132
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000011133 if (Idx < (int)NumElts) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011134 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000011135 if (IsSV1Undef && Idx >= (int) NumElts)
11136 Idx = -1; // Propagate Undef.
11137 } else
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011138 Idx = HasSameOp0 ? Idx - NumElts : Idx;
11139
11140 Mask.push_back(Idx);
11141 }
11142
Andrea Di Biagiob23bad12014-08-16 00:29:44 +000011143 // Check if all indices in Mask are Undef. In case, propagate Undef.
11144 bool isUndefMask = true;
11145 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11146 isUndefMask &= Mask[i] < 0;
11147
11148 if (isUndefMask)
11149 return DAG.getUNDEF(VT);
11150
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011151 // Avoid introducing shuffles with illegal mask.
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000011152 if (TLI.isShuffleMaskLegal(Mask, VT)) {
11153 if (IsSV1Undef)
11154 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11155 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11156 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011157 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000011158 }
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011159 }
11160
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011161 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000011162}
11163
Manman Ren413a6cb2014-01-31 01:10:35 +000011164SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11165 SDValue N0 = N->getOperand(0);
11166 SDValue N2 = N->getOperand(2);
11167
11168 // If the input vector is a concatenation, and the insert replaces
11169 // one of the halves, we can optimize into a single concat_vectors.
11170 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11171 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11172 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11173 EVT VT = N->getValueType(0);
11174
11175 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11176 // (concat_vectors Z, Y)
11177 if (InsIdx == 0)
11178 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11179 N->getOperand(1), N0.getOperand(1));
11180
11181 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11182 // (concat_vectors X, Z)
11183 if (InsIdx == VT.getVectorNumElements()/2)
11184 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11185 N0.getOperand(0), N->getOperand(1));
11186 }
11187
11188 return SDValue();
11189}
11190
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011191/// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11192/// with the destination vector and a zero vector.
Dan Gohmana8665142007-06-25 16:23:39 +000011193/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000011194/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011195SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011196 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011197 SDLoc dl(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011198 SDValue LHS = N->getOperand(0);
11199 SDValue RHS = N->getOperand(1);
Dan Gohmana8665142007-06-25 16:23:39 +000011200 if (N->getOpcode() == ISD::AND) {
Wesley Peck527da1b2010-11-23 03:31:01 +000011201 if (RHS.getOpcode() == ISD::BITCAST)
Evan Chenga320abc2006-04-20 08:56:16 +000011202 RHS = RHS.getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000011203 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011204 SmallVector<int, 8> Indices;
11205 unsigned NumElts = RHS.getNumOperands();
Evan Chenga320abc2006-04-20 08:56:16 +000011206 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011207 SDValue Elt = RHS.getOperand(i);
Evan Chenga320abc2006-04-20 08:56:16 +000011208 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011209 return SDValue();
Craig Toppere5893f62012-04-09 05:59:53 +000011210
11211 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011212 Indices.push_back(i);
Evan Chenga320abc2006-04-20 08:56:16 +000011213 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011214 Indices.push_back(NumElts);
Evan Chenga320abc2006-04-20 08:56:16 +000011215 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011216 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000011217 }
11218
11219 // Let's see if the target supports this vector_shuffle.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011220 EVT RVT = RHS.getValueType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011221 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011222 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000011223
Dan Gohmana8665142007-06-25 16:23:39 +000011224 // Return the new VECTOR_SHUFFLE node.
Dan Gohman08c0a952009-09-23 21:02:20 +000011225 EVT EltVT = RVT.getVectorElementType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011226 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman08c0a952009-09-23 21:02:20 +000011227 DAG.getConstant(0, EltVT));
Craig Topper48d114b2014-04-26 18:35:24 +000011228 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
Wesley Peck527da1b2010-11-23 03:31:01 +000011229 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011230 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peck527da1b2010-11-23 03:31:01 +000011231 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000011232 }
11233 }
Bill Wendling31b50992009-01-30 23:59:18 +000011234
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011235 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000011236}
11237
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011238/// Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011239SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000011240 assert(N->getValueType(0).isVector() &&
11241 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000011242
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011243 SDValue LHS = N->getOperand(0);
11244 SDValue RHS = N->getOperand(1);
11245 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011246 if (Shuffle.getNode()) return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000011247
Dan Gohmana8665142007-06-25 16:23:39 +000011248 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000011249 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011250 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000011251 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000011252 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000011253 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11254 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000011255 return SDValue();
11256
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011257 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000011258 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011259 SDValue LHSOp = LHS.getOperand(i);
11260 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000011261
Evan Cheng64d28462006-05-31 06:08:35 +000011262 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000011263 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11264 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000011265 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000011266 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000011267 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000011268 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000011269 break;
11270 }
Bill Wendling31b50992009-01-30 23:59:18 +000011271
Bob Wilson54081442010-12-17 23:06:49 +000011272 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000011273 EVT RVT = RHSOp.getValueType();
11274 if (RVT != VT) {
11275 // Integer BUILD_VECTOR operands may have types larger than the element
11276 // size (e.g., when the element type is not legal). Prior to type
11277 // legalization, the types may not match between the two BUILD_VECTORS.
11278 // Truncate one of the operands to make them match.
11279 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011280 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000011281 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011282 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000011283 VT = RVT;
11284 }
11285 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000011286 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000011287 LHSOp, RHSOp);
11288 if (FoldOp.getOpcode() != ISD::UNDEF &&
11289 FoldOp.getOpcode() != ISD::Constant &&
11290 FoldOp.getOpcode() != ISD::ConstantFP)
11291 break;
11292 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011293 AddToWorklist(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000011294 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011295
Bob Wilson54081442010-12-17 23:06:49 +000011296 if (Ops.size() == LHS.getNumOperands())
Craig Topper48d114b2014-04-26 18:35:24 +000011297 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
Chris Lattner0442a182006-04-02 03:25:57 +000011298 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011299
Andrea Di Biagio446a5272014-05-30 23:17:53 +000011300 // Type legalization might introduce new shuffles in the DAG.
11301 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11302 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
11303 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11304 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11305 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11306 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11307 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11308 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11309
11310 if (SVN0->getMask().equals(SVN1->getMask())) {
11311 EVT VT = N->getValueType(0);
11312 SDValue UndefVector = LHS.getOperand(1);
11313 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11314 LHS.getOperand(0), RHS.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011315 AddUsersToWorklist(N);
Andrea Di Biagio446a5272014-05-30 23:17:53 +000011316 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11317 &SVN0->getMask()[0]);
11318 }
11319 }
11320
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011321 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000011322}
11323
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011324/// Visit a binary vector operation, like FABS/FNEG.
Craig Topper82384612012-09-11 01:45:21 +000011325SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topper82384612012-09-11 01:45:21 +000011326 assert(N->getValueType(0).isVector() &&
11327 "SimplifyVUnaryOp only works on vectors!");
11328
11329 SDValue N0 = N->getOperand(0);
11330
11331 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11332 return SDValue();
11333
11334 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11335 SmallVector<SDValue, 8> Ops;
11336 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11337 SDValue Op = N0.getOperand(i);
11338 if (Op.getOpcode() != ISD::UNDEF &&
11339 Op.getOpcode() != ISD::ConstantFP)
11340 break;
11341 EVT EltVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011342 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topper82384612012-09-11 01:45:21 +000011343 if (FoldOp.getOpcode() != ISD::UNDEF &&
11344 FoldOp.getOpcode() != ISD::ConstantFP)
11345 break;
11346 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011347 AddToWorklist(FoldOp.getNode());
Craig Topper82384612012-09-11 01:45:21 +000011348 }
11349
11350 if (Ops.size() != N0.getNumOperands())
11351 return SDValue();
11352
Craig Topper48d114b2014-04-26 18:35:24 +000011353 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
Craig Topper82384612012-09-11 01:45:21 +000011354}
11355
Andrew Trickef9de2a2013-05-25 02:42:55 +000011356SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011357 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000011358 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000011359
Bill Wendling31b50992009-01-30 23:59:18 +000011360 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000011361 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000011362
Nate Begeman2042aa52005-10-08 00:29:44 +000011363 // If we got a simplified select_cc node back from SimplifySelectCC, then
11364 // break it down into a new SETCC node, and a new SELECT node, and then return
11365 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000011366 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000011367 // Check to see if we got a select_cc back (to turn into setcc/select).
11368 // Otherwise, just return whatever node we got back, like fabs.
11369 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011370 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011371 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000011372 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000011373 SCC.getOperand(4));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011374 AddToWorklist(SETCC.getNode());
Chandler Carruth40dbd382014-08-04 21:29:59 +000011375 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11376 SCC.getOperand(2), SCC.getOperand(3));
Nate Begeman2042aa52005-10-08 00:29:44 +000011377 }
Bill Wendling31b50992009-01-30 23:59:18 +000011378
Nate Begeman2042aa52005-10-08 00:29:44 +000011379 return SCC;
11380 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011381 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011382}
11383
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011384/// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11385/// being selected between, see if we can simplify the select. Callers of this
11386/// should assume that TheSelect is deleted if this returns true. As such, they
11387/// should return the appropriate thing (e.g. the node) back to the top-level of
11388/// the DAG combiner loop to avoid it being looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011389bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011390 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011391
Nadav Rotema49a02a2011-02-11 19:57:47 +000011392 // Cannot simplify select with vector condition
11393 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11394
Chris Lattner6c14c352005-10-18 06:04:22 +000011395 // If this is a select from two identical things, try to pull the operation
11396 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000011397 if (LHS.getOpcode() != RHS.getOpcode() ||
11398 !LHS.hasOneUse() || !RHS.hasOneUse())
11399 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011400
Chris Lattner254c4452010-09-21 15:46:59 +000011401 // If this is a load and the token chain is identical, replace the select
11402 // of two loads with a load through a select of the address to load from.
11403 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11404 // constants have been dropped into the constant pool.
11405 if (LHS.getOpcode() == ISD::LOAD) {
11406 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11407 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000011408
Chris Lattner254c4452010-09-21 15:46:59 +000011409 // Token chains must be identical.
11410 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000011411 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000011412 LLD->isVolatile() || RLD->isVolatile() ||
11413 // If this is an EXTLOAD, the VT's must match.
11414 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000011415 // If this is an EXTLOAD, the kind of extension must match.
11416 (LLD->getExtensionType() != RLD->getExtensionType() &&
11417 // The only exception is if one of the extensions is anyext.
11418 LLD->getExtensionType() != ISD::EXTLOAD &&
11419 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000011420 // FIXME: this discards src value information. This is
11421 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000011422 // both potential memory locations. Since we are discarding
11423 // src value info, don't do the transformation if the memory
11424 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000011425 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000011426 RLD->getPointerInfo().getAddrSpace() != 0 ||
11427 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11428 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000011429 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011430
Chris Lattnere3267522010-09-21 15:58:55 +000011431 // Check that the select condition doesn't reach either load. If so,
11432 // folding this will induce a cycle into the DAG. If not, this is safe to
11433 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000011434 SDValue Addr;
11435 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000011436 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11437 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11438 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11439 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000011440 // The loads must not depend on one another.
11441 if (LLD->isPredecessorOf(RLD) ||
11442 RLD->isPredecessorOf(LLD))
11443 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011444 Addr = DAG.getSelect(SDLoc(TheSelect),
11445 LLD->getBasePtr().getValueType(),
11446 TheSelect->getOperand(0), LLD->getBasePtr(),
11447 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000011448 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000011449 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11450 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11451
11452 if ((LLD->hasAnyUseOfValue(1) &&
11453 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000011454 (RLD->hasAnyUseOfValue(1) &&
11455 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000011456 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011457
Andrew Trickef9de2a2013-05-25 02:42:55 +000011458 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000011459 LLD->getBasePtr().getValueType(),
11460 TheSelect->getOperand(0),
11461 TheSelect->getOperand(1),
11462 LLD->getBasePtr(), RLD->getBasePtr(),
11463 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000011464 }
11465
Chris Lattnere3267522010-09-21 15:58:55 +000011466 SDValue Load;
Louis Gerbarg4fc09b32014-07-30 18:24:41 +000011467 // It is safe to replace the two loads if they have different alignments,
11468 // but the new load must be the minimum (most restrictive) alignment of the
11469 // inputs.
Louis Gerbarg67474e32014-07-31 21:45:05 +000011470 bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
Louis Gerbarg09b8cde2014-07-31 22:57:46 +000011471 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000011472 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11473 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000011474 SDLoc(TheSelect),
Hal Finkelcc39b672014-07-24 12:16:19 +000011475 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000011476 LLD->getChain(), Addr, MachinePointerInfo(),
11477 LLD->isVolatile(), LLD->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000011478 isInvariant, Alignment);
Chris Lattnere3267522010-09-21 15:58:55 +000011479 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000011480 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11481 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000011482 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000011483 TheSelect->getValueType(0),
Hal Finkelcc39b672014-07-24 12:16:19 +000011484 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000011485 LLD->getChain(), Addr, MachinePointerInfo(),
11486 LLD->getMemoryVT(), LLD->isVolatile(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000011487 LLD->isNonTemporal(), isInvariant, Alignment);
Chris Lattner6c14c352005-10-18 06:04:22 +000011488 }
Chris Lattnere3267522010-09-21 15:58:55 +000011489
11490 // Users of the select now use the result of the load.
11491 CombineTo(TheSelect, Load);
11492
11493 // Users of the old loads now use the new load's chain. We know the
11494 // old-load value is dead now.
11495 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11496 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11497 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000011498 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011499
Chris Lattner6c14c352005-10-18 06:04:22 +000011500 return false;
11501}
11502
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011503/// Simplify an expression of the form (N0 cond N1) ? N2 : N3
Chris Lattner43d63772009-03-11 05:08:08 +000011504/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000011505SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011506 SDValue N2, SDValue N3,
11507 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000011508 // (x ? y : y) -> y.
11509 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000011510
Owen Anderson53aa7a92009-08-10 22:56:29 +000011511 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000011512 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11513 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11514 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011515
11516 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000011517 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000011518 N0, N1, CC, DL, false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011519 if (SCC.getNode()) AddToWorklist(SCC.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +000011520 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011521
11522 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000011523 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000011524 return N2;
11525 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000011526 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000011527 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011528
Nate Begeman2042aa52005-10-08 00:29:44 +000011529 // Check to see if we can simplify the select into an fabs node
11530 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11531 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000011532 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000011533 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11534 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11535 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11536 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000011537 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011538
Nate Begeman2042aa52005-10-08 00:29:44 +000011539 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11540 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11541 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11542 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000011543 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000011544 }
11545 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011546
Chris Lattner43d63772009-03-11 05:08:08 +000011547 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11548 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11549 // in it. This is a win when the constant is not otherwise available because
11550 // it replaces two constant pool loads with one. We only do this if the FP
11551 // type is known to be legal, because if it isn't, then we are before legalize
11552 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000011553 // messing with soft float) and if the ConstantFP is not legal, because if
11554 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000011555 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11556 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11557 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000011558 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
Tim Northover863a7892014-04-16 09:03:09 +000011559 TargetLowering::Legal &&
11560 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11561 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
Chris Lattner43d63772009-03-11 05:08:08 +000011562 // If both constants have multiple uses, then we won't need to do an
11563 // extra load, they are likely around in registers for other users.
11564 (TV->hasOneUse() || FV->hasOneUse())) {
11565 Constant *Elts[] = {
11566 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11567 const_cast<ConstantFP*>(TV->getConstantFPValue())
11568 };
Chris Lattner229907c2011-07-18 04:54:35 +000011569 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000011570 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000011571
Chris Lattner43d63772009-03-11 05:08:08 +000011572 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000011573 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000011574 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11575 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000011576 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000011577
11578 // Get the offsets to the 0 and 1 element of the array so that we can
11579 // select between them.
11580 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000011581 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000011582 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000011583
Chris Lattner43d63772009-03-11 05:08:08 +000011584 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000011585 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000011586 N0, N1, CC);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011587 AddToWorklist(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011588 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11589 Cond, One, Zero);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011590 AddToWorklist(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000011591 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000011592 CstOffset);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011593 AddToWorklist(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000011594 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000011595 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000011596 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000011597
11598 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011599 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011600
Nate Begeman2042aa52005-10-08 00:29:44 +000011601 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000011602 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000011603 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000011604 (N1C->isNullValue() || // (a < 0) ? b : 0
11605 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000011606 EVT XType = N0.getValueType();
11607 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000011608 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000011609 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000011610 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011611 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11612 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000011613 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000011614 SDValue ShCt = DAG.getConstant(ShCtV,
11615 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011616 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011617 XType, N0, ShCt);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011618 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011619
Duncan Sands11dd4242008-06-08 20:54:56 +000011620 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011621 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011622 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011623 }
Bill Wendling31b50992009-01-30 23:59:18 +000011624
11625 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011626 }
Bill Wendling31b50992009-01-30 23:59:18 +000011627
Andrew Trickef9de2a2013-05-25 02:42:55 +000011628 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011629 XType, N0,
11630 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011631 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011632 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011633
Duncan Sands11dd4242008-06-08 20:54:56 +000011634 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011635 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011636 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011637 }
Bill Wendling31b50992009-01-30 23:59:18 +000011638
11639 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011640 }
11641 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011642
Owen Anderson3231d132010-09-22 22:58:22 +000011643 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11644 // where y is has a single bit set.
11645 // A plaintext description would be, we can turn the SELECT_CC into an AND
11646 // when the condition can be materialized as an all-ones register. Any
11647 // single bit-test can be materialized as an all-ones register with
11648 // shift-left and shift-right-arith.
11649 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11650 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000011651 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000011652 N2C && N2C->isNullValue()) {
11653 SDValue AndLHS = N0->getOperand(0);
11654 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11655 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11656 // Shift the tested bit over the sign bit.
11657 APInt AndMask = ConstAndRHS->getAPIntValue();
11658 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011659 DAG.getConstant(AndMask.countLeadingZeros(),
11660 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011661 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011662
Owen Anderson3231d132010-09-22 22:58:22 +000011663 // Now arithmetic right shift it all the way over, so the result is either
11664 // all-ones, or zero.
11665 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011666 DAG.getConstant(AndMask.getBitWidth()-1,
11667 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011668 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011669
Owen Anderson3231d132010-09-22 22:58:22 +000011670 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11671 }
11672 }
11673
Nate Begeman6828ed92005-10-10 21:26:48 +000011674 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000011675 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +000011676 TLI.getBooleanContents(N0.getValueType()) ==
11677 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011678
Chris Lattnera083ffc2007-04-11 06:50:51 +000011679 // If the caller doesn't want us to simplify this into a zext of a compare,
11680 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011681 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011682 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011683
Nate Begeman6828ed92005-10-10 21:26:48 +000011684 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011685 // NOTE: Don't create a SETCC if it's not legal on this target.
11686 if (!LegalOperations ||
11687 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000011688 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011689 SDValue Temp, SCC;
11690 // cast from setcc result type to select result type
11691 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000011692 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011693 N0, N1, CC);
11694 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000011695 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011696 N2.getValueType());
11697 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000011698 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011699 N2.getValueType(), SCC);
11700 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011701 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11702 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000011703 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011704 }
11705
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011706 AddToWorklist(SCC.getNode());
11707 AddToWorklist(Temp.getNode());
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011708
11709 if (N2C->getAPIntValue() == 1)
11710 return Temp;
11711
11712 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000011713 return DAG.getNode(
11714 ISD::SHL, DL, N2.getValueType(), Temp,
11715 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11716 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000011717 }
Nate Begeman6828ed92005-10-10 21:26:48 +000011718 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011719
Nate Begeman2042aa52005-10-08 00:29:44 +000011720 // Check to see if this is the equivalent of setcc
11721 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11722 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011723 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011724 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011725 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000011726 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11727 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000011728 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000011729 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000011730 return Res;
11731 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011732
Bill Wendling31b50992009-01-30 23:59:18 +000011733 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011734 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011735 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000011736 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011737 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011738 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000011739 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000011740 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000011741 }
Bill Wendling31b50992009-01-30 23:59:18 +000011742 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011743 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011744 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011745 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011746 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000011747 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000011748 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000011749 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011750 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000011751 }
Bill Wendling31b50992009-01-30 23:59:18 +000011752 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000011753 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011754 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011755 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011756 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000011757 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000011758 }
11759 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011760
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011761 // Check to see if this is an integer abs.
11762 // select_cc setg[te] X, 0, X, -X ->
11763 // select_cc setgt X, -1, X, -X ->
11764 // select_cc setl[te] X, 0, -X, X ->
11765 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000011766 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011767 if (N1C) {
Craig Topperc0196b12014-04-14 00:51:57 +000011768 ConstantSDNode *SubC = nullptr;
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011769 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11770 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11771 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11772 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11773 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11774 (N1C->isOne() && CC == ISD::SETLT)) &&
11775 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11776 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11777
Owen Anderson53aa7a92009-08-10 22:56:29 +000011778 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011779 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011780 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011781 N0,
11782 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011783 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011784 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011785 XType, N0, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011786 AddToWorklist(Shift.getNode());
11787 AddToWorklist(Add.getNode());
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011788 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000011789 }
11790 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011791
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011792 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011793}
11794
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011795/// This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011796SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011797 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000011798 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011799 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000011800 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000011801 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000011802}
11803
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011804/// Given an ISD::SDIV node expressing a divide by constant, return
Chad Rosier17020f92014-07-23 14:57:52 +000011805/// a DAG expression to select that will generate the same value by multiplying
Sanjay Patelbb292212014-09-15 19:47:44 +000011806/// by a magic number.
11807/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011808SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011809 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11810 if (!C)
11811 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011812
11813 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011814 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011815 return SDValue();
11816
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011817 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011818 SDValue S =
11819 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011820
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011821 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011822 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011823 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011824}
11825
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011826/// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
11827/// DAG expression that will generate the same value by right shifting.
Chad Rosier17020f92014-07-23 14:57:52 +000011828SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11829 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11830 if (!C)
11831 return SDValue();
11832
11833 // Avoid division by zero.
11834 if (!C->getAPIntValue())
11835 return SDValue();
11836
11837 std::vector<SDNode *> Built;
11838 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11839
11840 for (SDNode *N : Built)
11841 AddToWorklist(N);
11842 return S;
11843}
11844
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011845/// Given an ISD::UDIV node expressing a divide by constant, return a DAG
11846/// expression that will generate the same value by multiplying by a magic
Sanjay Patelbb292212014-09-15 19:47:44 +000011847/// number.
11848/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011849SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011850 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11851 if (!C)
11852 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011853
11854 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011855 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011856 return SDValue();
11857
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011858 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011859 SDValue S =
11860 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000011861
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011862 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011863 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011864 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011865}
11866
Sanjay Patelbdf1e382014-09-26 23:01:47 +000011867SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
11868 if (Level >= AfterLegalizeDAG)
11869 return SDValue();
11870
Sanjay Patelb67bd262014-09-21 15:19:15 +000011871 // Expose the DAG combiner to the target combiner implementations.
11872 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
Sanjay Patelb67bd262014-09-21 15:19:15 +000011873
Sanjay Patelab7f4602014-09-30 20:44:23 +000011874 unsigned Iterations = 0;
Sanjay Patel8fde95c2014-09-30 20:28:48 +000011875 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
Sanjay Patelab7f4602014-09-30 20:44:23 +000011876 if (Iterations) {
11877 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
11878 // For the reciprocal, we need to find the zero of the function:
11879 // F(X) = A X - 1 [which has a zero at X = 1/A]
11880 // =>
11881 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
11882 // does not require additional intermediate precision]
11883 EVT VT = Op.getValueType();
11884 SDLoc DL(Op);
11885 SDValue FPOne = DAG.getConstantFP(1.0, VT);
Sanjay Patelbdf1e382014-09-26 23:01:47 +000011886
Sanjay Patelbdf1e382014-09-26 23:01:47 +000011887 AddToWorklist(Est.getNode());
Sanjay Patelbdf1e382014-09-26 23:01:47 +000011888
Sanjay Patelab7f4602014-09-30 20:44:23 +000011889 // Newton iterations: Est = Est + Est (1 - Arg * Est)
11890 for (unsigned i = 0; i < Iterations; ++i) {
11891 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
11892 AddToWorklist(NewEst.getNode());
11893
11894 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
11895 AddToWorklist(NewEst.getNode());
11896
11897 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
11898 AddToWorklist(NewEst.getNode());
11899
11900 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
11901 AddToWorklist(Est.getNode());
11902 }
11903 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +000011904 return Est;
11905 }
11906
11907 return SDValue();
11908}
11909
11910SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
11911 if (Level >= AfterLegalizeDAG)
11912 return SDValue();
11913
11914 // Expose the DAG combiner to the target combiner implementations.
11915 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
Sanjay Patelab7f4602014-09-30 20:44:23 +000011916 unsigned Iterations = 0;
Sanjay Patel8fde95c2014-09-30 20:28:48 +000011917 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations)) {
Sanjay Patelab7f4602014-09-30 20:44:23 +000011918 if (Iterations) {
11919 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
11920 // For the reciprocal sqrt, we need to find the zero of the function:
11921 // F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
11922 // =>
11923 // X_{i+1} = X_i (1.5 - A X_i^2 / 2)
11924 // As a result, we precompute A/2 prior to the iteration loop.
11925 EVT VT = Op.getValueType();
11926 SDLoc DL(Op);
11927 SDValue FPThreeHalves = DAG.getConstantFP(1.5, VT);
Sanjay Patelbdf1e382014-09-26 23:01:47 +000011928
Sanjay Patelbdf1e382014-09-26 23:01:47 +000011929 AddToWorklist(Est.getNode());
Sanjay Patelbdf1e382014-09-26 23:01:47 +000011930
Sanjay Patelab7f4602014-09-30 20:44:23 +000011931 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
11932 // this entire sequence requires only one FP constant.
11933 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, FPThreeHalves, Op);
11934 AddToWorklist(HalfArg.getNode());
11935
11936 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Op);
11937 AddToWorklist(HalfArg.getNode());
11938
11939 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
11940 for (unsigned i = 0; i < Iterations; ++i) {
11941 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
11942 AddToWorklist(NewEst.getNode());
11943
11944 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
11945 AddToWorklist(NewEst.getNode());
11946
11947 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPThreeHalves, NewEst);
11948 AddToWorklist(NewEst.getNode());
11949
11950 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
11951 AddToWorklist(Est.getNode());
11952 }
11953 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +000011954 return Est;
Sanjay Patelb67bd262014-09-21 15:19:15 +000011955 }
11956
11957 return SDValue();
11958}
11959
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011960/// Return true if base is a frame index, which is known not to alias with
11961/// anything but itself. Provides base object and offset as results.
Nate Begeman18150d52009-09-25 06:05:26 +000011962static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000011963 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000011964 // Assume it is a primitive operation.
Craig Topperc0196b12014-04-14 00:51:57 +000011965 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011966
Jim Laskey0463e082006-10-07 23:37:56 +000011967 // If it's an adding a simple constant then integrate the offset.
11968 if (Base.getOpcode() == ISD::ADD) {
11969 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11970 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000011971 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000011972 }
11973 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011974
Nate Begeman18150d52009-09-25 06:05:26 +000011975 // Return the underlying GlobalValue, and update the Offset. Return false
11976 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11977 // by multiple nodes with different offsets.
11978 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11979 GV = G->getGlobal();
11980 Offset += G->getOffset();
11981 return false;
11982 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011983
Nate Begeman18150d52009-09-25 06:05:26 +000011984 // Return the underlying Constant value, and update the Offset. Return false
11985 // for ConstantSDNodes since the same constant pool entry may be represented
11986 // by multiple nodes with different offsets.
11987 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000011988 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11989 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000011990 Offset += C->getOffset();
11991 return false;
11992 }
Jim Laskey0463e082006-10-07 23:37:56 +000011993 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000011994 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000011995}
11996
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011997/// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011998bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
Jim Laskey0463e082006-10-07 23:37:56 +000011999 // If they are the same then they must be aliases.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012000 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012001
Richard Sandiford981fdeb2013-10-28 12:00:00 +000012002 // If they are both volatile then they cannot be reordered.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012003 if (Op0->isVolatile() && Op1->isVolatile()) return true;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000012004
Jim Laskey0463e082006-10-07 23:37:56 +000012005 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012006 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000012007 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000012008 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000012009 const void *CV1, *CV2;
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012010 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12011 Base1, Offset1, GV1, CV1);
12012 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12013 Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000012014
Nate Begeman18150d52009-09-25 06:05:26 +000012015 // If they have a same base address then check to see if they overlap.
12016 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012017 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12018 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000012019
Owen Anderson272ff942010-09-20 20:39:59 +000012020 // It is possible for different frame indices to alias each other, mostly
12021 // when tail call optimization reuses return address slots for arguments.
12022 // To catch this case, look up the actual index of frame indices to compute
12023 // the real alias relationship.
12024 if (isFrameIndex1 && isFrameIndex2) {
12025 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12026 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12027 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012028 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12029 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Owen Anderson272ff942010-09-20 20:39:59 +000012030 }
12031
Wesley Peck527da1b2010-11-23 03:31:01 +000012032 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000012033 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000012034 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12035 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000012036
Nate Begeman879d8f12009-09-15 00:18:30 +000012037 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12038 // compared to the size and offset of the access, we may be able to prove they
12039 // do not alias. This check is conservative for now to catch cases created by
12040 // splitting vector types.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012041 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12042 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12043 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12044 Op1->getMemoryVT().getSizeInBits() >> 3) &&
12045 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12046 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12047 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
Wesley Peck527da1b2010-11-23 03:31:01 +000012048
Nate Begeman879d8f12009-09-15 00:18:30 +000012049 // There is no overlap between these relatively aligned accesses of similar
12050 // size, return no alias.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012051 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12052 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
Nate Begeman879d8f12009-09-15 00:18:30 +000012053 return false;
12054 }
Wesley Peck527da1b2010-11-23 03:31:01 +000012055
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000012056 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
12057 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000012058#ifndef NDEBUG
12059 if (CombinerAAOnlyFunc.getNumOccurrences() &&
12060 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12061 UseAA = false;
12062#endif
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012063 if (UseAA &&
12064 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000012065 // Use alias analysis information.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012066 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12067 Op1->getSrcValueOffset());
12068 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12069 Op0->getSrcValueOffset() - MinOffset;
12070 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12071 Op1->getSrcValueOffset() - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012072 AliasAnalysis::AliasResult AAResult =
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012073 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12074 Overlap1,
Hal Finkelcc39b672014-07-24 12:16:19 +000012075 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012076 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12077 Overlap2,
Hal Finkelcc39b672014-07-24 12:16:19 +000012078 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
Jim Laskey55e4dca2006-10-18 19:08:31 +000012079 if (AAResult == AliasAnalysis::NoAlias)
12080 return false;
12081 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000012082
12083 // Otherwise we have to assume they alias.
12084 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000012085}
12086
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012087/// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +000012088/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012089void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000012090 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012091 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000012092 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012093
Jim Laskeyd07be232006-09-25 16:29:54 +000012094 // Get alias information for node.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012095 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
Jim Laskeyd07be232006-09-25 16:29:54 +000012096
Jim Laskey708d0db2006-10-04 16:53:27 +000012097 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000012098 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012099 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000012100
Jim Laskey6549d222006-10-05 15:07:25 +000012101 // Look at each chain and determine if it is an alias. If so, add it to the
12102 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000012103 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000012104 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012105 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000012106 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000012107
12108 // For TokenFactor nodes, look at each operand and only continue up the
12109 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012110 // find more and revert to original chain since the xform is unlikely to be
12111 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000012112 //
12113 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012114 // chain we found before we hit a tokenfactor rather than the original
12115 // chain.
12116 if (Depth > 6 || Aliases.size() == 2) {
12117 Aliases.clear();
12118 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000012119 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012120 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012121
Nate Begeman879d8f12009-09-15 00:18:30 +000012122 // Don't bother if we've been before.
12123 if (!Visited.insert(Chain.getNode()))
12124 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012125
Jim Laskey6549d222006-10-05 15:07:25 +000012126 switch (Chain.getOpcode()) {
12127 case ISD::EntryToken:
12128 // Entry token is ideal chain operand, but handled in FindBetterChain.
12129 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012130
Jim Laskey6549d222006-10-05 15:07:25 +000012131 case ISD::LOAD:
12132 case ISD::STORE: {
12133 // Get alias information for Chain.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012134 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12135 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
Scott Michelcf0da6c2009-02-17 22:15:04 +000012136
Jim Laskey6549d222006-10-05 15:07:25 +000012137 // If chain is alias then stop here.
12138 if (!(IsLoad && IsOpLoad) &&
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012139 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
Jim Laskey6549d222006-10-05 15:07:25 +000012140 Aliases.push_back(Chain);
12141 } else {
12142 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012143 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012144 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000012145 }
Jim Laskey6549d222006-10-05 15:07:25 +000012146 break;
12147 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012148
Jim Laskey6549d222006-10-05 15:07:25 +000012149 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000012150 // We have to check each of the operands of the token factor for "small"
12151 // token factors, so we queue them up. Adding the operands to the queue
12152 // (stack) in reverse order maintains the original order and increases the
12153 // likelihood that getNode will find a matching token factor (CSE.)
12154 if (Chain.getNumOperands() > 16) {
12155 Aliases.push_back(Chain);
12156 break;
12157 }
Jim Laskey6549d222006-10-05 15:07:25 +000012158 for (unsigned n = Chain.getNumOperands(); n;)
12159 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012160 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000012161 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012162
Jim Laskey6549d222006-10-05 15:07:25 +000012163 default:
12164 // For all other instructions we will just have to take what we can get.
12165 Aliases.push_back(Chain);
12166 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000012167 }
12168 }
Hal Finkel51a98382014-01-24 20:12:02 +000012169
12170 // We need to be careful here to also search for aliases through the
12171 // value operand of a store, etc. Consider the following situation:
12172 // Token1 = ...
12173 // L1 = load Token1, %52
12174 // S1 = store Token1, L1, %51
12175 // L2 = load Token1, %52+8
12176 // S2 = store Token1, L2, %51+8
12177 // Token2 = Token(S1, S2)
12178 // L3 = load Token2, %53
12179 // S3 = store Token2, L3, %52
12180 // L4 = load Token2, %53+8
12181 // S4 = store Token2, L4, %52+8
12182 // If we search for aliases of S3 (which loads address %52), and we look
12183 // only through the chain, then we'll miss the trivial dependence on L1
12184 // (which also loads from %52). We then might change all loads and
12185 // stores to use Token1 as their chain operand, which could result in
12186 // copying %53 into %52 before copying %52 into %51 (which should
12187 // happen first).
12188 //
12189 // The problem is, however, that searching for such data dependencies
12190 // can become expensive, and the cost is not directly related to the
12191 // chain depth. Instead, we'll rule out such configurations here by
12192 // insisting that we've visited all chain users (except for users
12193 // of the original chain, which is not necessary). When doing this,
12194 // we need to look through nodes we don't care about (otherwise, things
12195 // like register copies will interfere with trivial cases).
12196
12197 SmallVector<const SDNode *, 16> Worklist;
Craig Topper46276792014-08-24 23:23:06 +000012198 for (const SDNode *N : Visited)
12199 if (N != OriginalChain.getNode())
12200 Worklist.push_back(N);
Hal Finkel51a98382014-01-24 20:12:02 +000012201
12202 while (!Worklist.empty()) {
12203 const SDNode *M = Worklist.pop_back_val();
12204
12205 // We have already visited M, and want to make sure we've visited any uses
12206 // of M that we care about. For uses that we've not visisted, and don't
12207 // care about, queue them to the worklist.
12208
12209 for (SDNode::use_iterator UI = M->use_begin(),
12210 UIE = M->use_end(); UI != UIE; ++UI)
12211 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
12212 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12213 // We've not visited this use, and we care about it (it could have an
12214 // ordering dependency with the original node).
12215 Aliases.clear();
12216 Aliases.push_back(OriginalChain);
12217 return;
12218 }
12219
12220 // We've not visited this use, but we don't care about it. Mark it as
12221 // visited and enqueue it to the worklist.
12222 Worklist.push_back(*UI);
12223 }
12224 }
Jim Laskey708d0db2006-10-04 16:53:27 +000012225}
12226
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012227/// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12228/// (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012229SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12230 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012231
Jim Laskey708d0db2006-10-04 16:53:27 +000012232 // Accumulate all the aliases to this node.
12233 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000012234
Dan Gohman4298df62011-05-17 22:20:36 +000012235 // If no operands then chain to entry token.
12236 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000012237 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000012238
12239 // If a single operand then chain to it. We don't need to revisit it.
12240 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000012241 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000012242
Jim Laskey708d0db2006-10-04 16:53:27 +000012243 // Construct a custom tailored token factor.
Craig Topper48d114b2014-04-26 18:35:24 +000012244 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
Jim Laskeyd07be232006-09-25 16:29:54 +000012245}
12246
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012247/// This is the entry point for the file.
Bill Wendling084669a2009-04-29 00:15:41 +000012248void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000012249 CodeGenOpt::Level OptLevel) {
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012250 /// This is the main entry point to this class.
Bill Wendling084669a2009-04-29 00:15:41 +000012251 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000012252}