blob: e556e74980c7a46690566463e36ce8263b7ec93a [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"
Chris Lattner48fb92f2007-05-16 06:37:59 +000020#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth9a0051c2014-07-23 07:08:53 +000021#include "llvm/ADT/SetVector.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000022#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/LLVMContext.h"
Jim Laskey5d19d592006-09-21 16:28:59 +000030#include "llvm/Support/CommandLine.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000031#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000032#include "llvm/Support/ErrorHandling.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000033#include "llvm/Support/MathExtras.h"
Chris Lattner4dc3edd2009-08-23 06:35:02 +000034#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Target/TargetLowering.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetOptions.h"
Quentin Colombetde0e0622013-10-11 18:29:42 +000038#include "llvm/Target/TargetRegisterInfo.h"
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000039#include "llvm/Target/TargetSubtargetInfo.h"
Chris Lattnerbd39c1a2005-09-09 23:53:39 +000040#include <algorithm>
Nate Begeman21158fc2005-09-01 00:19:25 +000041using namespace llvm;
42
Chandler Carruth1b9dde02014-04-22 02:02:50 +000043#define DEBUG_TYPE "dagcombine"
44
Chris Lattneraee775a2006-12-19 22:41:21 +000045STATISTIC(NodesCombined , "Number of dag nodes combined");
46STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
Evan Chenga9cda8a2009-05-28 00:35:15 +000048STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
Evan Chengd42641c2011-02-02 01:06:55 +000049STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
Quentin Colombetde0e0622013-10-11 18:29:42 +000050STATISTIC(SlicedLoads, "Number of load sliced");
Chris Lattneraee775a2006-12-19 22:41:21 +000051
Nate Begeman21158fc2005-09-01 00:19:25 +000052namespace {
Jim Laskey0463e082006-10-07 23:37:56 +000053 static cl::opt<bool>
Owen Anderson7b8d2ae2010-09-19 21:01:26 +000054 CombinerAA("combiner-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000055 cl::desc("Enable DAG combiner alias-analysis heuristics"));
Jim Laskeydf2ccc32006-10-12 15:22:24 +000056
Jim Laskey55e4dca2006-10-18 19:08:31 +000057 static cl::opt<bool>
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000059 cl::desc("Enable DAG combiner's use of IR alias analysis"));
Jim Laskey55e4dca2006-10-18 19:08:31 +000060
Hal Finkeldbebb522014-01-25 19:24:54 +000061 static cl::opt<bool>
Hal Finkel3b48d082014-04-12 01:26:00 +000062 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
Hal Finkeldbebb522014-01-25 19:24:54 +000063 cl::desc("Enable DAG combiner's use of TBAA"));
64
Hal Finkel9b2617a2014-01-25 17:32:39 +000065#ifndef NDEBUG
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
69 " function"));
70#endif
71
Quentin Colombetde0e0622013-10-11 18:29:42 +000072 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
74 static cl::opt<bool>
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
77 "slicing"),
78 cl::init(false));
79
Hal Finkel51e6fa22014-09-02 06:24:04 +000080 static cl::opt<bool>
81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82 cl::desc("DAG combiner may split indexing from loads"));
83
Jim Laskey6549d222006-10-05 15:07:25 +000084//------------------------------ DAGCombiner ---------------------------------//
85
Nick Lewycky02d5f772009-10-25 06:33:48 +000086 class DAGCombiner {
Nate Begeman21158fc2005-09-01 00:19:25 +000087 SelectionDAG &DAG;
Dan Gohman619ef482009-01-15 19:20:50 +000088 const TargetLowering &TLI;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000089 CombineLevel Level;
Bill Wendling026e5d72009-04-29 23:29:43 +000090 CodeGenOpt::Level OptLevel;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000091 bool LegalOperations;
92 bool LegalTypes;
Quentin Colombetde0e0622013-10-11 18:29:42 +000093 bool ForCodeSize;
Nate Begeman21158fc2005-09-01 00:19:25 +000094
Chandler Carruth9a0051c2014-07-23 07:08:53 +000095 /// \brief Worklist of all of the nodes that need to be simplified.
96 ///
97 /// This must behave as a stack -- new nodes to process are pushed onto the
98 /// back and when processing we pop off of the back.
99 ///
100 /// The worklist will not contain duplicates but may contain null entries
101 /// due to nodes being deleted from the underlying DAG.
102 SmallVector<SDNode *, 64> Worklist;
103
104 /// \brief Mapping from an SDNode to its position on the worklist.
105 ///
106 /// This is used to find and remove nodes from the worklist (by nulling
107 /// them) when they are deleted from the underlying DAG. It relies on
108 /// stable indices of nodes within the worklist.
109 DenseMap<SDNode *, unsigned> WorklistMap;
Nate Begeman21158fc2005-09-01 00:19:25 +0000110
Chandler Carruth9f4530b2014-07-24 22:15:28 +0000111 /// \brief Set of nodes which have been combined (at least once).
112 ///
113 /// This is used to allow us to reliably add any operands of a DAG node
114 /// which have not yet been combined to the worklist.
115 SmallPtrSet<SDNode *, 64> CombinedNodes;
116
Jim Laskeydcb2b832006-10-16 20:52:31 +0000117 // AA - Used for DAG load/store alias analysis.
118 AliasAnalysis &AA;
119
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000120 /// When an instruction is simplified, add all users of the instruction to
121 /// the work lists because they might get more simplified now.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000122 void AddUsersToWorklist(SDNode *N) {
Jim Grosbache8160032014-04-11 01:13:13 +0000123 for (SDNode *Node : N->uses())
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000124 AddToWorklist(Node);
Nate Begeman21158fc2005-09-01 00:19:25 +0000125 }
126
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000127 /// Call the node-specific routine that folds each particular type of node.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000128 SDValue visit(SDNode *N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000129
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000130 public:
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000131 /// Add to the worklist making sure its instance is at the back (next to be
132 /// processed.)
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000133 void AddToWorklist(SDNode *N) {
Chandler Carruth24ceb0c2014-07-21 08:32:31 +0000134 // Skip handle nodes as they can't usefully be combined and confuse the
135 // zero-use deletion strategy.
136 if (N->getOpcode() == ISD::HANDLENODE)
137 return;
138
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140 Worklist.push_back(N);
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000141 }
Jim Laskey708d0db2006-10-04 16:53:27 +0000142
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000143 /// Remove all instances of N from the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000144 void removeFromWorklist(SDNode *N) {
Chandler Carruth9f4530b2014-07-24 22:15:28 +0000145 CombinedNodes.erase(N);
146
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000147 auto It = WorklistMap.find(N);
148 if (It == WorklistMap.end())
149 return; // Not in the worklist.
150
151 // Null out the entry rather than erasing it to avoid a linear operation.
152 Worklist[It->second] = nullptr;
153 WorklistMap.erase(It);
Chris Lattnere260ed82005-10-10 22:04:48 +0000154 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000155
Chandler Carruth18066972014-08-02 10:02:07 +0000156 void deleteAndRecombine(SDNode *N);
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000157 bool recursivelyDeleteUnusedNodes(SDNode *N);
158
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
Evan Chengfd81c732009-03-28 05:57:29 +0000160 bool AddTo = true);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000161
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
Jim Laskeydcf983c2006-10-13 23:32:28 +0000163 return CombineTo(N, &Res, 1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000164 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000165
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
Evan Chengfd81c732009-03-28 05:57:29 +0000167 bool AddTo = true) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000168 SDValue To[] = { Res0, Res1 };
Jim Laskeydcf983c2006-10-13 23:32:28 +0000169 return CombineTo(N, To, 2, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000170 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000171
172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000173
174 private:
175
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000176 /// Check the specified integer node value to see if it can be simplified or
177 /// if things it uses can be simplified by bit propagation.
178 /// If so, return true.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000179 bool SimplifyDemandedBits(SDValue Op) {
Dan Gohman1d459e42009-12-11 21:31:27 +0000180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181 APInt Demanded = APInt::getAllOnesValue(BitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000182 return SimplifyDemandedBits(Op, Demanded);
183 }
184
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
Chris Lattner04c73702005-10-10 22:31:19 +0000186
Chris Lattnerffad2162006-11-11 00:39:41 +0000187 bool CombineToPreIndexedLoadStore(SDNode *N);
188 bool CombineToPostIndexedLoadStore(SDNode *N);
Hal Finkel51e6fa22014-09-02 06:24:04 +0000189 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000190 bool SliceUpLoad(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000191
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +0000192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193 /// load.
194 ///
195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197 /// \param EltNo index of the vector element to load.
198 /// \param OriginalLoad load that EVE came from to be replaced.
199 /// \returns EVE on success SDValue() on failure.
200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
Evan Chengaf56fac2010-04-16 06:14:10 +0000206 SDValue PromoteIntBinOp(SDValue Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000207 SDValue PromoteIntShiftOp(SDValue Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +0000208 SDValue PromoteExtend(SDValue Op);
209 bool PromoteLoad(SDValue Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000210
Craig Toppere0b71182013-07-13 07:43:40 +0000211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000212 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +0000213 ISD::NodeType ExtType);
214
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000215 /// Call the node-specific routine that knows how to fold each
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000216 /// particular type of node. If that doesn't do anything, try the
217 /// target-specific DAG combines.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000218 SDValue combine(SDNode *N);
Nate Begeman21158fc2005-09-01 00:19:25 +0000219
220 // Visitation implementation - Implement dag node combining for different
221 // node types. The semantics are as follows:
222 // Return Value:
Evan Cheng5e7658c2008-08-29 22:21:44 +0000223 // SDValue.getNode() == 0 - No change was made
224 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
225 // otherwise - N should be replaced by the returned Operand.
Nate Begeman21158fc2005-09-01 00:19:25 +0000226 //
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000227 SDValue visitTokenFactor(SDNode *N);
228 SDValue visitMERGE_VALUES(SDNode *N);
229 SDValue visitADD(SDNode *N);
230 SDValue visitSUB(SDNode *N);
231 SDValue visitADDC(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000232 SDValue visitSUBC(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000233 SDValue visitADDE(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000234 SDValue visitSUBE(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000235 SDValue visitMUL(SDNode *N);
236 SDValue visitSDIV(SDNode *N);
237 SDValue visitUDIV(SDNode *N);
238 SDValue visitSREM(SDNode *N);
239 SDValue visitUREM(SDNode *N);
240 SDValue visitMULHU(SDNode *N);
241 SDValue visitMULHS(SDNode *N);
242 SDValue visitSMUL_LOHI(SDNode *N);
243 SDValue visitUMUL_LOHI(SDNode *N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +0000244 SDValue visitSMULO(SDNode *N);
245 SDValue visitUMULO(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000246 SDValue visitSDIVREM(SDNode *N);
247 SDValue visitUDIVREM(SDNode *N);
248 SDValue visitAND(SDNode *N);
249 SDValue visitOR(SDNode *N);
250 SDValue visitXOR(SDNode *N);
251 SDValue SimplifyVBinOp(SDNode *N);
Craig Topper82384612012-09-11 01:45:21 +0000252 SDValue SimplifyVUnaryOp(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000253 SDValue visitSHL(SDNode *N);
254 SDValue visitSRA(SDNode *N);
255 SDValue visitSRL(SDNode *N);
Adam Nemet7f928f12014-03-07 23:56:30 +0000256 SDValue visitRotate(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000257 SDValue visitCTLZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000258 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000259 SDValue visitCTTZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000260 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000261 SDValue visitCTPOP(SDNode *N);
262 SDValue visitSELECT(SDNode *N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +0000263 SDValue visitVSELECT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000264 SDValue visitSELECT_CC(SDNode *N);
265 SDValue visitSETCC(SDNode *N);
266 SDValue visitSIGN_EXTEND(SDNode *N);
267 SDValue visitZERO_EXTEND(SDNode *N);
268 SDValue visitANY_EXTEND(SDNode *N);
269 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
270 SDValue visitTRUNCATE(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000271 SDValue visitBITCAST(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000272 SDValue visitBUILD_PAIR(SDNode *N);
273 SDValue visitFADD(SDNode *N);
274 SDValue visitFSUB(SDNode *N);
275 SDValue visitFMUL(SDNode *N);
Owen Anderson41b06652012-05-02 22:17:40 +0000276 SDValue visitFMA(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000277 SDValue visitFDIV(SDNode *N);
278 SDValue visitFREM(SDNode *N);
279 SDValue visitFCOPYSIGN(SDNode *N);
280 SDValue visitSINT_TO_FP(SDNode *N);
281 SDValue visitUINT_TO_FP(SDNode *N);
282 SDValue visitFP_TO_SINT(SDNode *N);
283 SDValue visitFP_TO_UINT(SDNode *N);
284 SDValue visitFP_ROUND(SDNode *N);
285 SDValue visitFP_ROUND_INREG(SDNode *N);
286 SDValue visitFP_EXTEND(SDNode *N);
287 SDValue visitFNEG(SDNode *N);
288 SDValue visitFABS(SDNode *N);
Owen Andersona40319b2012-08-13 23:32:49 +0000289 SDValue visitFCEIL(SDNode *N);
290 SDValue visitFTRUNC(SDNode *N);
291 SDValue visitFFLOOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000292 SDValue visitBRCOND(SDNode *N);
293 SDValue visitBR_CC(SDNode *N);
294 SDValue visitLOAD(SDNode *N);
295 SDValue visitSTORE(SDNode *N);
296 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
297 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
298 SDValue visitBUILD_VECTOR(SDNode *N);
299 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +0000300 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000301 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Manman Ren413a6cb2014-01-31 01:10:35 +0000302 SDValue visitINSERT_SUBVECTOR(SDNode *N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000303
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000304 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000305 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000306
Matt Arsenault985b9de2014-03-17 18:58:01 +0000307 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
Chris Lattner7c709a52007-12-06 07:33:36 +0000308
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000309 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
310 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000311 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
312 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelcf0da6c2009-02-17 22:15:04 +0000313 SDValue N3, ISD::CondCode CC,
Bill Wendling31b50992009-01-30 23:59:18 +0000314 bool NotExtCompare = false);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000315 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000316 SDLoc DL, bool foldBooleans = true);
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000317
318 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
319 SDValue &CC) const;
320 bool isOneUseSetCC(SDValue N) const;
321
Scott Michelcf0da6c2009-02-17 22:15:04 +0000322 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner31e9edc2008-01-26 01:09:19 +0000323 unsigned HiOp);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000324 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000325 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000326 SDValue BuildSDIV(SDNode *N);
Chad Rosier17020f92014-07-23 14:57:52 +0000327 SDValue BuildSDIVPow2(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000328 SDValue BuildUDIV(SDNode *N);
Evan Cheng4c0bd962011-06-21 06:01:08 +0000329 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
330 bool DemandHighBits = true);
331 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Richard Sandiford95c864d2014-01-08 15:40:47 +0000332 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
333 SDValue InnerPos, SDValue InnerNeg,
334 unsigned PosOpcode, unsigned NegOpcode,
335 SDLoc DL);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000336 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000337 SDValue ReduceLoadWidth(SDNode *N);
Evan Chenga9cda8a2009-05-28 00:35:15 +0000338 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Chengd42641c2011-02-02 01:06:55 +0000339 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liao6d106b72012-10-23 23:06:52 +0000340 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao59229792012-10-24 04:14:18 +0000341 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000342
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000343 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000344
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000345 /// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +0000346 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000347 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +0000348 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey708d0db2006-10-04 16:53:27 +0000349
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000350 /// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000351 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000352
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000353 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
354 /// chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000355 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands41826032009-01-31 15:50:11 +0000356
Nadav Rotem7cbc12a2012-10-03 16:11:15 +0000357 /// Merge consecutive store operations into a wide store.
358 /// This optimization uses wide integers or vectors when possible.
359 /// \return True if some memory operations were changed.
360 bool MergeConsecutiveStores(StoreSDNode *N);
361
Adam Nemet67483892014-03-04 23:28:31 +0000362 /// \brief Try to transform a truncation where C is a constant:
363 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
364 ///
365 /// \p N needs to be a truncation and its first operand an AND. Other
366 /// requirements are checked by the function (e.g. that trunc is
367 /// single-use) and if missed an empty SDValue is returned.
368 SDValue distributeTruncateThroughAnd(SDNode *N);
369
Chris Lattner4041ab62010-04-15 04:48:01 +0000370 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000371 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombetde0e0622013-10-11 18:29:42 +0000372 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
373 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
374 AttributeSet FnAttrs =
375 DAG.getMachineFunction().getFunction()->getAttributes();
376 ForCodeSize =
377 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
378 Attribute::OptimizeForSize) ||
379 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
380 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000381
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000382 /// Runs the dag combiner on all nodes in the work list
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000383 void Run(CombineLevel AtLevel);
Wesley Peck527da1b2010-11-23 03:31:01 +0000384
Chris Lattner4041ab62010-04-15 04:48:01 +0000385 SelectionDAG &getDAG() const { return DAG; }
Wesley Peck527da1b2010-11-23 03:31:01 +0000386
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000387 /// Returns a type large enough to hold any valid shift amount - before type
388 /// legalization these can be huge.
Owen Andersonb2c80da2011-02-25 21:41:48 +0000389 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +0000390 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
391 if (LHSTy.isVector())
392 return LHSTy;
Jack Carterd4e96152013-10-17 01:34:33 +0000393 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
394 : TLI.getPointerTy();
Chris Lattner4041ab62010-04-15 04:48:01 +0000395 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000396
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000397 /// This method returns true if we are running before type legalization or
398 /// if the specified VT is legal.
Chris Lattner4041ab62010-04-15 04:48:01 +0000399 bool isTypeLegal(const EVT &VT) {
400 if (!LegalTypes) return true;
401 return TLI.isTypeLegal(VT);
402 }
Matt Arsenault758659232013-05-18 00:21:46 +0000403
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000404 /// Convenience wrapper around TargetLowering::getSetCCResultType
Matt Arsenault758659232013-05-18 00:21:46 +0000405 EVT getSetCCResultType(EVT VT) const {
406 return TLI.getSetCCResultType(*DAG.getContext(), VT);
407 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000408 };
409}
410
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000411
412namespace {
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000413/// This class is a DAGUpdateListener that removes any deleted
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000414/// nodes from the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000415class WorklistRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000416 DAGCombiner &DC;
417public:
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000418 explicit WorklistRemover(DAGCombiner &dc)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000419 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000420
Craig Topper7b883b32014-03-08 06:31:39 +0000421 void NodeDeleted(SDNode *N, SDNode *E) override {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000422 DC.removeFromWorklist(N);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000423 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000424};
425}
426
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000427//===----------------------------------------------------------------------===//
428// TargetLowering::DAGCombinerInfo implementation
429//===----------------------------------------------------------------------===//
430
431void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000432 ((DAGCombiner*)DC)->AddToWorklist(N);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000433}
434
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000435void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000436 ((DAGCombiner*)DC)->removeFromWorklist(N);
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000437}
438
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000439SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000440CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
441 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000442}
443
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000444SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000445CombineTo(SDNode *N, SDValue Res, bool AddTo) {
446 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000447}
448
449
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000450SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000451CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
452 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000453}
454
Dan Gohmane58ab792009-01-29 01:59:02 +0000455void TargetLowering::DAGCombinerInfo::
456CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
457 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
458}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000459
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000460//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000461// Helper Functions
462//===----------------------------------------------------------------------===//
463
Chandler Carruth18066972014-08-02 10:02:07 +0000464void DAGCombiner::deleteAndRecombine(SDNode *N) {
465 removeFromWorklist(N);
466
467 // If the operands of this node are only used by the node, they will now be
468 // dead. Make sure to re-visit them and recursively delete dead nodes.
469 for (const SDValue &Op : N->ops())
Hal Finkel51e6fa22014-09-02 06:24:04 +0000470 // For an operand generating multiple values, one of the values may
471 // become dead allowing further simplification (e.g. split index
472 // arithmetic from an indexed load).
473 if (Op->hasOneUse() || Op->getNumValues() > 1)
Chandler Carruth18066972014-08-02 10:02:07 +0000474 AddToWorklist(Op.getNode());
475
476 DAG.DeleteNode(N);
477}
478
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000479/// Return 1 if we can compute the negated form of the specified expression for
480/// the same cost as the expression itself, or 2 if we can compute the negated
481/// form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000482static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000483 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000484 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000485 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000486 // fneg is removable even if it has multiple uses.
487 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000488
Chris Lattnere49c9742007-05-14 22:04:50 +0000489 // Don't allow anything with multiple uses.
490 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000491
Chris Lattner46980832007-05-25 02:19:06 +0000492 // Don't recurse exponentially.
493 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000494
Chris Lattnere49c9742007-05-14 22:04:50 +0000495 switch (Op.getOpcode()) {
496 default: return false;
497 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000498 // Don't invert constant FP values after legalize. The negated constant
499 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000500 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000501 case ISD::FADD:
502 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000503 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000504
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000505 // After operation legalization, it might not be legal to create new FSUBs.
506 if (LegalOperations &&
507 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
508 return 0;
509
Craig Topper03f39772012-09-09 22:58:45 +0000510 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000511 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
512 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000513 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000514 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000515 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000516 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000517 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000518 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000519 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000520
Bill Wendling6fbf5492009-01-30 23:10:18 +0000521 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000522 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000523
Chris Lattnere49c9742007-05-14 22:04:50 +0000524 case ISD::FMUL:
525 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000526 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000527
Bill Wendling6fbf5492009-01-30 23:10:18 +0000528 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000529 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
530 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000531 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000532
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000533 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000534 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000535
Chris Lattnere49c9742007-05-14 22:04:50 +0000536 case ISD::FP_EXTEND:
537 case ISD::FP_ROUND:
538 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000539 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000540 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000541 }
542}
543
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000544/// If isNegatibleForFree returns true, return the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000545static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000546 bool LegalOperations, unsigned Depth = 0) {
Sanjay Patel78614bf2014-08-28 15:53:16 +0000547 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattnere49c9742007-05-14 22:04:50 +0000548 // fneg is removable even if it has multiple uses.
549 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000550
Chris Lattnere49c9742007-05-14 22:04:50 +0000551 // Don't allow anything with multiple uses.
552 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000553
Chris Lattner46980832007-05-25 02:19:06 +0000554 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000555 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000556 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000557 case ISD::ConstantFP: {
558 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
559 V.changeSign();
560 return DAG.getConstantFP(V, Op.getValueType());
561 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000562 case ISD::FADD:
563 // FIXME: determine better conditions for this xform.
Sanjay Patel78614bf2014-08-28 15:53:16 +0000564 assert(Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000565
Bill Wendling6fbf5492009-01-30 23:10:18 +0000566 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000567 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Sanjay Patel78614bf2014-08-28 15:53:16 +0000568 DAG.getTargetLoweringInfo(), &Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000569 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000570 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000571 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000572 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000573 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000574 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000575 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000576 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000577 Op.getOperand(0));
578 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000579 // We can't turn -(A-B) into B-A when we honor signed zeros.
Sanjay Patel78614bf2014-08-28 15:53:16 +0000580 assert(Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000581
Bill Wendling6fbf5492009-01-30 23:10:18 +0000582 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000583 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen446b9002007-08-31 23:34:27 +0000584 if (N0CFP->getValueAPF().isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000585 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000586
Bill Wendling6fbf5492009-01-30 23:10:18 +0000587 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000588 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000589 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000590
Chris Lattnere49c9742007-05-14 22:04:50 +0000591 case ISD::FMUL:
592 case ISD::FDIV:
Sanjay Patel78614bf2014-08-28 15:53:16 +0000593 assert(!Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000594
Bill Wendling6fbf5492009-01-30 23:10:18 +0000595 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000596 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Sanjay Patel78614bf2014-08-28 15:53:16 +0000597 DAG.getTargetLoweringInfo(), &Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000598 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000599 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000600 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000601 Op.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000602
Bill Wendling6fbf5492009-01-30 23:10:18 +0000603 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000604 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattnere49c9742007-05-14 22:04:50 +0000605 Op.getOperand(0),
Chris Lattnere7c14012008-02-26 07:04:54 +0000606 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000607 LegalOperations, Depth+1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000608
Chris Lattnere49c9742007-05-14 22:04:50 +0000609 case ISD::FP_EXTEND:
Chris Lattnere49c9742007-05-14 22:04:50 +0000610 case ISD::FSIN:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000611 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000612 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000613 LegalOperations, Depth+1));
Chris Lattner72733e52008-01-17 07:00:52 +0000614 case ISD::FP_ROUND:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000615 return DAG.getNode(ISD::FP_ROUND, 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 Op.getOperand(1));
Chris Lattnere49c9742007-05-14 22:04:50 +0000619 }
620}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000621
Nate Begeman2504fe22005-09-01 23:24:04 +0000622// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000623// that selects between the target values used for true and false, making it
624// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
625// the appropriate nodes based on the type of node we are checking. This
626// simplifies life a bit for the callers.
627bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
628 SDValue &CC) const {
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000629 if (N.getOpcode() == ISD::SETCC) {
630 LHS = N.getOperand(0);
631 RHS = N.getOperand(1);
632 CC = N.getOperand(2);
Nate Begeman2504fe22005-09-01 23:24:04 +0000633 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000634 }
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000635
636 if (N.getOpcode() != ISD::SELECT_CC ||
637 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
638 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
639 return false;
640
641 LHS = N.getOperand(0);
642 RHS = N.getOperand(1);
643 CC = N.getOperand(4);
644 return true;
Nate Begeman21158fc2005-09-01 00:19:25 +0000645}
646
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000647/// Return true if this is a SetCC-equivalent operation with only one use.
648/// If this is true, it allows the users to invert the operation for free when
649/// it is profitable to do so.
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000650bool DAGCombiner::isOneUseSetCC(SDValue N) const {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000651 SDValue N0, N1, N2;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000652 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman2504fe22005-09-01 23:24:04 +0000653 return true;
654 return false;
655}
656
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000657/// Returns true if N is a BUILD_VECTOR node whose
Matt Arsenault985b9de2014-03-17 18:58:01 +0000658/// elements are all the same constant or undefined.
659static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
660 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
661 if (!C)
662 return false;
663
664 APInt SplatUndef;
665 unsigned SplatBitSize;
666 bool HasAnyUndefs;
667 EVT EltVT = N->getValueType(0).getVectorElementType();
668 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
669 HasAnyUndefs) &&
670 EltVT.getSizeInBits() >= SplatBitSize);
671}
672
673// \brief Returns the SDNode if it is a constant BuildVector or constant.
Juergen Ributzka68402822014-01-13 21:49:25 +0000674static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
675 if (isa<ConstantSDNode>(N))
676 return N.getNode();
677 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
678 if(BV && BV->isConstant())
679 return BV;
Craig Topperc0196b12014-04-14 00:51:57 +0000680 return nullptr;
Juergen Ributzka68402822014-01-13 21:49:25 +0000681}
682
Matt Arsenault985b9de2014-03-17 18:58:01 +0000683// \brief Returns the SDNode if it is a constant splat BuildVector or constant
684// int.
685static ConstantSDNode *isConstOrConstSplat(SDValue N) {
686 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
687 return CN;
688
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000689 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000690 BitVector UndefElements;
691 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000692
693 // BuildVectors can truncate their operands. Ignore that case here.
Chandler Carruthb844e722014-07-08 07:19:55 +0000694 // FIXME: We blindly ignore splats which include undef which is overly
695 // pessimistic.
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000696 if (CN && UndefElements.none() &&
Chandler Carruthb844e722014-07-08 07:19:55 +0000697 CN->getValueType(0) == N.getValueType().getScalarType())
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000698 return CN;
699 }
Matt Arsenault985b9de2014-03-17 18:58:01 +0000700
701 return nullptr;
702}
703
Matt Arsenault6cc00422014-08-16 10:14:19 +0000704// \brief Returns the SDNode if it is a constant splat BuildVector or constant
705// float.
706static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
707 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
708 return CN;
709
710 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
711 BitVector UndefElements;
712 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
713
Matt Arsenault965de302014-09-02 18:33:51 +0000714 if (CN && UndefElements.none())
Matt Arsenault6cc00422014-08-16 10:14:19 +0000715 return CN;
716 }
717
718 return nullptr;
719}
720
Andrew Trickef9de2a2013-05-25 02:42:55 +0000721SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000722 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000723 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000724 if (N0.getOpcode() == Opc) {
725 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
726 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
727 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
728 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
729 if (!OpNode.getNode())
730 return SDValue();
731 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
Juergen Ributzka73844052014-01-13 20:51:35 +0000732 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000733 if (N0.hasOneUse()) {
734 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
735 // use
736 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
737 if (!OpNode.getNode())
738 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000739 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000740 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000741 }
742 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000743 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000744
Juergen Ributzka68402822014-01-13 21:49:25 +0000745 if (N1.getOpcode() == Opc) {
746 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
747 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
748 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
749 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
750 if (!OpNode.getNode())
751 return SDValue();
752 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
753 }
754 if (N1.hasOneUse()) {
755 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
756 // use
757 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
758 if (!OpNode.getNode())
759 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000760 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000761 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
762 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000763 }
764 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000765
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000766 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000767}
768
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000769SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
770 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000771 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
772 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000773 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000774 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000775 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000776 To[0].getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000777 dbgs() << " and " << NumTo-1 << " other values\n";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000778 for (unsigned i = 0, e = NumTo; i != e; ++i)
Jakob Stoklund Olesen32042f92009-12-03 05:15:35 +0000779 assert((!To[i].getNode() ||
780 N->getValueType(i) == To[i].getValueType()) &&
Dan Gohman7e6b9322009-01-21 15:17:51 +0000781 "Cannot combine value to value of different type!"));
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000782 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000783 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000784 if (AddTo) {
785 // Push the new nodes and any users onto the worklist
786 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000787 if (To[i].getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000788 AddToWorklist(To[i].getNode());
789 AddUsersToWorklist(To[i].getNode());
Chris Lattner4147f082009-03-12 06:52:53 +0000790 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000791 }
792 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000793
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000794 // Finally, if the node is now dead, remove it from the graph. The node
795 // may not be dead if the replacement process recursively simplified to
796 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000797 if (N->use_empty())
798 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000799 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000800}
801
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000802void DAGCombiner::
803CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000804 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000805 // are deleted, make sure to remove them from our worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000806 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000807 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000808
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000809 // Push the new node and any (possibly new) users onto the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000810 AddToWorklist(TLO.New.getNode());
811 AddUsersToWorklist(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000812
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000813 // Finally, if the node is now dead, remove it from the graph. The node
814 // may not be dead if the replacement process recursively simplified to
815 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000816 if (TLO.Old.getNode()->use_empty())
817 deleteAndRecombine(TLO.Old.getNode());
Dan Gohmane58ab792009-01-29 01:59:02 +0000818}
819
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000820/// Check the specified integer node value to see if it can be simplified or if
821/// things it uses can be simplified by bit propagation. If so, return true.
Dan Gohmane58ab792009-01-29 01:59:02 +0000822bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000823 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000824 APInt KnownZero, KnownOne;
825 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
826 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000827
Dan Gohmane58ab792009-01-29 01:59:02 +0000828 // Revisit the node.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000829 AddToWorklist(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000830
Dan Gohmane58ab792009-01-29 01:59:02 +0000831 // Replace the old value with the new one.
832 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000833 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000834 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000835 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000836 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000837 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000838
Dan Gohmane58ab792009-01-29 01:59:02 +0000839 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000840 return true;
841}
842
Evan Cheng0abb54d2010-04-24 04:43:44 +0000843void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000844 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000845 EVT VT = Load->getValueType(0);
846 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000847
Evan Cheng0abb54d2010-04-24 04:43:44 +0000848 DEBUG(dbgs() << "\nReplacing.9 ";
849 Load->dump(&DAG);
850 dbgs() << "\nWith: ";
851 Trunc.getNode()->dump(&DAG);
852 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000853 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000854 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
855 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Chandler Carruth18066972014-08-02 10:02:07 +0000856 deleteAndRecombine(Load);
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000857 AddToWorklist(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000858}
859
860SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
861 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000862 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000863 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000864 EVT MemVT = LD->getMemoryVT();
865 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +0000866 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +0000867 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000868 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000869 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000870 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000871 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000872 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000873 }
874
Evan Chenge19aa5c2010-04-19 19:29:22 +0000875 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000876 switch (Opc) {
877 default: break;
878 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000879 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000880 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000881 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000882 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000883 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000884 ZExtPromoteOperand(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::Constant: {
887 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000888 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000889 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000890 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000891 }
892
893 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000894 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000895 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000896}
897
Evan Cheng0abb54d2010-04-24 04:43:44 +0000898SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000899 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
900 return SDValue();
901 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000902 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000903 bool Replace = false;
904 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000905 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000906 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000907 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000908
909 if (Replace)
910 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
911 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000912 DAG.getValueType(OldVT));
913}
914
Evan Cheng0abb54d2010-04-24 04:43:44 +0000915SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000916 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000917 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000918 bool Replace = false;
919 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000920 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000921 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000922 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000923
924 if (Replace)
925 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
926 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000927}
928
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000929/// Promote the specified integer binary operation if the target indicates it is
930/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
931/// i32 since i16 instructions are longer.
Evan Chengaf56fac2010-04-16 06:14:10 +0000932SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
933 if (!LegalOperations)
934 return SDValue();
935
936 EVT VT = Op.getValueType();
937 if (VT.isVector() || !VT.isInteger())
938 return SDValue();
939
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000940 // If operation type is 'undesirable', e.g. i16 on x86, consider
941 // promoting it.
942 unsigned Opc = Op.getOpcode();
943 if (TLI.isTypeDesirableForOp(Opc, VT))
944 return SDValue();
945
Evan Chengaf56fac2010-04-16 06:14:10 +0000946 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000947 // Consult target whether it is a good idea to promote this operation and
948 // what's the right type to promote it to.
949 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +0000950 assert(PVT != VT && "Don't know what type to promote to!");
951
Evan Cheng0abb54d2010-04-24 04:43:44 +0000952 bool Replace0 = false;
953 SDValue N0 = Op.getOperand(0);
954 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
Craig Topperc0196b12014-04-14 00:51:57 +0000955 if (!NN0.getNode())
Evan Chengf1223bd2010-04-22 20:19:46 +0000956 return SDValue();
957
Evan Cheng0abb54d2010-04-24 04:43:44 +0000958 bool Replace1 = false;
959 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +0000960 SDValue NN1;
961 if (N0 == N1)
962 NN1 = NN0;
963 else {
964 NN1 = PromoteOperand(N1, PVT, Replace1);
Craig Topperc0196b12014-04-14 00:51:57 +0000965 if (!NN1.getNode())
Evan Cheng02947a42010-05-10 19:03:57 +0000966 return SDValue();
967 }
Evan Chengf1223bd2010-04-22 20:19:46 +0000968
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000969 AddToWorklist(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +0000970 if (NN1.getNode())
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000971 AddToWorklist(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000972
973 if (Replace0)
974 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
975 if (Replace1)
976 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +0000977
Evan Chenge8136902010-04-27 19:48:13 +0000978 DEBUG(dbgs() << "\nPromoting ";
979 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000980 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000981 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000982 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +0000983 }
984 return SDValue();
985}
986
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000987/// Promote the specified integer shift operation if the target indicates it is
988/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
989/// i32 since i16 instructions are longer.
Evan Chengf1223bd2010-04-22 20:19:46 +0000990SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
991 if (!LegalOperations)
992 return SDValue();
993
994 EVT VT = Op.getValueType();
995 if (VT.isVector() || !VT.isInteger())
996 return SDValue();
997
998 // If operation type is 'undesirable', e.g. i16 on x86, consider
999 // promoting it.
1000 unsigned Opc = Op.getOpcode();
1001 if (TLI.isTypeDesirableForOp(Opc, VT))
1002 return SDValue();
1003
1004 EVT PVT = VT;
1005 // Consult target whether it is a good idea to promote this operation and
1006 // what's the right type to promote it to.
1007 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1008 assert(PVT != VT && "Don't know what type to promote to!");
1009
Evan Cheng0abb54d2010-04-24 04:43:44 +00001010 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001011 SDValue N0 = Op.getOperand(0);
1012 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +00001013 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001014 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +00001015 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001016 else
Evan Cheng0abb54d2010-04-24 04:43:44 +00001017 N0 = PromoteOperand(N0, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +00001018 if (!N0.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001019 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +00001020
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001021 AddToWorklist(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +00001022 if (Replace)
1023 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +00001024
Evan Chenge8136902010-04-27 19:48:13 +00001025 DEBUG(dbgs() << "\nPromoting ";
1026 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001027 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +00001028 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +00001029 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +00001030 }
1031 return SDValue();
1032}
1033
Evan Chenge19aa5c2010-04-19 19:29:22 +00001034SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1035 if (!LegalOperations)
1036 return SDValue();
1037
1038 EVT VT = Op.getValueType();
1039 if (VT.isVector() || !VT.isInteger())
1040 return SDValue();
1041
1042 // If operation type is 'undesirable', e.g. i16 on x86, consider
1043 // promoting it.
1044 unsigned Opc = Op.getOpcode();
1045 if (TLI.isTypeDesirableForOp(Opc, VT))
1046 return SDValue();
1047
1048 EVT PVT = VT;
1049 // Consult target whether it is a good idea to promote this operation and
1050 // what's the right type to promote it to.
1051 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1052 assert(PVT != VT && "Don't know what type to promote to!");
1053 // fold (aext (aext x)) -> (aext x)
1054 // fold (aext (zext x)) -> (zext x)
1055 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +00001056 DEBUG(dbgs() << "\nPromoting ";
1057 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001058 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001059 }
1060 return SDValue();
1061}
1062
1063bool DAGCombiner::PromoteLoad(SDValue Op) {
1064 if (!LegalOperations)
1065 return false;
1066
1067 EVT VT = Op.getValueType();
1068 if (VT.isVector() || !VT.isInteger())
1069 return false;
1070
1071 // If operation type is 'undesirable', e.g. i16 on x86, consider
1072 // promoting it.
1073 unsigned Opc = Op.getOpcode();
1074 if (TLI.isTypeDesirableForOp(Opc, VT))
1075 return false;
1076
1077 EVT PVT = VT;
1078 // Consult target whether it is a good idea to promote this operation and
1079 // what's the right type to promote it to.
1080 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1081 assert(PVT != VT && "Don't know what type to promote to!");
1082
Andrew Trickef9de2a2013-05-25 02:42:55 +00001083 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001084 SDNode *N = Op.getNode();
1085 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001086 EVT MemVT = LD->getMemoryVT();
1087 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +00001088 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +00001089 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001090 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001091 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001092 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001093 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001094 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1095
Evan Cheng0abb54d2010-04-24 04:43:44 +00001096 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001097 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001098 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001099 Result.getNode()->dump(&DAG);
1100 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001101 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001102 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1103 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Chandler Carruth18066972014-08-02 10:02:07 +00001104 deleteAndRecombine(N);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001105 AddToWorklist(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001106 return true;
1107 }
1108 return false;
1109}
1110
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001111/// \brief Recursively delete a node which has no uses and any operands for
1112/// which it is the only use.
1113///
1114/// Note that this both deletes the nodes and removes them from the worklist.
1115/// It also adds any nodes who have had a user deleted to the worklist as they
1116/// may now have only one use and subject to other combines.
1117bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1118 if (!N->use_empty())
1119 return false;
1120
1121 SmallSetVector<SDNode *, 16> Nodes;
1122 Nodes.insert(N);
1123 do {
1124 N = Nodes.pop_back_val();
1125 if (!N)
1126 continue;
1127
1128 if (N->use_empty()) {
1129 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1130 Nodes.insert(N->getOperand(i).getNode());
1131
1132 removeFromWorklist(N);
1133 DAG.DeleteNode(N);
1134 } else {
1135 AddToWorklist(N);
1136 }
1137 } while (!Nodes.empty());
1138 return true;
1139}
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001140
Chris Lattnere49c9742007-05-14 22:04:50 +00001141//===----------------------------------------------------------------------===//
1142// Main DAG Combiner implementation
1143//===----------------------------------------------------------------------===//
1144
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001145void DAGCombiner::Run(CombineLevel AtLevel) {
1146 // set the instance variables, so that the various visit routines may use it.
1147 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001148 LegalOperations = Level >= AfterLegalizeVectorOps;
1149 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001150
Evan Cheng5e7658c2008-08-29 22:21:44 +00001151 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001152 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1153 E = DAG.allnodes_end(); I != E; ++I)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001154 AddToWorklist(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001155
Evan Cheng5e7658c2008-08-29 22:21:44 +00001156 // Create a dummy node (which is not added to allnodes), that adds a reference
1157 // to the root node, preventing it from being deleted, and tracking any
1158 // changes of the root.
1159 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001160
James Molloy67b6b112012-02-16 09:17:04 +00001161 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001162 // try and combine it.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001163 while (!WorklistMap.empty()) {
James Molloy67b6b112012-02-16 09:17:04 +00001164 SDNode *N;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001165 // The Worklist holds the SDNodes in order, but it may contain null entries.
James Molloy67b6b112012-02-16 09:17:04 +00001166 do {
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001167 N = Worklist.pop_back_val();
1168 } while (!N);
1169
1170 bool GoodWorklistEntry = WorklistMap.erase(N);
1171 (void)GoodWorklistEntry;
1172 assert(GoodWorklistEntry &&
1173 "Found a worklist entry without a corresponding map entry!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00001174
Evan Cheng5e7658c2008-08-29 22:21:44 +00001175 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1176 // N is deleted from the DAG, since they too may now be dead or may have a
1177 // reduced number of uses, allowing other xforms.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001178 if (recursivelyDeleteUnusedNodes(N))
Evan Cheng5e7658c2008-08-29 22:21:44 +00001179 continue;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001180
1181 WorklistRemover DeadNodes(*this);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001182
Chandler Carruth411fb402014-07-26 05:49:40 +00001183 // If this combine is running after legalizing the DAG, re-legalize any
1184 // nodes pulled off the worklist.
1185 if (Level == AfterLegalizeDAG) {
1186 SmallSetVector<SDNode *, 16> UpdatedNodes;
1187 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1188
1189 for (SDNode *LN : UpdatedNodes) {
1190 AddToWorklist(LN);
1191 AddUsersToWorklist(LN);
1192 }
1193 if (!NIsValid)
1194 continue;
1195 }
1196
Chandler Carruthb1432742014-07-28 17:55:07 +00001197 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1198
Chandler Carruthcde4eb52014-08-03 23:10:59 +00001199 // Add any operands of the new node which have not yet been combined to the
1200 // worklist as well. Because the worklist uniques things already, this
1201 // won't repeatedly process the same operand.
1202 CombinedNodes.insert(N);
1203 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1204 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1205 AddToWorklist(N->getOperand(i).getNode());
1206
Evan Cheng5e7658c2008-08-29 22:21:44 +00001207 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001208
Craig Topperc0196b12014-04-14 00:51:57 +00001209 if (!RV.getNode())
Evan Cheng5e7658c2008-08-29 22:21:44 +00001210 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001211
Evan Cheng5e7658c2008-08-29 22:21:44 +00001212 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001213
Evan Cheng5e7658c2008-08-29 22:21:44 +00001214 // If we get back the same node we passed in, rather than a new node or
1215 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001216 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001217 // mechanics for us, we have no work to do in this case.
1218 if (RV.getNode() == N)
1219 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001220
Evan Cheng5e7658c2008-08-29 22:21:44 +00001221 assert(N->getOpcode() != ISD::DELETED_NODE &&
1222 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1223 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001224
Chandler Carruth9f4530b2014-07-24 22:15:28 +00001225 DEBUG(dbgs() << " ... into: ";
1226 RV.getNode()->dump(&DAG));
Eric Christopherd6300d22011-07-14 01:12:15 +00001227
Devang Patelefec7712011-05-23 22:04:42 +00001228 // Transfer debug value.
1229 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001230 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001231 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001232 else {
1233 assert(N->getValueType(0) == RV.getValueType() &&
1234 N->getNumValues() == 1 && "Type mismatch");
1235 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001236 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001237 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001238
Evan Cheng5e7658c2008-08-29 22:21:44 +00001239 // Push the new node and any users onto the worklist
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001240 AddToWorklist(RV.getNode());
1241 AddUsersToWorklist(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001242
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001243 // Finally, if the node is now dead, remove it from the graph. The node
1244 // may not be dead if the replacement process recursively simplified to
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001245 // something else needing this node. This will also take care of adding any
1246 // operands which have lost a user to the worklist.
1247 recursivelyDeleteUnusedNodes(N);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001248 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001249
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001250 // If the root changed (e.g. it was a dead load, update the root).
1251 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001252 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001253}
1254
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001255SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001256 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001257 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001258 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001259 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001260 case ISD::ADD: return visitADD(N);
1261 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001262 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001263 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001264 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001265 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001266 case ISD::MUL: return visitMUL(N);
1267 case ISD::SDIV: return visitSDIV(N);
1268 case ISD::UDIV: return visitUDIV(N);
1269 case ISD::SREM: return visitSREM(N);
1270 case ISD::UREM: return visitUREM(N);
1271 case ISD::MULHU: return visitMULHU(N);
1272 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001273 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1274 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001275 case ISD::SMULO: return visitSMULO(N);
1276 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001277 case ISD::SDIVREM: return visitSDIVREM(N);
1278 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001279 case ISD::AND: return visitAND(N);
1280 case ISD::OR: return visitOR(N);
1281 case ISD::XOR: return visitXOR(N);
1282 case ISD::SHL: return visitSHL(N);
1283 case ISD::SRA: return visitSRA(N);
1284 case ISD::SRL: return visitSRL(N);
Adam Nemet7f928f12014-03-07 23:56:30 +00001285 case ISD::ROTR:
1286 case ISD::ROTL: return visitRotate(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001287 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001288 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001289 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001290 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001291 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001292 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001293 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001294 case ISD::SELECT_CC: return visitSELECT_CC(N);
1295 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001296 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1297 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001298 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001299 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1300 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001301 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001302 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001303 case ISD::FADD: return visitFADD(N);
1304 case ISD::FSUB: return visitFSUB(N);
1305 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001306 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001307 case ISD::FDIV: return visitFDIV(N);
1308 case ISD::FREM: return visitFREM(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001309 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001310 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1311 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1312 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1313 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1314 case ISD::FP_ROUND: return visitFP_ROUND(N);
1315 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1316 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1317 case ISD::FNEG: return visitFNEG(N);
1318 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001319 case ISD::FFLOOR: return visitFFLOOR(N);
1320 case ISD::FCEIL: return visitFCEIL(N);
1321 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001322 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001323 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001324 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001325 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001326 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001327 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001328 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1329 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001330 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001331 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001332 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001333 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001334 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001335}
1336
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001337SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001338 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001339
1340 // If nothing happened, try a target-specific DAG combine.
Craig Topperc0196b12014-04-14 00:51:57 +00001341 if (!RV.getNode()) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001342 assert(N->getOpcode() != ISD::DELETED_NODE &&
1343 "Node was deleted but visit returned NULL!");
1344
1345 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1346 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1347
1348 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001349 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001350 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001351
1352 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1353 }
1354 }
1355
Evan Chengf1005572010-04-28 07:10:39 +00001356 // If nothing happened still, try promoting the operation.
Craig Topperc0196b12014-04-14 00:51:57 +00001357 if (!RV.getNode()) {
Evan Chengf1005572010-04-28 07:10:39 +00001358 switch (N->getOpcode()) {
1359 default: break;
1360 case ISD::ADD:
1361 case ISD::SUB:
1362 case ISD::MUL:
1363 case ISD::AND:
1364 case ISD::OR:
1365 case ISD::XOR:
1366 RV = PromoteIntBinOp(SDValue(N, 0));
1367 break;
1368 case ISD::SHL:
1369 case ISD::SRA:
1370 case ISD::SRL:
1371 RV = PromoteIntShiftOp(SDValue(N, 0));
1372 break;
1373 case ISD::SIGN_EXTEND:
1374 case ISD::ZERO_EXTEND:
1375 case ISD::ANY_EXTEND:
1376 RV = PromoteExtend(SDValue(N, 0));
1377 break;
1378 case ISD::LOAD:
1379 if (PromoteLoad(SDValue(N, 0)))
1380 RV = SDValue(N, 0);
1381 break;
1382 }
1383 }
1384
Scott Michelcf0da6c2009-02-17 22:15:04 +00001385 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001386 // sdisel CSE.
Craig Topperc0196b12014-04-14 00:51:57 +00001387 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
Evan Cheng31604a62008-03-22 01:55:50 +00001388 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001389 SDValue N0 = N->getOperand(0);
1390 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001391
Evan Cheng31604a62008-03-22 01:55:50 +00001392 // Constant operands are canonicalized to RHS.
1393 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00001394 SDValue Ops[] = {N1, N0};
1395 SDNode *CSENode;
1396 if (const BinaryWithFlagsSDNode *BinNode =
1397 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1398 CSENode = DAG.getNodeIfExists(
1399 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1400 BinNode->hasNoSignedWrap(), BinNode->isExact());
1401 } else {
1402 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1403 }
Evan Chengfe7610f2008-03-24 23:55:16 +00001404 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001405 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001406 }
1407 }
1408
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001409 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001410}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001411
Sanjay Patel50cbfc52014-08-28 16:29:51 +00001412/// Given a node, return its input chain if it has one, otherwise return a null
1413/// sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001414static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001415 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001416 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001417 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001418 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001419 return N->getOperand(NumOps-1);
1420 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001421 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001422 return N->getOperand(i);
1423 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001424 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001425}
1426
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001427SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001428 // If N has two operands, where one has an input chain equal to the other,
1429 // the 'other' chain is redundant.
1430 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001431 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001432 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001433 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001434 return N->getOperand(1);
1435 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001436
Chris Lattner48fb92f2007-05-16 06:37:59 +00001437 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001438 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001439 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001440 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001441
Jim Laskey708d0db2006-10-04 16:53:27 +00001442 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001443 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001444
Jim Laskey0463e082006-10-07 23:37:56 +00001445 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001446 // encountered.
1447 for (unsigned i = 0; i < TFs.size(); ++i) {
1448 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001449
Jim Laskey708d0db2006-10-04 16:53:27 +00001450 // Check each of the operands.
1451 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001452 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001453
Jim Laskey708d0db2006-10-04 16:53:27 +00001454 switch (Op.getOpcode()) {
1455 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001456 // Entry tokens don't need to be added to the list. They are
1457 // rededundant.
1458 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001459 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001460
Jim Laskey708d0db2006-10-04 16:53:27 +00001461 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001462 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001463 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001464 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001465 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001466 // Clean up in case the token factor is removed.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001467 AddToWorklist(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001468 Changed = true;
1469 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001470 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001471 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001472
Jim Laskey708d0db2006-10-04 16:53:27 +00001473 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001474 // Only add if it isn't already in the list.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001475 if (SeenOps.insert(Op.getNode()))
Jim Laskey6549d222006-10-05 15:07:25 +00001476 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001477 else
1478 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001479 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001480 }
1481 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001482 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001483
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001484 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001485
1486 // If we've change things around then replace token factor.
1487 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001488 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001489 // The entry token is the only possible outcome.
1490 Result = DAG.getEntryNode();
1491 } else {
1492 // New and improved token factor.
Craig Topper48d114b2014-04-26 18:35:24 +00001493 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
Nate Begeman02b23c62005-10-13 03:11:28 +00001494 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001495
Jim Laskeydcf983c2006-10-13 23:32:28 +00001496 // Don't add users to work list.
1497 return CombineTo(N, Result, false);
Nate Begeman02b23c62005-10-13 03:11:28 +00001498 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001499
Jim Laskey708d0db2006-10-04 16:53:27 +00001500 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001501}
1502
Chris Lattneree322b42008-02-13 07:25:05 +00001503/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001504SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001505 WorklistRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001506 // Replacing results may cause a different MERGE_VALUES to suddenly
1507 // be CSE'd with N, and carry its uses with it. Iterate until no
1508 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001509 // First add the users of this node to the work list so that they
1510 // can be tried again once they have new operands.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001511 AddUsersToWorklist(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001512 do {
1513 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001514 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001515 } while (!N->use_empty());
Chandler Carruth18066972014-08-02 10:02:07 +00001516 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001517 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001518}
1519
Evan Cheng92011002007-01-19 17:51:44 +00001520static
Andrew Trickef9de2a2013-05-25 02:42:55 +00001521SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001522 SelectionDAG &DAG) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001523 EVT VT = N0.getValueType();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001524 SDValue N00 = N0.getOperand(0);
1525 SDValue N01 = N0.getOperand(1);
Evan Cheng92011002007-01-19 17:51:44 +00001526 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
Bill Wendlingcdd96132009-01-30 02:23:43 +00001527
Gabor Greiff304a7a2008-08-28 21:40:38 +00001528 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
Evan Cheng92011002007-01-19 17:51:44 +00001529 isa<ConstantSDNode>(N00.getOperand(1))) {
Bill Wendlingcdd96132009-01-30 02:23:43 +00001530 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Andrew Trickef9de2a2013-05-25 02:42:55 +00001531 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1532 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001533 N00.getOperand(0), N01),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001534 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001535 N00.getOperand(1), N01));
1536 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
Evan Cheng92011002007-01-19 17:51:44 +00001537 }
Bill Wendlingcdd96132009-01-30 02:23:43 +00001538
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001539 return SDValue();
Evan Cheng92011002007-01-19 17:51:44 +00001540}
1541
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001542SDValue DAGCombiner::visitADD(SDNode *N) {
1543 SDValue N0 = N->getOperand(0);
1544 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001545 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1546 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001547 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001548
1549 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001550 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001551 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001552 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001553
1554 // fold (add x, 0) -> x, vector edition
1555 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1556 return N0;
1557 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1558 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001559 }
Bill Wendling0864a752008-12-10 22:36:00 +00001560
Dan Gohman06563a82007-07-03 14:03:57 +00001561 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001562 if (N0.getOpcode() == ISD::UNDEF)
1563 return N0;
1564 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001565 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001566 // fold (add c1, c2) -> c1+c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001567 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001568 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001569 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00001570 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001571 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001572 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001573 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001574 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001575 // fold (add Sym, c) -> Sym+c
1576 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001577 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001578 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001579 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001580 GA->getOffset() +
1581 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001582 // fold ((c1-A)+c2) -> (c1+c2)-A
1583 if (N1C && N0.getOpcode() == ISD::SUB)
1584 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001585 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001586 DAG.getConstant(N1C->getAPIntValue()+
1587 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001588 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001589 // reassociate add
Andrew Trickef9de2a2013-05-25 02:42:55 +00001590 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001591 if (RADD.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001592 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001593 // fold ((0-A) + B) -> B-A
1594 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1595 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001596 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001597 // fold (A + (0-B)) -> A-B
1598 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1599 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001600 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001601 // fold (A+(B-A)) -> B
1602 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001603 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001604 // fold ((B-A)+A) -> B
1605 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1606 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001607 // fold (A+(B-(A+C))) to (B-C)
1608 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001609 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001610 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001611 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001612 // fold (A+(B-(C+A))) to (B-C)
1613 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001614 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001615 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001616 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001617 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001618 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1619 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001620 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001621 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001622 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001623
Dale Johannesen8c766702008-12-02 01:30:54 +00001624 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1625 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1626 SDValue N00 = N0.getOperand(0);
1627 SDValue N01 = N0.getOperand(1);
1628 SDValue N10 = N1.getOperand(0);
1629 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001630
1631 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001632 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1633 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1634 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001635 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001636
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001637 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1638 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001639
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001640 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001641 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001642 APInt LHSZero, LHSOne;
1643 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001644 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001645
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001646 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001647 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001648
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001649 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1650 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001651 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1652 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1653 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1654 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001655 }
1656 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001657
Evan Cheng92011002007-01-19 17:51:44 +00001658 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Gabor Greiff304a7a2008-08-28 21:40:38 +00001659 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001660 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001661 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001662 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00001663 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001664 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001665 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001666 }
1667
Dan Gohman954f4902010-01-19 23:30:49 +00001668 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1669 if (N1.getOpcode() == ISD::SHL &&
1670 N1.getOperand(0).getOpcode() == ISD::SUB)
1671 if (ConstantSDNode *C =
1672 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1673 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001674 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1675 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001676 N1.getOperand(0).getOperand(1),
1677 N1.getOperand(1)));
1678 if (N0.getOpcode() == ISD::SHL &&
1679 N0.getOperand(0).getOpcode() == ISD::SUB)
1680 if (ConstantSDNode *C =
1681 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1682 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001683 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1684 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001685 N0.getOperand(0).getOperand(1),
1686 N0.getOperand(1)));
1687
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001688 if (N1.getOpcode() == ISD::AND) {
1689 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001690 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001691 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1692 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001693
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001694 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1695 // and similar xforms where the inner op is either ~0 or 0.
1696 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001697 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001698 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1699 }
1700 }
1701
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001702 // add (sext i1), X -> sub X, (zext i1)
1703 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1704 N0.getOperand(0).getValueType() == MVT::i1 &&
1705 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001706 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001707 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1708 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1709 }
1710
Evan Chengf1005572010-04-28 07:10:39 +00001711 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001712}
1713
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001714SDValue DAGCombiner::visitADDC(SDNode *N) {
1715 SDValue N0 = N->getOperand(0);
1716 SDValue N1 = N->getOperand(1);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001717 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1718 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001719 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001720
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001721 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001722 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001723 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001724 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001725 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001726
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001727 // canonicalize constant to RHS.
Dan Gohmanb4e26372008-06-23 15:29:14 +00001728 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001729 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001730
Chris Lattner47206662007-03-04 20:40:38 +00001731 // fold (addc x, 0) -> x + no carry out
1732 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001733 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001734 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001735
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001736 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001737 APInt LHSZero, LHSOne;
1738 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001739 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001740
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001741 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001742 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001743
Chris Lattner47206662007-03-04 20:40:38 +00001744 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1745 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001746 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001747 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001748 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001749 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001750 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001751
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001752 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001753}
1754
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001755SDValue DAGCombiner::visitADDE(SDNode *N) {
1756 SDValue N0 = N->getOperand(0);
1757 SDValue N1 = N->getOperand(1);
1758 SDValue CarryIn = N->getOperand(2);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001759 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1760 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001761
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001762 // canonicalize constant to RHS
Dan Gohmanb4e26372008-06-23 15:29:14 +00001763 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001764 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001765 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001766
Chris Lattner47206662007-03-04 20:40:38 +00001767 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001768 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001769 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001770
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001771 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001772}
1773
Eric Christophere5ca1e02011-02-16 04:50:12 +00001774// Since it may not be valid to emit a fold to zero for vector initializers
1775// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001776static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001777 SelectionDAG &DAG,
1778 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001779 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001780 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001781 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1782 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001783 return SDValue();
1784}
1785
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001786SDValue DAGCombiner::visitSUB(SDNode *N) {
1787 SDValue N0 = N->getOperand(0);
1788 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001789 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1790 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00001791 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
Eric Christopherd6300d22011-07-14 01:12:15 +00001792 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001793 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001794
Dan Gohmana8665142007-06-25 16:23:39 +00001795 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001796 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001797 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001798 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001799
1800 // fold (sub x, 0) -> x, vector edition
1801 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1802 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001803 }
Bill Wendling0864a752008-12-10 22:36:00 +00001804
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001805 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001806 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001807 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001808 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001809 // fold (sub c1, c2) -> c1-c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001810 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001811 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001812 // fold (sub x, c) -> (add x, -c)
1813 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001814 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001815 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001816 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1817 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001818 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001819 // fold A-(A-B) -> B
1820 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1821 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001822 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001823 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001824 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001825 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001826 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001827 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001828 // fold C2-(A+C1) -> (C2-C1)-A
1829 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001830 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1831 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001832 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001833 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001834 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001835 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001836 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001837 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1838 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001839 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001840 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001841 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001842 // fold ((A+(C+B))-B) -> A+C
1843 if (N0.getOpcode() == ISD::ADD &&
1844 N0.getOperand(1).getOpcode() == ISD::ADD &&
1845 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001846 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001847 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001848 // fold ((A-(B-C))-C) -> A-B
1849 if (N0.getOpcode() == ISD::SUB &&
1850 N0.getOperand(1).getOpcode() == ISD::SUB &&
1851 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001852 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001853 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001854
Dan Gohman06563a82007-07-03 14:03:57 +00001855 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001856 if (N0.getOpcode() == ISD::UNDEF)
1857 return N0;
1858 if (N1.getOpcode() == ISD::UNDEF)
1859 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001860
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001861 // If the relocation model supports it, consider symbol offsets.
1862 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001863 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001864 // fold (sub Sym, c) -> Sym-c
1865 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001866 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001867 GA->getOffset() -
1868 (uint64_t)N1C->getSExtValue());
1869 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1870 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1871 if (GA->getGlobal() == GB->getGlobal())
1872 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1873 VT);
1874 }
1875
Evan Chengf1005572010-04-28 07:10:39 +00001876 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001877}
1878
Craig Topper43a1bd62012-01-07 09:06:39 +00001879SDValue DAGCombiner::visitSUBC(SDNode *N) {
1880 SDValue N0 = N->getOperand(0);
1881 SDValue N1 = N->getOperand(1);
1882 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1883 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1884 EVT VT = N0.getValueType();
1885
1886 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001887 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001888 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1889 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001890 MVT::Glue));
1891
1892 // fold (subc x, x) -> 0 + no borrow
1893 if (N0 == N1)
1894 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001895 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001896 MVT::Glue));
1897
1898 // fold (subc x, 0) -> x + no borrow
1899 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001900 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001901 MVT::Glue));
1902
1903 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1904 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001905 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1906 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001907 MVT::Glue));
1908
1909 return SDValue();
1910}
1911
1912SDValue DAGCombiner::visitSUBE(SDNode *N) {
1913 SDValue N0 = N->getOperand(0);
1914 SDValue N1 = N->getOperand(1);
1915 SDValue CarryIn = N->getOperand(2);
1916
1917 // fold (sube x, y, false) -> (subc x, y)
1918 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001919 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001920
1921 return SDValue();
1922}
1923
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001924SDValue DAGCombiner::visitMUL(SDNode *N) {
1925 SDValue N0 = N->getOperand(0);
1926 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001927 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001928
Dan Gohman06563a82007-07-03 14:03:57 +00001929 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001930 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001931 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001932
1933 bool N0IsConst = false;
1934 bool N1IsConst = false;
1935 APInt ConstValue0, ConstValue1;
1936 // fold vector ops
1937 if (VT.isVector()) {
1938 SDValue FoldedVOp = SimplifyVBinOp(N);
1939 if (FoldedVOp.getNode()) return FoldedVOp;
1940
1941 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1942 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1943 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00001944 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001945 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1946 : APInt();
Craig Topperc0196b12014-04-14 00:51:57 +00001947 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001948 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1949 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001950 }
1951
Nate Begeman21158fc2005-09-01 00:19:25 +00001952 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001953 if (N0IsConst && N1IsConst)
1954 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1955
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001956 // canonicalize constant to RHS
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001957 if (N0IsConst && !N1IsConst)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001958 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001959 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001960 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00001961 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001962 // We require a splat of the entire scalar bit width for non-contiguous
1963 // bit patterns.
1964 bool IsFullSplat =
1965 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001966 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001967 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001968 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00001969 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001970 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001971 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001972 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001973 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001974 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001975 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001976 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00001977 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00001978 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001979 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001980 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001981 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00001982 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001983 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001984 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001985 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00001986 DAG.getConstant(Log2Val,
1987 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00001988 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001989
1990 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00001991 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00001992 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001993 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1994 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001995 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001996 N1, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001997 AddToWorklist(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001998 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001999 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00002000 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002001
Chris Lattner324871e2006-03-01 03:44:24 +00002002 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2003 // use.
2004 {
Craig Topperc0196b12014-04-14 00:51:57 +00002005 SDValue Sh(nullptr,0), Y(nullptr,0);
Chris Lattner324871e2006-03-01 03:44:24 +00002006 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00002007 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002008 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2009 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00002010 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00002011 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002012 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00002013 isa<ConstantSDNode>(N1.getOperand(1)) &&
2014 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00002015 Sh = N1; Y = N0;
2016 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00002017
Gabor Greiff304a7a2008-08-28 21:40:38 +00002018 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002019 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002020 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002021 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002022 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00002023 }
2024 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00002025
Chris Lattnerf29f5202006-03-04 23:33:26 +00002026 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002027 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2028 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2029 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002030 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2031 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002032 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00002033 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002034 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00002035
Nate Begeman22e251a2006-02-03 06:46:56 +00002036 // reassociate mul
Andrew Trickef9de2a2013-05-25 02:42:55 +00002037 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002038 if (RMUL.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002039 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00002040
Evan Chengf1005572010-04-28 07:10:39 +00002041 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002042}
2043
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002044SDValue DAGCombiner::visitSDIV(SDNode *N) {
2045 SDValue N0 = N->getOperand(0);
2046 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002047 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2048 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002049 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002050
Dan Gohmana8665142007-06-25 16:23:39 +00002051 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002052 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002053 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002054 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002055 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002056
Nate Begeman21158fc2005-09-01 00:19:25 +00002057 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002058 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002059 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00002060 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00002061 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00002062 return N0;
2063 // fold (sdiv X, -1) -> 0-X
2064 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002065 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00002066 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00002067 // If we know the sign bits of both operands are zero, strength reduce to a
2068 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00002069 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002070 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002071 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00002072 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00002073 }
Benjamin Kramerad016872014-04-26 13:00:53 +00002074
Nate Begeman57b35672006-02-17 07:26:20 +00002075 // fold (sdiv X, pow2) -> simple ops after legalize
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002076 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2077 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00002078 // If dividing by powers of two is cheap, then don't perform the following
2079 // fold.
Sanjay Patel2cdea4c2014-08-21 22:31:48 +00002080 if (TLI.isPow2SDivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002081 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00002082
Chad Rosier17020f92014-07-23 14:57:52 +00002083 // Target-specific implementation of sdiv x, pow2.
2084 SDValue Res = BuildSDIVPow2(N);
2085 if (Res.getNode())
2086 return Res;
2087
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002088 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00002089
Chris Lattner471627c2006-02-16 08:02:36 +00002090 // Splat the sign bit into the register
Benjamin Kramerad016872014-04-26 13:00:53 +00002091 SDValue SGN =
2092 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2093 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2094 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002095 AddToWorklist(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002096
Chris Lattner471627c2006-02-16 08:02:36 +00002097 // Add (N0 < 0) ? abs2 - 1 : 0;
Benjamin Kramerad016872014-04-26 13:00:53 +00002098 SDValue SRL =
2099 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2100 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2101 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002102 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002103 AddToWorklist(SRL.getNode());
2104 AddToWorklist(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00002105 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002106 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002107
Nate Begeman4dd38312005-10-21 00:02:42 +00002108 // If we're dividing by a positive value, we're done. Otherwise, we must
2109 // negate the result.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002110 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002111 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002112
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002113 AddToWorklist(SRA.getNode());
Benjamin Kramerad016872014-04-26 13:00:53 +00002114 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002115 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002116
Nate Begemanc6f067a2005-10-20 02:15:44 +00002117 // if integer divide is expensive and we satisfy the requirements, emit an
2118 // alternate sequence.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002119 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002120 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002121 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002122 }
Dan Gohmana8665142007-06-25 16:23:39 +00002123
Dan Gohman06563a82007-07-03 14:03:57 +00002124 // undef / X -> 0
2125 if (N0.getOpcode() == ISD::UNDEF)
2126 return DAG.getConstant(0, VT);
2127 // X / undef -> undef
2128 if (N1.getOpcode() == ISD::UNDEF)
2129 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002130
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002131 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002132}
2133
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002134SDValue DAGCombiner::visitUDIV(SDNode *N) {
2135 SDValue N0 = N->getOperand(0);
2136 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002137 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2138 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002139 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002140
Dan Gohmana8665142007-06-25 16:23:39 +00002141 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002142 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002143 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002144 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002145 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002146
Nate Begeman21158fc2005-09-01 00:19:25 +00002147 // fold (udiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002148 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002149 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002150 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002151 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002152 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002153 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002154 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002155 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002156 if (N1.getOpcode() == ISD::SHL) {
2157 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002158 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002159 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002160 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002161 N1.getOperand(1),
2162 DAG.getConstant(SHC->getAPIntValue()
2163 .logBase2(),
2164 ADDVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002165 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002166 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002167 }
2168 }
2169 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002170 // fold (udiv x, c) -> alternate
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002171 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002172 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002173 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002174 }
Dan Gohmana8665142007-06-25 16:23:39 +00002175
Dan Gohman06563a82007-07-03 14:03:57 +00002176 // undef / X -> 0
2177 if (N0.getOpcode() == ISD::UNDEF)
2178 return DAG.getConstant(0, VT);
2179 // X / undef -> undef
2180 if (N1.getOpcode() == ISD::UNDEF)
2181 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002182
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002183 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002184}
2185
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002186SDValue DAGCombiner::visitSREM(SDNode *N) {
2187 SDValue N0 = N->getOperand(0);
2188 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002189 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2190 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002191 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002192
Nate Begeman21158fc2005-09-01 00:19:25 +00002193 // fold (srem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002194 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002195 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002196 // If we know the sign bits of both operands are zero, strength reduce to a
2197 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002198 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002199 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002200 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002201 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002202
Dan Gohman9a693412007-11-26 23:46:11 +00002203 // If X/C can be simplified by the division-by-constant logic, lower
2204 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002205 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002206 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002207 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002208 SDValue OptimizedDiv = combine(Div.getNode());
2209 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002210 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002211 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002212 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002213 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002214 return Sub;
2215 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002216 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002217
Dan Gohman06563a82007-07-03 14:03:57 +00002218 // undef % X -> 0
2219 if (N0.getOpcode() == ISD::UNDEF)
2220 return DAG.getConstant(0, VT);
2221 // X % undef -> undef
2222 if (N1.getOpcode() == ISD::UNDEF)
2223 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002224
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002225 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002226}
2227
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002228SDValue DAGCombiner::visitUREM(SDNode *N) {
2229 SDValue N0 = N->getOperand(0);
2230 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002231 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2232 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002233 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002234
Nate Begeman21158fc2005-09-01 00:19:25 +00002235 // fold (urem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002236 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002237 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002238 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002239 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002240 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002241 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002242 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2243 if (N1.getOpcode() == ISD::SHL) {
2244 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002245 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002246 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002247 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002248 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002249 VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002250 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002251 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002252 }
2253 }
2254 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002255
Dan Gohman9a693412007-11-26 23:46:11 +00002256 // If X/C can be simplified by the division-by-constant logic, lower
2257 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002258 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002259 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002260 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002261 SDValue OptimizedDiv = combine(Div.getNode());
2262 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002263 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002264 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002265 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002266 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002267 return Sub;
2268 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002269 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002270
Dan Gohman06563a82007-07-03 14:03:57 +00002271 // undef % X -> 0
2272 if (N0.getOpcode() == ISD::UNDEF)
2273 return DAG.getConstant(0, VT);
2274 // X % undef -> undef
2275 if (N1.getOpcode() == ISD::UNDEF)
2276 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002277
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002278 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002279}
2280
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002281SDValue DAGCombiner::visitMULHS(SDNode *N) {
2282 SDValue N0 = N->getOperand(0);
2283 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002284 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002285 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002286 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002287
Nate Begeman21158fc2005-09-01 00:19:25 +00002288 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002289 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002290 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002291 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002292 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002293 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002294 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002295 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002296 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002297 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002298 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002299
Chris Lattner10bd29f2010-12-13 08:39:01 +00002300 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2301 // plus a shift.
2302 if (VT.isSimple() && !VT.isVector()) {
2303 MVT Simple = VT.getSimpleVT();
2304 unsigned SimpleSize = Simple.getSizeInBits();
2305 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2306 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2307 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2308 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2309 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002310 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002311 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002312 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2313 }
2314 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002315
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002316 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002317}
2318
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002319SDValue DAGCombiner::visitMULHU(SDNode *N) {
2320 SDValue N0 = N->getOperand(0);
2321 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002322 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002323 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002324 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002325
Nate Begeman21158fc2005-09-01 00:19:25 +00002326 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002327 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002328 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002329 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002330 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002331 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002332 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002333 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002334 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002335
Chris Lattner10bd29f2010-12-13 08:39:01 +00002336 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2337 // plus a shift.
2338 if (VT.isSimple() && !VT.isVector()) {
2339 MVT Simple = VT.getSimpleVT();
2340 unsigned SimpleSize = Simple.getSizeInBits();
2341 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2342 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2343 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2344 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2345 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2346 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002347 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002348 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2349 }
2350 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002351
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002352 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002353}
2354
Sanjay Patel50cbfc52014-08-28 16:29:51 +00002355/// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2356/// give the opcodes for the two computations that are being performed. Return
2357/// true if a simplification was made.
Scott Michelcf0da6c2009-02-17 22:15:04 +00002358SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002359 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002360 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002361 bool HiExists = N->hasAnyUseOfValue(1);
2362 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002363 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002364 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Craig Toppere1d12942014-08-27 05:25:25 +00002365 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002366 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002367 }
2368
2369 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002370 bool LoExists = N->hasAnyUseOfValue(0);
2371 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002372 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002373 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Craig Toppere1d12942014-08-27 05:25:25 +00002374 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002375 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002376 }
2377
Evan Chengece4c682007-11-08 09:25:29 +00002378 // If both halves are used, return as it is.
2379 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002380 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002381
2382 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002383 if (LoExists) {
Craig Toppere1d12942014-08-27 05:25:25 +00002384 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002385 AddToWorklist(Lo.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002386 SDValue LoOpt = combine(Lo.getNode());
2387 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002388 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002389 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002390 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002391 }
2392
Evan Chengece4c682007-11-08 09:25:29 +00002393 if (HiExists) {
Craig Toppere1d12942014-08-27 05:25:25 +00002394 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002395 AddToWorklist(Hi.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002396 SDValue HiOpt = combine(Hi.getNode());
2397 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002398 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002399 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002400 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002401 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002402
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002403 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002404}
2405
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002406SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2407 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002408 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002409
Chris Lattner15090e12010-12-15 06:04:19 +00002410 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002411 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002412
2413 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2414 // plus a shift.
2415 if (VT.isSimple() && !VT.isVector()) {
2416 MVT Simple = VT.getSimpleVT();
2417 unsigned SimpleSize = Simple.getSizeInBits();
2418 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2419 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2420 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2421 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2422 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2423 // Compute the high part as N1.
2424 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002425 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002426 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2427 // Compute the low part as N0.
2428 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2429 return CombineTo(N, Lo, Hi);
2430 }
2431 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002432
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002433 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002434}
2435
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002436SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2437 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002438 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002439
Chris Lattner15090e12010-12-15 06:04:19 +00002440 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002441 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002442
Chris Lattner15090e12010-12-15 06:04:19 +00002443 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2444 // plus a shift.
2445 if (VT.isSimple() && !VT.isVector()) {
2446 MVT Simple = VT.getSimpleVT();
2447 unsigned SimpleSize = Simple.getSizeInBits();
2448 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2449 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2450 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2451 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2452 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2453 // Compute the high part as N1.
2454 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002455 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002456 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2457 // Compute the low part as N0.
2458 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2459 return CombineTo(N, Lo, Hi);
2460 }
2461 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002462
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002463 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002464}
2465
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002466SDValue DAGCombiner::visitSMULO(SDNode *N) {
2467 // (smulo x, 2) -> (saddo x, x)
2468 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2469 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002470 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002471 N->getOperand(0), N->getOperand(0));
2472
2473 return SDValue();
2474}
2475
2476SDValue DAGCombiner::visitUMULO(SDNode *N) {
2477 // (umulo x, 2) -> (uaddo x, x)
2478 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2479 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002480 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002481 N->getOperand(0), N->getOperand(0));
2482
2483 return SDValue();
2484}
2485
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002486SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2487 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002488 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002489
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002490 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002491}
2492
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002493SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2494 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002495 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002496
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002497 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002498}
2499
Sanjay Patel50cbfc52014-08-28 16:29:51 +00002500/// If this is a binary operator with two operands of the same opcode, try to
2501/// simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002502SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2503 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002504 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002505 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002506
Dan Gohmandd5286d2010-01-14 03:08:49 +00002507 // Bail early if none of these transforms apply.
2508 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2509
Chris Lattner002ee912006-05-05 06:31:05 +00002510 // For each of OP in AND/OR/XOR:
2511 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2512 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2513 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002514 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002515 //
2516 // do not sink logical op inside of a vector extend, since it may combine
2517 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002518 EVT Op0VT = N0.getOperand(0).getValueType();
2519 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002520 N0.getOpcode() == ISD::SIGN_EXTEND ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002521 // Avoid infinite looping with PromoteIntBinOp.
2522 (N0.getOpcode() == ISD::ANY_EXTEND &&
2523 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002524 (N0.getOpcode() == ISD::TRUNCATE &&
2525 (!TLI.isZExtFree(VT, Op0VT) ||
2526 !TLI.isTruncateFree(Op0VT, VT)) &&
2527 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002528 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002529 Op0VT == N1.getOperand(0).getValueType() &&
2530 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002531 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002532 N0.getOperand(0).getValueType(),
2533 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002534 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002535 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002536 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002537
Chris Lattner5ac42932006-05-05 06:10:43 +00002538 // For each of OP in SHL/SRL/SRA/AND...
2539 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2540 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2541 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002542 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002543 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002544 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002545 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002546 N0.getOperand(0).getValueType(),
2547 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002548 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002549 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002550 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002551 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002552
Nadav Rotemb0783502012-04-01 19:31:22 +00002553 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2554 // Only perform this optimization after type legalization and before
2555 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2556 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2557 // we don't want to undo this promotion.
2558 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2559 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002560 if ((N0.getOpcode() == ISD::BITCAST ||
2561 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2562 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002563 SDValue In0 = N0.getOperand(0);
2564 SDValue In1 = N1.getOperand(0);
2565 EVT In0Ty = In0.getValueType();
2566 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002567 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002568 // If both incoming values are integers, and the original types are the
2569 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002570 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002571 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2572 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002573 AddToWorklist(Op.getNode());
Nadav Rotemb0783502012-04-01 19:31:22 +00002574 return BC;
2575 }
2576 }
2577
2578 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2579 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2580 // If both shuffles use the same mask, and both shuffle within a single
2581 // vector, then it is worthwhile to move the swizzle after the operation.
2582 // The type-legalizer generates this pattern when loading illegal
2583 // vector types from memory. In many cases this allows additional shuffle
2584 // optimizations.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002585 // There are other cases where moving the shuffle after the xor/and/or
2586 // is profitable even if shuffles don't perform a swizzle.
2587 // If both shuffles use the same mask, and both shuffles have the same first
2588 // or second operand, then it might still be profitable to move the shuffle
2589 // after the xor/and/or operation.
2590 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002591 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2592 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002593
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002594 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
Craig Topper9c3da312012-04-09 07:19:09 +00002595 "Inputs to shuffles are not the same type");
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00002596
Nadav Rotemb0783502012-04-01 19:31:22 +00002597 // Check that both shuffles use the same mask. The masks are known to be of
2598 // the same length because the result vector type is the same.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002599 // Check also that shuffles have only one use to avoid introducing extra
2600 // instructions.
2601 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2602 SVN0->getMask().equals(SVN1->getMask())) {
2603 SDValue ShOp = N0->getOperand(1);
Nadav Rotemb0783502012-04-01 19:31:22 +00002604
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002605 // Don't try to fold this node if it requires introducing a
2606 // build vector of all zeros that might be illegal at this stage.
2607 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2608 if (!LegalTypes)
2609 ShOp = DAG.getConstant(0, VT);
2610 else
2611 ShOp = SDValue();
2612 }
2613
2614 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2615 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2616 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2617 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2618 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2619 N0->getOperand(0), N1->getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002620 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002621 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2622 &SVN0->getMask()[0]);
2623 }
2624
2625 // Don't try to fold this node if it requires introducing a
2626 // build vector of all zeros that might be illegal at this stage.
2627 ShOp = N0->getOperand(0);
2628 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2629 if (!LegalTypes)
2630 ShOp = DAG.getConstant(0, VT);
2631 else
2632 ShOp = SDValue();
2633 }
2634
2635 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2636 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2637 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2638 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2639 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2640 N0->getOperand(1), N1->getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002641 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002642 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2643 &SVN0->getMask()[0]);
2644 }
Nadav Rotemb0783502012-04-01 19:31:22 +00002645 }
2646 }
Craig Topper9c3da312012-04-09 07:19:09 +00002647
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002648 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002649}
2650
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002651SDValue DAGCombiner::visitAND(SDNode *N) {
2652 SDValue N0 = N->getOperand(0);
2653 SDValue N1 = N->getOperand(1);
2654 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002655 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2656 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002657 EVT VT = N1.getValueType();
Dan Gohmane14c4082010-03-04 00:23:16 +00002658 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002659
Dan Gohmana8665142007-06-25 16:23:39 +00002660 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002661 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002662 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002663 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002664
2665 // fold (and x, 0) -> 0, vector edition
2666 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2667 return N0;
2668 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2669 return N1;
2670
2671 // fold (and x, -1) -> x, vector edition
2672 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2673 return N1;
2674 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2675 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002676 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002677
Dan Gohman06563a82007-07-03 14:03:57 +00002678 // fold (and x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002679 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002680 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00002681 // fold (and c1, c2) -> c1&c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002682 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002683 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002684 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00002685 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002686 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002687 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002688 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002689 return N0;
2690 // if (and x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002691 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002692 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002693 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002694 // reassociate and
Andrew Trickef9de2a2013-05-25 02:42:55 +00002695 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002696 if (RAND.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002697 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002698 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002699 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002700 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002701 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002702 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002703 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2704 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002705 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002706 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002707 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002708 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002709 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002710 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002711
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002712 // Replace uses of the AND with uses of the Zero extend node.
2713 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002714
Chris Lattner49beaf42006-02-02 07:17:31 +00002715 // We actually want to replace all uses of the any_extend with the
2716 // zero_extend, to avoid duplicating things. This will later cause this
2717 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002718 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002719 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002720 }
2721 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002722 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002723 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2724 // already be zero by virtue of the width of the base type of the load.
2725 //
2726 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2727 // more cases.
2728 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2729 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2730 N0.getOpcode() == ISD::LOAD) {
2731 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2732 N0 : N0.getOperand(0) );
2733
2734 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2735 // This can be a pure constant or a vector splat, in which case we treat the
2736 // vector as a scalar and use the splat value.
2737 APInt Constant = APInt::getNullValue(1);
2738 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2739 Constant = C->getAPIntValue();
2740 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2741 APInt SplatValue, SplatUndef;
2742 unsigned SplatBitSize;
2743 bool HasAnyUndefs;
2744 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2745 SplatBitSize, HasAnyUndefs);
2746 if (IsSplat) {
2747 // Undef bits can contribute to a possible optimisation if set, so
2748 // set them.
2749 SplatValue |= SplatUndef;
2750
2751 // The splat value may be something like "0x00FFFFFF", which means 0 for
2752 // the first vector value and FF for the rest, repeating. We need a mask
2753 // that will apply equally to all members of the vector, so AND all the
2754 // lanes of the constant together.
2755 EVT VT = Vector->getValueType(0);
2756 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002757
2758 // If the splat value has been compressed to a bitlength lower
2759 // than the size of the vector lane, we need to re-expand it to
2760 // the lane size.
2761 if (BitWidth > SplatBitSize)
2762 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2763 SplatBitSize < BitWidth;
2764 SplatBitSize = SplatBitSize * 2)
2765 SplatValue |= SplatValue.shl(SplatBitSize);
2766
James Molloy862fe492012-02-20 12:02:38 +00002767 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3f40d872012-09-05 08:57:21 +00002768 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy862fe492012-02-20 12:02:38 +00002769 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2770 }
2771 }
2772
2773 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2774 // actually legal and isn't going to get expanded, else this is a false
2775 // optimisation.
2776 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2777 Load->getMemoryVT());
2778
2779 // Resize the constant to the same size as the original memory access before
2780 // extension. If it is still the AllOnesValue then this AND is completely
2781 // unneeded.
2782 Constant =
2783 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2784
2785 bool B;
2786 switch (Load->getExtensionType()) {
2787 default: B = false; break;
2788 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2789 case ISD::ZEXTLOAD:
2790 case ISD::NON_EXTLOAD: B = true; break;
2791 }
2792
2793 if (B && Constant.isAllOnesValue()) {
2794 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2795 // preserve semantics once we get rid of the AND.
2796 SDValue NewLoad(Load, 0);
2797 if (Load->getExtensionType() == ISD::EXTLOAD) {
2798 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002799 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002800 Load->getChain(), Load->getBasePtr(),
2801 Load->getOffset(), Load->getMemoryVT(),
2802 Load->getMemOperand());
2803 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002804 if (Load->getNumValues() == 3) {
2805 // PRE/POST_INC loads have 3 values.
2806 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2807 NewLoad.getValue(2) };
2808 CombineTo(Load, To, 3, true);
2809 } else {
2810 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2811 }
James Molloy862fe492012-02-20 12:02:38 +00002812 }
2813
2814 // Fold the AND away, taking care not to fold to the old load node if we
2815 // replaced it.
2816 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2817
2818 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2819 }
2820 }
Nate Begeman049b7482005-09-09 19:49:52 +00002821 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2822 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2823 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2824 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002825
Tom Stellard7783b0a2014-06-12 16:04:47 +00002826 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002827 LL.getValueType().isInteger()) {
Bill Wendling86171912009-01-30 20:43:18 +00002828 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002829 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002830 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002831 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002832 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002833 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002834 }
Bill Wendling86171912009-01-30 20:43:18 +00002835 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002836 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002837 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002838 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002839 AddToWorklist(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002840 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002841 }
Bill Wendling86171912009-01-30 20:43:18 +00002842 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002843 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002844 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002845 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002846 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002847 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002848 }
2849 }
Jim Grosbach327ccc72013-08-13 21:30:58 +00002850 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2851 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2852 Op0 == Op1 && LL.getValueType().isInteger() &&
2853 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2854 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2855 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2856 cast<ConstantSDNode>(RR)->isNullValue()))) {
2857 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2858 LL, DAG.getConstant(1, LL.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002859 AddToWorklist(ADDNode.getNode());
Jim Grosbach327ccc72013-08-13 21:30:58 +00002860 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2861 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2862 }
Nate Begeman049b7482005-09-09 19:49:52 +00002863 // canonicalize equivalent to ll == rl
2864 if (LL == RR && LR == RL) {
2865 Op1 = ISD::getSetCCSwappedOperands(Op1);
2866 std::swap(RL, RR);
2867 }
2868 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00002869 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00002870 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00002871 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002872 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00002873 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2874 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00002875 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002876 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling86171912009-01-30 20:43:18 +00002877 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00002878 }
2879 }
Chris Lattner8d6fc202006-05-05 05:51:50 +00002880
Bill Wendling86171912009-01-30 20:43:18 +00002881 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00002882 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002883 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002884 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00002885 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002886
Nate Begemandc7bba92006-02-03 22:24:05 +00002887 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2888 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands13237ac2008-06-06 12:08:01 +00002889 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002890 SimplifyDemandedBits(SDValue(N, 0)))
2891 return SDValue(N, 0);
Evan Cheng166a4e62010-01-06 19:38:29 +00002892
Nate Begeman02b23c62005-10-13 03:11:28 +00002893 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greiff304a7a2008-08-28 21:40:38 +00002894 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002895 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002896 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002897 // If we zero all the possible extended bits, then we can turn this into
2898 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002899 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002900 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002901 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002902 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002903 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002904 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling86171912009-01-30 20:43:18 +00002905 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002906 MemVT, LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002907 AddToWorklist(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002908 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002909 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002910 }
2911 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002912 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00002913 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00002914 N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002915 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002916 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002917 // If we zero all the possible extended bits, then we can turn this into
2918 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002919 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002920 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002921 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002922 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002923 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002924 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002925 LN0->getChain(), LN0->getBasePtr(),
2926 MemVT, LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002927 AddToWorklist(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002928 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002929 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002930 }
2931 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002932
Chris Lattnerf0032b32006-02-28 06:49:37 +00002933 // fold (and (load x), 255) -> (zextload x, i8)
2934 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002935 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2936 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2937 (N0.getOpcode() == ISD::ANY_EXTEND &&
2938 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2939 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2940 LoadSDNode *LN0 = HasAnyExt
2941 ? cast<LoadSDNode>(N0.getOperand(0))
2942 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002943 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002944 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002945 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002946 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2947 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2948 EVT LoadedVT = LN0->getMemoryVT();
Duncan Sands93b66092008-06-09 11:32:28 +00002949
Evan Cheng166a4e62010-01-06 19:38:29 +00002950 if (ExtVT == LoadedVT &&
2951 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00002952 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Wesley Peck527da1b2010-11-23 03:31:01 +00002953
2954 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002955 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002956 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2957 LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002958 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00002959 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2960 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2961 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002962
Chris Lattner88de3842010-01-07 21:53:27 +00002963 // Do not change the width of a volatile load.
2964 // Do not generate loads of non-round integer types since these can
2965 // be expensive (and would be wrong if the type is not byte sized).
2966 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2967 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2968 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00002969
Chris Lattner88de3842010-01-07 21:53:27 +00002970 unsigned Alignment = LN0->getAlignment();
2971 SDValue NewPtr = LN0->getBasePtr();
2972
2973 // For big endian targets, we need to add an offset to the pointer
2974 // to load the correct bytes. For little endian systems, we merely
2975 // need to read fewer bytes from the same pointer.
2976 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00002977 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2978 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2979 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002980 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00002981 NewPtr, DAG.getConstant(PtrOff, PtrType));
2982 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00002983 }
Chris Lattner88de3842010-01-07 21:53:27 +00002984
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002985 AddToWorklist(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00002986
Chris Lattner88de3842010-01-07 21:53:27 +00002987 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2988 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002989 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00002990 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00002991 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00002992 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00002993 LN0->isInvariant(), Alignment, LN0->getAAInfo());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002994 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00002995 CombineTo(LN0, Load, Load.getValue(1));
2996 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00002997 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00002998 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00002999 }
3000 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003001
Evan Chenge6a3b032012-07-17 18:54:11 +00003002 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3003 VT.getSizeInBits() <= 64) {
3004 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3005 APInt ADDC = ADDI->getAPIntValue();
3006 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3007 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3008 // immediate for an add, but it is legal if its top c2 bits are set,
3009 // transform the ADD so the immediate doesn't need to be materialized
3010 // in a register.
3011 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3012 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3013 SRLI->getZExtValue());
3014 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3015 ADDC |= Mask;
3016 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3017 SDValue NewAdd =
Andrew Trickef9de2a2013-05-25 02:42:55 +00003018 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenge6a3b032012-07-17 18:54:11 +00003019 N0.getOperand(0), DAG.getConstant(ADDC, VT));
3020 CombineTo(N0.getNode(), NewAdd);
3021 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3022 }
3023 }
3024 }
3025 }
3026 }
3027 }
Evan Chenge6a3b032012-07-17 18:54:11 +00003028
Tim Northover819bfb52013-08-27 13:46:45 +00003029 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3030 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3031 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3032 N0.getOperand(1), false);
3033 if (BSwap.getNode())
3034 return BSwap;
3035 }
3036
Evan Chengf1005572010-04-28 07:10:39 +00003037 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003038}
3039
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003040/// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003041SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3042 bool DemandHighBits) {
3043 if (!LegalOperations)
3044 return SDValue();
3045
3046 EVT VT = N->getValueType(0);
3047 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3048 return SDValue();
3049 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3050 return SDValue();
3051
3052 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3053 bool LookPassAnd0 = false;
3054 bool LookPassAnd1 = false;
3055 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3056 std::swap(N0, N1);
3057 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3058 std::swap(N0, N1);
3059 if (N0.getOpcode() == ISD::AND) {
3060 if (!N0.getNode()->hasOneUse())
3061 return SDValue();
3062 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3063 if (!N01C || N01C->getZExtValue() != 0xFF00)
3064 return SDValue();
3065 N0 = N0.getOperand(0);
3066 LookPassAnd0 = true;
3067 }
3068
3069 if (N1.getOpcode() == ISD::AND) {
3070 if (!N1.getNode()->hasOneUse())
3071 return SDValue();
3072 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3073 if (!N11C || N11C->getZExtValue() != 0xFF)
3074 return SDValue();
3075 N1 = N1.getOperand(0);
3076 LookPassAnd1 = true;
3077 }
3078
3079 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3080 std::swap(N0, N1);
3081 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3082 return SDValue();
3083 if (!N0.getNode()->hasOneUse() ||
3084 !N1.getNode()->hasOneUse())
3085 return SDValue();
3086
3087 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3088 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3089 if (!N01C || !N11C)
3090 return SDValue();
3091 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3092 return SDValue();
3093
3094 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3095 SDValue N00 = N0->getOperand(0);
3096 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3097 if (!N00.getNode()->hasOneUse())
3098 return SDValue();
3099 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3100 if (!N001C || N001C->getZExtValue() != 0xFF)
3101 return SDValue();
3102 N00 = N00.getOperand(0);
3103 LookPassAnd0 = true;
3104 }
3105
3106 SDValue N10 = N1->getOperand(0);
3107 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3108 if (!N10.getNode()->hasOneUse())
3109 return SDValue();
3110 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3111 if (!N101C || N101C->getZExtValue() != 0xFF00)
3112 return SDValue();
3113 N10 = N10.getOperand(0);
3114 LookPassAnd1 = true;
3115 }
3116
3117 if (N00 != N10)
3118 return SDValue();
3119
Tim Northover819bfb52013-08-27 13:46:45 +00003120 // Make sure everything beyond the low halfword gets set to zero since the SRL
3121 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003122 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003123 if (DemandHighBits && OpSizeInBits > 16) {
3124 // If the left-shift isn't masked out then the only way this is a bswap is
3125 // if all bits beyond the low 8 are 0. In that case the entire pattern
3126 // reduces to a left shift anyway: leave it for other parts of the combiner.
3127 if (!LookPassAnd0)
3128 return SDValue();
3129
3130 // However, if the right shift isn't masked out then it might be because
3131 // it's not needed. See if we can spot that too.
3132 if (!LookPassAnd1 &&
3133 !DAG.MaskedValueIsZero(
3134 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3135 return SDValue();
3136 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003137
Andrew Trickef9de2a2013-05-25 02:42:55 +00003138 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003139 if (OpSizeInBits > 16)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003140 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003141 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3142 return Res;
3143}
3144
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003145/// Return true if the specified node is an element that makes up a 32-bit
3146/// packed halfword byteswap.
3147/// ((x & 0x000000ff) << 8) |
3148/// ((x & 0x0000ff00) >> 8) |
3149/// ((x & 0x00ff0000) << 8) |
3150/// ((x & 0xff000000) >> 8)
Craig Topperb94011f2013-07-14 04:42:23 +00003151static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003152 if (!N.getNode()->hasOneUse())
3153 return false;
3154
3155 unsigned Opc = N.getOpcode();
3156 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3157 return false;
3158
3159 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3160 if (!N1C)
3161 return false;
3162
3163 unsigned Num;
3164 switch (N1C->getZExtValue()) {
3165 default:
3166 return false;
3167 case 0xFF: Num = 0; break;
3168 case 0xFF00: Num = 1; break;
3169 case 0xFF0000: Num = 2; break;
3170 case 0xFF000000: Num = 3; break;
3171 }
3172
3173 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3174 SDValue N0 = N.getOperand(0);
3175 if (Opc == ISD::AND) {
3176 if (Num == 0 || Num == 2) {
3177 // (x >> 8) & 0xff
3178 // (x >> 8) & 0xff0000
3179 if (N0.getOpcode() != ISD::SRL)
3180 return false;
3181 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3182 if (!C || C->getZExtValue() != 8)
3183 return false;
3184 } else {
3185 // (x << 8) & 0xff00
3186 // (x << 8) & 0xff000000
3187 if (N0.getOpcode() != ISD::SHL)
3188 return false;
3189 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3190 if (!C || C->getZExtValue() != 8)
3191 return false;
3192 }
3193 } else if (Opc == ISD::SHL) {
3194 // (x & 0xff) << 8
3195 // (x & 0xff0000) << 8
3196 if (Num != 0 && Num != 2)
3197 return false;
3198 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3199 if (!C || C->getZExtValue() != 8)
3200 return false;
3201 } else { // Opc == ISD::SRL
3202 // (x & 0xff00) >> 8
3203 // (x & 0xff000000) >> 8
3204 if (Num != 1 && Num != 3)
3205 return false;
3206 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3207 if (!C || C->getZExtValue() != 8)
3208 return false;
3209 }
3210
3211 if (Parts[Num])
3212 return false;
3213
3214 Parts[Num] = N0.getOperand(0).getNode();
3215 return true;
3216}
3217
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003218/// Match a 32-bit packed halfword bswap. That is
3219/// ((x & 0x000000ff) << 8) |
3220/// ((x & 0x0000ff00) >> 8) |
3221/// ((x & 0x00ff0000) << 8) |
3222/// ((x & 0xff000000) >> 8)
Evan Cheng4c0bd962011-06-21 06:01:08 +00003223/// => (rotl (bswap x), 16)
3224SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3225 if (!LegalOperations)
3226 return SDValue();
3227
3228 EVT VT = N->getValueType(0);
3229 if (VT != MVT::i32)
3230 return SDValue();
3231 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3232 return SDValue();
3233
Craig Topperc0196b12014-04-14 00:51:57 +00003234 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003235 // Look for either
3236 // (or (or (and), (and)), (or (and), (and)))
3237 // (or (or (or (and), (and)), (and)), (and))
3238 if (N0.getOpcode() != ISD::OR)
3239 return SDValue();
3240 SDValue N00 = N0.getOperand(0);
3241 SDValue N01 = N0.getOperand(1);
3242
Evan Chengbf0baa92012-12-13 01:34:32 +00003243 if (N1.getOpcode() == ISD::OR &&
3244 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003245 // (or (or (and), (and)), (or (and), (and)))
3246 SDValue N000 = N00.getOperand(0);
3247 if (!isBSwapHWordElement(N000, Parts))
3248 return SDValue();
3249
3250 SDValue N001 = N00.getOperand(1);
3251 if (!isBSwapHWordElement(N001, Parts))
3252 return SDValue();
3253 SDValue N010 = N01.getOperand(0);
3254 if (!isBSwapHWordElement(N010, Parts))
3255 return SDValue();
3256 SDValue N011 = N01.getOperand(1);
3257 if (!isBSwapHWordElement(N011, Parts))
3258 return SDValue();
3259 } else {
3260 // (or (or (or (and), (and)), (and)), (and))
3261 if (!isBSwapHWordElement(N1, Parts))
3262 return SDValue();
3263 if (!isBSwapHWordElement(N01, Parts))
3264 return SDValue();
3265 if (N00.getOpcode() != ISD::OR)
3266 return SDValue();
3267 SDValue N000 = N00.getOperand(0);
3268 if (!isBSwapHWordElement(N000, Parts))
3269 return SDValue();
3270 SDValue N001 = N00.getOperand(1);
3271 if (!isBSwapHWordElement(N001, Parts))
3272 return SDValue();
3273 }
3274
3275 // Make sure the parts are all coming from the same node.
3276 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3277 return SDValue();
3278
Andrew Trickef9de2a2013-05-25 02:42:55 +00003279 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003280 SDValue(Parts[0],0));
3281
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003282 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003283 // do (x << 16) | (x >> 16).
3284 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3285 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003286 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003287 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003288 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3289 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3290 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3291 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003292}
3293
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003294SDValue DAGCombiner::visitOR(SDNode *N) {
3295 SDValue N0 = N->getOperand(0);
3296 SDValue N1 = N->getOperand(1);
3297 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003298 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3299 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003300 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003301
Dan Gohmana8665142007-06-25 16:23:39 +00003302 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003303 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003304 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003305 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003306
3307 // fold (or x, 0) -> x, vector edition
3308 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3309 return N1;
3310 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3311 return N0;
3312
3313 // fold (or x, -1) -> -1, vector edition
3314 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3315 return N0;
3316 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3317 return N1;
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003318
3319 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3320 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3321 // Do this only if the resulting shuffle is legal.
3322 if (isa<ShuffleVectorSDNode>(N0) &&
3323 isa<ShuffleVectorSDNode>(N1) &&
Andrea Di Biagio2152a6c2014-07-15 00:02:32 +00003324 // Avoid folding a node with illegal type.
3325 TLI.isTypeLegal(VT) &&
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003326 N0->getOperand(1) == N1->getOperand(1) &&
3327 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3328 bool CanFold = true;
3329 unsigned NumElts = VT.getVectorNumElements();
3330 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3331 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3332 // We construct two shuffle masks:
3333 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3334 // and N1 as the second operand.
3335 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3336 // and N0 as the second operand.
3337 // We do this because OR is commutable and therefore there might be
3338 // two ways to fold this node into a shuffle.
3339 SmallVector<int,4> Mask1;
3340 SmallVector<int,4> Mask2;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003341
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003342 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3343 int M0 = SV0->getMaskElt(i);
3344 int M1 = SV1->getMaskElt(i);
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003345
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003346 // Both shuffle indexes are undef. Propagate Undef.
3347 if (M0 < 0 && M1 < 0) {
3348 Mask1.push_back(M0);
3349 Mask2.push_back(M0);
3350 continue;
3351 }
3352
3353 if (M0 < 0 || M1 < 0 ||
3354 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3355 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3356 CanFold = false;
3357 break;
3358 }
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003359
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003360 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3361 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3362 }
3363
3364 if (CanFold) {
3365 // Fold this sequence only if the resulting shuffle is 'legal'.
3366 if (TLI.isShuffleMaskLegal(Mask1, VT))
3367 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3368 N1->getOperand(0), &Mask1[0]);
3369 if (TLI.isShuffleMaskLegal(Mask2, VT))
3370 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3371 N0->getOperand(0), &Mask2[0]);
3372 }
3373 }
Dan Gohman80f9f072007-07-13 20:03:40 +00003374 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003375
Dan Gohman06563a82007-07-03 14:03:57 +00003376 // fold (or x, undef) -> -1
Bob Wilson269a89f2010-06-28 23:40:25 +00003377 if (!LegalOperations &&
3378 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman9655f842009-12-03 07:11:29 +00003379 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3380 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3381 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003382 // fold (or c1, c2) -> c1|c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003383 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003384 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003385 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003386 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003387 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003388 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003389 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003390 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003391 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003392 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003393 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003394 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003395 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003396 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003397
3398 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3399 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003400 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003401 return BSwap;
3402 BSwap = MatchBSwapHWordLow(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003403 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003404 return BSwap;
3405
Nate Begeman22e251a2006-02-03 06:46:56 +00003406 // reassociate or
Andrew Trickef9de2a2013-05-25 02:42:55 +00003407 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003408 if (ROR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003409 return ROR;
3410 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003411 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003412 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003413 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003414 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003415 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3416 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3417 if (!COR.getNode())
3418 return SDValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00003419 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3420 DAG.getNode(ISD::OR, SDLoc(N0), VT,
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003421 N0.getOperand(0), N1), COR);
3422 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003423 }
Nate Begeman049b7482005-09-09 19:49:52 +00003424 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3425 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3426 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3427 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003428
Nate Begeman049b7482005-09-09 19:49:52 +00003429 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00003430 LL.getValueType().isInteger()) {
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003431 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3432 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003433 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003434 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003435 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003436 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003437 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003438 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003439 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003440 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3441 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003442 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003443 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003444 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003445 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003446 AddToWorklist(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003447 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003448 }
3449 }
3450 // canonicalize equivalent to ll == rl
3451 if (LL == RR && LR == RL) {
3452 Op1 = ISD::getSetCCSwappedOperands(Op1);
3453 std::swap(RL, RR);
3454 }
3455 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003456 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00003457 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00003458 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003459 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00003460 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3461 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00003462 getSetCCResultType(N0.getValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003463 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003464 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00003465 }
3466 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003467
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003468 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003469 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003470 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003471 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003472 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003473
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003474 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner46d710e2006-09-14 21:11:37 +00003475 if (N0.getOpcode() == ISD::AND &&
3476 N1.getOpcode() == ISD::AND &&
3477 N0.getOperand(1).getOpcode() == ISD::Constant &&
3478 N1.getOperand(1).getOpcode() == ISD::Constant &&
3479 // Don't increase # computations.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003480 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner46d710e2006-09-14 21:11:37 +00003481 // We can only do this xform if we know that bits from X that are set in C2
3482 // but not in C1 are already zero. Likewise for Y.
Dan Gohman1f372ed2008-02-25 21:11:39 +00003483 const APInt &LHSMask =
3484 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3485 const APInt &RHSMask =
3486 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003487
Dan Gohman309d3d52007-06-22 14:59:07 +00003488 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3489 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003490 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003491 N0.getOperand(0), N1.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003492 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003493 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner46d710e2006-09-14 21:11:37 +00003494 }
3495 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003496
Chris Lattner97614c82006-09-14 20:50:57 +00003497 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003498 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003499 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003500
Dan Gohman600f62b2010-06-24 14:30:44 +00003501 // Simplify the operands using demanded-bits information.
3502 if (!VT.isVector() &&
3503 SimplifyDemandedBits(SDValue(N, 0)))
3504 return SDValue(N, 0);
3505
Evan Chengf1005572010-04-28 07:10:39 +00003506 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003507}
3508
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003509/// Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003510static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003511 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003512 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003513 Mask = Op.getOperand(1);
3514 Op = Op.getOperand(0);
3515 } else {
3516 return false;
3517 }
3518 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003519
Chris Lattner97614c82006-09-14 20:50:57 +00003520 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3521 Shift = Op;
3522 return true;
3523 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003524
Scott Michelcf0da6c2009-02-17 22:15:04 +00003525 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003526}
3527
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003528// Return true if we can prove that, whenever Neg and Pos are both in the
3529// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003530// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3531//
3532// (or (shift1 X, Neg), (shift2 X, Pos))
3533//
Adam Nemetc6553a82014-03-07 23:56:24 +00003534// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3535// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3536// to consider shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003537static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003538 // If OpSize is a power of 2 then:
3539 //
3540 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3541 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3542 //
3543 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3544 // for the stronger condition:
3545 //
3546 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3547 //
3548 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3549 // we can just replace Neg with Neg' for the rest of the function.
3550 //
3551 // In other cases we check for the even stronger condition:
3552 //
3553 // Neg == OpSize - Pos [B]
3554 //
3555 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3556 // behavior if Pos == 0 (and consequently Neg == OpSize).
Adam Nemetc6553a82014-03-07 23:56:24 +00003557 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003558 // We could actually use [A] whenever OpSize is a power of 2, but the
3559 // only extra cases that it would match are those uninteresting ones
3560 // where Neg and Pos are never in range at the same time. E.g. for
3561 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3562 // as well as (sub 32, Pos), but:
3563 //
3564 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3565 //
3566 // always invokes undefined behavior for 32-bit X.
3567 //
3568 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
Adam Nemetc6553a82014-03-07 23:56:24 +00003569 unsigned MaskLoBits = 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003570 if (Neg.getOpcode() == ISD::AND &&
3571 isPowerOf2_64(OpSize) &&
3572 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3573 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3574 Neg = Neg.getOperand(0);
Adam Nemetc6553a82014-03-07 23:56:24 +00003575 MaskLoBits = Log2_64(OpSize);
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003576 }
3577
Richard Sandiford0f264db2014-01-09 10:49:40 +00003578 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3579 if (Neg.getOpcode() != ISD::SUB)
3580 return 0;
3581 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3582 if (!NegC)
3583 return 0;
3584 SDValue NegOp1 = Neg.getOperand(1);
3585
Adam Nemet5117f5d2014-03-07 23:56:28 +00003586 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3587 // Pos'. The truncation is redundant for the purpose of the equality.
3588 if (MaskLoBits &&
3589 Pos.getOpcode() == ISD::AND &&
3590 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3591 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3592 Pos = Pos.getOperand(0);
3593
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003594 // The condition we need is now:
3595 //
3596 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3597 //
3598 // If NegOp1 == Pos then we need:
3599 //
3600 // OpSize & Mask == NegC & Mask
3601 //
3602 // (because "x & Mask" is a truncation and distributes through subtraction).
3603 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003604 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003605 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003606 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3607 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003608 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003609 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3610 //
3611 // which, again because "x & Mask" is a truncation, becomes:
3612 //
3613 // NegC & Mask == (OpSize - PosC) & Mask
3614 // OpSize & Mask == (NegC + PosC) & Mask
3615 else if (Pos.getOpcode() == ISD::ADD &&
3616 Pos.getOperand(0) == NegOp1 &&
3617 Pos.getOperand(1).getOpcode() == ISD::Constant)
3618 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3619 NegC->getAPIntValue());
3620 else
3621 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003622
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003623 // Now we just need to check that OpSize & Mask == Width & Mask.
Adam Nemetc6553a82014-03-07 23:56:24 +00003624 if (MaskLoBits)
3625 // Opsize & Mask is 0 since Mask is Opsize - 1.
3626 return Width.getLoBits(MaskLoBits) == 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003627 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003628}
3629
Richard Sandiford95c864d2014-01-08 15:40:47 +00003630// A subroutine of MatchRotate used once we have found an OR of two opposite
3631// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3632// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3633// former being preferred if supported. InnerPos and InnerNeg are Pos and
3634// Neg with outer conversions stripped away.
3635SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3636 SDValue Neg, SDValue InnerPos,
3637 SDValue InnerNeg, unsigned PosOpcode,
3638 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003639 // fold (or (shl x, (*ext y)),
3640 // (srl x, (*ext (sub 32, y)))) ->
3641 // (rotl x, y) or (rotr x, (sub 32, y))
3642 //
3643 // fold (or (shl x, (*ext (sub 32, y))),
3644 // (srl x, (*ext y))) ->
3645 // (rotr x, y) or (rotl x, (sub 32, y))
3646 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003647 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003648 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3649 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3650 HasPos ? Pos : Neg).getNode();
3651 }
3652
Craig Topperc0196b12014-04-14 00:51:57 +00003653 return nullptr;
Richard Sandiford95c864d2014-01-08 15:40:47 +00003654}
3655
Chris Lattner97614c82006-09-14 20:50:57 +00003656// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3657// idioms for rotate, and if the target supports rotation instructions, generate
3658// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003659SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003660 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003661 EVT VT = LHS.getValueType();
Craig Topperc0196b12014-04-14 00:51:57 +00003662 if (!TLI.isTypeLegal(VT)) return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003663
3664 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003665 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3666 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Craig Topperc0196b12014-04-14 00:51:57 +00003667 if (!HasROTL && !HasROTR) return nullptr;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003668
Chris Lattner97614c82006-09-14 20:50:57 +00003669 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003670 SDValue LHSShift; // The shift.
3671 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003672 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003673 return nullptr; // Not part of a rotate.
Chris Lattner97614c82006-09-14 20:50:57 +00003674
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003675 SDValue RHSShift; // The shift.
3676 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003677 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003678 return nullptr; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003679
Chris Lattner97614c82006-09-14 20:50:57 +00003680 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
Craig Topperc0196b12014-04-14 00:51:57 +00003681 return nullptr; // Not shifting the same value.
Chris Lattner97614c82006-09-14 20:50:57 +00003682
3683 if (LHSShift.getOpcode() == RHSShift.getOpcode())
Craig Topperc0196b12014-04-14 00:51:57 +00003684 return nullptr; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003685
Chris Lattner97614c82006-09-14 20:50:57 +00003686 // Canonicalize shl to left side in a shl/srl pair.
3687 if (RHSShift.getOpcode() == ISD::SHL) {
3688 std::swap(LHS, RHS);
3689 std::swap(LHSShift, RHSShift);
3690 std::swap(LHSMask , RHSMask );
3691 }
3692
Duncan Sands13237ac2008-06-06 12:08:01 +00003693 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003694 SDValue LHSShiftArg = LHSShift.getOperand(0);
3695 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003696 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003697 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003698
3699 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3700 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003701 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3702 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003703 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3704 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003705 if ((LShVal + RShVal) != OpSizeInBits)
Craig Topperc0196b12014-04-14 00:51:57 +00003706 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003707
Craig Topper65161fa2012-09-29 06:54:22 +00003708 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3709 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003710
Chris Lattner97614c82006-09-14 20:50:57 +00003711 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003712 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003713 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003714
Gabor Greiff304a7a2008-08-28 21:40:38 +00003715 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003716 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3717 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003718 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003719 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003720 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3721 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003722 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003723
Bill Wendling35972a92009-01-30 21:14:50 +00003724 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003725 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003726
Gabor Greiff304a7a2008-08-28 21:40:38 +00003727 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003728 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003729
Chris Lattner97614c82006-09-14 20:50:57 +00003730 // If there is a mask here, and we have a variable shift, we can't be sure
3731 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003732 if (LHSMask.getNode() || RHSMask.getNode())
Craig Topperc0196b12014-04-14 00:51:57 +00003733 return nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003734
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003735 // If the shift amount is sign/zext/any-extended just peel it off.
3736 SDValue LExtOp0 = LHSShiftAmt;
3737 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003738 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3739 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3740 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3741 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3742 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3743 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3744 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3745 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003746 LExtOp0 = LHSShiftAmt.getOperand(0);
3747 RExtOp0 = RHSShiftAmt.getOperand(0);
3748 }
3749
Richard Sandiford95c864d2014-01-08 15:40:47 +00003750 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3751 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3752 if (TryL)
3753 return TryL;
3754
3755 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3756 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3757 if (TryR)
3758 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003759
Craig Topperc0196b12014-04-14 00:51:57 +00003760 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003761}
3762
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003763SDValue DAGCombiner::visitXOR(SDNode *N) {
3764 SDValue N0 = N->getOperand(0);
3765 SDValue N1 = N->getOperand(1);
3766 SDValue LHS, RHS, CC;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003767 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3768 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003769 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003770
Dan Gohmana8665142007-06-25 16:23:39 +00003771 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003772 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003773 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003774 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003775
3776 // fold (xor x, 0) -> x, vector edition
3777 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3778 return N1;
3779 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3780 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003781 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003782
Evan Chengdf1690d2008-03-25 20:08:07 +00003783 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3784 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3785 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003786 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003787 if (N0.getOpcode() == ISD::UNDEF)
3788 return N0;
3789 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003790 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003791 // fold (xor c1, c2) -> c1^c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003792 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003793 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003794 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003795 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003796 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003797 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003798 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003799 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003800 // reassociate xor
Andrew Trickef9de2a2013-05-25 02:42:55 +00003801 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003802 if (RXOR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003803 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003804
Nate Begeman21158fc2005-09-01 00:19:25 +00003805 // fold !(x cc y) -> (x !cc y)
Dan Gohmanb72127a2008-03-13 22:13:53 +00003806 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003807 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003808 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3809 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003810
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003811 if (!LegalOperations ||
3812 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003813 switch (N0.getOpcode()) {
3814 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003815 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003816 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003817 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003818 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003819 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003820 N0.getOperand(3), NotCC);
3821 }
3822 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003823 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003824
Chris Lattner58c227b2007-09-10 21:39:07 +00003825 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003826 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003827 N0.getNode()->hasOneUse() &&
3828 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003829 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003830 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003831 DAG.getConstant(1, V.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003832 AddToWorklist(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003833 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003834 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003835
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003836 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003837 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003838 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003839 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003840 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3841 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003842 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3843 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003844 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003845 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003846 }
3847 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003848 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003849 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003850 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003851 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003852 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3853 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003854 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3855 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003856 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003857 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003858 }
3859 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003860 // fold (xor (and x, y), y) -> (and (not x), y)
3861 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003862 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003863 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003864 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003865 AddToWorklist(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003866 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003867 }
Bill Wendling35972a92009-01-30 21:14:50 +00003868 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003869 if (N1C && N0.getOpcode() == ISD::XOR) {
3870 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3871 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3872 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003873 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003874 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003875 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003876 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003877 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003878 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003879 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003880 }
3881 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003882 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003883 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003884
Chris Lattner8d6fc202006-05-05 05:51:50 +00003885 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3886 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003887 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003888 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003889 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003890
Chris Lattner098c01e2006-04-08 04:15:24 +00003891 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00003892 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003893 SimplifyDemandedBits(SDValue(N, 0)))
3894 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003895
Evan Chengf1005572010-04-28 07:10:39 +00003896 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003897}
3898
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003899/// Handle transforms common to the three shifts, when the shift amount is a
3900/// constant.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003901SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003902 // We can't and shouldn't fold opaque constants.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003903 if (Amt->isOpaque())
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003904 return SDValue();
3905
Gabor Greiff304a7a2008-08-28 21:40:38 +00003906 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003907 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003908
Chris Lattner7c709a52007-12-06 07:33:36 +00003909 // We want to pull some binops through shifts, so that we have (and (shift))
3910 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3911 // thing happens with address calculations, so it's important to canonicalize
3912 // it.
3913 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00003914
Chris Lattner7c709a52007-12-06 07:33:36 +00003915 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003916 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003917 case ISD::OR:
3918 case ISD::XOR:
3919 HighBitSet = false; // We can only transform sra if the high bit is clear.
3920 break;
3921 case ISD::AND:
3922 HighBitSet = true; // We can only transform sra if the high bit is set.
3923 break;
3924 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00003925 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003926 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00003927 HighBitSet = false; // We can only transform sra if the high bit is clear.
3928 break;
3929 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003930
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003931 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00003932 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003933 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003934
3935 // FIXME: disable this unless the input to the binop is a shift by a constant.
3936 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00003937 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003938 // void foo(int *X, int i) { X[i & 1235] = 1; }
3939 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003940 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003941 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00003942 BinOpLHSVal->getOpcode() != ISD::SRA &&
3943 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3944 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003945 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003946
Owen Anderson53aa7a92009-08-10 22:56:29 +00003947 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003948
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003949 // If this is a signed shift right, and the high bit is modified by the
3950 // logical operation, do not perform the transformation. The highBitSet
3951 // boolean indicates the value of the high bit of the constant which would
3952 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00003953 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003954 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3955 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003956 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003957 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003958
Weiming Zhao7f6daf12014-04-30 21:07:24 +00003959 if (!TLI.isDesirableToCommuteWithShift(LHS))
3960 return SDValue();
3961
Chris Lattner7c709a52007-12-06 07:33:36 +00003962 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003963 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003964 N->getValueType(0),
3965 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003966 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00003967
3968 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00003969 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00003970 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003971 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00003972
3973 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003974 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00003975}
3976
Adam Nemet67483892014-03-04 23:28:31 +00003977SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3978 assert(N->getOpcode() == ISD::TRUNCATE);
3979 assert(N->getOperand(0).getOpcode() == ISD::AND);
3980
3981 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3982 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3983 SDValue N01 = N->getOperand(0).getOperand(1);
3984
Matt Arsenault985b9de2014-03-17 18:58:01 +00003985 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
Adam Nemet67483892014-03-04 23:28:31 +00003986 EVT TruncVT = N->getValueType(0);
3987 SDValue N00 = N->getOperand(0).getOperand(0);
3988 APInt TruncC = N01C->getAPIntValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003989 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
Adam Nemet67483892014-03-04 23:28:31 +00003990
3991 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3992 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3993 DAG.getConstant(TruncC, TruncVT));
3994 }
3995 }
3996
3997 return SDValue();
3998}
Adam Nemet7f928f12014-03-07 23:56:30 +00003999
4000SDValue DAGCombiner::visitRotate(SDNode *N) {
4001 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4002 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4003 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4004 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4005 if (NewOp1.getNode())
4006 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4007 N->getOperand(0), NewOp1);
4008 }
4009 return SDValue();
4010}
4011
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004012SDValue DAGCombiner::visitSHL(SDNode *N) {
4013 SDValue N0 = N->getOperand(0);
4014 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004015 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4016 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004017 EVT VT = N0.getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004018 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004019
Daniel Sandersa1840d22013-11-11 17:23:41 +00004020 // fold vector ops
4021 if (VT.isVector()) {
4022 SDValue FoldedVOp = SimplifyVBinOp(N);
4023 if (FoldedVOp.getNode()) return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00004024
4025 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4026 // If setcc produces all-one true value then:
4027 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004028 if (N1CV && N1CV->isConstant()) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004029 if (N0.getOpcode() == ISD::AND) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004030 SDValue N00 = N0->getOperand(0);
4031 SDValue N01 = N0->getOperand(1);
4032 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004033
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004034 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4035 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4036 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004037 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4038 if (C.getNode())
4039 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4040 }
4041 } else {
4042 N1C = isConstOrConstSplat(N1);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004043 }
4044 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00004045 }
4046
Nate Begeman21158fc2005-09-01 00:19:25 +00004047 // fold (shl c1, c2) -> c1<<c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004048 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004049 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004050 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004051 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004052 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004053 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004054 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004055 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004056 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004057 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004058 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00004059 // fold (shl undef, x) -> 0
4060 if (N0.getOpcode() == ISD::UNDEF)
4061 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004062 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004063 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00004064 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004065 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00004066 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004067 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004068 N1.getOperand(0).getOpcode() == ISD::AND) {
4069 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4070 if (NewOp1.getNode())
4071 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004072 }
4073
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004074 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4075 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004076
4077 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004078 if (N1C && N0.getOpcode() == ISD::SHL) {
4079 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4080 uint64_t c1 = N0C1->getZExtValue();
4081 uint64_t c2 = N1C->getZExtValue();
4082 if (c1 + c2 >= OpSizeInBits)
4083 return DAG.getConstant(0, VT);
4084 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4085 DAG.getConstant(c1 + c2, N1.getValueType()));
4086 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004087 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004088
4089 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4090 // For this to be valid, the second form must not preserve any of the bits
4091 // that are shifted out by the inner shift in the first form. This means
4092 // the outer shift size must be >= the number of bits added by the ext.
4093 // As a corollary, we don't care what kind of ext it is.
4094 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4095 N0.getOpcode() == ISD::ANY_EXTEND ||
4096 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004097 N0.getOperand(0).getOpcode() == ISD::SHL) {
4098 SDValue N0Op0 = N0.getOperand(0);
4099 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4100 uint64_t c1 = N0Op0C1->getZExtValue();
4101 uint64_t c2 = N1C->getZExtValue();
4102 EVT InnerShiftVT = N0Op0.getValueType();
4103 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4104 if (c2 >= OpSizeInBits - InnerShiftSize) {
4105 if (c1 + c2 >= OpSizeInBits)
4106 return DAG.getConstant(0, VT);
4107 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4108 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4109 N0Op0->getOperand(0)),
4110 DAG.getConstant(c1 + c2, N1.getValueType()));
4111 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004112 }
4113 }
4114
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004115 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4116 // Only fold this if the inner zext has no other uses to avoid increasing
4117 // the total number of instructions.
4118 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004119 N0.getOperand(0).getOpcode() == ISD::SRL) {
4120 SDValue N0Op0 = N0.getOperand(0);
4121 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4122 uint64_t c1 = N0Op0C1->getZExtValue();
4123 if (c1 < VT.getScalarSizeInBits()) {
4124 uint64_t c2 = N1C->getZExtValue();
4125 if (c1 == c2) {
4126 SDValue NewOp0 = N0.getOperand(0);
4127 EVT CountVT = NewOp0.getOperand(1).getValueType();
4128 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4129 NewOp0, DAG.getConstant(c2, CountVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004130 AddToWorklist(NewSHL.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004131 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4132 }
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004133 }
4134 }
4135 }
4136
Eli Friedman1877ac92011-06-09 22:14:44 +00004137 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4138 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00004139 // Only fold this if the inner shift has no other uses -- if it does, folding
4140 // this will increase the total number of instructions.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004141 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4142 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4143 uint64_t c1 = N0C1->getZExtValue();
4144 if (c1 < OpSizeInBits) {
4145 uint64_t c2 = N1C->getZExtValue();
4146 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4147 SDValue Shift;
4148 if (c2 > c1) {
4149 Mask = Mask.shl(c2 - c1);
4150 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4151 DAG.getConstant(c2 - c1, N1.getValueType()));
4152 } else {
4153 Mask = Mask.lshr(c1 - c2);
4154 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4155 DAG.getConstant(c1 - c2, N1.getValueType()));
4156 }
4157 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4158 DAG.getConstant(Mask, VT));
Eli Friedman1877ac92011-06-09 22:14:44 +00004159 }
Evan Chenga7bb55e2009-07-21 05:40:15 +00004160 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004161 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004162 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00004163 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004164 unsigned BitSize = VT.getScalarSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004165 SDValue HiBitsMask =
Matt Arsenault985b9de2014-03-17 18:58:01 +00004166 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4167 BitSize - N1C->getZExtValue()), VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004168 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004169 HiBitsMask);
4170 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004171
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004172 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004173 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004174 if (NewSHL.getNode())
4175 return NewSHL;
4176 }
4177
Evan Chengf1005572010-04-28 07:10:39 +00004178 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004179}
4180
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004181SDValue DAGCombiner::visitSRA(SDNode *N) {
4182 SDValue N0 = N->getOperand(0);
4183 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004184 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4185 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004186 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004187 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004188
Daniel Sandersa1840d22013-11-11 17:23:41 +00004189 // fold vector ops
4190 if (VT.isVector()) {
4191 SDValue FoldedVOp = SimplifyVBinOp(N);
4192 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004193
4194 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004195 }
4196
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004197 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004198 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004199 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004200 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004201 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004202 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004203 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004204 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004205 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004206 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004207 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004208 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004209 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004210 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004211 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004212 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4213 // sext_inreg.
4214 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004215 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004216 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4217 if (VT.isVector())
4218 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4219 ExtVT, VT.getVectorNumElements());
4220 if ((!LegalOperations ||
4221 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004222 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004223 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004224 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004225
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004226 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004227 if (N1C && N0.getOpcode() == ISD::SRA) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004228 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004229 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004230 if (Sum >= OpSizeInBits)
4231 Sum = OpSizeInBits - 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004232 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Matt Arsenault985b9de2014-03-17 18:58:01 +00004233 DAG.getConstant(Sum, N1.getValueType()));
Chris Lattner0f8a7272006-02-28 06:23:04 +00004234 }
4235 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004236
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004237 // fold (sra (shl X, m), (sub result_size, n))
4238 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004239 // result_size - n != m.
4240 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004241 // code.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004242 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb8fe91092008-03-19 08:30:06 +00004243 // Get the two constanst of the shifts, CN0 = m, CN = n.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004244 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4245 if (N01C) {
4246 LLVMContext &Ctx = *DAG.getContext();
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004247 // Determine what the truncate's result bitsize and type would be.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004248 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4249
4250 if (VT.isVector())
4251 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4252
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004253 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004254 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004255
Scott Michelcf0da6c2009-02-17 22:15:04 +00004256 // If the shift is not a no-op (in which case this should be just a sign
4257 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004258 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004259 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004260 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004261 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4262 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004263 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004264
Owen Andersonb2c80da2011-02-25 21:41:48 +00004265 SDValue Amt = DAG.getConstant(ShiftAmt,
4266 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004267 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004268 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004269 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004270 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004271 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004272 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004273 }
4274 }
4275 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004276
Duncan Sands3ed76882009-02-01 18:06:53 +00004277 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004278 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004279 N1.getOperand(0).getOpcode() == ISD::AND) {
4280 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4281 if (NewOp1.getNode())
4282 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004283 }
4284
Matt Arsenault985b9de2014-03-17 18:58:01 +00004285 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer946e1522011-01-30 16:38:43 +00004286 // if c1 is equal to the number of bits the trunc removes
4287 if (N0.getOpcode() == ISD::TRUNCATE &&
4288 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4289 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4290 N0.getOperand(0).hasOneUse() &&
4291 N0.getOperand(0).getOperand(1).hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004292 N1C) {
4293 SDValue N0Op0 = N0.getOperand(0);
4294 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4295 unsigned LargeShiftVal = LargeShift->getZExtValue();
4296 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer946e1522011-01-30 16:38:43 +00004297
Matt Arsenault985b9de2014-03-17 18:58:01 +00004298 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4299 SDValue Amt =
4300 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4301 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4302 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4303 N0Op0.getOperand(0), Amt);
4304 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4305 }
Benjamin Kramer946e1522011-01-30 16:38:43 +00004306 }
4307 }
4308
Scott Michelcf0da6c2009-02-17 22:15:04 +00004309 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004310 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4311 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004312
4313
Nate Begeman21158fc2005-09-01 00:19:25 +00004314 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004315 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004316 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004317
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004318 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004319 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004320 if (NewSRA.getNode())
4321 return NewSRA;
4322 }
4323
Evan Chengf1005572010-04-28 07:10:39 +00004324 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004325}
4326
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004327SDValue DAGCombiner::visitSRL(SDNode *N) {
4328 SDValue N0 = N->getOperand(0);
4329 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004330 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4331 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004332 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004333 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004334
Daniel Sandersa1840d22013-11-11 17:23:41 +00004335 // fold vector ops
4336 if (VT.isVector()) {
4337 SDValue FoldedVOp = SimplifyVBinOp(N);
4338 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004339
4340 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004341 }
4342
Nate Begeman21158fc2005-09-01 00:19:25 +00004343 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004344 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004345 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004346 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004347 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004348 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004349 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004350 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004351 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004352 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004353 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004354 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004355 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004356 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004357 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004358 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004359
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004360 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004361 if (N1C && N0.getOpcode() == ISD::SRL) {
4362 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4363 uint64_t c1 = N01C->getZExtValue();
4364 uint64_t c2 = N1C->getZExtValue();
4365 if (c1 + c2 >= OpSizeInBits)
4366 return DAG.getConstant(0, VT);
4367 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4368 DAG.getConstant(c1 + c2, N1.getValueType()));
4369 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004370 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004371
Dale Johannesencd538af2010-12-17 21:45:49 +00004372 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004373 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4374 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004375 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004376 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004377 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4378 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004379 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4380 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004381 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004382 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004383 if (c1 + OpSizeInBits == InnerShiftSize) {
4384 if (c1 + c2 >= InnerShiftSize)
4385 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004386 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4387 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004388 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004389 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004390 }
4391 }
4392
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004393 // fold (srl (shl x, c), c) -> (and x, cst2)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004394 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4395 unsigned BitSize = N0.getScalarValueSizeInBits();
4396 if (BitSize <= 64) {
4397 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4398 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4399 DAG.getConstant(~0ULL >> ShAmt, VT));
4400 }
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004401 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004402
Michael Liao62ebfd82013-06-21 18:45:27 +00004403 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004404 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4405 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004406 EVT SmallVT = N0.getOperand(0).getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004407 unsigned BitSize = SmallVT.getScalarSizeInBits();
4408 if (N1C->getZExtValue() >= BitSize)
Dale Johannesen84935752009-02-06 23:05:02 +00004409 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004410
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004411 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004412 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004413 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004414 N0.getOperand(0),
4415 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004416 AddToWorklist(SmallShift.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004417 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Michael Liao62ebfd82013-06-21 18:45:27 +00004418 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4419 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4420 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004421 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004422 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004423
Chris Lattner2e33fb42006-10-12 20:23:19 +00004424 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4425 // bit, which is unmodified by sra.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004426 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004427 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004428 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004429 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004430
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004431 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004432 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004433 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004434 APInt KnownZero, KnownOne;
Jay Foada0653a32014-05-14 21:14:37 +00004435 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004436
Chris Lattner49932492006-04-02 06:11:11 +00004437 // If any of the input bits are KnownOne, then the input couldn't be all
4438 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004439 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004440
Chris Lattner49932492006-04-02 06:11:11 +00004441 // If all of the bits input the to ctlz node are known to be zero, then
4442 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004443 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004444 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004445
Chris Lattner49932492006-04-02 06:11:11 +00004446 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004447 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004448 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004449 // could be set on input to the CTLZ node. If this bit is set, the SRL
4450 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4451 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004452 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004453 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004454
Chris Lattner49932492006-04-02 06:11:11 +00004455 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004456 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004457 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004458 AddToWorklist(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004459 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004460
Andrew Trickef9de2a2013-05-25 02:42:55 +00004461 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004462 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004463 }
4464 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004465
Duncan Sands3ed76882009-02-01 18:06:53 +00004466 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004467 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004468 N1.getOperand(0).getOpcode() == ISD::AND) {
4469 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4470 if (NewOp1.getNode())
4471 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004472 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004473
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004474 // fold operands of srl based on knowledge that the low bits are not
4475 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004476 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4477 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004478
Evan Chengb175de62009-12-18 21:31:31 +00004479 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004480 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Chengb175de62009-12-18 21:31:31 +00004481 if (NewSRL.getNode())
4482 return NewSRL;
4483 }
4484
Dan Gohman600f62b2010-06-24 14:30:44 +00004485 // Attempt to convert a srl of a load into a narrower zero-extending load.
4486 SDValue NarrowLoad = ReduceLoadWidth(N);
4487 if (NarrowLoad.getNode())
4488 return NarrowLoad;
4489
Evan Chengb175de62009-12-18 21:31:31 +00004490 // Here is a common situation. We want to optimize:
4491 //
4492 // %a = ...
4493 // %b = and i32 %a, 2
4494 // %c = srl i32 %b, 1
4495 // brcond i32 %c ...
4496 //
4497 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004498 //
Evan Chengb175de62009-12-18 21:31:31 +00004499 // %a = ...
4500 // %b = and %a, 2
4501 // %c = setcc eq %b, 0
4502 // brcond %c ...
4503 //
4504 // However when after the source operand of SRL is optimized into AND, the SRL
4505 // itself may not be optimized further. Look for it and add the BRCOND into
4506 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004507 if (N->hasOneUse()) {
4508 SDNode *Use = *N->use_begin();
4509 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004510 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004511 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4512 // Also look pass the truncate.
4513 Use = *Use->use_begin();
4514 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004515 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004516 }
4517 }
Evan Chengb175de62009-12-18 21:31:31 +00004518
Evan Chengf1005572010-04-28 07:10:39 +00004519 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004520}
4521
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004522SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4523 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004524 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004525
4526 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004527 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004528 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004529 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004530}
4531
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004532SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4533 SDValue N0 = N->getOperand(0);
4534 EVT VT = N->getValueType(0);
4535
4536 // fold (ctlz_zero_undef c1) -> c2
4537 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004538 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004539 return SDValue();
4540}
4541
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004542SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4543 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004544 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004545
Nate Begeman21158fc2005-09-01 00:19:25 +00004546 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004547 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004548 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004549 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004550}
4551
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004552SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4553 SDValue N0 = N->getOperand(0);
4554 EVT VT = N->getValueType(0);
4555
4556 // fold (cttz_zero_undef c1) -> c2
4557 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004558 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004559 return SDValue();
4560}
4561
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004562SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4563 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004564 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004565
Nate Begeman21158fc2005-09-01 00:19:25 +00004566 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004567 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004568 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004569 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004570}
4571
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004572SDValue DAGCombiner::visitSELECT(SDNode *N) {
4573 SDValue N0 = N->getOperand(0);
4574 SDValue N1 = N->getOperand(1);
4575 SDValue N2 = N->getOperand(2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004576 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4577 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4578 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004579 EVT VT = N->getValueType(0);
4580 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004581
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004582 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004583 if (N1 == N2)
4584 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004585 // fold (select true, X, Y) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004586 if (N0C && !N0C->isNullValue())
4587 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004588 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004589 if (N0C && N0C->isNullValue())
4590 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004591 // fold (select C, 1, X) -> (or C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004592 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004593 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004594 // fold (select C, 0, 1) -> (xor C, 1)
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004595 // We can't do this reliably if integer based booleans have different contents
4596 // to floating point based booleans. This is because we can't tell whether we
4597 // have an integer-based boolean or a floating-point-based boolean unless we
4598 // can find the SETCC that produced it and inspect its operands. This is
4599 // fairly easy if C is the SETCC node, but it can potentially be
4600 // undiscoverable (or not reasonably discoverable). For example, it could be
4601 // in another basic block or it could require searching a complicated
4602 // expression.
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004603 if (VT.isInteger() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004604 (VT0 == MVT::i1 || (VT0.isInteger() &&
4605 TLI.getBooleanContents(false, false) ==
4606 TLI.getBooleanContents(false, true) &&
4607 TLI.getBooleanContents(false, false) ==
4608 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004609 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004610 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004611 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004612 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004613 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004614 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004615 N0, DAG.getConstant(1, VT0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004616 AddToWorklist(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004617 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004618 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4619 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004620 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004621 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004622 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004623 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004624 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004625 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004626 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004627 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004628 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004629 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004630 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004631 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004632 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004633 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004634 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004635 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004636 // fold (select X, X, Y) -> (or X, Y)
4637 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004638 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004639 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004640 // fold (select X, Y, X) -> (and X, Y)
4641 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004642 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004643 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004644
Chris Lattner6c14c352005-10-18 06:04:22 +00004645 // If we can fold this based on the true/false value, do so.
4646 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004647 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004648
Nate Begemanc760f802005-09-19 22:34:01 +00004649 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004650 if (N0.getOpcode() == ISD::SETCC) {
Tom Stellard3787b122014-06-10 16:01:29 +00004651 if ((!LegalOperations &&
4652 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4653 TLI.isOperationLegal(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004654 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004655 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004656 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004657 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004658 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004659
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004660 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004661}
4662
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004663static
4664std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4665 SDLoc DL(N);
4666 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004667 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004668
4669 // Split the inputs.
4670 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004671 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4672 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004673
4674 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4675 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4676
4677 return std::make_pair(Lo, Hi);
4678}
4679
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004680// This function assumes all the vselect's arguments are CONCAT_VECTOR
4681// nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4682static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4683 SDLoc dl(N);
4684 SDValue Cond = N->getOperand(0);
4685 SDValue LHS = N->getOperand(1);
4686 SDValue RHS = N->getOperand(2);
Benjamin Kramerff8b8832014-08-21 13:28:02 +00004687 EVT VT = N->getValueType(0);
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004688 int NumElems = VT.getVectorNumElements();
4689 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4690 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4691 Cond.getOpcode() == ISD::BUILD_VECTOR);
4692
Benjamin Kramerff8b8832014-08-21 13:28:02 +00004693 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4694 // binary ones here.
4695 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4696 return SDValue();
4697
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004698 // We're sure we have an even number of elements due to the
4699 // concat_vectors we have as arguments to vselect.
4700 // Skip BV elements until we find one that's not an UNDEF
4701 // After we find an UNDEF element, keep looping until we get to half the
4702 // length of the BV and see if all the non-undef nodes are the same.
4703 ConstantSDNode *BottomHalf = nullptr;
4704 for (int i = 0; i < NumElems / 2; ++i) {
4705 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4706 continue;
4707
4708 if (BottomHalf == nullptr)
4709 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4710 else if (Cond->getOperand(i).getNode() != BottomHalf)
4711 return SDValue();
4712 }
4713
4714 // Do the same for the second half of the BuildVector
4715 ConstantSDNode *TopHalf = nullptr;
4716 for (int i = NumElems / 2; i < NumElems; ++i) {
4717 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4718 continue;
4719
4720 if (TopHalf == nullptr)
4721 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4722 else if (Cond->getOperand(i).getNode() != TopHalf)
4723 return SDValue();
4724 }
4725
4726 assert(TopHalf && BottomHalf &&
4727 "One half of the selector was all UNDEFs and the other was all the "
4728 "same value. This should have been addressed before this function.");
4729 return DAG.getNode(
4730 ISD::CONCAT_VECTORS, dl, VT,
4731 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4732 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4733}
4734
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004735SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4736 SDValue N0 = N->getOperand(0);
4737 SDValue N1 = N->getOperand(1);
4738 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004739 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004740
4741 // Canonicalize integer abs.
4742 // vselect (setg[te] X, 0), X, -X ->
4743 // vselect (setgt X, -1), X, -X ->
4744 // vselect (setl[te] X, 0), -X, X ->
4745 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4746 if (N0.getOpcode() == ISD::SETCC) {
4747 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4748 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4749 bool isAbs = false;
4750 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4751
4752 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4753 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4754 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4755 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4756 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4757 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4758 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4759
4760 if (isAbs) {
4761 EVT VT = LHS.getValueType();
4762 SDValue Shift = DAG.getNode(
4763 ISD::SRA, DL, VT, LHS,
4764 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4765 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004766 AddToWorklist(Shift.getNode());
4767 AddToWorklist(Add.getNode());
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004768 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4769 }
4770 }
4771
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004772 // If the VSELECT result requires splitting and the mask is provided by a
4773 // SETCC, then split both nodes and its operands before legalization. This
4774 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4775 // and enables future optimizations (e.g. min/max pattern matching on X86).
4776 if (N0.getOpcode() == ISD::SETCC) {
4777 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004778
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004779 // Check if any splitting is required.
4780 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4781 TargetLowering::TypeSplitVector)
4782 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004783
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004784 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004785 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4786 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4787 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004788
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004789 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4790 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004791
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004792 // Add the new VSELECT nodes to the work list in case they need to be split
4793 // again.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004794 AddToWorklist(Lo.getNode());
4795 AddToWorklist(Hi.getNode());
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004796
4797 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004798 }
4799
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00004800 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4801 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4802 return N1;
4803 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4804 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4805 return N2;
4806
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004807 // The ConvertSelectToConcatVector function is assuming both the above
4808 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4809 // and addressed.
4810 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4811 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4812 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4813 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4814 if (CV.getNode())
4815 return CV;
4816 }
4817
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004818 return SDValue();
4819}
4820
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004821SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4822 SDValue N0 = N->getOperand(0);
4823 SDValue N1 = N->getOperand(1);
4824 SDValue N2 = N->getOperand(2);
4825 SDValue N3 = N->getOperand(3);
4826 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00004827 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004828
Nate Begemanc760f802005-09-19 22:34:01 +00004829 // fold select_cc lhs, rhs, x, x, cc -> x
4830 if (N2 == N3)
4831 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00004832
Chris Lattner8b68dec2006-09-20 06:19:26 +00004833 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00004834 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004835 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00004836 if (SCC.getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004837 AddToWorklist(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00004838
Stephen Lin605207f2013-06-15 04:03:33 +00004839 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4840 if (!SCCC->isNullValue())
4841 return N2; // cond always true -> true val
4842 else
4843 return N3; // cond always false -> false val
4844 }
4845
4846 // Fold to a simpler select_cc
4847 if (SCC.getOpcode() == ISD::SETCC)
4848 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4849 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4850 SCC.getOperand(2));
Chris Lattner8b68dec2006-09-20 06:19:26 +00004851 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004852
Chris Lattner6c14c352005-10-18 06:04:22 +00004853 // If we can fold this based on the true/false value, do so.
4854 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004855 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00004856
Nate Begemanc760f802005-09-19 22:34:01 +00004857 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00004858 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004859}
4860
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004861SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00004862 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00004863 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004864 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00004865}
4866
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004867// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4868// dag node into a ConstantSDNode or a build_vector of constants.
4869// This function is called by the DAGCombiner when visiting sext/zext/aext
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00004870// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004871// Vector extends are not folded if operations are legal; this is to
4872// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004873static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4874 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004875 bool LegalOperations) {
4876 unsigned Opcode = N->getOpcode();
4877 SDValue N0 = N->getOperand(0);
4878 EVT VT = N->getValueType(0);
4879
4880 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4881 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4882
4883 // fold (sext c1) -> c1
4884 // fold (zext c1) -> c1
4885 // fold (aext c1) -> c1
4886 if (isa<ConstantSDNode>(N0))
4887 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4888
4889 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4890 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4891 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004892 EVT SVT = VT.getScalarType();
4893 if (!(VT.isVector() &&
4894 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004895 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
Craig Topperc0196b12014-04-14 00:51:57 +00004896 return nullptr;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00004897
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004898 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004899 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004900 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4901 unsigned ShAmt = VTBits - EVTBits;
4902 SmallVector<SDValue, 8> Elts;
4903 unsigned NumElts = N0->getNumOperands();
4904 SDLoc DL(N);
4905
4906 for (unsigned i=0; i != NumElts; ++i) {
4907 SDValue Op = N0->getOperand(i);
4908 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004909 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004910 continue;
4911 }
4912
4913 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4914 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4915 if (Opcode == ISD::SIGN_EXTEND)
4916 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004917 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004918 else
4919 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004920 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004921 }
4922
Craig Topper48d114b2014-04-26 18:35:24 +00004923 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004924}
4925
Evan Chenge106e2f2007-10-29 19:58:20 +00004926// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00004927// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00004928// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00004929// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004930static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00004931 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00004932 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00004933 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004934 bool HasCopyToRegUses = false;
4935 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00004936 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4937 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00004938 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00004939 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00004940 if (User == N)
4941 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00004942 if (UI.getUse().getResNo() != N0.getResNo())
4943 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004944 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00004945 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004946 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4947 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4948 // Sign bits will be lost after a zext.
4949 return false;
4950 bool Add = false;
4951 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004952 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00004953 if (UseOp == N0)
4954 continue;
4955 if (!isa<ConstantSDNode>(UseOp))
4956 return false;
4957 Add = true;
4958 }
4959 if (Add)
4960 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00004961 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004962 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00004963 // If truncates aren't free and there are users we can't
4964 // extend, it isn't worthwhile.
4965 if (!isTruncFree)
4966 return false;
4967 // Remember if this value is live-out.
4968 if (User->getOpcode() == ISD::CopyToReg)
4969 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00004970 }
4971
4972 if (HasCopyToRegUses) {
4973 bool BothLiveOut = false;
4974 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4975 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00004976 SDUse &Use = UI.getUse();
4977 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4978 BothLiveOut = true;
4979 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00004980 }
4981 }
4982 if (BothLiveOut)
4983 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00004984 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00004985 return ExtendNodes.size();
4986 }
4987 return true;
4988}
4989
Craig Toppere0b71182013-07-13 07:43:40 +00004990void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004991 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004992 ISD::NodeType ExtType) {
4993 // Extend SetCC uses if necessary.
4994 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4995 SDNode *SetCC = SetCCs[i];
4996 SmallVector<SDValue, 4> Ops;
4997
4998 for (unsigned j = 0; j != 2; ++j) {
4999 SDValue SOp = SetCC->getOperand(j);
5000 if (SOp == Trunc)
5001 Ops.push_back(ExtLoad);
5002 else
5003 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5004 }
5005
5006 Ops.push_back(SetCC->getOperand(2));
Craig Topper48d114b2014-04-26 18:35:24 +00005007 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005008 }
5009}
5010
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005011SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5012 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005013 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005014
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005015 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5016 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005017 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005018
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005019 // fold (sext (sext x)) -> (sext x)
5020 // fold (sext (aext x)) -> (sext x)
5021 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005022 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005023 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005024
Chris Lattnerfce448f2007-02-26 03:13:59 +00005025 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005026 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5027 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005028 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5029 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005030 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5031 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005032 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005033 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005034 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005035 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00005036 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005037 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005038
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005039 // See if the value being truncated is already sign extended. If so, just
5040 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005041 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005042 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5043 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5044 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00005045 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005046
Chris Lattnerfce448f2007-02-26 03:13:59 +00005047 if (OpBits == DestBits) {
5048 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5049 // bits, it is already ready.
5050 if (NumSignBits > DestBits-MidBits)
5051 return Op;
5052 } else if (OpBits < DestBits) {
5053 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5054 // bits, just sext from i32.
5055 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005056 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00005057 } else {
5058 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5059 // bits, just truncate to i32.
5060 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005061 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00005062 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005063
Chris Lattnerfce448f2007-02-26 03:13:59 +00005064 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005065 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5066 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005067 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005068 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005069 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005070 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5071 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005072 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00005073 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00005074 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005075
Evan Chengbce7c472005-12-14 02:19:23 +00005076 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005077 // None of the supported targets knows how to perform load and sign extend
Nadav Rotemb0091302011-02-27 07:40:43 +00005078 // on vectors in one instruction. We only perform this transformation on
5079 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005080 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005081 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005082 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005083 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005084 bool DoXform = true;
5085 SmallVector<SDNode*, 4> SetCCs;
5086 if (!N0.hasOneUse())
5087 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5088 if (DoXform) {
5089 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005090 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005091 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005092 LN0->getBasePtr(), N0.getValueType(),
5093 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005094 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005095 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005096 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005097 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005098 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005099 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005100 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005101 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005102 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005103
5104 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5105 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005106 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5107 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005108 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005109 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005110 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005111 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005112 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005113 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005114 LN0->getBasePtr(), MemVT,
5115 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00005116 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005117 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005118 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005119 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00005120 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005121 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00005122 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005123 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005124
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005125 // fold (sext (and/or/xor (load x), cst)) ->
5126 // (and/or/xor (sextload x), (sext cst))
5127 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5128 N0.getOpcode() == ISD::XOR) &&
5129 isa<LoadSDNode>(N0.getOperand(0)) &&
5130 N0.getOperand(1).getOpcode() == ISD::Constant &&
5131 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5132 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5133 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005134 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005135 bool DoXform = true;
5136 SmallVector<SDNode*, 4> SetCCs;
5137 if (!N0.hasOneUse())
5138 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5139 SetCCs, TLI);
5140 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005141 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005142 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005143 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005144 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005145 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5146 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005147 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005148 ExtLoad, DAG.getConstant(Mask, VT));
5149 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005150 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005151 N0.getOperand(0).getValueType(), ExtLoad);
5152 CombineTo(N, And);
5153 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005154 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005155 ISD::SIGN_EXTEND);
5156 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5157 }
5158 }
5159 }
5160
Chris Lattner65786b02007-04-11 05:32:27 +00005161 if (N0.getOpcode() == ISD::SETCC) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005162 EVT N0VT = N0.getOperand(0).getValueType();
Chris Lattner4ac60732009-07-08 00:31:33 +00005163 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00005164 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00005165 if (VT.isVector() && !LegalOperations &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005166 TLI.getBooleanContents(N0VT) ==
5167 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Nadav Rotem9d376b62012-04-11 08:26:11 +00005168 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5169 // of the same size as the compared operands. Only optimize sext(setcc())
5170 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00005171 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00005172
5173 // We know that the # elements of the results is the same as the
5174 // # elements of the compare (and the # elements of the compare result
5175 // for that matter). Check to see that they are the same size. If so,
5176 // we know that the element size of the sext'd result matches the
5177 // element size of the compare operands.
5178 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005179 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005180 N0.getOperand(1),
5181 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00005182
Dan Gohmane82c25e2010-04-30 17:19:19 +00005183 // If the desired elements are smaller or larger than the source
5184 // elements we can use a matching integer vector type and then
5185 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00005186 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00005187 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005188 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00005189 N0.getOperand(0), N0.getOperand(1),
5190 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005191 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00005192 }
Chris Lattner4ac60732009-07-08 00:31:33 +00005193 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00005194
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005195 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00005196 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00005197 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00005198 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005199 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005200 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00005201 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005202 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005203 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005204
5205 if (!VT.isVector()) {
5206 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5207 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5208 SDLoc DL(N);
5209 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5210 SDValue SetCC = DAG.getSetCC(DL,
5211 SetCCVT,
5212 N0.getOperand(0), N0.getOperand(1), CC);
5213 EVT SelectVT = getSetCCResultType(VT);
5214 return DAG.getSelect(DL, VT,
5215 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5216 NegOne, DAG.getConstant(0, VT));
5217
5218 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00005219 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005220 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005221
Dan Gohman3eb10f72008-04-28 16:58:24 +00005222 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005223 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00005224 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005225 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005226
Evan Chengf1005572010-04-28 07:10:39 +00005227 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005228}
5229
Rafael Espindola8f62b322012-04-09 16:06:03 +00005230// isTruncateOf - If N is a truncate of some other value, return true, record
5231// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5232// This function computes KnownZero to avoid a duplicated call to
Jay Foada0653a32014-05-14 21:14:37 +00005233// computeKnownBits in the caller.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005234static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5235 APInt &KnownZero) {
5236 APInt KnownOne;
5237 if (N->getOpcode() == ISD::TRUNCATE) {
5238 Op = N->getOperand(0);
Jay Foada0653a32014-05-14 21:14:37 +00005239 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005240 return true;
5241 }
5242
5243 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5244 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5245 return false;
5246
5247 SDValue Op0 = N->getOperand(0);
5248 SDValue Op1 = N->getOperand(1);
5249 assert(Op0.getValueType() == Op1.getValueType());
5250
5251 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5252 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005253 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005254 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005255 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005256 Op = Op0;
5257 else
5258 return false;
5259
Jay Foada0653a32014-05-14 21:14:37 +00005260 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005261
5262 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5263 return false;
5264
5265 return true;
5266}
5267
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005268SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5269 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005270 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005271
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005272 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5273 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005274 return SDValue(Res, 0);
5275
Nate Begeman21158fc2005-09-01 00:19:25 +00005276 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005277 // fold (zext (aext x)) -> (zext x)
5278 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005279 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005280 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00005281
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005282 // fold (zext (truncate x)) -> (zext x) or
5283 // (zext (truncate x)) -> (truncate x)
5284 // This is valid when the truncated bits of x are already zero.
5285 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005286 SDValue Op;
5287 APInt KnownZero;
5288 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5289 APInt TruncatedBits =
5290 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5291 APInt(Op.getValueSizeInBits(), 0) :
5292 APInt::getBitsSet(Op.getValueSizeInBits(),
5293 N0.getValueSizeInBits(),
5294 std::min(Op.getValueSizeInBits(),
5295 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00005296 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005297 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005298 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005299 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005300 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005301
5302 return Op;
5303 }
5304 }
5305
Evan Cheng464dc9b2007-03-22 01:54:19 +00005306 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5307 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00005308 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005309 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5310 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005311 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5312 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005313 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005314 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005315 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005316 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005317 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005318 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005319 }
5320
Chris Lattnera31f0a62006-09-21 06:00:20 +00005321 // fold (zext (truncate x)) -> (and x, mask)
5322 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00005323 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005324
5325 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5326 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5327 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5328 if (NarrowLoad.getNode()) {
5329 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5330 if (NarrowLoad.getNode() != N0.getNode()) {
5331 CombineTo(N0.getNode(), NarrowLoad);
5332 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005333 AddToWorklist(oye);
Dan Gohman68fb0042010-11-03 01:47:46 +00005334 }
5335 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5336 }
5337
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005338 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005339 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005340 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005341 AddToWorklist(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00005342 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005343 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005344 AddToWorklist(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005345 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005346 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00005347 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005348 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005349
Dan Gohmanad3e5492009-04-08 00:15:30 +00005350 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5351 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005352 if (N0.getOpcode() == ISD::AND &&
5353 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005354 N0.getOperand(1).getOpcode() == ISD::Constant &&
5355 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5356 N0.getValueType()) ||
5357 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005358 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005359 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005360 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005361 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005362 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005363 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005364 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005365 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005366 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005367 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005368 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005369
Evan Chengbce7c472005-12-14 02:19:23 +00005370 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005371 // None of the supported targets knows how to perform load and vector_zext
Nadav Rotemb0091302011-02-27 07:40:43 +00005372 // on vectors in one instruction. We only perform this transformation on
5373 // scalars.
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005374 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005375 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005376 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005377 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005378 bool DoXform = true;
5379 SmallVector<SDNode*, 4> SetCCs;
5380 if (!N0.hasOneUse())
5381 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5382 if (DoXform) {
5383 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005384 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005385 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005386 LN0->getBasePtr(), N0.getValueType(),
5387 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005388 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005389 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005390 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005391 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005392
Andrew Trickef9de2a2013-05-25 02:42:55 +00005393 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005394 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005395 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005396 }
Evan Chengbce7c472005-12-14 02:19:23 +00005397 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005398
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005399 // fold (zext (and/or/xor (load x), cst)) ->
5400 // (and/or/xor (zextload x), (zext cst))
5401 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5402 N0.getOpcode() == ISD::XOR) &&
5403 isa<LoadSDNode>(N0.getOperand(0)) &&
5404 N0.getOperand(1).getOpcode() == ISD::Constant &&
5405 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5406 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5407 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005408 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005409 bool DoXform = true;
5410 SmallVector<SDNode*, 4> SetCCs;
5411 if (!N0.hasOneUse())
5412 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5413 SetCCs, TLI);
5414 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005415 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005416 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005417 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005418 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005419 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5420 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005421 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005422 ExtLoad, DAG.getConstant(Mask, VT));
5423 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005424 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005425 N0.getOperand(0).getValueType(), ExtLoad);
5426 CombineTo(N, And);
5427 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005428 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005429 ISD::ZERO_EXTEND);
5430 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5431 }
5432 }
5433 }
5434
Chris Lattner7dac1082005-12-14 19:05:06 +00005435 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5436 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005437 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5438 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005439 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005440 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005441 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005442 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005443 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005444 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005445 LN0->getBasePtr(), MemVT,
5446 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005447 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005448 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005449 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005450 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005451 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005452 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005453 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005454 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005455
Chris Lattner65786b02007-04-11 05:32:27 +00005456 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005457 if (!LegalOperations && VT.isVector() &&
5458 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005459 EVT N0VT = N0.getOperand(0).getValueType();
5460 if (getSetCCResultType(N0VT) == N0.getValueType())
5461 return SDValue();
5462
Evan Chengabd0ad52010-05-19 01:08:17 +00005463 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5464 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005465 EVT EltVT = VT.getVectorElementType();
5466 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5467 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00005468 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00005469 // We know that the # elements of the results is the same as the
5470 // # elements of the compare (and the # elements of the compare result
5471 // for that matter). Check to see that they are the same size. If so,
5472 // we know that the element size of the sext'd result matches the
5473 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005474 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5475 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00005476 N0.getOperand(1),
5477 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005478 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Craig Topper48d114b2014-04-26 18:35:24 +00005479 OneOps));
Dan Gohman4298df62011-05-17 22:20:36 +00005480
5481 // If the desired elements are smaller or larger than the source
5482 // elements we can use a matching integer vector type and then
5483 // truncate/sign extend
5484 EVT MatchingElementType =
5485 EVT::getIntegerVT(*DAG.getContext(),
5486 N0VT.getScalarType().getSizeInBits());
5487 EVT MatchingVectorType =
5488 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5489 N0VT.getVectorNumElements());
5490 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005491 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00005492 N0.getOperand(1),
5493 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005494 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5495 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
Craig Topper48d114b2014-04-26 18:35:24 +00005496 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
Evan Chengabd0ad52010-05-19 01:08:17 +00005497 }
5498
5499 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005500 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005501 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00005502 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005503 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005504 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005505 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005506
Evan Cheng852c4862009-12-15 03:00:32 +00005507 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00005508 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00005509 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00005510 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5511 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005512 SDValue ShAmt = N0.getOperand(1);
5513 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00005514 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005515 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00005516 // If the original shl may be shifting out bits, do not perform this
5517 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00005518 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5519 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5520 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00005521 return SDValue();
5522 }
Chris Lattnere95d1952011-02-13 19:09:16 +00005523
Andrew Trickef9de2a2013-05-25 02:42:55 +00005524 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005525
5526 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00005527 if (VT.getSizeInBits() >= 256)
5528 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005529
Chris Lattnere95d1952011-02-13 19:09:16 +00005530 return DAG.getNode(N0.getOpcode(), DL, VT,
5531 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5532 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00005533 }
5534
Evan Chengf1005572010-04-28 07:10:39 +00005535 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005536}
5537
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005538SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5539 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005540 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005541
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005542 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5543 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005544 return SDValue(Res, 0);
5545
Chris Lattner812646a2006-05-05 05:58:59 +00005546 // fold (aext (aext x)) -> (aext x)
5547 // fold (aext (zext x)) -> (zext x)
5548 // fold (aext (sext x)) -> (sext x)
5549 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5550 N0.getOpcode() == ISD::ZERO_EXTEND ||
5551 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005552 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005553
Evan Cheng464dc9b2007-03-22 01:54:19 +00005554 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5555 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5556 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005557 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5558 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005559 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5560 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005561 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005562 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005563 AddToWorklist(oye);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005564 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005565 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005566 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005567 }
5568
Chris Lattner8746e2c2006-09-20 06:29:17 +00005569 // fold (aext (truncate x))
5570 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005571 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005572 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005573 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00005574 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005575 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5576 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005577 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005578
Dan Gohmanad3e5492009-04-08 00:15:30 +00005579 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5580 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00005581 if (N0.getOpcode() == ISD::AND &&
5582 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005583 N0.getOperand(1).getOpcode() == ISD::Constant &&
5584 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5585 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005586 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005587 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005588 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005589 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005590 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00005591 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005592 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005593 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005594 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005595 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00005596 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005597
Chris Lattner812646a2006-05-05 05:58:59 +00005598 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005599 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00005600 // on vectors in one instruction. We only perform this transformation on
5601 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005602 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005603 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Tim Northover7f3e11e2014-07-16 15:37:24 +00005604 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005605 bool DoXform = true;
5606 SmallVector<SDNode*, 4> SetCCs;
5607 if (!N0.hasOneUse())
5608 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5609 if (DoXform) {
5610 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005611 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005612 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005613 LN0->getBasePtr(), N0.getValueType(),
5614 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00005615 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005616 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00005617 N0.getValueType(), ExtLoad);
5618 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005619 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005620 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005621 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5622 }
Chris Lattner812646a2006-05-05 05:58:59 +00005623 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005624
Chris Lattner812646a2006-05-05 05:58:59 +00005625 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5626 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5627 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005628 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005629 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00005630 N0.hasOneUse()) {
5631 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005632 ISD::LoadExtType ExtType = LN0->getExtensionType();
Dan Gohman08c0a952009-09-23 21:02:20 +00005633 EVT MemVT = LN0->getMemoryVT();
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005634 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5635 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5636 VT, LN0->getChain(), LN0->getBasePtr(),
5637 MemVT, LN0->getMemOperand());
5638 CombineTo(N, ExtLoad);
5639 CombineTo(N0.getNode(),
5640 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5641 N0.getValueType(), ExtLoad),
5642 ExtLoad.getValue(1));
5643 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5644 }
Chris Lattner812646a2006-05-05 05:58:59 +00005645 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005646
Chris Lattner65786b02007-04-11 05:32:27 +00005647 if (N0.getOpcode() == ISD::SETCC) {
Hao Liuc636d152014-04-22 09:57:06 +00005648 // For vectors:
5649 // aext(setcc) -> vsetcc
5650 // aext(setcc) -> truncate(vsetcc)
5651 // aext(setcc) -> aext(vsetcc)
Evan Chengabd0ad52010-05-19 01:08:17 +00005652 // Only do this before legalize for now.
5653 if (VT.isVector() && !LegalOperations) {
5654 EVT N0VT = N0.getOperand(0).getValueType();
5655 // We know that the # elements of the results is the same as the
5656 // # elements of the compare (and the # elements of the compare result
5657 // for that matter). Check to see that they are the same size. If so,
5658 // we know that the element size of the sext'd result matches the
5659 // element size of the compare operands.
5660 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005661 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005662 N0.getOperand(1),
5663 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00005664 // If the desired elements are smaller or larger than the source
5665 // elements we can use a matching integer vector type and then
Hao Liuc636d152014-04-22 09:57:06 +00005666 // truncate/any extend
Evan Chengabd0ad52010-05-19 01:08:17 +00005667 else {
Hao Liuc636d152014-04-22 09:57:06 +00005668 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005669 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005670 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005671 N0.getOperand(1),
5672 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Hao Liuc636d152014-04-22 09:57:06 +00005673 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00005674 }
5675 }
5676
5677 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005678 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005679 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005680 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00005681 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005682 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00005683 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005684 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005685
Evan Chengf1005572010-04-28 07:10:39 +00005686 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00005687}
5688
Sanjay Patel50cbfc52014-08-28 16:29:51 +00005689/// See if the specified operand can be simplified with the knowledge that only
5690/// the bits specified by Mask are used. If so, return the simpler operand,
5691/// otherwise return a null SDValue.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005692SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00005693 switch (V.getOpcode()) {
5694 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00005695 case ISD::Constant: {
5696 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00005697 assert(CV && "Const value should be ConstSDNode.");
Lang Hamesb85fcd02011-11-08 18:56:23 +00005698 const APInt &CVal = CV->getAPIntValue();
5699 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00005700 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00005701 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00005702 break;
5703 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005704 case ISD::OR:
5705 case ISD::XOR:
5706 // If the LHS or RHS don't contribute bits to the or, drop them.
5707 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5708 return V.getOperand(1);
5709 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5710 return V.getOperand(0);
5711 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00005712 case ISD::SRL:
5713 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00005714 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00005715 break;
5716 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5717 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00005718 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005719
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00005720 // Watch out for shift count overflow though.
5721 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00005722 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005723 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005724 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005725 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00005726 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00005727 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005728 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005729 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00005730}
5731
Sanjay Patel50cbfc52014-08-28 16:29:51 +00005732/// If the result of a wider load is shifted to right of N bits and then
5733/// truncated to a narrower type and where N is a multiple of number of bits of
5734/// the narrower type, transform it to a narrower load from address + N / num of
5735/// bits of new type. If the result is to be extended, also fold the extension
5736/// to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005737SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005738 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00005739
Evan Cheng464dc9b2007-03-22 01:54:19 +00005740 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005741 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005742 EVT VT = N->getValueType(0);
5743 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005744
Dan Gohman550c9af2008-08-14 20:04:46 +00005745 // This transformation isn't valid for vector loads.
5746 if (VT.isVector())
5747 return SDValue();
5748
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005749 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00005750 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00005751 if (Opc == ISD::SIGN_EXTEND_INREG) {
5752 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00005753 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00005754 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00005755 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00005756 ExtType = ISD::ZEXTLOAD;
5757 N0 = SDValue(N, 0);
5758 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5759 if (!N01) return SDValue();
5760 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5761 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00005762 }
Richard Osborne272e0842011-01-31 17:41:44 +00005763 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5764 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005765
Owen Anderson53aa7a92009-08-10 22:56:29 +00005766 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005767
Chris Lattner9a499e92010-12-22 08:01:44 +00005768 // Do not generate loads of non-round integer types since these can
5769 // be expensive (and would be wrong if the type is not byte sized).
5770 if (!ExtVT.isRound())
5771 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005772
Evan Cheng464dc9b2007-03-22 01:54:19 +00005773 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00005774 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005775 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00005776 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005777 // Is the shift amount a multiple of size of VT?
5778 if ((ShAmt & (EVTBits-1)) == 0) {
5779 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00005780 // Is the load width a multiple of size of VT?
5781 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005782 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005783 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005784
Chris Lattnercafc1e62010-12-22 08:02:57 +00005785 // At this point, we must have a load or else we can't do the transform.
5786 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005787
Chandler Carruthb27041c2012-12-11 00:36:57 +00005788 // Because a SRL must be assumed to *need* to zero-extend the high bits
5789 // (as opposed to anyext the high bits), we can't combine the zextload
5790 // lowering of SRL and an sextload.
5791 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5792 return SDValue();
5793
Chris Lattnera2050552010-10-01 05:36:09 +00005794 // If the shift amount is larger than the input type then we're not
5795 // accessing any of the loaded bytes. If the load was a zextload/extload
5796 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00005797 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00005798 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005799 }
5800 }
5801
Dan Gohman68fb0042010-11-03 01:47:46 +00005802 // If the load is shifted left (and the result isn't shifted back right),
5803 // we can fold the truncate through the shift.
5804 unsigned ShLeftAmt = 0;
5805 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00005806 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005807 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5808 ShLeftAmt = N01->getZExtValue();
5809 N0 = N0.getOperand(0);
5810 }
5811 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00005812
Chris Lattner222374d2010-12-22 07:36:50 +00005813 // If we haven't found a load, we can't narrow it. Don't transform one with
5814 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00005815 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5816 return SDValue();
5817
5818 // Don't change the width of a volatile load.
5819 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5820 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00005821 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005822
Chris Lattner9a499e92010-12-22 08:01:44 +00005823 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00005824 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00005825 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005826
Bill Schmidtd006c692013-01-14 22:04:38 +00005827 // For the transform to be legal, the load must produce only two values
5828 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00005829 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00005830 // transformation is not equivalent, and the downstream logic to replace
5831 // uses gets things wrong.
5832 if (LN0->getNumValues() > 2)
5833 return SDValue();
5834
Benjamin Kramerc7332b22013-07-06 14:05:09 +00005835 // If the load that we're shrinking is an extload and we're not just
5836 // discarding the extension we can't simply shrink the load. Bail.
5837 // TODO: It would be possible to merge the extensions in some cases.
5838 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5839 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5840 return SDValue();
5841
Chris Lattner222374d2010-12-22 07:36:50 +00005842 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005843
Evan Cheng4c6f9172012-06-26 01:19:33 +00005844 if (PtrType == MVT::Untyped || PtrType.isExtended())
5845 // It's not possible to generate a constant of extended or untyped type.
5846 return SDValue();
5847
Chris Lattner222374d2010-12-22 07:36:50 +00005848 // For big endian targets, we need to adjust the offset to the pointer to
5849 // load the correct bytes.
5850 if (TLI.isBigEndian()) {
5851 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5852 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5853 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005854 }
5855
Chris Lattner222374d2010-12-22 07:36:50 +00005856 uint64_t PtrOff = ShAmt / 8;
5857 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005858 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00005859 PtrType, LN0->getBasePtr(),
5860 DAG.getConstant(PtrOff, PtrType));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005861 AddToWorklist(NewPtr.getNode());
Chris Lattner222374d2010-12-22 07:36:50 +00005862
Chris Lattner9a499e92010-12-22 08:01:44 +00005863 SDValue Load;
5864 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005865 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005866 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00005867 LN0->isVolatile(), LN0->isNonTemporal(),
Hal Finkelcc39b672014-07-24 12:16:19 +00005868 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00005869 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005870 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005871 LN0->getPointerInfo().getWithOffset(PtrOff),
5872 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00005873 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00005874
5875 // Replace the old load's chain with the new load's chain.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005876 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00005877 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00005878
5879 // Shift the result left, if we've swallowed a left shift.
5880 SDValue Result = Load;
5881 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00005882 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00005883 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5884 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00005885 // If the shift amount is as large as the result size (but, presumably,
5886 // no larger than the source) then the useful bits of the result are
5887 // zero; we can't simply return the shortened shift, because the result
5888 // of that operation is undefined.
5889 if (ShLeftAmt >= VT.getSizeInBits())
5890 Result = DAG.getConstant(0, VT);
5891 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005892 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00005893 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00005894 }
5895
5896 // Return the new loaded value.
5897 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005898}
5899
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005900SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5901 SDValue N0 = N->getOperand(0);
5902 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005903 EVT VT = N->getValueType(0);
5904 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00005905 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005906 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005907
Nate Begeman21158fc2005-09-01 00:19:25 +00005908 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00005909 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005910 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005911
Chris Lattner2a4d7b82006-05-06 22:43:44 +00005912 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00005913 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00005914 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005915
Nate Begeman7cea6ef2005-09-02 21:18:40 +00005916 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5917 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00005918 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005919 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005920 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00005921
Dan Gohman345d63c2008-07-31 00:50:31 +00005922 // fold (sext_in_reg (sext x)) -> (sext x)
5923 // fold (sext_in_reg (aext x)) -> (sext x)
5924 // if x is small enough.
5925 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5926 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00005927 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5928 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005929 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00005930 }
5931
Chris Lattner9ad59152007-04-17 19:03:21 +00005932 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00005933 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005934 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005935
Chris Lattner9ad59152007-04-17 19:03:21 +00005936 // fold operands of sext_in_reg based on knowledge that the top bits are not
5937 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005938 if (SimplifyDemandedBits(SDValue(N, 0)))
5939 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005940
Evan Cheng464dc9b2007-03-22 01:54:19 +00005941 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5942 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005943 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005944 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00005945 return NarrowLoad;
5946
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005947 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005948 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00005949 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5950 if (N0.getOpcode() == ISD::SRL) {
5951 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00005952 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005953 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00005954 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00005955 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00005956 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005957 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005958 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00005959 }
5960 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005961
Nate Begeman02b23c62005-10-13 03:11:28 +00005962 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00005963 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005964 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005965 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005966 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005967 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005968 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005969 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005970 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005971 LN0->getBasePtr(), EVT,
5972 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005973 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005974 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005975 AddToWorklist(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005976 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005977 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005978 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00005979 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005980 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005981 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005982 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005983 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005984 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005985 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005986 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005987 LN0->getBasePtr(), EVT,
5988 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005989 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005990 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005991 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005992 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00005993
5994 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5995 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5996 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5997 N0.getOperand(1), false);
Craig Topperc0196b12014-04-14 00:51:57 +00005998 if (BSwap.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005999 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00006000 BSwap, N1);
6001 }
6002
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006003 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6004 // into a build_vector.
6005 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6006 SmallVector<SDValue, 8> Elts;
6007 unsigned NumElts = N0->getNumOperands();
6008 unsigned ShAmt = VTBits - EVTBits;
6009
6010 for (unsigned i = 0; i != NumElts; ++i) {
6011 SDValue Op = N0->getOperand(i);
6012 if (Op->getOpcode() == ISD::UNDEF) {
6013 Elts.push_back(Op);
6014 continue;
6015 }
6016
6017 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00006018 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6019 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006020 Op.getValueType()));
6021 }
6022
Craig Topper48d114b2014-04-26 18:35:24 +00006023 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006024 }
6025
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006026 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006027}
6028
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006029SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6030 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006031 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006032 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00006033
6034 // noop truncate
6035 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00006036 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00006037 // fold (truncate c1) -> c1
Chris Lattner7e7bcf32006-05-06 23:06:26 +00006038 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006039 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006040 // fold (truncate (truncate x)) -> (truncate x)
6041 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006042 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00006043 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00006044 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6045 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00006046 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00006047 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006048 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00006049 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006050 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006051 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006052 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00006053 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006054 // if the source and dest are the same type, we can drop both the extend
6055 // and the truncate.
6056 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006057 }
Evan Chengd63baea2007-03-21 20:14:05 +00006058
Nadav Rotem4f4546b2012-02-05 11:39:23 +00006059 // Fold extract-and-trunc into a narrow extract. For example:
6060 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6061 // i32 y = TRUNCATE(i64 x)
6062 // -- becomes --
6063 // v16i8 b = BITCAST (v2i64 val)
6064 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6065 //
6066 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006067 // creates this pattern) and before operation legalization after which
6068 // we need to be more careful about the vector instructions that we generate.
6069 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00006070 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006071
6072 EVT VecTy = N0.getOperand(0).getValueType();
6073 EVT ExTy = N0.getValueType();
6074 EVT TrTy = N->getValueType(0);
6075
6076 unsigned NumElem = VecTy.getVectorNumElements();
6077 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6078
6079 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6080 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6081
6082 SDValue EltNo = N0->getOperand(1);
6083 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6084 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00006085 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006086 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6087
Andrew Trickef9de2a2013-05-25 02:42:55 +00006088 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006089 NVT, N0.getOperand(0));
6090
6091 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00006092 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00006093 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006094 }
6095 }
6096
Matt Arsenault3332b702014-07-10 18:21:04 +00006097 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6098 if (N0.getOpcode() == ISD::SELECT) {
6099 EVT SrcVT = N0.getValueType();
6100 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6101 TLI.isTruncateFree(SrcVT, VT)) {
6102 SDLoc SL(N0);
6103 SDValue Cond = N0.getOperand(0);
6104 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6105 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6106 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6107 }
6108 }
6109
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006110 // Fold a series of buildvector, bitcast, and truncate if possible.
6111 // For example fold
6112 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6113 // (2xi32 (buildvector x, y)).
6114 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6115 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6116 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6117 N0.getOperand(0).hasOneUse()) {
6118
6119 SDValue BuildVect = N0.getOperand(0);
6120 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6121 EVT TruncVecEltTy = VT.getVectorElementType();
6122
6123 // Check that the element types match.
6124 if (BuildVectEltTy == TruncVecEltTy) {
6125 // Now we only need to compute the offset of the truncated elements.
6126 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6127 unsigned TruncVecNumElts = VT.getVectorNumElements();
6128 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6129
6130 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6131 "Invalid number of elements");
6132
6133 SmallVector<SDValue, 8> Opnds;
6134 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6135 Opnds.push_back(BuildVect.getOperand(i));
6136
Craig Topper48d114b2014-04-26 18:35:24 +00006137 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006138 }
6139 }
6140
Chris Lattner5e6fe052007-10-13 06:35:54 +00006141 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00006142 // only the low bits are being used.
6143 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00006144 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00006145 // may have different active low bits.
6146 if (!VT.isVector()) {
6147 SDValue Shorter =
6148 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6149 VT.getSizeInBits()));
6150 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006151 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00006152 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00006153 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00006154 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00006155 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6156 SDValue Reduced = ReduceLoadWidth(N);
6157 if (Reduced.getNode())
6158 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00006159 // Handle the case where the load remains an extending load even
6160 // after truncation.
6161 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6162 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6163 if (!LN0->isVolatile() &&
6164 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6165 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6166 VT, LN0->getChain(), LN0->getBasePtr(),
6167 LN0->getMemoryVT(),
6168 LN0->getMemOperand());
6169 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6170 return NewLoad;
6171 }
6172 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006173 }
Michael Liao3ac82012012-10-17 23:45:54 +00006174 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6175 // where ... are all 'undef'.
6176 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6177 SmallVector<EVT, 8> VTs;
6178 SDValue V;
6179 unsigned Idx = 0;
6180 unsigned NumDefs = 0;
6181
6182 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6183 SDValue X = N0.getOperand(i);
6184 if (X.getOpcode() != ISD::UNDEF) {
6185 V = X;
6186 Idx = i;
6187 NumDefs++;
6188 }
6189 // Stop if more than one members are non-undef.
6190 if (NumDefs > 1)
6191 break;
6192 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6193 VT.getVectorElementType(),
6194 X.getValueType().getVectorNumElements()));
6195 }
6196
6197 if (NumDefs == 0)
6198 return DAG.getUNDEF(VT);
6199
6200 if (NumDefs == 1) {
6201 assert(V.getNode() && "The single defined operand is empty!");
6202 SmallVector<SDValue, 8> Opnds;
6203 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6204 if (i != Idx) {
6205 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6206 continue;
6207 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006208 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006209 AddToWorklist(NV.getNode());
Michael Liao3ac82012012-10-17 23:45:54 +00006210 Opnds.push_back(NV);
6211 }
Craig Topper48d114b2014-04-26 18:35:24 +00006212 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
Michael Liao3ac82012012-10-17 23:45:54 +00006213 }
6214 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006215
6216 // Simplify the operands using demanded-bits information.
6217 if (!VT.isVector() &&
6218 SimplifyDemandedBits(SDValue(N, 0)))
6219 return SDValue(N, 0);
6220
Evan Chengf1bd5fc2010-04-17 06:13:15 +00006221 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006222}
6223
Evan Chengb980f6f2008-05-12 23:04:07 +00006224static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006225 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00006226 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006227 return Elt.getNode();
6228 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00006229}
6230
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006231/// build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00006232/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00006233SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00006234 assert(N->getOpcode() == ISD::BUILD_PAIR);
6235
Nate Begeman624690c2009-06-05 21:37:30 +00006236 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6237 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006238 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00006239 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006240 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00006241 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00006242
Evan Chengb980f6f2008-05-12 23:04:07 +00006243 if (ISD::isNON_EXTLoad(LD2) &&
6244 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006245 // If both are volatile this would reduce the number of volatile loads.
6246 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00006247 !LD1->isVolatile() &&
6248 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00006249 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00006250 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006251 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006252 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00006253
Duncan Sands8651e9c2008-06-13 19:07:40 +00006254 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006255 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006256 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006257 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006258 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00006259 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00006260
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006261 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00006262}
6263
Wesley Peck527da1b2010-11-23 03:31:01 +00006264SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006265 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006266 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00006267
Dan Gohmana8665142007-06-25 16:23:39 +00006268 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6269 // Only do this before legalize, since afterward the target may be depending
6270 // on the bitconvert.
6271 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006272 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006273 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006274 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00006275 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006276
Owen Anderson53aa7a92009-08-10 22:56:29 +00006277 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006278 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00006279 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00006280 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00006281 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00006282 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006283
Dan Gohman921ddd62008-09-05 01:58:21 +00006284 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00006285 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006286 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Dan Gohman733a64d2009-08-10 23:15:10 +00006287 if (Res.getNode() != N) {
6288 if (!LegalOperations ||
6289 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6290 return Res;
6291
6292 // Folding it resulted in an illegal node, and it's too late to
6293 // do that. Clean up the old node and forego the transformation.
6294 // Ideally this won't happen very often, because instcombine
6295 // and the earlier dagcombine runs (where illegal nodes are
6296 // permitted) should have folded most of them already.
Chandler Carruth18066972014-08-02 10:02:07 +00006297 deleteAndRecombine(Res.getNode());
Dan Gohman733a64d2009-08-10 23:15:10 +00006298 }
Chris Lattnera1874602005-12-23 05:30:37 +00006299 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006300
Bill Wendling4e0a6152009-01-30 22:44:24 +00006301 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00006302 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006303 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006304 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006305
Chris Lattner54560f62005-12-23 05:44:41 +00006306 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00006307 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00006308 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006309 // Do not change the width of a volatile load.
6310 !cast<LoadSDNode>(N0)->isVolatile() &&
Ulrich Weigandf236bb12014-07-03 15:06:47 +00006311 // Do not remove the cast if the types differ in endian layout.
6312 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6313 TLI.hasBigEndianPartOrdering(VT) &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00006314 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6315 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006316 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006317 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006318 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006319 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00006320
Evan Chenga4cf58a2007-05-07 21:27:48 +00006321 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006322 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006323 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00006324 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006325 LN0->isInvariant(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00006326 LN0->getAAInfo());
Chandler Carruth7cd15be2014-08-14 08:18:34 +00006327 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006328 return Load;
6329 }
Chris Lattner54560f62005-12-23 05:44:41 +00006330 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006331
Bill Wendling4e0a6152009-01-30 22:44:24 +00006332 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6333 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00006334 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00006335 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6336 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00006337 N0.getNode()->hasOneUse() && VT.isInteger() &&
6338 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006339 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006340 N0.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006341 AddToWorklist(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00006342
Duncan Sands13237ac2008-06-06 12:08:01 +00006343 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00006344 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006345 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006346 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006347 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006348 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006349 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006350 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006351
Bill Wendling4e0a6152009-01-30 22:44:24 +00006352 // fold (bitconvert (fcopysign cst, x)) ->
6353 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6354 // Note that we don't handle (copysign x, cst) because this can always be
6355 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006356 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00006357 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006358 VT.isInteger() && !VT.isVector()) {
6359 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00006360 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00006361 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006362 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006363 IntXVT, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006364 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006365
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006366 // If X has a different width than the result/lhs, sext it or truncate it.
6367 unsigned VTWidth = VT.getSizeInBits();
6368 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006369 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006370 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006371 } else if (OrigXWidth > VTWidth) {
6372 // To get the sign bit in the right place, we have to shift it right
6373 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006374 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006375 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006376 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006377 AddToWorklist(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006378 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006379 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006380 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006381
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006382 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006383 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006384 X, DAG.getConstant(SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006385 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006386
Andrew Trickef9de2a2013-05-25 02:42:55 +00006387 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006388 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006389 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006390 Cst, DAG.getConstant(~SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006391 AddToWorklist(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006392
Andrew Trickef9de2a2013-05-25 02:42:55 +00006393 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006394 }
Chris Lattner888560d2008-01-27 17:42:27 +00006395 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006396
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006397 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006398 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006399 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6400 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006401 return CombineLD;
6402 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006403
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006404 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006405}
6406
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006407SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006408 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006409 return CombineConsecutiveLoads(N, VT);
6410}
6411
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006412/// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6413/// operands. DstEltVT indicates the destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006414SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006415ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006416 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006417
Chris Lattnere4e64b62006-04-02 02:53:43 +00006418 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006419 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006420
Duncan Sands13237ac2008-06-06 12:08:01 +00006421 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6422 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006423
Chris Lattnere4e64b62006-04-02 02:53:43 +00006424 // If this is a conversion of N elements of one type to N elements of another
6425 // type, convert each element. This handles FP<->INT cases.
6426 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006427 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6428 BV->getValueType(0).getVectorNumElements());
6429
6430 // Due to the FP element handling below calling this routine recursively,
6431 // we can end up with a scalar-to-vector node here.
6432 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006433 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6434 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006435 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006436
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006437 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006438 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006439 SDValue Op = BV->getOperand(i);
6440 // If the vector element type is not legal, the BUILD_VECTOR operands
6441 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006442 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006443 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6444 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006445 DstEltVT, Op));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006446 AddToWorklist(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006447 }
Craig Topper48d114b2014-04-26 18:35:24 +00006448 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006449 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006450
Chris Lattnere4e64b62006-04-02 02:53:43 +00006451 // Otherwise, we're growing or shrinking the elements. To avoid having to
6452 // handle annoying details of growing/shrinking FP values, we convert them to
6453 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006454 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006455 // Convert the input float vector to a int vector where the elements are the
6456 // same sizes.
Owen Anderson9f944592009-08-11 20:47:22 +00006457 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006458 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006459 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006460 SrcEltVT = IntVT;
6461 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006462
Chris Lattnere4e64b62006-04-02 02:53:43 +00006463 // Now we know the input is an integer vector. If the output is a FP type,
6464 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006465 if (DstEltVT.isFloatingPoint()) {
Owen Anderson9f944592009-08-11 20:47:22 +00006466 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006467 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006468 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006469
Chris Lattnere4e64b62006-04-02 02:53:43 +00006470 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00006471 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006472 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006473
Chris Lattnere4e64b62006-04-02 02:53:43 +00006474 // Okay, we know the src/dst types are both integers of differing types.
6475 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006476 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006477 if (SrcBitSize < DstBitSize) {
6478 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006479
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006480 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006481 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00006482 i += NumInputsPerOutput) {
6483 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00006484 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006485 bool EltIsUndef = true;
6486 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6487 // Shift the previously computed bits over.
6488 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006489 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006490 if (Op.getOpcode() == ISD::UNDEF) continue;
6491 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006492
Jay Foad583abbc2010-12-07 08:25:19 +00006493 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00006494 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006495 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006496
Chris Lattnere4e64b62006-04-02 02:53:43 +00006497 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00006498 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006499 else
6500 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6501 }
6502
Owen Anderson117c9e82009-08-12 00:36:31 +00006503 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Craig Topper48d114b2014-04-26 18:35:24 +00006504 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006505 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006506
Chris Lattnere4e64b62006-04-02 02:53:43 +00006507 // Finally, this must be the case where we are shrinking elements: each input
6508 // turns into multiple outputs.
Evan Cheng6200c222008-02-18 23:04:32 +00006509 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006510 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00006511 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6512 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006513 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006514
Dan Gohmana8665142007-06-25 16:23:39 +00006515 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006516 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6517 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesen84935752009-02-06 23:05:02 +00006518 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006519 continue;
6520 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006521
Jay Foad583abbc2010-12-07 08:25:19 +00006522 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6523 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006524
Chris Lattnere4e64b62006-04-02 02:53:43 +00006525 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00006526 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006527 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad583abbc2010-12-07 08:25:19 +00006528 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Cheng6200c222008-02-18 23:04:32 +00006529 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006530 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006531 Ops[0]);
Dan Gohmane1c4f992008-03-03 23:51:38 +00006532 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006533 }
6534
6535 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00006536 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00006537 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6538 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006539
Craig Topper48d114b2014-04-26 18:35:24 +00006540 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006541}
6542
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006543SDValue DAGCombiner::visitFADD(SDNode *N) {
6544 SDValue N0 = N->getOperand(0);
6545 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006546 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6547 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006548 EVT VT = N->getValueType(0);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006549 const TargetOptions &Options = DAG.getTarget().Options;
Sanjay Patel159f1272014-08-27 21:42:42 +00006550
Dan Gohmana8665142007-06-25 16:23:39 +00006551 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006552 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006553 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006554 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006555 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006556
Lang Hamesa33db652012-06-14 20:37:15 +00006557 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006558 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006559 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006560 // canonicalize constant to RHS
6561 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006562 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006563 // fold (fadd A, 0) -> A
Sanjay Patel78614bf2014-08-28 15:53:16 +00006564 if (Options.UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006565 return N0;
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 Patel78614bf2014-08-28 15:53:16 +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));
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006571 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006572 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel78614bf2014-08-28 15:53:16 +00006573 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006574 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006575 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006576
Chris Lattner0199fd62007-01-08 23:04:05 +00006577 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
Sanjay Patel78614bf2014-08-28 15:53:16 +00006578 if (Options.UnsafeFPMath && N1CFP &&
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006579 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6580 isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006581 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6582 DAG.getNode(ISD::FADD, SDLoc(N), VT,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +00006583 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006584
Shuxin Yang93b1f122013-03-25 22:52:29 +00006585 // No FP constant should be created after legalization as Instruction
6586 // Selection pass has hard time in dealing with FP constant.
6587 //
6588 // We don't need test this condition for transformation like following, as
6589 // the DAG being transformed implies it is legal to take FP constant as
6590 // operand.
Stephen Lincfe7f352013-07-08 00:37:03 +00006591 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006592 // (fadd (fmul c, x), x) -> (fmul c+1, x)
Stephen Lincfe7f352013-07-08 00:37:03 +00006593 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006594 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6595
Owen Andersonb351c8d2012-11-01 02:00:53 +00006596 // If allow, fold (fadd (fneg x), x) -> 0.0
Sanjay Patel78614bf2014-08-28 15:53:16 +00006597 if (AllowNewFpConst && Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006598 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006599 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006600
Sanjay Patel159f1272014-08-27 21:42:42 +00006601 // If allow, fold (fadd x, (fneg x)) -> 0.0
Sanjay Patel78614bf2014-08-28 15:53:16 +00006602 if (AllowNewFpConst && Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006603 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006604 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006605
Owen Andersoncc61f872012-08-30 23:35:16 +00006606 // In unsafe math mode, we can fold chains of FADD's of the same value
6607 // into multiplications. This transform is not safe in general because
6608 // we are reducing the number of rounding steps.
Sanjay Patel78614bf2014-08-28 15:53:16 +00006609 if (Options.UnsafeFPMath && TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
Owen Andersoncc61f872012-08-30 23:35:16 +00006610 !N0CFP && !N1CFP) {
6611 if (N0.getOpcode() == ISD::FMUL) {
6612 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6613 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6614
Stephen Line31f2d22013-06-14 18:17:35 +00006615 // (fadd (fmul c, x), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006616 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006617 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006618 SDValue(CFP00, 0),
6619 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006620 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006621 N1, NewCFP);
6622 }
6623
Stephen Line31f2d22013-06-14 18:17:35 +00006624 // (fadd (fmul x, c), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006625 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006626 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006627 SDValue(CFP01, 0),
6628 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006629 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006630 N1, NewCFP);
6631 }
6632
Stephen Line31f2d22013-06-14 18:17:35 +00006633 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006634 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6635 N1.getOperand(0) == N1.getOperand(1) &&
6636 N0.getOperand(1) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006637 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006638 SDValue(CFP00, 0),
6639 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006640 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006641 N0.getOperand(1), NewCFP);
6642 }
6643
Stephen Line31f2d22013-06-14 18:17:35 +00006644 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006645 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6646 N1.getOperand(0) == N1.getOperand(1) &&
6647 N0.getOperand(0) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006648 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006649 SDValue(CFP01, 0),
6650 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006651 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006652 N0.getOperand(0), NewCFP);
6653 }
6654 }
6655
6656 if (N1.getOpcode() == ISD::FMUL) {
6657 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6658 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6659
Stephen Line31f2d22013-06-14 18:17:35 +00006660 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006661 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006662 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006663 SDValue(CFP10, 0),
6664 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006665 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006666 N0, NewCFP);
6667 }
6668
Stephen Line31f2d22013-06-14 18:17:35 +00006669 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006670 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006671 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006672 SDValue(CFP11, 0),
6673 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006674 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006675 N0, NewCFP);
6676 }
6677
Owen Andersoncc61f872012-08-30 23:35:16 +00006678
Stephen Line31f2d22013-06-14 18:17:35 +00006679 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6680 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6681 N0.getOperand(0) == N0.getOperand(1) &&
6682 N1.getOperand(1) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006683 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006684 SDValue(CFP10, 0),
6685 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006686 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006687 N1.getOperand(1), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006688 }
6689
Stephen Line31f2d22013-06-14 18:17:35 +00006690 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6691 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6692 N0.getOperand(0) == N0.getOperand(1) &&
6693 N1.getOperand(0) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006694 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006695 SDValue(CFP11, 0),
6696 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006697 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006698 N1.getOperand(0), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006699 }
6700 }
6701
Shuxin Yang93b1f122013-03-25 22:52:29 +00006702 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006703 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006704 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006705 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006706 (N0.getOperand(0) == N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006707 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006708 N1, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006709 }
6710
Shuxin Yang93b1f122013-03-25 22:52:29 +00006711 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006712 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006713 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006714 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006715 N1.getOperand(0) == N0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006716 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006717 N0, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006718 }
6719
Stephen Lin4e69d012013-06-14 21:33:58 +00006720 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
Shuxin Yang93b1f122013-03-25 22:52:29 +00006721 if (AllowNewFpConst &&
6722 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Owen Andersoncc61f872012-08-30 23:35:16 +00006723 N0.getOperand(0) == N0.getOperand(1) &&
6724 N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006725 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006726 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006727 N0.getOperand(0),
6728 DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006729 }
6730
Lang Hames39fb1d02012-06-19 22:51:23 +00006731 // FADD -> FMA combines:
Sanjay Patel78614bf2014-08-28 15:53:16 +00006732 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
Eric Christopherd9134482014-08-04 21:25:23 +00006733 DAG.getTarget()
6734 .getSubtargetImpl()
6735 ->getTargetLowering()
6736 ->isFMAFasterThanFMulAndFAdd(VT) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006737 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006738
6739 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Stephen Lin8e8424e2013-07-09 00:44:49 +00006740 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006741 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006742 N0.getOperand(0), N0.getOperand(1), N1);
Owen Andersoncc61f872012-08-30 23:35:16 +00006743
Michael Liaoec3850122012-09-01 04:09:16 +00006744 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hames39fb1d02012-06-19 22:51:23 +00006745 // Note: Commutes FADD operands.
Stephen Lin8e8424e2013-07-09 00:44:49 +00006746 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006747 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006748 N1.getOperand(0), N1.getOperand(1), N0);
Lang Hames39fb1d02012-06-19 22:51:23 +00006749 }
6750
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006751 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006752}
6753
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006754SDValue DAGCombiner::visitFSUB(SDNode *N) {
6755 SDValue N0 = N->getOperand(0);
6756 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006757 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6758 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006759 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006760 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006761 const TargetOptions &Options = DAG.getTarget().Options;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006762
Dan Gohmana8665142007-06-25 16:23:39 +00006763 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006764 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006765 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006766 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006767 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006768
Nate Begeman418c6e42005-10-18 00:28:13 +00006769 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006770 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006771 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Sanjay Patelae402a32014-08-27 20:57:52 +00006772
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006773 // fold (fsub A, (fneg B)) -> (fadd A, B)
Sanjay Patel78614bf2014-08-28 15:53:16 +00006774 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006775 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006776 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006777
Sanjay Patelae402a32014-08-27 20:57:52 +00006778 // If 'unsafe math' is enabled, fold lots of things.
Sanjay Patel78614bf2014-08-28 15:53:16 +00006779 if (Options.UnsafeFPMath) {
Sanjay Patelae402a32014-08-27 20:57:52 +00006780 // (fsub A, 0) -> A
6781 if (N1CFP && N1CFP->getValueAPF().isZero())
6782 return N0;
6783
6784 // (fsub 0, B) -> -B
6785 if (N0CFP && N0CFP->getValueAPF().isZero()) {
Sanjay Patel78614bf2014-08-28 15:53:16 +00006786 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Sanjay Patelae402a32014-08-27 20:57:52 +00006787 return GetNegatedExpression(N1, DAG, LegalOperations);
6788 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6789 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6790 }
6791
6792 // (fsub x, x) -> 0.0
Owen Andersonab63d842012-05-07 20:51:25 +00006793 if (N0 == N1)
6794 return DAG.getConstantFP(0.0f, VT);
6795
Sanjay Patelae402a32014-08-27 20:57:52 +00006796 // (fsub x, (fadd x, y)) -> (fneg y)
6797 // (fsub x, (fadd y, x)) -> (fneg y)
Bill Wendlingdf170db2012-03-15 05:12:00 +00006798 if (N1.getOpcode() == ISD::FADD) {
6799 SDValue N10 = N1->getOperand(0);
6800 SDValue N11 = N1->getOperand(1);
6801
Sanjay Patel78614bf2014-08-28 15:53:16 +00006802 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006803 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00006804
Sanjay Patel78614bf2014-08-28 15:53:16 +00006805 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006806 return GetNegatedExpression(N10, DAG, LegalOperations);
6807 }
6808 }
6809
Lang Hames39fb1d02012-06-19 22:51:23 +00006810 // FSUB -> FMA combines:
Sanjay Patel78614bf2014-08-28 15:53:16 +00006811 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
Sanjay Patela828f2b2014-08-27 20:40:31 +00006812 DAG.getTarget().getSubtargetImpl()
Eric Christopherd9134482014-08-04 21:25:23 +00006813 ->getTargetLowering()
6814 ->isFMAFasterThanFMulAndFAdd(VT) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006815 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006816
6817 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006818 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006819 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006820 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006821 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hames39fb1d02012-06-19 22:51:23 +00006822
6823 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6824 // Note: Commutes FSUB operands.
Stephen Lin10947502013-07-10 20:47:39 +00006825 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006826 return DAG.getNode(ISD::FMA, dl, VT,
6827 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006828 N1.getOperand(0)),
6829 N1.getOperand(1), N0);
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006830
Stephen Lin8e8424e2013-07-09 00:44:49 +00006831 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lincfe7f352013-07-08 00:37:03 +00006832 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006833 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6834 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6835 SDValue N00 = N0.getOperand(0).getOperand(0);
6836 SDValue N01 = N0.getOperand(0).getOperand(1);
6837 return DAG.getNode(ISD::FMA, dl, VT,
6838 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6839 DAG.getNode(ISD::FNEG, dl, VT, N1));
6840 }
Lang Hames39fb1d02012-06-19 22:51:23 +00006841 }
6842
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006843 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006844}
6845
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006846SDValue DAGCombiner::visitFMUL(SDNode *N) {
6847 SDValue N0 = N->getOperand(0);
6848 SDValue N1 = N->getOperand(1);
Matt Arsenault6cc00422014-08-16 10:14:19 +00006849 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6850 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006851 EVT VT = N->getValueType(0);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006852 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00006853
Dan Gohmana8665142007-06-25 16:23:39 +00006854 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006855 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006856 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006857 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006858 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006859
Nate Begemanec48a1b2005-10-17 20:40:11 +00006860 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006861 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006862 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006863 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00006864 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006865 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Bill Wendling3dc5d242009-01-30 22:57:07 +00006866 // fold (fmul A, 0) -> 0
Sanjay Patel78614bf2014-08-28 15:53:16 +00006867 if (Options.UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006868 return N1;
Owen Andersonb5f167c2012-05-02 21:32:35 +00006869 // fold (fmul A, 1.0) -> A
6870 if (N1CFP && N1CFP->isExactlyValue(1.0))
6871 return N0;
Matt Arsenault6cc00422014-08-16 10:14:19 +00006872
Nate Begemanec48a1b2005-10-17 20:40:11 +00006873 // fold (fmul X, 2.0) -> (fadd X, X)
6874 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006875 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Dan Gohmanb7170912009-08-10 16:50:32 +00006876 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00006877 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00006878 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006879 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006880
Bill Wendling3dc5d242009-01-30 22:57:07 +00006881 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00006882 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
6883 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006884 // Both can be negated for free, check to see if at least one is cheaper
6885 // negated.
6886 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006887 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006888 GetNegatedExpression(N0, DAG, LegalOperations),
6889 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006890 }
6891 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006892
Chris Lattner0199fd62007-01-08 23:04:05 +00006893 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Sanjay Patel78614bf2014-08-28 15:53:16 +00006894 if (Options.UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
Matt Arsenault6cc00422014-08-16 10:14:19 +00006895 N0.getNode()->hasOneUse() && isConstOrConstSplatFP(N0.getOperand(1))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006896 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6897 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Dale Johannesen400dc2e2009-02-06 21:50:26 +00006898 N0.getOperand(1), N1));
Matt Arsenault6cc00422014-08-16 10:14:19 +00006899 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006900
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006901 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006902}
6903
Owen Anderson41b06652012-05-02 22:17:40 +00006904SDValue DAGCombiner::visitFMA(SDNode *N) {
6905 SDValue N0 = N->getOperand(0);
6906 SDValue N1 = N->getOperand(1);
6907 SDValue N2 = N->getOperand(2);
6908 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6909 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6910 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006911 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006912 const TargetOptions &Options = DAG.getTarget().Options;
Owen Anderson9d5a8c22014-08-02 08:45:33 +00006913
6914 // Constant fold FMA.
6915 if (isa<ConstantFPSDNode>(N0) &&
6916 isa<ConstantFPSDNode>(N1) &&
6917 isa<ConstantFPSDNode>(N2)) {
6918 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6919 }
6920
Sanjay Patel78614bf2014-08-28 15:53:16 +00006921 if (Options.UnsafeFPMath) {
Owen Andersonb351c8d2012-11-01 02:00:53 +00006922 if (N0CFP && N0CFP->isZero())
6923 return N2;
6924 if (N1CFP && N1CFP->isZero())
6925 return N2;
6926 }
Owen Anderson41b06652012-05-02 22:17:40 +00006927 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006928 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006929 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006930 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006931
Owen Andersonc7aaf522012-05-30 18:50:39 +00006932 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00006933 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006934 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00006935
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006936 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
Sanjay Patel78614bf2014-08-28 15:53:16 +00006937 if (Options.UnsafeFPMath && N1CFP &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006938 N2.getOpcode() == ISD::FMUL &&
6939 N0 == N2.getOperand(0) &&
6940 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6941 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6942 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6943 }
6944
6945
6946 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00006947 if (Options.UnsafeFPMath &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006948 N0.getOpcode() == ISD::FMUL && N1CFP &&
6949 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6950 return DAG.getNode(ISD::FMA, dl, VT,
6951 N0.getOperand(0),
6952 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6953 N2);
6954 }
6955
6956 // (fma x, 1, y) -> (fadd x, y)
6957 // (fma x, -1, y) -> (fadd (fneg x), y)
6958 if (N1CFP) {
6959 if (N1CFP->isExactlyValue(1.0))
6960 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6961
6962 if (N1CFP->isExactlyValue(-1.0) &&
6963 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6964 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006965 AddToWorklist(RHSNeg.getNode());
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006966 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6967 }
6968 }
6969
6970 // (fma x, c, x) -> (fmul x, (c+1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00006971 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
Stephen Lin8e8424e2013-07-09 00:44:49 +00006972 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006973 DAG.getNode(ISD::FADD, dl, VT,
6974 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006975
6976 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00006977 if (Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006978 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6979 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006980 DAG.getNode(ISD::FADD, dl, VT,
6981 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006982
6983
Owen Anderson41b06652012-05-02 22:17:40 +00006984 return SDValue();
6985}
6986
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006987SDValue DAGCombiner::visitFDIV(SDNode *N) {
6988 SDValue N0 = N->getOperand(0);
6989 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006990 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6991 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006992 EVT VT = N->getValueType(0);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006993 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00006994
Dan Gohmana8665142007-06-25 16:23:39 +00006995 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006996 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006997 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006998 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006999 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007000
Nate Begeman569c4392006-01-18 22:35:16 +00007001 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007002 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007003 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007004
Duncan Sands2f1dc382012-04-08 18:08:12 +00007005 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
Sanjay Patel78614bf2014-08-28 15:53:16 +00007006 if (N1CFP && Options.UnsafeFPMath) {
Duncan Sands5f8397a2012-04-07 20:04:00 +00007007 // Compute the reciprocal 1.0 / c2.
7008 APFloat N1APF = N1CFP->getValueAPF();
7009 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7010 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
Duncan Sands4f530742012-04-10 20:35:27 +00007011 // Only do the transform if the reciprocal is a legal fp immediate that
7012 // isn't too nasty (eg NaN, denormal, ...).
7013 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
Anton Korobeynikov4d1220d2012-04-10 13:22:49 +00007014 (!LegalOperations ||
7015 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7016 // backend)... we should handle this gracefully after Legalize.
7017 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7018 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7019 TLI.isFPImmLegal(Recip, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007020 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
Duncan Sands5f8397a2012-04-07 20:04:00 +00007021 DAG.getConstantFP(Recip, VT));
7022 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007023
Bill Wendling3dc5d242009-01-30 22:57:07 +00007024 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007025 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7026 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00007027 // Both can be negated for free, check to see if at least one is cheaper
7028 // negated.
7029 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007030 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007031 GetNegatedExpression(N0, DAG, LegalOperations),
7032 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00007033 }
7034 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007035
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007036 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007037}
7038
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007039SDValue DAGCombiner::visitFREM(SDNode *N) {
7040 SDValue N0 = N->getOperand(0);
7041 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007042 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7043 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007044 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00007045
Nate Begeman569c4392006-01-18 22:35:16 +00007046 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007047 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007048 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00007049
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007050 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007051}
7052
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007053SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7054 SDValue N0 = N->getOperand(0);
7055 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007056 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7057 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007058 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00007059
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007060 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00007061 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007062
Chris Lattner3bc40502006-03-05 05:30:57 +00007063 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00007064 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00007065 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7066 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00007067 if (!V.isNegative()) {
7068 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007069 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00007070 } else {
7071 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007072 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7073 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00007074 }
Chris Lattner3bc40502006-03-05 05:30:57 +00007075 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007076
Chris Lattner3bc40502006-03-05 05:30:57 +00007077 // copysign(fabs(x), y) -> copysign(x, y)
7078 // copysign(fneg(x), y) -> copysign(x, y)
7079 // copysign(copysign(x,z), y) -> copysign(x, y)
7080 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7081 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007082 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007083 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007084
7085 // copysign(x, abs(y)) -> abs(x)
7086 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007087 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007088
Chris Lattner3bc40502006-03-05 05:30:57 +00007089 // copysign(x, copysign(y,z)) -> copysign(x, z)
7090 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007091 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007092 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007093
Chris Lattner3bc40502006-03-05 05:30:57 +00007094 // copysign(x, fp_extend(y)) -> copysign(x, y)
7095 // copysign(x, fp_round(y)) -> copysign(x, y)
7096 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007097 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007098 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007099
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007100 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00007101}
7102
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007103SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7104 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007105 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007106 EVT VT = N->getValueType(0);
7107 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007108
Nate Begeman21158fc2005-09-01 00:19:25 +00007109 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007110 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007111 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007112 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007113 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007114 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007115
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007116 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7117 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007118 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7119 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007120 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007121 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007122 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007123 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007124
Alp Tokercb402912014-01-24 17:20:08 +00007125 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007126 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007127 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7128 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7129 !VT.isVector() &&
7130 (!LegalOperations ||
7131 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7132 SDValue Ops[] =
7133 { N0.getOperand(0), N0.getOperand(1),
7134 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7135 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007136 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007137 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007138
Nadav Rotem90560762012-07-23 07:59:50 +00007139 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7140 // (select_cc x, y, 1.0, 0.0,, cc)
7141 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7142 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7143 (!LegalOperations ||
7144 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7145 SDValue Ops[] =
7146 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7147 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7148 N0.getOperand(0).getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007149 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007150 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007151 }
7152
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007153 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007154}
7155
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007156SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7157 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007158 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007159 EVT VT = N->getValueType(0);
7160 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00007161
Nate Begeman21158fc2005-09-01 00:19:25 +00007162 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007163 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007164 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007165 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007166 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007167 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007168
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007169 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7170 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007171 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7172 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007173 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007174 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007175 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007176 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007177
Alp Tokercb402912014-01-24 17:20:08 +00007178 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007179 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007180 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00007181
Nadav Rotem90560762012-07-23 07:59:50 +00007182 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7183 (!LegalOperations ||
7184 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7185 SDValue Ops[] =
7186 { N0.getOperand(0), N0.getOperand(1),
7187 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7188 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007189 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007190 }
7191 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007192
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007193 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007194}
7195
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007196SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7197 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007198 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007199 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007200
Nate Begeman21158fc2005-09-01 00:19:25 +00007201 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007202 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007203 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007204
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007205 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007206}
7207
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007208SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7209 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007210 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007211 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007212
Nate Begeman21158fc2005-09-01 00:19:25 +00007213 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007214 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007215 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007216
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007217 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007218}
7219
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007220SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7221 SDValue N0 = N->getOperand(0);
7222 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007223 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007224 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007225
Nate Begeman21158fc2005-09-01 00:19:25 +00007226 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007227 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007228 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007229
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007230 // fold (fp_round (fp_extend x)) -> x
7231 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7232 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007233
Chris Lattner0feb1b02008-01-24 06:45:35 +00007234 // fold (fp_round (fp_round x)) -> (fp_round x)
7235 if (N0.getOpcode() == ISD::FP_ROUND) {
7236 // This is a value preserving truncation if both round's are.
7237 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00007238 N0.getNode()->getConstantOperandVal(1) == 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00007239 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0feb1b02008-01-24 06:45:35 +00007240 DAG.getIntPtrConstant(IsTrunc));
7241 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007242
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007243 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00007244 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007245 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007246 N0.getOperand(0), N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007247 AddToWorklist(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007248 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007249 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007250 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007251
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007252 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007253}
7254
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007255SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7256 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007257 EVT VT = N->getValueType(0);
7258 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007259 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007260
Nate Begeman21158fc2005-09-01 00:19:25 +00007261 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00007262 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00007263 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007264 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00007265 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007266
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007267 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007268}
7269
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007270SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7271 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007272 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007273 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007274
Chris Lattner5919b482007-12-29 06:55:23 +00007275 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007276 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00007277 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007278 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00007279
Nate Begeman21158fc2005-09-01 00:19:25 +00007280 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007281 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007282 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00007283
7284 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7285 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00007286 if (N0.getOpcode() == ISD::FP_ROUND
7287 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007288 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00007289 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00007290 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007291 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007292 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00007293 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00007294 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007295
Chris Lattner72733e52008-01-17 07:00:52 +00007296 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00007297 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover7f3e11e2014-07-16 15:37:24 +00007298 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007299 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007300 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007301 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007302 LN0->getBasePtr(), N0.getValueType(),
7303 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00007304 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00007305 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007306 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00007307 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00007308 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007309 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00007310 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00007311
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007312 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007313}
7314
Sanjay Patelccd26762014-08-28 21:51:37 +00007315SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7316 SDValue N0 = N->getOperand(0);
7317 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7318 EVT VT = N->getValueType(0);
7319
7320 // fold (fceil c1) -> fceil(c1)
7321 if (N0CFP)
7322 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7323
7324 return SDValue();
7325}
7326
7327SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7328 SDValue N0 = N->getOperand(0);
7329 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7330 EVT VT = N->getValueType(0);
7331
7332 // fold (ftrunc c1) -> ftrunc(c1)
7333 if (N0CFP)
7334 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7335
7336 return SDValue();
7337}
7338
7339SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7340 SDValue N0 = N->getOperand(0);
7341 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7342 EVT VT = N->getValueType(0);
7343
7344 // fold (ffloor c1) -> ffloor(c1)
7345 if (N0CFP)
7346 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7347
7348 return SDValue();
7349}
7350
7351// FIXME: FNEG and FABS have a lot in common; refactor.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007352SDValue DAGCombiner::visitFNEG(SDNode *N) {
7353 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007354 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007355
Craig Topper82384612012-09-11 01:45:21 +00007356 if (VT.isVector()) {
7357 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7358 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper03f39772012-09-09 22:58:45 +00007359 }
7360
Sanjay Patelccd26762014-08-28 21:51:37 +00007361 // Constant fold FNEG.
7362 if (isa<ConstantFPSDNode>(N0))
7363 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7364
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007365 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7366 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007367 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00007368
Sanjay Patel35d31332014-08-14 15:15:28 +00007369 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00007370 // constant pool values.
Sanjay Patelccd26762014-08-28 21:51:37 +00007371 if (!TLI.isFNegFree(VT) &&
7372 N0.getOpcode() == ISD::BITCAST &&
Sanjay Patel35d31332014-08-14 15:15:28 +00007373 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007374 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007375 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007376 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel35d31332014-08-14 15:15:28 +00007377 APInt SignMask;
7378 if (N0.getValueType().isVector()) {
7379 // For a vector, get a mask such as 0x80... per scalar element
7380 // and splat it.
7381 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7382 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7383 } else {
7384 // For a scalar, just generate 0x80...
7385 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7386 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00007387 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Sanjay Patel35d31332014-08-14 15:15:28 +00007388 DAG.getConstant(SignMask, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007389 AddToWorklist(Int.getNode());
Sanjay Patel35d31332014-08-14 15:15:28 +00007390 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007391 }
7392 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007393
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007394 // (fneg (fmul c, x)) -> (fmul -c, x)
7395 if (N0.getOpcode() == ISD::FMUL) {
7396 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Tim Northover820e0412014-05-02 17:25:02 +00007397 if (CFP1) {
7398 APFloat CVal = CFP1->getValueAPF();
7399 CVal.changeSign();
7400 if (Level >= AfterLegalizeDAG &&
7401 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7402 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7403 return DAG.getNode(
7404 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7405 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7406 }
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007407 }
7408
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007409 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007410}
7411
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007412SDValue DAGCombiner::visitFABS(SDNode *N) {
7413 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007414 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007415
Craig Topper82384612012-09-11 01:45:21 +00007416 if (VT.isVector()) {
7417 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7418 if (FoldedVOp.getNode()) return FoldedVOp;
7419 }
7420
Nate Begeman21158fc2005-09-01 00:19:25 +00007421 // fold (fabs c1) -> fabs(c1)
Sanjay Patelccd26762014-08-28 21:51:37 +00007422 if (isa<ConstantFPSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007423 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Sanjay Patelccd26762014-08-28 21:51:37 +00007424
Nate Begeman21158fc2005-09-01 00:19:25 +00007425 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007426 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00007427 return N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00007428
Nate Begeman21158fc2005-09-01 00:19:25 +00007429 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007430 // fold (fabs (fcopysign x, y)) -> (fabs x)
7431 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007432 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007433
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007434 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00007435 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00007436 if (!TLI.isFAbsFree(VT) &&
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007437 N0.getOpcode() == ISD::BITCAST &&
7438 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007439 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007440 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007441 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007442 APInt SignMask;
7443 if (N0.getValueType().isVector()) {
7444 // For a vector, get a mask such as 0x7f... per scalar element
7445 // and splat it.
7446 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7447 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7448 } else {
7449 // For a scalar, just generate 0x7f...
7450 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7451 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00007452 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007453 DAG.getConstant(SignMask, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007454 AddToWorklist(Int.getNode());
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007455 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007456 }
7457 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007458
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007459 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007460}
7461
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007462SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7463 SDValue Chain = N->getOperand(0);
7464 SDValue N1 = N->getOperand(1);
7465 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007466
Dan Gohman82e80012009-11-17 00:47:23 +00007467 // If N is a constant we could fold this into a fallthrough or unconditional
7468 // branch. However that doesn't happen very often in normal code, because
7469 // Instcombine/SimplifyCFG should have handled the available opportunities.
7470 // If we did this folding here, it would be necessary to update the
7471 // MachineBasicBlock CFG, which is awkward.
7472
Nate Begeman7e7f4392006-02-01 07:19:44 +00007473 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7474 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007475 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00007476 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7477 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007478 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007479 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00007480 N1.getOperand(0), N1.getOperand(1), N2);
7481 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007482
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007483 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7484 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7485 (N1.getOperand(0).hasOneUse() &&
7486 N1.getOperand(0).getOpcode() == ISD::SRL))) {
Craig Topperc0196b12014-04-14 00:51:57 +00007487 SDNode *Trunc = nullptr;
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007488 if (N1.getOpcode() == ISD::TRUNCATE) {
7489 // Look pass the truncate.
7490 Trunc = N1.getNode();
7491 N1 = N1.getOperand(0);
7492 }
Evan Cheng166a4e62010-01-06 19:38:29 +00007493
Bill Wendlingaa28be62009-03-26 06:14:09 +00007494 // Match this pattern so that we can generate simpler code:
7495 //
7496 // %a = ...
7497 // %b = and i32 %a, 2
7498 // %c = srl i32 %b, 1
7499 // brcond i32 %c ...
7500 //
7501 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00007502 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00007503 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00007504 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00007505 // %c = setcc eq %b, 0
7506 // brcond %c ...
7507 //
7508 // This applies only when the AND constant value has one bit set and the
7509 // SRL constant is equal to the log2 of the AND constant. The back-end is
7510 // smart enough to convert the result into a TEST/JMP sequence.
7511 SDValue Op0 = N1.getOperand(0);
7512 SDValue Op1 = N1.getOperand(1);
7513
7514 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00007515 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00007516 SDValue AndOp1 = Op0.getOperand(1);
7517
7518 if (AndOp1.getOpcode() == ISD::Constant) {
7519 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7520
7521 if (AndConst.isPowerOf2() &&
7522 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7523 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007524 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00007525 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00007526 Op0, DAG.getConstant(0, Op0.getValueType()),
7527 ISD::SETNE);
7528
Andrew Trickef9de2a2013-05-25 02:42:55 +00007529 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00007530 MVT::Other, Chain, SetCC, N2);
7531 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7532 // will convert it back to (X & C1) >> C2.
7533 CombineTo(N, NewBRCond, false);
7534 // Truncate is dead.
Chandler Carruth18066972014-08-02 10:02:07 +00007535 if (Trunc)
7536 deleteAndRecombine(Trunc);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007537 // Replace the uses of SRL with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007538 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007539 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00007540 deleteAndRecombine(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00007541 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00007542 }
7543 }
7544 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007545
7546 if (Trunc)
7547 // Restore N1 if the above transformation doesn't match.
7548 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007549 }
Wesley Peck527da1b2010-11-23 03:31:01 +00007550
Evan Cheng228c31f2010-02-27 07:36:59 +00007551 // Transform br(xor(x, y)) -> br(x != y)
7552 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7553 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7554 SDNode *TheXor = N1.getNode();
7555 SDValue Op0 = TheXor->getOperand(0);
7556 SDValue Op1 = TheXor->getOperand(1);
7557 if (Op0.getOpcode() == Op1.getOpcode()) {
7558 // Avoid missing important xor optimizations.
7559 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007560 if (Tmp.getNode()) {
7561 if (Tmp.getNode() != TheXor) {
7562 DEBUG(dbgs() << "\nReplacing.8 ";
7563 TheXor->dump(&DAG);
7564 dbgs() << "\nWith: ";
7565 Tmp.getNode()->dump(&DAG);
7566 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007567 WorklistRemover DeadNodes(*this);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007568 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
Chandler Carruth18066972014-08-02 10:02:07 +00007569 deleteAndRecombine(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007570 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00007571 MVT::Other, Chain, Tmp, N2);
7572 }
7573
Benjamin Kramer93354432013-03-30 21:28:18 +00007574 // visitXOR has changed XOR's operands or replaced the XOR completely,
7575 // bail out.
7576 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00007577 }
7578 }
7579
7580 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7581 bool Equal = false;
7582 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7583 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7584 Op0.getOpcode() == ISD::XOR) {
7585 TheXor = Op0.getNode();
7586 Equal = true;
7587 }
7588
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007589 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00007590 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00007591 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007592 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00007593 SetCCVT,
7594 Op0, Op1,
7595 Equal ? ISD::SETEQ : ISD::SETNE);
7596 // Replace the uses of XOR with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007597 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007598 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00007599 deleteAndRecombine(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007600 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00007601 MVT::Other, Chain, SetCC, N2);
7602 }
7603 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007604
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007605 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007606}
7607
Chris Lattnera49e16f2005-10-05 06:47:48 +00007608// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7609//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007610SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00007611 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007612 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007613
Dan Gohman82e80012009-11-17 00:47:23 +00007614 // If N is a constant we could fold this into a fallthrough or unconditional
7615 // branch. However that doesn't happen very often in normal code, because
7616 // Instcombine/SimplifyCFG should have handled the available opportunities.
7617 // If we did this folding here, it would be necessary to update the
7618 // MachineBasicBlock CFG, which is awkward.
7619
Duncan Sands93b66092008-06-09 11:32:28 +00007620 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00007621 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007622 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00007623 false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007624 if (Simp.getNode()) AddToWorklist(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00007625
Nate Begemanbd7df032005-10-05 21:43:42 +00007626 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00007627 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007628 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007629 N->getOperand(0), Simp.getOperand(2),
7630 Simp.getOperand(0), Simp.getOperand(1),
7631 N->getOperand(4));
7632
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007633 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007634}
7635
Sanjay Patel50cbfc52014-08-28 16:29:51 +00007636/// Return true if 'Use' is a load or a store that uses N as its base pointer
7637/// and that N may be folded in the load / store addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00007638static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7639 SelectionDAG &DAG,
7640 const TargetLowering &TLI) {
7641 EVT VT;
7642 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7643 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7644 return false;
7645 VT = Use->getValueType(0);
7646 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7647 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7648 return false;
7649 VT = ST->getValue().getValueType();
7650 } else
7651 return false;
7652
Chandler Carruth95f83e02013-01-07 15:14:13 +00007653 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00007654 if (N->getOpcode() == ISD::ADD) {
7655 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7656 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007657 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007658 AM.BaseOffs = Offset->getSExtValue();
7659 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007660 // [reg +/- reg]
7661 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007662 } else if (N->getOpcode() == ISD::SUB) {
7663 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7664 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007665 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007666 AM.BaseOffs = -Offset->getSExtValue();
7667 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007668 // [reg +/- reg]
7669 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007670 } else
7671 return false;
7672
7673 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7674}
7675
Sanjay Patel50cbfc52014-08-28 16:29:51 +00007676/// Try turning a load/store into a pre-indexed load/store when the base
7677/// pointer is an add or subtract and it has other uses besides the load/store.
7678/// After the transformation, the new indexed load/store has effectively folded
7679/// the add/subtract in and all of its other uses are redirected to the
7680/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00007681bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007682 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007683 return false;
7684
7685 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007686 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007687 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007688 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007689 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007690 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007691 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00007692 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00007693 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7694 return false;
7695 Ptr = LD->getBasePtr();
7696 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007697 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007698 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007699 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007700 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7701 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7702 return false;
7703 Ptr = ST->getBasePtr();
7704 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007705 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007706 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007707 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007708
Chris Lattnereabc15c2006-11-11 00:56:29 +00007709 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7710 // out. There is no reason to make this a preinc/predec.
7711 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00007712 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007713 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007714
Chris Lattnereabc15c2006-11-11 00:56:29 +00007715 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007716 SDValue BasePtr;
7717 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007718 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7719 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7720 return false;
Hal Finkel25819052013-02-08 21:35:47 +00007721
7722 // Backends without true r+i pre-indexed forms may need to pass a
7723 // constant base with a variable offset so that constant coercion
7724 // will work with the patterns in canonical form.
7725 bool Swapped = false;
7726 if (isa<ConstantSDNode>(BasePtr)) {
7727 std::swap(BasePtr, Offset);
7728 Swapped = true;
7729 }
7730
Evan Cheng044a0a82007-05-03 23:52:19 +00007731 // Don't create a indexed load / store with zero offset.
7732 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007733 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007734 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007735
Chris Lattnera0a80032006-11-11 01:00:15 +00007736 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00007737 // 1) The new base ptr is a frame index.
7738 // 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 +00007739 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00007740 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00007741 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00007742 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00007743
Chris Lattnera0a80032006-11-11 01:00:15 +00007744 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7745 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00007746 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00007747 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007748
Chris Lattnera0a80032006-11-11 01:00:15 +00007749 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007750 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007751 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00007752 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007753 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007754 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007755
Hal Finkel25819052013-02-08 21:35:47 +00007756 // If the offset is a constant, there may be other adds of constants that
7757 // can be folded with this one. We should do this to avoid having to keep
7758 // a copy of the original base pointer.
7759 SmallVector<SDNode *, 16> OtherUses;
7760 if (isa<ConstantSDNode>(Offset))
Jim Grosbache8160032014-04-11 01:13:13 +00007761 for (SDNode *Use : BasePtr.getNode()->uses()) {
Hal Finkel25819052013-02-08 21:35:47 +00007762 if (Use == Ptr.getNode())
7763 continue;
7764
7765 if (Use->isPredecessorOf(N))
7766 continue;
7767
7768 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7769 OtherUses.clear();
7770 break;
7771 }
7772
7773 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7774 if (Op1.getNode() == BasePtr.getNode())
7775 std::swap(Op0, Op1);
7776 assert(Op0.getNode() == BasePtr.getNode() &&
7777 "Use of ADD/SUB but not an operand");
7778
7779 if (!isa<ConstantSDNode>(Op1)) {
7780 OtherUses.clear();
7781 break;
7782 }
7783
7784 // FIXME: In some cases, we can be smarter about this.
7785 if (Op1.getValueType() != Offset.getValueType()) {
7786 OtherUses.clear();
7787 break;
7788 }
7789
7790 OtherUses.push_back(Use);
7791 }
7792
7793 if (Swapped)
7794 std::swap(BasePtr, Offset);
7795
Evan Chenga4d187b2007-05-24 02:35:39 +00007796 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007797 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00007798
7799 // Caches for hasPredecessorHelper
7800 SmallPtrSet<const SDNode *, 32> Visited;
7801 SmallVector<const SDNode *, 16> Worklist;
7802
Jim Grosbache8160032014-04-11 01:13:13 +00007803 for (SDNode *Use : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007804 if (Use == N)
7805 continue;
Lang Hames5a004992011-07-07 04:31:51 +00007806 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007807 return false;
7808
Evan Chengfa832632012-01-13 01:37:24 +00007809 // If Ptr may be folded in addressing mode of other use, then it's
7810 // not profitable to do this transformation.
7811 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007812 RealUse = true;
7813 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007814
Chris Lattnereabc15c2006-11-11 00:56:29 +00007815 if (!RealUse)
7816 return false;
7817
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007818 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007819 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007820 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007821 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007822 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00007823 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007824 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007825 ++PreIndexedNodes;
7826 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007827 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007828 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007829 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007830 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007831 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007832 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007833 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007834 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7835 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007836 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007837 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007838 }
7839
Chris Lattnereabc15c2006-11-11 00:56:29 +00007840 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00007841 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007842
Hal Finkel25819052013-02-08 21:35:47 +00007843 if (Swapped)
7844 std::swap(BasePtr, Offset);
7845
7846 // Replace other uses of BasePtr that can be updated to use Ptr
7847 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7848 unsigned OffsetIdx = 1;
7849 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7850 OffsetIdx = 0;
7851 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7852 BasePtr.getNode() && "Expected BasePtr operand");
7853
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007854 // We need to replace ptr0 in the following expression:
7855 // x0 * offset0 + y0 * ptr0 = t0
7856 // knowing that
7857 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00007858 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007859 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7860 // indexed load/store and the expresion that needs to be re-written.
7861 //
7862 // Therefore, we have:
7863 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00007864
7865 ConstantSDNode *CN =
7866 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007867 int X0, X1, Y0, Y1;
7868 APInt Offset0 = CN->getAPIntValue();
7869 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00007870
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007871 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7872 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7873 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7874 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00007875
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007876 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7877
7878 APInt CNV = Offset0;
7879 if (X0 < 0) CNV = -CNV;
7880 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7881 else CNV = CNV - Offset1;
7882
7883 // We can now generate the new expression.
7884 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7885 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7886
7887 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00007888 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00007889 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7890 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
Chandler Carruth18066972014-08-02 10:02:07 +00007891 deleteAndRecombine(OtherUses[i]);
Hal Finkel25819052013-02-08 21:35:47 +00007892 }
7893
Chris Lattnereabc15c2006-11-11 00:56:29 +00007894 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007895 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00007896 deleteAndRecombine(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00007897
7898 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007899}
7900
Sanjay Patel50cbfc52014-08-28 16:29:51 +00007901/// Try to combine a load/store with a add/sub of the base pointer node into a
7902/// post-indexed load/store. The transformation folded the add/subtract into the
7903/// new indexed load/store effectively and all of its uses are redirected to the
7904/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00007905bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007906 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007907 return false;
7908
7909 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007910 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007911 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007912 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007913 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007914 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007915 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007916 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7917 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7918 return false;
7919 Ptr = LD->getBasePtr();
7920 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007921 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007922 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007923 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007924 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7925 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7926 return false;
7927 Ptr = ST->getBasePtr();
7928 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007929 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007930 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007931 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007932
Gabor Greiff304a7a2008-08-28 21:40:38 +00007933 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007934 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007935
Jim Grosbache8160032014-04-11 01:13:13 +00007936 for (SDNode *Op : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007937 if (Op == N ||
7938 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7939 continue;
7940
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007941 SDValue BasePtr;
7942 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007943 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7944 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00007945 // Don't create a indexed load / store with zero offset.
7946 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007947 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007948 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007949
Chris Lattnereabc15c2006-11-11 00:56:29 +00007950 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00007951 // 1) All uses are load / store ops that use it as base ptr (and
7952 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00007953 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7954 // nor a successor of N. Otherwise, if Op is folded that would
7955 // create a cycle.
7956
Evan Chengcfc05132009-05-06 18:25:01 +00007957 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7958 continue;
7959
Chris Lattnereabc15c2006-11-11 00:56:29 +00007960 // Check for #1.
7961 bool TryNext = false;
Jim Grosbache8160032014-04-11 01:13:13 +00007962 for (SDNode *Use : BasePtr.getNode()->uses()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007963 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00007964 continue;
7965
Chris Lattnereabc15c2006-11-11 00:56:29 +00007966 // If all the uses are load / store addresses, then don't do the
7967 // transformation.
7968 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7969 bool RealUse = false;
Jim Grosbache8160032014-04-11 01:13:13 +00007970 for (SDNode *UseUse : Use->uses()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00007971 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007972 RealUse = true;
7973 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007974
Chris Lattnereabc15c2006-11-11 00:56:29 +00007975 if (!RealUse) {
7976 TryNext = true;
7977 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00007978 }
7979 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007980 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007981
Chris Lattnereabc15c2006-11-11 00:56:29 +00007982 if (TryNext)
7983 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007984
Chris Lattnereabc15c2006-11-11 00:56:29 +00007985 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00007986 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007987 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00007988 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007989 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007990 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007991 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007992 ++PostIndexedNodes;
7993 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007994 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007995 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007996 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007997 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007998 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007999 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008000 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008001 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8002 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00008003 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008004 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00008005 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00008006
Chris Lattnereabc15c2006-11-11 00:56:29 +00008007 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00008008 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008009
8010 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008011 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008012 Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00008013 deleteAndRecombine(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008014 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00008015 }
8016 }
8017 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008018
Chris Lattnerffad2162006-11-11 00:39:41 +00008019 return false;
8020}
8021
Hal Finkel51e6fa22014-09-02 06:24:04 +00008022/// \brief Return the base-pointer arithmetic from an indexed \p LD.
8023SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8024 ISD::MemIndexedMode AM = LD->getAddressingMode();
8025 assert(AM != ISD::UNINDEXED);
8026 SDValue BP = LD->getOperand(1);
8027 SDValue Inc = LD->getOperand(2);
Hal Finkele19006e2014-09-02 16:05:23 +00008028
8029 // Some backends use TargetConstants for load offsets, but don't expect
8030 // TargetConstants in general ADD nodes. We can convert these constants into
8031 // regular Constants (if the constant is not opaque).
8032 assert((Inc.getOpcode() != ISD::TargetConstant ||
8033 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8034 "Cannot split out indexing using opaque target constants");
8035 if (Inc.getOpcode() == ISD::TargetConstant) {
8036 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8037 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8038 ConstInc->getValueType(0));
8039 }
8040
Hal Finkel51e6fa22014-09-02 06:24:04 +00008041 unsigned Opc =
8042 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8043 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8044}
8045
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008046SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00008047 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008048 SDValue Chain = LD->getChain();
8049 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00008050
Evan Chenga684cd22007-05-01 00:38:21 +00008051 // If load is not volatile and there are no uses of the loaded value (and
8052 // the updated indexed value in case of indexed loads), change uses of the
8053 // chain value into uses of the chain input (i.e. delete the dead load).
8054 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00008055 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00008056 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00008057 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00008058 // It's not safe to use the two value CombineTo variant here. e.g.
8059 // v1, chain2 = load chain1, loc
8060 // v2, chain3 = load chain2, loc
8061 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00008062 // Now we replace use of chain2 with chain1. This makes the second load
8063 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00008064 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008065 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008066 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008067 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008068 dbgs() << "\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008069 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008070 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00008071
Chandler Carruth18066972014-08-02 10:02:07 +00008072 if (N->use_empty())
8073 deleteAndRecombine(N);
Bill Wendling306bfc22009-01-30 23:27:35 +00008074
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008075 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00008076 }
Evan Chengb68343c2007-05-01 08:53:39 +00008077 } else {
8078 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00008079 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Hal Finkel51e6fa22014-09-02 06:24:04 +00008080
Hal Finkele19006e2014-09-02 16:05:23 +00008081 // If this load has an opaque TargetConstant offset, then we cannot split
8082 // the indexing into an add/sub directly (that TargetConstant may not be
8083 // valid for a different type of node, and we cannot convert an opaque
8084 // target constant into a regular constant).
8085 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8086 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
Hal Finkel51e6fa22014-09-02 06:24:04 +00008087
8088 if (!N->hasAnyUseOfValue(0) &&
Hal Finkele19006e2014-09-02 16:05:23 +00008089 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
Dale Johannesen84935752009-02-06 23:05:02 +00008090 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Hal Finkel51e6fa22014-09-02 06:24:04 +00008091 SDValue Index;
Hal Finkele19006e2014-09-02 16:05:23 +00008092 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
Hal Finkel51e6fa22014-09-02 06:24:04 +00008093 Index = SplitIndexingFromLoad(LD);
8094 // Try to fold the base pointer arithmetic into subsequent loads and
8095 // stores.
8096 AddUsersToWorklist(N);
8097 } else
8098 Index = DAG.getUNDEF(N->getValueType(1));
Evan Cheng228c31f2010-02-27 07:36:59 +00008099 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008100 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008101 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008102 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008103 dbgs() << " and 2 other values\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008104 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008105 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Hal Finkel51e6fa22014-09-02 06:24:04 +00008106 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008107 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Chandler Carruth18066972014-08-02 10:02:07 +00008108 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008109 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00008110 }
Evan Chenga684cd22007-05-01 00:38:21 +00008111 }
8112 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008113
Chris Lattnere260ed82005-10-10 22:04:48 +00008114 // If this load is directly stored, replace the load value with the stored
8115 // value.
8116 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00008117 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00008118 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00008119 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00008120 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8121 if (PrevST->getBasePtr() == Ptr &&
8122 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00008123 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00008124 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00008125 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008126
Evan Cheng43cd9e32010-04-01 06:04:33 +00008127 // Try to infer better alignment information than the load already has.
8128 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00008129 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00008130 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8131 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00008132 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00008133 LD->getValueType(0),
8134 Chain, Ptr, LD->getPointerInfo(),
8135 LD->getMemoryVT(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00008136 LD->isVolatile(), LD->isNonTemporal(),
8137 LD->isInvariant(), Align, LD->getAAInfo());
Owen Andersonde89ecf2013-02-05 19:24:39 +00008138 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8139 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00008140 }
8141 }
8142
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00008143 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8144 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00008145#ifndef NDEBUG
8146 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8147 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8148 UseAA = false;
8149#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00008150 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00008151 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008152 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008153
Jim Laskey708d0db2006-10-04 16:53:27 +00008154 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00008155 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008156 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00008157
Jim Laskeyd07be232006-09-25 16:29:54 +00008158 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00008159 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008160 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008161 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008162 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008163 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00008164 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008165 BetterChain, Ptr, LD->getMemoryVT(),
8166 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008167 }
Jim Laskeyd07be232006-09-25 16:29:54 +00008168
Jim Laskey708d0db2006-10-04 16:53:27 +00008169 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008170 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00008171 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00008172
Nate Begeman879d8f12009-09-15 00:18:30 +00008173 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008174 AddToWorklist(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00008175
Jim Laskeydcf983c2006-10-13 23:32:28 +00008176 // Replace uses with load result and token factor. Don't add users
8177 // to work list.
8178 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00008179 }
8180 }
8181
Evan Cheng357017f2006-11-03 03:06:21 +00008182 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00008183 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008184 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00008185
Quentin Colombetde0e0622013-10-11 18:29:42 +00008186 // Try to slice up N to more direct loads if the slices are mapped to
8187 // different register banks or pairing can take place.
8188 if (SliceUpLoad(N))
8189 return SDValue(N, 0);
8190
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008191 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00008192}
8193
Quentin Colombetde0e0622013-10-11 18:29:42 +00008194namespace {
8195/// \brief Helper structure used to slice a load in smaller loads.
8196/// Basically a slice is obtained from the following sequence:
8197/// Origin = load Ty1, Base
8198/// Shift = srl Ty1 Origin, CstTy Amount
8199/// Inst = trunc Shift to Ty2
8200///
8201/// Then, it will be rewriten into:
8202/// Slice = load SliceTy, Base + SliceOffset
8203/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8204///
8205/// SliceTy is deduced from the number of bits that are actually used to
8206/// build Inst.
8207struct LoadedSlice {
8208 /// \brief Helper structure used to compute the cost of a slice.
8209 struct Cost {
8210 /// Are we optimizing for code size.
8211 bool ForCodeSize;
8212 /// Various cost.
8213 unsigned Loads;
8214 unsigned Truncates;
8215 unsigned CrossRegisterBanksCopies;
8216 unsigned ZExts;
8217 unsigned Shift;
8218
8219 Cost(bool ForCodeSize = false)
8220 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8221 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8222
8223 /// \brief Get the cost of one isolated slice.
8224 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8225 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8226 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8227 EVT TruncType = LS.Inst->getValueType(0);
8228 EVT LoadedType = LS.getLoadedType();
8229 if (TruncType != LoadedType &&
8230 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8231 ZExts = 1;
8232 }
8233
8234 /// \brief Account for slicing gain in the current cost.
8235 /// Slicing provide a few gains like removing a shift or a
8236 /// truncate. This method allows to grow the cost of the original
8237 /// load with the gain from this slice.
8238 void addSliceGain(const LoadedSlice &LS) {
8239 // Each slice saves a truncate.
8240 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8241 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8242 LS.Inst->getOperand(0).getValueType()))
8243 ++Truncates;
8244 // If there is a shift amount, this slice gets rid of it.
8245 if (LS.Shift)
8246 ++Shift;
8247 // If this slice can merge a cross register bank copy, account for it.
8248 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8249 ++CrossRegisterBanksCopies;
8250 }
8251
8252 Cost &operator+=(const Cost &RHS) {
8253 Loads += RHS.Loads;
8254 Truncates += RHS.Truncates;
8255 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8256 ZExts += RHS.ZExts;
8257 Shift += RHS.Shift;
8258 return *this;
8259 }
8260
8261 bool operator==(const Cost &RHS) const {
8262 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8263 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8264 ZExts == RHS.ZExts && Shift == RHS.Shift;
8265 }
8266
8267 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8268
8269 bool operator<(const Cost &RHS) const {
8270 // Assume cross register banks copies are as expensive as loads.
8271 // FIXME: Do we want some more target hooks?
8272 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8273 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8274 // Unless we are optimizing for code size, consider the
8275 // expensive operation first.
8276 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8277 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8278 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8279 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8280 }
8281
8282 bool operator>(const Cost &RHS) const { return RHS < *this; }
8283
8284 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8285
8286 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8287 };
8288 // The last instruction that represent the slice. This should be a
8289 // truncate instruction.
8290 SDNode *Inst;
8291 // The original load instruction.
8292 LoadSDNode *Origin;
8293 // The right shift amount in bits from the original load.
8294 unsigned Shift;
8295 // The DAG from which Origin came from.
8296 // This is used to get some contextual information about legal types, etc.
8297 SelectionDAG *DAG;
8298
Craig Topperc0196b12014-04-14 00:51:57 +00008299 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8300 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
Quentin Colombetde0e0622013-10-11 18:29:42 +00008301 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8302
8303 LoadedSlice(const LoadedSlice &LS)
8304 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8305
8306 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8307 /// \return Result is \p BitWidth and has used bits set to 1 and
8308 /// not used bits set to 0.
8309 APInt getUsedBits() const {
8310 // Reproduce the trunc(lshr) sequence:
8311 // - Start from the truncated value.
8312 // - Zero extend to the desired bit width.
8313 // - Shift left.
8314 assert(Origin && "No original load to compare against.");
8315 unsigned BitWidth = Origin->getValueSizeInBits(0);
8316 assert(Inst && "This slice is not bound to an instruction");
8317 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8318 "Extracted slice is bigger than the whole type!");
8319 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8320 UsedBits.setAllBits();
8321 UsedBits = UsedBits.zext(BitWidth);
8322 UsedBits <<= Shift;
8323 return UsedBits;
8324 }
8325
8326 /// \brief Get the size of the slice to be loaded in bytes.
8327 unsigned getLoadedSize() const {
8328 unsigned SliceSize = getUsedBits().countPopulation();
8329 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8330 return SliceSize / 8;
8331 }
8332
8333 /// \brief Get the type that will be loaded for this slice.
8334 /// Note: This may not be the final type for the slice.
8335 EVT getLoadedType() const {
8336 assert(DAG && "Missing context");
8337 LLVMContext &Ctxt = *DAG->getContext();
8338 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8339 }
8340
8341 /// \brief Get the alignment of the load used for this slice.
8342 unsigned getAlignment() const {
8343 unsigned Alignment = Origin->getAlignment();
8344 unsigned Offset = getOffsetFromBase();
8345 if (Offset != 0)
8346 Alignment = MinAlign(Alignment, Alignment + Offset);
8347 return Alignment;
8348 }
8349
8350 /// \brief Check if this slice can be rewritten with legal operations.
8351 bool isLegal() const {
8352 // An invalid slice is not legal.
8353 if (!Origin || !Inst || !DAG)
8354 return false;
8355
8356 // Offsets are for indexed load only, we do not handle that.
8357 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8358 return false;
8359
8360 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8361
8362 // Check that the type is legal.
8363 EVT SliceType = getLoadedType();
8364 if (!TLI.isTypeLegal(SliceType))
8365 return false;
8366
8367 // Check that the load is legal for this type.
8368 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8369 return false;
8370
8371 // Check that the offset can be computed.
8372 // 1. Check its type.
8373 EVT PtrType = Origin->getBasePtr().getValueType();
8374 if (PtrType == MVT::Untyped || PtrType.isExtended())
8375 return false;
8376
8377 // 2. Check that it fits in the immediate.
8378 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8379 return false;
8380
8381 // 3. Check that the computation is legal.
8382 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8383 return false;
8384
8385 // Check that the zext is legal if it needs one.
8386 EVT TruncateType = Inst->getValueType(0);
8387 if (TruncateType != SliceType &&
8388 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8389 return false;
8390
8391 return true;
8392 }
8393
8394 /// \brief Get the offset in bytes of this slice in the original chunk of
8395 /// bits.
Craig Topperc0196b12014-04-14 00:51:57 +00008396 /// \pre DAG != nullptr.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008397 uint64_t getOffsetFromBase() const {
8398 assert(DAG && "Missing context.");
8399 bool IsBigEndian =
8400 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8401 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8402 uint64_t Offset = Shift / 8;
8403 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8404 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8405 "The size of the original loaded type is not a multiple of a"
8406 " byte.");
8407 // If Offset is bigger than TySizeInBytes, it means we are loading all
8408 // zeros. This should have been optimized before in the process.
8409 assert(TySizeInBytes > Offset &&
8410 "Invalid shift amount for given loaded size");
8411 if (IsBigEndian)
8412 Offset = TySizeInBytes - Offset - getLoadedSize();
8413 return Offset;
8414 }
8415
8416 /// \brief Generate the sequence of instructions to load the slice
8417 /// represented by this object and redirect the uses of this slice to
8418 /// this new sequence of instructions.
8419 /// \pre this->Inst && this->Origin are valid Instructions and this
8420 /// object passed the legal check: LoadedSlice::isLegal returned true.
8421 /// \return The last instruction of the sequence used to load the slice.
8422 SDValue loadSlice() const {
8423 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8424 const SDValue &OldBaseAddr = Origin->getBasePtr();
8425 SDValue BaseAddr = OldBaseAddr;
8426 // Get the offset in that chunk of bytes w.r.t. the endianess.
8427 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8428 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8429 if (Offset) {
8430 // BaseAddr = BaseAddr + Offset.
8431 EVT ArithType = BaseAddr.getValueType();
8432 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8433 DAG->getConstant(Offset, ArithType));
8434 }
8435
8436 // Create the type of the loaded slice according to its size.
8437 EVT SliceType = getLoadedType();
8438
8439 // Create the load for the slice.
8440 SDValue LastInst = DAG->getLoad(
8441 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8442 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8443 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8444 // If the final type is not the same as the loaded type, this means that
8445 // we have to pad with zero. Create a zero extend for that.
8446 EVT FinalType = Inst->getValueType(0);
8447 if (SliceType != FinalType)
8448 LastInst =
8449 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8450 return LastInst;
8451 }
8452
8453 /// \brief Check if this slice can be merged with an expensive cross register
8454 /// bank copy. E.g.,
8455 /// i = load i32
8456 /// f = bitcast i32 i to float
8457 bool canMergeExpensiveCrossRegisterBankCopy() const {
8458 if (!Inst || !Inst->hasOneUse())
8459 return false;
8460 SDNode *Use = *Inst->use_begin();
8461 if (Use->getOpcode() != ISD::BITCAST)
8462 return false;
8463 assert(DAG && "Missing context");
8464 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8465 EVT ResVT = Use->getValueType(0);
8466 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8467 const TargetRegisterClass *ArgRC =
8468 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8469 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8470 return false;
8471
8472 // At this point, we know that we perform a cross-register-bank copy.
8473 // Check if it is expensive.
Eric Christopherd9134482014-08-04 21:25:23 +00008474 const TargetRegisterInfo *TRI =
8475 TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo();
Quentin Colombetde0e0622013-10-11 18:29:42 +00008476 // Assume bitcasts are cheap, unless both register classes do not
8477 // explicitly share a common sub class.
8478 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8479 return false;
8480
8481 // Check if it will be merged with the load.
8482 // 1. Check the alignment constraint.
8483 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8484 ResVT.getTypeForEVT(*DAG->getContext()));
8485
8486 if (RequiredAlignment > getAlignment())
8487 return false;
8488
8489 // 2. Check that the load is a legal operation for that type.
8490 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8491 return false;
8492
8493 // 3. Check that we do not have a zext in the way.
8494 if (Inst->getValueType(0) != getLoadedType())
8495 return false;
8496
8497 return true;
8498 }
8499};
8500}
8501
Quentin Colombetde0e0622013-10-11 18:29:42 +00008502/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8503/// \p UsedBits looks like 0..0 1..1 0..0.
8504static bool areUsedBitsDense(const APInt &UsedBits) {
8505 // If all the bits are one, this is dense!
8506 if (UsedBits.isAllOnesValue())
8507 return true;
8508
8509 // Get rid of the unused bits on the right.
8510 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8511 // Get rid of the unused bits on the left.
8512 if (NarrowedUsedBits.countLeadingZeros())
8513 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8514 // Check that the chunk of bits is completely used.
8515 return NarrowedUsedBits.isAllOnesValue();
8516}
8517
8518/// \brief Check whether or not \p First and \p Second are next to each other
8519/// in memory. This means that there is no hole between the bits loaded
8520/// by \p First and the bits loaded by \p Second.
8521static bool areSlicesNextToEachOther(const LoadedSlice &First,
8522 const LoadedSlice &Second) {
8523 assert(First.Origin == Second.Origin && First.Origin &&
8524 "Unable to match different memory origins.");
8525 APInt UsedBits = First.getUsedBits();
8526 assert((UsedBits & Second.getUsedBits()) == 0 &&
8527 "Slices are not supposed to overlap.");
8528 UsedBits |= Second.getUsedBits();
8529 return areUsedBitsDense(UsedBits);
8530}
8531
8532/// \brief Adjust the \p GlobalLSCost according to the target
8533/// paring capabilities and the layout of the slices.
8534/// \pre \p GlobalLSCost should account for at least as many loads as
8535/// there is in the slices in \p LoadedSlices.
8536static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8537 LoadedSlice::Cost &GlobalLSCost) {
8538 unsigned NumberOfSlices = LoadedSlices.size();
8539 // If there is less than 2 elements, no pairing is possible.
8540 if (NumberOfSlices < 2)
8541 return;
8542
8543 // Sort the slices so that elements that are likely to be next to each
8544 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00008545 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8546 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8547 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8548 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8549 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00008550 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8551 // First (resp. Second) is the first (resp. Second) potentially candidate
8552 // to be placed in a paired load.
Craig Topperc0196b12014-04-14 00:51:57 +00008553 const LoadedSlice *First = nullptr;
8554 const LoadedSlice *Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008555 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8556 // Set the beginning of the pair.
8557 First = Second) {
8558
8559 Second = &LoadedSlices[CurrSlice];
8560
8561 // If First is NULL, it means we start a new pair.
8562 // Get to the next slice.
8563 if (!First)
8564 continue;
8565
8566 EVT LoadedType = First->getLoadedType();
8567
8568 // If the types of the slices are different, we cannot pair them.
8569 if (LoadedType != Second->getLoadedType())
8570 continue;
8571
8572 // Check if the target supplies paired loads for this type.
8573 unsigned RequiredAlignment = 0;
8574 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8575 // move to the next pair, this type is hopeless.
Craig Topperc0196b12014-04-14 00:51:57 +00008576 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008577 continue;
8578 }
8579 // Check if we meet the alignment requirement.
8580 if (RequiredAlignment > First->getAlignment())
8581 continue;
8582
8583 // Check that both loads are next to each other in memory.
8584 if (!areSlicesNextToEachOther(*First, *Second))
8585 continue;
8586
8587 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8588 --GlobalLSCost.Loads;
8589 // Move to the next pair.
Craig Topperc0196b12014-04-14 00:51:57 +00008590 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008591 }
8592}
8593
8594/// \brief Check the profitability of all involved LoadedSlice.
8595/// Currently, it is considered profitable if there is exactly two
8596/// involved slices (1) which are (2) next to each other in memory, and
8597/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8598///
8599/// Note: The order of the elements in \p LoadedSlices may be modified, but not
8600/// the elements themselves.
8601///
8602/// FIXME: When the cost model will be mature enough, we can relax
8603/// constraints (1) and (2).
8604static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8605 const APInt &UsedBits, bool ForCodeSize) {
8606 unsigned NumberOfSlices = LoadedSlices.size();
8607 if (StressLoadSlicing)
8608 return NumberOfSlices > 1;
8609
8610 // Check (1).
8611 if (NumberOfSlices != 2)
8612 return false;
8613
8614 // Check (2).
8615 if (!areUsedBitsDense(UsedBits))
8616 return false;
8617
8618 // Check (3).
8619 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8620 // The original code has one big load.
8621 OrigCost.Loads = 1;
8622 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8623 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8624 // Accumulate the cost of all the slices.
8625 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8626 GlobalSlicingCost += SliceCost;
8627
8628 // Account as cost in the original configuration the gain obtained
8629 // with the current slices.
8630 OrigCost.addSliceGain(LS);
8631 }
8632
8633 // If the target supports paired load, adjust the cost accordingly.
8634 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8635 return OrigCost > GlobalSlicingCost;
8636}
8637
8638/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8639/// operations, split it in the various pieces being extracted.
8640///
8641/// This sort of thing is introduced by SROA.
8642/// This slicing takes care not to insert overlapping loads.
8643/// \pre LI is a simple load (i.e., not an atomic or volatile load).
8644bool DAGCombiner::SliceUpLoad(SDNode *N) {
8645 if (Level < AfterLegalizeDAG)
8646 return false;
8647
8648 LoadSDNode *LD = cast<LoadSDNode>(N);
8649 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8650 !LD->getValueType(0).isInteger())
8651 return false;
8652
8653 // Keep track of already used bits to detect overlapping values.
8654 // In that case, we will just abort the transformation.
8655 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8656
8657 SmallVector<LoadedSlice, 4> LoadedSlices;
8658
8659 // Check if this load is used as several smaller chunks of bits.
8660 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8661 // of computation for each trunc.
8662 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8663 UI != UIEnd; ++UI) {
8664 // Skip the uses of the chain.
8665 if (UI.getUse().getResNo() != 0)
8666 continue;
8667
8668 SDNode *User = *UI;
8669 unsigned Shift = 0;
8670
8671 // Check if this is a trunc(lshr).
8672 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8673 isa<ConstantSDNode>(User->getOperand(1))) {
8674 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8675 User = *User->use_begin();
8676 }
8677
8678 // At this point, User is a Truncate, iff we encountered, trunc or
8679 // trunc(lshr).
8680 if (User->getOpcode() != ISD::TRUNCATE)
8681 return false;
8682
8683 // The width of the type must be a power of 2 and greater than 8-bits.
8684 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00008685 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00008686 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008687 unsigned Width = User->getValueSizeInBits(0);
8688 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8689 return 0;
8690
8691 // Build the slice for this chain of computations.
8692 LoadedSlice LS(User, LD, Shift, &DAG);
8693 APInt CurrentUsedBits = LS.getUsedBits();
8694
8695 // Check if this slice overlaps with another.
8696 if ((CurrentUsedBits & UsedBits) != 0)
8697 return false;
8698 // Update the bits used globally.
8699 UsedBits |= CurrentUsedBits;
8700
8701 // Check if the new slice would be legal.
8702 if (!LS.isLegal())
8703 return false;
8704
8705 // Record the slice.
8706 LoadedSlices.push_back(LS);
8707 }
8708
8709 // Abort slicing if it does not seem to be profitable.
8710 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8711 return false;
8712
8713 ++SlicedLoads;
8714
8715 // Rewrite each chain to use an independent load.
8716 // By construction, each chain can be represented by a unique load.
8717
8718 // Prepare the argument for the new token factor for all the slices.
8719 SmallVector<SDValue, 8> ArgChains;
8720 for (SmallVectorImpl<LoadedSlice>::const_iterator
8721 LSIt = LoadedSlices.begin(),
8722 LSItEnd = LoadedSlices.end();
8723 LSIt != LSItEnd; ++LSIt) {
8724 SDValue SliceInst = LSIt->loadSlice();
8725 CombineTo(LSIt->Inst, SliceInst, true);
8726 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8727 SliceInst = SliceInst.getOperand(0);
8728 assert(SliceInst->getOpcode() == ISD::LOAD &&
8729 "It takes more than a zext to get to the loaded slice!!");
8730 ArgChains.push_back(SliceInst.getValue(1));
8731 }
8732
8733 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +00008734 ArgChains);
Quentin Colombetde0e0622013-10-11 18:29:42 +00008735 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8736 return true;
8737}
8738
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008739/// Check to see if V is (and load (ptr), imm), where the load is having
8740/// specific bytes cleared out. If so, return the byte size being masked out
8741/// and the shift amount.
Chris Lattner4041ab62010-04-15 04:48:01 +00008742static std::pair<unsigned, unsigned>
8743CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8744 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008745
Chris Lattner4041ab62010-04-15 04:48:01 +00008746 // Check for the structure we're looking for.
8747 if (V->getOpcode() != ISD::AND ||
8748 !isa<ConstantSDNode>(V->getOperand(1)) ||
8749 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8750 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008751
Chris Lattner3245afd2010-04-15 06:10:49 +00008752 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00008753 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00008754 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00008755
Chris Lattner3245afd2010-04-15 06:10:49 +00008756 // The store should be chained directly to the load or be an operand of a
8757 // tokenfactor.
8758 if (LD == Chain.getNode())
8759 ; // ok.
8760 else if (Chain->getOpcode() != ISD::TokenFactor)
8761 return Result; // Fail.
8762 else {
8763 bool isOk = false;
8764 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8765 if (Chain->getOperand(i).getNode() == LD) {
8766 isOk = true;
8767 break;
8768 }
8769 if (!isOk) return Result;
8770 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008771
Chris Lattner4041ab62010-04-15 04:48:01 +00008772 // This only handles simple types.
8773 if (V.getValueType() != MVT::i16 &&
8774 V.getValueType() != MVT::i32 &&
8775 V.getValueType() != MVT::i64)
8776 return Result;
8777
8778 // Check the constant mask. Invert it so that the bits being masked out are
8779 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8780 // follow the sign bit for uniformity.
8781 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008782 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008783 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008784 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008785 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8786 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00008787
Chris Lattner4041ab62010-04-15 04:48:01 +00008788 // See if we have a continuous run of bits. If so, we have 0*1+0*
8789 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8790 return Result;
8791
8792 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8793 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8794 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00008795
Chris Lattner4041ab62010-04-15 04:48:01 +00008796 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8797 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00008798 case 1:
8799 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00008800 case 4: break;
8801 default: return Result; // All one mask, or 5-byte mask.
8802 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008803
Chris Lattner4041ab62010-04-15 04:48:01 +00008804 // Verify that the first bit starts at a multiple of mask so that the access
8805 // is aligned the same as the access width.
8806 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008807
Chris Lattner4041ab62010-04-15 04:48:01 +00008808 Result.first = MaskedBytes;
8809 Result.second = NotMaskTZ/8;
8810 return Result;
8811}
8812
8813
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008814/// Check to see if IVal is something that provides a value as specified by
8815/// MaskInfo. If so, replace the specified store with a narrower store of
8816/// truncated IVal.
Chris Lattner4041ab62010-04-15 04:48:01 +00008817static SDNode *
8818ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8819 SDValue IVal, StoreSDNode *St,
8820 DAGCombiner *DC) {
8821 unsigned NumBytes = MaskInfo.first;
8822 unsigned ByteShift = MaskInfo.second;
8823 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00008824
Chris Lattner4041ab62010-04-15 04:48:01 +00008825 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8826 // that uses this. If not, this is not a replacement.
8827 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8828 ByteShift*8, (ByteShift+NumBytes)*8);
Craig Topperc0196b12014-04-14 00:51:57 +00008829 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008830
Chris Lattner4041ab62010-04-15 04:48:01 +00008831 // Check that it is legal on the target to do this. It is legal if the new
8832 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8833 // legalization.
8834 MVT VT = MVT::getIntegerVT(NumBytes*8);
8835 if (!DC->isTypeLegal(VT))
Craig Topperc0196b12014-04-14 00:51:57 +00008836 return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008837
Chris Lattner4041ab62010-04-15 04:48:01 +00008838 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8839 // shifted by ByteShift and truncated down to NumBytes.
8840 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008841 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00008842 DAG.getConstant(ByteShift*8,
8843 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00008844
8845 // Figure out the offset for the store and the alignment of the access.
8846 unsigned StOffset;
8847 unsigned NewAlign = St->getAlignment();
8848
8849 if (DAG.getTargetLoweringInfo().isLittleEndian())
8850 StOffset = ByteShift;
8851 else
8852 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00008853
Chris Lattner4041ab62010-04-15 04:48:01 +00008854 SDValue Ptr = St->getBasePtr();
8855 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008856 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00008857 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8858 NewAlign = MinAlign(NewAlign, StOffset);
8859 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008860
Chris Lattner4041ab62010-04-15 04:48:01 +00008861 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008862 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00008863
Chris Lattner4041ab62010-04-15 04:48:01 +00008864 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00008865 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00008866 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00008867 false, false, NewAlign).getNode();
8868}
8869
Evan Chenga9cda8a2009-05-28 00:35:15 +00008870
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008871/// Look for sequence of load / op / store where op is one of 'or', 'xor', and
8872/// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
8873/// narrowing the load and store if it would end up being a win for performance
8874/// or code size.
Evan Chenga9cda8a2009-05-28 00:35:15 +00008875SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8876 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00008877 if (ST->isVolatile())
8878 return SDValue();
8879
Evan Chenga9cda8a2009-05-28 00:35:15 +00008880 SDValue Chain = ST->getChain();
8881 SDValue Value = ST->getValue();
8882 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00008883 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008884
8885 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +00008886 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008887
8888 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +00008889
Chris Lattner4041ab62010-04-15 04:48:01 +00008890 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8891 // is a byte mask indicating a consecutive number of bytes, check to see if
8892 // Y is known to provide just those bytes. If so, we try to replace the
8893 // load + replace + store sequence with a single (narrower) store, which makes
8894 // the load dead.
8895 if (Opc == ISD::OR) {
8896 std::pair<unsigned, unsigned> MaskedLoad;
8897 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8898 if (MaskedLoad.first)
8899 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8900 Value.getOperand(1), ST,this))
8901 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008902
Chris Lattner4041ab62010-04-15 04:48:01 +00008903 // Or is commutative, so try swapping X and Y.
8904 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8905 if (MaskedLoad.first)
8906 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8907 Value.getOperand(0), ST,this))
8908 return SDValue(NewST, 0);
8909 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008910
Evan Chenga9cda8a2009-05-28 00:35:15 +00008911 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8912 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +00008913 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008914
8915 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +00008916 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8917 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00008918 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008919 if (LD->getBasePtr() != Ptr ||
8920 LD->getPointerInfo().getAddrSpace() !=
8921 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +00008922 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008923
8924 // Find the type to narrow it the load / op / store to.
8925 SDValue N1 = Value.getOperand(1);
8926 unsigned BitWidth = N1.getValueSizeInBits();
8927 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8928 if (Opc == ISD::AND)
8929 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +00008930 if (Imm == 0 || Imm.isAllOnesValue())
8931 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008932 unsigned ShAmt = Imm.countTrailingZeros();
8933 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8934 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +00008935 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008936 while (NewBW < BitWidth &&
Evan Cheng6673ff02009-05-28 18:41:02 +00008937 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
Evan Chenga9cda8a2009-05-28 00:35:15 +00008938 TLI.isNarrowingProfitable(VT, NewVT))) {
8939 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +00008940 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008941 }
Evan Cheng6673ff02009-05-28 18:41:02 +00008942 if (NewBW >= BitWidth)
8943 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008944
8945 // If the lsb changed does not start at the type bitwidth boundary,
8946 // start at the previous one.
8947 if (ShAmt % NewBW)
8948 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +00008949 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8950 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008951 if ((Imm & Mask) == Imm) {
8952 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8953 if (Opc == ISD::AND)
8954 NewImm ^= APInt::getAllOnesValue(NewBW);
8955 uint64_t PtrOff = ShAmt / 8;
8956 // For big endian targets, we need to adjust the offset to the pointer to
8957 // load the correct bytes.
8958 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +00008959 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +00008960
8961 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +00008962 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008963 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +00008964 return SDValue();
8965
Andrew Trickef9de2a2013-05-25 02:42:55 +00008966 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008967 Ptr.getValueType(), Ptr,
8968 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008969 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008970 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008971 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008972 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008973 LD->isInvariant(), NewAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00008974 LD->getAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008975 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +00008976 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008977 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008978 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008979 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008980 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008981
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008982 AddToWorklist(NewPtr.getNode());
8983 AddToWorklist(NewLD.getNode());
8984 AddToWorklist(NewVal.getNode());
8985 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008986 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008987 ++OpsNarrowed;
8988 return NewST;
8989 }
8990 }
8991
Evan Cheng6673ff02009-05-28 18:41:02 +00008992 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008993}
8994
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008995/// For a given floating point load / store pair, if the load value isn't used
8996/// by any other operations, then consider transforming the pair to integer
8997/// load / store operations if the target deems the transformation profitable.
Evan Chengd42641c2011-02-02 01:06:55 +00008998SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8999 StoreSDNode *ST = cast<StoreSDNode>(N);
9000 SDValue Chain = ST->getChain();
9001 SDValue Value = ST->getValue();
9002 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9003 Value.hasOneUse() &&
9004 Chain == SDValue(Value.getNode(), 1)) {
9005 LoadSDNode *LD = cast<LoadSDNode>(Value);
9006 EVT VT = LD->getMemoryVT();
9007 if (!VT.isFloatingPoint() ||
9008 VT != ST->getMemoryVT() ||
9009 LD->isNonTemporal() ||
9010 ST->isNonTemporal() ||
9011 LD->getPointerInfo().getAddrSpace() != 0 ||
9012 ST->getPointerInfo().getAddrSpace() != 0)
9013 return SDValue();
9014
9015 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9016 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9017 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9018 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9019 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9020 return SDValue();
9021
9022 unsigned LDAlign = LD->getAlignment();
9023 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +00009024 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009025 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +00009026 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9027 return SDValue();
9028
Andrew Trickef9de2a2013-05-25 02:42:55 +00009029 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +00009030 LD->getChain(), LD->getBasePtr(),
9031 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00009032 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +00009033
Andrew Trickef9de2a2013-05-25 02:42:55 +00009034 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +00009035 NewLD, ST->getBasePtr(),
9036 ST->getPointerInfo(),
9037 false, false, STAlign);
9038
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009039 AddToWorklist(NewLD.getNode());
9040 AddToWorklist(NewST.getNode());
9041 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009042 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +00009043 ++LdStFP2Int;
9044 return NewST;
9045 }
9046
9047 return SDValue();
9048}
9049
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009050/// Helper struct to parse and store a memory address as base + index + offset.
9051/// We ignore sign extensions when it is safe to do so.
9052/// The following two expressions are not equivalent. To differentiate we need
9053/// to store whether there was a sign extension involved in the index
9054/// computation.
9055/// (load (i64 add (i64 copyfromreg %c)
9056/// (i64 signextend (add (i8 load %index)
9057/// (i8 1))))
9058/// vs
9059///
9060/// (load (i64 add (i64 copyfromreg %c)
9061/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9062/// (i32 1)))))
9063struct BaseIndexOffset {
9064 SDValue Base;
9065 SDValue Index;
9066 int64_t Offset;
9067 bool IsIndexSignExt;
9068
9069 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9070
9071 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9072 bool IsIndexSignExt) :
9073 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9074
9075 bool equalBaseIndex(const BaseIndexOffset &Other) {
9076 return Other.Base == Base && Other.Index == Index &&
9077 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009078 }
9079
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009080 /// Parses tree in Ptr for base, index, offset addresses.
9081 static BaseIndexOffset match(SDValue Ptr) {
9082 bool IsIndexSignExt = false;
9083
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009084 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9085 // instruction, then it could be just the BASE or everything else we don't
9086 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009087 if (Ptr->getOpcode() != ISD::ADD)
9088 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9089
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009090 // We know that we have at least an ADD instruction. Try to pattern match
9091 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009092 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9093 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9094 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9095 IsIndexSignExt);
9096 }
9097
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009098 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +00009099 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009100 // (i64 add (i64 %array_ptr)
9101 // (i64 mul (i64 %induction_var)
9102 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +00009103 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009104 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009105
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009106 // Look at Base + Index + Offset cases.
9107 SDValue Base = Ptr->getOperand(0);
9108 SDValue IndexOffset = Ptr->getOperand(1);
9109
9110 // Skip signextends.
9111 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9112 IndexOffset = IndexOffset->getOperand(0);
9113 IsIndexSignExt = true;
9114 }
9115
9116 // Either the case of Base + Index (no offset) or something else.
9117 if (IndexOffset->getOpcode() != ISD::ADD)
9118 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9119
9120 // Now we have the case of Base + Index + offset.
9121 SDValue Index = IndexOffset->getOperand(0);
9122 SDValue Offset = IndexOffset->getOperand(1);
9123
9124 if (!isa<ConstantSDNode>(Offset))
9125 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9126
9127 // Ignore signextends.
9128 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9129 Index = Index->getOperand(0);
9130 IsIndexSignExt = true;
9131 } else IsIndexSignExt = false;
9132
9133 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9134 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9135 }
9136};
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009137
9138/// Holds a pointer to an LSBaseSDNode as well as information on where it
9139/// is located in a sequence of memory operations connected by a chain.
9140struct MemOpLink {
9141 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9142 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9143 // Ptr to the mem node.
9144 LSBaseSDNode *MemNode;
9145 // Offset from the base ptr.
9146 int64_t OffsetFromBase;
9147 // What is the sequence number of this mem node.
9148 // Lowest mem operand in the DAG starts at zero.
9149 unsigned SequenceNum;
9150};
9151
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009152bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9153 EVT MemVT = St->getMemoryVT();
9154 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009155 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9156 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009157
9158 // Don't merge vectors into wider inputs.
9159 if (MemVT.isVector() || !MemVT.isSimple())
9160 return false;
9161
9162 // Perform an early exit check. Do not bother looking at stored values that
9163 // are not constants or loads.
9164 SDValue StoredVal = St->getValue();
9165 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9166 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9167 !IsLoadSrc)
9168 return false;
9169
9170 // Only look at ends of store sequences.
Chandler Carruth94bd5532014-07-25 07:23:23 +00009171 SDValue Chain = SDValue(St, 0);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009172 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9173 return false;
9174
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009175 // This holds the base pointer, index, and the offset in bytes from the base
9176 // pointer.
9177 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009178
9179 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009180 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009181 return false;
9182
9183 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009184 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009185 return false;
9186
Nadav Rotem307d7672012-11-29 00:00:08 +00009187 // Save the LoadSDNodes that we find in the chain.
9188 // We need to make sure that these nodes do not interfere with
9189 // any of the store nodes.
9190 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9191
9192 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009193 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +00009194
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009195 // Walk up the chain and look for nodes with offsets from the same
9196 // base pointer. Stop when reaching an instruction with a different kind
9197 // or instruction which has a different base pointer.
9198 unsigned Seq = 0;
9199 StoreSDNode *Index = St;
9200 while (Index) {
9201 // If the chain has more than one use, then we can't reorder the mem ops.
Matt Arsenault197a1e22014-07-25 07:56:42 +00009202 if (Index != St && !SDValue(Index, 0)->hasOneUse())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009203 break;
9204
9205 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009206 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009207
9208 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009209 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009210 break;
9211
9212 // Check that the alignment is the same.
9213 if (Index->getAlignment() != St->getAlignment())
9214 break;
9215
9216 // The memory operands must not be volatile.
9217 if (Index->isVolatile() || Index->isIndexed())
9218 break;
9219
9220 // No truncation.
9221 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9222 if (St->isTruncatingStore())
9223 break;
9224
9225 // The stored memory type must be the same.
9226 if (Index->getMemoryVT() != MemVT)
9227 break;
9228
9229 // We do not allow unaligned stores because we want to prevent overriding
9230 // stores.
9231 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9232 break;
9233
9234 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009235 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009236
Nadav Rotem307d7672012-11-29 00:00:08 +00009237 // Find the next memory operand in the chain. If the next operand in the
9238 // chain is a store then move up and continue the scan with the next
9239 // memory operand. If the next operand is a load save it and use alias
9240 // information to check if it interferes with anything.
9241 SDNode *NextInChain = Index->getChain().getNode();
9242 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +00009243 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +00009244 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +00009245 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +00009246 break;
9247 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +00009248 if (Ldn->isVolatile()) {
Craig Topperc0196b12014-04-14 00:51:57 +00009249 Index = nullptr;
Bill Wendling9200bb02013-11-25 18:05:22 +00009250 break;
9251 }
9252
Nadav Rotem307d7672012-11-29 00:00:08 +00009253 // Save the load node for later. Continue the scan.
9254 AliasLoadNodes.push_back(Ldn);
9255 NextInChain = Ldn->getChain().getNode();
9256 continue;
9257 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00009258 Index = nullptr;
Nadav Rotem307d7672012-11-29 00:00:08 +00009259 break;
9260 }
9261 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009262 }
9263
9264 // Check if there is anything to merge.
9265 if (StoreNodes.size() < 2)
9266 return false;
9267
9268 // Sort the memory operands according to their distance from the base pointer.
9269 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009270 [](MemOpLink LHS, MemOpLink RHS) {
9271 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9272 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9273 LHS.SequenceNum > RHS.SequenceNum);
9274 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009275
9276 // Scan the memory operations on the chain and find the first non-consecutive
9277 // store memory address.
9278 unsigned LastConsecutiveStore = 0;
9279 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +00009280 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9281
9282 // Check that the addresses are consecutive starting from the second
9283 // element in the list of stores.
9284 if (i > 0) {
9285 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9286 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9287 break;
9288 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009289
Nadav Rotem307d7672012-11-29 00:00:08 +00009290 bool Alias = false;
9291 // Check if this store interferes with any of the loads that we found.
9292 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9293 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9294 Alias = true;
9295 break;
9296 }
Nadav Rotem307d7672012-11-29 00:00:08 +00009297 // We found a load that alias with this store. Stop the sequence.
9298 if (Alias)
9299 break;
9300
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009301 // Mark this node as useful.
9302 LastConsecutiveStore = i;
9303 }
9304
9305 // The node with the lowest store address.
9306 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9307
9308 // Store the constants into memory as one consecutive store.
9309 if (!IsLoadSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009310 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009311 unsigned LastLegalVectorType = 0;
9312 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009313 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9314 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9315 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009316
9317 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009318 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009319 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009320 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009321 } else {
Alp Tokerf907b892013-12-05 05:44:44 +00009322 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009323 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009324 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009325
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009326 // Find a legal type for the constant store.
9327 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9328 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9329 if (TLI.isTypeLegal(StoreTy))
9330 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009331 // Or check whether a truncstore is legal.
9332 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9333 TargetLowering::TypePromoteInteger) {
9334 EVT LegalizedStoredValueTy =
9335 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9336 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9337 LastLegalType = i+1;
9338 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009339
9340 // Find a legal type for the vector store.
9341 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9342 if (TLI.isTypeLegal(Ty))
9343 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009344 }
9345
Bob Wilson3365b802012-12-20 01:36:20 +00009346 // We only use vectors if the constant is known to be zero and the
9347 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009348 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +00009349 LastLegalVectorType = 0;
9350
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009351 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +00009352 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009353 return false;
9354
Nadav Rotem495b1a42013-02-14 18:28:52 +00009355 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009356 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9357
9358 // Make sure we have something to merge.
9359 if (NumElem < 2)
9360 return false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009361
9362 unsigned EarliestNodeUsed = 0;
9363 for (unsigned i=0; i < NumElem; ++i) {
9364 // Find a chain for the new wide-store operand. Notice that some
9365 // of the store nodes that we found may not be selected for inclusion
9366 // in the wide store. The chain we use needs to be the chain of the
9367 // earliest store node which is *used* and replaced by the wide store.
9368 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9369 EarliestNodeUsed = i;
9370 }
9371
9372 // The earliest Node in the DAG.
9373 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009374 SDLoc DL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009375
Nadav Rotemb27777f2012-10-04 22:35:15 +00009376 SDValue StoredVal;
9377 if (UseVector) {
9378 // Find a legal type for the vector store.
9379 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9380 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9381 StoredVal = DAG.getConstant(0, Ty);
9382 } else {
9383 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9384 APInt StoreInt(StoreBW, 0);
9385
9386 // Construct a single integer constant which is made of the smaller
9387 // constant inputs.
9388 bool IsLE = TLI.isLittleEndian();
9389 for (unsigned i = 0; i < NumElem ; ++i) {
9390 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9391 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9392 SDValue Val = St->getValue();
9393 StoreInt<<=ElementSizeBytes*8;
9394 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9395 StoreInt|=C->getAPIntValue().zext(StoreBW);
9396 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9397 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9398 } else {
9399 assert(false && "Invalid constant element type");
9400 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009401 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009402
9403 // Create the new Load and Store operations.
9404 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9405 StoredVal = DAG.getConstant(StoreInt, StoreTy);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009406 }
9407
Nadav Rotemb27777f2012-10-04 22:35:15 +00009408 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009409 FirstInChain->getBasePtr(),
9410 FirstInChain->getPointerInfo(),
9411 false, false,
9412 FirstInChain->getAlignment());
9413
9414 // Replace the first store with the new store
9415 CombineTo(EarliestOp, NewStore);
9416 // Erase all other stores.
9417 for (unsigned i = 0; i < NumElem ; ++i) {
9418 if (StoreNodes[i].MemNode == EarliestOp)
9419 continue;
9420 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Rafael Espindolac79532d2012-11-14 05:08:56 +00009421 // ReplaceAllUsesWith will replace all uses that existed when it was
9422 // called, but graph optimizations may cause new ones to appear. For
9423 // example, the case in pr14333 looks like
9424 //
9425 // St's chain -> St -> another store -> X
9426 //
9427 // And the only difference from St to the other store is the chain.
9428 // When we change it's chain to be St's chain they become identical,
9429 // get CSEed and the net result is that X is now a use of St.
9430 // Since we know that St is redundant, just iterate.
9431 while (!St->use_empty())
9432 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
Chandler Carruth18066972014-08-02 10:02:07 +00009433 deleteAndRecombine(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009434 }
9435
9436 return true;
9437 }
9438
9439 // Below we handle the case of multiple consecutive stores that
9440 // come from multiple consecutive loads. We merge them into a single
9441 // wide load and a single wide store.
9442
9443 // Look for load nodes which are used by the stored values.
9444 SmallVector<MemOpLink, 8> LoadNodes;
9445
9446 // Find acceptable loads. Loads need to have the same chain (token factor),
9447 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009448 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009449 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9450 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9451 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9452 if (!Ld) break;
9453
9454 // Loads must only have one use.
9455 if (!Ld->hasNUsesOfValue(1, 0))
9456 break;
9457
9458 // Check that the alignment is the same as the stores.
9459 if (Ld->getAlignment() != St->getAlignment())
9460 break;
9461
9462 // The memory operands must not be volatile.
9463 if (Ld->isVolatile() || Ld->isIndexed())
9464 break;
9465
9466 // We do not accept ext loads.
9467 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9468 break;
9469
9470 // The stored memory type must be the same.
9471 if (Ld->getMemoryVT() != MemVT)
9472 break;
9473
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009474 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009475 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009476 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009477 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009478 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009479 break;
9480 } else {
9481 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009482 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009483 }
9484
9485 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009486 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009487 }
9488
9489 if (LoadNodes.size() < 2)
9490 return false;
9491
James Molloyce45be02014-08-02 14:51:24 +00009492 // If we have load/store pair instructions and we only have two values,
9493 // don't bother.
9494 unsigned RequiredAlignment;
9495 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9496 St->getAlignment() >= RequiredAlignment)
9497 return false;
9498
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009499 // Scan the memory operations on the chain and find the first non-consecutive
9500 // load memory address. These variables hold the index in the store node
9501 // array.
9502 unsigned LastConsecutiveLoad = 0;
9503 // This variable refers to the size and not index in the array.
9504 unsigned LastLegalVectorType = 0;
9505 unsigned LastLegalIntegerType = 0;
9506 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +00009507 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9508 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9509 // All loads much share the same chain.
9510 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9511 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009512
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009513 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9514 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9515 break;
9516 LastConsecutiveLoad = i;
9517
9518 // Find a legal type for the vector store.
9519 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9520 if (TLI.isTypeLegal(StoreTy))
9521 LastLegalVectorType = i + 1;
9522
9523 // Find a legal type for the integer store.
9524 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9525 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9526 if (TLI.isTypeLegal(StoreTy))
9527 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009528 // Or check whether a truncstore and extload is legal.
9529 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9530 TargetLowering::TypePromoteInteger) {
9531 EVT LegalizedStoredValueTy =
9532 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9533 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9534 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9535 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9536 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9537 LastLegalIntegerType = i+1;
9538 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009539 }
9540
9541 // Only use vector types if the vector type is larger than the integer type.
9542 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009543 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009544 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9545
9546 // We add +1 here because the LastXXX variables refer to location while
9547 // the NumElem refers to array/index size.
9548 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9549 NumElem = std::min(LastLegalType, NumElem);
9550
9551 if (NumElem < 2)
9552 return false;
9553
9554 // The earliest Node in the DAG.
9555 unsigned EarliestNodeUsed = 0;
9556 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9557 for (unsigned i=1; i<NumElem; ++i) {
9558 // Find a chain for the new wide-store operand. Notice that some
9559 // of the store nodes that we found may not be selected for inclusion
9560 // in the wide store. The chain we use needs to be the chain of the
9561 // earliest store node which is *used* and replaced by the wide store.
9562 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9563 EarliestNodeUsed = i;
9564 }
9565
9566 // Find if it is better to use vectors or integers to load and store
9567 // to memory.
9568 EVT JointMemOpVT;
9569 if (UseVectorTy) {
9570 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9571 } else {
9572 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9573 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9574 }
9575
Andrew Trickef9de2a2013-05-25 02:42:55 +00009576 SDLoc LoadDL(LoadNodes[0].MemNode);
9577 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009578
9579 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9580 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9581 FirstLoad->getChain(),
9582 FirstLoad->getBasePtr(),
9583 FirstLoad->getPointerInfo(),
9584 false, false, false,
9585 FirstLoad->getAlignment());
9586
9587 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9588 FirstInChain->getBasePtr(),
9589 FirstInChain->getPointerInfo(), false, false,
9590 FirstInChain->getAlignment());
9591
Nadav Rotemac920662012-10-03 19:30:31 +00009592 // Replace one of the loads with the new load.
9593 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9594 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9595 SDValue(NewLoad.getNode(), 1));
9596
9597 // Remove the rest of the load chains.
9598 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009599 // Replace all chain users of the old load nodes with the chain of the new
9600 // load node.
9601 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +00009602 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9603 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009604
Nadav Rotemac920662012-10-03 19:30:31 +00009605 // Replace the first store with the new store.
9606 CombineTo(EarliestOp, NewStore);
9607 // Erase all other stores.
9608 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009609 // Remove all Store nodes.
9610 if (StoreNodes[i].MemNode == EarliestOp)
9611 continue;
9612 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9613 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
Chandler Carruth18066972014-08-02 10:02:07 +00009614 deleteAndRecombine(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009615 }
9616
9617 return true;
9618}
9619
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009620SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +00009621 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009622 SDValue Chain = ST->getChain();
9623 SDValue Value = ST->getValue();
9624 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009625
Evan Chenga4cf58a2007-05-07 21:27:48 +00009626 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +00009627 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +00009628 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009629 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +00009630 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009631 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009632 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00009633 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +00009634 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009635 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +00009636 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009637 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +00009638 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009639 ST->isNonTemporal(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00009640 ST->getAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +00009641 }
Owen Andersona5192842011-04-14 17:30:49 +00009642
Chris Lattner41c80e82011-04-09 02:32:02 +00009643 // Turn 'store undef, Ptr' -> nothing.
9644 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9645 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +00009646
Nate Begeman8e20c762006-12-11 02:23:46 +00009647 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +00009648 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00009649 // NOTE: If the original store is volatile, this transform must not increase
9650 // the number of stores. For example, on x86-32 an f64 can be stored in one
9651 // processor operation but an i64 (which is not legal) requires two. So the
9652 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +00009653 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009654 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +00009655 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00009656 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +00009657 case MVT::f16: // We don't do this for these yet.
9658 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +00009659 case MVT::f128:
9660 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +00009661 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009662 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +00009663 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009664 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +00009665 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +00009666 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009667 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009668 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +00009669 }
9670 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009671 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +00009672 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +00009673 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009674 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00009675 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +00009676 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009677 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009678 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +00009679 }
Owen Andersona5192842011-04-14 17:30:49 +00009680
Chris Lattner41c80e82011-04-09 02:32:02 +00009681 if (!ST->isVolatile() &&
9682 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +00009683 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +00009684 // argument passing. Since this is so common, custom legalize the
9685 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +00009686 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +00009687 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9688 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +00009689 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009690
Dan Gohman2af30632007-07-09 22:18:38 +00009691 unsigned Alignment = ST->getAlignment();
9692 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +00009693 bool isNonTemporal = ST->isNonTemporal();
Hal Finkelcc39b672014-07-24 12:16:19 +00009694 AAMDNodes AAInfo = ST->getAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +00009695
Andrew Trickef9de2a2013-05-25 02:42:55 +00009696 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +00009697 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00009698 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +00009699 ST->getAlignment(), AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009700 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +00009701 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +00009702 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009703 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +00009704 Ptr, ST->getPointerInfo().getWithOffset(4),
9705 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +00009706 Alignment, AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009707 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +00009708 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009709 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009710
Chris Lattnerb7524b62006-12-12 04:16:14 +00009711 break;
Evan Cheng21836982006-12-11 17:25:19 +00009712 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009713 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009714 }
9715
Evan Cheng43cd9e32010-04-01 06:04:33 +00009716 // Try to infer better alignment information than the store already has.
9717 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009718 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9719 if (Align > ST->getAlignment())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009720 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +00009721 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009722 ST->isVolatile(), ST->isNonTemporal(), Align,
Hal Finkelcc39b672014-07-24 12:16:19 +00009723 ST->getAAInfo());
Evan Cheng43cd9e32010-04-01 06:04:33 +00009724 }
9725 }
9726
Evan Chengd42641c2011-02-02 01:06:55 +00009727 // Try transforming a pair floating point load / store ops to integer
9728 // load / store ops.
9729 SDValue NewST = TransformFPLoadStorePair(N);
9730 if (NewST.getNode())
9731 return NewST;
9732
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00009733 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9734 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00009735#ifndef NDEBUG
9736 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9737 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9738 UseAA = false;
9739#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00009740 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009741 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009742 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009743
Jim Laskey708d0db2006-10-04 16:53:27 +00009744 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009745 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009746 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +00009747
9748 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009749 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009750 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009751 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009752 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009753 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009754 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009755 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009756
Jim Laskeyd07be232006-09-25 16:29:54 +00009757 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009758 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009759 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009760
Nate Begeman879d8f12009-09-15 00:18:30 +00009761 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009762 AddToWorklist(Token.getNode());
Nate Begeman879d8f12009-09-15 00:18:30 +00009763
Jim Laskeydcf983c2006-10-13 23:32:28 +00009764 // Don't add users to work list.
9765 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009766 }
Jim Laskey5d19d592006-09-21 16:28:59 +00009767 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009768
Evan Cheng33157702006-11-05 09:31:14 +00009769 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +00009770 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009771 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +00009772
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009773 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009774 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009775 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00009776 // See if we can simplify the input to this truncstore with knowledge that
9777 // only the low bits are being used. For example:
9778 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +00009779 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +00009780 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009781 APInt::getLowBitsSet(
9782 Value.getValueType().getScalarType().getSizeInBits(),
9783 ST->getMemoryVT().getScalarType().getSizeInBits()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009784 AddToWorklist(Value.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00009785 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009786 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009787 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +00009788
Chris Lattnerf47e3062007-10-13 06:58:48 +00009789 // Otherwise, see if we can simplify the operation with
9790 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00009791 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009792 APInt::getLowBitsSet(
9793 Value.getValueType().getScalarType().getSizeInBits(),
9794 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009795 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +00009796 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009797
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009798 // If this is a load followed by a store to the same location, then the store
9799 // is dead/noop.
9800 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009801 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009802 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +00009803 // There can't be any side effects between the load and store, such as
9804 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009805 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009806 // The store is dead, remove it.
9807 return Chain;
9808 }
9809 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009810
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009811 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9812 // truncating store. We can do this even if this is already a truncstore.
9813 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +00009814 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009815 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009816 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009817 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009818 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009819 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009820
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009821 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +00009822 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +00009823 if (!LegalTypes) {
9824 bool EverChanged = false;
9825
9826 do {
9827 // There can be multiple store sequences on the same chain.
9828 // Keep trying to merge store sequences until we are unable to do so
9829 // or until we merge the last store on the chain.
9830 bool Changed = MergeConsecutiveStores(ST);
9831 EverChanged |= Changed;
9832 if (!Changed) break;
9833 } while (ST->getOpcode() != ISD::DELETED_NODE);
9834
9835 if (EverChanged)
9836 return SDValue(N, 0);
9837 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009838
Evan Chenga9cda8a2009-05-28 00:35:15 +00009839 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +00009840}
9841
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009842SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9843 SDValue InVec = N->getOperand(0);
9844 SDValue InVal = N->getOperand(1);
9845 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009846 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009847
Bob Wilson42603952010-05-19 23:42:58 +00009848 // If the inserted element is an UNDEF, just use the input vector.
9849 if (InVal.getOpcode() == ISD::UNDEF)
9850 return InVec;
9851
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009852 EVT VT = InVec.getValueType();
9853
Owen Andersonb2c80da2011-02-25 21:41:48 +00009854 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009855 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9856 return SDValue();
9857
Eli Friedmanb7910b72011-09-09 21:04:06 +00009858 // Check that we know which element is being inserted
9859 if (!isa<ConstantSDNode>(EltNo))
9860 return SDValue();
9861 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009862
Andrea Di Biagiof99dd642014-06-09 16:54:41 +00009863 // Canonicalize insert_vector_elt dag nodes.
9864 // Example:
9865 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9866 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9867 //
9868 // Do this only if the child insert_vector node has one use; also
9869 // do this only if indices are both constants and Idx1 < Idx0.
9870 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9871 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9872 unsigned OtherElt =
9873 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9874 if (Elt < OtherElt) {
9875 // Swap nodes.
9876 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9877 InVec.getOperand(0), InVal, EltNo);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009878 AddToWorklist(NewOp.getNode());
Andrea Di Biagiof99dd642014-06-09 16:54:41 +00009879 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9880 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9881 }
9882 }
9883
Eli Friedmanb7910b72011-09-09 21:04:06 +00009884 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9885 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9886 // vector elements.
9887 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +00009888 // Do not combine these two vectors if the output vector will not replace
9889 // the input vector.
9890 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +00009891 Ops.append(InVec.getNode()->op_begin(),
9892 InVec.getNode()->op_end());
9893 } else if (InVec.getOpcode() == ISD::UNDEF) {
9894 unsigned NElts = VT.getVectorNumElements();
9895 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9896 } else {
9897 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +00009898 }
Eli Friedmanb7910b72011-09-09 21:04:06 +00009899
9900 // Insert the element
9901 if (Elt < Ops.size()) {
9902 // All the operands of BUILD_VECTOR must have the same type;
9903 // we enforce that here.
9904 EVT OpVT = Ops[0].getValueType();
9905 if (InVal.getValueType() != OpVT)
9906 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9907 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9908 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9909 Ops[Elt] = InVal;
9910 }
9911
9912 // Return the new vector
Craig Topper48d114b2014-04-26 18:35:24 +00009913 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
Chris Lattner5336a592006-03-19 01:27:56 +00009914}
9915
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +00009916SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9917 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9918 EVT ResultVT = EVE->getValueType(0);
9919 EVT VecEltVT = InVecVT.getVectorElementType();
9920 unsigned Align = OriginalLoad->getAlignment();
9921 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9922 VecEltVT.getTypeForEVT(*DAG.getContext()));
9923
9924 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9925 return SDValue();
9926
9927 Align = NewAlign;
9928
9929 SDValue NewPtr = OriginalLoad->getBasePtr();
9930 SDValue Offset;
9931 EVT PtrType = NewPtr.getValueType();
9932 MachinePointerInfo MPI;
9933 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9934 int Elt = ConstEltNo->getZExtValue();
9935 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9936 if (TLI.isBigEndian())
9937 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9938 Offset = DAG.getConstant(PtrOff, PtrType);
9939 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9940 } else {
9941 Offset = DAG.getNode(
9942 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9943 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9944 if (TLI.isBigEndian())
9945 Offset = DAG.getNode(
9946 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9947 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9948 MPI = OriginalLoad->getPointerInfo();
9949 }
9950 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9951
9952 // The replacement we need to do here is a little tricky: we need to
9953 // replace an extractelement of a load with a load.
9954 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9955 // Note that this replacement assumes that the extractvalue is the only
9956 // use of the load; that's okay because we don't want to perform this
9957 // transformation in other cases anyway.
9958 SDValue Load;
9959 SDValue Chain;
9960 if (ResultVT.bitsGT(VecEltVT)) {
9961 // If the result type of vextract is wider than the load, then issue an
9962 // extending load instead.
9963 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9964 ? ISD::ZEXTLOAD
9965 : ISD::EXTLOAD;
9966 Load = DAG.getExtLoad(
9967 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
9968 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9969 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9970 Chain = Load.getValue(1);
9971 } else {
9972 Load = DAG.getLoad(
9973 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9974 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9975 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9976 Chain = Load.getValue(1);
9977 if (ResultVT.bitsLT(VecEltVT))
9978 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9979 else
9980 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9981 }
9982 WorklistRemover DeadNodes(*this);
9983 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9984 SDValue To[] = { Load, Chain };
9985 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9986 // Since we're explicitly calling ReplaceAllUses, add the new node to the
9987 // worklist explicitly as well.
9988 AddToWorklist(Load.getNode());
9989 AddUsersToWorklist(Load.getNode()); // Add users too
9990 // Make sure to revisit this node to clean it up; it will usually be dead.
9991 AddToWorklist(EVE);
9992 ++OpsNarrowed;
9993 return SDValue(EVE, 0);
9994}
9995
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009996SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +00009997 // (vextract (scalar_to_vector val, 0) -> val
9998 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009999 EVT VT = InVec.getValueType();
10000 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +000010001
Duncan Sands6be291a2011-05-09 08:03:33 +000010002 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10003 // Check if the result type doesn't match the inserted element type. A
10004 // SCALAR_TO_VECTOR may truncate the inserted element and the
10005 // EXTRACT_VECTOR_ELT may widen the extracted vector.
10006 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +000010007 if (InOp.getValueType() != NVT) {
10008 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +000010009 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +000010010 }
10011 return InOp;
10012 }
Evan Cheng1120279a2008-05-13 08:35:03 +000010013
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010014 SDValue EltNo = N->getOperand(1);
10015 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10016
10017 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10018 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +000010019 // we may introduce new vector instructions which are not backed by TD
10020 // patterns. For example on AVX, extracting elements from a wide vector
Hal Finkel02807592014-03-31 11:43:19 +000010021 // without using extract_subvector. However, if we can find an underlying
10022 // scalar value, then we can always use that.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010023 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Hal Finkel02807592014-03-31 11:43:19 +000010024 && ConstEltNo) {
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010025 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10026 int NumElem = VT.getVectorNumElements();
10027 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10028 // Find the new index to extract from.
10029 int OrigElt = SVOp->getMaskElt(Elt);
10030
10031 // Extracting an undef index is undef.
10032 if (OrigElt == -1)
10033 return DAG.getUNDEF(NVT);
10034
10035 // Select the right vector half to extract from.
Hal Finkel02807592014-03-31 11:43:19 +000010036 SDValue SVInVec;
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010037 if (OrigElt < NumElem) {
Hal Finkel02807592014-03-31 11:43:19 +000010038 SVInVec = InVec->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010039 } else {
Hal Finkel02807592014-03-31 11:43:19 +000010040 SVInVec = InVec->getOperand(1);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010041 OrigElt -= NumElem;
10042 }
10043
Hal Finkel02807592014-03-31 11:43:19 +000010044 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10045 SDValue InOp = SVInVec.getOperand(OrigElt);
10046 if (InOp.getValueType() != NVT) {
10047 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10048 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10049 }
10050
10051 return InOp;
10052 }
10053
10054 // FIXME: We should handle recursing on other vector shuffles and
10055 // scalar_to_vector here as well.
10056
10057 if (!LegalOperations) {
10058 EVT IndexTy = TLI.getVectorIdxTy();
10059 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10060 SVInVec, DAG.getConstant(OrigElt, IndexTy));
10061 }
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010062 }
10063
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010064 bool BCNumEltsChanged = false;
10065 EVT ExtVT = VT.getVectorElementType();
10066 EVT LVT = ExtVT;
10067
10068 // If the result of load has to be truncated, then it's not necessarily
10069 // profitable.
10070 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10071 return SDValue();
10072
10073 if (InVec.getOpcode() == ISD::BITCAST) {
10074 // Don't duplicate a load with other uses.
10075 if (!InVec.hasOneUse())
10076 return SDValue();
10077
10078 EVT BCVT = InVec.getOperand(0).getValueType();
10079 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10080 return SDValue();
10081 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10082 BCNumEltsChanged = true;
10083 InVec = InVec.getOperand(0);
10084 ExtVT = BCVT.getVectorElementType();
10085 }
10086
10087 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10088 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10089 ISD::isNormalLoad(InVec.getNode()) &&
10090 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10091 SDValue Index = N->getOperand(1);
10092 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10093 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10094 OrigLoad);
10095 }
10096
Evan Cheng1120279a2008-05-13 08:35:03 +000010097 // Perform only after legalization to ensure build_vector / vector_shuffle
10098 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010099 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000010100
Mon P Wangca6d6de2009-01-17 00:07:25 +000010101 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10102 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10103 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +000010104
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010105 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +000010106 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000010107
Craig Topperc0196b12014-04-14 00:51:57 +000010108 LoadSDNode *LN0 = nullptr;
10109 const ShuffleVectorSDNode *SVN = nullptr;
Bill Wendling27d9dd42009-01-30 23:36:47 +000010110 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010111 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +000010112 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +000010113 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +000010114 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +000010115 // Don't duplicate a load with other uses.
10116 if (!InVec.hasOneUse())
10117 return SDValue();
10118
Evan Cheng1120279a2008-05-13 08:35:03 +000010119 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +000010120 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010121 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10122 // =>
10123 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +000010124
Eli Friedmane96286c2011-12-26 22:49:32 +000010125 // Don't duplicate a load with other uses.
10126 if (!InVec.hasOneUse())
10127 return SDValue();
10128
Mon P Wangb5eb7202008-12-11 00:26:16 +000010129 // If the bit convert changed the number of elements, it is unsafe
10130 // to examine the mask.
10131 if (BCNumEltsChanged)
10132 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +000010133
10134 // Select the input vector, guarding against out of range extract vector.
10135 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +000010136 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +000010137 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10138
Eli Friedmane96286c2011-12-26 22:49:32 +000010139 if (InVec.getOpcode() == ISD::BITCAST) {
10140 // Don't duplicate a load with other uses.
10141 if (!InVec.hasOneUse())
10142 return SDValue();
10143
Evan Cheng1120279a2008-05-13 08:35:03 +000010144 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +000010145 }
Gabor Greiff304a7a2008-08-28 21:40:38 +000010146 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010147 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +000010148 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010149 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
Evan Cheng0de312d2007-10-06 08:19:55 +000010150 }
10151 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010152
Eli Friedmane96286c2011-12-26 22:49:32 +000010153 // Make sure we found a non-volatile load and the extractelement is
10154 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +000010155 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010156 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000010157
Eric Christopherc6418b12010-11-03 20:44:42 +000010158 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10159 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +000010160 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +000010161
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010162 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
Evan Cheng0de312d2007-10-06 08:19:55 +000010163 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010164
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010165 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000010166}
Evan Cheng0de312d2007-10-06 08:19:55 +000010167
Michael Liao6d106b72012-10-23 23:06:52 +000010168// Simplify (build_vec (ext )) to (bitcast (build_vec ))
10169SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10170 // We perform this optimization post type-legalization because
10171 // the type-legalizer often scalarizes integer-promoted vectors.
10172 // Performing this optimization before may create bit-casts which
10173 // will be type-legalized to complex code sequences.
10174 // We perform this optimization only before the operation legalizer because we
10175 // may introduce illegal operations.
10176 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10177 return SDValue();
10178
Dan Gohmana8665142007-06-25 16:23:39 +000010179 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010180 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +000010181 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010182
Nadav Rotembf6568b2011-10-29 21:23:04 +000010183 // Check to see if this is a BUILD_VECTOR of a bunch of values
10184 // which come from any_extend or zero_extend nodes. If so, we can create
10185 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +000010186 // optimizations. We do not handle sign-extend because we can't fill the sign
10187 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010188 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +000010189 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +000010190
Craig Topper02cb0fb2012-01-17 09:09:48 +000010191 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +000010192 SDValue In = N->getOperand(i);
10193 // Ignore undef inputs.
10194 if (In.getOpcode() == ISD::UNDEF) continue;
10195
10196 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10197 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10198
Nadav Rotemf3103612011-10-31 20:08:25 +000010199 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010200 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +000010201 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010202 break;
10203 }
10204
10205 // The input is a ZeroExt or AnyExt. Check the original type.
10206 EVT InTy = In.getOperand(0).getValueType();
10207
10208 // Check that all of the widened source types are the same.
10209 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +000010210 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010211 SourceType = InTy;
10212 else if (InTy != SourceType) {
10213 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +000010214 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010215 break;
10216 }
10217
10218 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +000010219 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010220 }
10221
Nadav Rotemf3103612011-10-31 20:08:25 +000010222 // In order to have valid types, all of the inputs must be extended from the
10223 // same source type and all of the inputs must be any or zero extend.
10224 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +000010225 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010226 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +000010227 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10228 isPowerOf2_32(SourceType.getSizeInBits());
10229
Nadav Rotem6fd1d322012-03-15 08:49:06 +000010230 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10231 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +000010232 if (!ValidTypes)
10233 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +000010234
Michael Liao6d106b72012-10-23 23:06:52 +000010235 bool isLE = TLI.isLittleEndian();
10236 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10237 assert(ElemRatio > 1 && "Invalid element size ratio");
10238 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10239 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010240
Michael Liao6d106b72012-10-23 23:06:52 +000010241 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10242 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010243
Michael Liao6d106b72012-10-23 23:06:52 +000010244 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +000010245 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +000010246 SDValue Cast = N->getOperand(i);
10247 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10248 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10249 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10250 SDValue In;
10251 if (Cast.getOpcode() == ISD::UNDEF)
10252 In = DAG.getUNDEF(SourceType);
10253 else
10254 In = Cast->getOperand(0);
10255 unsigned Index = isLE ? (i * ElemRatio) :
10256 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +000010257
Michael Liao6d106b72012-10-23 23:06:52 +000010258 assert(Index < Ops.size() && "Invalid index");
10259 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010260 }
Chris Lattner5336a592006-03-19 01:27:56 +000010261
Michael Liao6d106b72012-10-23 23:06:52 +000010262 // The type of the new BUILD_VECTOR node.
10263 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10264 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10265 "Invalid vector size");
10266 // Check if the new vector type is legal.
10267 if (!isTypeLegal(VecVT)) return SDValue();
10268
10269 // Make the new BUILD_VECTOR.
Craig Topper48d114b2014-04-26 18:35:24 +000010270 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
Michael Liao6d106b72012-10-23 23:06:52 +000010271
10272 // The new BUILD_VECTOR node has the potential to be further optimized.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010273 AddToWorklist(BV.getNode());
Michael Liao6d106b72012-10-23 23:06:52 +000010274 // Bitcast to the desired type.
10275 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10276}
10277
Michael Liao59229792012-10-24 04:14:18 +000010278SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10279 EVT VT = N->getValueType(0);
10280
10281 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010282 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +000010283
10284 EVT SrcVT = MVT::Other;
10285 unsigned Opcode = ISD::DELETED_NODE;
10286 unsigned NumDefs = 0;
10287
10288 for (unsigned i = 0; i != NumInScalars; ++i) {
10289 SDValue In = N->getOperand(i);
10290 unsigned Opc = In.getOpcode();
10291
10292 if (Opc == ISD::UNDEF)
10293 continue;
10294
10295 // If all scalar values are floats and converted from integers.
10296 if (Opcode == ISD::DELETED_NODE &&
10297 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10298 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +000010299 }
Tom Stellard567f8862013-01-02 22:13:01 +000010300
Michael Liao59229792012-10-24 04:14:18 +000010301 if (Opc != Opcode)
10302 return SDValue();
10303
10304 EVT InVT = In.getOperand(0).getValueType();
10305
10306 // If all scalar values are typed differently, bail out. It's chosen to
10307 // simplify BUILD_VECTOR of integer types.
10308 if (SrcVT == MVT::Other)
10309 SrcVT = InVT;
10310 if (SrcVT != InVT)
10311 return SDValue();
10312 NumDefs++;
10313 }
10314
10315 // If the vector has just one element defined, it's not worth to fold it into
10316 // a vectorized one.
10317 if (NumDefs < 2)
10318 return SDValue();
10319
10320 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10321 && "Should only handle conversion from integer to float.");
10322 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10323
10324 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000010325
10326 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10327 return SDValue();
10328
Michael Liao59229792012-10-24 04:14:18 +000010329 SmallVector<SDValue, 8> Opnds;
10330 for (unsigned i = 0; i != NumInScalars; ++i) {
10331 SDValue In = N->getOperand(i);
10332
10333 if (In.getOpcode() == ISD::UNDEF)
10334 Opnds.push_back(DAG.getUNDEF(SrcVT));
10335 else
10336 Opnds.push_back(In.getOperand(0));
10337 }
Craig Topper48d114b2014-04-26 18:35:24 +000010338 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010339 AddToWorklist(BV.getNode());
Michael Liao59229792012-10-24 04:14:18 +000010340
10341 return DAG.getNode(Opcode, dl, VT, BV);
10342}
10343
Michael Liao6d106b72012-10-23 23:06:52 +000010344SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10345 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010346 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000010347 EVT VT = N->getValueType(0);
10348
10349 // A vector built entirely of undefs is undef.
10350 if (ISD::allOperandsUndef(N))
10351 return DAG.getUNDEF(VT);
10352
10353 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10354 if (V.getNode())
10355 return V;
10356
Michael Liao59229792012-10-24 04:14:18 +000010357 V = reduceBuildVecConvertToConvertBuildVec(N);
10358 if (V.getNode())
10359 return V;
10360
Dan Gohmana8665142007-06-25 16:23:39 +000010361 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10362 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10363 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010364
10365 // May only combine to shuffle after legalize if shuffle is legal.
Owen Anderson3eb910b2014-08-28 17:49:58 +000010366 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010367 return SDValue();
10368
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010369 SDValue VecIn1, VecIn2;
Chris Lattnerc9992542006-03-28 20:28:38 +000010370 for (unsigned i = 0; i != NumInScalars; ++i) {
10371 // Ignore undef inputs.
10372 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010373
Dan Gohmana8665142007-06-25 16:23:39 +000010374 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000010375 // constant index, bail out.
Dan Gohmana8665142007-06-25 16:23:39 +000010376 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Chris Lattnerc9992542006-03-28 20:28:38 +000010377 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
Craig Topperc0196b12014-04-14 00:51:57 +000010378 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010379 break;
10380 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010381
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010382 // We allow up to two distinct input vectors.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010383 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010384 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10385 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010386
Craig Topperc0196b12014-04-14 00:51:57 +000010387 if (!VecIn1.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010388 VecIn1 = ExtractedFromVec;
Craig Topperc0196b12014-04-14 00:51:57 +000010389 } else if (!VecIn2.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010390 VecIn2 = ExtractedFromVec;
10391 } else {
10392 // Too many inputs.
Craig Topperc0196b12014-04-14 00:51:57 +000010393 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010394 break;
10395 }
10396 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010397
Jim Grosbach2eb60fd2014-04-29 22:41:50 +000010398 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010399 if (VecIn1.getNode()) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010400 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000010401 for (unsigned i = 0; i != NumInScalars; ++i) {
10402 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010403 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010404 continue;
10405 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010406
Rafael Espindolab93db662009-04-24 12:40:33 +000010407 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010408 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000010409 SDValue ExtVal = Extract.getOperand(1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010410 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000010411 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10412 if (ExtIndex > VT.getVectorNumElements())
10413 return SDValue();
Wesley Peck527da1b2010-11-23 03:31:01 +000010414
Nate Begeman5f829d82009-04-29 05:20:52 +000010415 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000010416 continue;
10417 }
10418
10419 // Otherwise, use InIdx + VecSize
Mon P Wang523c0852009-03-17 06:33:10 +000010420 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010421 Mask.push_back(Idx+NumInScalars);
Chris Lattnerc9992542006-03-28 20:28:38 +000010422 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010423
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010424 // We can't generate a shuffle node with mismatched input and output types.
10425 // Attempt to transform a single input vector to the correct type.
10426 if ((VT != VecIn1.getValueType())) {
10427 // We don't support shuffeling between TWO values of different types.
Craig Topperc0196b12014-04-14 00:51:57 +000010428 if (VecIn2.getNode())
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010429 return SDValue();
10430
10431 // We only support widening of vectors which are half the size of the
10432 // output registers. For example XMM->YMM widening on X86 with AVX.
10433 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10434 return SDValue();
10435
James Molloy1e5c6112012-09-10 14:01:21 +000010436 // If the input vector type has a different base type to the output
10437 // vector type, bail out.
10438 if (VecIn1.getValueType().getVectorElementType() !=
10439 VT.getVectorElementType())
10440 return SDValue();
10441
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010442 // Widen the input vector by adding undef values.
Michael Liao6d106b72012-10-23 23:06:52 +000010443 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010444 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010445 }
10446
10447 // If VecIn2 is unused then change it to undef.
10448 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10449
Nadav Rotem841c9a82012-09-20 08:53:31 +000010450 // Check that we were able to transform all incoming values to the same
10451 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000010452 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10453 VecIn1.getValueType() != VT)
10454 return SDValue();
10455
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010456 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
Nadav Rotem0c650642012-02-13 12:42:26 +000010457 if (!isTypeLegal(VT))
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010458 return SDValue();
10459
Dan Gohmana8665142007-06-25 16:23:39 +000010460 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010461 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000010462 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010463 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000010464 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000010465 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010466
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010467 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000010468}
10469
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010470SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000010471 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10472 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10473 // inputs come from at most two distinct vectors, turn this into a shuffle
10474 // node.
10475
10476 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000010477 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000010478 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010479
Nadav Rotem01892102012-07-14 21:30:27 +000010480 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010481 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010482 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010483 return DAG.getUNDEF(VT);
10484
10485 // Optimize concat_vectors where one of the vectors is undef.
10486 if (N->getNumOperands() == 2 &&
10487 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10488 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000010489 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010490
10491 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10492 if (In->getOpcode() == ISD::BITCAST &&
10493 !In->getOperand(0)->getValueType(0).isVector()) {
10494 SDValue Scalar = In->getOperand(0);
10495 EVT SclTy = Scalar->getValueType(0);
10496
10497 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10498 return SDValue();
10499
10500 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10501 VT.getSizeInBits() / SclTy.getSizeInBits());
10502 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10503 return SDValue();
10504
10505 SDLoc dl = SDLoc(N);
10506 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10507 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10508 }
10509 }
Nadav Rotem01892102012-07-14 21:30:27 +000010510
Robert Lougher7d9084f2014-02-11 15:42:46 +000010511 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10512 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10513 if (N->getNumOperands() == 2 &&
10514 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10515 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10516 EVT VT = N->getValueType(0);
10517 SDValue N0 = N->getOperand(0);
10518 SDValue N1 = N->getOperand(1);
10519 SmallVector<SDValue, 8> Opnds;
10520 unsigned BuildVecNumElts = N0.getNumOperands();
10521
Hao Liu71224b02014-07-10 03:41:50 +000010522 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10523 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10524 if (SclTy0.isFloatingPoint()) {
10525 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10526 Opnds.push_back(N0.getOperand(i));
10527 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10528 Opnds.push_back(N1.getOperand(i));
10529 } else {
10530 // If BUILD_VECTOR are from built from integer, they may have different
10531 // operand types. Get the smaller type and truncate all operands to it.
10532 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10533 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10534 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10535 N0.getOperand(i)));
10536 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10537 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10538 N1.getOperand(i)));
10539 }
Robert Lougher7d9084f2014-02-11 15:42:46 +000010540
Craig Topper48d114b2014-04-26 18:35:24 +000010541 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Robert Lougher7d9084f2014-02-11 15:42:46 +000010542 }
10543
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010544 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10545 // nodes often generate nop CONCAT_VECTOR nodes.
10546 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10547 // place the incoming vectors at the exact same location.
10548 SDValue SingleSource = SDValue();
10549 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10550
10551 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10552 SDValue Op = N->getOperand(i);
10553
10554 if (Op.getOpcode() == ISD::UNDEF)
10555 continue;
10556
10557 // Check if this is the identity extract:
10558 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10559 return SDValue();
10560
10561 // Find the single incoming vector for the extract_subvector.
10562 if (SingleSource.getNode()) {
10563 if (Op.getOperand(0) != SingleSource)
10564 return SDValue();
10565 } else {
10566 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000010567
10568 // Check the source type is the same as the type of the result.
10569 // If not, this concat may extend the vector, so we can not
10570 // optimize it away.
10571 if (SingleSource.getValueType() != N->getValueType(0))
10572 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010573 }
10574
10575 unsigned IdentityIndex = i * PartNumElem;
10576 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10577 // The extract index must be constant.
10578 if (!CS)
10579 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000010580
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010581 // Check that we are reading from the identity index.
10582 if (CS->getZExtValue() != IdentityIndex)
10583 return SDValue();
10584 }
10585
10586 if (SingleSource.getNode())
10587 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000010588
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010589 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000010590}
10591
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010592SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10593 EVT NVT = N->getValueType(0);
10594 SDValue V = N->getOperand(0);
10595
Michael Liao7a442c802012-10-17 20:48:33 +000010596 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10597 // Combine:
10598 // (extract_subvec (concat V1, V2, ...), i)
10599 // Into:
10600 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000010601 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10602 // type.
Michael Liao2c235802012-10-19 03:17:00 +000010603 if (V->getOperand(0).getValueType() != NVT)
10604 return SDValue();
Michael Liao7a442c802012-10-17 20:48:33 +000010605 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10606 unsigned NumElems = NVT.getVectorNumElements();
10607 assert((Idx % NumElems) == 0 &&
10608 "IDX in concat is not a multiple of the result vector length.");
10609 return V->getOperand(Idx / NumElems);
10610 }
10611
Michael Liaobb05a1d2013-03-25 23:47:35 +000010612 // Skip bitcasting
10613 if (V->getOpcode() == ISD::BITCAST)
10614 V = V.getOperand(0);
10615
10616 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010617 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000010618 // Handle only simple case where vector being inserted and vector
10619 // being extracted are of same type, and are half size of larger vectors.
10620 EVT BigVT = V->getOperand(0).getValueType();
10621 EVT SmallVT = V->getOperand(1).getValueType();
10622 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10623 return SDValue();
10624
10625 // Only handle cases where both indexes are constants with the same type.
10626 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10627 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10628
10629 if (InsIdx && ExtIdx &&
10630 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10631 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10632 // Combine:
10633 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10634 // Into:
10635 // indices are equal or bit offsets are equal => V1
10636 // otherwise => (extract_subvec V1, ExtIdx)
10637 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10638 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10639 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10640 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10641 DAG.getNode(ISD::BITCAST, dl,
10642 N->getOperand(0).getValueType(),
10643 V->getOperand(0)), N->getOperand(1));
10644 }
10645 }
10646
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010647 return SDValue();
10648}
10649
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010650// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10651static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10652 EVT VT = N->getValueType(0);
10653 unsigned NumElts = VT.getVectorNumElements();
10654
10655 SDValue N0 = N->getOperand(0);
10656 SDValue N1 = N->getOperand(1);
10657 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10658
10659 SmallVector<SDValue, 4> Ops;
10660 EVT ConcatVT = N0.getOperand(0).getValueType();
10661 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10662 unsigned NumConcats = NumElts / NumElemsPerConcat;
10663
10664 // Look at every vector that's inserted. We're looking for exact
10665 // subvector-sized copies from a concatenated vector
10666 for (unsigned I = 0; I != NumConcats; ++I) {
10667 // Make sure we're dealing with a copy.
10668 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000010669 bool AllUndef = true, NoUndef = true;
10670 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10671 if (SVN->getMaskElt(J) >= 0)
10672 AllUndef = false;
10673 else
10674 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010675 }
10676
Hao Liubc601962013-05-13 02:07:05 +000010677 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000010678 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10679 return SDValue();
10680
10681 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10682 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10683 return SDValue();
10684
10685 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10686 if (FirstElt < N0.getNumOperands())
10687 Ops.push_back(N0.getOperand(FirstElt));
10688 else
10689 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10690
10691 } else if (AllUndef) {
10692 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10693 } else { // Mixed with general masks and undefs, can't do optimization.
10694 return SDValue();
10695 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010696 }
10697
Craig Topper48d114b2014-04-26 18:35:24 +000010698 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010699}
10700
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010701SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010702 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010703 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010704
Mon P Wang25f01062008-11-10 04:46:22 +000010705 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000010706 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000010707
Craig Topper5894fe42012-04-09 05:16:56 +000010708 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000010709
Craig Topper279c77b2012-01-04 08:07:43 +000010710 // Canonicalize shuffle undef, undef -> undef
10711 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10712 return DAG.getUNDEF(VT);
10713
10714 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10715
10716 // Canonicalize shuffle v, v -> v, undef
10717 if (N0 == N1) {
10718 SmallVector<int, 8> NewMask;
10719 for (unsigned i = 0; i != NumElts; ++i) {
10720 int Idx = SVN->getMaskElt(i);
10721 if (Idx >= (int)NumElts) Idx -= NumElts;
10722 NewMask.push_back(Idx);
10723 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010724 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010725 &NewMask[0]);
10726 }
10727
10728 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10729 if (N0.getOpcode() == ISD::UNDEF) {
10730 SmallVector<int, 8> NewMask;
10731 for (unsigned i = 0; i != NumElts; ++i) {
10732 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000010733 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000010734 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000010735 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000010736 else
10737 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000010738 }
10739 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000010740 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010741 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010742 &NewMask[0]);
10743 }
10744
10745 // Remove references to rhs if it is undef
10746 if (N1.getOpcode() == ISD::UNDEF) {
10747 bool Changed = false;
10748 SmallVector<int, 8> NewMask;
10749 for (unsigned i = 0; i != NumElts; ++i) {
10750 int Idx = SVN->getMaskElt(i);
10751 if (Idx >= (int)NumElts) {
10752 Idx = -1;
10753 Changed = true;
10754 }
10755 NewMask.push_back(Idx);
10756 }
10757 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000010758 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000010759 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000010760
Bob Wilsonf63da122010-10-28 17:06:14 +000010761 // If it is a splat, check if the argument vector is another splat or a
10762 // build_vector with all scalar elements the same.
Bob Wilsonf63da122010-10-28 17:06:14 +000010763 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000010764 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000010765
Dan Gohmana8665142007-06-25 16:23:39 +000010766 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000010767 // not the number of vector elements, look through it. Be careful not to
10768 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000010769 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010770 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000010771 if (ConvInput.getValueType().isVector() &&
10772 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000010773 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000010774 }
10775
Dan Gohmana8665142007-06-25 16:23:39 +000010776 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000010777 assert(V->getNumOperands() == NumElts &&
10778 "BUILD_VECTOR has wrong number of operands");
10779 SDValue Base;
10780 bool AllSame = true;
10781 for (unsigned i = 0; i != NumElts; ++i) {
10782 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10783 Base = V->getOperand(i);
10784 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000010785 }
Evan Cheng7c970b92006-07-21 08:25:53 +000010786 }
Bob Wilsonf63da122010-10-28 17:06:14 +000010787 // Splat of <u, u, u, u>, return <u, u, u, u>
10788 if (!Base.getNode())
10789 return N0;
10790 for (unsigned i = 0; i != NumElts; ++i) {
10791 if (V->getOperand(i) != Base) {
10792 AllSame = false;
10793 break;
10794 }
10795 }
10796 // Splat of <x, x, x, x>, return <x, x, x, x>
10797 if (AllSame)
10798 return N0;
Evan Cheng7c970b92006-07-21 08:25:53 +000010799 }
10800 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010801
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010802 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10803 Level < AfterLegalizeVectorOps &&
10804 (N1.getOpcode() == ISD::UNDEF ||
10805 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10806 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10807 SDValue V = partitionShuffleOfConcats(N, DAG);
10808
10809 if (V.getNode())
10810 return V;
10811 }
10812
Nadav Rotemb0783502012-04-01 19:31:22 +000010813 // If this shuffle node is simply a swizzle of another shuffle node,
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010814 // then try to simplify it.
Nadav Rotemb0783502012-04-01 19:31:22 +000010815 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10816 N1.getOpcode() == ISD::UNDEF) {
10817
Nadav Rotemb0783502012-04-01 19:31:22 +000010818 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10819
Craig Topper5894fe42012-04-09 05:16:56 +000010820 // The incoming shuffle must be of the same type as the result of the
10821 // current shuffle.
10822 assert(OtherSV->getOperand(0).getValueType() == VT &&
10823 "Shuffle types don't match");
Nadav Rotemb0783502012-04-01 19:31:22 +000010824
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010825 SmallVector<int, 4> Mask;
10826 // Compute the combined shuffle mask.
Nadav Rotemb0783502012-04-01 19:31:22 +000010827 for (unsigned i = 0; i != NumElts; ++i) {
10828 int Idx = SVN->getMaskElt(i);
Craig Topper5894fe42012-04-09 05:16:56 +000010829 assert(Idx < (int)NumElts && "Index references undef operand");
Nadav Rotemb0783502012-04-01 19:31:22 +000010830 // Next, this index comes from the first value, which is the incoming
10831 // shuffle. Adopt the incoming index.
10832 if (Idx >= 0)
10833 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010834 Mask.push_back(Idx);
Nadav Rotemb0783502012-04-01 19:31:22 +000010835 }
Andrea Di Biagiob23bad12014-08-16 00:29:44 +000010836
10837 // Check if all indices in Mask are Undef. In case, propagate Undef.
10838 bool isUndefMask = true;
10839 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10840 isUndefMask &= Mask[i] < 0;
10841
10842 if (isUndefMask)
10843 return DAG.getUNDEF(VT);
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010844
10845 bool CommuteOperands = false;
10846 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10847 // To be valid, the combine shuffle mask should only reference elements
10848 // from one of the two vectors in input to the inner shufflevector.
10849 bool IsValidMask = true;
10850 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10851 // See if the combined mask only reference undefs or elements coming
10852 // from the first shufflevector operand.
10853 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010854
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010855 if (!IsValidMask) {
10856 IsValidMask = true;
10857 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10858 // Check that all the elements come from the second shuffle operand.
10859 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10860 CommuteOperands = IsValidMask;
10861 }
10862
10863 // Early exit if the combined shuffle mask is not valid.
10864 if (!IsValidMask)
10865 return SDValue();
10866 }
10867
10868 // See if this pair of shuffles can be safely folded according to either
10869 // of the following rules:
10870 // shuffle(shuffle(x, y), undef) -> x
10871 // shuffle(shuffle(x, undef), undef) -> x
10872 // shuffle(shuffle(x, y), undef) -> y
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010873 bool IsIdentityMask = true;
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010874 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010875 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10876 // Skip Undefs.
10877 if (Mask[i] < 0)
10878 continue;
10879
10880 // The combined shuffle must map each index to itself.
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010881 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010882 }
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010883
10884 if (IsIdentityMask) {
10885 if (CommuteOperands)
10886 // optimize shuffle(shuffle(x, y), undef) -> y.
10887 return OtherSV->getOperand(1);
10888
10889 // optimize shuffle(shuffle(x, undef), undef) -> x
10890 // optimize shuffle(shuffle(x, y), undef) -> x
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010891 return OtherSV->getOperand(0);
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010892 }
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010893
10894 // It may still be beneficial to combine the two shuffles if the
10895 // resulting shuffle is legal.
Andrea Di Biagioace8e1e2014-08-13 16:09:40 +000010896 if (TLI.isTypeLegal(VT)) {
10897 if (!CommuteOperands) {
10898 if (TLI.isShuffleMaskLegal(Mask, VT))
10899 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10900 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10901 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10902 &Mask[0]);
10903 } else {
10904 // Compute the commuted shuffle mask.
10905 for (unsigned i = 0; i != NumElts; ++i) {
10906 int idx = Mask[i];
10907 if (idx < 0)
10908 continue;
10909 else if (idx < (int)NumElts)
10910 Mask[i] = idx + NumElts;
10911 else
10912 Mask[i] = idx - NumElts;
10913 }
10914
10915 if (TLI.isShuffleMaskLegal(Mask, VT))
10916 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
10917 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
10918 &Mask[0]);
10919 }
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010920 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010921 }
10922
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000010923 // Canonicalize shuffles according to rules:
10924 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10925 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10926 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10927 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10928 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10929 TLI.isTypeLegal(VT)) {
10930 // The incoming shuffle must be of the same type as the result of the
10931 // current shuffle.
10932 assert(N1->getOperand(0).getValueType() == VT &&
10933 "Shuffle types don't match");
10934
10935 SDValue SV0 = N1->getOperand(0);
10936 SDValue SV1 = N1->getOperand(1);
10937 bool HasSameOp0 = N0 == SV0;
10938 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10939 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10940 // Commute the operands of this shuffle so that next rule
10941 // will trigger.
10942 return DAG.getCommutedVectorShuffle(*SVN);
10943 }
10944
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010945 // Try to fold according to rules:
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010946 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10947 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10948 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10949 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010950 // Don't try to fold shuffles with illegal type.
10951 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010952 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010953 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10954
10955 // The incoming shuffle must be of the same type as the result of the
10956 // current shuffle.
10957 assert(OtherSV->getOperand(0).getValueType() == VT &&
10958 "Shuffle types don't match");
10959
10960 SDValue SV0 = OtherSV->getOperand(0);
10961 SDValue SV1 = OtherSV->getOperand(1);
10962 bool HasSameOp0 = N1 == SV0;
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010963 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10964 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010965 // Early exit.
10966 return SDValue();
10967
10968 SmallVector<int, 4> Mask;
10969 // Compute the combined shuffle mask for a shuffle with SV0 as the first
10970 // operand, and SV1 as the second operand.
10971 for (unsigned i = 0; i != NumElts; ++i) {
10972 int Idx = SVN->getMaskElt(i);
10973 if (Idx < 0) {
10974 // Propagate Undef.
10975 Mask.push_back(Idx);
10976 continue;
10977 }
10978
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010979 if (Idx < (int)NumElts) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010980 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010981 if (IsSV1Undef && Idx >= (int) NumElts)
10982 Idx = -1; // Propagate Undef.
10983 } else
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010984 Idx = HasSameOp0 ? Idx - NumElts : Idx;
10985
10986 Mask.push_back(Idx);
10987 }
10988
Andrea Di Biagiob23bad12014-08-16 00:29:44 +000010989 // Check if all indices in Mask are Undef. In case, propagate Undef.
10990 bool isUndefMask = true;
10991 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10992 isUndefMask &= Mask[i] < 0;
10993
10994 if (isUndefMask)
10995 return DAG.getUNDEF(VT);
10996
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010997 // Avoid introducing shuffles with illegal mask.
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010998 if (TLI.isShuffleMaskLegal(Mask, VT)) {
10999 if (IsSV1Undef)
11000 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11001 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11002 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011003 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000011004 }
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011005 }
11006
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011007 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000011008}
11009
Manman Ren413a6cb2014-01-31 01:10:35 +000011010SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11011 SDValue N0 = N->getOperand(0);
11012 SDValue N2 = N->getOperand(2);
11013
11014 // If the input vector is a concatenation, and the insert replaces
11015 // one of the halves, we can optimize into a single concat_vectors.
11016 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11017 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11018 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11019 EVT VT = N->getValueType(0);
11020
11021 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11022 // (concat_vectors Z, Y)
11023 if (InsIdx == 0)
11024 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11025 N->getOperand(1), N0.getOperand(1));
11026
11027 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11028 // (concat_vectors X, Z)
11029 if (InsIdx == VT.getVectorNumElements()/2)
11030 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11031 N0.getOperand(0), N->getOperand(1));
11032 }
11033
11034 return SDValue();
11035}
11036
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011037/// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11038/// with the destination vector and a zero vector.
Dan Gohmana8665142007-06-25 16:23:39 +000011039/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000011040/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011041SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011042 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011043 SDLoc dl(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011044 SDValue LHS = N->getOperand(0);
11045 SDValue RHS = N->getOperand(1);
Dan Gohmana8665142007-06-25 16:23:39 +000011046 if (N->getOpcode() == ISD::AND) {
Wesley Peck527da1b2010-11-23 03:31:01 +000011047 if (RHS.getOpcode() == ISD::BITCAST)
Evan Chenga320abc2006-04-20 08:56:16 +000011048 RHS = RHS.getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000011049 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011050 SmallVector<int, 8> Indices;
11051 unsigned NumElts = RHS.getNumOperands();
Evan Chenga320abc2006-04-20 08:56:16 +000011052 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011053 SDValue Elt = RHS.getOperand(i);
Evan Chenga320abc2006-04-20 08:56:16 +000011054 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011055 return SDValue();
Craig Toppere5893f62012-04-09 05:59:53 +000011056
11057 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011058 Indices.push_back(i);
Evan Chenga320abc2006-04-20 08:56:16 +000011059 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011060 Indices.push_back(NumElts);
Evan Chenga320abc2006-04-20 08:56:16 +000011061 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011062 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000011063 }
11064
11065 // Let's see if the target supports this vector_shuffle.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011066 EVT RVT = RHS.getValueType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011067 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011068 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000011069
Dan Gohmana8665142007-06-25 16:23:39 +000011070 // Return the new VECTOR_SHUFFLE node.
Dan Gohman08c0a952009-09-23 21:02:20 +000011071 EVT EltVT = RVT.getVectorElementType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011072 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman08c0a952009-09-23 21:02:20 +000011073 DAG.getConstant(0, EltVT));
Craig Topper48d114b2014-04-26 18:35:24 +000011074 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
Wesley Peck527da1b2010-11-23 03:31:01 +000011075 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011076 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peck527da1b2010-11-23 03:31:01 +000011077 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000011078 }
11079 }
Bill Wendling31b50992009-01-30 23:59:18 +000011080
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011081 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000011082}
11083
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011084/// Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011085SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000011086 assert(N->getValueType(0).isVector() &&
11087 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000011088
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011089 SDValue LHS = N->getOperand(0);
11090 SDValue RHS = N->getOperand(1);
11091 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011092 if (Shuffle.getNode()) return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000011093
Dan Gohmana8665142007-06-25 16:23:39 +000011094 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000011095 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011096 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000011097 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000011098 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000011099 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11100 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000011101 return SDValue();
11102
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011103 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000011104 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011105 SDValue LHSOp = LHS.getOperand(i);
11106 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000011107
Evan Cheng64d28462006-05-31 06:08:35 +000011108 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000011109 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11110 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000011111 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000011112 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000011113 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000011114 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000011115 break;
11116 }
Bill Wendling31b50992009-01-30 23:59:18 +000011117
Bob Wilson54081442010-12-17 23:06:49 +000011118 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000011119 EVT RVT = RHSOp.getValueType();
11120 if (RVT != VT) {
11121 // Integer BUILD_VECTOR operands may have types larger than the element
11122 // size (e.g., when the element type is not legal). Prior to type
11123 // legalization, the types may not match between the two BUILD_VECTORS.
11124 // Truncate one of the operands to make them match.
11125 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011126 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000011127 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011128 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000011129 VT = RVT;
11130 }
11131 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000011132 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000011133 LHSOp, RHSOp);
11134 if (FoldOp.getOpcode() != ISD::UNDEF &&
11135 FoldOp.getOpcode() != ISD::Constant &&
11136 FoldOp.getOpcode() != ISD::ConstantFP)
11137 break;
11138 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011139 AddToWorklist(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000011140 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011141
Bob Wilson54081442010-12-17 23:06:49 +000011142 if (Ops.size() == LHS.getNumOperands())
Craig Topper48d114b2014-04-26 18:35:24 +000011143 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
Chris Lattner0442a182006-04-02 03:25:57 +000011144 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011145
Andrea Di Biagio446a5272014-05-30 23:17:53 +000011146 // Type legalization might introduce new shuffles in the DAG.
11147 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11148 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
11149 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11150 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11151 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11152 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11153 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11154 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11155
11156 if (SVN0->getMask().equals(SVN1->getMask())) {
11157 EVT VT = N->getValueType(0);
11158 SDValue UndefVector = LHS.getOperand(1);
11159 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11160 LHS.getOperand(0), RHS.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011161 AddUsersToWorklist(N);
Andrea Di Biagio446a5272014-05-30 23:17:53 +000011162 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11163 &SVN0->getMask()[0]);
11164 }
11165 }
11166
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011167 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000011168}
11169
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011170/// Visit a binary vector operation, like FABS/FNEG.
Craig Topper82384612012-09-11 01:45:21 +000011171SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topper82384612012-09-11 01:45:21 +000011172 assert(N->getValueType(0).isVector() &&
11173 "SimplifyVUnaryOp only works on vectors!");
11174
11175 SDValue N0 = N->getOperand(0);
11176
11177 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11178 return SDValue();
11179
11180 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11181 SmallVector<SDValue, 8> Ops;
11182 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11183 SDValue Op = N0.getOperand(i);
11184 if (Op.getOpcode() != ISD::UNDEF &&
11185 Op.getOpcode() != ISD::ConstantFP)
11186 break;
11187 EVT EltVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011188 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topper82384612012-09-11 01:45:21 +000011189 if (FoldOp.getOpcode() != ISD::UNDEF &&
11190 FoldOp.getOpcode() != ISD::ConstantFP)
11191 break;
11192 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011193 AddToWorklist(FoldOp.getNode());
Craig Topper82384612012-09-11 01:45:21 +000011194 }
11195
11196 if (Ops.size() != N0.getNumOperands())
11197 return SDValue();
11198
Craig Topper48d114b2014-04-26 18:35:24 +000011199 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
Craig Topper82384612012-09-11 01:45:21 +000011200}
11201
Andrew Trickef9de2a2013-05-25 02:42:55 +000011202SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011203 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000011204 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000011205
Bill Wendling31b50992009-01-30 23:59:18 +000011206 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000011207 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000011208
Nate Begeman2042aa52005-10-08 00:29:44 +000011209 // If we got a simplified select_cc node back from SimplifySelectCC, then
11210 // break it down into a new SETCC node, and a new SELECT node, and then return
11211 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000011212 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000011213 // Check to see if we got a select_cc back (to turn into setcc/select).
11214 // Otherwise, just return whatever node we got back, like fabs.
11215 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011216 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011217 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000011218 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000011219 SCC.getOperand(4));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011220 AddToWorklist(SETCC.getNode());
Chandler Carruth40dbd382014-08-04 21:29:59 +000011221 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11222 SCC.getOperand(2), SCC.getOperand(3));
Nate Begeman2042aa52005-10-08 00:29:44 +000011223 }
Bill Wendling31b50992009-01-30 23:59:18 +000011224
Nate Begeman2042aa52005-10-08 00:29:44 +000011225 return SCC;
11226 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011227 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011228}
11229
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011230/// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11231/// being selected between, see if we can simplify the select. Callers of this
11232/// should assume that TheSelect is deleted if this returns true. As such, they
11233/// should return the appropriate thing (e.g. the node) back to the top-level of
11234/// the DAG combiner loop to avoid it being looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011235bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011236 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011237
Nadav Rotema49a02a2011-02-11 19:57:47 +000011238 // Cannot simplify select with vector condition
11239 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11240
Chris Lattner6c14c352005-10-18 06:04:22 +000011241 // If this is a select from two identical things, try to pull the operation
11242 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000011243 if (LHS.getOpcode() != RHS.getOpcode() ||
11244 !LHS.hasOneUse() || !RHS.hasOneUse())
11245 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011246
Chris Lattner254c4452010-09-21 15:46:59 +000011247 // If this is a load and the token chain is identical, replace the select
11248 // of two loads with a load through a select of the address to load from.
11249 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11250 // constants have been dropped into the constant pool.
11251 if (LHS.getOpcode() == ISD::LOAD) {
11252 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11253 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000011254
Chris Lattner254c4452010-09-21 15:46:59 +000011255 // Token chains must be identical.
11256 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000011257 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000011258 LLD->isVolatile() || RLD->isVolatile() ||
11259 // If this is an EXTLOAD, the VT's must match.
11260 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000011261 // If this is an EXTLOAD, the kind of extension must match.
11262 (LLD->getExtensionType() != RLD->getExtensionType() &&
11263 // The only exception is if one of the extensions is anyext.
11264 LLD->getExtensionType() != ISD::EXTLOAD &&
11265 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000011266 // FIXME: this discards src value information. This is
11267 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000011268 // both potential memory locations. Since we are discarding
11269 // src value info, don't do the transformation if the memory
11270 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000011271 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000011272 RLD->getPointerInfo().getAddrSpace() != 0 ||
11273 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11274 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000011275 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011276
Chris Lattnere3267522010-09-21 15:58:55 +000011277 // Check that the select condition doesn't reach either load. If so,
11278 // folding this will induce a cycle into the DAG. If not, this is safe to
11279 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000011280 SDValue Addr;
11281 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000011282 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11283 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11284 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11285 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000011286 // The loads must not depend on one another.
11287 if (LLD->isPredecessorOf(RLD) ||
11288 RLD->isPredecessorOf(LLD))
11289 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011290 Addr = DAG.getSelect(SDLoc(TheSelect),
11291 LLD->getBasePtr().getValueType(),
11292 TheSelect->getOperand(0), LLD->getBasePtr(),
11293 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000011294 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000011295 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11296 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11297
11298 if ((LLD->hasAnyUseOfValue(1) &&
11299 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000011300 (RLD->hasAnyUseOfValue(1) &&
11301 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000011302 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011303
Andrew Trickef9de2a2013-05-25 02:42:55 +000011304 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000011305 LLD->getBasePtr().getValueType(),
11306 TheSelect->getOperand(0),
11307 TheSelect->getOperand(1),
11308 LLD->getBasePtr(), RLD->getBasePtr(),
11309 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000011310 }
11311
Chris Lattnere3267522010-09-21 15:58:55 +000011312 SDValue Load;
Louis Gerbarg4fc09b32014-07-30 18:24:41 +000011313 // It is safe to replace the two loads if they have different alignments,
11314 // but the new load must be the minimum (most restrictive) alignment of the
11315 // inputs.
Louis Gerbarg67474e32014-07-31 21:45:05 +000011316 bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
Louis Gerbarg09b8cde2014-07-31 22:57:46 +000011317 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000011318 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11319 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000011320 SDLoc(TheSelect),
Hal Finkelcc39b672014-07-24 12:16:19 +000011321 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000011322 LLD->getChain(), Addr, MachinePointerInfo(),
11323 LLD->isVolatile(), LLD->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000011324 isInvariant, Alignment);
Chris Lattnere3267522010-09-21 15:58:55 +000011325 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000011326 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11327 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000011328 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000011329 TheSelect->getValueType(0),
Hal Finkelcc39b672014-07-24 12:16:19 +000011330 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000011331 LLD->getChain(), Addr, MachinePointerInfo(),
11332 LLD->getMemoryVT(), LLD->isVolatile(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000011333 LLD->isNonTemporal(), isInvariant, Alignment);
Chris Lattner6c14c352005-10-18 06:04:22 +000011334 }
Chris Lattnere3267522010-09-21 15:58:55 +000011335
11336 // Users of the select now use the result of the load.
11337 CombineTo(TheSelect, Load);
11338
11339 // Users of the old loads now use the new load's chain. We know the
11340 // old-load value is dead now.
11341 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11342 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11343 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000011344 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011345
Chris Lattner6c14c352005-10-18 06:04:22 +000011346 return false;
11347}
11348
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011349/// Simplify an expression of the form (N0 cond N1) ? N2 : N3
Chris Lattner43d63772009-03-11 05:08:08 +000011350/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000011351SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011352 SDValue N2, SDValue N3,
11353 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000011354 // (x ? y : y) -> y.
11355 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000011356
Owen Anderson53aa7a92009-08-10 22:56:29 +000011357 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000011358 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11359 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11360 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011361
11362 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000011363 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000011364 N0, N1, CC, DL, false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011365 if (SCC.getNode()) AddToWorklist(SCC.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +000011366 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011367
11368 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000011369 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000011370 return N2;
11371 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000011372 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000011373 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011374
Nate Begeman2042aa52005-10-08 00:29:44 +000011375 // Check to see if we can simplify the select into an fabs node
11376 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11377 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000011378 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000011379 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11380 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11381 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11382 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000011383 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011384
Nate Begeman2042aa52005-10-08 00:29:44 +000011385 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11386 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11387 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11388 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000011389 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000011390 }
11391 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011392
Chris Lattner43d63772009-03-11 05:08:08 +000011393 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11394 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11395 // in it. This is a win when the constant is not otherwise available because
11396 // it replaces two constant pool loads with one. We only do this if the FP
11397 // type is known to be legal, because if it isn't, then we are before legalize
11398 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000011399 // messing with soft float) and if the ConstantFP is not legal, because if
11400 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000011401 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11402 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11403 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000011404 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
Tim Northover863a7892014-04-16 09:03:09 +000011405 TargetLowering::Legal &&
11406 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11407 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
Chris Lattner43d63772009-03-11 05:08:08 +000011408 // If both constants have multiple uses, then we won't need to do an
11409 // extra load, they are likely around in registers for other users.
11410 (TV->hasOneUse() || FV->hasOneUse())) {
11411 Constant *Elts[] = {
11412 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11413 const_cast<ConstantFP*>(TV->getConstantFPValue())
11414 };
Chris Lattner229907c2011-07-18 04:54:35 +000011415 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000011416 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000011417
Chris Lattner43d63772009-03-11 05:08:08 +000011418 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000011419 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000011420 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11421 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000011422 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000011423
11424 // Get the offsets to the 0 and 1 element of the array so that we can
11425 // select between them.
11426 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000011427 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000011428 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000011429
Chris Lattner43d63772009-03-11 05:08:08 +000011430 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000011431 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000011432 N0, N1, CC);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011433 AddToWorklist(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011434 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11435 Cond, One, Zero);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011436 AddToWorklist(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000011437 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000011438 CstOffset);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011439 AddToWorklist(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000011440 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000011441 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000011442 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000011443
11444 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011445 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011446
Nate Begeman2042aa52005-10-08 00:29:44 +000011447 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000011448 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000011449 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000011450 (N1C->isNullValue() || // (a < 0) ? b : 0
11451 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000011452 EVT XType = N0.getValueType();
11453 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000011454 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000011455 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000011456 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011457 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11458 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000011459 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000011460 SDValue ShCt = DAG.getConstant(ShCtV,
11461 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011462 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011463 XType, N0, ShCt);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011464 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011465
Duncan Sands11dd4242008-06-08 20:54:56 +000011466 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011467 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011468 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011469 }
Bill Wendling31b50992009-01-30 23:59:18 +000011470
11471 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011472 }
Bill Wendling31b50992009-01-30 23:59:18 +000011473
Andrew Trickef9de2a2013-05-25 02:42:55 +000011474 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011475 XType, N0,
11476 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011477 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011478 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011479
Duncan Sands11dd4242008-06-08 20:54:56 +000011480 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011481 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011482 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011483 }
Bill Wendling31b50992009-01-30 23:59:18 +000011484
11485 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011486 }
11487 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011488
Owen Anderson3231d132010-09-22 22:58:22 +000011489 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11490 // where y is has a single bit set.
11491 // A plaintext description would be, we can turn the SELECT_CC into an AND
11492 // when the condition can be materialized as an all-ones register. Any
11493 // single bit-test can be materialized as an all-ones register with
11494 // shift-left and shift-right-arith.
11495 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11496 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000011497 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000011498 N2C && N2C->isNullValue()) {
11499 SDValue AndLHS = N0->getOperand(0);
11500 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11501 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11502 // Shift the tested bit over the sign bit.
11503 APInt AndMask = ConstAndRHS->getAPIntValue();
11504 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011505 DAG.getConstant(AndMask.countLeadingZeros(),
11506 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011507 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011508
Owen Anderson3231d132010-09-22 22:58:22 +000011509 // Now arithmetic right shift it all the way over, so the result is either
11510 // all-ones, or zero.
11511 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011512 DAG.getConstant(AndMask.getBitWidth()-1,
11513 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011514 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011515
Owen Anderson3231d132010-09-22 22:58:22 +000011516 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11517 }
11518 }
11519
Nate Begeman6828ed92005-10-10 21:26:48 +000011520 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000011521 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +000011522 TLI.getBooleanContents(N0.getValueType()) ==
11523 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011524
Chris Lattnera083ffc2007-04-11 06:50:51 +000011525 // If the caller doesn't want us to simplify this into a zext of a compare,
11526 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011527 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011528 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011529
Nate Begeman6828ed92005-10-10 21:26:48 +000011530 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011531 // NOTE: Don't create a SETCC if it's not legal on this target.
11532 if (!LegalOperations ||
11533 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000011534 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011535 SDValue Temp, SCC;
11536 // cast from setcc result type to select result type
11537 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000011538 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011539 N0, N1, CC);
11540 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000011541 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011542 N2.getValueType());
11543 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000011544 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011545 N2.getValueType(), SCC);
11546 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011547 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11548 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000011549 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011550 }
11551
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011552 AddToWorklist(SCC.getNode());
11553 AddToWorklist(Temp.getNode());
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011554
11555 if (N2C->getAPIntValue() == 1)
11556 return Temp;
11557
11558 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000011559 return DAG.getNode(
11560 ISD::SHL, DL, N2.getValueType(), Temp,
11561 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11562 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000011563 }
Nate Begeman6828ed92005-10-10 21:26:48 +000011564 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011565
Nate Begeman2042aa52005-10-08 00:29:44 +000011566 // Check to see if this is the equivalent of setcc
11567 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11568 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011569 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011570 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011571 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000011572 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11573 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000011574 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000011575 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000011576 return Res;
11577 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011578
Bill Wendling31b50992009-01-30 23:59:18 +000011579 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011580 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011581 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000011582 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011583 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011584 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000011585 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000011586 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000011587 }
Bill Wendling31b50992009-01-30 23:59:18 +000011588 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011589 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011590 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011591 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011592 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000011593 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000011594 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000011595 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011596 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000011597 }
Bill Wendling31b50992009-01-30 23:59:18 +000011598 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000011599 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011600 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011601 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011602 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000011603 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000011604 }
11605 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011606
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011607 // Check to see if this is an integer abs.
11608 // select_cc setg[te] X, 0, X, -X ->
11609 // select_cc setgt X, -1, X, -X ->
11610 // select_cc setl[te] X, 0, -X, X ->
11611 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000011612 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011613 if (N1C) {
Craig Topperc0196b12014-04-14 00:51:57 +000011614 ConstantSDNode *SubC = nullptr;
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011615 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11616 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11617 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11618 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11619 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11620 (N1C->isOne() && CC == ISD::SETLT)) &&
11621 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11622 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11623
Owen Anderson53aa7a92009-08-10 22:56:29 +000011624 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011625 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011626 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011627 N0,
11628 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011629 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011630 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011631 XType, N0, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011632 AddToWorklist(Shift.getNode());
11633 AddToWorklist(Add.getNode());
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011634 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000011635 }
11636 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011637
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011638 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011639}
11640
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011641/// This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011642SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011643 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000011644 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011645 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000011646 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000011647 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000011648}
11649
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011650/// Given an ISD::SDIV node expressing a divide by constant, return
Chad Rosier17020f92014-07-23 14:57:52 +000011651/// a DAG expression to select that will generate the same value by multiplying
11652/// by a magic number. See:
Nate Begemanc6f067a2005-10-20 02:15:44 +000011653/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011654SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011655 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11656 if (!C)
11657 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011658
11659 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011660 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011661 return SDValue();
11662
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011663 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011664 SDValue S =
11665 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011666
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011667 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011668 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011669 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011670}
11671
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011672/// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
11673/// DAG expression that will generate the same value by right shifting.
Chad Rosier17020f92014-07-23 14:57:52 +000011674SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11675 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11676 if (!C)
11677 return SDValue();
11678
11679 // Avoid division by zero.
11680 if (!C->getAPIntValue())
11681 return SDValue();
11682
11683 std::vector<SDNode *> Built;
11684 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11685
11686 for (SDNode *N : Built)
11687 AddToWorklist(N);
11688 return S;
11689}
11690
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011691/// Given an ISD::UDIV node expressing a divide by constant, return a DAG
11692/// expression that will generate the same value by multiplying by a magic
11693/// number. See:
Nate Begemanc6f067a2005-10-20 02:15:44 +000011694/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011695SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011696 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11697 if (!C)
11698 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011699
11700 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011701 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011702 return SDValue();
11703
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011704 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011705 SDValue S =
11706 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000011707
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011708 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011709 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011710 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011711}
11712
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011713/// Return true if base is a frame index, which is known not to alias with
11714/// anything but itself. Provides base object and offset as results.
Nate Begeman18150d52009-09-25 06:05:26 +000011715static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000011716 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000011717 // Assume it is a primitive operation.
Craig Topperc0196b12014-04-14 00:51:57 +000011718 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011719
Jim Laskey0463e082006-10-07 23:37:56 +000011720 // If it's an adding a simple constant then integrate the offset.
11721 if (Base.getOpcode() == ISD::ADD) {
11722 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11723 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000011724 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000011725 }
11726 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011727
Nate Begeman18150d52009-09-25 06:05:26 +000011728 // Return the underlying GlobalValue, and update the Offset. Return false
11729 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11730 // by multiple nodes with different offsets.
11731 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11732 GV = G->getGlobal();
11733 Offset += G->getOffset();
11734 return false;
11735 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011736
Nate Begeman18150d52009-09-25 06:05:26 +000011737 // Return the underlying Constant value, and update the Offset. Return false
11738 // for ConstantSDNodes since the same constant pool entry may be represented
11739 // by multiple nodes with different offsets.
11740 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000011741 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11742 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000011743 Offset += C->getOffset();
11744 return false;
11745 }
Jim Laskey0463e082006-10-07 23:37:56 +000011746 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000011747 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000011748}
11749
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011750/// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011751bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
Jim Laskey0463e082006-10-07 23:37:56 +000011752 // If they are the same then they must be aliases.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011753 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011754
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011755 // If they are both volatile then they cannot be reordered.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011756 if (Op0->isVolatile() && Op1->isVolatile()) return true;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011757
Jim Laskey0463e082006-10-07 23:37:56 +000011758 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011759 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000011760 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000011761 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000011762 const void *CV1, *CV2;
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011763 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11764 Base1, Offset1, GV1, CV1);
11765 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11766 Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011767
Nate Begeman18150d52009-09-25 06:05:26 +000011768 // If they have a same base address then check to see if they overlap.
11769 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011770 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11771 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011772
Owen Anderson272ff942010-09-20 20:39:59 +000011773 // It is possible for different frame indices to alias each other, mostly
11774 // when tail call optimization reuses return address slots for arguments.
11775 // To catch this case, look up the actual index of frame indices to compute
11776 // the real alias relationship.
11777 if (isFrameIndex1 && isFrameIndex2) {
11778 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11779 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11780 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011781 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11782 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Owen Anderson272ff942010-09-20 20:39:59 +000011783 }
11784
Wesley Peck527da1b2010-11-23 03:31:01 +000011785 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000011786 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000011787 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11788 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011789
Nate Begeman879d8f12009-09-15 00:18:30 +000011790 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11791 // compared to the size and offset of the access, we may be able to prove they
11792 // do not alias. This check is conservative for now to catch cases created by
11793 // splitting vector types.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011794 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11795 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11796 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11797 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11798 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11799 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11800 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
Wesley Peck527da1b2010-11-23 03:31:01 +000011801
Nate Begeman879d8f12009-09-15 00:18:30 +000011802 // There is no overlap between these relatively aligned accesses of similar
11803 // size, return no alias.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011804 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11805 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
Nate Begeman879d8f12009-09-15 00:18:30 +000011806 return false;
11807 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011808
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000011809 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11810 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000011811#ifndef NDEBUG
11812 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11813 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11814 UseAA = false;
11815#endif
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011816 if (UseAA &&
11817 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000011818 // Use alias analysis information.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011819 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11820 Op1->getSrcValueOffset());
11821 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11822 Op0->getSrcValueOffset() - MinOffset;
11823 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11824 Op1->getSrcValueOffset() - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011825 AliasAnalysis::AliasResult AAResult =
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011826 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11827 Overlap1,
Hal Finkelcc39b672014-07-24 12:16:19 +000011828 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011829 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11830 Overlap2,
Hal Finkelcc39b672014-07-24 12:16:19 +000011831 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
Jim Laskey55e4dca2006-10-18 19:08:31 +000011832 if (AAResult == AliasAnalysis::NoAlias)
11833 return false;
11834 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011835
11836 // Otherwise we have to assume they alias.
11837 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000011838}
11839
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011840/// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +000011841/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011842void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000011843 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011844 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000011845 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011846
Jim Laskeyd07be232006-09-25 16:29:54 +000011847 // Get alias information for node.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011848 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
Jim Laskeyd07be232006-09-25 16:29:54 +000011849
Jim Laskey708d0db2006-10-04 16:53:27 +000011850 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000011851 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011852 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000011853
Jim Laskey6549d222006-10-05 15:07:25 +000011854 // Look at each chain and determine if it is an alias. If so, add it to the
11855 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000011856 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000011857 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011858 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000011859 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000011860
11861 // For TokenFactor nodes, look at each operand and only continue up the
11862 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011863 // find more and revert to original chain since the xform is unlikely to be
11864 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000011865 //
11866 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011867 // chain we found before we hit a tokenfactor rather than the original
11868 // chain.
11869 if (Depth > 6 || Aliases.size() == 2) {
11870 Aliases.clear();
11871 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000011872 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011873 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011874
Nate Begeman879d8f12009-09-15 00:18:30 +000011875 // Don't bother if we've been before.
11876 if (!Visited.insert(Chain.getNode()))
11877 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011878
Jim Laskey6549d222006-10-05 15:07:25 +000011879 switch (Chain.getOpcode()) {
11880 case ISD::EntryToken:
11881 // Entry token is ideal chain operand, but handled in FindBetterChain.
11882 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011883
Jim Laskey6549d222006-10-05 15:07:25 +000011884 case ISD::LOAD:
11885 case ISD::STORE: {
11886 // Get alias information for Chain.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011887 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11888 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011889
Jim Laskey6549d222006-10-05 15:07:25 +000011890 // If chain is alias then stop here.
11891 if (!(IsLoad && IsOpLoad) &&
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011892 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
Jim Laskey6549d222006-10-05 15:07:25 +000011893 Aliases.push_back(Chain);
11894 } else {
11895 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011896 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011897 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000011898 }
Jim Laskey6549d222006-10-05 15:07:25 +000011899 break;
11900 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011901
Jim Laskey6549d222006-10-05 15:07:25 +000011902 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000011903 // We have to check each of the operands of the token factor for "small"
11904 // token factors, so we queue them up. Adding the operands to the queue
11905 // (stack) in reverse order maintains the original order and increases the
11906 // likelihood that getNode will find a matching token factor (CSE.)
11907 if (Chain.getNumOperands() > 16) {
11908 Aliases.push_back(Chain);
11909 break;
11910 }
Jim Laskey6549d222006-10-05 15:07:25 +000011911 for (unsigned n = Chain.getNumOperands(); n;)
11912 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011913 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000011914 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011915
Jim Laskey6549d222006-10-05 15:07:25 +000011916 default:
11917 // For all other instructions we will just have to take what we can get.
11918 Aliases.push_back(Chain);
11919 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000011920 }
11921 }
Hal Finkel51a98382014-01-24 20:12:02 +000011922
11923 // We need to be careful here to also search for aliases through the
11924 // value operand of a store, etc. Consider the following situation:
11925 // Token1 = ...
11926 // L1 = load Token1, %52
11927 // S1 = store Token1, L1, %51
11928 // L2 = load Token1, %52+8
11929 // S2 = store Token1, L2, %51+8
11930 // Token2 = Token(S1, S2)
11931 // L3 = load Token2, %53
11932 // S3 = store Token2, L3, %52
11933 // L4 = load Token2, %53+8
11934 // S4 = store Token2, L4, %52+8
11935 // If we search for aliases of S3 (which loads address %52), and we look
11936 // only through the chain, then we'll miss the trivial dependence on L1
11937 // (which also loads from %52). We then might change all loads and
11938 // stores to use Token1 as their chain operand, which could result in
11939 // copying %53 into %52 before copying %52 into %51 (which should
11940 // happen first).
11941 //
11942 // The problem is, however, that searching for such data dependencies
11943 // can become expensive, and the cost is not directly related to the
11944 // chain depth. Instead, we'll rule out such configurations here by
11945 // insisting that we've visited all chain users (except for users
11946 // of the original chain, which is not necessary). When doing this,
11947 // we need to look through nodes we don't care about (otherwise, things
11948 // like register copies will interfere with trivial cases).
11949
11950 SmallVector<const SDNode *, 16> Worklist;
Craig Topper46276792014-08-24 23:23:06 +000011951 for (const SDNode *N : Visited)
11952 if (N != OriginalChain.getNode())
11953 Worklist.push_back(N);
Hal Finkel51a98382014-01-24 20:12:02 +000011954
11955 while (!Worklist.empty()) {
11956 const SDNode *M = Worklist.pop_back_val();
11957
11958 // We have already visited M, and want to make sure we've visited any uses
11959 // of M that we care about. For uses that we've not visisted, and don't
11960 // care about, queue them to the worklist.
11961
11962 for (SDNode::use_iterator UI = M->use_begin(),
11963 UIE = M->use_end(); UI != UIE; ++UI)
11964 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11965 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11966 // We've not visited this use, and we care about it (it could have an
11967 // ordering dependency with the original node).
11968 Aliases.clear();
11969 Aliases.push_back(OriginalChain);
11970 return;
11971 }
11972
11973 // We've not visited this use, but we don't care about it. Mark it as
11974 // visited and enqueue it to the worklist.
11975 Worklist.push_back(*UI);
11976 }
11977 }
Jim Laskey708d0db2006-10-04 16:53:27 +000011978}
11979
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011980/// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
11981/// (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011982SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11983 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011984
Jim Laskey708d0db2006-10-04 16:53:27 +000011985 // Accumulate all the aliases to this node.
11986 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011987
Dan Gohman4298df62011-05-17 22:20:36 +000011988 // If no operands then chain to entry token.
11989 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000011990 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000011991
11992 // If a single operand then chain to it. We don't need to revisit it.
11993 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000011994 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000011995
Jim Laskey708d0db2006-10-04 16:53:27 +000011996 // Construct a custom tailored token factor.
Craig Topper48d114b2014-04-26 18:35:24 +000011997 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
Jim Laskeyd07be232006-09-25 16:29:54 +000011998}
11999
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012000/// This is the entry point for the file.
Bill Wendling084669a2009-04-29 00:15:41 +000012001void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000012002 CodeGenOpt::Level OptLevel) {
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012003 /// This is the main entry point to this class.
Bill Wendling084669a2009-04-29 00:15:41 +000012004 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000012005}