blob: e8cbd8af7a83d9b2580250e66cde4349a42bb641 [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
Jim Laskey6549d222006-10-05 15:07:25 +000080//------------------------------ DAGCombiner ---------------------------------//
81
Nick Lewycky02d5f772009-10-25 06:33:48 +000082 class DAGCombiner {
Nate Begeman21158fc2005-09-01 00:19:25 +000083 SelectionDAG &DAG;
Dan Gohman619ef482009-01-15 19:20:50 +000084 const TargetLowering &TLI;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000085 CombineLevel Level;
Bill Wendling026e5d72009-04-29 23:29:43 +000086 CodeGenOpt::Level OptLevel;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000087 bool LegalOperations;
88 bool LegalTypes;
Quentin Colombetde0e0622013-10-11 18:29:42 +000089 bool ForCodeSize;
Nate Begeman21158fc2005-09-01 00:19:25 +000090
Chandler Carruth9a0051c2014-07-23 07:08:53 +000091 /// \brief Worklist of all of the nodes that need to be simplified.
92 ///
93 /// This must behave as a stack -- new nodes to process are pushed onto the
94 /// back and when processing we pop off of the back.
95 ///
96 /// The worklist will not contain duplicates but may contain null entries
97 /// due to nodes being deleted from the underlying DAG.
98 SmallVector<SDNode *, 64> Worklist;
99
100 /// \brief Mapping from an SDNode to its position on the worklist.
101 ///
102 /// This is used to find and remove nodes from the worklist (by nulling
103 /// them) when they are deleted from the underlying DAG. It relies on
104 /// stable indices of nodes within the worklist.
105 DenseMap<SDNode *, unsigned> WorklistMap;
Nate Begeman21158fc2005-09-01 00:19:25 +0000106
Chandler Carruth9f4530b2014-07-24 22:15:28 +0000107 /// \brief Set of nodes which have been combined (at least once).
108 ///
109 /// This is used to allow us to reliably add any operands of a DAG node
110 /// which have not yet been combined to the worklist.
111 SmallPtrSet<SDNode *, 64> CombinedNodes;
112
Jim Laskeydcb2b832006-10-16 20:52:31 +0000113 // AA - Used for DAG load/store alias analysis.
114 AliasAnalysis &AA;
115
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000116 /// AddUsersToWorklist - When an instruction is simplified, add all users of
Nate Begeman21158fc2005-09-01 00:19:25 +0000117 /// the instruction to the work lists because they might get more simplified
118 /// now.
119 ///
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000120 void AddUsersToWorklist(SDNode *N) {
Jim Grosbache8160032014-04-11 01:13:13 +0000121 for (SDNode *Node : N->uses())
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000122 AddToWorklist(Node);
Nate Begeman21158fc2005-09-01 00:19:25 +0000123 }
124
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000125 /// visit - call the node-specific routine that knows how to fold each
126 /// particular type of node.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000127 SDValue visit(SDNode *N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000128
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000129 public:
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000130 /// AddToWorklist - Add to the work list making sure its instance is at the
James Molloy67b6b112012-02-16 09:17:04 +0000131 /// back (next to be processed.)
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000132 void AddToWorklist(SDNode *N) {
Chandler Carruth24ceb0c2014-07-21 08:32:31 +0000133 // Skip handle nodes as they can't usefully be combined and confuse the
134 // zero-use deletion strategy.
135 if (N->getOpcode() == ISD::HANDLENODE)
136 return;
137
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000138 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
139 Worklist.push_back(N);
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000140 }
Jim Laskey708d0db2006-10-04 16:53:27 +0000141
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000142 /// removeFromWorklist - remove all instances of N from the worklist.
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000143 ///
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
Chris Lattner375e1a72006-02-17 21:58:01 +0000176 /// SimplifyDemandedBits - Check the specified integer node value to see if
Chris Lattner232024e2006-03-01 19:55:35 +0000177 /// it can be simplified or if things it uses can be simplified by bit
Chris Lattner375e1a72006-02-17 21:58:01 +0000178 /// propagation. 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);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000189 bool SliceUpLoad(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000190
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +0000191 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
192 /// load.
193 ///
194 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
195 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
196 /// \param EltNo index of the vector element to load.
197 /// \param OriginalLoad load that EVE came from to be replaced.
198 /// \returns EVE on success SDValue() on failure.
199 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
200 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000201 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
202 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
203 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
204 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
Evan Chengaf56fac2010-04-16 06:14:10 +0000205 SDValue PromoteIntBinOp(SDValue Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000206 SDValue PromoteIntShiftOp(SDValue Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +0000207 SDValue PromoteExtend(SDValue Op);
208 bool PromoteLoad(SDValue Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000209
Craig Toppere0b71182013-07-13 07:43:40 +0000210 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000211 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +0000212 ISD::NodeType ExtType);
213
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000214 /// combine - call the node-specific routine that knows how to fold each
215 /// particular type of node. If that doesn't do anything, try the
216 /// target-specific DAG combines.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000217 SDValue combine(SDNode *N);
Nate Begeman21158fc2005-09-01 00:19:25 +0000218
219 // Visitation implementation - Implement dag node combining for different
220 // node types. The semantics are as follows:
221 // Return Value:
Evan Cheng5e7658c2008-08-29 22:21:44 +0000222 // SDValue.getNode() == 0 - No change was made
223 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
224 // otherwise - N should be replaced by the returned Operand.
Nate Begeman21158fc2005-09-01 00:19:25 +0000225 //
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000226 SDValue visitTokenFactor(SDNode *N);
227 SDValue visitMERGE_VALUES(SDNode *N);
228 SDValue visitADD(SDNode *N);
229 SDValue visitSUB(SDNode *N);
230 SDValue visitADDC(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000231 SDValue visitSUBC(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000232 SDValue visitADDE(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000233 SDValue visitSUBE(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000234 SDValue visitMUL(SDNode *N);
235 SDValue visitSDIV(SDNode *N);
236 SDValue visitUDIV(SDNode *N);
237 SDValue visitSREM(SDNode *N);
238 SDValue visitUREM(SDNode *N);
239 SDValue visitMULHU(SDNode *N);
240 SDValue visitMULHS(SDNode *N);
241 SDValue visitSMUL_LOHI(SDNode *N);
242 SDValue visitUMUL_LOHI(SDNode *N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +0000243 SDValue visitSMULO(SDNode *N);
244 SDValue visitUMULO(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000245 SDValue visitSDIVREM(SDNode *N);
246 SDValue visitUDIVREM(SDNode *N);
247 SDValue visitAND(SDNode *N);
248 SDValue visitOR(SDNode *N);
249 SDValue visitXOR(SDNode *N);
250 SDValue SimplifyVBinOp(SDNode *N);
Craig Topper82384612012-09-11 01:45:21 +0000251 SDValue SimplifyVUnaryOp(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000252 SDValue visitSHL(SDNode *N);
253 SDValue visitSRA(SDNode *N);
254 SDValue visitSRL(SDNode *N);
Adam Nemet7f928f12014-03-07 23:56:30 +0000255 SDValue visitRotate(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000256 SDValue visitCTLZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000257 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000258 SDValue visitCTTZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000259 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000260 SDValue visitCTPOP(SDNode *N);
261 SDValue visitSELECT(SDNode *N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +0000262 SDValue visitVSELECT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000263 SDValue visitSELECT_CC(SDNode *N);
264 SDValue visitSETCC(SDNode *N);
265 SDValue visitSIGN_EXTEND(SDNode *N);
266 SDValue visitZERO_EXTEND(SDNode *N);
267 SDValue visitANY_EXTEND(SDNode *N);
268 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
269 SDValue visitTRUNCATE(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000270 SDValue visitBITCAST(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000271 SDValue visitBUILD_PAIR(SDNode *N);
272 SDValue visitFADD(SDNode *N);
273 SDValue visitFSUB(SDNode *N);
274 SDValue visitFMUL(SDNode *N);
Owen Anderson41b06652012-05-02 22:17:40 +0000275 SDValue visitFMA(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000276 SDValue visitFDIV(SDNode *N);
277 SDValue visitFREM(SDNode *N);
278 SDValue visitFCOPYSIGN(SDNode *N);
279 SDValue visitSINT_TO_FP(SDNode *N);
280 SDValue visitUINT_TO_FP(SDNode *N);
281 SDValue visitFP_TO_SINT(SDNode *N);
282 SDValue visitFP_TO_UINT(SDNode *N);
283 SDValue visitFP_ROUND(SDNode *N);
284 SDValue visitFP_ROUND_INREG(SDNode *N);
285 SDValue visitFP_EXTEND(SDNode *N);
286 SDValue visitFNEG(SDNode *N);
287 SDValue visitFABS(SDNode *N);
Owen Andersona40319b2012-08-13 23:32:49 +0000288 SDValue visitFCEIL(SDNode *N);
289 SDValue visitFTRUNC(SDNode *N);
290 SDValue visitFFLOOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000291 SDValue visitBRCOND(SDNode *N);
292 SDValue visitBR_CC(SDNode *N);
293 SDValue visitLOAD(SDNode *N);
294 SDValue visitSTORE(SDNode *N);
295 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
296 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
297 SDValue visitBUILD_VECTOR(SDNode *N);
298 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +0000299 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000300 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Manman Ren413a6cb2014-01-31 01:10:35 +0000301 SDValue visitINSERT_SUBVECTOR(SDNode *N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000302
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000303 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000304 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000305
Matt Arsenault985b9de2014-03-17 18:58:01 +0000306 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
Chris Lattner7c709a52007-12-06 07:33:36 +0000307
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000308 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
309 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000310 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
311 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelcf0da6c2009-02-17 22:15:04 +0000312 SDValue N3, ISD::CondCode CC,
Bill Wendling31b50992009-01-30 23:59:18 +0000313 bool NotExtCompare = false);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000314 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000315 SDLoc DL, bool foldBooleans = true);
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000316
317 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
318 SDValue &CC) const;
319 bool isOneUseSetCC(SDValue N) const;
320
Scott Michelcf0da6c2009-02-17 22:15:04 +0000321 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner31e9edc2008-01-26 01:09:19 +0000322 unsigned HiOp);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000323 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000324 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000325 SDValue BuildSDIV(SDNode *N);
Chad Rosier17020f92014-07-23 14:57:52 +0000326 SDValue BuildSDIVPow2(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000327 SDValue BuildUDIV(SDNode *N);
Evan Cheng4c0bd962011-06-21 06:01:08 +0000328 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
329 bool DemandHighBits = true);
330 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Richard Sandiford95c864d2014-01-08 15:40:47 +0000331 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
332 SDValue InnerPos, SDValue InnerNeg,
333 unsigned PosOpcode, unsigned NegOpcode,
334 SDLoc DL);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000335 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000336 SDValue ReduceLoadWidth(SDNode *N);
Evan Chenga9cda8a2009-05-28 00:35:15 +0000337 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Chengd42641c2011-02-02 01:06:55 +0000338 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liao6d106b72012-10-23 23:06:52 +0000339 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao59229792012-10-24 04:14:18 +0000340 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000341
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000342 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000343
Jim Laskey708d0db2006-10-04 16:53:27 +0000344 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
345 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000346 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +0000347 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey708d0db2006-10-04 16:53:27 +0000348
Jim Laskeya15b0eb2006-10-18 12:29:57 +0000349 /// isAlias - Return true if there is any possibility that the two addresses
350 /// overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000351 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000352
Jim Laskeyd07be232006-09-25 16:29:54 +0000353 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +0000354 /// looking for a better 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
Nate Begeman21158fc2005-09-01 00:19:25 +0000382 /// Run - 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
Chris Lattner4041ab62010-04-15 04:48:01 +0000387 /// getShiftAmountTy - Returns a type large enough to hold any valid
388 /// shift amount - before type 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
Chris Lattner4041ab62010-04-15 04:48:01 +0000397 /// isTypeLegal - This method returns true if we are running before type
398 /// legalization or if the specified VT is legal.
399 bool isTypeLegal(const EVT &VT) {
400 if (!LegalTypes) return true;
401 return TLI.isTypeLegal(VT);
402 }
Matt Arsenault758659232013-05-18 00:21:46 +0000403
404 /// getSetCCResultType - Convenience wrapper around
405 /// TargetLowering::getSetCCResultType
406 EVT getSetCCResultType(EVT VT) const {
407 return TLI.getSetCCResultType(*DAG.getContext(), VT);
408 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000409 };
410}
411
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000412
413namespace {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000414/// WorklistRemover - This class is a DAGUpdateListener that removes any deleted
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000415/// nodes from the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000416class WorklistRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000417 DAGCombiner &DC;
418public:
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000419 explicit WorklistRemover(DAGCombiner &dc)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000420 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000421
Craig Topper7b883b32014-03-08 06:31:39 +0000422 void NodeDeleted(SDNode *N, SDNode *E) override {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000423 DC.removeFromWorklist(N);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000424 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000425};
426}
427
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000428//===----------------------------------------------------------------------===//
429// TargetLowering::DAGCombinerInfo implementation
430//===----------------------------------------------------------------------===//
431
432void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000433 ((DAGCombiner*)DC)->AddToWorklist(N);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000434}
435
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000436void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000437 ((DAGCombiner*)DC)->removeFromWorklist(N);
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000438}
439
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000440SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000441CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
442 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000443}
444
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000445SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000446CombineTo(SDNode *N, SDValue Res, bool AddTo) {
447 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000448}
449
450
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000451SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000452CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
453 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000454}
455
Dan Gohmane58ab792009-01-29 01:59:02 +0000456void TargetLowering::DAGCombinerInfo::
457CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
458 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
459}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000460
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000461//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000462// Helper Functions
463//===----------------------------------------------------------------------===//
464
Chandler Carruth18066972014-08-02 10:02:07 +0000465void DAGCombiner::deleteAndRecombine(SDNode *N) {
466 removeFromWorklist(N);
467
468 // If the operands of this node are only used by the node, they will now be
469 // dead. Make sure to re-visit them and recursively delete dead nodes.
470 for (const SDValue &Op : N->ops())
471 if (Op->hasOneUse())
472 AddToWorklist(Op.getNode());
473
474 DAG.DeleteNode(N);
475}
476
Chris Lattnere49c9742007-05-14 22:04:50 +0000477/// isNegatibleForFree - Return 1 if we can compute the negated form of the
478/// specified expression for the same cost as the expression itself, or 2 if we
479/// can compute the negated form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000480static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000481 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000482 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000483 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000484 // fneg is removable even if it has multiple uses.
485 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000486
Chris Lattnere49c9742007-05-14 22:04:50 +0000487 // Don't allow anything with multiple uses.
488 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000489
Chris Lattner46980832007-05-25 02:19:06 +0000490 // Don't recurse exponentially.
491 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000492
Chris Lattnere49c9742007-05-14 22:04:50 +0000493 switch (Op.getOpcode()) {
494 default: return false;
495 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000496 // Don't invert constant FP values after legalize. The negated constant
497 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000498 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000499 case ISD::FADD:
500 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000501 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000502
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000503 // After operation legalization, it might not be legal to create new FSUBs.
504 if (LegalOperations &&
505 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
506 return 0;
507
Craig Topper03f39772012-09-09 22:58:45 +0000508 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000509 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
510 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000511 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000512 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000513 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000514 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000515 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000516 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000517 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000518
Bill Wendling6fbf5492009-01-30 23:10:18 +0000519 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000520 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000521
Chris Lattnere49c9742007-05-14 22:04:50 +0000522 case ISD::FMUL:
523 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000524 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000525
Bill Wendling6fbf5492009-01-30 23:10:18 +0000526 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000527 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
528 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000529 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000530
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000531 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000532 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000533
Chris Lattnere49c9742007-05-14 22:04:50 +0000534 case ISD::FP_EXTEND:
535 case ISD::FP_ROUND:
536 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000537 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000538 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000539 }
540}
541
542/// GetNegatedExpression - If isNegatibleForFree returns true, this function
543/// returns the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000544static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000545 bool LegalOperations, unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000546 // fneg is removable even if it has multiple uses.
547 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000548
Chris Lattnere49c9742007-05-14 22:04:50 +0000549 // Don't allow anything with multiple uses.
550 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000551
Chris Lattner46980832007-05-25 02:19:06 +0000552 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000553 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000554 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000555 case ISD::ConstantFP: {
556 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
557 V.changeSign();
558 return DAG.getConstantFP(V, Op.getValueType());
559 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000560 case ISD::FADD:
561 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000562 assert(DAG.getTarget().Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000563
Bill Wendling6fbf5492009-01-30 23:10:18 +0000564 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000565 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000566 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000567 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000568 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000569 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000570 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000571 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000572 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000573 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000574 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000575 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000576 Op.getOperand(0));
577 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000578 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000579 assert(DAG.getTarget().Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000580
Bill Wendling6fbf5492009-01-30 23:10:18 +0000581 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000582 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen446b9002007-08-31 23:34:27 +0000583 if (N0CFP->getValueAPF().isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000584 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000585
Bill Wendling6fbf5492009-01-30 23:10:18 +0000586 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000587 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000588 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000589
Chris Lattnere49c9742007-05-14 22:04:50 +0000590 case ISD::FMUL:
591 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000592 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000593
Bill Wendling6fbf5492009-01-30 23:10:18 +0000594 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000595 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000596 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000597 &DAG.getTarget().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
Nate Begeman2cc2c9a2005-09-07 23:25:52 +0000647// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
648// one use. If this is true, it allows the users to invert the operation for
649// free when 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
Matt Arsenault985b9de2014-03-17 18:58:01 +0000657/// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
658/// 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
Andrew Trickef9de2a2013-05-25 02:42:55 +0000704SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000705 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000706 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000707 if (N0.getOpcode() == Opc) {
708 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
709 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
710 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
711 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
712 if (!OpNode.getNode())
713 return SDValue();
714 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
Juergen Ributzka73844052014-01-13 20:51:35 +0000715 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000716 if (N0.hasOneUse()) {
717 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
718 // use
719 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
720 if (!OpNode.getNode())
721 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000722 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000723 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000724 }
725 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000726 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000727
Juergen Ributzka68402822014-01-13 21:49:25 +0000728 if (N1.getOpcode() == Opc) {
729 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
730 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
731 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
732 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
733 if (!OpNode.getNode())
734 return SDValue();
735 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
736 }
737 if (N1.hasOneUse()) {
738 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
739 // use
740 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
741 if (!OpNode.getNode())
742 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000743 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000744 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
745 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000746 }
747 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000748
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000749 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000750}
751
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000752SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
753 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000754 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
755 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000756 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000757 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000758 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000759 To[0].getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000760 dbgs() << " and " << NumTo-1 << " other values\n";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000761 for (unsigned i = 0, e = NumTo; i != e; ++i)
Jakob Stoklund Olesen32042f92009-12-03 05:15:35 +0000762 assert((!To[i].getNode() ||
763 N->getValueType(i) == To[i].getValueType()) &&
Dan Gohman7e6b9322009-01-21 15:17:51 +0000764 "Cannot combine value to value of different type!"));
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000765 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000766 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000767 if (AddTo) {
768 // Push the new nodes and any users onto the worklist
769 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000770 if (To[i].getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000771 AddToWorklist(To[i].getNode());
772 AddUsersToWorklist(To[i].getNode());
Chris Lattner4147f082009-03-12 06:52:53 +0000773 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000774 }
775 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000776
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000777 // Finally, if the node is now dead, remove it from the graph. The node
778 // may not be dead if the replacement process recursively simplified to
779 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000780 if (N->use_empty())
781 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000782 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000783}
784
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000785void DAGCombiner::
786CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000787 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000788 // are deleted, make sure to remove them from our worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000789 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000790 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000791
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000792 // Push the new node and any (possibly new) users onto the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000793 AddToWorklist(TLO.New.getNode());
794 AddUsersToWorklist(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000795
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000796 // Finally, if the node is now dead, remove it from the graph. The node
797 // may not be dead if the replacement process recursively simplified to
798 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000799 if (TLO.Old.getNode()->use_empty())
800 deleteAndRecombine(TLO.Old.getNode());
Dan Gohmane58ab792009-01-29 01:59:02 +0000801}
802
803/// SimplifyDemandedBits - Check the specified integer node value to see if
804/// it can be simplified or if things it uses can be simplified by bit
805/// propagation. If so, return true.
806bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000807 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000808 APInt KnownZero, KnownOne;
809 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
810 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000811
Dan Gohmane58ab792009-01-29 01:59:02 +0000812 // Revisit the node.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000813 AddToWorklist(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000814
Dan Gohmane58ab792009-01-29 01:59:02 +0000815 // Replace the old value with the new one.
816 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000817 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000818 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000819 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000820 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000821 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000822
Dan Gohmane58ab792009-01-29 01:59:02 +0000823 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000824 return true;
825}
826
Evan Cheng0abb54d2010-04-24 04:43:44 +0000827void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000828 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000829 EVT VT = Load->getValueType(0);
830 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000831
Evan Cheng0abb54d2010-04-24 04:43:44 +0000832 DEBUG(dbgs() << "\nReplacing.9 ";
833 Load->dump(&DAG);
834 dbgs() << "\nWith: ";
835 Trunc.getNode()->dump(&DAG);
836 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000837 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000838 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
839 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Chandler Carruth18066972014-08-02 10:02:07 +0000840 deleteAndRecombine(Load);
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000841 AddToWorklist(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000842}
843
844SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
845 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000846 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000847 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000848 EVT MemVT = LD->getMemoryVT();
849 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +0000850 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +0000851 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000852 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000853 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000854 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000855 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000856 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000857 }
858
Evan Chenge19aa5c2010-04-19 19:29:22 +0000859 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000860 switch (Opc) {
861 default: break;
862 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000863 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000864 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000865 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000866 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000867 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000868 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000869 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000870 case ISD::Constant: {
871 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000872 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000873 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000874 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000875 }
876
877 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000878 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000879 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000880}
881
Evan Cheng0abb54d2010-04-24 04:43:44 +0000882SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000883 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
884 return SDValue();
885 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000886 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000887 bool Replace = false;
888 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000889 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000890 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000891 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000892
893 if (Replace)
894 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
895 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000896 DAG.getValueType(OldVT));
897}
898
Evan Cheng0abb54d2010-04-24 04:43:44 +0000899SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000900 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000901 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000902 bool Replace = false;
903 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000904 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000905 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000906 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000907
908 if (Replace)
909 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
910 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000911}
912
Evan Chengaf56fac2010-04-16 06:14:10 +0000913/// PromoteIntBinOp - Promote the specified integer binary operation if the
914/// target indicates it is beneficial. e.g. On x86, it's usually better to
915/// promote i16 operations to i32 since i16 instructions are longer.
916SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
917 if (!LegalOperations)
918 return SDValue();
919
920 EVT VT = Op.getValueType();
921 if (VT.isVector() || !VT.isInteger())
922 return SDValue();
923
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000924 // If operation type is 'undesirable', e.g. i16 on x86, consider
925 // promoting it.
926 unsigned Opc = Op.getOpcode();
927 if (TLI.isTypeDesirableForOp(Opc, VT))
928 return SDValue();
929
Evan Chengaf56fac2010-04-16 06:14:10 +0000930 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000931 // Consult target whether it is a good idea to promote this operation and
932 // what's the right type to promote it to.
933 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +0000934 assert(PVT != VT && "Don't know what type to promote to!");
935
Evan Cheng0abb54d2010-04-24 04:43:44 +0000936 bool Replace0 = false;
937 SDValue N0 = Op.getOperand(0);
938 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
Craig Topperc0196b12014-04-14 00:51:57 +0000939 if (!NN0.getNode())
Evan Chengf1223bd2010-04-22 20:19:46 +0000940 return SDValue();
941
Evan Cheng0abb54d2010-04-24 04:43:44 +0000942 bool Replace1 = false;
943 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +0000944 SDValue NN1;
945 if (N0 == N1)
946 NN1 = NN0;
947 else {
948 NN1 = PromoteOperand(N1, PVT, Replace1);
Craig Topperc0196b12014-04-14 00:51:57 +0000949 if (!NN1.getNode())
Evan Cheng02947a42010-05-10 19:03:57 +0000950 return SDValue();
951 }
Evan Chengf1223bd2010-04-22 20:19:46 +0000952
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000953 AddToWorklist(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +0000954 if (NN1.getNode())
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000955 AddToWorklist(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000956
957 if (Replace0)
958 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
959 if (Replace1)
960 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +0000961
Evan Chenge8136902010-04-27 19:48:13 +0000962 DEBUG(dbgs() << "\nPromoting ";
963 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000964 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000965 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000966 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +0000967 }
968 return SDValue();
969}
970
971/// PromoteIntShiftOp - Promote the specified integer shift operation if the
972/// target indicates it is beneficial. e.g. On x86, it's usually better to
973/// promote i16 operations to i32 since i16 instructions are longer.
974SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
975 if (!LegalOperations)
976 return SDValue();
977
978 EVT VT = Op.getValueType();
979 if (VT.isVector() || !VT.isInteger())
980 return SDValue();
981
982 // If operation type is 'undesirable', e.g. i16 on x86, consider
983 // promoting it.
984 unsigned Opc = Op.getOpcode();
985 if (TLI.isTypeDesirableForOp(Opc, VT))
986 return SDValue();
987
988 EVT PVT = VT;
989 // Consult target whether it is a good idea to promote this operation and
990 // what's the right type to promote it to.
991 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
992 assert(PVT != VT && "Don't know what type to promote to!");
993
Evan Cheng0abb54d2010-04-24 04:43:44 +0000994 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000995 SDValue N0 = Op.getOperand(0);
996 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000997 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000998 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000999 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001000 else
Evan Cheng0abb54d2010-04-24 04:43:44 +00001001 N0 = PromoteOperand(N0, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +00001002 if (!N0.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001003 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +00001004
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001005 AddToWorklist(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +00001006 if (Replace)
1007 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +00001008
Evan Chenge8136902010-04-27 19:48:13 +00001009 DEBUG(dbgs() << "\nPromoting ";
1010 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001011 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +00001012 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +00001013 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +00001014 }
1015 return SDValue();
1016}
1017
Evan Chenge19aa5c2010-04-19 19:29:22 +00001018SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1019 if (!LegalOperations)
1020 return SDValue();
1021
1022 EVT VT = Op.getValueType();
1023 if (VT.isVector() || !VT.isInteger())
1024 return SDValue();
1025
1026 // If operation type is 'undesirable', e.g. i16 on x86, consider
1027 // promoting it.
1028 unsigned Opc = Op.getOpcode();
1029 if (TLI.isTypeDesirableForOp(Opc, VT))
1030 return SDValue();
1031
1032 EVT PVT = VT;
1033 // Consult target whether it is a good idea to promote this operation and
1034 // what's the right type to promote it to.
1035 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1036 assert(PVT != VT && "Don't know what type to promote to!");
1037 // fold (aext (aext x)) -> (aext x)
1038 // fold (aext (zext x)) -> (zext x)
1039 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +00001040 DEBUG(dbgs() << "\nPromoting ";
1041 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001042 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001043 }
1044 return SDValue();
1045}
1046
1047bool DAGCombiner::PromoteLoad(SDValue Op) {
1048 if (!LegalOperations)
1049 return false;
1050
1051 EVT VT = Op.getValueType();
1052 if (VT.isVector() || !VT.isInteger())
1053 return false;
1054
1055 // If operation type is 'undesirable', e.g. i16 on x86, consider
1056 // promoting it.
1057 unsigned Opc = Op.getOpcode();
1058 if (TLI.isTypeDesirableForOp(Opc, VT))
1059 return false;
1060
1061 EVT PVT = VT;
1062 // Consult target whether it is a good idea to promote this operation and
1063 // what's the right type to promote it to.
1064 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1065 assert(PVT != VT && "Don't know what type to promote to!");
1066
Andrew Trickef9de2a2013-05-25 02:42:55 +00001067 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001068 SDNode *N = Op.getNode();
1069 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001070 EVT MemVT = LD->getMemoryVT();
1071 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +00001072 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +00001073 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001074 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001075 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001076 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001077 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001078 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1079
Evan Cheng0abb54d2010-04-24 04:43:44 +00001080 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001081 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001082 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001083 Result.getNode()->dump(&DAG);
1084 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001085 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001086 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1087 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Chandler Carruth18066972014-08-02 10:02:07 +00001088 deleteAndRecombine(N);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001089 AddToWorklist(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001090 return true;
1091 }
1092 return false;
1093}
1094
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001095/// \brief Recursively delete a node which has no uses and any operands for
1096/// which it is the only use.
1097///
1098/// Note that this both deletes the nodes and removes them from the worklist.
1099/// It also adds any nodes who have had a user deleted to the worklist as they
1100/// may now have only one use and subject to other combines.
1101bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1102 if (!N->use_empty())
1103 return false;
1104
1105 SmallSetVector<SDNode *, 16> Nodes;
1106 Nodes.insert(N);
1107 do {
1108 N = Nodes.pop_back_val();
1109 if (!N)
1110 continue;
1111
1112 if (N->use_empty()) {
1113 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1114 Nodes.insert(N->getOperand(i).getNode());
1115
1116 removeFromWorklist(N);
1117 DAG.DeleteNode(N);
1118 } else {
1119 AddToWorklist(N);
1120 }
1121 } while (!Nodes.empty());
1122 return true;
1123}
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001124
Chris Lattnere49c9742007-05-14 22:04:50 +00001125//===----------------------------------------------------------------------===//
1126// Main DAG Combiner implementation
1127//===----------------------------------------------------------------------===//
1128
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001129void DAGCombiner::Run(CombineLevel AtLevel) {
1130 // set the instance variables, so that the various visit routines may use it.
1131 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001132 LegalOperations = Level >= AfterLegalizeVectorOps;
1133 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001134
Evan Cheng5e7658c2008-08-29 22:21:44 +00001135 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001136 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1137 E = DAG.allnodes_end(); I != E; ++I)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001138 AddToWorklist(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001139
Evan Cheng5e7658c2008-08-29 22:21:44 +00001140 // Create a dummy node (which is not added to allnodes), that adds a reference
1141 // to the root node, preventing it from being deleted, and tracking any
1142 // changes of the root.
1143 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001144
James Molloy67b6b112012-02-16 09:17:04 +00001145 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001146 // try and combine it.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001147 while (!WorklistMap.empty()) {
James Molloy67b6b112012-02-16 09:17:04 +00001148 SDNode *N;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001149 // The Worklist holds the SDNodes in order, but it may contain null entries.
James Molloy67b6b112012-02-16 09:17:04 +00001150 do {
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001151 N = Worklist.pop_back_val();
1152 } while (!N);
1153
1154 bool GoodWorklistEntry = WorklistMap.erase(N);
1155 (void)GoodWorklistEntry;
1156 assert(GoodWorklistEntry &&
1157 "Found a worklist entry without a corresponding map entry!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00001158
Evan Cheng5e7658c2008-08-29 22:21:44 +00001159 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1160 // N is deleted from the DAG, since they too may now be dead or may have a
1161 // reduced number of uses, allowing other xforms.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001162 if (recursivelyDeleteUnusedNodes(N))
Evan Cheng5e7658c2008-08-29 22:21:44 +00001163 continue;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001164
1165 WorklistRemover DeadNodes(*this);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001166
Chandler Carruth411fb402014-07-26 05:49:40 +00001167 // If this combine is running after legalizing the DAG, re-legalize any
1168 // nodes pulled off the worklist.
1169 if (Level == AfterLegalizeDAG) {
1170 SmallSetVector<SDNode *, 16> UpdatedNodes;
1171 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1172
1173 for (SDNode *LN : UpdatedNodes) {
1174 AddToWorklist(LN);
1175 AddUsersToWorklist(LN);
1176 }
1177 if (!NIsValid)
1178 continue;
1179 }
1180
Chandler Carruthb1432742014-07-28 17:55:07 +00001181 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1182
Chandler Carruthcde4eb52014-08-03 23:10:59 +00001183 // Add any operands of the new node which have not yet been combined to the
1184 // worklist as well. Because the worklist uniques things already, this
1185 // won't repeatedly process the same operand.
1186 CombinedNodes.insert(N);
1187 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1188 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1189 AddToWorklist(N->getOperand(i).getNode());
1190
Evan Cheng5e7658c2008-08-29 22:21:44 +00001191 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001192
Craig Topperc0196b12014-04-14 00:51:57 +00001193 if (!RV.getNode())
Evan Cheng5e7658c2008-08-29 22:21:44 +00001194 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001195
Evan Cheng5e7658c2008-08-29 22:21:44 +00001196 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001197
Evan Cheng5e7658c2008-08-29 22:21:44 +00001198 // If we get back the same node we passed in, rather than a new node or
1199 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001200 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001201 // mechanics for us, we have no work to do in this case.
1202 if (RV.getNode() == N)
1203 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001204
Evan Cheng5e7658c2008-08-29 22:21:44 +00001205 assert(N->getOpcode() != ISD::DELETED_NODE &&
1206 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1207 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001208
Chandler Carruth9f4530b2014-07-24 22:15:28 +00001209 DEBUG(dbgs() << " ... into: ";
1210 RV.getNode()->dump(&DAG));
Eric Christopherd6300d22011-07-14 01:12:15 +00001211
Devang Patelefec7712011-05-23 22:04:42 +00001212 // Transfer debug value.
1213 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001214 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001215 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001216 else {
1217 assert(N->getValueType(0) == RV.getValueType() &&
1218 N->getNumValues() == 1 && "Type mismatch");
1219 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001220 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001221 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001222
Evan Cheng5e7658c2008-08-29 22:21:44 +00001223 // Push the new node and any users onto the worklist
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001224 AddToWorklist(RV.getNode());
1225 AddUsersToWorklist(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001226
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001227 // Finally, if the node is now dead, remove it from the graph. The node
1228 // may not be dead if the replacement process recursively simplified to
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001229 // something else needing this node. This will also take care of adding any
1230 // operands which have lost a user to the worklist.
1231 recursivelyDeleteUnusedNodes(N);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001232 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001233
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001234 // If the root changed (e.g. it was a dead load, update the root).
1235 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001236 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001237}
1238
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001239SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001240 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001241 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001242 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001243 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001244 case ISD::ADD: return visitADD(N);
1245 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001246 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001247 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001248 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001249 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001250 case ISD::MUL: return visitMUL(N);
1251 case ISD::SDIV: return visitSDIV(N);
1252 case ISD::UDIV: return visitUDIV(N);
1253 case ISD::SREM: return visitSREM(N);
1254 case ISD::UREM: return visitUREM(N);
1255 case ISD::MULHU: return visitMULHU(N);
1256 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001257 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1258 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001259 case ISD::SMULO: return visitSMULO(N);
1260 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001261 case ISD::SDIVREM: return visitSDIVREM(N);
1262 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001263 case ISD::AND: return visitAND(N);
1264 case ISD::OR: return visitOR(N);
1265 case ISD::XOR: return visitXOR(N);
1266 case ISD::SHL: return visitSHL(N);
1267 case ISD::SRA: return visitSRA(N);
1268 case ISD::SRL: return visitSRL(N);
Adam Nemet7f928f12014-03-07 23:56:30 +00001269 case ISD::ROTR:
1270 case ISD::ROTL: return visitRotate(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001271 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001272 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001273 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001274 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001275 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001276 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001277 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001278 case ISD::SELECT_CC: return visitSELECT_CC(N);
1279 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001280 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1281 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001282 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001283 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1284 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001285 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001286 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001287 case ISD::FADD: return visitFADD(N);
1288 case ISD::FSUB: return visitFSUB(N);
1289 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001290 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001291 case ISD::FDIV: return visitFDIV(N);
1292 case ISD::FREM: return visitFREM(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001293 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001294 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1295 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1296 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1297 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1298 case ISD::FP_ROUND: return visitFP_ROUND(N);
1299 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1300 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1301 case ISD::FNEG: return visitFNEG(N);
1302 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001303 case ISD::FFLOOR: return visitFFLOOR(N);
1304 case ISD::FCEIL: return visitFCEIL(N);
1305 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001306 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001307 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001308 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001309 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001310 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001311 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001312 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1313 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001314 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001315 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001316 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001317 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001318 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001319}
1320
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001321SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001322 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001323
1324 // If nothing happened, try a target-specific DAG combine.
Craig Topperc0196b12014-04-14 00:51:57 +00001325 if (!RV.getNode()) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001326 assert(N->getOpcode() != ISD::DELETED_NODE &&
1327 "Node was deleted but visit returned NULL!");
1328
1329 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1330 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1331
1332 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001333 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001334 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001335
1336 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1337 }
1338 }
1339
Evan Chengf1005572010-04-28 07:10:39 +00001340 // If nothing happened still, try promoting the operation.
Craig Topperc0196b12014-04-14 00:51:57 +00001341 if (!RV.getNode()) {
Evan Chengf1005572010-04-28 07:10:39 +00001342 switch (N->getOpcode()) {
1343 default: break;
1344 case ISD::ADD:
1345 case ISD::SUB:
1346 case ISD::MUL:
1347 case ISD::AND:
1348 case ISD::OR:
1349 case ISD::XOR:
1350 RV = PromoteIntBinOp(SDValue(N, 0));
1351 break;
1352 case ISD::SHL:
1353 case ISD::SRA:
1354 case ISD::SRL:
1355 RV = PromoteIntShiftOp(SDValue(N, 0));
1356 break;
1357 case ISD::SIGN_EXTEND:
1358 case ISD::ZERO_EXTEND:
1359 case ISD::ANY_EXTEND:
1360 RV = PromoteExtend(SDValue(N, 0));
1361 break;
1362 case ISD::LOAD:
1363 if (PromoteLoad(SDValue(N, 0)))
1364 RV = SDValue(N, 0);
1365 break;
1366 }
1367 }
1368
Scott Michelcf0da6c2009-02-17 22:15:04 +00001369 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001370 // sdisel CSE.
Craig Topperc0196b12014-04-14 00:51:57 +00001371 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
Evan Cheng31604a62008-03-22 01:55:50 +00001372 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001373 SDValue N0 = N->getOperand(0);
1374 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001375
Evan Cheng31604a62008-03-22 01:55:50 +00001376 // Constant operands are canonicalized to RHS.
1377 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00001378 SDValue Ops[] = {N1, N0};
1379 SDNode *CSENode;
1380 if (const BinaryWithFlagsSDNode *BinNode =
1381 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1382 CSENode = DAG.getNodeIfExists(
1383 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1384 BinNode->hasNoSignedWrap(), BinNode->isExact());
1385 } else {
1386 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1387 }
Evan Chengfe7610f2008-03-24 23:55:16 +00001388 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001389 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001390 }
1391 }
1392
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001393 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001394}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001395
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001396/// getInputChainForNode - Given a node, return its input chain if it has one,
1397/// otherwise return a null sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001398static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001399 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001400 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001401 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001402 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001403 return N->getOperand(NumOps-1);
1404 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001405 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001406 return N->getOperand(i);
1407 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001408 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001409}
1410
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001411SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001412 // If N has two operands, where one has an input chain equal to the other,
1413 // the 'other' chain is redundant.
1414 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001415 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001416 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001417 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001418 return N->getOperand(1);
1419 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001420
Chris Lattner48fb92f2007-05-16 06:37:59 +00001421 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001422 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001423 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001424 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001425
Jim Laskey708d0db2006-10-04 16:53:27 +00001426 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001427 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001428
Jim Laskey0463e082006-10-07 23:37:56 +00001429 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001430 // encountered.
1431 for (unsigned i = 0; i < TFs.size(); ++i) {
1432 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001433
Jim Laskey708d0db2006-10-04 16:53:27 +00001434 // Check each of the operands.
1435 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001436 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001437
Jim Laskey708d0db2006-10-04 16:53:27 +00001438 switch (Op.getOpcode()) {
1439 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001440 // Entry tokens don't need to be added to the list. They are
1441 // rededundant.
1442 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001443 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001444
Jim Laskey708d0db2006-10-04 16:53:27 +00001445 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001446 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001447 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001448 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001449 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001450 // Clean up in case the token factor is removed.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001451 AddToWorklist(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001452 Changed = true;
1453 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001454 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001455 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001456
Jim Laskey708d0db2006-10-04 16:53:27 +00001457 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001458 // Only add if it isn't already in the list.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001459 if (SeenOps.insert(Op.getNode()))
Jim Laskey6549d222006-10-05 15:07:25 +00001460 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001461 else
1462 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001463 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001464 }
1465 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001466 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001467
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001468 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001469
1470 // If we've change things around then replace token factor.
1471 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001472 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001473 // The entry token is the only possible outcome.
1474 Result = DAG.getEntryNode();
1475 } else {
1476 // New and improved token factor.
Craig Topper48d114b2014-04-26 18:35:24 +00001477 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
Nate Begeman02b23c62005-10-13 03:11:28 +00001478 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001479
Jim Laskeydcf983c2006-10-13 23:32:28 +00001480 // Don't add users to work list.
1481 return CombineTo(N, Result, false);
Nate Begeman02b23c62005-10-13 03:11:28 +00001482 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001483
Jim Laskey708d0db2006-10-04 16:53:27 +00001484 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001485}
1486
Chris Lattneree322b42008-02-13 07:25:05 +00001487/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001488SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001489 WorklistRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001490 // Replacing results may cause a different MERGE_VALUES to suddenly
1491 // be CSE'd with N, and carry its uses with it. Iterate until no
1492 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001493 // First add the users of this node to the work list so that they
1494 // can be tried again once they have new operands.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001495 AddUsersToWorklist(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001496 do {
1497 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001498 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001499 } while (!N->use_empty());
Chandler Carruth18066972014-08-02 10:02:07 +00001500 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001501 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001502}
1503
Evan Cheng92011002007-01-19 17:51:44 +00001504static
Andrew Trickef9de2a2013-05-25 02:42:55 +00001505SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001506 SelectionDAG &DAG) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001507 EVT VT = N0.getValueType();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001508 SDValue N00 = N0.getOperand(0);
1509 SDValue N01 = N0.getOperand(1);
Evan Cheng92011002007-01-19 17:51:44 +00001510 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
Bill Wendlingcdd96132009-01-30 02:23:43 +00001511
Gabor Greiff304a7a2008-08-28 21:40:38 +00001512 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
Evan Cheng92011002007-01-19 17:51:44 +00001513 isa<ConstantSDNode>(N00.getOperand(1))) {
Bill Wendlingcdd96132009-01-30 02:23:43 +00001514 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Andrew Trickef9de2a2013-05-25 02:42:55 +00001515 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1516 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001517 N00.getOperand(0), N01),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001518 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001519 N00.getOperand(1), N01));
1520 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
Evan Cheng92011002007-01-19 17:51:44 +00001521 }
Bill Wendlingcdd96132009-01-30 02:23:43 +00001522
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001523 return SDValue();
Evan Cheng92011002007-01-19 17:51:44 +00001524}
1525
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001526SDValue DAGCombiner::visitADD(SDNode *N) {
1527 SDValue N0 = N->getOperand(0);
1528 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001529 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1530 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001531 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001532
1533 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001534 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001535 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001536 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001537
1538 // fold (add x, 0) -> x, vector edition
1539 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1540 return N0;
1541 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1542 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001543 }
Bill Wendling0864a752008-12-10 22:36:00 +00001544
Dan Gohman06563a82007-07-03 14:03:57 +00001545 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001546 if (N0.getOpcode() == ISD::UNDEF)
1547 return N0;
1548 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001549 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001550 // fold (add c1, c2) -> c1+c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001551 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001552 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001553 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00001554 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001555 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001556 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001557 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001558 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001559 // fold (add Sym, c) -> Sym+c
1560 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001561 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001562 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001563 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001564 GA->getOffset() +
1565 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001566 // fold ((c1-A)+c2) -> (c1+c2)-A
1567 if (N1C && N0.getOpcode() == ISD::SUB)
1568 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001569 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001570 DAG.getConstant(N1C->getAPIntValue()+
1571 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001572 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001573 // reassociate add
Andrew Trickef9de2a2013-05-25 02:42:55 +00001574 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001575 if (RADD.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001576 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001577 // fold ((0-A) + B) -> B-A
1578 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1579 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001580 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001581 // fold (A + (0-B)) -> A-B
1582 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1583 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001584 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001585 // fold (A+(B-A)) -> B
1586 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001587 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001588 // fold ((B-A)+A) -> B
1589 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1590 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001591 // fold (A+(B-(A+C))) to (B-C)
1592 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001593 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001594 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001595 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001596 // fold (A+(B-(C+A))) to (B-C)
1597 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001598 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001599 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001600 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001601 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001602 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1603 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001604 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001605 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001606 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001607
Dale Johannesen8c766702008-12-02 01:30:54 +00001608 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1609 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1610 SDValue N00 = N0.getOperand(0);
1611 SDValue N01 = N0.getOperand(1);
1612 SDValue N10 = N1.getOperand(0);
1613 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001614
1615 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001616 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1617 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1618 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001619 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001620
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001621 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1622 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001623
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001624 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001625 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001626 APInt LHSZero, LHSOne;
1627 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001628 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001629
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001630 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001631 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001632
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001633 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1634 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001635 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1636 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1637 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1638 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001639 }
1640 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001641
Evan Cheng92011002007-01-19 17:51:44 +00001642 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Gabor Greiff304a7a2008-08-28 21:40:38 +00001643 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001644 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001645 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001646 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00001647 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001648 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001649 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001650 }
1651
Dan Gohman954f4902010-01-19 23:30:49 +00001652 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1653 if (N1.getOpcode() == ISD::SHL &&
1654 N1.getOperand(0).getOpcode() == ISD::SUB)
1655 if (ConstantSDNode *C =
1656 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1657 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001658 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1659 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001660 N1.getOperand(0).getOperand(1),
1661 N1.getOperand(1)));
1662 if (N0.getOpcode() == ISD::SHL &&
1663 N0.getOperand(0).getOpcode() == ISD::SUB)
1664 if (ConstantSDNode *C =
1665 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1666 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001667 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1668 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001669 N0.getOperand(0).getOperand(1),
1670 N0.getOperand(1)));
1671
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001672 if (N1.getOpcode() == ISD::AND) {
1673 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001674 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001675 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1676 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001677
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001678 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1679 // and similar xforms where the inner op is either ~0 or 0.
1680 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001681 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001682 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1683 }
1684 }
1685
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001686 // add (sext i1), X -> sub X, (zext i1)
1687 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1688 N0.getOperand(0).getValueType() == MVT::i1 &&
1689 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001690 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001691 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1692 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1693 }
1694
Evan Chengf1005572010-04-28 07:10:39 +00001695 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001696}
1697
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001698SDValue DAGCombiner::visitADDC(SDNode *N) {
1699 SDValue N0 = N->getOperand(0);
1700 SDValue N1 = N->getOperand(1);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001701 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1702 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001703 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001704
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001705 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001706 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001707 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001708 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001709 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001710
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001711 // canonicalize constant to RHS.
Dan Gohmanb4e26372008-06-23 15:29:14 +00001712 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001713 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001714
Chris Lattner47206662007-03-04 20:40:38 +00001715 // fold (addc x, 0) -> x + no carry out
1716 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001717 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001718 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001719
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001720 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001721 APInt LHSZero, LHSOne;
1722 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001723 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001724
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001725 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001726 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001727
Chris Lattner47206662007-03-04 20:40:38 +00001728 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1729 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001730 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001731 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001732 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001733 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001734 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001735
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001736 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001737}
1738
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001739SDValue DAGCombiner::visitADDE(SDNode *N) {
1740 SDValue N0 = N->getOperand(0);
1741 SDValue N1 = N->getOperand(1);
1742 SDValue CarryIn = N->getOperand(2);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001743 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1744 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001745
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001746 // canonicalize constant to RHS
Dan Gohmanb4e26372008-06-23 15:29:14 +00001747 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001748 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001749 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001750
Chris Lattner47206662007-03-04 20:40:38 +00001751 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001752 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001753 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001754
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001755 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001756}
1757
Eric Christophere5ca1e02011-02-16 04:50:12 +00001758// Since it may not be valid to emit a fold to zero for vector initializers
1759// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001760static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001761 SelectionDAG &DAG,
1762 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001763 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001764 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001765 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1766 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001767 return SDValue();
1768}
1769
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001770SDValue DAGCombiner::visitSUB(SDNode *N) {
1771 SDValue N0 = N->getOperand(0);
1772 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001773 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1774 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00001775 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
Eric Christopherd6300d22011-07-14 01:12:15 +00001776 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001777 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001778
Dan Gohmana8665142007-06-25 16:23:39 +00001779 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001780 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001781 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001782 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001783
1784 // fold (sub x, 0) -> x, vector edition
1785 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1786 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001787 }
Bill Wendling0864a752008-12-10 22:36:00 +00001788
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001789 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001790 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001791 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001792 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001793 // fold (sub c1, c2) -> c1-c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001794 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001795 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001796 // fold (sub x, c) -> (add x, -c)
1797 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001798 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001799 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001800 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1801 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001802 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001803 // fold A-(A-B) -> B
1804 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1805 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001806 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001807 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001808 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001809 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001810 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001811 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001812 // fold C2-(A+C1) -> (C2-C1)-A
1813 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001814 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1815 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001816 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001817 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001818 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001819 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001820 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001821 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1822 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001823 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001824 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001825 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001826 // fold ((A+(C+B))-B) -> A+C
1827 if (N0.getOpcode() == ISD::ADD &&
1828 N0.getOperand(1).getOpcode() == ISD::ADD &&
1829 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001830 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001831 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001832 // fold ((A-(B-C))-C) -> A-B
1833 if (N0.getOpcode() == ISD::SUB &&
1834 N0.getOperand(1).getOpcode() == ISD::SUB &&
1835 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001836 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001837 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001838
Dan Gohman06563a82007-07-03 14:03:57 +00001839 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001840 if (N0.getOpcode() == ISD::UNDEF)
1841 return N0;
1842 if (N1.getOpcode() == ISD::UNDEF)
1843 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001844
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001845 // If the relocation model supports it, consider symbol offsets.
1846 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001847 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001848 // fold (sub Sym, c) -> Sym-c
1849 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001850 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001851 GA->getOffset() -
1852 (uint64_t)N1C->getSExtValue());
1853 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1854 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1855 if (GA->getGlobal() == GB->getGlobal())
1856 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1857 VT);
1858 }
1859
Evan Chengf1005572010-04-28 07:10:39 +00001860 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001861}
1862
Craig Topper43a1bd62012-01-07 09:06:39 +00001863SDValue DAGCombiner::visitSUBC(SDNode *N) {
1864 SDValue N0 = N->getOperand(0);
1865 SDValue N1 = N->getOperand(1);
1866 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1867 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1868 EVT VT = N0.getValueType();
1869
1870 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001871 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001872 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1873 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001874 MVT::Glue));
1875
1876 // fold (subc x, x) -> 0 + no borrow
1877 if (N0 == N1)
1878 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001879 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001880 MVT::Glue));
1881
1882 // fold (subc x, 0) -> x + no borrow
1883 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001884 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001885 MVT::Glue));
1886
1887 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1888 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001889 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1890 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001891 MVT::Glue));
1892
1893 return SDValue();
1894}
1895
1896SDValue DAGCombiner::visitSUBE(SDNode *N) {
1897 SDValue N0 = N->getOperand(0);
1898 SDValue N1 = N->getOperand(1);
1899 SDValue CarryIn = N->getOperand(2);
1900
1901 // fold (sube x, y, false) -> (subc x, y)
1902 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001903 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001904
1905 return SDValue();
1906}
1907
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001908SDValue DAGCombiner::visitMUL(SDNode *N) {
1909 SDValue N0 = N->getOperand(0);
1910 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001911 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001912
Dan Gohman06563a82007-07-03 14:03:57 +00001913 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001914 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001915 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001916
1917 bool N0IsConst = false;
1918 bool N1IsConst = false;
1919 APInt ConstValue0, ConstValue1;
1920 // fold vector ops
1921 if (VT.isVector()) {
1922 SDValue FoldedVOp = SimplifyVBinOp(N);
1923 if (FoldedVOp.getNode()) return FoldedVOp;
1924
1925 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1926 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1927 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00001928 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001929 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1930 : APInt();
Craig Topperc0196b12014-04-14 00:51:57 +00001931 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001932 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1933 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001934 }
1935
Nate Begeman21158fc2005-09-01 00:19:25 +00001936 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001937 if (N0IsConst && N1IsConst)
1938 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1939
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001940 // canonicalize constant to RHS
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001941 if (N0IsConst && !N1IsConst)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001942 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001943 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001944 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00001945 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001946 // We require a splat of the entire scalar bit width for non-contiguous
1947 // bit patterns.
1948 bool IsFullSplat =
1949 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001950 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001951 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001952 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00001953 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001954 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001955 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001956 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001957 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001958 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001959 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001960 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00001961 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00001962 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001963 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001964 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001965 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00001966 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001967 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001968 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001969 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00001970 DAG.getConstant(Log2Val,
1971 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00001972 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001973
1974 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00001975 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00001976 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001977 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1978 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001979 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001980 N1, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001981 AddToWorklist(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001982 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001983 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00001984 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001985
Chris Lattner324871e2006-03-01 03:44:24 +00001986 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1987 // use.
1988 {
Craig Topperc0196b12014-04-14 00:51:57 +00001989 SDValue Sh(nullptr,0), Y(nullptr,0);
Chris Lattner324871e2006-03-01 03:44:24 +00001990 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00001991 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001992 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1993 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001994 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001995 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001996 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00001997 isa<ConstantSDNode>(N1.getOperand(1)) &&
1998 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001999 Sh = N1; Y = N0;
2000 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00002001
Gabor Greiff304a7a2008-08-28 21:40:38 +00002002 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002003 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002004 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002005 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002006 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00002007 }
2008 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00002009
Chris Lattnerf29f5202006-03-04 23:33:26 +00002010 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002011 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2012 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2013 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002014 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2015 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002016 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00002017 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002018 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00002019
Nate Begeman22e251a2006-02-03 06:46:56 +00002020 // reassociate mul
Andrew Trickef9de2a2013-05-25 02:42:55 +00002021 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002022 if (RMUL.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002023 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00002024
Evan Chengf1005572010-04-28 07:10:39 +00002025 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002026}
2027
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002028SDValue DAGCombiner::visitSDIV(SDNode *N) {
2029 SDValue N0 = N->getOperand(0);
2030 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002031 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2032 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002033 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002034
Dan Gohmana8665142007-06-25 16:23:39 +00002035 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002036 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002037 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002038 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002039 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002040
Nate Begeman21158fc2005-09-01 00:19:25 +00002041 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002042 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002043 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00002044 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00002045 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00002046 return N0;
2047 // fold (sdiv X, -1) -> 0-X
2048 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002049 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00002050 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00002051 // If we know the sign bits of both operands are zero, strength reduce to a
2052 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00002053 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002054 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002055 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00002056 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00002057 }
Benjamin Kramerad016872014-04-26 13:00:53 +00002058
Nate Begeman57b35672006-02-17 07:26:20 +00002059 // fold (sdiv X, pow2) -> simple ops after legalize
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002060 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2061 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00002062 // If dividing by powers of two is cheap, then don't perform the following
2063 // fold.
2064 if (TLI.isPow2DivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002065 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00002066
Chad Rosier17020f92014-07-23 14:57:52 +00002067 // Target-specific implementation of sdiv x, pow2.
2068 SDValue Res = BuildSDIVPow2(N);
2069 if (Res.getNode())
2070 return Res;
2071
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002072 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00002073
Chris Lattner471627c2006-02-16 08:02:36 +00002074 // Splat the sign bit into the register
Benjamin Kramerad016872014-04-26 13:00:53 +00002075 SDValue SGN =
2076 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2077 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2078 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002079 AddToWorklist(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002080
Chris Lattner471627c2006-02-16 08:02:36 +00002081 // Add (N0 < 0) ? abs2 - 1 : 0;
Benjamin Kramerad016872014-04-26 13:00:53 +00002082 SDValue SRL =
2083 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2084 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2085 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002086 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002087 AddToWorklist(SRL.getNode());
2088 AddToWorklist(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00002089 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002090 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002091
Nate Begeman4dd38312005-10-21 00:02:42 +00002092 // If we're dividing by a positive value, we're done. Otherwise, we must
2093 // negate the result.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002094 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002095 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002096
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002097 AddToWorklist(SRA.getNode());
Benjamin Kramerad016872014-04-26 13:00:53 +00002098 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002099 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002100
Nate Begemanc6f067a2005-10-20 02:15:44 +00002101 // if integer divide is expensive and we satisfy the requirements, emit an
2102 // alternate sequence.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002103 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002104 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002105 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002106 }
Dan Gohmana8665142007-06-25 16:23:39 +00002107
Dan Gohman06563a82007-07-03 14:03:57 +00002108 // undef / X -> 0
2109 if (N0.getOpcode() == ISD::UNDEF)
2110 return DAG.getConstant(0, VT);
2111 // X / undef -> undef
2112 if (N1.getOpcode() == ISD::UNDEF)
2113 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002114
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002115 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002116}
2117
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002118SDValue DAGCombiner::visitUDIV(SDNode *N) {
2119 SDValue N0 = N->getOperand(0);
2120 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002121 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2122 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002123 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002124
Dan Gohmana8665142007-06-25 16:23:39 +00002125 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002126 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002127 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002128 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002129 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002130
Nate Begeman21158fc2005-09-01 00:19:25 +00002131 // fold (udiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002132 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002133 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002134 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002135 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002136 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002137 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002138 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002139 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002140 if (N1.getOpcode() == ISD::SHL) {
2141 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002142 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002143 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002144 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002145 N1.getOperand(1),
2146 DAG.getConstant(SHC->getAPIntValue()
2147 .logBase2(),
2148 ADDVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002149 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002150 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002151 }
2152 }
2153 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002154 // fold (udiv x, c) -> alternate
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002155 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002156 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002157 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002158 }
Dan Gohmana8665142007-06-25 16:23:39 +00002159
Dan Gohman06563a82007-07-03 14:03:57 +00002160 // undef / X -> 0
2161 if (N0.getOpcode() == ISD::UNDEF)
2162 return DAG.getConstant(0, VT);
2163 // X / undef -> undef
2164 if (N1.getOpcode() == ISD::UNDEF)
2165 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002166
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002167 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002168}
2169
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002170SDValue DAGCombiner::visitSREM(SDNode *N) {
2171 SDValue N0 = N->getOperand(0);
2172 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002173 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2174 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002175 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002176
Nate Begeman21158fc2005-09-01 00:19:25 +00002177 // fold (srem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002178 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002179 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002180 // If we know the sign bits of both operands are zero, strength reduce to a
2181 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002182 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002183 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002184 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002185 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002186
Dan Gohman9a693412007-11-26 23:46:11 +00002187 // If X/C can be simplified by the division-by-constant logic, lower
2188 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002189 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002190 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002191 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002192 SDValue OptimizedDiv = combine(Div.getNode());
2193 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002194 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002195 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002196 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002197 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002198 return Sub;
2199 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002200 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002201
Dan Gohman06563a82007-07-03 14:03:57 +00002202 // undef % X -> 0
2203 if (N0.getOpcode() == ISD::UNDEF)
2204 return DAG.getConstant(0, VT);
2205 // X % undef -> undef
2206 if (N1.getOpcode() == ISD::UNDEF)
2207 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002208
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002209 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002210}
2211
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002212SDValue DAGCombiner::visitUREM(SDNode *N) {
2213 SDValue N0 = N->getOperand(0);
2214 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002215 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2216 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002217 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002218
Nate Begeman21158fc2005-09-01 00:19:25 +00002219 // fold (urem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002220 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002221 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002222 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002223 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002224 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002225 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002226 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2227 if (N1.getOpcode() == ISD::SHL) {
2228 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002229 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002230 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002231 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002232 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002233 VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002234 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002235 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002236 }
2237 }
2238 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002239
Dan Gohman9a693412007-11-26 23:46:11 +00002240 // If X/C can be simplified by the division-by-constant logic, lower
2241 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002242 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002243 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002244 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002245 SDValue OptimizedDiv = combine(Div.getNode());
2246 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002247 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002248 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002249 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002250 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002251 return Sub;
2252 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002253 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002254
Dan Gohman06563a82007-07-03 14:03:57 +00002255 // undef % X -> 0
2256 if (N0.getOpcode() == ISD::UNDEF)
2257 return DAG.getConstant(0, VT);
2258 // X % undef -> undef
2259 if (N1.getOpcode() == ISD::UNDEF)
2260 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002261
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002262 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002263}
2264
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002265SDValue DAGCombiner::visitMULHS(SDNode *N) {
2266 SDValue N0 = N->getOperand(0);
2267 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002268 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002269 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002270 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002271
Nate Begeman21158fc2005-09-01 00:19:25 +00002272 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002273 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002274 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002275 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002276 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002277 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002278 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002279 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002280 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002281 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002282 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002283
Chris Lattner10bd29f2010-12-13 08:39:01 +00002284 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2285 // plus a shift.
2286 if (VT.isSimple() && !VT.isVector()) {
2287 MVT Simple = VT.getSimpleVT();
2288 unsigned SimpleSize = Simple.getSizeInBits();
2289 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2290 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2291 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2292 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2293 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002294 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002295 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002296 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2297 }
2298 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002299
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002300 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002301}
2302
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002303SDValue DAGCombiner::visitMULHU(SDNode *N) {
2304 SDValue N0 = N->getOperand(0);
2305 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002306 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002307 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002308 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002309
Nate Begeman21158fc2005-09-01 00:19:25 +00002310 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002311 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002312 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002313 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002314 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002315 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002316 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002317 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002318 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002319
Chris Lattner10bd29f2010-12-13 08:39:01 +00002320 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2321 // plus a shift.
2322 if (VT.isSimple() && !VT.isVector()) {
2323 MVT Simple = VT.getSimpleVT();
2324 unsigned SimpleSize = Simple.getSizeInBits();
2325 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2326 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2327 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2328 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2329 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2330 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002331 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002332 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2333 }
2334 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002335
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002336 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002337}
2338
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002339/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2340/// compute two values. LoOp and HiOp give the opcodes for the two computations
2341/// that are being performed. Return true if a simplification was made.
2342///
Scott Michelcf0da6c2009-02-17 22:15:04 +00002343SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002344 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002345 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002346 bool HiExists = N->hasAnyUseOfValue(1);
2347 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002348 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002349 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002350 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002351 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chris Lattner31e9edc2008-01-26 01:09:19 +00002352 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002353 }
2354
2355 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002356 bool LoExists = N->hasAnyUseOfValue(0);
2357 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002358 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002359 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002360 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002361 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chris Lattner31e9edc2008-01-26 01:09:19 +00002362 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002363 }
2364
Evan Chengece4c682007-11-08 09:25:29 +00002365 // If both halves are used, return as it is.
2366 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002367 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002368
2369 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002370 if (LoExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002371 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002372 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002373 AddToWorklist(Lo.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002374 SDValue LoOpt = combine(Lo.getNode());
2375 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002376 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002377 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002378 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002379 }
2380
Evan Chengece4c682007-11-08 09:25:29 +00002381 if (HiExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002382 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002383 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002384 AddToWorklist(Hi.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002385 SDValue HiOpt = combine(Hi.getNode());
2386 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002387 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002388 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002389 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002390 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002391
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002392 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002393}
2394
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002395SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2396 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002397 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002398
Chris Lattner15090e12010-12-15 06:04:19 +00002399 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002400 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002401
2402 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2403 // plus a shift.
2404 if (VT.isSimple() && !VT.isVector()) {
2405 MVT Simple = VT.getSimpleVT();
2406 unsigned SimpleSize = Simple.getSizeInBits();
2407 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2408 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2409 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2410 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2411 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2412 // Compute the high part as N1.
2413 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002414 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002415 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2416 // Compute the low part as N0.
2417 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2418 return CombineTo(N, Lo, Hi);
2419 }
2420 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002421
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002422 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002423}
2424
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002425SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2426 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002427 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002428
Chris Lattner15090e12010-12-15 06:04:19 +00002429 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002430 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002431
Chris Lattner15090e12010-12-15 06:04:19 +00002432 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2433 // plus a shift.
2434 if (VT.isSimple() && !VT.isVector()) {
2435 MVT Simple = VT.getSimpleVT();
2436 unsigned SimpleSize = Simple.getSizeInBits();
2437 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2438 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2439 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2440 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2441 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2442 // Compute the high part as N1.
2443 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002444 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002445 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2446 // Compute the low part as N0.
2447 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2448 return CombineTo(N, Lo, Hi);
2449 }
2450 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002451
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002452 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002453}
2454
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002455SDValue DAGCombiner::visitSMULO(SDNode *N) {
2456 // (smulo x, 2) -> (saddo x, x)
2457 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2458 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002459 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002460 N->getOperand(0), N->getOperand(0));
2461
2462 return SDValue();
2463}
2464
2465SDValue DAGCombiner::visitUMULO(SDNode *N) {
2466 // (umulo x, 2) -> (uaddo x, x)
2467 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2468 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002469 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002470 N->getOperand(0), N->getOperand(0));
2471
2472 return SDValue();
2473}
2474
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002475SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2476 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002477 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002478
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002479 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002480}
2481
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002482SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2483 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002484 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002485
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002486 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002487}
2488
Chris Lattner8d6fc202006-05-05 05:51:50 +00002489/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2490/// two operands of the same opcode, try to simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002491SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2492 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002493 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002494 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002495
Dan Gohmandd5286d2010-01-14 03:08:49 +00002496 // Bail early if none of these transforms apply.
2497 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2498
Chris Lattner002ee912006-05-05 06:31:05 +00002499 // For each of OP in AND/OR/XOR:
2500 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2501 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2502 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002503 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002504 //
2505 // do not sink logical op inside of a vector extend, since it may combine
2506 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002507 EVT Op0VT = N0.getOperand(0).getValueType();
2508 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002509 N0.getOpcode() == ISD::SIGN_EXTEND ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002510 // Avoid infinite looping with PromoteIntBinOp.
2511 (N0.getOpcode() == ISD::ANY_EXTEND &&
2512 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002513 (N0.getOpcode() == ISD::TRUNCATE &&
2514 (!TLI.isZExtFree(VT, Op0VT) ||
2515 !TLI.isTruncateFree(Op0VT, VT)) &&
2516 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002517 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002518 Op0VT == N1.getOperand(0).getValueType() &&
2519 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002520 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002521 N0.getOperand(0).getValueType(),
2522 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002523 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002524 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002525 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002526
Chris Lattner5ac42932006-05-05 06:10:43 +00002527 // For each of OP in SHL/SRL/SRA/AND...
2528 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2529 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2530 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002531 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002532 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002533 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002534 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002535 N0.getOperand(0).getValueType(),
2536 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002537 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002538 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002539 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002540 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002541
Nadav Rotemb0783502012-04-01 19:31:22 +00002542 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2543 // Only perform this optimization after type legalization and before
2544 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2545 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2546 // we don't want to undo this promotion.
2547 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2548 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002549 if ((N0.getOpcode() == ISD::BITCAST ||
2550 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2551 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002552 SDValue In0 = N0.getOperand(0);
2553 SDValue In1 = N1.getOperand(0);
2554 EVT In0Ty = In0.getValueType();
2555 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002556 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002557 // If both incoming values are integers, and the original types are the
2558 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002559 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002560 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2561 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002562 AddToWorklist(Op.getNode());
Nadav Rotemb0783502012-04-01 19:31:22 +00002563 return BC;
2564 }
2565 }
2566
2567 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2568 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2569 // If both shuffles use the same mask, and both shuffle within a single
2570 // vector, then it is worthwhile to move the swizzle after the operation.
2571 // The type-legalizer generates this pattern when loading illegal
2572 // vector types from memory. In many cases this allows additional shuffle
2573 // optimizations.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002574 // There are other cases where moving the shuffle after the xor/and/or
2575 // is profitable even if shuffles don't perform a swizzle.
2576 // If both shuffles use the same mask, and both shuffles have the same first
2577 // or second operand, then it might still be profitable to move the shuffle
2578 // after the xor/and/or operation.
2579 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002580 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2581 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002582
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002583 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
Craig Topper9c3da312012-04-09 07:19:09 +00002584 "Inputs to shuffles are not the same type");
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00002585
Nadav Rotemb0783502012-04-01 19:31:22 +00002586 // Check that both shuffles use the same mask. The masks are known to be of
2587 // the same length because the result vector type is the same.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002588 // Check also that shuffles have only one use to avoid introducing extra
2589 // instructions.
2590 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2591 SVN0->getMask().equals(SVN1->getMask())) {
2592 SDValue ShOp = N0->getOperand(1);
Nadav Rotemb0783502012-04-01 19:31:22 +00002593
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002594 // Don't try to fold this node if it requires introducing a
2595 // build vector of all zeros that might be illegal at this stage.
2596 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2597 if (!LegalTypes)
2598 ShOp = DAG.getConstant(0, VT);
2599 else
2600 ShOp = SDValue();
2601 }
2602
2603 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2604 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2605 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2606 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2607 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2608 N0->getOperand(0), N1->getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002609 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002610 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2611 &SVN0->getMask()[0]);
2612 }
2613
2614 // Don't try to fold this node if it requires introducing a
2615 // build vector of all zeros that might be illegal at this stage.
2616 ShOp = N0->getOperand(0);
2617 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2618 if (!LegalTypes)
2619 ShOp = DAG.getConstant(0, VT);
2620 else
2621 ShOp = SDValue();
2622 }
2623
2624 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2625 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2626 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2627 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2628 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2629 N0->getOperand(1), N1->getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002630 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002631 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2632 &SVN0->getMask()[0]);
2633 }
Nadav Rotemb0783502012-04-01 19:31:22 +00002634 }
2635 }
Craig Topper9c3da312012-04-09 07:19:09 +00002636
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002637 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002638}
2639
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002640SDValue DAGCombiner::visitAND(SDNode *N) {
2641 SDValue N0 = N->getOperand(0);
2642 SDValue N1 = N->getOperand(1);
2643 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002644 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2645 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002646 EVT VT = N1.getValueType();
Dan Gohmane14c4082010-03-04 00:23:16 +00002647 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002648
Dan Gohmana8665142007-06-25 16:23:39 +00002649 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002650 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002651 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002652 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002653
2654 // fold (and x, 0) -> 0, vector edition
2655 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2656 return N0;
2657 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2658 return N1;
2659
2660 // fold (and x, -1) -> x, vector edition
2661 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2662 return N1;
2663 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2664 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002665 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002666
Dan Gohman06563a82007-07-03 14:03:57 +00002667 // fold (and x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002668 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002669 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00002670 // fold (and c1, c2) -> c1&c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002671 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002672 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002673 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00002674 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002675 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002676 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002677 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002678 return N0;
2679 // if (and x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002680 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002681 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002682 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002683 // reassociate and
Andrew Trickef9de2a2013-05-25 02:42:55 +00002684 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002685 if (RAND.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002686 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002687 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002688 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002689 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002690 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002691 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002692 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2693 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002694 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002695 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002696 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002697 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002698 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002699 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002700
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002701 // Replace uses of the AND with uses of the Zero extend node.
2702 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002703
Chris Lattner49beaf42006-02-02 07:17:31 +00002704 // We actually want to replace all uses of the any_extend with the
2705 // zero_extend, to avoid duplicating things. This will later cause this
2706 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002707 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002708 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002709 }
2710 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002711 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002712 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2713 // already be zero by virtue of the width of the base type of the load.
2714 //
2715 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2716 // more cases.
2717 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2718 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2719 N0.getOpcode() == ISD::LOAD) {
2720 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2721 N0 : N0.getOperand(0) );
2722
2723 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2724 // This can be a pure constant or a vector splat, in which case we treat the
2725 // vector as a scalar and use the splat value.
2726 APInt Constant = APInt::getNullValue(1);
2727 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2728 Constant = C->getAPIntValue();
2729 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2730 APInt SplatValue, SplatUndef;
2731 unsigned SplatBitSize;
2732 bool HasAnyUndefs;
2733 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2734 SplatBitSize, HasAnyUndefs);
2735 if (IsSplat) {
2736 // Undef bits can contribute to a possible optimisation if set, so
2737 // set them.
2738 SplatValue |= SplatUndef;
2739
2740 // The splat value may be something like "0x00FFFFFF", which means 0 for
2741 // the first vector value and FF for the rest, repeating. We need a mask
2742 // that will apply equally to all members of the vector, so AND all the
2743 // lanes of the constant together.
2744 EVT VT = Vector->getValueType(0);
2745 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002746
2747 // If the splat value has been compressed to a bitlength lower
2748 // than the size of the vector lane, we need to re-expand it to
2749 // the lane size.
2750 if (BitWidth > SplatBitSize)
2751 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2752 SplatBitSize < BitWidth;
2753 SplatBitSize = SplatBitSize * 2)
2754 SplatValue |= SplatValue.shl(SplatBitSize);
2755
James Molloy862fe492012-02-20 12:02:38 +00002756 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3f40d872012-09-05 08:57:21 +00002757 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy862fe492012-02-20 12:02:38 +00002758 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2759 }
2760 }
2761
2762 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2763 // actually legal and isn't going to get expanded, else this is a false
2764 // optimisation.
2765 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2766 Load->getMemoryVT());
2767
2768 // Resize the constant to the same size as the original memory access before
2769 // extension. If it is still the AllOnesValue then this AND is completely
2770 // unneeded.
2771 Constant =
2772 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2773
2774 bool B;
2775 switch (Load->getExtensionType()) {
2776 default: B = false; break;
2777 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2778 case ISD::ZEXTLOAD:
2779 case ISD::NON_EXTLOAD: B = true; break;
2780 }
2781
2782 if (B && Constant.isAllOnesValue()) {
2783 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2784 // preserve semantics once we get rid of the AND.
2785 SDValue NewLoad(Load, 0);
2786 if (Load->getExtensionType() == ISD::EXTLOAD) {
2787 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002788 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002789 Load->getChain(), Load->getBasePtr(),
2790 Load->getOffset(), Load->getMemoryVT(),
2791 Load->getMemOperand());
2792 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002793 if (Load->getNumValues() == 3) {
2794 // PRE/POST_INC loads have 3 values.
2795 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2796 NewLoad.getValue(2) };
2797 CombineTo(Load, To, 3, true);
2798 } else {
2799 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2800 }
James Molloy862fe492012-02-20 12:02:38 +00002801 }
2802
2803 // Fold the AND away, taking care not to fold to the old load node if we
2804 // replaced it.
2805 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2806
2807 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2808 }
2809 }
Nate Begeman049b7482005-09-09 19:49:52 +00002810 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2811 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2812 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2813 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002814
Tom Stellard7783b0a2014-06-12 16:04:47 +00002815 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002816 LL.getValueType().isInteger()) {
Bill Wendling86171912009-01-30 20:43:18 +00002817 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002818 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002819 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002820 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002821 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002822 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002823 }
Bill Wendling86171912009-01-30 20:43:18 +00002824 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002825 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002826 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002827 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002828 AddToWorklist(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002829 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002830 }
Bill Wendling86171912009-01-30 20:43:18 +00002831 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002832 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002833 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002834 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002835 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002836 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002837 }
2838 }
Jim Grosbach327ccc72013-08-13 21:30:58 +00002839 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2840 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2841 Op0 == Op1 && LL.getValueType().isInteger() &&
2842 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2843 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2844 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2845 cast<ConstantSDNode>(RR)->isNullValue()))) {
2846 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2847 LL, DAG.getConstant(1, LL.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002848 AddToWorklist(ADDNode.getNode());
Jim Grosbach327ccc72013-08-13 21:30:58 +00002849 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2850 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2851 }
Nate Begeman049b7482005-09-09 19:49:52 +00002852 // canonicalize equivalent to ll == rl
2853 if (LL == RR && LR == RL) {
2854 Op1 = ISD::getSetCCSwappedOperands(Op1);
2855 std::swap(RL, RR);
2856 }
2857 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00002858 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00002859 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00002860 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002861 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00002862 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2863 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00002864 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002865 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling86171912009-01-30 20:43:18 +00002866 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00002867 }
2868 }
Chris Lattner8d6fc202006-05-05 05:51:50 +00002869
Bill Wendling86171912009-01-30 20:43:18 +00002870 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00002871 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002872 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002873 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00002874 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002875
Nate Begemandc7bba92006-02-03 22:24:05 +00002876 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2877 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands13237ac2008-06-06 12:08:01 +00002878 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002879 SimplifyDemandedBits(SDValue(N, 0)))
2880 return SDValue(N, 0);
Evan Cheng166a4e62010-01-06 19:38:29 +00002881
Nate Begeman02b23c62005-10-13 03:11:28 +00002882 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greiff304a7a2008-08-28 21:40:38 +00002883 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002884 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002885 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002886 // If we zero all the possible extended bits, then we can turn this into
2887 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002888 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002889 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002890 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002891 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002892 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002893 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling86171912009-01-30 20:43:18 +00002894 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002895 MemVT, LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002896 AddToWorklist(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002897 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002898 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002899 }
2900 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002901 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00002902 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00002903 N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002904 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002905 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002906 // If we zero all the possible extended bits, then we can turn this into
2907 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002908 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002909 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002910 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002911 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002912 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002913 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002914 LN0->getChain(), LN0->getBasePtr(),
2915 MemVT, LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002916 AddToWorklist(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002917 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002918 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002919 }
2920 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002921
Chris Lattnerf0032b32006-02-28 06:49:37 +00002922 // fold (and (load x), 255) -> (zextload x, i8)
2923 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002924 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2925 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2926 (N0.getOpcode() == ISD::ANY_EXTEND &&
2927 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2928 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2929 LoadSDNode *LN0 = HasAnyExt
2930 ? cast<LoadSDNode>(N0.getOperand(0))
2931 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002932 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002933 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002934 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002935 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2936 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2937 EVT LoadedVT = LN0->getMemoryVT();
Duncan Sands93b66092008-06-09 11:32:28 +00002938
Evan Cheng166a4e62010-01-06 19:38:29 +00002939 if (ExtVT == LoadedVT &&
2940 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00002941 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Wesley Peck527da1b2010-11-23 03:31:01 +00002942
2943 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002944 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002945 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2946 LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002947 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00002948 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2949 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2950 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002951
Chris Lattner88de3842010-01-07 21:53:27 +00002952 // Do not change the width of a volatile load.
2953 // Do not generate loads of non-round integer types since these can
2954 // be expensive (and would be wrong if the type is not byte sized).
2955 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2956 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2957 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00002958
Chris Lattner88de3842010-01-07 21:53:27 +00002959 unsigned Alignment = LN0->getAlignment();
2960 SDValue NewPtr = LN0->getBasePtr();
2961
2962 // For big endian targets, we need to add an offset to the pointer
2963 // to load the correct bytes. For little endian systems, we merely
2964 // need to read fewer bytes from the same pointer.
2965 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00002966 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2967 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2968 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002969 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00002970 NewPtr, DAG.getConstant(PtrOff, PtrType));
2971 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00002972 }
Chris Lattner88de3842010-01-07 21:53:27 +00002973
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002974 AddToWorklist(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00002975
Chris Lattner88de3842010-01-07 21:53:27 +00002976 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2977 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002978 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00002979 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00002980 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00002981 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00002982 LN0->isInvariant(), Alignment, LN0->getAAInfo());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002983 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00002984 CombineTo(LN0, Load, Load.getValue(1));
2985 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00002986 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00002987 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00002988 }
2989 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002990
Evan Chenge6a3b032012-07-17 18:54:11 +00002991 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2992 VT.getSizeInBits() <= 64) {
2993 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2994 APInt ADDC = ADDI->getAPIntValue();
2995 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2996 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2997 // immediate for an add, but it is legal if its top c2 bits are set,
2998 // transform the ADD so the immediate doesn't need to be materialized
2999 // in a register.
3000 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3001 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3002 SRLI->getZExtValue());
3003 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3004 ADDC |= Mask;
3005 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3006 SDValue NewAdd =
Andrew Trickef9de2a2013-05-25 02:42:55 +00003007 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenge6a3b032012-07-17 18:54:11 +00003008 N0.getOperand(0), DAG.getConstant(ADDC, VT));
3009 CombineTo(N0.getNode(), NewAdd);
3010 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3011 }
3012 }
3013 }
3014 }
3015 }
3016 }
Evan Chenge6a3b032012-07-17 18:54:11 +00003017
Tim Northover819bfb52013-08-27 13:46:45 +00003018 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3019 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3020 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3021 N0.getOperand(1), false);
3022 if (BSwap.getNode())
3023 return BSwap;
3024 }
3025
Evan Chengf1005572010-04-28 07:10:39 +00003026 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003027}
3028
Evan Cheng4c0bd962011-06-21 06:01:08 +00003029/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
3030///
3031SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3032 bool DemandHighBits) {
3033 if (!LegalOperations)
3034 return SDValue();
3035
3036 EVT VT = N->getValueType(0);
3037 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3038 return SDValue();
3039 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3040 return SDValue();
3041
3042 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3043 bool LookPassAnd0 = false;
3044 bool LookPassAnd1 = false;
3045 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3046 std::swap(N0, N1);
3047 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3048 std::swap(N0, N1);
3049 if (N0.getOpcode() == ISD::AND) {
3050 if (!N0.getNode()->hasOneUse())
3051 return SDValue();
3052 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3053 if (!N01C || N01C->getZExtValue() != 0xFF00)
3054 return SDValue();
3055 N0 = N0.getOperand(0);
3056 LookPassAnd0 = true;
3057 }
3058
3059 if (N1.getOpcode() == ISD::AND) {
3060 if (!N1.getNode()->hasOneUse())
3061 return SDValue();
3062 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3063 if (!N11C || N11C->getZExtValue() != 0xFF)
3064 return SDValue();
3065 N1 = N1.getOperand(0);
3066 LookPassAnd1 = true;
3067 }
3068
3069 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3070 std::swap(N0, N1);
3071 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3072 return SDValue();
3073 if (!N0.getNode()->hasOneUse() ||
3074 !N1.getNode()->hasOneUse())
3075 return SDValue();
3076
3077 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3078 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3079 if (!N01C || !N11C)
3080 return SDValue();
3081 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3082 return SDValue();
3083
3084 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3085 SDValue N00 = N0->getOperand(0);
3086 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3087 if (!N00.getNode()->hasOneUse())
3088 return SDValue();
3089 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3090 if (!N001C || N001C->getZExtValue() != 0xFF)
3091 return SDValue();
3092 N00 = N00.getOperand(0);
3093 LookPassAnd0 = true;
3094 }
3095
3096 SDValue N10 = N1->getOperand(0);
3097 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3098 if (!N10.getNode()->hasOneUse())
3099 return SDValue();
3100 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3101 if (!N101C || N101C->getZExtValue() != 0xFF00)
3102 return SDValue();
3103 N10 = N10.getOperand(0);
3104 LookPassAnd1 = true;
3105 }
3106
3107 if (N00 != N10)
3108 return SDValue();
3109
Tim Northover819bfb52013-08-27 13:46:45 +00003110 // Make sure everything beyond the low halfword gets set to zero since the SRL
3111 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003112 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003113 if (DemandHighBits && OpSizeInBits > 16) {
3114 // If the left-shift isn't masked out then the only way this is a bswap is
3115 // if all bits beyond the low 8 are 0. In that case the entire pattern
3116 // reduces to a left shift anyway: leave it for other parts of the combiner.
3117 if (!LookPassAnd0)
3118 return SDValue();
3119
3120 // However, if the right shift isn't masked out then it might be because
3121 // it's not needed. See if we can spot that too.
3122 if (!LookPassAnd1 &&
3123 !DAG.MaskedValueIsZero(
3124 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3125 return SDValue();
3126 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003127
Andrew Trickef9de2a2013-05-25 02:42:55 +00003128 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003129 if (OpSizeInBits > 16)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003130 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003131 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3132 return Res;
3133}
3134
3135/// isBSwapHWordElement - Return true if the specified node is an element
3136/// that makes up a 32-bit packed halfword byteswap. i.e.
3137/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
Craig Topperb94011f2013-07-14 04:42:23 +00003138static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003139 if (!N.getNode()->hasOneUse())
3140 return false;
3141
3142 unsigned Opc = N.getOpcode();
3143 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3144 return false;
3145
3146 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3147 if (!N1C)
3148 return false;
3149
3150 unsigned Num;
3151 switch (N1C->getZExtValue()) {
3152 default:
3153 return false;
3154 case 0xFF: Num = 0; break;
3155 case 0xFF00: Num = 1; break;
3156 case 0xFF0000: Num = 2; break;
3157 case 0xFF000000: Num = 3; break;
3158 }
3159
3160 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3161 SDValue N0 = N.getOperand(0);
3162 if (Opc == ISD::AND) {
3163 if (Num == 0 || Num == 2) {
3164 // (x >> 8) & 0xff
3165 // (x >> 8) & 0xff0000
3166 if (N0.getOpcode() != ISD::SRL)
3167 return false;
3168 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3169 if (!C || C->getZExtValue() != 8)
3170 return false;
3171 } else {
3172 // (x << 8) & 0xff00
3173 // (x << 8) & 0xff000000
3174 if (N0.getOpcode() != ISD::SHL)
3175 return false;
3176 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3177 if (!C || C->getZExtValue() != 8)
3178 return false;
3179 }
3180 } else if (Opc == ISD::SHL) {
3181 // (x & 0xff) << 8
3182 // (x & 0xff0000) << 8
3183 if (Num != 0 && Num != 2)
3184 return false;
3185 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3186 if (!C || C->getZExtValue() != 8)
3187 return false;
3188 } else { // Opc == ISD::SRL
3189 // (x & 0xff00) >> 8
3190 // (x & 0xff000000) >> 8
3191 if (Num != 1 && Num != 3)
3192 return false;
3193 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3194 if (!C || C->getZExtValue() != 8)
3195 return false;
3196 }
3197
3198 if (Parts[Num])
3199 return false;
3200
3201 Parts[Num] = N0.getOperand(0).getNode();
3202 return true;
3203}
3204
3205/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3206/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3207/// => (rotl (bswap x), 16)
3208SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3209 if (!LegalOperations)
3210 return SDValue();
3211
3212 EVT VT = N->getValueType(0);
3213 if (VT != MVT::i32)
3214 return SDValue();
3215 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3216 return SDValue();
3217
Craig Topperc0196b12014-04-14 00:51:57 +00003218 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003219 // Look for either
3220 // (or (or (and), (and)), (or (and), (and)))
3221 // (or (or (or (and), (and)), (and)), (and))
3222 if (N0.getOpcode() != ISD::OR)
3223 return SDValue();
3224 SDValue N00 = N0.getOperand(0);
3225 SDValue N01 = N0.getOperand(1);
3226
Evan Chengbf0baa92012-12-13 01:34:32 +00003227 if (N1.getOpcode() == ISD::OR &&
3228 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003229 // (or (or (and), (and)), (or (and), (and)))
3230 SDValue N000 = N00.getOperand(0);
3231 if (!isBSwapHWordElement(N000, Parts))
3232 return SDValue();
3233
3234 SDValue N001 = N00.getOperand(1);
3235 if (!isBSwapHWordElement(N001, Parts))
3236 return SDValue();
3237 SDValue N010 = N01.getOperand(0);
3238 if (!isBSwapHWordElement(N010, Parts))
3239 return SDValue();
3240 SDValue N011 = N01.getOperand(1);
3241 if (!isBSwapHWordElement(N011, Parts))
3242 return SDValue();
3243 } else {
3244 // (or (or (or (and), (and)), (and)), (and))
3245 if (!isBSwapHWordElement(N1, Parts))
3246 return SDValue();
3247 if (!isBSwapHWordElement(N01, Parts))
3248 return SDValue();
3249 if (N00.getOpcode() != ISD::OR)
3250 return SDValue();
3251 SDValue N000 = N00.getOperand(0);
3252 if (!isBSwapHWordElement(N000, Parts))
3253 return SDValue();
3254 SDValue N001 = N00.getOperand(1);
3255 if (!isBSwapHWordElement(N001, Parts))
3256 return SDValue();
3257 }
3258
3259 // Make sure the parts are all coming from the same node.
3260 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3261 return SDValue();
3262
Andrew Trickef9de2a2013-05-25 02:42:55 +00003263 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003264 SDValue(Parts[0],0));
3265
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003266 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003267 // do (x << 16) | (x >> 16).
3268 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3269 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003270 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003271 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003272 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3273 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3274 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3275 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003276}
3277
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003278SDValue DAGCombiner::visitOR(SDNode *N) {
3279 SDValue N0 = N->getOperand(0);
3280 SDValue N1 = N->getOperand(1);
3281 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003282 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3283 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003284 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003285
Dan Gohmana8665142007-06-25 16:23:39 +00003286 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003287 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003288 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003289 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003290
3291 // fold (or x, 0) -> x, vector edition
3292 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3293 return N1;
3294 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3295 return N0;
3296
3297 // fold (or x, -1) -> -1, vector edition
3298 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3299 return N0;
3300 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3301 return N1;
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003302
3303 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3304 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3305 // Do this only if the resulting shuffle is legal.
3306 if (isa<ShuffleVectorSDNode>(N0) &&
3307 isa<ShuffleVectorSDNode>(N1) &&
Andrea Di Biagio2152a6c2014-07-15 00:02:32 +00003308 // Avoid folding a node with illegal type.
3309 TLI.isTypeLegal(VT) &&
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003310 N0->getOperand(1) == N1->getOperand(1) &&
3311 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3312 bool CanFold = true;
3313 unsigned NumElts = VT.getVectorNumElements();
3314 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3315 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3316 // We construct two shuffle masks:
3317 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3318 // and N1 as the second operand.
3319 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3320 // and N0 as the second operand.
3321 // We do this because OR is commutable and therefore there might be
3322 // two ways to fold this node into a shuffle.
3323 SmallVector<int,4> Mask1;
3324 SmallVector<int,4> Mask2;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003325
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003326 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3327 int M0 = SV0->getMaskElt(i);
3328 int M1 = SV1->getMaskElt(i);
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003329
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003330 // Both shuffle indexes are undef. Propagate Undef.
3331 if (M0 < 0 && M1 < 0) {
3332 Mask1.push_back(M0);
3333 Mask2.push_back(M0);
3334 continue;
3335 }
3336
3337 if (M0 < 0 || M1 < 0 ||
3338 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3339 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3340 CanFold = false;
3341 break;
3342 }
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003343
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003344 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3345 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3346 }
3347
3348 if (CanFold) {
3349 // Fold this sequence only if the resulting shuffle is 'legal'.
3350 if (TLI.isShuffleMaskLegal(Mask1, VT))
3351 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3352 N1->getOperand(0), &Mask1[0]);
3353 if (TLI.isShuffleMaskLegal(Mask2, VT))
3354 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3355 N0->getOperand(0), &Mask2[0]);
3356 }
3357 }
Dan Gohman80f9f072007-07-13 20:03:40 +00003358 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003359
Dan Gohman06563a82007-07-03 14:03:57 +00003360 // fold (or x, undef) -> -1
Bob Wilson269a89f2010-06-28 23:40:25 +00003361 if (!LegalOperations &&
3362 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman9655f842009-12-03 07:11:29 +00003363 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3364 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3365 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003366 // fold (or c1, c2) -> c1|c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003367 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003368 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003369 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003370 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003371 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003372 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003373 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003374 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003375 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003376 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003377 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003378 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003379 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003380 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003381
3382 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3383 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003384 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003385 return BSwap;
3386 BSwap = MatchBSwapHWordLow(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003387 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003388 return BSwap;
3389
Nate Begeman22e251a2006-02-03 06:46:56 +00003390 // reassociate or
Andrew Trickef9de2a2013-05-25 02:42:55 +00003391 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003392 if (ROR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003393 return ROR;
3394 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003395 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003396 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003397 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003398 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003399 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3400 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3401 if (!COR.getNode())
3402 return SDValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00003403 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3404 DAG.getNode(ISD::OR, SDLoc(N0), VT,
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003405 N0.getOperand(0), N1), COR);
3406 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003407 }
Nate Begeman049b7482005-09-09 19:49:52 +00003408 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3409 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3410 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3411 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003412
Nate Begeman049b7482005-09-09 19:49:52 +00003413 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00003414 LL.getValueType().isInteger()) {
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003415 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3416 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003417 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003418 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003419 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003420 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003421 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003422 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003423 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003424 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3425 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003426 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003427 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003428 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003429 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003430 AddToWorklist(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003431 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003432 }
3433 }
3434 // canonicalize equivalent to ll == rl
3435 if (LL == RR && LR == RL) {
3436 Op1 = ISD::getSetCCSwappedOperands(Op1);
3437 std::swap(RL, RR);
3438 }
3439 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003440 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00003441 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00003442 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003443 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00003444 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3445 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00003446 getSetCCResultType(N0.getValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003447 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003448 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00003449 }
3450 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003451
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003452 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003453 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003454 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003455 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003456 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003457
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003458 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner46d710e2006-09-14 21:11:37 +00003459 if (N0.getOpcode() == ISD::AND &&
3460 N1.getOpcode() == ISD::AND &&
3461 N0.getOperand(1).getOpcode() == ISD::Constant &&
3462 N1.getOperand(1).getOpcode() == ISD::Constant &&
3463 // Don't increase # computations.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003464 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner46d710e2006-09-14 21:11:37 +00003465 // We can only do this xform if we know that bits from X that are set in C2
3466 // but not in C1 are already zero. Likewise for Y.
Dan Gohman1f372ed2008-02-25 21:11:39 +00003467 const APInt &LHSMask =
3468 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3469 const APInt &RHSMask =
3470 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003471
Dan Gohman309d3d52007-06-22 14:59:07 +00003472 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3473 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003474 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003475 N0.getOperand(0), N1.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003476 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003477 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner46d710e2006-09-14 21:11:37 +00003478 }
3479 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003480
Chris Lattner97614c82006-09-14 20:50:57 +00003481 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003482 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003483 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003484
Dan Gohman600f62b2010-06-24 14:30:44 +00003485 // Simplify the operands using demanded-bits information.
3486 if (!VT.isVector() &&
3487 SimplifyDemandedBits(SDValue(N, 0)))
3488 return SDValue(N, 0);
3489
Evan Chengf1005572010-04-28 07:10:39 +00003490 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003491}
3492
Chris Lattner97614c82006-09-14 20:50:57 +00003493/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003494static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003495 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003496 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003497 Mask = Op.getOperand(1);
3498 Op = Op.getOperand(0);
3499 } else {
3500 return false;
3501 }
3502 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003503
Chris Lattner97614c82006-09-14 20:50:57 +00003504 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3505 Shift = Op;
3506 return true;
3507 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003508
Scott Michelcf0da6c2009-02-17 22:15:04 +00003509 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003510}
3511
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003512// Return true if we can prove that, whenever Neg and Pos are both in the
3513// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003514// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3515//
3516// (or (shift1 X, Neg), (shift2 X, Pos))
3517//
Adam Nemetc6553a82014-03-07 23:56:24 +00003518// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3519// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3520// to consider shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003521static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003522 // If OpSize is a power of 2 then:
3523 //
3524 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3525 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3526 //
3527 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3528 // for the stronger condition:
3529 //
3530 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3531 //
3532 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3533 // we can just replace Neg with Neg' for the rest of the function.
3534 //
3535 // In other cases we check for the even stronger condition:
3536 //
3537 // Neg == OpSize - Pos [B]
3538 //
3539 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3540 // behavior if Pos == 0 (and consequently Neg == OpSize).
Adam Nemetc6553a82014-03-07 23:56:24 +00003541 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003542 // We could actually use [A] whenever OpSize is a power of 2, but the
3543 // only extra cases that it would match are those uninteresting ones
3544 // where Neg and Pos are never in range at the same time. E.g. for
3545 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3546 // as well as (sub 32, Pos), but:
3547 //
3548 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3549 //
3550 // always invokes undefined behavior for 32-bit X.
3551 //
3552 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
Adam Nemetc6553a82014-03-07 23:56:24 +00003553 unsigned MaskLoBits = 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003554 if (Neg.getOpcode() == ISD::AND &&
3555 isPowerOf2_64(OpSize) &&
3556 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3557 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3558 Neg = Neg.getOperand(0);
Adam Nemetc6553a82014-03-07 23:56:24 +00003559 MaskLoBits = Log2_64(OpSize);
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003560 }
3561
Richard Sandiford0f264db2014-01-09 10:49:40 +00003562 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3563 if (Neg.getOpcode() != ISD::SUB)
3564 return 0;
3565 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3566 if (!NegC)
3567 return 0;
3568 SDValue NegOp1 = Neg.getOperand(1);
3569
Adam Nemet5117f5d2014-03-07 23:56:28 +00003570 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3571 // Pos'. The truncation is redundant for the purpose of the equality.
3572 if (MaskLoBits &&
3573 Pos.getOpcode() == ISD::AND &&
3574 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3575 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3576 Pos = Pos.getOperand(0);
3577
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003578 // The condition we need is now:
3579 //
3580 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3581 //
3582 // If NegOp1 == Pos then we need:
3583 //
3584 // OpSize & Mask == NegC & Mask
3585 //
3586 // (because "x & Mask" is a truncation and distributes through subtraction).
3587 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003588 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003589 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003590 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3591 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003592 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003593 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3594 //
3595 // which, again because "x & Mask" is a truncation, becomes:
3596 //
3597 // NegC & Mask == (OpSize - PosC) & Mask
3598 // OpSize & Mask == (NegC + PosC) & Mask
3599 else if (Pos.getOpcode() == ISD::ADD &&
3600 Pos.getOperand(0) == NegOp1 &&
3601 Pos.getOperand(1).getOpcode() == ISD::Constant)
3602 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3603 NegC->getAPIntValue());
3604 else
3605 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003606
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003607 // Now we just need to check that OpSize & Mask == Width & Mask.
Adam Nemetc6553a82014-03-07 23:56:24 +00003608 if (MaskLoBits)
3609 // Opsize & Mask is 0 since Mask is Opsize - 1.
3610 return Width.getLoBits(MaskLoBits) == 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003611 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003612}
3613
Richard Sandiford95c864d2014-01-08 15:40:47 +00003614// A subroutine of MatchRotate used once we have found an OR of two opposite
3615// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3616// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3617// former being preferred if supported. InnerPos and InnerNeg are Pos and
3618// Neg with outer conversions stripped away.
3619SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3620 SDValue Neg, SDValue InnerPos,
3621 SDValue InnerNeg, unsigned PosOpcode,
3622 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003623 // fold (or (shl x, (*ext y)),
3624 // (srl x, (*ext (sub 32, y)))) ->
3625 // (rotl x, y) or (rotr x, (sub 32, y))
3626 //
3627 // fold (or (shl x, (*ext (sub 32, y))),
3628 // (srl x, (*ext y))) ->
3629 // (rotr x, y) or (rotl x, (sub 32, y))
3630 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003631 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003632 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3633 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3634 HasPos ? Pos : Neg).getNode();
3635 }
3636
Craig Topperc0196b12014-04-14 00:51:57 +00003637 return nullptr;
Richard Sandiford95c864d2014-01-08 15:40:47 +00003638}
3639
Chris Lattner97614c82006-09-14 20:50:57 +00003640// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3641// idioms for rotate, and if the target supports rotation instructions, generate
3642// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003643SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003644 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003645 EVT VT = LHS.getValueType();
Craig Topperc0196b12014-04-14 00:51:57 +00003646 if (!TLI.isTypeLegal(VT)) return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003647
3648 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003649 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3650 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Craig Topperc0196b12014-04-14 00:51:57 +00003651 if (!HasROTL && !HasROTR) return nullptr;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003652
Chris Lattner97614c82006-09-14 20:50:57 +00003653 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003654 SDValue LHSShift; // The shift.
3655 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003656 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003657 return nullptr; // Not part of a rotate.
Chris Lattner97614c82006-09-14 20:50:57 +00003658
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003659 SDValue RHSShift; // The shift.
3660 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003661 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003662 return nullptr; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003663
Chris Lattner97614c82006-09-14 20:50:57 +00003664 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
Craig Topperc0196b12014-04-14 00:51:57 +00003665 return nullptr; // Not shifting the same value.
Chris Lattner97614c82006-09-14 20:50:57 +00003666
3667 if (LHSShift.getOpcode() == RHSShift.getOpcode())
Craig Topperc0196b12014-04-14 00:51:57 +00003668 return nullptr; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003669
Chris Lattner97614c82006-09-14 20:50:57 +00003670 // Canonicalize shl to left side in a shl/srl pair.
3671 if (RHSShift.getOpcode() == ISD::SHL) {
3672 std::swap(LHS, RHS);
3673 std::swap(LHSShift, RHSShift);
3674 std::swap(LHSMask , RHSMask );
3675 }
3676
Duncan Sands13237ac2008-06-06 12:08:01 +00003677 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003678 SDValue LHSShiftArg = LHSShift.getOperand(0);
3679 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003680 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003681 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003682
3683 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3684 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003685 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3686 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003687 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3688 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003689 if ((LShVal + RShVal) != OpSizeInBits)
Craig Topperc0196b12014-04-14 00:51:57 +00003690 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003691
Craig Topper65161fa2012-09-29 06:54:22 +00003692 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3693 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003694
Chris Lattner97614c82006-09-14 20:50:57 +00003695 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003696 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003697 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003698
Gabor Greiff304a7a2008-08-28 21:40:38 +00003699 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003700 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3701 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003702 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003703 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003704 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3705 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003706 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003707
Bill Wendling35972a92009-01-30 21:14:50 +00003708 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003709 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003710
Gabor Greiff304a7a2008-08-28 21:40:38 +00003711 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003712 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003713
Chris Lattner97614c82006-09-14 20:50:57 +00003714 // If there is a mask here, and we have a variable shift, we can't be sure
3715 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003716 if (LHSMask.getNode() || RHSMask.getNode())
Craig Topperc0196b12014-04-14 00:51:57 +00003717 return nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003718
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003719 // If the shift amount is sign/zext/any-extended just peel it off.
3720 SDValue LExtOp0 = LHSShiftAmt;
3721 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003722 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3723 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3724 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3725 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3726 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3727 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3728 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3729 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003730 LExtOp0 = LHSShiftAmt.getOperand(0);
3731 RExtOp0 = RHSShiftAmt.getOperand(0);
3732 }
3733
Richard Sandiford95c864d2014-01-08 15:40:47 +00003734 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3735 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3736 if (TryL)
3737 return TryL;
3738
3739 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3740 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3741 if (TryR)
3742 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003743
Craig Topperc0196b12014-04-14 00:51:57 +00003744 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003745}
3746
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003747SDValue DAGCombiner::visitXOR(SDNode *N) {
3748 SDValue N0 = N->getOperand(0);
3749 SDValue N1 = N->getOperand(1);
3750 SDValue LHS, RHS, CC;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003751 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3752 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003753 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003754
Dan Gohmana8665142007-06-25 16:23:39 +00003755 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003756 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003757 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003758 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003759
3760 // fold (xor x, 0) -> x, vector edition
3761 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3762 return N1;
3763 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3764 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003765 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003766
Evan Chengdf1690d2008-03-25 20:08:07 +00003767 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3768 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3769 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003770 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003771 if (N0.getOpcode() == ISD::UNDEF)
3772 return N0;
3773 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003774 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003775 // fold (xor c1, c2) -> c1^c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003776 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003777 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003778 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003779 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003780 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003781 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003782 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003783 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003784 // reassociate xor
Andrew Trickef9de2a2013-05-25 02:42:55 +00003785 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003786 if (RXOR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003787 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003788
Nate Begeman21158fc2005-09-01 00:19:25 +00003789 // fold !(x cc y) -> (x !cc y)
Dan Gohmanb72127a2008-03-13 22:13:53 +00003790 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003791 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003792 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3793 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003794
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003795 if (!LegalOperations ||
3796 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003797 switch (N0.getOpcode()) {
3798 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003799 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003800 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003801 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003802 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003803 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003804 N0.getOperand(3), NotCC);
3805 }
3806 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003807 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003808
Chris Lattner58c227b2007-09-10 21:39:07 +00003809 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003810 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003811 N0.getNode()->hasOneUse() &&
3812 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003813 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003814 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003815 DAG.getConstant(1, V.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003816 AddToWorklist(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003817 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003818 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003819
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003820 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003821 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003822 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003823 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003824 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3825 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003826 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3827 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003828 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003829 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003830 }
3831 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003832 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003833 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003834 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003835 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003836 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3837 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003838 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3839 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003840 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003841 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003842 }
3843 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003844 // fold (xor (and x, y), y) -> (and (not x), y)
3845 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003846 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003847 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003848 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003849 AddToWorklist(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003850 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003851 }
Bill Wendling35972a92009-01-30 21:14:50 +00003852 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003853 if (N1C && N0.getOpcode() == ISD::XOR) {
3854 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3855 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3856 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003857 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003858 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003859 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003860 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003861 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003862 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003863 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003864 }
3865 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003866 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003867 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003868
Chris Lattner8d6fc202006-05-05 05:51:50 +00003869 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3870 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003871 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003872 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003873 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003874
Chris Lattner098c01e2006-04-08 04:15:24 +00003875 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00003876 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003877 SimplifyDemandedBits(SDValue(N, 0)))
3878 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003879
Evan Chengf1005572010-04-28 07:10:39 +00003880 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003881}
3882
Chris Lattner7c709a52007-12-06 07:33:36 +00003883/// visitShiftByConstant - Handle transforms common to the three shifts, when
3884/// the shift amount is a constant.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003885SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003886 // We can't and shouldn't fold opaque constants.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003887 if (Amt->isOpaque())
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003888 return SDValue();
3889
Gabor Greiff304a7a2008-08-28 21:40:38 +00003890 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003891 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003892
Chris Lattner7c709a52007-12-06 07:33:36 +00003893 // We want to pull some binops through shifts, so that we have (and (shift))
3894 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3895 // thing happens with address calculations, so it's important to canonicalize
3896 // it.
3897 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00003898
Chris Lattner7c709a52007-12-06 07:33:36 +00003899 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003900 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003901 case ISD::OR:
3902 case ISD::XOR:
3903 HighBitSet = false; // We can only transform sra if the high bit is clear.
3904 break;
3905 case ISD::AND:
3906 HighBitSet = true; // We can only transform sra if the high bit is set.
3907 break;
3908 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00003909 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003910 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00003911 HighBitSet = false; // We can only transform sra if the high bit is clear.
3912 break;
3913 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003914
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003915 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00003916 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003917 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003918
3919 // FIXME: disable this unless the input to the binop is a shift by a constant.
3920 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00003921 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003922 // void foo(int *X, int i) { X[i & 1235] = 1; }
3923 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003924 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003925 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00003926 BinOpLHSVal->getOpcode() != ISD::SRA &&
3927 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3928 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003929 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003930
Owen Anderson53aa7a92009-08-10 22:56:29 +00003931 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003932
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003933 // If this is a signed shift right, and the high bit is modified by the
3934 // logical operation, do not perform the transformation. The highBitSet
3935 // boolean indicates the value of the high bit of the constant which would
3936 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00003937 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003938 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3939 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003940 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003941 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003942
Weiming Zhao7f6daf12014-04-30 21:07:24 +00003943 if (!TLI.isDesirableToCommuteWithShift(LHS))
3944 return SDValue();
3945
Chris Lattner7c709a52007-12-06 07:33:36 +00003946 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003947 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003948 N->getValueType(0),
3949 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003950 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00003951
3952 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00003953 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00003954 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003955 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00003956
3957 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003958 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00003959}
3960
Adam Nemet67483892014-03-04 23:28:31 +00003961SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3962 assert(N->getOpcode() == ISD::TRUNCATE);
3963 assert(N->getOperand(0).getOpcode() == ISD::AND);
3964
3965 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3966 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3967 SDValue N01 = N->getOperand(0).getOperand(1);
3968
Matt Arsenault985b9de2014-03-17 18:58:01 +00003969 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
Adam Nemet67483892014-03-04 23:28:31 +00003970 EVT TruncVT = N->getValueType(0);
3971 SDValue N00 = N->getOperand(0).getOperand(0);
3972 APInt TruncC = N01C->getAPIntValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003973 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
Adam Nemet67483892014-03-04 23:28:31 +00003974
3975 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3976 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3977 DAG.getConstant(TruncC, TruncVT));
3978 }
3979 }
3980
3981 return SDValue();
3982}
Adam Nemet7f928f12014-03-07 23:56:30 +00003983
3984SDValue DAGCombiner::visitRotate(SDNode *N) {
3985 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3986 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3987 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3988 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3989 if (NewOp1.getNode())
3990 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3991 N->getOperand(0), NewOp1);
3992 }
3993 return SDValue();
3994}
3995
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003996SDValue DAGCombiner::visitSHL(SDNode *N) {
3997 SDValue N0 = N->getOperand(0);
3998 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003999 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4000 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004001 EVT VT = N0.getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004002 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004003
Daniel Sandersa1840d22013-11-11 17:23:41 +00004004 // fold vector ops
4005 if (VT.isVector()) {
4006 SDValue FoldedVOp = SimplifyVBinOp(N);
4007 if (FoldedVOp.getNode()) return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00004008
4009 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4010 // If setcc produces all-one true value then:
4011 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004012 if (N1CV && N1CV->isConstant()) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004013 if (N0.getOpcode() == ISD::AND) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004014 SDValue N00 = N0->getOperand(0);
4015 SDValue N01 = N0->getOperand(1);
4016 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004017
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004018 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4019 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4020 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004021 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4022 if (C.getNode())
4023 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4024 }
4025 } else {
4026 N1C = isConstOrConstSplat(N1);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004027 }
4028 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00004029 }
4030
Nate Begeman21158fc2005-09-01 00:19:25 +00004031 // fold (shl c1, c2) -> c1<<c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004032 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004033 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004034 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004035 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004036 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004037 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004038 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004039 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004040 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004041 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004042 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00004043 // fold (shl undef, x) -> 0
4044 if (N0.getOpcode() == ISD::UNDEF)
4045 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004046 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004047 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00004048 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004049 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00004050 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004051 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004052 N1.getOperand(0).getOpcode() == ISD::AND) {
4053 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4054 if (NewOp1.getNode())
4055 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004056 }
4057
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004058 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4059 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004060
4061 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004062 if (N1C && N0.getOpcode() == ISD::SHL) {
4063 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4064 uint64_t c1 = N0C1->getZExtValue();
4065 uint64_t c2 = N1C->getZExtValue();
4066 if (c1 + c2 >= OpSizeInBits)
4067 return DAG.getConstant(0, VT);
4068 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4069 DAG.getConstant(c1 + c2, N1.getValueType()));
4070 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004071 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004072
4073 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4074 // For this to be valid, the second form must not preserve any of the bits
4075 // that are shifted out by the inner shift in the first form. This means
4076 // the outer shift size must be >= the number of bits added by the ext.
4077 // As a corollary, we don't care what kind of ext it is.
4078 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4079 N0.getOpcode() == ISD::ANY_EXTEND ||
4080 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004081 N0.getOperand(0).getOpcode() == ISD::SHL) {
4082 SDValue N0Op0 = N0.getOperand(0);
4083 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4084 uint64_t c1 = N0Op0C1->getZExtValue();
4085 uint64_t c2 = N1C->getZExtValue();
4086 EVT InnerShiftVT = N0Op0.getValueType();
4087 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4088 if (c2 >= OpSizeInBits - InnerShiftSize) {
4089 if (c1 + c2 >= OpSizeInBits)
4090 return DAG.getConstant(0, VT);
4091 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4092 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4093 N0Op0->getOperand(0)),
4094 DAG.getConstant(c1 + c2, N1.getValueType()));
4095 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004096 }
4097 }
4098
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004099 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4100 // Only fold this if the inner zext has no other uses to avoid increasing
4101 // the total number of instructions.
4102 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004103 N0.getOperand(0).getOpcode() == ISD::SRL) {
4104 SDValue N0Op0 = N0.getOperand(0);
4105 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4106 uint64_t c1 = N0Op0C1->getZExtValue();
4107 if (c1 < VT.getScalarSizeInBits()) {
4108 uint64_t c2 = N1C->getZExtValue();
4109 if (c1 == c2) {
4110 SDValue NewOp0 = N0.getOperand(0);
4111 EVT CountVT = NewOp0.getOperand(1).getValueType();
4112 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4113 NewOp0, DAG.getConstant(c2, CountVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004114 AddToWorklist(NewSHL.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004115 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4116 }
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004117 }
4118 }
4119 }
4120
Eli Friedman1877ac92011-06-09 22:14:44 +00004121 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4122 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00004123 // Only fold this if the inner shift has no other uses -- if it does, folding
4124 // this will increase the total number of instructions.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004125 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4126 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4127 uint64_t c1 = N0C1->getZExtValue();
4128 if (c1 < OpSizeInBits) {
4129 uint64_t c2 = N1C->getZExtValue();
4130 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4131 SDValue Shift;
4132 if (c2 > c1) {
4133 Mask = Mask.shl(c2 - c1);
4134 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4135 DAG.getConstant(c2 - c1, N1.getValueType()));
4136 } else {
4137 Mask = Mask.lshr(c1 - c2);
4138 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4139 DAG.getConstant(c1 - c2, N1.getValueType()));
4140 }
4141 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4142 DAG.getConstant(Mask, VT));
Eli Friedman1877ac92011-06-09 22:14:44 +00004143 }
Evan Chenga7bb55e2009-07-21 05:40:15 +00004144 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004145 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004146 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00004147 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004148 unsigned BitSize = VT.getScalarSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004149 SDValue HiBitsMask =
Matt Arsenault985b9de2014-03-17 18:58:01 +00004150 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4151 BitSize - N1C->getZExtValue()), VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004152 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004153 HiBitsMask);
4154 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004155
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004156 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004157 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004158 if (NewSHL.getNode())
4159 return NewSHL;
4160 }
4161
Evan Chengf1005572010-04-28 07:10:39 +00004162 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004163}
4164
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004165SDValue DAGCombiner::visitSRA(SDNode *N) {
4166 SDValue N0 = N->getOperand(0);
4167 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004168 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4169 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004170 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004171 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004172
Daniel Sandersa1840d22013-11-11 17:23:41 +00004173 // fold vector ops
4174 if (VT.isVector()) {
4175 SDValue FoldedVOp = SimplifyVBinOp(N);
4176 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004177
4178 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004179 }
4180
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004181 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004182 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004183 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004184 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004185 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004186 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004187 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004188 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004189 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004190 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004191 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004192 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004193 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004194 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004195 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004196 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4197 // sext_inreg.
4198 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004199 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004200 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4201 if (VT.isVector())
4202 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4203 ExtVT, VT.getVectorNumElements());
4204 if ((!LegalOperations ||
4205 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004206 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004207 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004208 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004209
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004210 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004211 if (N1C && N0.getOpcode() == ISD::SRA) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004212 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004213 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004214 if (Sum >= OpSizeInBits)
4215 Sum = OpSizeInBits - 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004216 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Matt Arsenault985b9de2014-03-17 18:58:01 +00004217 DAG.getConstant(Sum, N1.getValueType()));
Chris Lattner0f8a7272006-02-28 06:23:04 +00004218 }
4219 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004220
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004221 // fold (sra (shl X, m), (sub result_size, n))
4222 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004223 // result_size - n != m.
4224 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004225 // code.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004226 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb8fe91092008-03-19 08:30:06 +00004227 // Get the two constanst of the shifts, CN0 = m, CN = n.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004228 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4229 if (N01C) {
4230 LLVMContext &Ctx = *DAG.getContext();
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004231 // Determine what the truncate's result bitsize and type would be.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004232 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4233
4234 if (VT.isVector())
4235 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4236
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004237 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004238 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004239
Scott Michelcf0da6c2009-02-17 22:15:04 +00004240 // If the shift is not a no-op (in which case this should be just a sign
4241 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004242 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004243 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004244 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004245 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4246 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004247 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004248
Owen Andersonb2c80da2011-02-25 21:41:48 +00004249 SDValue Amt = DAG.getConstant(ShiftAmt,
4250 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004251 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004252 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004253 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004254 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004255 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004256 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004257 }
4258 }
4259 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004260
Duncan Sands3ed76882009-02-01 18:06:53 +00004261 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004262 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004263 N1.getOperand(0).getOpcode() == ISD::AND) {
4264 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4265 if (NewOp1.getNode())
4266 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004267 }
4268
Matt Arsenault985b9de2014-03-17 18:58:01 +00004269 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer946e1522011-01-30 16:38:43 +00004270 // if c1 is equal to the number of bits the trunc removes
4271 if (N0.getOpcode() == ISD::TRUNCATE &&
4272 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4273 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4274 N0.getOperand(0).hasOneUse() &&
4275 N0.getOperand(0).getOperand(1).hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004276 N1C) {
4277 SDValue N0Op0 = N0.getOperand(0);
4278 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4279 unsigned LargeShiftVal = LargeShift->getZExtValue();
4280 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer946e1522011-01-30 16:38:43 +00004281
Matt Arsenault985b9de2014-03-17 18:58:01 +00004282 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4283 SDValue Amt =
4284 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4285 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4286 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4287 N0Op0.getOperand(0), Amt);
4288 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4289 }
Benjamin Kramer946e1522011-01-30 16:38:43 +00004290 }
4291 }
4292
Scott Michelcf0da6c2009-02-17 22:15:04 +00004293 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004294 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4295 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004296
4297
Nate Begeman21158fc2005-09-01 00:19:25 +00004298 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004299 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004300 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004301
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004302 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004303 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004304 if (NewSRA.getNode())
4305 return NewSRA;
4306 }
4307
Evan Chengf1005572010-04-28 07:10:39 +00004308 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004309}
4310
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004311SDValue DAGCombiner::visitSRL(SDNode *N) {
4312 SDValue N0 = N->getOperand(0);
4313 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004314 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4315 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004316 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004317 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004318
Daniel Sandersa1840d22013-11-11 17:23:41 +00004319 // fold vector ops
4320 if (VT.isVector()) {
4321 SDValue FoldedVOp = SimplifyVBinOp(N);
4322 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004323
4324 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004325 }
4326
Nate Begeman21158fc2005-09-01 00:19:25 +00004327 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004328 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004329 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004330 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004331 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004332 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004333 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004334 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004335 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004336 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004337 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004338 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004339 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004340 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004341 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004342 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004343
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004344 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004345 if (N1C && N0.getOpcode() == ISD::SRL) {
4346 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4347 uint64_t c1 = N01C->getZExtValue();
4348 uint64_t c2 = N1C->getZExtValue();
4349 if (c1 + c2 >= OpSizeInBits)
4350 return DAG.getConstant(0, VT);
4351 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4352 DAG.getConstant(c1 + c2, N1.getValueType()));
4353 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004354 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004355
Dale Johannesencd538af2010-12-17 21:45:49 +00004356 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004357 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4358 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004359 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004360 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004361 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4362 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004363 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4364 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004365 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004366 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004367 if (c1 + OpSizeInBits == InnerShiftSize) {
4368 if (c1 + c2 >= InnerShiftSize)
4369 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004370 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4371 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004372 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004373 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004374 }
4375 }
4376
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004377 // fold (srl (shl x, c), c) -> (and x, cst2)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004378 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4379 unsigned BitSize = N0.getScalarValueSizeInBits();
4380 if (BitSize <= 64) {
4381 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4382 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4383 DAG.getConstant(~0ULL >> ShAmt, VT));
4384 }
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004385 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004386
Michael Liao62ebfd82013-06-21 18:45:27 +00004387 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004388 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4389 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004390 EVT SmallVT = N0.getOperand(0).getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004391 unsigned BitSize = SmallVT.getScalarSizeInBits();
4392 if (N1C->getZExtValue() >= BitSize)
Dale Johannesen84935752009-02-06 23:05:02 +00004393 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004394
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004395 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004396 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004397 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004398 N0.getOperand(0),
4399 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004400 AddToWorklist(SmallShift.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004401 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Michael Liao62ebfd82013-06-21 18:45:27 +00004402 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4403 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4404 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004405 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004406 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004407
Chris Lattner2e33fb42006-10-12 20:23:19 +00004408 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4409 // bit, which is unmodified by sra.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004410 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004411 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004412 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004413 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004414
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004415 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004416 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004417 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004418 APInt KnownZero, KnownOne;
Jay Foada0653a32014-05-14 21:14:37 +00004419 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004420
Chris Lattner49932492006-04-02 06:11:11 +00004421 // If any of the input bits are KnownOne, then the input couldn't be all
4422 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004423 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004424
Chris Lattner49932492006-04-02 06:11:11 +00004425 // If all of the bits input the to ctlz node are known to be zero, then
4426 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004427 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004428 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004429
Chris Lattner49932492006-04-02 06:11:11 +00004430 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004431 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004432 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004433 // could be set on input to the CTLZ node. If this bit is set, the SRL
4434 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4435 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004436 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004437 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004438
Chris Lattner49932492006-04-02 06:11:11 +00004439 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004440 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004441 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004442 AddToWorklist(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004443 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004444
Andrew Trickef9de2a2013-05-25 02:42:55 +00004445 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004446 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004447 }
4448 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004449
Duncan Sands3ed76882009-02-01 18:06:53 +00004450 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004451 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004452 N1.getOperand(0).getOpcode() == ISD::AND) {
4453 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4454 if (NewOp1.getNode())
4455 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004456 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004457
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004458 // fold operands of srl based on knowledge that the low bits are not
4459 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004460 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4461 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004462
Evan Chengb175de62009-12-18 21:31:31 +00004463 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004464 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Chengb175de62009-12-18 21:31:31 +00004465 if (NewSRL.getNode())
4466 return NewSRL;
4467 }
4468
Dan Gohman600f62b2010-06-24 14:30:44 +00004469 // Attempt to convert a srl of a load into a narrower zero-extending load.
4470 SDValue NarrowLoad = ReduceLoadWidth(N);
4471 if (NarrowLoad.getNode())
4472 return NarrowLoad;
4473
Evan Chengb175de62009-12-18 21:31:31 +00004474 // Here is a common situation. We want to optimize:
4475 //
4476 // %a = ...
4477 // %b = and i32 %a, 2
4478 // %c = srl i32 %b, 1
4479 // brcond i32 %c ...
4480 //
4481 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004482 //
Evan Chengb175de62009-12-18 21:31:31 +00004483 // %a = ...
4484 // %b = and %a, 2
4485 // %c = setcc eq %b, 0
4486 // brcond %c ...
4487 //
4488 // However when after the source operand of SRL is optimized into AND, the SRL
4489 // itself may not be optimized further. Look for it and add the BRCOND into
4490 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004491 if (N->hasOneUse()) {
4492 SDNode *Use = *N->use_begin();
4493 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004494 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004495 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4496 // Also look pass the truncate.
4497 Use = *Use->use_begin();
4498 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004499 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004500 }
4501 }
Evan Chengb175de62009-12-18 21:31:31 +00004502
Evan Chengf1005572010-04-28 07:10:39 +00004503 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004504}
4505
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004506SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4507 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004508 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004509
4510 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004511 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004512 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004513 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004514}
4515
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004516SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4517 SDValue N0 = N->getOperand(0);
4518 EVT VT = N->getValueType(0);
4519
4520 // fold (ctlz_zero_undef c1) -> c2
4521 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004522 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004523 return SDValue();
4524}
4525
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004526SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4527 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004528 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004529
Nate Begeman21158fc2005-09-01 00:19:25 +00004530 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004531 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004532 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004533 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004534}
4535
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004536SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4537 SDValue N0 = N->getOperand(0);
4538 EVT VT = N->getValueType(0);
4539
4540 // fold (cttz_zero_undef c1) -> c2
4541 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004542 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004543 return SDValue();
4544}
4545
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004546SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4547 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004548 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004549
Nate Begeman21158fc2005-09-01 00:19:25 +00004550 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004551 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004552 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004553 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004554}
4555
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004556SDValue DAGCombiner::visitSELECT(SDNode *N) {
4557 SDValue N0 = N->getOperand(0);
4558 SDValue N1 = N->getOperand(1);
4559 SDValue N2 = N->getOperand(2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004560 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4561 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4562 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004563 EVT VT = N->getValueType(0);
4564 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004565
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004566 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004567 if (N1 == N2)
4568 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004569 // fold (select true, X, Y) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004570 if (N0C && !N0C->isNullValue())
4571 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004572 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004573 if (N0C && N0C->isNullValue())
4574 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004575 // fold (select C, 1, X) -> (or C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004576 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004577 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004578 // fold (select C, 0, 1) -> (xor C, 1)
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004579 // We can't do this reliably if integer based booleans have different contents
4580 // to floating point based booleans. This is because we can't tell whether we
4581 // have an integer-based boolean or a floating-point-based boolean unless we
4582 // can find the SETCC that produced it and inspect its operands. This is
4583 // fairly easy if C is the SETCC node, but it can potentially be
4584 // undiscoverable (or not reasonably discoverable). For example, it could be
4585 // in another basic block or it could require searching a complicated
4586 // expression.
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004587 if (VT.isInteger() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004588 (VT0 == MVT::i1 || (VT0.isInteger() &&
4589 TLI.getBooleanContents(false, false) ==
4590 TLI.getBooleanContents(false, true) &&
4591 TLI.getBooleanContents(false, false) ==
4592 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004593 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004594 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004595 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004596 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004597 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004598 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004599 N0, DAG.getConstant(1, VT0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004600 AddToWorklist(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004601 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004602 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4603 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004604 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004605 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004606 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004607 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004608 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004609 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004610 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004611 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004612 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004613 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004614 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004615 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004616 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004617 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004618 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004619 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004620 // fold (select X, X, Y) -> (or X, Y)
4621 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004622 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004623 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004624 // fold (select X, Y, X) -> (and X, Y)
4625 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004626 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004627 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004628
Chris Lattner6c14c352005-10-18 06:04:22 +00004629 // If we can fold this based on the true/false value, do so.
4630 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004631 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004632
Nate Begemanc760f802005-09-19 22:34:01 +00004633 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004634 if (N0.getOpcode() == ISD::SETCC) {
Tom Stellard3787b122014-06-10 16:01:29 +00004635 if ((!LegalOperations &&
4636 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4637 TLI.isOperationLegal(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004638 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004639 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004640 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004641 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004642 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004643
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004644 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004645}
4646
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004647static
4648std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4649 SDLoc DL(N);
4650 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004651 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004652
4653 // Split the inputs.
4654 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004655 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4656 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004657
4658 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4659 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4660
4661 return std::make_pair(Lo, Hi);
4662}
4663
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004664// This function assumes all the vselect's arguments are CONCAT_VECTOR
4665// nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4666static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4667 SDLoc dl(N);
4668 SDValue Cond = N->getOperand(0);
4669 SDValue LHS = N->getOperand(1);
4670 SDValue RHS = N->getOperand(2);
4671 MVT VT = N->getSimpleValueType(0);
4672 int NumElems = VT.getVectorNumElements();
4673 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4674 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4675 Cond.getOpcode() == ISD::BUILD_VECTOR);
4676
4677 // We're sure we have an even number of elements due to the
4678 // concat_vectors we have as arguments to vselect.
4679 // Skip BV elements until we find one that's not an UNDEF
4680 // After we find an UNDEF element, keep looping until we get to half the
4681 // length of the BV and see if all the non-undef nodes are the same.
4682 ConstantSDNode *BottomHalf = nullptr;
4683 for (int i = 0; i < NumElems / 2; ++i) {
4684 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4685 continue;
4686
4687 if (BottomHalf == nullptr)
4688 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4689 else if (Cond->getOperand(i).getNode() != BottomHalf)
4690 return SDValue();
4691 }
4692
4693 // Do the same for the second half of the BuildVector
4694 ConstantSDNode *TopHalf = nullptr;
4695 for (int i = NumElems / 2; i < NumElems; ++i) {
4696 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4697 continue;
4698
4699 if (TopHalf == nullptr)
4700 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4701 else if (Cond->getOperand(i).getNode() != TopHalf)
4702 return SDValue();
4703 }
4704
4705 assert(TopHalf && BottomHalf &&
4706 "One half of the selector was all UNDEFs and the other was all the "
4707 "same value. This should have been addressed before this function.");
4708 return DAG.getNode(
4709 ISD::CONCAT_VECTORS, dl, VT,
4710 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4711 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4712}
4713
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004714SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4715 SDValue N0 = N->getOperand(0);
4716 SDValue N1 = N->getOperand(1);
4717 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004718 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004719
4720 // Canonicalize integer abs.
4721 // vselect (setg[te] X, 0), X, -X ->
4722 // vselect (setgt X, -1), X, -X ->
4723 // vselect (setl[te] X, 0), -X, X ->
4724 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4725 if (N0.getOpcode() == ISD::SETCC) {
4726 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4727 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4728 bool isAbs = false;
4729 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4730
4731 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4732 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4733 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4734 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4735 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4736 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4737 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4738
4739 if (isAbs) {
4740 EVT VT = LHS.getValueType();
4741 SDValue Shift = DAG.getNode(
4742 ISD::SRA, DL, VT, LHS,
4743 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4744 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004745 AddToWorklist(Shift.getNode());
4746 AddToWorklist(Add.getNode());
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004747 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4748 }
4749 }
4750
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004751 // If the VSELECT result requires splitting and the mask is provided by a
4752 // SETCC, then split both nodes and its operands before legalization. This
4753 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4754 // and enables future optimizations (e.g. min/max pattern matching on X86).
4755 if (N0.getOpcode() == ISD::SETCC) {
4756 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004757
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004758 // Check if any splitting is required.
4759 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4760 TargetLowering::TypeSplitVector)
4761 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004762
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004763 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004764 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4765 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4766 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004767
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004768 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4769 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004770
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004771 // Add the new VSELECT nodes to the work list in case they need to be split
4772 // again.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004773 AddToWorklist(Lo.getNode());
4774 AddToWorklist(Hi.getNode());
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004775
4776 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004777 }
4778
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00004779 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4780 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4781 return N1;
4782 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4783 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4784 return N2;
4785
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004786 // The ConvertSelectToConcatVector function is assuming both the above
4787 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4788 // and addressed.
4789 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4790 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4791 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4792 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4793 if (CV.getNode())
4794 return CV;
4795 }
4796
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004797 return SDValue();
4798}
4799
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004800SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4801 SDValue N0 = N->getOperand(0);
4802 SDValue N1 = N->getOperand(1);
4803 SDValue N2 = N->getOperand(2);
4804 SDValue N3 = N->getOperand(3);
4805 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00004806 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004807
Nate Begemanc760f802005-09-19 22:34:01 +00004808 // fold select_cc lhs, rhs, x, x, cc -> x
4809 if (N2 == N3)
4810 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00004811
Chris Lattner8b68dec2006-09-20 06:19:26 +00004812 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00004813 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004814 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00004815 if (SCC.getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004816 AddToWorklist(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00004817
Stephen Lin605207f2013-06-15 04:03:33 +00004818 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4819 if (!SCCC->isNullValue())
4820 return N2; // cond always true -> true val
4821 else
4822 return N3; // cond always false -> false val
4823 }
4824
4825 // Fold to a simpler select_cc
4826 if (SCC.getOpcode() == ISD::SETCC)
4827 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4828 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4829 SCC.getOperand(2));
Chris Lattner8b68dec2006-09-20 06:19:26 +00004830 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004831
Chris Lattner6c14c352005-10-18 06:04:22 +00004832 // If we can fold this based on the true/false value, do so.
4833 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004834 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00004835
Nate Begemanc760f802005-09-19 22:34:01 +00004836 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00004837 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004838}
4839
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004840SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00004841 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00004842 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004843 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00004844}
4845
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004846// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4847// dag node into a ConstantSDNode or a build_vector of constants.
4848// This function is called by the DAGCombiner when visiting sext/zext/aext
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00004849// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004850// Vector extends are not folded if operations are legal; this is to
4851// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004852static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4853 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004854 bool LegalOperations) {
4855 unsigned Opcode = N->getOpcode();
4856 SDValue N0 = N->getOperand(0);
4857 EVT VT = N->getValueType(0);
4858
4859 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4860 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4861
4862 // fold (sext c1) -> c1
4863 // fold (zext c1) -> c1
4864 // fold (aext c1) -> c1
4865 if (isa<ConstantSDNode>(N0))
4866 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4867
4868 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4869 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4870 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004871 EVT SVT = VT.getScalarType();
4872 if (!(VT.isVector() &&
4873 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004874 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
Craig Topperc0196b12014-04-14 00:51:57 +00004875 return nullptr;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00004876
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004877 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004878 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004879 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4880 unsigned ShAmt = VTBits - EVTBits;
4881 SmallVector<SDValue, 8> Elts;
4882 unsigned NumElts = N0->getNumOperands();
4883 SDLoc DL(N);
4884
4885 for (unsigned i=0; i != NumElts; ++i) {
4886 SDValue Op = N0->getOperand(i);
4887 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004888 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004889 continue;
4890 }
4891
4892 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4893 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4894 if (Opcode == ISD::SIGN_EXTEND)
4895 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004896 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004897 else
4898 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004899 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004900 }
4901
Craig Topper48d114b2014-04-26 18:35:24 +00004902 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004903}
4904
Evan Chenge106e2f2007-10-29 19:58:20 +00004905// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00004906// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00004907// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00004908// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004909static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00004910 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00004911 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00004912 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004913 bool HasCopyToRegUses = false;
4914 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00004915 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4916 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00004917 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00004918 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00004919 if (User == N)
4920 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00004921 if (UI.getUse().getResNo() != N0.getResNo())
4922 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004923 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00004924 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004925 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4926 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4927 // Sign bits will be lost after a zext.
4928 return false;
4929 bool Add = false;
4930 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004931 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00004932 if (UseOp == N0)
4933 continue;
4934 if (!isa<ConstantSDNode>(UseOp))
4935 return false;
4936 Add = true;
4937 }
4938 if (Add)
4939 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00004940 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004941 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00004942 // If truncates aren't free and there are users we can't
4943 // extend, it isn't worthwhile.
4944 if (!isTruncFree)
4945 return false;
4946 // Remember if this value is live-out.
4947 if (User->getOpcode() == ISD::CopyToReg)
4948 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00004949 }
4950
4951 if (HasCopyToRegUses) {
4952 bool BothLiveOut = false;
4953 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4954 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00004955 SDUse &Use = UI.getUse();
4956 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4957 BothLiveOut = true;
4958 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00004959 }
4960 }
4961 if (BothLiveOut)
4962 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00004963 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00004964 return ExtendNodes.size();
4965 }
4966 return true;
4967}
4968
Craig Toppere0b71182013-07-13 07:43:40 +00004969void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004970 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004971 ISD::NodeType ExtType) {
4972 // Extend SetCC uses if necessary.
4973 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4974 SDNode *SetCC = SetCCs[i];
4975 SmallVector<SDValue, 4> Ops;
4976
4977 for (unsigned j = 0; j != 2; ++j) {
4978 SDValue SOp = SetCC->getOperand(j);
4979 if (SOp == Trunc)
4980 Ops.push_back(ExtLoad);
4981 else
4982 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4983 }
4984
4985 Ops.push_back(SetCC->getOperand(2));
Craig Topper48d114b2014-04-26 18:35:24 +00004986 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004987 }
4988}
4989
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004990SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4991 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004992 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004993
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004994 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4995 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004996 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004997
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004998 // fold (sext (sext x)) -> (sext x)
4999 // fold (sext (aext x)) -> (sext x)
5000 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005001 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005002 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005003
Chris Lattnerfce448f2007-02-26 03:13:59 +00005004 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005005 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5006 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005007 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5008 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005009 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5010 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005011 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005012 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005013 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005014 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00005015 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005016 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005017
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005018 // See if the value being truncated is already sign extended. If so, just
5019 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005020 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005021 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5022 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5023 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00005024 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005025
Chris Lattnerfce448f2007-02-26 03:13:59 +00005026 if (OpBits == DestBits) {
5027 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5028 // bits, it is already ready.
5029 if (NumSignBits > DestBits-MidBits)
5030 return Op;
5031 } else if (OpBits < DestBits) {
5032 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5033 // bits, just sext from i32.
5034 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005035 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00005036 } else {
5037 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5038 // bits, just truncate to i32.
5039 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005040 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00005041 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005042
Chris Lattnerfce448f2007-02-26 03:13:59 +00005043 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005044 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5045 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005046 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005047 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005048 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005049 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5050 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005051 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00005052 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00005053 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005054
Evan Chengbce7c472005-12-14 02:19:23 +00005055 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005056 // None of the supported targets knows how to perform load and sign extend
Nadav Rotemb0091302011-02-27 07:40:43 +00005057 // on vectors in one instruction. We only perform this transformation on
5058 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005059 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005060 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005061 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005062 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005063 bool DoXform = true;
5064 SmallVector<SDNode*, 4> SetCCs;
5065 if (!N0.hasOneUse())
5066 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5067 if (DoXform) {
5068 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005069 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005070 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005071 LN0->getBasePtr(), N0.getValueType(),
5072 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005073 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005074 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005075 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005076 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005077 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005078 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005079 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005080 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005081 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005082
5083 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5084 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005085 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5086 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005087 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005088 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005089 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005090 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005091 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005092 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005093 LN0->getBasePtr(), MemVT,
5094 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00005095 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005096 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005097 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005098 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00005099 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005100 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00005101 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005102 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005103
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005104 // fold (sext (and/or/xor (load x), cst)) ->
5105 // (and/or/xor (sextload x), (sext cst))
5106 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5107 N0.getOpcode() == ISD::XOR) &&
5108 isa<LoadSDNode>(N0.getOperand(0)) &&
5109 N0.getOperand(1).getOpcode() == ISD::Constant &&
5110 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5111 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5112 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005113 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005114 bool DoXform = true;
5115 SmallVector<SDNode*, 4> SetCCs;
5116 if (!N0.hasOneUse())
5117 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5118 SetCCs, TLI);
5119 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005120 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005121 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005122 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005123 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005124 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5125 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005126 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005127 ExtLoad, DAG.getConstant(Mask, VT));
5128 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005129 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005130 N0.getOperand(0).getValueType(), ExtLoad);
5131 CombineTo(N, And);
5132 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005133 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005134 ISD::SIGN_EXTEND);
5135 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5136 }
5137 }
5138 }
5139
Chris Lattner65786b02007-04-11 05:32:27 +00005140 if (N0.getOpcode() == ISD::SETCC) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005141 EVT N0VT = N0.getOperand(0).getValueType();
Chris Lattner4ac60732009-07-08 00:31:33 +00005142 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00005143 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00005144 if (VT.isVector() && !LegalOperations &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005145 TLI.getBooleanContents(N0VT) ==
5146 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Nadav Rotem9d376b62012-04-11 08:26:11 +00005147 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5148 // of the same size as the compared operands. Only optimize sext(setcc())
5149 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00005150 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00005151
5152 // We know that the # elements of the results is the same as the
5153 // # elements of the compare (and the # elements of the compare result
5154 // for that matter). Check to see that they are the same size. If so,
5155 // we know that the element size of the sext'd result matches the
5156 // element size of the compare operands.
5157 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005158 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005159 N0.getOperand(1),
5160 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00005161
Dan Gohmane82c25e2010-04-30 17:19:19 +00005162 // If the desired elements are smaller or larger than the source
5163 // elements we can use a matching integer vector type and then
5164 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00005165 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00005166 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005167 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00005168 N0.getOperand(0), N0.getOperand(1),
5169 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005170 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00005171 }
Chris Lattner4ac60732009-07-08 00:31:33 +00005172 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00005173
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005174 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00005175 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00005176 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00005177 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005178 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005179 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00005180 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005181 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005182 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005183
5184 if (!VT.isVector()) {
5185 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5186 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5187 SDLoc DL(N);
5188 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5189 SDValue SetCC = DAG.getSetCC(DL,
5190 SetCCVT,
5191 N0.getOperand(0), N0.getOperand(1), CC);
5192 EVT SelectVT = getSetCCResultType(VT);
5193 return DAG.getSelect(DL, VT,
5194 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5195 NegOne, DAG.getConstant(0, VT));
5196
5197 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00005198 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005199 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005200
Dan Gohman3eb10f72008-04-28 16:58:24 +00005201 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005202 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00005203 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005204 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005205
Evan Chengf1005572010-04-28 07:10:39 +00005206 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005207}
5208
Rafael Espindola8f62b322012-04-09 16:06:03 +00005209// isTruncateOf - If N is a truncate of some other value, return true, record
5210// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5211// This function computes KnownZero to avoid a duplicated call to
Jay Foada0653a32014-05-14 21:14:37 +00005212// computeKnownBits in the caller.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005213static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5214 APInt &KnownZero) {
5215 APInt KnownOne;
5216 if (N->getOpcode() == ISD::TRUNCATE) {
5217 Op = N->getOperand(0);
Jay Foada0653a32014-05-14 21:14:37 +00005218 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005219 return true;
5220 }
5221
5222 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5223 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5224 return false;
5225
5226 SDValue Op0 = N->getOperand(0);
5227 SDValue Op1 = N->getOperand(1);
5228 assert(Op0.getValueType() == Op1.getValueType());
5229
5230 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5231 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005232 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005233 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005234 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005235 Op = Op0;
5236 else
5237 return false;
5238
Jay Foada0653a32014-05-14 21:14:37 +00005239 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005240
5241 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5242 return false;
5243
5244 return true;
5245}
5246
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005247SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5248 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005249 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005250
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005251 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5252 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005253 return SDValue(Res, 0);
5254
Nate Begeman21158fc2005-09-01 00:19:25 +00005255 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005256 // fold (zext (aext x)) -> (zext x)
5257 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005258 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005259 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00005260
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005261 // fold (zext (truncate x)) -> (zext x) or
5262 // (zext (truncate x)) -> (truncate x)
5263 // This is valid when the truncated bits of x are already zero.
5264 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005265 SDValue Op;
5266 APInt KnownZero;
5267 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5268 APInt TruncatedBits =
5269 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5270 APInt(Op.getValueSizeInBits(), 0) :
5271 APInt::getBitsSet(Op.getValueSizeInBits(),
5272 N0.getValueSizeInBits(),
5273 std::min(Op.getValueSizeInBits(),
5274 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00005275 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005276 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005277 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005278 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005279 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005280
5281 return Op;
5282 }
5283 }
5284
Evan Cheng464dc9b2007-03-22 01:54:19 +00005285 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5286 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00005287 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005288 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5289 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005290 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5291 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005292 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005293 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005294 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005295 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005296 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005297 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005298 }
5299
Chris Lattnera31f0a62006-09-21 06:00:20 +00005300 // fold (zext (truncate x)) -> (and x, mask)
5301 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00005302 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005303
5304 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5305 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5306 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5307 if (NarrowLoad.getNode()) {
5308 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5309 if (NarrowLoad.getNode() != N0.getNode()) {
5310 CombineTo(N0.getNode(), NarrowLoad);
5311 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005312 AddToWorklist(oye);
Dan Gohman68fb0042010-11-03 01:47:46 +00005313 }
5314 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5315 }
5316
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005317 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005318 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005319 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005320 AddToWorklist(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00005321 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005322 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005323 AddToWorklist(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005324 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005325 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00005326 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005327 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005328
Dan Gohmanad3e5492009-04-08 00:15:30 +00005329 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5330 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005331 if (N0.getOpcode() == ISD::AND &&
5332 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005333 N0.getOperand(1).getOpcode() == ISD::Constant &&
5334 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5335 N0.getValueType()) ||
5336 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005337 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005338 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005339 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005340 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005341 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005342 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005343 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005344 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005345 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005346 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005347 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005348
Evan Chengbce7c472005-12-14 02:19:23 +00005349 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005350 // None of the supported targets knows how to perform load and vector_zext
Nadav Rotemb0091302011-02-27 07:40:43 +00005351 // on vectors in one instruction. We only perform this transformation on
5352 // scalars.
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005353 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005354 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005355 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005356 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005357 bool DoXform = true;
5358 SmallVector<SDNode*, 4> SetCCs;
5359 if (!N0.hasOneUse())
5360 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5361 if (DoXform) {
5362 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005363 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005364 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005365 LN0->getBasePtr(), N0.getValueType(),
5366 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005367 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005368 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005369 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005370 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005371
Andrew Trickef9de2a2013-05-25 02:42:55 +00005372 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005373 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005374 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005375 }
Evan Chengbce7c472005-12-14 02:19:23 +00005376 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005377
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005378 // fold (zext (and/or/xor (load x), cst)) ->
5379 // (and/or/xor (zextload x), (zext cst))
5380 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5381 N0.getOpcode() == ISD::XOR) &&
5382 isa<LoadSDNode>(N0.getOperand(0)) &&
5383 N0.getOperand(1).getOpcode() == ISD::Constant &&
5384 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5385 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5386 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005387 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005388 bool DoXform = true;
5389 SmallVector<SDNode*, 4> SetCCs;
5390 if (!N0.hasOneUse())
5391 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5392 SetCCs, TLI);
5393 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005394 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005395 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005396 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005397 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005398 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5399 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005400 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005401 ExtLoad, DAG.getConstant(Mask, VT));
5402 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005403 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005404 N0.getOperand(0).getValueType(), ExtLoad);
5405 CombineTo(N, And);
5406 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005407 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005408 ISD::ZERO_EXTEND);
5409 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5410 }
5411 }
5412 }
5413
Chris Lattner7dac1082005-12-14 19:05:06 +00005414 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5415 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005416 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5417 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005418 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005419 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005420 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005421 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005422 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005423 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005424 LN0->getBasePtr(), MemVT,
5425 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005426 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005427 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005428 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005429 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005430 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005431 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005432 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005433 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005434
Chris Lattner65786b02007-04-11 05:32:27 +00005435 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005436 if (!LegalOperations && VT.isVector() &&
5437 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005438 EVT N0VT = N0.getOperand(0).getValueType();
5439 if (getSetCCResultType(N0VT) == N0.getValueType())
5440 return SDValue();
5441
Evan Chengabd0ad52010-05-19 01:08:17 +00005442 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5443 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005444 EVT EltVT = VT.getVectorElementType();
5445 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5446 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00005447 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00005448 // We know that the # elements of the results is the same as the
5449 // # elements of the compare (and the # elements of the compare result
5450 // for that matter). Check to see that they are the same size. If so,
5451 // we know that the element size of the sext'd result matches the
5452 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005453 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5454 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00005455 N0.getOperand(1),
5456 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005457 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Craig Topper48d114b2014-04-26 18:35:24 +00005458 OneOps));
Dan Gohman4298df62011-05-17 22:20:36 +00005459
5460 // If the desired elements are smaller or larger than the source
5461 // elements we can use a matching integer vector type and then
5462 // truncate/sign extend
5463 EVT MatchingElementType =
5464 EVT::getIntegerVT(*DAG.getContext(),
5465 N0VT.getScalarType().getSizeInBits());
5466 EVT MatchingVectorType =
5467 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5468 N0VT.getVectorNumElements());
5469 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005470 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00005471 N0.getOperand(1),
5472 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005473 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5474 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
Craig Topper48d114b2014-04-26 18:35:24 +00005475 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
Evan Chengabd0ad52010-05-19 01:08:17 +00005476 }
5477
5478 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005479 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005480 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00005481 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005482 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005483 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005484 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005485
Evan Cheng852c4862009-12-15 03:00:32 +00005486 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00005487 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00005488 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00005489 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5490 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005491 SDValue ShAmt = N0.getOperand(1);
5492 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00005493 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005494 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00005495 // If the original shl may be shifting out bits, do not perform this
5496 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00005497 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5498 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5499 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00005500 return SDValue();
5501 }
Chris Lattnere95d1952011-02-13 19:09:16 +00005502
Andrew Trickef9de2a2013-05-25 02:42:55 +00005503 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005504
5505 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00005506 if (VT.getSizeInBits() >= 256)
5507 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005508
Chris Lattnere95d1952011-02-13 19:09:16 +00005509 return DAG.getNode(N0.getOpcode(), DL, VT,
5510 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5511 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00005512 }
5513
Evan Chengf1005572010-04-28 07:10:39 +00005514 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005515}
5516
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005517SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5518 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005519 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005520
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005521 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5522 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005523 return SDValue(Res, 0);
5524
Chris Lattner812646a2006-05-05 05:58:59 +00005525 // fold (aext (aext x)) -> (aext x)
5526 // fold (aext (zext x)) -> (zext x)
5527 // fold (aext (sext x)) -> (sext x)
5528 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5529 N0.getOpcode() == ISD::ZERO_EXTEND ||
5530 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005531 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005532
Evan Cheng464dc9b2007-03-22 01:54:19 +00005533 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5534 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5535 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005536 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5537 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005538 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5539 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005540 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005541 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005542 AddToWorklist(oye);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005543 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005544 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005545 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005546 }
5547
Chris Lattner8746e2c2006-09-20 06:29:17 +00005548 // fold (aext (truncate x))
5549 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005550 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005551 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005552 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00005553 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005554 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5555 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005556 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005557
Dan Gohmanad3e5492009-04-08 00:15:30 +00005558 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5559 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00005560 if (N0.getOpcode() == ISD::AND &&
5561 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005562 N0.getOperand(1).getOpcode() == ISD::Constant &&
5563 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5564 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005565 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005566 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005567 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005568 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005569 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00005570 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005571 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005572 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005573 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005574 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00005575 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005576
Chris Lattner812646a2006-05-05 05:58:59 +00005577 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005578 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00005579 // on vectors in one instruction. We only perform this transformation on
5580 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005581 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005582 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Tim Northover7f3e11e2014-07-16 15:37:24 +00005583 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005584 bool DoXform = true;
5585 SmallVector<SDNode*, 4> SetCCs;
5586 if (!N0.hasOneUse())
5587 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5588 if (DoXform) {
5589 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005590 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005591 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005592 LN0->getBasePtr(), N0.getValueType(),
5593 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00005594 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005595 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00005596 N0.getValueType(), ExtLoad);
5597 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005598 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005599 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005600 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5601 }
Chris Lattner812646a2006-05-05 05:58:59 +00005602 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005603
Chris Lattner812646a2006-05-05 05:58:59 +00005604 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5605 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5606 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005607 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005608 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00005609 N0.hasOneUse()) {
5610 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005611 ISD::LoadExtType ExtType = LN0->getExtensionType();
Dan Gohman08c0a952009-09-23 21:02:20 +00005612 EVT MemVT = LN0->getMemoryVT();
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005613 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5614 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5615 VT, LN0->getChain(), LN0->getBasePtr(),
5616 MemVT, LN0->getMemOperand());
5617 CombineTo(N, ExtLoad);
5618 CombineTo(N0.getNode(),
5619 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5620 N0.getValueType(), ExtLoad),
5621 ExtLoad.getValue(1));
5622 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5623 }
Chris Lattner812646a2006-05-05 05:58:59 +00005624 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005625
Chris Lattner65786b02007-04-11 05:32:27 +00005626 if (N0.getOpcode() == ISD::SETCC) {
Hao Liuc636d152014-04-22 09:57:06 +00005627 // For vectors:
5628 // aext(setcc) -> vsetcc
5629 // aext(setcc) -> truncate(vsetcc)
5630 // aext(setcc) -> aext(vsetcc)
Evan Chengabd0ad52010-05-19 01:08:17 +00005631 // Only do this before legalize for now.
5632 if (VT.isVector() && !LegalOperations) {
5633 EVT N0VT = N0.getOperand(0).getValueType();
5634 // We know that the # elements of the results is the same as the
5635 // # elements of the compare (and the # elements of the compare result
5636 // for that matter). Check to see that they are the same size. If so,
5637 // we know that the element size of the sext'd result matches the
5638 // element size of the compare operands.
5639 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005640 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005641 N0.getOperand(1),
5642 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00005643 // If the desired elements are smaller or larger than the source
5644 // elements we can use a matching integer vector type and then
Hao Liuc636d152014-04-22 09:57:06 +00005645 // truncate/any extend
Evan Chengabd0ad52010-05-19 01:08:17 +00005646 else {
Hao Liuc636d152014-04-22 09:57:06 +00005647 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005648 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005649 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005650 N0.getOperand(1),
5651 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Hao Liuc636d152014-04-22 09:57:06 +00005652 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00005653 }
5654 }
5655
5656 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005657 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005658 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005659 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00005660 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005661 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00005662 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005663 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005664
Evan Chengf1005572010-04-28 07:10:39 +00005665 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00005666}
5667
Chris Lattner5e6fe052007-10-13 06:35:54 +00005668/// GetDemandedBits - See if the specified operand can be simplified with the
5669/// knowledge that only the bits specified by Mask are used. If so, return the
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005670/// simpler operand, otherwise return a null SDValue.
5671SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00005672 switch (V.getOpcode()) {
5673 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00005674 case ISD::Constant: {
5675 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00005676 assert(CV && "Const value should be ConstSDNode.");
Lang Hamesb85fcd02011-11-08 18:56:23 +00005677 const APInt &CVal = CV->getAPIntValue();
5678 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00005679 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00005680 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00005681 break;
5682 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005683 case ISD::OR:
5684 case ISD::XOR:
5685 // If the LHS or RHS don't contribute bits to the or, drop them.
5686 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5687 return V.getOperand(1);
5688 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5689 return V.getOperand(0);
5690 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00005691 case ISD::SRL:
5692 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00005693 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00005694 break;
5695 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5696 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00005697 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005698
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00005699 // Watch out for shift count overflow though.
5700 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00005701 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005702 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005703 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005704 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00005705 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00005706 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005707 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005708 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00005709}
5710
Evan Cheng464dc9b2007-03-22 01:54:19 +00005711/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5712/// bits and then truncated to a narrower type and where N is a multiple
5713/// of number of bits of the narrower type, transform it to a narrower load
5714/// from address + N / num of bits of new type. If the result is to be
5715/// extended, also fold the extension to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005716SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005717 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00005718
Evan Cheng464dc9b2007-03-22 01:54:19 +00005719 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005720 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005721 EVT VT = N->getValueType(0);
5722 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005723
Dan Gohman550c9af2008-08-14 20:04:46 +00005724 // This transformation isn't valid for vector loads.
5725 if (VT.isVector())
5726 return SDValue();
5727
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005728 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00005729 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00005730 if (Opc == ISD::SIGN_EXTEND_INREG) {
5731 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00005732 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00005733 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00005734 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00005735 ExtType = ISD::ZEXTLOAD;
5736 N0 = SDValue(N, 0);
5737 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5738 if (!N01) return SDValue();
5739 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5740 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00005741 }
Richard Osborne272e0842011-01-31 17:41:44 +00005742 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5743 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005744
Owen Anderson53aa7a92009-08-10 22:56:29 +00005745 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005746
Chris Lattner9a499e92010-12-22 08:01:44 +00005747 // Do not generate loads of non-round integer types since these can
5748 // be expensive (and would be wrong if the type is not byte sized).
5749 if (!ExtVT.isRound())
5750 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005751
Evan Cheng464dc9b2007-03-22 01:54:19 +00005752 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00005753 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005754 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00005755 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005756 // Is the shift amount a multiple of size of VT?
5757 if ((ShAmt & (EVTBits-1)) == 0) {
5758 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00005759 // Is the load width a multiple of size of VT?
5760 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005761 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005762 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005763
Chris Lattnercafc1e62010-12-22 08:02:57 +00005764 // At this point, we must have a load or else we can't do the transform.
5765 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005766
Chandler Carruthb27041c2012-12-11 00:36:57 +00005767 // Because a SRL must be assumed to *need* to zero-extend the high bits
5768 // (as opposed to anyext the high bits), we can't combine the zextload
5769 // lowering of SRL and an sextload.
5770 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5771 return SDValue();
5772
Chris Lattnera2050552010-10-01 05:36:09 +00005773 // If the shift amount is larger than the input type then we're not
5774 // accessing any of the loaded bytes. If the load was a zextload/extload
5775 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00005776 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00005777 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005778 }
5779 }
5780
Dan Gohman68fb0042010-11-03 01:47:46 +00005781 // If the load is shifted left (and the result isn't shifted back right),
5782 // we can fold the truncate through the shift.
5783 unsigned ShLeftAmt = 0;
5784 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00005785 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005786 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5787 ShLeftAmt = N01->getZExtValue();
5788 N0 = N0.getOperand(0);
5789 }
5790 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00005791
Chris Lattner222374d2010-12-22 07:36:50 +00005792 // If we haven't found a load, we can't narrow it. Don't transform one with
5793 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00005794 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5795 return SDValue();
5796
5797 // Don't change the width of a volatile load.
5798 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5799 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00005800 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005801
Chris Lattner9a499e92010-12-22 08:01:44 +00005802 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00005803 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00005804 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005805
Bill Schmidtd006c692013-01-14 22:04:38 +00005806 // For the transform to be legal, the load must produce only two values
5807 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00005808 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00005809 // transformation is not equivalent, and the downstream logic to replace
5810 // uses gets things wrong.
5811 if (LN0->getNumValues() > 2)
5812 return SDValue();
5813
Benjamin Kramerc7332b22013-07-06 14:05:09 +00005814 // If the load that we're shrinking is an extload and we're not just
5815 // discarding the extension we can't simply shrink the load. Bail.
5816 // TODO: It would be possible to merge the extensions in some cases.
5817 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5818 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5819 return SDValue();
5820
Chris Lattner222374d2010-12-22 07:36:50 +00005821 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005822
Evan Cheng4c6f9172012-06-26 01:19:33 +00005823 if (PtrType == MVT::Untyped || PtrType.isExtended())
5824 // It's not possible to generate a constant of extended or untyped type.
5825 return SDValue();
5826
Chris Lattner222374d2010-12-22 07:36:50 +00005827 // For big endian targets, we need to adjust the offset to the pointer to
5828 // load the correct bytes.
5829 if (TLI.isBigEndian()) {
5830 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5831 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5832 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005833 }
5834
Chris Lattner222374d2010-12-22 07:36:50 +00005835 uint64_t PtrOff = ShAmt / 8;
5836 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005837 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00005838 PtrType, LN0->getBasePtr(),
5839 DAG.getConstant(PtrOff, PtrType));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005840 AddToWorklist(NewPtr.getNode());
Chris Lattner222374d2010-12-22 07:36:50 +00005841
Chris Lattner9a499e92010-12-22 08:01:44 +00005842 SDValue Load;
5843 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005844 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005845 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00005846 LN0->isVolatile(), LN0->isNonTemporal(),
Hal Finkelcc39b672014-07-24 12:16:19 +00005847 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00005848 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005849 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005850 LN0->getPointerInfo().getWithOffset(PtrOff),
5851 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00005852 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00005853
5854 // Replace the old load's chain with the new load's chain.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005855 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00005856 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00005857
5858 // Shift the result left, if we've swallowed a left shift.
5859 SDValue Result = Load;
5860 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00005861 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00005862 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5863 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00005864 // If the shift amount is as large as the result size (but, presumably,
5865 // no larger than the source) then the useful bits of the result are
5866 // zero; we can't simply return the shortened shift, because the result
5867 // of that operation is undefined.
5868 if (ShLeftAmt >= VT.getSizeInBits())
5869 Result = DAG.getConstant(0, VT);
5870 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005871 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00005872 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00005873 }
5874
5875 // Return the new loaded value.
5876 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005877}
5878
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005879SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5880 SDValue N0 = N->getOperand(0);
5881 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005882 EVT VT = N->getValueType(0);
5883 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00005884 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005885 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005886
Nate Begeman21158fc2005-09-01 00:19:25 +00005887 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00005888 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005889 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005890
Chris Lattner2a4d7b82006-05-06 22:43:44 +00005891 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00005892 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00005893 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005894
Nate Begeman7cea6ef2005-09-02 21:18:40 +00005895 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5896 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00005897 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005898 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005899 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00005900
Dan Gohman345d63c2008-07-31 00:50:31 +00005901 // fold (sext_in_reg (sext x)) -> (sext x)
5902 // fold (sext_in_reg (aext x)) -> (sext x)
5903 // if x is small enough.
5904 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5905 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00005906 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5907 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005908 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00005909 }
5910
Chris Lattner9ad59152007-04-17 19:03:21 +00005911 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00005912 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005913 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005914
Chris Lattner9ad59152007-04-17 19:03:21 +00005915 // fold operands of sext_in_reg based on knowledge that the top bits are not
5916 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005917 if (SimplifyDemandedBits(SDValue(N, 0)))
5918 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005919
Evan Cheng464dc9b2007-03-22 01:54:19 +00005920 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5921 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005922 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005923 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00005924 return NarrowLoad;
5925
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005926 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005927 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00005928 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5929 if (N0.getOpcode() == ISD::SRL) {
5930 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00005931 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005932 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00005933 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00005934 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00005935 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005936 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005937 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00005938 }
5939 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005940
Nate Begeman02b23c62005-10-13 03:11:28 +00005941 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00005942 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005943 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005944 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005945 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005946 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005947 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005948 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005949 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005950 LN0->getBasePtr(), EVT,
5951 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005952 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005953 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005954 AddToWorklist(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005955 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005956 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005957 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00005958 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005959 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005960 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005961 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005962 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005963 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005964 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005965 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005966 LN0->getBasePtr(), EVT,
5967 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005968 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005969 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005970 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005971 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00005972
5973 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5974 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5975 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5976 N0.getOperand(1), false);
Craig Topperc0196b12014-04-14 00:51:57 +00005977 if (BSwap.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005978 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00005979 BSwap, N1);
5980 }
5981
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005982 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5983 // into a build_vector.
5984 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5985 SmallVector<SDValue, 8> Elts;
5986 unsigned NumElts = N0->getNumOperands();
5987 unsigned ShAmt = VTBits - EVTBits;
5988
5989 for (unsigned i = 0; i != NumElts; ++i) {
5990 SDValue Op = N0->getOperand(i);
5991 if (Op->getOpcode() == ISD::UNDEF) {
5992 Elts.push_back(Op);
5993 continue;
5994 }
5995
5996 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00005997 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5998 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005999 Op.getValueType()));
6000 }
6001
Craig Topper48d114b2014-04-26 18:35:24 +00006002 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006003 }
6004
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006005 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006006}
6007
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006008SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6009 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006010 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006011 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00006012
6013 // noop truncate
6014 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00006015 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00006016 // fold (truncate c1) -> c1
Chris Lattner7e7bcf32006-05-06 23:06:26 +00006017 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006018 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006019 // fold (truncate (truncate x)) -> (truncate x)
6020 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006021 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00006022 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00006023 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6024 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00006025 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00006026 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006027 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00006028 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006029 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006030 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006031 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00006032 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006033 // if the source and dest are the same type, we can drop both the extend
6034 // and the truncate.
6035 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006036 }
Evan Chengd63baea2007-03-21 20:14:05 +00006037
Nadav Rotem4f4546b2012-02-05 11:39:23 +00006038 // Fold extract-and-trunc into a narrow extract. For example:
6039 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6040 // i32 y = TRUNCATE(i64 x)
6041 // -- becomes --
6042 // v16i8 b = BITCAST (v2i64 val)
6043 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6044 //
6045 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006046 // creates this pattern) and before operation legalization after which
6047 // we need to be more careful about the vector instructions that we generate.
6048 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00006049 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006050
6051 EVT VecTy = N0.getOperand(0).getValueType();
6052 EVT ExTy = N0.getValueType();
6053 EVT TrTy = N->getValueType(0);
6054
6055 unsigned NumElem = VecTy.getVectorNumElements();
6056 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6057
6058 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6059 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6060
6061 SDValue EltNo = N0->getOperand(1);
6062 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6063 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00006064 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006065 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6066
Andrew Trickef9de2a2013-05-25 02:42:55 +00006067 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006068 NVT, N0.getOperand(0));
6069
6070 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00006071 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00006072 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006073 }
6074 }
6075
Matt Arsenault3332b702014-07-10 18:21:04 +00006076 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6077 if (N0.getOpcode() == ISD::SELECT) {
6078 EVT SrcVT = N0.getValueType();
6079 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6080 TLI.isTruncateFree(SrcVT, VT)) {
6081 SDLoc SL(N0);
6082 SDValue Cond = N0.getOperand(0);
6083 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6084 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6085 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6086 }
6087 }
6088
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006089 // Fold a series of buildvector, bitcast, and truncate if possible.
6090 // For example fold
6091 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6092 // (2xi32 (buildvector x, y)).
6093 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6094 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6095 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6096 N0.getOperand(0).hasOneUse()) {
6097
6098 SDValue BuildVect = N0.getOperand(0);
6099 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6100 EVT TruncVecEltTy = VT.getVectorElementType();
6101
6102 // Check that the element types match.
6103 if (BuildVectEltTy == TruncVecEltTy) {
6104 // Now we only need to compute the offset of the truncated elements.
6105 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6106 unsigned TruncVecNumElts = VT.getVectorNumElements();
6107 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6108
6109 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6110 "Invalid number of elements");
6111
6112 SmallVector<SDValue, 8> Opnds;
6113 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6114 Opnds.push_back(BuildVect.getOperand(i));
6115
Craig Topper48d114b2014-04-26 18:35:24 +00006116 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006117 }
6118 }
6119
Chris Lattner5e6fe052007-10-13 06:35:54 +00006120 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00006121 // only the low bits are being used.
6122 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00006123 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00006124 // may have different active low bits.
6125 if (!VT.isVector()) {
6126 SDValue Shorter =
6127 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6128 VT.getSizeInBits()));
6129 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006130 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00006131 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00006132 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00006133 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00006134 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6135 SDValue Reduced = ReduceLoadWidth(N);
6136 if (Reduced.getNode())
6137 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00006138 // Handle the case where the load remains an extending load even
6139 // after truncation.
6140 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6141 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6142 if (!LN0->isVolatile() &&
6143 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6144 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6145 VT, LN0->getChain(), LN0->getBasePtr(),
6146 LN0->getMemoryVT(),
6147 LN0->getMemOperand());
6148 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6149 return NewLoad;
6150 }
6151 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006152 }
Michael Liao3ac82012012-10-17 23:45:54 +00006153 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6154 // where ... are all 'undef'.
6155 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6156 SmallVector<EVT, 8> VTs;
6157 SDValue V;
6158 unsigned Idx = 0;
6159 unsigned NumDefs = 0;
6160
6161 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6162 SDValue X = N0.getOperand(i);
6163 if (X.getOpcode() != ISD::UNDEF) {
6164 V = X;
6165 Idx = i;
6166 NumDefs++;
6167 }
6168 // Stop if more than one members are non-undef.
6169 if (NumDefs > 1)
6170 break;
6171 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6172 VT.getVectorElementType(),
6173 X.getValueType().getVectorNumElements()));
6174 }
6175
6176 if (NumDefs == 0)
6177 return DAG.getUNDEF(VT);
6178
6179 if (NumDefs == 1) {
6180 assert(V.getNode() && "The single defined operand is empty!");
6181 SmallVector<SDValue, 8> Opnds;
6182 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6183 if (i != Idx) {
6184 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6185 continue;
6186 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006187 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006188 AddToWorklist(NV.getNode());
Michael Liao3ac82012012-10-17 23:45:54 +00006189 Opnds.push_back(NV);
6190 }
Craig Topper48d114b2014-04-26 18:35:24 +00006191 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
Michael Liao3ac82012012-10-17 23:45:54 +00006192 }
6193 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006194
6195 // Simplify the operands using demanded-bits information.
6196 if (!VT.isVector() &&
6197 SimplifyDemandedBits(SDValue(N, 0)))
6198 return SDValue(N, 0);
6199
Evan Chengf1bd5fc2010-04-17 06:13:15 +00006200 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006201}
6202
Evan Chengb980f6f2008-05-12 23:04:07 +00006203static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006204 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00006205 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006206 return Elt.getNode();
6207 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00006208}
6209
6210/// CombineConsecutiveLoads - build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00006211/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00006212SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00006213 assert(N->getOpcode() == ISD::BUILD_PAIR);
6214
Nate Begeman624690c2009-06-05 21:37:30 +00006215 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6216 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006217 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00006218 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006219 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00006220 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00006221
Evan Chengb980f6f2008-05-12 23:04:07 +00006222 if (ISD::isNON_EXTLoad(LD2) &&
6223 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006224 // If both are volatile this would reduce the number of volatile loads.
6225 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00006226 !LD1->isVolatile() &&
6227 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00006228 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00006229 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006230 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006231 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00006232
Duncan Sands8651e9c2008-06-13 19:07:40 +00006233 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006234 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006235 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006236 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006237 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00006238 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00006239
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006240 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00006241}
6242
Wesley Peck527da1b2010-11-23 03:31:01 +00006243SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006244 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006245 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00006246
Dan Gohmana8665142007-06-25 16:23:39 +00006247 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6248 // Only do this before legalize, since afterward the target may be depending
6249 // on the bitconvert.
6250 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006251 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006252 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006253 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00006254 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006255
Owen Anderson53aa7a92009-08-10 22:56:29 +00006256 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006257 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00006258 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00006259 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00006260 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00006261 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006262
Dan Gohman921ddd62008-09-05 01:58:21 +00006263 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00006264 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006265 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Dan Gohman733a64d2009-08-10 23:15:10 +00006266 if (Res.getNode() != N) {
6267 if (!LegalOperations ||
6268 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6269 return Res;
6270
6271 // Folding it resulted in an illegal node, and it's too late to
6272 // do that. Clean up the old node and forego the transformation.
6273 // Ideally this won't happen very often, because instcombine
6274 // and the earlier dagcombine runs (where illegal nodes are
6275 // permitted) should have folded most of them already.
Chandler Carruth18066972014-08-02 10:02:07 +00006276 deleteAndRecombine(Res.getNode());
Dan Gohman733a64d2009-08-10 23:15:10 +00006277 }
Chris Lattnera1874602005-12-23 05:30:37 +00006278 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006279
Bill Wendling4e0a6152009-01-30 22:44:24 +00006280 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00006281 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006282 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006283 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006284
Chris Lattner54560f62005-12-23 05:44:41 +00006285 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00006286 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00006287 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006288 // Do not change the width of a volatile load.
6289 !cast<LoadSDNode>(N0)->isVolatile() &&
Ulrich Weigandf236bb12014-07-03 15:06:47 +00006290 // Do not remove the cast if the types differ in endian layout.
6291 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6292 TLI.hasBigEndianPartOrdering(VT) &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00006293 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6294 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006295 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006296 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006297 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006298 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00006299
Evan Chenga4cf58a2007-05-07 21:27:48 +00006300 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006301 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006302 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00006303 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006304 LN0->isInvariant(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00006305 LN0->getAAInfo());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006306 AddToWorklist(N);
Gabor Greife12264b2008-08-30 19:29:20 +00006307 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00006308 DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006309 N0.getValueType(), Load),
Evan Chenga4cf58a2007-05-07 21:27:48 +00006310 Load.getValue(1));
6311 return Load;
6312 }
Chris Lattner54560f62005-12-23 05:44:41 +00006313 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006314
Bill Wendling4e0a6152009-01-30 22:44:24 +00006315 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6316 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00006317 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00006318 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6319 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00006320 N0.getNode()->hasOneUse() && VT.isInteger() &&
6321 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006322 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006323 N0.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006324 AddToWorklist(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00006325
Duncan Sands13237ac2008-06-06 12:08:01 +00006326 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00006327 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006328 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006329 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006330 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006331 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006332 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006333 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006334
Bill Wendling4e0a6152009-01-30 22:44:24 +00006335 // fold (bitconvert (fcopysign cst, x)) ->
6336 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6337 // Note that we don't handle (copysign x, cst) because this can always be
6338 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006339 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00006340 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006341 VT.isInteger() && !VT.isVector()) {
6342 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00006343 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00006344 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006345 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006346 IntXVT, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006347 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006348
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006349 // If X has a different width than the result/lhs, sext it or truncate it.
6350 unsigned VTWidth = VT.getSizeInBits();
6351 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006352 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006353 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006354 } else if (OrigXWidth > VTWidth) {
6355 // To get the sign bit in the right place, we have to shift it right
6356 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006357 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006358 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006359 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006360 AddToWorklist(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006361 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006362 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006363 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006364
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006365 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006366 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006367 X, DAG.getConstant(SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006368 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006369
Andrew Trickef9de2a2013-05-25 02:42:55 +00006370 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006371 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006372 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006373 Cst, DAG.getConstant(~SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006374 AddToWorklist(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006375
Andrew Trickef9de2a2013-05-25 02:42:55 +00006376 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006377 }
Chris Lattner888560d2008-01-27 17:42:27 +00006378 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006379
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006380 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006381 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006382 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6383 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006384 return CombineLD;
6385 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006386
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006387 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006388}
6389
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006390SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006391 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006392 return CombineConsecutiveLoads(N, VT);
6393}
6394
Wesley Peck527da1b2010-11-23 03:31:01 +00006395/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
Scott Michelcf0da6c2009-02-17 22:15:04 +00006396/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
Chris Lattnere4e64b62006-04-02 02:53:43 +00006397/// destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006398SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006399ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006400 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006401
Chris Lattnere4e64b62006-04-02 02:53:43 +00006402 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006403 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006404
Duncan Sands13237ac2008-06-06 12:08:01 +00006405 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6406 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006407
Chris Lattnere4e64b62006-04-02 02:53:43 +00006408 // If this is a conversion of N elements of one type to N elements of another
6409 // type, convert each element. This handles FP<->INT cases.
6410 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006411 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6412 BV->getValueType(0).getVectorNumElements());
6413
6414 // Due to the FP element handling below calling this routine recursively,
6415 // we can end up with a scalar-to-vector node here.
6416 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006417 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6418 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006419 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006420
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006421 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006422 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006423 SDValue Op = BV->getOperand(i);
6424 // If the vector element type is not legal, the BUILD_VECTOR operands
6425 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006426 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006427 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6428 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006429 DstEltVT, Op));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006430 AddToWorklist(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006431 }
Craig Topper48d114b2014-04-26 18:35:24 +00006432 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006433 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006434
Chris Lattnere4e64b62006-04-02 02:53:43 +00006435 // Otherwise, we're growing or shrinking the elements. To avoid having to
6436 // handle annoying details of growing/shrinking FP values, we convert them to
6437 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006438 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006439 // Convert the input float vector to a int vector where the elements are the
6440 // same sizes.
Owen Anderson9f944592009-08-11 20:47:22 +00006441 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006442 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006443 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006444 SrcEltVT = IntVT;
6445 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006446
Chris Lattnere4e64b62006-04-02 02:53:43 +00006447 // Now we know the input is an integer vector. If the output is a FP type,
6448 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006449 if (DstEltVT.isFloatingPoint()) {
Owen Anderson9f944592009-08-11 20:47:22 +00006450 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006451 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006452 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006453
Chris Lattnere4e64b62006-04-02 02:53:43 +00006454 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00006455 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006456 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006457
Chris Lattnere4e64b62006-04-02 02:53:43 +00006458 // Okay, we know the src/dst types are both integers of differing types.
6459 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006460 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006461 if (SrcBitSize < DstBitSize) {
6462 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006463
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006464 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006465 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00006466 i += NumInputsPerOutput) {
6467 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00006468 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006469 bool EltIsUndef = true;
6470 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6471 // Shift the previously computed bits over.
6472 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006473 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006474 if (Op.getOpcode() == ISD::UNDEF) continue;
6475 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006476
Jay Foad583abbc2010-12-07 08:25:19 +00006477 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00006478 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006479 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006480
Chris Lattnere4e64b62006-04-02 02:53:43 +00006481 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00006482 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006483 else
6484 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6485 }
6486
Owen Anderson117c9e82009-08-12 00:36:31 +00006487 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Craig Topper48d114b2014-04-26 18:35:24 +00006488 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006489 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006490
Chris Lattnere4e64b62006-04-02 02:53:43 +00006491 // Finally, this must be the case where we are shrinking elements: each input
6492 // turns into multiple outputs.
Evan Cheng6200c222008-02-18 23:04:32 +00006493 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006494 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00006495 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6496 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006497 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006498
Dan Gohmana8665142007-06-25 16:23:39 +00006499 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006500 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6501 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesen84935752009-02-06 23:05:02 +00006502 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006503 continue;
6504 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006505
Jay Foad583abbc2010-12-07 08:25:19 +00006506 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6507 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006508
Chris Lattnere4e64b62006-04-02 02:53:43 +00006509 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00006510 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006511 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad583abbc2010-12-07 08:25:19 +00006512 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Cheng6200c222008-02-18 23:04:32 +00006513 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006514 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006515 Ops[0]);
Dan Gohmane1c4f992008-03-03 23:51:38 +00006516 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006517 }
6518
6519 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00006520 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00006521 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6522 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006523
Craig Topper48d114b2014-04-26 18:35:24 +00006524 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006525}
6526
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006527SDValue DAGCombiner::visitFADD(SDNode *N) {
6528 SDValue N0 = N->getOperand(0);
6529 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006530 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6531 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006532 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006533
Dan Gohmana8665142007-06-25 16:23:39 +00006534 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006535 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006536 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006537 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006538 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006539
Lang Hamesa33db652012-06-14 20:37:15 +00006540 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006541 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006542 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006543 // canonicalize constant to RHS
6544 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006545 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006546 // fold (fadd A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006547 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6548 N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006549 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006550 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006551 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006552 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006553 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006554 GetNegatedExpression(N1, DAG, LegalOperations));
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006555 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006556 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006557 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006558 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006559 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006560
Chris Lattner0199fd62007-01-08 23:04:05 +00006561 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006562 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6563 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6564 isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006565 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6566 DAG.getNode(ISD::FADD, SDLoc(N), VT,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +00006567 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006568
Shuxin Yang93b1f122013-03-25 22:52:29 +00006569 // No FP constant should be created after legalization as Instruction
6570 // Selection pass has hard time in dealing with FP constant.
6571 //
6572 // We don't need test this condition for transformation like following, as
6573 // the DAG being transformed implies it is legal to take FP constant as
6574 // operand.
Stephen Lincfe7f352013-07-08 00:37:03 +00006575 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006576 // (fadd (fmul c, x), x) -> (fmul c+1, x)
Stephen Lincfe7f352013-07-08 00:37:03 +00006577 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006578 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6579
Owen Andersonb351c8d2012-11-01 02:00:53 +00006580 // If allow, fold (fadd (fneg x), x) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006581 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006582 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006583 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006584
6585 // If allow, fold (fadd x, (fneg x)) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006586 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006587 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006588 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006589
Owen Andersoncc61f872012-08-30 23:35:16 +00006590 // In unsafe math mode, we can fold chains of FADD's of the same value
6591 // into multiplications. This transform is not safe in general because
6592 // we are reducing the number of rounding steps.
6593 if (DAG.getTarget().Options.UnsafeFPMath &&
6594 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6595 !N0CFP && !N1CFP) {
6596 if (N0.getOpcode() == ISD::FMUL) {
6597 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6598 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6599
Stephen Line31f2d22013-06-14 18:17:35 +00006600 // (fadd (fmul c, x), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006601 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006602 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006603 SDValue(CFP00, 0),
6604 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006605 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006606 N1, NewCFP);
6607 }
6608
Stephen Line31f2d22013-06-14 18:17:35 +00006609 // (fadd (fmul x, c), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006610 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006611 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006612 SDValue(CFP01, 0),
6613 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006614 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006615 N1, NewCFP);
6616 }
6617
Stephen Line31f2d22013-06-14 18:17:35 +00006618 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006619 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6620 N1.getOperand(0) == N1.getOperand(1) &&
6621 N0.getOperand(1) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006622 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006623 SDValue(CFP00, 0),
6624 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006625 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006626 N0.getOperand(1), NewCFP);
6627 }
6628
Stephen Line31f2d22013-06-14 18:17:35 +00006629 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006630 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6631 N1.getOperand(0) == N1.getOperand(1) &&
6632 N0.getOperand(0) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006633 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006634 SDValue(CFP01, 0),
6635 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006636 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006637 N0.getOperand(0), NewCFP);
6638 }
6639 }
6640
6641 if (N1.getOpcode() == ISD::FMUL) {
6642 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6643 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6644
Stephen Line31f2d22013-06-14 18:17:35 +00006645 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006646 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006647 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006648 SDValue(CFP10, 0),
6649 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006650 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006651 N0, NewCFP);
6652 }
6653
Stephen Line31f2d22013-06-14 18:17:35 +00006654 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006655 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006656 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006657 SDValue(CFP11, 0),
6658 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006659 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006660 N0, NewCFP);
6661 }
6662
Owen Andersoncc61f872012-08-30 23:35:16 +00006663
Stephen Line31f2d22013-06-14 18:17:35 +00006664 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6665 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6666 N0.getOperand(0) == N0.getOperand(1) &&
6667 N1.getOperand(1) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006668 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006669 SDValue(CFP10, 0),
6670 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006671 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006672 N1.getOperand(1), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006673 }
6674
Stephen Line31f2d22013-06-14 18:17:35 +00006675 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6676 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6677 N0.getOperand(0) == N0.getOperand(1) &&
6678 N1.getOperand(0) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006679 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006680 SDValue(CFP11, 0),
6681 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006682 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006683 N1.getOperand(0), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006684 }
6685 }
6686
Shuxin Yang93b1f122013-03-25 22:52:29 +00006687 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006688 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006689 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006690 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006691 (N0.getOperand(0) == N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006692 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006693 N1, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006694 }
6695
Shuxin Yang93b1f122013-03-25 22:52:29 +00006696 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006697 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006698 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006699 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006700 N1.getOperand(0) == N0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006701 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006702 N0, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006703 }
6704
Stephen Lin4e69d012013-06-14 21:33:58 +00006705 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
Shuxin Yang93b1f122013-03-25 22:52:29 +00006706 if (AllowNewFpConst &&
6707 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Owen Andersoncc61f872012-08-30 23:35:16 +00006708 N0.getOperand(0) == N0.getOperand(1) &&
6709 N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006710 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006711 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006712 N0.getOperand(0),
6713 DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006714 }
6715
Lang Hames39fb1d02012-06-19 22:51:23 +00006716 // FADD -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006717 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006718 DAG.getTarget().Options.UnsafeFPMath) &&
Eric Christopherd9134482014-08-04 21:25:23 +00006719 DAG.getTarget()
6720 .getSubtargetImpl()
6721 ->getTargetLowering()
6722 ->isFMAFasterThanFMulAndFAdd(VT) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006723 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006724
6725 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Stephen Lin8e8424e2013-07-09 00:44:49 +00006726 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006727 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006728 N0.getOperand(0), N0.getOperand(1), N1);
Owen Andersoncc61f872012-08-30 23:35:16 +00006729
Michael Liaoec3850122012-09-01 04:09:16 +00006730 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hames39fb1d02012-06-19 22:51:23 +00006731 // Note: Commutes FADD operands.
Stephen Lin8e8424e2013-07-09 00:44:49 +00006732 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006733 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006734 N1.getOperand(0), N1.getOperand(1), N0);
Lang Hames39fb1d02012-06-19 22:51:23 +00006735 }
6736
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006737 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006738}
6739
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006740SDValue DAGCombiner::visitFSUB(SDNode *N) {
6741 SDValue N0 = N->getOperand(0);
6742 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006743 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6744 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006745 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006746 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006747
Dan Gohmana8665142007-06-25 16:23:39 +00006748 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006749 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006750 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006751 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006752 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006753
Nate Begeman418c6e42005-10-18 00:28:13 +00006754 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006755 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006756 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006757 // fold (fsub A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006758 if (DAG.getTarget().Options.UnsafeFPMath &&
6759 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1275e282009-01-23 19:10:37 +00006760 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006761 // fold (fsub 0, B) -> -B
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006762 if (DAG.getTarget().Options.UnsafeFPMath &&
6763 N0CFP && N0CFP->getValueAPF().isZero()) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006764 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006765 return GetNegatedExpression(N1, DAG, LegalOperations);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006766 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006767 return DAG.getNode(ISD::FNEG, dl, VT, N1);
Dan Gohman9a708232007-07-02 15:48:56 +00006768 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006769 // fold (fsub A, (fneg B)) -> (fadd A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006770 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006771 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006772 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006773
Bill Wendlingdf170db2012-03-15 05:12:00 +00006774 // If 'unsafe math' is enabled, fold
Owen Andersonab63d842012-05-07 20:51:25 +00006775 // (fsub x, x) -> 0.0 &
Bill Wendlingdf170db2012-03-15 05:12:00 +00006776 // (fsub x, (fadd x, y)) -> (fneg y) &
6777 // (fsub x, (fadd y, x)) -> (fneg y)
6778 if (DAG.getTarget().Options.UnsafeFPMath) {
Owen Andersonab63d842012-05-07 20:51:25 +00006779 if (N0 == N1)
6780 return DAG.getConstantFP(0.0f, VT);
6781
Bill Wendlingdf170db2012-03-15 05:12:00 +00006782 if (N1.getOpcode() == ISD::FADD) {
6783 SDValue N10 = N1->getOperand(0);
6784 SDValue N11 = N1->getOperand(1);
6785
6786 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6787 &DAG.getTarget().Options))
6788 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00006789
Stephen Lin8e8424e2013-07-09 00:44:49 +00006790 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6791 &DAG.getTarget().Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006792 return GetNegatedExpression(N10, DAG, LegalOperations);
6793 }
6794 }
6795
Lang Hames39fb1d02012-06-19 22:51:23 +00006796 // FSUB -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006797 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006798 DAG.getTarget().Options.UnsafeFPMath) &&
Eric Christopherd9134482014-08-04 21:25:23 +00006799 DAG.getTarget()
6800 .getSubtargetImpl()
6801 ->getTargetLowering()
6802 ->isFMAFasterThanFMulAndFAdd(VT) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006803 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006804
6805 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006806 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006807 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006808 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006809 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hames39fb1d02012-06-19 22:51:23 +00006810
6811 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6812 // Note: Commutes FSUB operands.
Stephen Lin10947502013-07-10 20:47:39 +00006813 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006814 return DAG.getNode(ISD::FMA, dl, VT,
6815 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006816 N1.getOperand(0)),
6817 N1.getOperand(1), N0);
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006818
Stephen Lin8e8424e2013-07-09 00:44:49 +00006819 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lincfe7f352013-07-08 00:37:03 +00006820 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006821 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6822 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6823 SDValue N00 = N0.getOperand(0).getOperand(0);
6824 SDValue N01 = N0.getOperand(0).getOperand(1);
6825 return DAG.getNode(ISD::FMA, dl, VT,
6826 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6827 DAG.getNode(ISD::FNEG, dl, VT, N1));
6828 }
Lang Hames39fb1d02012-06-19 22:51:23 +00006829 }
6830
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006831 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006832}
6833
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006834SDValue DAGCombiner::visitFMUL(SDNode *N) {
6835 SDValue N0 = N->getOperand(0);
6836 SDValue N1 = N->getOperand(1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006837 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6838 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006839 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006840 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006841
Dan Gohmana8665142007-06-25 16:23:39 +00006842 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006843 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006844 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006845 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006846 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006847
Nate Begemanec48a1b2005-10-17 20:40:11 +00006848 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006849 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006850 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006851 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00006852 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006853 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Bill Wendling3dc5d242009-01-30 22:57:07 +00006854 // fold (fmul A, 0) -> 0
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006855 if (DAG.getTarget().Options.UnsafeFPMath &&
6856 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006857 return N1;
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006858 // fold (fmul A, 0) -> 0, vector edition.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006859 if (DAG.getTarget().Options.UnsafeFPMath &&
6860 ISD::isBuildVectorAllZeros(N1.getNode()))
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006861 return N1;
Owen Andersonb5f167c2012-05-02 21:32:35 +00006862 // fold (fmul A, 1.0) -> A
6863 if (N1CFP && N1CFP->isExactlyValue(1.0))
6864 return N0;
Nate Begemanec48a1b2005-10-17 20:40:11 +00006865 // fold (fmul X, 2.0) -> (fadd X, X)
6866 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006867 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Dan Gohmanb7170912009-08-10 16:50:32 +00006868 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00006869 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00006870 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006871 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006872
Bill Wendling3dc5d242009-01-30 22:57:07 +00006873 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006874 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006875 &DAG.getTarget().Options)) {
Stephen Lincfe7f352013-07-08 00:37:03 +00006876 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006877 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006878 // Both can be negated for free, check to see if at least one is cheaper
6879 // negated.
6880 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006881 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006882 GetNegatedExpression(N0, DAG, LegalOperations),
6883 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006884 }
6885 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006886
Chris Lattner0199fd62007-01-08 23:04:05 +00006887 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006888 if (DAG.getTarget().Options.UnsafeFPMath &&
6889 N1CFP && N0.getOpcode() == ISD::FMUL &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006890 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006891 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6892 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Dale Johannesen400dc2e2009-02-06 21:50:26 +00006893 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006894
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006895 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006896}
6897
Owen Anderson41b06652012-05-02 22:17:40 +00006898SDValue DAGCombiner::visitFMA(SDNode *N) {
6899 SDValue N0 = N->getOperand(0);
6900 SDValue N1 = N->getOperand(1);
6901 SDValue N2 = N->getOperand(2);
6902 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6903 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6904 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006905 SDLoc dl(N);
Owen Anderson41b06652012-05-02 22:17:40 +00006906
Owen Anderson9d5a8c22014-08-02 08:45:33 +00006907
6908 // Constant fold FMA.
6909 if (isa<ConstantFPSDNode>(N0) &&
6910 isa<ConstantFPSDNode>(N1) &&
6911 isa<ConstantFPSDNode>(N2)) {
6912 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6913 }
6914
Owen Andersonb351c8d2012-11-01 02:00:53 +00006915 if (DAG.getTarget().Options.UnsafeFPMath) {
6916 if (N0CFP && N0CFP->isZero())
6917 return N2;
6918 if (N1CFP && N1CFP->isZero())
6919 return N2;
6920 }
Owen Anderson41b06652012-05-02 22:17:40 +00006921 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006922 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006923 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006924 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006925
Owen Andersonc7aaf522012-05-30 18:50:39 +00006926 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00006927 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006928 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00006929
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006930 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6931 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6932 N2.getOpcode() == ISD::FMUL &&
6933 N0 == N2.getOperand(0) &&
6934 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6935 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6936 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6937 }
6938
6939
6940 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6941 if (DAG.getTarget().Options.UnsafeFPMath &&
6942 N0.getOpcode() == ISD::FMUL && N1CFP &&
6943 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6944 return DAG.getNode(ISD::FMA, dl, VT,
6945 N0.getOperand(0),
6946 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6947 N2);
6948 }
6949
6950 // (fma x, 1, y) -> (fadd x, y)
6951 // (fma x, -1, y) -> (fadd (fneg x), y)
6952 if (N1CFP) {
6953 if (N1CFP->isExactlyValue(1.0))
6954 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6955
6956 if (N1CFP->isExactlyValue(-1.0) &&
6957 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6958 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006959 AddToWorklist(RHSNeg.getNode());
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006960 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6961 }
6962 }
6963
6964 // (fma x, c, x) -> (fmul x, (c+1))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006965 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6966 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006967 DAG.getNode(ISD::FADD, dl, VT,
6968 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006969
6970 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6971 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006972 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6973 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006974 DAG.getNode(ISD::FADD, dl, VT,
6975 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006976
6977
Owen Anderson41b06652012-05-02 22:17:40 +00006978 return SDValue();
6979}
6980
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006981SDValue DAGCombiner::visitFDIV(SDNode *N) {
6982 SDValue N0 = N->getOperand(0);
6983 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006984 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6985 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006986 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006987 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006988
Dan Gohmana8665142007-06-25 16:23:39 +00006989 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006990 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006991 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006992 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006993 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006994
Nate Begeman569c4392006-01-18 22:35:16 +00006995 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006996 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006997 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006998
Duncan Sands2f1dc382012-04-08 18:08:12 +00006999 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007000 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
Duncan Sands5f8397a2012-04-07 20:04:00 +00007001 // Compute the reciprocal 1.0 / c2.
7002 APFloat N1APF = N1CFP->getValueAPF();
7003 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7004 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
Duncan Sands4f530742012-04-10 20:35:27 +00007005 // Only do the transform if the reciprocal is a legal fp immediate that
7006 // isn't too nasty (eg NaN, denormal, ...).
7007 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
Anton Korobeynikov4d1220d2012-04-10 13:22:49 +00007008 (!LegalOperations ||
7009 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7010 // backend)... we should handle this gracefully after Legalize.
7011 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7012 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7013 TLI.isFPImmLegal(Recip, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007014 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
Duncan Sands5f8397a2012-04-07 20:04:00 +00007015 DAG.getConstantFP(Recip, VT));
7016 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007017
Bill Wendling3dc5d242009-01-30 22:57:07 +00007018 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007019 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00007020 &DAG.getTarget().Options)) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007021 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00007022 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00007023 // Both can be negated for free, check to see if at least one is cheaper
7024 // negated.
7025 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007026 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007027 GetNegatedExpression(N0, DAG, LegalOperations),
7028 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00007029 }
7030 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007031
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007032 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007033}
7034
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007035SDValue DAGCombiner::visitFREM(SDNode *N) {
7036 SDValue N0 = N->getOperand(0);
7037 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007038 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7039 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007040 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00007041
Nate Begeman569c4392006-01-18 22:35:16 +00007042 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007043 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007044 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00007045
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007046 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007047}
7048
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007049SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7050 SDValue N0 = N->getOperand(0);
7051 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007052 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7053 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007054 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00007055
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007056 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00007057 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007058
Chris Lattner3bc40502006-03-05 05:30:57 +00007059 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00007060 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00007061 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7062 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00007063 if (!V.isNegative()) {
7064 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007065 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00007066 } else {
7067 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007068 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7069 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00007070 }
Chris Lattner3bc40502006-03-05 05:30:57 +00007071 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007072
Chris Lattner3bc40502006-03-05 05:30:57 +00007073 // copysign(fabs(x), y) -> copysign(x, y)
7074 // copysign(fneg(x), y) -> copysign(x, y)
7075 // copysign(copysign(x,z), y) -> copysign(x, y)
7076 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7077 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007078 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007079 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007080
7081 // copysign(x, abs(y)) -> abs(x)
7082 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007083 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007084
Chris Lattner3bc40502006-03-05 05:30:57 +00007085 // copysign(x, copysign(y,z)) -> copysign(x, z)
7086 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007087 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007088 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007089
Chris Lattner3bc40502006-03-05 05:30:57 +00007090 // copysign(x, fp_extend(y)) -> copysign(x, y)
7091 // copysign(x, fp_round(y)) -> copysign(x, y)
7092 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007093 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007094 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007095
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007096 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00007097}
7098
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007099SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7100 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007101 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007102 EVT VT = N->getValueType(0);
7103 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007104
Nate Begeman21158fc2005-09-01 00:19:25 +00007105 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007106 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007107 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007108 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007109 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007110 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007111
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007112 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7113 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007114 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7115 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007116 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007117 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007118 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007119 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007120
Alp Tokercb402912014-01-24 17:20:08 +00007121 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007122 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007123 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7124 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7125 !VT.isVector() &&
7126 (!LegalOperations ||
7127 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7128 SDValue Ops[] =
7129 { N0.getOperand(0), N0.getOperand(1),
7130 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7131 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007132 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007133 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007134
Nadav Rotem90560762012-07-23 07:59:50 +00007135 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7136 // (select_cc x, y, 1.0, 0.0,, cc)
7137 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7138 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7139 (!LegalOperations ||
7140 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7141 SDValue Ops[] =
7142 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7143 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7144 N0.getOperand(0).getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007145 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007146 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007147 }
7148
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007149 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007150}
7151
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007152SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7153 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007154 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007155 EVT VT = N->getValueType(0);
7156 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00007157
Nate Begeman21158fc2005-09-01 00:19:25 +00007158 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007159 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007160 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007161 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007162 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007163 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007164
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007165 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7166 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007167 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7168 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007169 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007170 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007171 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007172 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007173
Alp Tokercb402912014-01-24 17:20:08 +00007174 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007175 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007176 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00007177
Nadav Rotem90560762012-07-23 07:59:50 +00007178 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7179 (!LegalOperations ||
7180 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7181 SDValue Ops[] =
7182 { N0.getOperand(0), N0.getOperand(1),
7183 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7184 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007185 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007186 }
7187 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007188
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007189 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007190}
7191
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007192SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7193 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007194 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007195 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007196
Nate Begeman21158fc2005-09-01 00:19:25 +00007197 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007198 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007199 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007200
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007201 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007202}
7203
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007204SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7205 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007206 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007207 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007208
Nate Begeman21158fc2005-09-01 00:19:25 +00007209 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007210 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007211 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007212
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007213 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007214}
7215
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007216SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7217 SDValue N0 = N->getOperand(0);
7218 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007219 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007220 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007221
Nate Begeman21158fc2005-09-01 00:19:25 +00007222 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007223 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007224 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007225
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007226 // fold (fp_round (fp_extend x)) -> x
7227 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7228 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007229
Chris Lattner0feb1b02008-01-24 06:45:35 +00007230 // fold (fp_round (fp_round x)) -> (fp_round x)
7231 if (N0.getOpcode() == ISD::FP_ROUND) {
7232 // This is a value preserving truncation if both round's are.
7233 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00007234 N0.getNode()->getConstantOperandVal(1) == 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00007235 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0feb1b02008-01-24 06:45:35 +00007236 DAG.getIntPtrConstant(IsTrunc));
7237 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007238
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007239 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00007240 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007241 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007242 N0.getOperand(0), N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007243 AddToWorklist(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007244 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007245 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007246 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007247
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007248 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007249}
7250
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007251SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7252 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007253 EVT VT = N->getValueType(0);
7254 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007255 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007256
Nate Begeman21158fc2005-09-01 00:19:25 +00007257 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00007258 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00007259 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007260 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00007261 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007262
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007263 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007264}
7265
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007266SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7267 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007268 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007269 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007270
Chris Lattner5919b482007-12-29 06:55:23 +00007271 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007272 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00007273 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007274 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00007275
Nate Begeman21158fc2005-09-01 00:19:25 +00007276 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007277 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007278 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00007279
7280 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7281 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00007282 if (N0.getOpcode() == ISD::FP_ROUND
7283 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007284 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00007285 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00007286 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007287 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007288 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00007289 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00007290 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007291
Chris Lattner72733e52008-01-17 07:00:52 +00007292 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00007293 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover7f3e11e2014-07-16 15:37:24 +00007294 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007295 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007296 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007297 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007298 LN0->getBasePtr(), N0.getValueType(),
7299 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00007300 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00007301 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007302 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00007303 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00007304 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007305 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00007306 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00007307
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007308 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007309}
7310
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007311SDValue DAGCombiner::visitFNEG(SDNode *N) {
7312 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007313 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007314
Owen Anderson9d5a8c22014-08-02 08:45:33 +00007315 // Constant fold FNEG.
7316 if (isa<ConstantFPSDNode>(N0))
7317 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7318
Craig Topper82384612012-09-11 01:45:21 +00007319 if (VT.isVector()) {
7320 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7321 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper03f39772012-09-09 22:58:45 +00007322 }
7323
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007324 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7325 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007326 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00007327
Chris Lattner888560d2008-01-27 17:42:27 +00007328 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7329 // constant pool values.
Sanjay Patel2ef67442014-08-03 22:48:23 +00007330 // TODO: We can also optimize for vectors here, but we need to make sure
7331 // that the sign mask is created properly for each vector element.
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007332 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007333 !VT.isVector() &&
7334 N0.getNode()->hasOneUse() &&
7335 N0.getOperand(0).getValueType().isInteger()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007336 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007337 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007338 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007339 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007340 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007341 AddToWorklist(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007342 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007343 VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007344 }
7345 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007346
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007347 // (fneg (fmul c, x)) -> (fmul -c, x)
7348 if (N0.getOpcode() == ISD::FMUL) {
7349 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Tim Northover820e0412014-05-02 17:25:02 +00007350 if (CFP1) {
7351 APFloat CVal = CFP1->getValueAPF();
7352 CVal.changeSign();
7353 if (Level >= AfterLegalizeDAG &&
7354 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7355 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7356 return DAG.getNode(
7357 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7358 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7359 }
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007360 }
7361
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007362 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007363}
7364
Owen Andersona40319b2012-08-13 23:32:49 +00007365SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7366 SDValue N0 = N->getOperand(0);
7367 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7368 EVT VT = N->getValueType(0);
7369
7370 // fold (fceil c1) -> fceil(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007371 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007372 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007373
7374 return SDValue();
7375}
7376
7377SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7378 SDValue N0 = N->getOperand(0);
7379 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7380 EVT VT = N->getValueType(0);
7381
7382 // fold (ftrunc c1) -> ftrunc(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007383 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007384 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007385
7386 return SDValue();
7387}
7388
7389SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7390 SDValue N0 = N->getOperand(0);
7391 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7392 EVT VT = N->getValueType(0);
7393
7394 // fold (ffloor c1) -> ffloor(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007395 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007396 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007397
7398 return SDValue();
7399}
7400
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007401SDValue DAGCombiner::visitFABS(SDNode *N) {
7402 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007403 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007404 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007405
Craig Topper82384612012-09-11 01:45:21 +00007406 if (VT.isVector()) {
7407 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7408 if (FoldedVOp.getNode()) return FoldedVOp;
7409 }
7410
Nate Begeman21158fc2005-09-01 00:19:25 +00007411 // fold (fabs c1) -> fabs(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007412 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007413 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007414 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007415 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00007416 return N->getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007417 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007418 // fold (fabs (fcopysign x, y)) -> (fabs x)
7419 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007420 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007421
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007422 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00007423 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00007424 if (!TLI.isFAbsFree(VT) &&
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007425 N0.getOpcode() == ISD::BITCAST &&
7426 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007427 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007428 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007429 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007430 APInt SignMask;
7431 if (N0.getValueType().isVector()) {
7432 // For a vector, get a mask such as 0x7f... per scalar element
7433 // and splat it.
7434 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7435 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7436 } else {
7437 // For a scalar, just generate 0x7f...
7438 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7439 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00007440 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007441 DAG.getConstant(SignMask, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007442 AddToWorklist(Int.getNode());
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007443 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007444 }
7445 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007446
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007447 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007448}
7449
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007450SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7451 SDValue Chain = N->getOperand(0);
7452 SDValue N1 = N->getOperand(1);
7453 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007454
Dan Gohman82e80012009-11-17 00:47:23 +00007455 // If N is a constant we could fold this into a fallthrough or unconditional
7456 // branch. However that doesn't happen very often in normal code, because
7457 // Instcombine/SimplifyCFG should have handled the available opportunities.
7458 // If we did this folding here, it would be necessary to update the
7459 // MachineBasicBlock CFG, which is awkward.
7460
Nate Begeman7e7f4392006-02-01 07:19:44 +00007461 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7462 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007463 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00007464 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7465 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007466 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007467 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00007468 N1.getOperand(0), N1.getOperand(1), N2);
7469 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007470
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007471 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7472 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7473 (N1.getOperand(0).hasOneUse() &&
7474 N1.getOperand(0).getOpcode() == ISD::SRL))) {
Craig Topperc0196b12014-04-14 00:51:57 +00007475 SDNode *Trunc = nullptr;
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007476 if (N1.getOpcode() == ISD::TRUNCATE) {
7477 // Look pass the truncate.
7478 Trunc = N1.getNode();
7479 N1 = N1.getOperand(0);
7480 }
Evan Cheng166a4e62010-01-06 19:38:29 +00007481
Bill Wendlingaa28be62009-03-26 06:14:09 +00007482 // Match this pattern so that we can generate simpler code:
7483 //
7484 // %a = ...
7485 // %b = and i32 %a, 2
7486 // %c = srl i32 %b, 1
7487 // brcond i32 %c ...
7488 //
7489 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00007490 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00007491 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00007492 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00007493 // %c = setcc eq %b, 0
7494 // brcond %c ...
7495 //
7496 // This applies only when the AND constant value has one bit set and the
7497 // SRL constant is equal to the log2 of the AND constant. The back-end is
7498 // smart enough to convert the result into a TEST/JMP sequence.
7499 SDValue Op0 = N1.getOperand(0);
7500 SDValue Op1 = N1.getOperand(1);
7501
7502 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00007503 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00007504 SDValue AndOp1 = Op0.getOperand(1);
7505
7506 if (AndOp1.getOpcode() == ISD::Constant) {
7507 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7508
7509 if (AndConst.isPowerOf2() &&
7510 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7511 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007512 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00007513 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00007514 Op0, DAG.getConstant(0, Op0.getValueType()),
7515 ISD::SETNE);
7516
Andrew Trickef9de2a2013-05-25 02:42:55 +00007517 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00007518 MVT::Other, Chain, SetCC, N2);
7519 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7520 // will convert it back to (X & C1) >> C2.
7521 CombineTo(N, NewBRCond, false);
7522 // Truncate is dead.
Chandler Carruth18066972014-08-02 10:02:07 +00007523 if (Trunc)
7524 deleteAndRecombine(Trunc);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007525 // Replace the uses of SRL with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007526 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007527 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00007528 deleteAndRecombine(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00007529 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00007530 }
7531 }
7532 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007533
7534 if (Trunc)
7535 // Restore N1 if the above transformation doesn't match.
7536 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007537 }
Wesley Peck527da1b2010-11-23 03:31:01 +00007538
Evan Cheng228c31f2010-02-27 07:36:59 +00007539 // Transform br(xor(x, y)) -> br(x != y)
7540 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7541 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7542 SDNode *TheXor = N1.getNode();
7543 SDValue Op0 = TheXor->getOperand(0);
7544 SDValue Op1 = TheXor->getOperand(1);
7545 if (Op0.getOpcode() == Op1.getOpcode()) {
7546 // Avoid missing important xor optimizations.
7547 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007548 if (Tmp.getNode()) {
7549 if (Tmp.getNode() != TheXor) {
7550 DEBUG(dbgs() << "\nReplacing.8 ";
7551 TheXor->dump(&DAG);
7552 dbgs() << "\nWith: ";
7553 Tmp.getNode()->dump(&DAG);
7554 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007555 WorklistRemover DeadNodes(*this);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007556 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
Chandler Carruth18066972014-08-02 10:02:07 +00007557 deleteAndRecombine(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007558 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00007559 MVT::Other, Chain, Tmp, N2);
7560 }
7561
Benjamin Kramer93354432013-03-30 21:28:18 +00007562 // visitXOR has changed XOR's operands or replaced the XOR completely,
7563 // bail out.
7564 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00007565 }
7566 }
7567
7568 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7569 bool Equal = false;
7570 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7571 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7572 Op0.getOpcode() == ISD::XOR) {
7573 TheXor = Op0.getNode();
7574 Equal = true;
7575 }
7576
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007577 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00007578 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00007579 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007580 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00007581 SetCCVT,
7582 Op0, Op1,
7583 Equal ? ISD::SETEQ : ISD::SETNE);
7584 // Replace the uses of XOR with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007585 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007586 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00007587 deleteAndRecombine(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007588 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00007589 MVT::Other, Chain, SetCC, N2);
7590 }
7591 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007592
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007593 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007594}
7595
Chris Lattnera49e16f2005-10-05 06:47:48 +00007596// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7597//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007598SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00007599 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007600 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007601
Dan Gohman82e80012009-11-17 00:47:23 +00007602 // If N is a constant we could fold this into a fallthrough or unconditional
7603 // branch. However that doesn't happen very often in normal code, because
7604 // Instcombine/SimplifyCFG should have handled the available opportunities.
7605 // If we did this folding here, it would be necessary to update the
7606 // MachineBasicBlock CFG, which is awkward.
7607
Duncan Sands93b66092008-06-09 11:32:28 +00007608 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00007609 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007610 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00007611 false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007612 if (Simp.getNode()) AddToWorklist(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00007613
Nate Begemanbd7df032005-10-05 21:43:42 +00007614 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00007615 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007616 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007617 N->getOperand(0), Simp.getOperand(2),
7618 Simp.getOperand(0), Simp.getOperand(1),
7619 N->getOperand(4));
7620
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007621 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007622}
7623
Evan Chengfa832632012-01-13 01:37:24 +00007624/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7625/// uses N as its base pointer and that N may be folded in the load / store
Evan Cheng80893ce2012-03-06 23:33:32 +00007626/// addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00007627static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7628 SelectionDAG &DAG,
7629 const TargetLowering &TLI) {
7630 EVT VT;
7631 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7632 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7633 return false;
7634 VT = Use->getValueType(0);
7635 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7636 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7637 return false;
7638 VT = ST->getValue().getValueType();
7639 } else
7640 return false;
7641
Chandler Carruth95f83e02013-01-07 15:14:13 +00007642 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00007643 if (N->getOpcode() == ISD::ADD) {
7644 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7645 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007646 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007647 AM.BaseOffs = Offset->getSExtValue();
7648 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007649 // [reg +/- reg]
7650 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007651 } else if (N->getOpcode() == ISD::SUB) {
7652 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7653 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007654 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007655 AM.BaseOffs = -Offset->getSExtValue();
7656 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007657 // [reg +/- reg]
7658 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007659 } else
7660 return false;
7661
7662 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7663}
7664
Duncan Sands075293f2008-06-15 20:12:31 +00007665/// CombineToPreIndexedLoadStore - Try turning a load / store into a
7666/// pre-indexed load / store when the base pointer is an add or subtract
Chris Lattnerffad2162006-11-11 00:39:41 +00007667/// and it has other uses besides the load / store. After the
7668/// transformation, the new indexed load / store has effectively folded
7669/// the add / subtract in and all of its other uses are redirected to the
7670/// new load / store.
7671bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007672 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007673 return false;
7674
7675 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007676 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007677 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007678 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007679 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007680 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007681 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00007682 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00007683 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7684 return false;
7685 Ptr = LD->getBasePtr();
7686 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007687 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007688 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007689 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007690 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7691 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7692 return false;
7693 Ptr = ST->getBasePtr();
7694 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007695 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007696 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007697 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007698
Chris Lattnereabc15c2006-11-11 00:56:29 +00007699 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7700 // out. There is no reason to make this a preinc/predec.
7701 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00007702 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007703 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007704
Chris Lattnereabc15c2006-11-11 00:56:29 +00007705 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007706 SDValue BasePtr;
7707 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007708 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7709 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7710 return false;
Hal Finkel25819052013-02-08 21:35:47 +00007711
7712 // Backends without true r+i pre-indexed forms may need to pass a
7713 // constant base with a variable offset so that constant coercion
7714 // will work with the patterns in canonical form.
7715 bool Swapped = false;
7716 if (isa<ConstantSDNode>(BasePtr)) {
7717 std::swap(BasePtr, Offset);
7718 Swapped = true;
7719 }
7720
Evan Cheng044a0a82007-05-03 23:52:19 +00007721 // Don't create a indexed load / store with zero offset.
7722 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007723 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007724 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007725
Chris Lattnera0a80032006-11-11 01:00:15 +00007726 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00007727 // 1) The new base ptr is a frame index.
7728 // 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 +00007729 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00007730 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00007731 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00007732 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00007733
Chris Lattnera0a80032006-11-11 01:00:15 +00007734 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7735 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00007736 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00007737 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007738
Chris Lattnera0a80032006-11-11 01:00:15 +00007739 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007740 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007741 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00007742 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007743 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007744 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007745
Hal Finkel25819052013-02-08 21:35:47 +00007746 // If the offset is a constant, there may be other adds of constants that
7747 // can be folded with this one. We should do this to avoid having to keep
7748 // a copy of the original base pointer.
7749 SmallVector<SDNode *, 16> OtherUses;
7750 if (isa<ConstantSDNode>(Offset))
Jim Grosbache8160032014-04-11 01:13:13 +00007751 for (SDNode *Use : BasePtr.getNode()->uses()) {
Hal Finkel25819052013-02-08 21:35:47 +00007752 if (Use == Ptr.getNode())
7753 continue;
7754
7755 if (Use->isPredecessorOf(N))
7756 continue;
7757
7758 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7759 OtherUses.clear();
7760 break;
7761 }
7762
7763 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7764 if (Op1.getNode() == BasePtr.getNode())
7765 std::swap(Op0, Op1);
7766 assert(Op0.getNode() == BasePtr.getNode() &&
7767 "Use of ADD/SUB but not an operand");
7768
7769 if (!isa<ConstantSDNode>(Op1)) {
7770 OtherUses.clear();
7771 break;
7772 }
7773
7774 // FIXME: In some cases, we can be smarter about this.
7775 if (Op1.getValueType() != Offset.getValueType()) {
7776 OtherUses.clear();
7777 break;
7778 }
7779
7780 OtherUses.push_back(Use);
7781 }
7782
7783 if (Swapped)
7784 std::swap(BasePtr, Offset);
7785
Evan Chenga4d187b2007-05-24 02:35:39 +00007786 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007787 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00007788
7789 // Caches for hasPredecessorHelper
7790 SmallPtrSet<const SDNode *, 32> Visited;
7791 SmallVector<const SDNode *, 16> Worklist;
7792
Jim Grosbache8160032014-04-11 01:13:13 +00007793 for (SDNode *Use : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007794 if (Use == N)
7795 continue;
Lang Hames5a004992011-07-07 04:31:51 +00007796 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007797 return false;
7798
Evan Chengfa832632012-01-13 01:37:24 +00007799 // If Ptr may be folded in addressing mode of other use, then it's
7800 // not profitable to do this transformation.
7801 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007802 RealUse = true;
7803 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007804
Chris Lattnereabc15c2006-11-11 00:56:29 +00007805 if (!RealUse)
7806 return false;
7807
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007808 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007809 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007810 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007811 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007812 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00007813 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007814 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007815 ++PreIndexedNodes;
7816 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007817 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007818 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007819 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007820 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007821 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007822 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007823 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007824 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7825 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007826 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007827 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007828 }
7829
Chris Lattnereabc15c2006-11-11 00:56:29 +00007830 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00007831 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007832
Hal Finkel25819052013-02-08 21:35:47 +00007833 if (Swapped)
7834 std::swap(BasePtr, Offset);
7835
7836 // Replace other uses of BasePtr that can be updated to use Ptr
7837 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7838 unsigned OffsetIdx = 1;
7839 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7840 OffsetIdx = 0;
7841 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7842 BasePtr.getNode() && "Expected BasePtr operand");
7843
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007844 // We need to replace ptr0 in the following expression:
7845 // x0 * offset0 + y0 * ptr0 = t0
7846 // knowing that
7847 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00007848 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007849 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7850 // indexed load/store and the expresion that needs to be re-written.
7851 //
7852 // Therefore, we have:
7853 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00007854
7855 ConstantSDNode *CN =
7856 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007857 int X0, X1, Y0, Y1;
7858 APInt Offset0 = CN->getAPIntValue();
7859 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00007860
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007861 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7862 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7863 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7864 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00007865
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007866 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7867
7868 APInt CNV = Offset0;
7869 if (X0 < 0) CNV = -CNV;
7870 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7871 else CNV = CNV - Offset1;
7872
7873 // We can now generate the new expression.
7874 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7875 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7876
7877 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00007878 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00007879 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7880 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
Chandler Carruth18066972014-08-02 10:02:07 +00007881 deleteAndRecombine(OtherUses[i]);
Hal Finkel25819052013-02-08 21:35:47 +00007882 }
7883
Chris Lattnereabc15c2006-11-11 00:56:29 +00007884 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007885 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00007886 deleteAndRecombine(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00007887
7888 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007889}
7890
Duncan Sands075293f2008-06-15 20:12:31 +00007891/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
Chris Lattnerffad2162006-11-11 00:39:41 +00007892/// add / sub of the base pointer node into a post-indexed load / store.
7893/// The transformation folded the add / subtract into the new indexed
7894/// load / store effectively and all of its uses are redirected to the
7895/// new load / store.
7896bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007897 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007898 return false;
7899
7900 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007901 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007902 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007903 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007904 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007905 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007906 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007907 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7908 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7909 return false;
7910 Ptr = LD->getBasePtr();
7911 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007912 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007913 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007914 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007915 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7916 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7917 return false;
7918 Ptr = ST->getBasePtr();
7919 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007920 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007921 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007922 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007923
Gabor Greiff304a7a2008-08-28 21:40:38 +00007924 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007925 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007926
Jim Grosbache8160032014-04-11 01:13:13 +00007927 for (SDNode *Op : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007928 if (Op == N ||
7929 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7930 continue;
7931
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007932 SDValue BasePtr;
7933 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007934 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7935 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00007936 // Don't create a indexed load / store with zero offset.
7937 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007938 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007939 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007940
Chris Lattnereabc15c2006-11-11 00:56:29 +00007941 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00007942 // 1) All uses are load / store ops that use it as base ptr (and
7943 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00007944 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7945 // nor a successor of N. Otherwise, if Op is folded that would
7946 // create a cycle.
7947
Evan Chengcfc05132009-05-06 18:25:01 +00007948 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7949 continue;
7950
Chris Lattnereabc15c2006-11-11 00:56:29 +00007951 // Check for #1.
7952 bool TryNext = false;
Jim Grosbache8160032014-04-11 01:13:13 +00007953 for (SDNode *Use : BasePtr.getNode()->uses()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007954 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00007955 continue;
7956
Chris Lattnereabc15c2006-11-11 00:56:29 +00007957 // If all the uses are load / store addresses, then don't do the
7958 // transformation.
7959 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7960 bool RealUse = false;
Jim Grosbache8160032014-04-11 01:13:13 +00007961 for (SDNode *UseUse : Use->uses()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00007962 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007963 RealUse = true;
7964 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007965
Chris Lattnereabc15c2006-11-11 00:56:29 +00007966 if (!RealUse) {
7967 TryNext = true;
7968 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00007969 }
7970 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007971 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007972
Chris Lattnereabc15c2006-11-11 00:56:29 +00007973 if (TryNext)
7974 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007975
Chris Lattnereabc15c2006-11-11 00:56:29 +00007976 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00007977 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007978 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00007979 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007980 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007981 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007982 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007983 ++PostIndexedNodes;
7984 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007985 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007986 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007987 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007988 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007989 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007990 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007991 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007992 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7993 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007994 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007995 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00007996 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007997
Chris Lattnereabc15c2006-11-11 00:56:29 +00007998 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00007999 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008000
8001 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008002 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008003 Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00008004 deleteAndRecombine(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008005 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00008006 }
8007 }
8008 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008009
Chris Lattnerffad2162006-11-11 00:39:41 +00008010 return false;
8011}
8012
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008013SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00008014 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008015 SDValue Chain = LD->getChain();
8016 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00008017
Evan Chenga684cd22007-05-01 00:38:21 +00008018 // If load is not volatile and there are no uses of the loaded value (and
8019 // the updated indexed value in case of indexed loads), change uses of the
8020 // chain value into uses of the chain input (i.e. delete the dead load).
8021 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00008022 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00008023 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00008024 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00008025 // It's not safe to use the two value CombineTo variant here. e.g.
8026 // v1, chain2 = load chain1, loc
8027 // v2, chain3 = load chain2, loc
8028 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00008029 // Now we replace use of chain2 with chain1. This makes the second load
8030 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00008031 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008032 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008033 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008034 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008035 dbgs() << "\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008036 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008037 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00008038
Chandler Carruth18066972014-08-02 10:02:07 +00008039 if (N->use_empty())
8040 deleteAndRecombine(N);
Bill Wendling306bfc22009-01-30 23:27:35 +00008041
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008042 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00008043 }
Evan Chengb68343c2007-05-01 08:53:39 +00008044 } else {
8045 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00008046 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Hal Finkel2c77fe52014-05-28 15:33:19 +00008047 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
Dale Johannesen84935752009-02-06 23:05:02 +00008048 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Evan Cheng228c31f2010-02-27 07:36:59 +00008049 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008050 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008051 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008052 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008053 dbgs() << " and 2 other values\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008054 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008055 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Hal Finkel2c77fe52014-05-28 15:33:19 +00008056 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
8057 DAG.getUNDEF(N->getValueType(1)));
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008058 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Chandler Carruth18066972014-08-02 10:02:07 +00008059 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008060 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00008061 }
Evan Chenga684cd22007-05-01 00:38:21 +00008062 }
8063 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008064
Chris Lattnere260ed82005-10-10 22:04:48 +00008065 // If this load is directly stored, replace the load value with the stored
8066 // value.
8067 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00008068 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00008069 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00008070 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00008071 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8072 if (PrevST->getBasePtr() == Ptr &&
8073 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00008074 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00008075 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00008076 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008077
Evan Cheng43cd9e32010-04-01 06:04:33 +00008078 // Try to infer better alignment information than the load already has.
8079 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00008080 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00008081 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8082 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00008083 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00008084 LD->getValueType(0),
8085 Chain, Ptr, LD->getPointerInfo(),
8086 LD->getMemoryVT(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00008087 LD->isVolatile(), LD->isNonTemporal(),
8088 LD->isInvariant(), Align, LD->getAAInfo());
Owen Andersonde89ecf2013-02-05 19:24:39 +00008089 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8090 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00008091 }
8092 }
8093
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00008094 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8095 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00008096#ifndef NDEBUG
8097 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8098 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8099 UseAA = false;
8100#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00008101 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00008102 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008103 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008104
Jim Laskey708d0db2006-10-04 16:53:27 +00008105 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00008106 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008107 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00008108
Jim Laskeyd07be232006-09-25 16:29:54 +00008109 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00008110 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008111 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008112 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008113 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008114 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00008115 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008116 BetterChain, Ptr, LD->getMemoryVT(),
8117 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008118 }
Jim Laskeyd07be232006-09-25 16:29:54 +00008119
Jim Laskey708d0db2006-10-04 16:53:27 +00008120 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008121 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00008122 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00008123
Nate Begeman879d8f12009-09-15 00:18:30 +00008124 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008125 AddToWorklist(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00008126
Jim Laskeydcf983c2006-10-13 23:32:28 +00008127 // Replace uses with load result and token factor. Don't add users
8128 // to work list.
8129 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00008130 }
8131 }
8132
Evan Cheng357017f2006-11-03 03:06:21 +00008133 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00008134 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008135 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00008136
Quentin Colombetde0e0622013-10-11 18:29:42 +00008137 // Try to slice up N to more direct loads if the slices are mapped to
8138 // different register banks or pairing can take place.
8139 if (SliceUpLoad(N))
8140 return SDValue(N, 0);
8141
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008142 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00008143}
8144
Quentin Colombetde0e0622013-10-11 18:29:42 +00008145namespace {
8146/// \brief Helper structure used to slice a load in smaller loads.
8147/// Basically a slice is obtained from the following sequence:
8148/// Origin = load Ty1, Base
8149/// Shift = srl Ty1 Origin, CstTy Amount
8150/// Inst = trunc Shift to Ty2
8151///
8152/// Then, it will be rewriten into:
8153/// Slice = load SliceTy, Base + SliceOffset
8154/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8155///
8156/// SliceTy is deduced from the number of bits that are actually used to
8157/// build Inst.
8158struct LoadedSlice {
8159 /// \brief Helper structure used to compute the cost of a slice.
8160 struct Cost {
8161 /// Are we optimizing for code size.
8162 bool ForCodeSize;
8163 /// Various cost.
8164 unsigned Loads;
8165 unsigned Truncates;
8166 unsigned CrossRegisterBanksCopies;
8167 unsigned ZExts;
8168 unsigned Shift;
8169
8170 Cost(bool ForCodeSize = false)
8171 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8172 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8173
8174 /// \brief Get the cost of one isolated slice.
8175 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8176 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8177 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8178 EVT TruncType = LS.Inst->getValueType(0);
8179 EVT LoadedType = LS.getLoadedType();
8180 if (TruncType != LoadedType &&
8181 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8182 ZExts = 1;
8183 }
8184
8185 /// \brief Account for slicing gain in the current cost.
8186 /// Slicing provide a few gains like removing a shift or a
8187 /// truncate. This method allows to grow the cost of the original
8188 /// load with the gain from this slice.
8189 void addSliceGain(const LoadedSlice &LS) {
8190 // Each slice saves a truncate.
8191 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8192 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8193 LS.Inst->getOperand(0).getValueType()))
8194 ++Truncates;
8195 // If there is a shift amount, this slice gets rid of it.
8196 if (LS.Shift)
8197 ++Shift;
8198 // If this slice can merge a cross register bank copy, account for it.
8199 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8200 ++CrossRegisterBanksCopies;
8201 }
8202
8203 Cost &operator+=(const Cost &RHS) {
8204 Loads += RHS.Loads;
8205 Truncates += RHS.Truncates;
8206 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8207 ZExts += RHS.ZExts;
8208 Shift += RHS.Shift;
8209 return *this;
8210 }
8211
8212 bool operator==(const Cost &RHS) const {
8213 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8214 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8215 ZExts == RHS.ZExts && Shift == RHS.Shift;
8216 }
8217
8218 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8219
8220 bool operator<(const Cost &RHS) const {
8221 // Assume cross register banks copies are as expensive as loads.
8222 // FIXME: Do we want some more target hooks?
8223 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8224 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8225 // Unless we are optimizing for code size, consider the
8226 // expensive operation first.
8227 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8228 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8229 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8230 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8231 }
8232
8233 bool operator>(const Cost &RHS) const { return RHS < *this; }
8234
8235 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8236
8237 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8238 };
8239 // The last instruction that represent the slice. This should be a
8240 // truncate instruction.
8241 SDNode *Inst;
8242 // The original load instruction.
8243 LoadSDNode *Origin;
8244 // The right shift amount in bits from the original load.
8245 unsigned Shift;
8246 // The DAG from which Origin came from.
8247 // This is used to get some contextual information about legal types, etc.
8248 SelectionDAG *DAG;
8249
Craig Topperc0196b12014-04-14 00:51:57 +00008250 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8251 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
Quentin Colombetde0e0622013-10-11 18:29:42 +00008252 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8253
8254 LoadedSlice(const LoadedSlice &LS)
8255 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8256
8257 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8258 /// \return Result is \p BitWidth and has used bits set to 1 and
8259 /// not used bits set to 0.
8260 APInt getUsedBits() const {
8261 // Reproduce the trunc(lshr) sequence:
8262 // - Start from the truncated value.
8263 // - Zero extend to the desired bit width.
8264 // - Shift left.
8265 assert(Origin && "No original load to compare against.");
8266 unsigned BitWidth = Origin->getValueSizeInBits(0);
8267 assert(Inst && "This slice is not bound to an instruction");
8268 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8269 "Extracted slice is bigger than the whole type!");
8270 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8271 UsedBits.setAllBits();
8272 UsedBits = UsedBits.zext(BitWidth);
8273 UsedBits <<= Shift;
8274 return UsedBits;
8275 }
8276
8277 /// \brief Get the size of the slice to be loaded in bytes.
8278 unsigned getLoadedSize() const {
8279 unsigned SliceSize = getUsedBits().countPopulation();
8280 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8281 return SliceSize / 8;
8282 }
8283
8284 /// \brief Get the type that will be loaded for this slice.
8285 /// Note: This may not be the final type for the slice.
8286 EVT getLoadedType() const {
8287 assert(DAG && "Missing context");
8288 LLVMContext &Ctxt = *DAG->getContext();
8289 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8290 }
8291
8292 /// \brief Get the alignment of the load used for this slice.
8293 unsigned getAlignment() const {
8294 unsigned Alignment = Origin->getAlignment();
8295 unsigned Offset = getOffsetFromBase();
8296 if (Offset != 0)
8297 Alignment = MinAlign(Alignment, Alignment + Offset);
8298 return Alignment;
8299 }
8300
8301 /// \brief Check if this slice can be rewritten with legal operations.
8302 bool isLegal() const {
8303 // An invalid slice is not legal.
8304 if (!Origin || !Inst || !DAG)
8305 return false;
8306
8307 // Offsets are for indexed load only, we do not handle that.
8308 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8309 return false;
8310
8311 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8312
8313 // Check that the type is legal.
8314 EVT SliceType = getLoadedType();
8315 if (!TLI.isTypeLegal(SliceType))
8316 return false;
8317
8318 // Check that the load is legal for this type.
8319 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8320 return false;
8321
8322 // Check that the offset can be computed.
8323 // 1. Check its type.
8324 EVT PtrType = Origin->getBasePtr().getValueType();
8325 if (PtrType == MVT::Untyped || PtrType.isExtended())
8326 return false;
8327
8328 // 2. Check that it fits in the immediate.
8329 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8330 return false;
8331
8332 // 3. Check that the computation is legal.
8333 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8334 return false;
8335
8336 // Check that the zext is legal if it needs one.
8337 EVT TruncateType = Inst->getValueType(0);
8338 if (TruncateType != SliceType &&
8339 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8340 return false;
8341
8342 return true;
8343 }
8344
8345 /// \brief Get the offset in bytes of this slice in the original chunk of
8346 /// bits.
Craig Topperc0196b12014-04-14 00:51:57 +00008347 /// \pre DAG != nullptr.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008348 uint64_t getOffsetFromBase() const {
8349 assert(DAG && "Missing context.");
8350 bool IsBigEndian =
8351 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8352 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8353 uint64_t Offset = Shift / 8;
8354 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8355 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8356 "The size of the original loaded type is not a multiple of a"
8357 " byte.");
8358 // If Offset is bigger than TySizeInBytes, it means we are loading all
8359 // zeros. This should have been optimized before in the process.
8360 assert(TySizeInBytes > Offset &&
8361 "Invalid shift amount for given loaded size");
8362 if (IsBigEndian)
8363 Offset = TySizeInBytes - Offset - getLoadedSize();
8364 return Offset;
8365 }
8366
8367 /// \brief Generate the sequence of instructions to load the slice
8368 /// represented by this object and redirect the uses of this slice to
8369 /// this new sequence of instructions.
8370 /// \pre this->Inst && this->Origin are valid Instructions and this
8371 /// object passed the legal check: LoadedSlice::isLegal returned true.
8372 /// \return The last instruction of the sequence used to load the slice.
8373 SDValue loadSlice() const {
8374 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8375 const SDValue &OldBaseAddr = Origin->getBasePtr();
8376 SDValue BaseAddr = OldBaseAddr;
8377 // Get the offset in that chunk of bytes w.r.t. the endianess.
8378 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8379 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8380 if (Offset) {
8381 // BaseAddr = BaseAddr + Offset.
8382 EVT ArithType = BaseAddr.getValueType();
8383 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8384 DAG->getConstant(Offset, ArithType));
8385 }
8386
8387 // Create the type of the loaded slice according to its size.
8388 EVT SliceType = getLoadedType();
8389
8390 // Create the load for the slice.
8391 SDValue LastInst = DAG->getLoad(
8392 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8393 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8394 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8395 // If the final type is not the same as the loaded type, this means that
8396 // we have to pad with zero. Create a zero extend for that.
8397 EVT FinalType = Inst->getValueType(0);
8398 if (SliceType != FinalType)
8399 LastInst =
8400 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8401 return LastInst;
8402 }
8403
8404 /// \brief Check if this slice can be merged with an expensive cross register
8405 /// bank copy. E.g.,
8406 /// i = load i32
8407 /// f = bitcast i32 i to float
8408 bool canMergeExpensiveCrossRegisterBankCopy() const {
8409 if (!Inst || !Inst->hasOneUse())
8410 return false;
8411 SDNode *Use = *Inst->use_begin();
8412 if (Use->getOpcode() != ISD::BITCAST)
8413 return false;
8414 assert(DAG && "Missing context");
8415 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8416 EVT ResVT = Use->getValueType(0);
8417 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8418 const TargetRegisterClass *ArgRC =
8419 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8420 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8421 return false;
8422
8423 // At this point, we know that we perform a cross-register-bank copy.
8424 // Check if it is expensive.
Eric Christopherd9134482014-08-04 21:25:23 +00008425 const TargetRegisterInfo *TRI =
8426 TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo();
Quentin Colombetde0e0622013-10-11 18:29:42 +00008427 // Assume bitcasts are cheap, unless both register classes do not
8428 // explicitly share a common sub class.
8429 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8430 return false;
8431
8432 // Check if it will be merged with the load.
8433 // 1. Check the alignment constraint.
8434 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8435 ResVT.getTypeForEVT(*DAG->getContext()));
8436
8437 if (RequiredAlignment > getAlignment())
8438 return false;
8439
8440 // 2. Check that the load is a legal operation for that type.
8441 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8442 return false;
8443
8444 // 3. Check that we do not have a zext in the way.
8445 if (Inst->getValueType(0) != getLoadedType())
8446 return false;
8447
8448 return true;
8449 }
8450};
8451}
8452
Quentin Colombetde0e0622013-10-11 18:29:42 +00008453/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8454/// \p UsedBits looks like 0..0 1..1 0..0.
8455static bool areUsedBitsDense(const APInt &UsedBits) {
8456 // If all the bits are one, this is dense!
8457 if (UsedBits.isAllOnesValue())
8458 return true;
8459
8460 // Get rid of the unused bits on the right.
8461 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8462 // Get rid of the unused bits on the left.
8463 if (NarrowedUsedBits.countLeadingZeros())
8464 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8465 // Check that the chunk of bits is completely used.
8466 return NarrowedUsedBits.isAllOnesValue();
8467}
8468
8469/// \brief Check whether or not \p First and \p Second are next to each other
8470/// in memory. This means that there is no hole between the bits loaded
8471/// by \p First and the bits loaded by \p Second.
8472static bool areSlicesNextToEachOther(const LoadedSlice &First,
8473 const LoadedSlice &Second) {
8474 assert(First.Origin == Second.Origin && First.Origin &&
8475 "Unable to match different memory origins.");
8476 APInt UsedBits = First.getUsedBits();
8477 assert((UsedBits & Second.getUsedBits()) == 0 &&
8478 "Slices are not supposed to overlap.");
8479 UsedBits |= Second.getUsedBits();
8480 return areUsedBitsDense(UsedBits);
8481}
8482
8483/// \brief Adjust the \p GlobalLSCost according to the target
8484/// paring capabilities and the layout of the slices.
8485/// \pre \p GlobalLSCost should account for at least as many loads as
8486/// there is in the slices in \p LoadedSlices.
8487static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8488 LoadedSlice::Cost &GlobalLSCost) {
8489 unsigned NumberOfSlices = LoadedSlices.size();
8490 // If there is less than 2 elements, no pairing is possible.
8491 if (NumberOfSlices < 2)
8492 return;
8493
8494 // Sort the slices so that elements that are likely to be next to each
8495 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00008496 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8497 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8498 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8499 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8500 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00008501 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8502 // First (resp. Second) is the first (resp. Second) potentially candidate
8503 // to be placed in a paired load.
Craig Topperc0196b12014-04-14 00:51:57 +00008504 const LoadedSlice *First = nullptr;
8505 const LoadedSlice *Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008506 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8507 // Set the beginning of the pair.
8508 First = Second) {
8509
8510 Second = &LoadedSlices[CurrSlice];
8511
8512 // If First is NULL, it means we start a new pair.
8513 // Get to the next slice.
8514 if (!First)
8515 continue;
8516
8517 EVT LoadedType = First->getLoadedType();
8518
8519 // If the types of the slices are different, we cannot pair them.
8520 if (LoadedType != Second->getLoadedType())
8521 continue;
8522
8523 // Check if the target supplies paired loads for this type.
8524 unsigned RequiredAlignment = 0;
8525 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8526 // move to the next pair, this type is hopeless.
Craig Topperc0196b12014-04-14 00:51:57 +00008527 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008528 continue;
8529 }
8530 // Check if we meet the alignment requirement.
8531 if (RequiredAlignment > First->getAlignment())
8532 continue;
8533
8534 // Check that both loads are next to each other in memory.
8535 if (!areSlicesNextToEachOther(*First, *Second))
8536 continue;
8537
8538 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8539 --GlobalLSCost.Loads;
8540 // Move to the next pair.
Craig Topperc0196b12014-04-14 00:51:57 +00008541 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008542 }
8543}
8544
8545/// \brief Check the profitability of all involved LoadedSlice.
8546/// Currently, it is considered profitable if there is exactly two
8547/// involved slices (1) which are (2) next to each other in memory, and
8548/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8549///
8550/// Note: The order of the elements in \p LoadedSlices may be modified, but not
8551/// the elements themselves.
8552///
8553/// FIXME: When the cost model will be mature enough, we can relax
8554/// constraints (1) and (2).
8555static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8556 const APInt &UsedBits, bool ForCodeSize) {
8557 unsigned NumberOfSlices = LoadedSlices.size();
8558 if (StressLoadSlicing)
8559 return NumberOfSlices > 1;
8560
8561 // Check (1).
8562 if (NumberOfSlices != 2)
8563 return false;
8564
8565 // Check (2).
8566 if (!areUsedBitsDense(UsedBits))
8567 return false;
8568
8569 // Check (3).
8570 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8571 // The original code has one big load.
8572 OrigCost.Loads = 1;
8573 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8574 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8575 // Accumulate the cost of all the slices.
8576 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8577 GlobalSlicingCost += SliceCost;
8578
8579 // Account as cost in the original configuration the gain obtained
8580 // with the current slices.
8581 OrigCost.addSliceGain(LS);
8582 }
8583
8584 // If the target supports paired load, adjust the cost accordingly.
8585 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8586 return OrigCost > GlobalSlicingCost;
8587}
8588
8589/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8590/// operations, split it in the various pieces being extracted.
8591///
8592/// This sort of thing is introduced by SROA.
8593/// This slicing takes care not to insert overlapping loads.
8594/// \pre LI is a simple load (i.e., not an atomic or volatile load).
8595bool DAGCombiner::SliceUpLoad(SDNode *N) {
8596 if (Level < AfterLegalizeDAG)
8597 return false;
8598
8599 LoadSDNode *LD = cast<LoadSDNode>(N);
8600 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8601 !LD->getValueType(0).isInteger())
8602 return false;
8603
8604 // Keep track of already used bits to detect overlapping values.
8605 // In that case, we will just abort the transformation.
8606 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8607
8608 SmallVector<LoadedSlice, 4> LoadedSlices;
8609
8610 // Check if this load is used as several smaller chunks of bits.
8611 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8612 // of computation for each trunc.
8613 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8614 UI != UIEnd; ++UI) {
8615 // Skip the uses of the chain.
8616 if (UI.getUse().getResNo() != 0)
8617 continue;
8618
8619 SDNode *User = *UI;
8620 unsigned Shift = 0;
8621
8622 // Check if this is a trunc(lshr).
8623 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8624 isa<ConstantSDNode>(User->getOperand(1))) {
8625 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8626 User = *User->use_begin();
8627 }
8628
8629 // At this point, User is a Truncate, iff we encountered, trunc or
8630 // trunc(lshr).
8631 if (User->getOpcode() != ISD::TRUNCATE)
8632 return false;
8633
8634 // The width of the type must be a power of 2 and greater than 8-bits.
8635 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00008636 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00008637 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008638 unsigned Width = User->getValueSizeInBits(0);
8639 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8640 return 0;
8641
8642 // Build the slice for this chain of computations.
8643 LoadedSlice LS(User, LD, Shift, &DAG);
8644 APInt CurrentUsedBits = LS.getUsedBits();
8645
8646 // Check if this slice overlaps with another.
8647 if ((CurrentUsedBits & UsedBits) != 0)
8648 return false;
8649 // Update the bits used globally.
8650 UsedBits |= CurrentUsedBits;
8651
8652 // Check if the new slice would be legal.
8653 if (!LS.isLegal())
8654 return false;
8655
8656 // Record the slice.
8657 LoadedSlices.push_back(LS);
8658 }
8659
8660 // Abort slicing if it does not seem to be profitable.
8661 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8662 return false;
8663
8664 ++SlicedLoads;
8665
8666 // Rewrite each chain to use an independent load.
8667 // By construction, each chain can be represented by a unique load.
8668
8669 // Prepare the argument for the new token factor for all the slices.
8670 SmallVector<SDValue, 8> ArgChains;
8671 for (SmallVectorImpl<LoadedSlice>::const_iterator
8672 LSIt = LoadedSlices.begin(),
8673 LSItEnd = LoadedSlices.end();
8674 LSIt != LSItEnd; ++LSIt) {
8675 SDValue SliceInst = LSIt->loadSlice();
8676 CombineTo(LSIt->Inst, SliceInst, true);
8677 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8678 SliceInst = SliceInst.getOperand(0);
8679 assert(SliceInst->getOpcode() == ISD::LOAD &&
8680 "It takes more than a zext to get to the loaded slice!!");
8681 ArgChains.push_back(SliceInst.getValue(1));
8682 }
8683
8684 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +00008685 ArgChains);
Quentin Colombetde0e0622013-10-11 18:29:42 +00008686 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8687 return true;
8688}
8689
Chris Lattner4041ab62010-04-15 04:48:01 +00008690/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8691/// load is having specific bytes cleared out. If so, return the byte size
8692/// being masked out and the shift amount.
8693static std::pair<unsigned, unsigned>
8694CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8695 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008696
Chris Lattner4041ab62010-04-15 04:48:01 +00008697 // Check for the structure we're looking for.
8698 if (V->getOpcode() != ISD::AND ||
8699 !isa<ConstantSDNode>(V->getOperand(1)) ||
8700 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8701 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008702
Chris Lattner3245afd2010-04-15 06:10:49 +00008703 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00008704 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00008705 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00008706
Chris Lattner3245afd2010-04-15 06:10:49 +00008707 // The store should be chained directly to the load or be an operand of a
8708 // tokenfactor.
8709 if (LD == Chain.getNode())
8710 ; // ok.
8711 else if (Chain->getOpcode() != ISD::TokenFactor)
8712 return Result; // Fail.
8713 else {
8714 bool isOk = false;
8715 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8716 if (Chain->getOperand(i).getNode() == LD) {
8717 isOk = true;
8718 break;
8719 }
8720 if (!isOk) return Result;
8721 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008722
Chris Lattner4041ab62010-04-15 04:48:01 +00008723 // This only handles simple types.
8724 if (V.getValueType() != MVT::i16 &&
8725 V.getValueType() != MVT::i32 &&
8726 V.getValueType() != MVT::i64)
8727 return Result;
8728
8729 // Check the constant mask. Invert it so that the bits being masked out are
8730 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8731 // follow the sign bit for uniformity.
8732 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008733 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008734 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008735 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008736 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8737 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00008738
Chris Lattner4041ab62010-04-15 04:48:01 +00008739 // See if we have a continuous run of bits. If so, we have 0*1+0*
8740 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8741 return Result;
8742
8743 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8744 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8745 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00008746
Chris Lattner4041ab62010-04-15 04:48:01 +00008747 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8748 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00008749 case 1:
8750 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00008751 case 4: break;
8752 default: return Result; // All one mask, or 5-byte mask.
8753 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008754
Chris Lattner4041ab62010-04-15 04:48:01 +00008755 // Verify that the first bit starts at a multiple of mask so that the access
8756 // is aligned the same as the access width.
8757 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008758
Chris Lattner4041ab62010-04-15 04:48:01 +00008759 Result.first = MaskedBytes;
8760 Result.second = NotMaskTZ/8;
8761 return Result;
8762}
8763
8764
8765/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8766/// provides a value as specified by MaskInfo. If so, replace the specified
8767/// store with a narrower store of truncated IVal.
8768static SDNode *
8769ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8770 SDValue IVal, StoreSDNode *St,
8771 DAGCombiner *DC) {
8772 unsigned NumBytes = MaskInfo.first;
8773 unsigned ByteShift = MaskInfo.second;
8774 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00008775
Chris Lattner4041ab62010-04-15 04:48:01 +00008776 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8777 // that uses this. If not, this is not a replacement.
8778 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8779 ByteShift*8, (ByteShift+NumBytes)*8);
Craig Topperc0196b12014-04-14 00:51:57 +00008780 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008781
Chris Lattner4041ab62010-04-15 04:48:01 +00008782 // Check that it is legal on the target to do this. It is legal if the new
8783 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8784 // legalization.
8785 MVT VT = MVT::getIntegerVT(NumBytes*8);
8786 if (!DC->isTypeLegal(VT))
Craig Topperc0196b12014-04-14 00:51:57 +00008787 return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008788
Chris Lattner4041ab62010-04-15 04:48:01 +00008789 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8790 // shifted by ByteShift and truncated down to NumBytes.
8791 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008792 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00008793 DAG.getConstant(ByteShift*8,
8794 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00008795
8796 // Figure out the offset for the store and the alignment of the access.
8797 unsigned StOffset;
8798 unsigned NewAlign = St->getAlignment();
8799
8800 if (DAG.getTargetLoweringInfo().isLittleEndian())
8801 StOffset = ByteShift;
8802 else
8803 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00008804
Chris Lattner4041ab62010-04-15 04:48:01 +00008805 SDValue Ptr = St->getBasePtr();
8806 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008807 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00008808 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8809 NewAlign = MinAlign(NewAlign, StOffset);
8810 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008811
Chris Lattner4041ab62010-04-15 04:48:01 +00008812 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008813 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00008814
Chris Lattner4041ab62010-04-15 04:48:01 +00008815 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00008816 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00008817 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00008818 false, false, NewAlign).getNode();
8819}
8820
Evan Chenga9cda8a2009-05-28 00:35:15 +00008821
8822/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8823/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8824/// of the loaded bits, try narrowing the load and store if it would end up
8825/// being a win for performance or code size.
8826SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8827 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00008828 if (ST->isVolatile())
8829 return SDValue();
8830
Evan Chenga9cda8a2009-05-28 00:35:15 +00008831 SDValue Chain = ST->getChain();
8832 SDValue Value = ST->getValue();
8833 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00008834 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008835
8836 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +00008837 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008838
8839 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +00008840
Chris Lattner4041ab62010-04-15 04:48:01 +00008841 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8842 // is a byte mask indicating a consecutive number of bytes, check to see if
8843 // Y is known to provide just those bytes. If so, we try to replace the
8844 // load + replace + store sequence with a single (narrower) store, which makes
8845 // the load dead.
8846 if (Opc == ISD::OR) {
8847 std::pair<unsigned, unsigned> MaskedLoad;
8848 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8849 if (MaskedLoad.first)
8850 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8851 Value.getOperand(1), ST,this))
8852 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008853
Chris Lattner4041ab62010-04-15 04:48:01 +00008854 // Or is commutative, so try swapping X and Y.
8855 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8856 if (MaskedLoad.first)
8857 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8858 Value.getOperand(0), ST,this))
8859 return SDValue(NewST, 0);
8860 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008861
Evan Chenga9cda8a2009-05-28 00:35:15 +00008862 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8863 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +00008864 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008865
8866 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +00008867 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8868 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00008869 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008870 if (LD->getBasePtr() != Ptr ||
8871 LD->getPointerInfo().getAddrSpace() !=
8872 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +00008873 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008874
8875 // Find the type to narrow it the load / op / store to.
8876 SDValue N1 = Value.getOperand(1);
8877 unsigned BitWidth = N1.getValueSizeInBits();
8878 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8879 if (Opc == ISD::AND)
8880 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +00008881 if (Imm == 0 || Imm.isAllOnesValue())
8882 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008883 unsigned ShAmt = Imm.countTrailingZeros();
8884 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8885 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +00008886 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008887 while (NewBW < BitWidth &&
Evan Cheng6673ff02009-05-28 18:41:02 +00008888 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
Evan Chenga9cda8a2009-05-28 00:35:15 +00008889 TLI.isNarrowingProfitable(VT, NewVT))) {
8890 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +00008891 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008892 }
Evan Cheng6673ff02009-05-28 18:41:02 +00008893 if (NewBW >= BitWidth)
8894 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008895
8896 // If the lsb changed does not start at the type bitwidth boundary,
8897 // start at the previous one.
8898 if (ShAmt % NewBW)
8899 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +00008900 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8901 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008902 if ((Imm & Mask) == Imm) {
8903 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8904 if (Opc == ISD::AND)
8905 NewImm ^= APInt::getAllOnesValue(NewBW);
8906 uint64_t PtrOff = ShAmt / 8;
8907 // For big endian targets, we need to adjust the offset to the pointer to
8908 // load the correct bytes.
8909 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +00008910 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +00008911
8912 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +00008913 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008914 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +00008915 return SDValue();
8916
Andrew Trickef9de2a2013-05-25 02:42:55 +00008917 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008918 Ptr.getValueType(), Ptr,
8919 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008920 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008921 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008922 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008923 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008924 LD->isInvariant(), NewAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00008925 LD->getAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008926 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +00008927 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008928 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008929 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008930 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008931 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008932
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008933 AddToWorklist(NewPtr.getNode());
8934 AddToWorklist(NewLD.getNode());
8935 AddToWorklist(NewVal.getNode());
8936 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008937 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008938 ++OpsNarrowed;
8939 return NewST;
8940 }
8941 }
8942
Evan Cheng6673ff02009-05-28 18:41:02 +00008943 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008944}
8945
Evan Chengd42641c2011-02-02 01:06:55 +00008946/// TransformFPLoadStorePair - For a given floating point load / store pair,
8947/// if the load value isn't used by any other operations, then consider
8948/// transforming the pair to integer load / store operations if the target
8949/// deems the transformation profitable.
8950SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8951 StoreSDNode *ST = cast<StoreSDNode>(N);
8952 SDValue Chain = ST->getChain();
8953 SDValue Value = ST->getValue();
8954 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8955 Value.hasOneUse() &&
8956 Chain == SDValue(Value.getNode(), 1)) {
8957 LoadSDNode *LD = cast<LoadSDNode>(Value);
8958 EVT VT = LD->getMemoryVT();
8959 if (!VT.isFloatingPoint() ||
8960 VT != ST->getMemoryVT() ||
8961 LD->isNonTemporal() ||
8962 ST->isNonTemporal() ||
8963 LD->getPointerInfo().getAddrSpace() != 0 ||
8964 ST->getPointerInfo().getAddrSpace() != 0)
8965 return SDValue();
8966
8967 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8968 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8969 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8970 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8971 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8972 return SDValue();
8973
8974 unsigned LDAlign = LD->getAlignment();
8975 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +00008976 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008977 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +00008978 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8979 return SDValue();
8980
Andrew Trickef9de2a2013-05-25 02:42:55 +00008981 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +00008982 LD->getChain(), LD->getBasePtr(),
8983 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00008984 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +00008985
Andrew Trickef9de2a2013-05-25 02:42:55 +00008986 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +00008987 NewLD, ST->getBasePtr(),
8988 ST->getPointerInfo(),
8989 false, false, STAlign);
8990
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008991 AddToWorklist(NewLD.getNode());
8992 AddToWorklist(NewST.getNode());
8993 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008994 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +00008995 ++LdStFP2Int;
8996 return NewST;
8997 }
8998
8999 return SDValue();
9000}
9001
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009002/// Helper struct to parse and store a memory address as base + index + offset.
9003/// We ignore sign extensions when it is safe to do so.
9004/// The following two expressions are not equivalent. To differentiate we need
9005/// to store whether there was a sign extension involved in the index
9006/// computation.
9007/// (load (i64 add (i64 copyfromreg %c)
9008/// (i64 signextend (add (i8 load %index)
9009/// (i8 1))))
9010/// vs
9011///
9012/// (load (i64 add (i64 copyfromreg %c)
9013/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9014/// (i32 1)))))
9015struct BaseIndexOffset {
9016 SDValue Base;
9017 SDValue Index;
9018 int64_t Offset;
9019 bool IsIndexSignExt;
9020
9021 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9022
9023 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9024 bool IsIndexSignExt) :
9025 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9026
9027 bool equalBaseIndex(const BaseIndexOffset &Other) {
9028 return Other.Base == Base && Other.Index == Index &&
9029 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009030 }
9031
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009032 /// Parses tree in Ptr for base, index, offset addresses.
9033 static BaseIndexOffset match(SDValue Ptr) {
9034 bool IsIndexSignExt = false;
9035
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009036 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9037 // instruction, then it could be just the BASE or everything else we don't
9038 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009039 if (Ptr->getOpcode() != ISD::ADD)
9040 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9041
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009042 // We know that we have at least an ADD instruction. Try to pattern match
9043 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009044 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9045 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9046 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9047 IsIndexSignExt);
9048 }
9049
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009050 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +00009051 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009052 // (i64 add (i64 %array_ptr)
9053 // (i64 mul (i64 %induction_var)
9054 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +00009055 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009056 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009057
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009058 // Look at Base + Index + Offset cases.
9059 SDValue Base = Ptr->getOperand(0);
9060 SDValue IndexOffset = Ptr->getOperand(1);
9061
9062 // Skip signextends.
9063 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9064 IndexOffset = IndexOffset->getOperand(0);
9065 IsIndexSignExt = true;
9066 }
9067
9068 // Either the case of Base + Index (no offset) or something else.
9069 if (IndexOffset->getOpcode() != ISD::ADD)
9070 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9071
9072 // Now we have the case of Base + Index + offset.
9073 SDValue Index = IndexOffset->getOperand(0);
9074 SDValue Offset = IndexOffset->getOperand(1);
9075
9076 if (!isa<ConstantSDNode>(Offset))
9077 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9078
9079 // Ignore signextends.
9080 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9081 Index = Index->getOperand(0);
9082 IsIndexSignExt = true;
9083 } else IsIndexSignExt = false;
9084
9085 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9086 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9087 }
9088};
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009089
9090/// Holds a pointer to an LSBaseSDNode as well as information on where it
9091/// is located in a sequence of memory operations connected by a chain.
9092struct MemOpLink {
9093 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9094 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9095 // Ptr to the mem node.
9096 LSBaseSDNode *MemNode;
9097 // Offset from the base ptr.
9098 int64_t OffsetFromBase;
9099 // What is the sequence number of this mem node.
9100 // Lowest mem operand in the DAG starts at zero.
9101 unsigned SequenceNum;
9102};
9103
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009104bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9105 EVT MemVT = St->getMemoryVT();
9106 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009107 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9108 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009109
9110 // Don't merge vectors into wider inputs.
9111 if (MemVT.isVector() || !MemVT.isSimple())
9112 return false;
9113
9114 // Perform an early exit check. Do not bother looking at stored values that
9115 // are not constants or loads.
9116 SDValue StoredVal = St->getValue();
9117 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9118 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9119 !IsLoadSrc)
9120 return false;
9121
9122 // Only look at ends of store sequences.
Chandler Carruth94bd5532014-07-25 07:23:23 +00009123 SDValue Chain = SDValue(St, 0);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009124 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9125 return false;
9126
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009127 // This holds the base pointer, index, and the offset in bytes from the base
9128 // pointer.
9129 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009130
9131 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009132 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009133 return false;
9134
9135 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009136 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009137 return false;
9138
Nadav Rotem307d7672012-11-29 00:00:08 +00009139 // Save the LoadSDNodes that we find in the chain.
9140 // We need to make sure that these nodes do not interfere with
9141 // any of the store nodes.
9142 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9143
9144 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009145 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +00009146
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009147 // Walk up the chain and look for nodes with offsets from the same
9148 // base pointer. Stop when reaching an instruction with a different kind
9149 // or instruction which has a different base pointer.
9150 unsigned Seq = 0;
9151 StoreSDNode *Index = St;
9152 while (Index) {
9153 // If the chain has more than one use, then we can't reorder the mem ops.
Matt Arsenault197a1e22014-07-25 07:56:42 +00009154 if (Index != St && !SDValue(Index, 0)->hasOneUse())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009155 break;
9156
9157 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009158 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009159
9160 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009161 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009162 break;
9163
9164 // Check that the alignment is the same.
9165 if (Index->getAlignment() != St->getAlignment())
9166 break;
9167
9168 // The memory operands must not be volatile.
9169 if (Index->isVolatile() || Index->isIndexed())
9170 break;
9171
9172 // No truncation.
9173 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9174 if (St->isTruncatingStore())
9175 break;
9176
9177 // The stored memory type must be the same.
9178 if (Index->getMemoryVT() != MemVT)
9179 break;
9180
9181 // We do not allow unaligned stores because we want to prevent overriding
9182 // stores.
9183 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9184 break;
9185
9186 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009187 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009188
Nadav Rotem307d7672012-11-29 00:00:08 +00009189 // Find the next memory operand in the chain. If the next operand in the
9190 // chain is a store then move up and continue the scan with the next
9191 // memory operand. If the next operand is a load save it and use alias
9192 // information to check if it interferes with anything.
9193 SDNode *NextInChain = Index->getChain().getNode();
9194 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +00009195 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +00009196 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +00009197 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +00009198 break;
9199 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +00009200 if (Ldn->isVolatile()) {
Craig Topperc0196b12014-04-14 00:51:57 +00009201 Index = nullptr;
Bill Wendling9200bb02013-11-25 18:05:22 +00009202 break;
9203 }
9204
Nadav Rotem307d7672012-11-29 00:00:08 +00009205 // Save the load node for later. Continue the scan.
9206 AliasLoadNodes.push_back(Ldn);
9207 NextInChain = Ldn->getChain().getNode();
9208 continue;
9209 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00009210 Index = nullptr;
Nadav Rotem307d7672012-11-29 00:00:08 +00009211 break;
9212 }
9213 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009214 }
9215
9216 // Check if there is anything to merge.
9217 if (StoreNodes.size() < 2)
9218 return false;
9219
9220 // Sort the memory operands according to their distance from the base pointer.
9221 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009222 [](MemOpLink LHS, MemOpLink RHS) {
9223 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9224 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9225 LHS.SequenceNum > RHS.SequenceNum);
9226 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009227
9228 // Scan the memory operations on the chain and find the first non-consecutive
9229 // store memory address.
9230 unsigned LastConsecutiveStore = 0;
9231 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +00009232 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9233
9234 // Check that the addresses are consecutive starting from the second
9235 // element in the list of stores.
9236 if (i > 0) {
9237 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9238 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9239 break;
9240 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009241
Nadav Rotem307d7672012-11-29 00:00:08 +00009242 bool Alias = false;
9243 // Check if this store interferes with any of the loads that we found.
9244 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9245 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9246 Alias = true;
9247 break;
9248 }
Nadav Rotem307d7672012-11-29 00:00:08 +00009249 // We found a load that alias with this store. Stop the sequence.
9250 if (Alias)
9251 break;
9252
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009253 // Mark this node as useful.
9254 LastConsecutiveStore = i;
9255 }
9256
9257 // The node with the lowest store address.
9258 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9259
9260 // Store the constants into memory as one consecutive store.
9261 if (!IsLoadSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009262 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009263 unsigned LastLegalVectorType = 0;
9264 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009265 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9266 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9267 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009268
9269 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009270 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009271 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009272 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009273 } else {
Alp Tokerf907b892013-12-05 05:44:44 +00009274 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009275 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009276 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009277
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009278 // Find a legal type for the constant store.
9279 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9280 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9281 if (TLI.isTypeLegal(StoreTy))
9282 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009283 // Or check whether a truncstore is legal.
9284 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9285 TargetLowering::TypePromoteInteger) {
9286 EVT LegalizedStoredValueTy =
9287 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9288 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9289 LastLegalType = i+1;
9290 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009291
9292 // Find a legal type for the vector store.
9293 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9294 if (TLI.isTypeLegal(Ty))
9295 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009296 }
9297
Bob Wilson3365b802012-12-20 01:36:20 +00009298 // We only use vectors if the constant is known to be zero and the
9299 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009300 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +00009301 LastLegalVectorType = 0;
9302
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009303 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +00009304 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009305 return false;
9306
Nadav Rotem495b1a42013-02-14 18:28:52 +00009307 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009308 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9309
9310 // Make sure we have something to merge.
9311 if (NumElem < 2)
9312 return false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009313
9314 unsigned EarliestNodeUsed = 0;
9315 for (unsigned i=0; i < NumElem; ++i) {
9316 // Find a chain for the new wide-store operand. Notice that some
9317 // of the store nodes that we found may not be selected for inclusion
9318 // in the wide store. The chain we use needs to be the chain of the
9319 // earliest store node which is *used* and replaced by the wide store.
9320 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9321 EarliestNodeUsed = i;
9322 }
9323
9324 // The earliest Node in the DAG.
9325 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009326 SDLoc DL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009327
Nadav Rotemb27777f2012-10-04 22:35:15 +00009328 SDValue StoredVal;
9329 if (UseVector) {
9330 // Find a legal type for the vector store.
9331 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9332 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9333 StoredVal = DAG.getConstant(0, Ty);
9334 } else {
9335 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9336 APInt StoreInt(StoreBW, 0);
9337
9338 // Construct a single integer constant which is made of the smaller
9339 // constant inputs.
9340 bool IsLE = TLI.isLittleEndian();
9341 for (unsigned i = 0; i < NumElem ; ++i) {
9342 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9343 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9344 SDValue Val = St->getValue();
9345 StoreInt<<=ElementSizeBytes*8;
9346 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9347 StoreInt|=C->getAPIntValue().zext(StoreBW);
9348 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9349 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9350 } else {
9351 assert(false && "Invalid constant element type");
9352 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009353 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009354
9355 // Create the new Load and Store operations.
9356 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9357 StoredVal = DAG.getConstant(StoreInt, StoreTy);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009358 }
9359
Nadav Rotemb27777f2012-10-04 22:35:15 +00009360 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009361 FirstInChain->getBasePtr(),
9362 FirstInChain->getPointerInfo(),
9363 false, false,
9364 FirstInChain->getAlignment());
9365
9366 // Replace the first store with the new store
9367 CombineTo(EarliestOp, NewStore);
9368 // Erase all other stores.
9369 for (unsigned i = 0; i < NumElem ; ++i) {
9370 if (StoreNodes[i].MemNode == EarliestOp)
9371 continue;
9372 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Rafael Espindolac79532d2012-11-14 05:08:56 +00009373 // ReplaceAllUsesWith will replace all uses that existed when it was
9374 // called, but graph optimizations may cause new ones to appear. For
9375 // example, the case in pr14333 looks like
9376 //
9377 // St's chain -> St -> another store -> X
9378 //
9379 // And the only difference from St to the other store is the chain.
9380 // When we change it's chain to be St's chain they become identical,
9381 // get CSEed and the net result is that X is now a use of St.
9382 // Since we know that St is redundant, just iterate.
9383 while (!St->use_empty())
9384 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
Chandler Carruth18066972014-08-02 10:02:07 +00009385 deleteAndRecombine(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009386 }
9387
9388 return true;
9389 }
9390
9391 // Below we handle the case of multiple consecutive stores that
9392 // come from multiple consecutive loads. We merge them into a single
9393 // wide load and a single wide store.
9394
9395 // Look for load nodes which are used by the stored values.
9396 SmallVector<MemOpLink, 8> LoadNodes;
9397
9398 // Find acceptable loads. Loads need to have the same chain (token factor),
9399 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009400 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009401 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9402 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9403 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9404 if (!Ld) break;
9405
9406 // Loads must only have one use.
9407 if (!Ld->hasNUsesOfValue(1, 0))
9408 break;
9409
9410 // Check that the alignment is the same as the stores.
9411 if (Ld->getAlignment() != St->getAlignment())
9412 break;
9413
9414 // The memory operands must not be volatile.
9415 if (Ld->isVolatile() || Ld->isIndexed())
9416 break;
9417
9418 // We do not accept ext loads.
9419 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9420 break;
9421
9422 // The stored memory type must be the same.
9423 if (Ld->getMemoryVT() != MemVT)
9424 break;
9425
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009426 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009427 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009428 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009429 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009430 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009431 break;
9432 } else {
9433 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009434 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009435 }
9436
9437 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009438 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009439 }
9440
9441 if (LoadNodes.size() < 2)
9442 return false;
9443
James Molloyce45be02014-08-02 14:51:24 +00009444 // If we have load/store pair instructions and we only have two values,
9445 // don't bother.
9446 unsigned RequiredAlignment;
9447 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9448 St->getAlignment() >= RequiredAlignment)
9449 return false;
9450
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009451 // Scan the memory operations on the chain and find the first non-consecutive
9452 // load memory address. These variables hold the index in the store node
9453 // array.
9454 unsigned LastConsecutiveLoad = 0;
9455 // This variable refers to the size and not index in the array.
9456 unsigned LastLegalVectorType = 0;
9457 unsigned LastLegalIntegerType = 0;
9458 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +00009459 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9460 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9461 // All loads much share the same chain.
9462 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9463 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009464
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009465 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9466 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9467 break;
9468 LastConsecutiveLoad = i;
9469
9470 // Find a legal type for the vector store.
9471 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9472 if (TLI.isTypeLegal(StoreTy))
9473 LastLegalVectorType = i + 1;
9474
9475 // Find a legal type for the integer store.
9476 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9477 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9478 if (TLI.isTypeLegal(StoreTy))
9479 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009480 // Or check whether a truncstore and extload is legal.
9481 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9482 TargetLowering::TypePromoteInteger) {
9483 EVT LegalizedStoredValueTy =
9484 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9485 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9486 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9487 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9488 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9489 LastLegalIntegerType = i+1;
9490 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009491 }
9492
9493 // Only use vector types if the vector type is larger than the integer type.
9494 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009495 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009496 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9497
9498 // We add +1 here because the LastXXX variables refer to location while
9499 // the NumElem refers to array/index size.
9500 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9501 NumElem = std::min(LastLegalType, NumElem);
9502
9503 if (NumElem < 2)
9504 return false;
9505
9506 // The earliest Node in the DAG.
9507 unsigned EarliestNodeUsed = 0;
9508 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9509 for (unsigned i=1; i<NumElem; ++i) {
9510 // Find a chain for the new wide-store operand. Notice that some
9511 // of the store nodes that we found may not be selected for inclusion
9512 // in the wide store. The chain we use needs to be the chain of the
9513 // earliest store node which is *used* and replaced by the wide store.
9514 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9515 EarliestNodeUsed = i;
9516 }
9517
9518 // Find if it is better to use vectors or integers to load and store
9519 // to memory.
9520 EVT JointMemOpVT;
9521 if (UseVectorTy) {
9522 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9523 } else {
9524 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9525 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9526 }
9527
Andrew Trickef9de2a2013-05-25 02:42:55 +00009528 SDLoc LoadDL(LoadNodes[0].MemNode);
9529 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009530
9531 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9532 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9533 FirstLoad->getChain(),
9534 FirstLoad->getBasePtr(),
9535 FirstLoad->getPointerInfo(),
9536 false, false, false,
9537 FirstLoad->getAlignment());
9538
9539 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9540 FirstInChain->getBasePtr(),
9541 FirstInChain->getPointerInfo(), false, false,
9542 FirstInChain->getAlignment());
9543
Nadav Rotemac920662012-10-03 19:30:31 +00009544 // Replace one of the loads with the new load.
9545 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9546 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9547 SDValue(NewLoad.getNode(), 1));
9548
9549 // Remove the rest of the load chains.
9550 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009551 // Replace all chain users of the old load nodes with the chain of the new
9552 // load node.
9553 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +00009554 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9555 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009556
Nadav Rotemac920662012-10-03 19:30:31 +00009557 // Replace the first store with the new store.
9558 CombineTo(EarliestOp, NewStore);
9559 // Erase all other stores.
9560 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009561 // Remove all Store nodes.
9562 if (StoreNodes[i].MemNode == EarliestOp)
9563 continue;
9564 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9565 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
Chandler Carruth18066972014-08-02 10:02:07 +00009566 deleteAndRecombine(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009567 }
9568
9569 return true;
9570}
9571
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009572SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +00009573 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009574 SDValue Chain = ST->getChain();
9575 SDValue Value = ST->getValue();
9576 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009577
Evan Chenga4cf58a2007-05-07 21:27:48 +00009578 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +00009579 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +00009580 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009581 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +00009582 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009583 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009584 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00009585 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +00009586 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009587 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +00009588 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009589 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +00009590 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009591 ST->isNonTemporal(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00009592 ST->getAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +00009593 }
Owen Andersona5192842011-04-14 17:30:49 +00009594
Chris Lattner41c80e82011-04-09 02:32:02 +00009595 // Turn 'store undef, Ptr' -> nothing.
9596 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9597 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +00009598
Nate Begeman8e20c762006-12-11 02:23:46 +00009599 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +00009600 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00009601 // NOTE: If the original store is volatile, this transform must not increase
9602 // the number of stores. For example, on x86-32 an f64 can be stored in one
9603 // processor operation but an i64 (which is not legal) requires two. So the
9604 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +00009605 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009606 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +00009607 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00009608 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +00009609 case MVT::f16: // We don't do this for these yet.
9610 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +00009611 case MVT::f128:
9612 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +00009613 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009614 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +00009615 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009616 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +00009617 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +00009618 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009619 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009620 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +00009621 }
9622 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009623 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +00009624 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +00009625 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009626 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00009627 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +00009628 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009629 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009630 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +00009631 }
Owen Andersona5192842011-04-14 17:30:49 +00009632
Chris Lattner41c80e82011-04-09 02:32:02 +00009633 if (!ST->isVolatile() &&
9634 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +00009635 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +00009636 // argument passing. Since this is so common, custom legalize the
9637 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +00009638 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +00009639 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9640 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +00009641 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009642
Dan Gohman2af30632007-07-09 22:18:38 +00009643 unsigned Alignment = ST->getAlignment();
9644 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +00009645 bool isNonTemporal = ST->isNonTemporal();
Hal Finkelcc39b672014-07-24 12:16:19 +00009646 AAMDNodes AAInfo = ST->getAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +00009647
Andrew Trickef9de2a2013-05-25 02:42:55 +00009648 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +00009649 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00009650 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +00009651 ST->getAlignment(), AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009652 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +00009653 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +00009654 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009655 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +00009656 Ptr, ST->getPointerInfo().getWithOffset(4),
9657 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +00009658 Alignment, AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009659 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +00009660 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009661 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009662
Chris Lattnerb7524b62006-12-12 04:16:14 +00009663 break;
Evan Cheng21836982006-12-11 17:25:19 +00009664 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009665 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009666 }
9667
Evan Cheng43cd9e32010-04-01 06:04:33 +00009668 // Try to infer better alignment information than the store already has.
9669 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009670 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9671 if (Align > ST->getAlignment())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009672 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +00009673 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009674 ST->isVolatile(), ST->isNonTemporal(), Align,
Hal Finkelcc39b672014-07-24 12:16:19 +00009675 ST->getAAInfo());
Evan Cheng43cd9e32010-04-01 06:04:33 +00009676 }
9677 }
9678
Evan Chengd42641c2011-02-02 01:06:55 +00009679 // Try transforming a pair floating point load / store ops to integer
9680 // load / store ops.
9681 SDValue NewST = TransformFPLoadStorePair(N);
9682 if (NewST.getNode())
9683 return NewST;
9684
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00009685 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9686 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00009687#ifndef NDEBUG
9688 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9689 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9690 UseAA = false;
9691#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00009692 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009693 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009694 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009695
Jim Laskey708d0db2006-10-04 16:53:27 +00009696 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009697 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009698 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +00009699
9700 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009701 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009702 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009703 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009704 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009705 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009706 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009707 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009708
Jim Laskeyd07be232006-09-25 16:29:54 +00009709 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009710 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009711 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009712
Nate Begeman879d8f12009-09-15 00:18:30 +00009713 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009714 AddToWorklist(Token.getNode());
Nate Begeman879d8f12009-09-15 00:18:30 +00009715
Jim Laskeydcf983c2006-10-13 23:32:28 +00009716 // Don't add users to work list.
9717 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009718 }
Jim Laskey5d19d592006-09-21 16:28:59 +00009719 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009720
Evan Cheng33157702006-11-05 09:31:14 +00009721 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +00009722 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009723 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +00009724
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009725 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009726 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009727 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00009728 // See if we can simplify the input to this truncstore with knowledge that
9729 // only the low bits are being used. For example:
9730 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +00009731 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +00009732 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009733 APInt::getLowBitsSet(
9734 Value.getValueType().getScalarType().getSizeInBits(),
9735 ST->getMemoryVT().getScalarType().getSizeInBits()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009736 AddToWorklist(Value.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00009737 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009738 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009739 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +00009740
Chris Lattnerf47e3062007-10-13 06:58:48 +00009741 // Otherwise, see if we can simplify the operation with
9742 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00009743 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009744 APInt::getLowBitsSet(
9745 Value.getValueType().getScalarType().getSizeInBits(),
9746 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009747 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +00009748 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009749
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009750 // If this is a load followed by a store to the same location, then the store
9751 // is dead/noop.
9752 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009753 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009754 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +00009755 // There can't be any side effects between the load and store, such as
9756 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009757 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009758 // The store is dead, remove it.
9759 return Chain;
9760 }
9761 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009762
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009763 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9764 // truncating store. We can do this even if this is already a truncstore.
9765 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +00009766 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009767 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009768 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009769 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009770 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009771 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009772
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009773 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +00009774 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +00009775 if (!LegalTypes) {
9776 bool EverChanged = false;
9777
9778 do {
9779 // There can be multiple store sequences on the same chain.
9780 // Keep trying to merge store sequences until we are unable to do so
9781 // or until we merge the last store on the chain.
9782 bool Changed = MergeConsecutiveStores(ST);
9783 EverChanged |= Changed;
9784 if (!Changed) break;
9785 } while (ST->getOpcode() != ISD::DELETED_NODE);
9786
9787 if (EverChanged)
9788 return SDValue(N, 0);
9789 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009790
Evan Chenga9cda8a2009-05-28 00:35:15 +00009791 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +00009792}
9793
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009794SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9795 SDValue InVec = N->getOperand(0);
9796 SDValue InVal = N->getOperand(1);
9797 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009798 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009799
Bob Wilson42603952010-05-19 23:42:58 +00009800 // If the inserted element is an UNDEF, just use the input vector.
9801 if (InVal.getOpcode() == ISD::UNDEF)
9802 return InVec;
9803
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009804 EVT VT = InVec.getValueType();
9805
Owen Andersonb2c80da2011-02-25 21:41:48 +00009806 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009807 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9808 return SDValue();
9809
Eli Friedmanb7910b72011-09-09 21:04:06 +00009810 // Check that we know which element is being inserted
9811 if (!isa<ConstantSDNode>(EltNo))
9812 return SDValue();
9813 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009814
Andrea Di Biagiof99dd642014-06-09 16:54:41 +00009815 // Canonicalize insert_vector_elt dag nodes.
9816 // Example:
9817 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9818 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9819 //
9820 // Do this only if the child insert_vector node has one use; also
9821 // do this only if indices are both constants and Idx1 < Idx0.
9822 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9823 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9824 unsigned OtherElt =
9825 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9826 if (Elt < OtherElt) {
9827 // Swap nodes.
9828 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9829 InVec.getOperand(0), InVal, EltNo);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009830 AddToWorklist(NewOp.getNode());
Andrea Di Biagiof99dd642014-06-09 16:54:41 +00009831 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9832 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9833 }
9834 }
9835
Eli Friedmanb7910b72011-09-09 21:04:06 +00009836 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9837 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9838 // vector elements.
9839 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +00009840 // Do not combine these two vectors if the output vector will not replace
9841 // the input vector.
9842 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +00009843 Ops.append(InVec.getNode()->op_begin(),
9844 InVec.getNode()->op_end());
9845 } else if (InVec.getOpcode() == ISD::UNDEF) {
9846 unsigned NElts = VT.getVectorNumElements();
9847 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9848 } else {
9849 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +00009850 }
Eli Friedmanb7910b72011-09-09 21:04:06 +00009851
9852 // Insert the element
9853 if (Elt < Ops.size()) {
9854 // All the operands of BUILD_VECTOR must have the same type;
9855 // we enforce that here.
9856 EVT OpVT = Ops[0].getValueType();
9857 if (InVal.getValueType() != OpVT)
9858 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9859 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9860 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9861 Ops[Elt] = InVal;
9862 }
9863
9864 // Return the new vector
Craig Topper48d114b2014-04-26 18:35:24 +00009865 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
Chris Lattner5336a592006-03-19 01:27:56 +00009866}
9867
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +00009868SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9869 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9870 EVT ResultVT = EVE->getValueType(0);
9871 EVT VecEltVT = InVecVT.getVectorElementType();
9872 unsigned Align = OriginalLoad->getAlignment();
9873 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9874 VecEltVT.getTypeForEVT(*DAG.getContext()));
9875
9876 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9877 return SDValue();
9878
9879 Align = NewAlign;
9880
9881 SDValue NewPtr = OriginalLoad->getBasePtr();
9882 SDValue Offset;
9883 EVT PtrType = NewPtr.getValueType();
9884 MachinePointerInfo MPI;
9885 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9886 int Elt = ConstEltNo->getZExtValue();
9887 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9888 if (TLI.isBigEndian())
9889 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9890 Offset = DAG.getConstant(PtrOff, PtrType);
9891 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9892 } else {
9893 Offset = DAG.getNode(
9894 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9895 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9896 if (TLI.isBigEndian())
9897 Offset = DAG.getNode(
9898 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9899 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9900 MPI = OriginalLoad->getPointerInfo();
9901 }
9902 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9903
9904 // The replacement we need to do here is a little tricky: we need to
9905 // replace an extractelement of a load with a load.
9906 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9907 // Note that this replacement assumes that the extractvalue is the only
9908 // use of the load; that's okay because we don't want to perform this
9909 // transformation in other cases anyway.
9910 SDValue Load;
9911 SDValue Chain;
9912 if (ResultVT.bitsGT(VecEltVT)) {
9913 // If the result type of vextract is wider than the load, then issue an
9914 // extending load instead.
9915 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9916 ? ISD::ZEXTLOAD
9917 : ISD::EXTLOAD;
9918 Load = DAG.getExtLoad(
9919 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
9920 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9921 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9922 Chain = Load.getValue(1);
9923 } else {
9924 Load = DAG.getLoad(
9925 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9926 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9927 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9928 Chain = Load.getValue(1);
9929 if (ResultVT.bitsLT(VecEltVT))
9930 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9931 else
9932 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9933 }
9934 WorklistRemover DeadNodes(*this);
9935 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9936 SDValue To[] = { Load, Chain };
9937 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9938 // Since we're explicitly calling ReplaceAllUses, add the new node to the
9939 // worklist explicitly as well.
9940 AddToWorklist(Load.getNode());
9941 AddUsersToWorklist(Load.getNode()); // Add users too
9942 // Make sure to revisit this node to clean it up; it will usually be dead.
9943 AddToWorklist(EVE);
9944 ++OpsNarrowed;
9945 return SDValue(EVE, 0);
9946}
9947
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009948SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +00009949 // (vextract (scalar_to_vector val, 0) -> val
9950 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009951 EVT VT = InVec.getValueType();
9952 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +00009953
Duncan Sands6be291a2011-05-09 08:03:33 +00009954 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9955 // Check if the result type doesn't match the inserted element type. A
9956 // SCALAR_TO_VECTOR may truncate the inserted element and the
9957 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9958 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +00009959 if (InOp.getValueType() != NVT) {
9960 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +00009961 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +00009962 }
9963 return InOp;
9964 }
Evan Cheng1120279a2008-05-13 08:35:03 +00009965
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009966 SDValue EltNo = N->getOperand(1);
9967 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9968
9969 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9970 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +00009971 // we may introduce new vector instructions which are not backed by TD
9972 // patterns. For example on AVX, extracting elements from a wide vector
Hal Finkel02807592014-03-31 11:43:19 +00009973 // without using extract_subvector. However, if we can find an underlying
9974 // scalar value, then we can always use that.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009975 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Hal Finkel02807592014-03-31 11:43:19 +00009976 && ConstEltNo) {
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009977 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9978 int NumElem = VT.getVectorNumElements();
9979 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9980 // Find the new index to extract from.
9981 int OrigElt = SVOp->getMaskElt(Elt);
9982
9983 // Extracting an undef index is undef.
9984 if (OrigElt == -1)
9985 return DAG.getUNDEF(NVT);
9986
9987 // Select the right vector half to extract from.
Hal Finkel02807592014-03-31 11:43:19 +00009988 SDValue SVInVec;
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009989 if (OrigElt < NumElem) {
Hal Finkel02807592014-03-31 11:43:19 +00009990 SVInVec = InVec->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009991 } else {
Hal Finkel02807592014-03-31 11:43:19 +00009992 SVInVec = InVec->getOperand(1);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009993 OrigElt -= NumElem;
9994 }
9995
Hal Finkel02807592014-03-31 11:43:19 +00009996 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9997 SDValue InOp = SVInVec.getOperand(OrigElt);
9998 if (InOp.getValueType() != NVT) {
9999 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10000 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10001 }
10002
10003 return InOp;
10004 }
10005
10006 // FIXME: We should handle recursing on other vector shuffles and
10007 // scalar_to_vector here as well.
10008
10009 if (!LegalOperations) {
10010 EVT IndexTy = TLI.getVectorIdxTy();
10011 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10012 SVInVec, DAG.getConstant(OrigElt, IndexTy));
10013 }
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010014 }
10015
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010016 bool BCNumEltsChanged = false;
10017 EVT ExtVT = VT.getVectorElementType();
10018 EVT LVT = ExtVT;
10019
10020 // If the result of load has to be truncated, then it's not necessarily
10021 // profitable.
10022 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10023 return SDValue();
10024
10025 if (InVec.getOpcode() == ISD::BITCAST) {
10026 // Don't duplicate a load with other uses.
10027 if (!InVec.hasOneUse())
10028 return SDValue();
10029
10030 EVT BCVT = InVec.getOperand(0).getValueType();
10031 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10032 return SDValue();
10033 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10034 BCNumEltsChanged = true;
10035 InVec = InVec.getOperand(0);
10036 ExtVT = BCVT.getVectorElementType();
10037 }
10038
10039 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10040 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10041 ISD::isNormalLoad(InVec.getNode()) &&
10042 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10043 SDValue Index = N->getOperand(1);
10044 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10045 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10046 OrigLoad);
10047 }
10048
Evan Cheng1120279a2008-05-13 08:35:03 +000010049 // Perform only after legalization to ensure build_vector / vector_shuffle
10050 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010051 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000010052
Mon P Wangca6d6de2009-01-17 00:07:25 +000010053 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10054 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10055 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +000010056
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010057 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +000010058 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000010059
Craig Topperc0196b12014-04-14 00:51:57 +000010060 LoadSDNode *LN0 = nullptr;
10061 const ShuffleVectorSDNode *SVN = nullptr;
Bill Wendling27d9dd42009-01-30 23:36:47 +000010062 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010063 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +000010064 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +000010065 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +000010066 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +000010067 // Don't duplicate a load with other uses.
10068 if (!InVec.hasOneUse())
10069 return SDValue();
10070
Evan Cheng1120279a2008-05-13 08:35:03 +000010071 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +000010072 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010073 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10074 // =>
10075 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +000010076
Eli Friedmane96286c2011-12-26 22:49:32 +000010077 // Don't duplicate a load with other uses.
10078 if (!InVec.hasOneUse())
10079 return SDValue();
10080
Mon P Wangb5eb7202008-12-11 00:26:16 +000010081 // If the bit convert changed the number of elements, it is unsafe
10082 // to examine the mask.
10083 if (BCNumEltsChanged)
10084 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +000010085
10086 // Select the input vector, guarding against out of range extract vector.
10087 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +000010088 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +000010089 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10090
Eli Friedmane96286c2011-12-26 22:49:32 +000010091 if (InVec.getOpcode() == ISD::BITCAST) {
10092 // Don't duplicate a load with other uses.
10093 if (!InVec.hasOneUse())
10094 return SDValue();
10095
Evan Cheng1120279a2008-05-13 08:35:03 +000010096 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +000010097 }
Gabor Greiff304a7a2008-08-28 21:40:38 +000010098 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010099 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +000010100 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010101 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
Evan Cheng0de312d2007-10-06 08:19:55 +000010102 }
10103 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010104
Eli Friedmane96286c2011-12-26 22:49:32 +000010105 // Make sure we found a non-volatile load and the extractelement is
10106 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +000010107 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010108 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000010109
Eric Christopherc6418b12010-11-03 20:44:42 +000010110 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10111 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +000010112 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +000010113
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010114 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
Evan Cheng0de312d2007-10-06 08:19:55 +000010115 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010116
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010117 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000010118}
Evan Cheng0de312d2007-10-06 08:19:55 +000010119
Michael Liao6d106b72012-10-23 23:06:52 +000010120// Simplify (build_vec (ext )) to (bitcast (build_vec ))
10121SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10122 // We perform this optimization post type-legalization because
10123 // the type-legalizer often scalarizes integer-promoted vectors.
10124 // Performing this optimization before may create bit-casts which
10125 // will be type-legalized to complex code sequences.
10126 // We perform this optimization only before the operation legalizer because we
10127 // may introduce illegal operations.
10128 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10129 return SDValue();
10130
Dan Gohmana8665142007-06-25 16:23:39 +000010131 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010132 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +000010133 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010134
Nadav Rotembf6568b2011-10-29 21:23:04 +000010135 // Check to see if this is a BUILD_VECTOR of a bunch of values
10136 // which come from any_extend or zero_extend nodes. If so, we can create
10137 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +000010138 // optimizations. We do not handle sign-extend because we can't fill the sign
10139 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010140 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +000010141 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +000010142
Craig Topper02cb0fb2012-01-17 09:09:48 +000010143 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +000010144 SDValue In = N->getOperand(i);
10145 // Ignore undef inputs.
10146 if (In.getOpcode() == ISD::UNDEF) continue;
10147
10148 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10149 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10150
Nadav Rotemf3103612011-10-31 20:08:25 +000010151 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010152 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +000010153 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010154 break;
10155 }
10156
10157 // The input is a ZeroExt or AnyExt. Check the original type.
10158 EVT InTy = In.getOperand(0).getValueType();
10159
10160 // Check that all of the widened source types are the same.
10161 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +000010162 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010163 SourceType = InTy;
10164 else if (InTy != SourceType) {
10165 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +000010166 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010167 break;
10168 }
10169
10170 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +000010171 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010172 }
10173
Nadav Rotemf3103612011-10-31 20:08:25 +000010174 // In order to have valid types, all of the inputs must be extended from the
10175 // same source type and all of the inputs must be any or zero extend.
10176 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +000010177 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010178 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +000010179 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10180 isPowerOf2_32(SourceType.getSizeInBits());
10181
Nadav Rotem6fd1d322012-03-15 08:49:06 +000010182 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10183 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +000010184 if (!ValidTypes)
10185 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +000010186
Michael Liao6d106b72012-10-23 23:06:52 +000010187 bool isLE = TLI.isLittleEndian();
10188 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10189 assert(ElemRatio > 1 && "Invalid element size ratio");
10190 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10191 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010192
Michael Liao6d106b72012-10-23 23:06:52 +000010193 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10194 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010195
Michael Liao6d106b72012-10-23 23:06:52 +000010196 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +000010197 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +000010198 SDValue Cast = N->getOperand(i);
10199 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10200 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10201 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10202 SDValue In;
10203 if (Cast.getOpcode() == ISD::UNDEF)
10204 In = DAG.getUNDEF(SourceType);
10205 else
10206 In = Cast->getOperand(0);
10207 unsigned Index = isLE ? (i * ElemRatio) :
10208 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +000010209
Michael Liao6d106b72012-10-23 23:06:52 +000010210 assert(Index < Ops.size() && "Invalid index");
10211 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010212 }
Chris Lattner5336a592006-03-19 01:27:56 +000010213
Michael Liao6d106b72012-10-23 23:06:52 +000010214 // The type of the new BUILD_VECTOR node.
10215 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10216 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10217 "Invalid vector size");
10218 // Check if the new vector type is legal.
10219 if (!isTypeLegal(VecVT)) return SDValue();
10220
10221 // Make the new BUILD_VECTOR.
Craig Topper48d114b2014-04-26 18:35:24 +000010222 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
Michael Liao6d106b72012-10-23 23:06:52 +000010223
10224 // The new BUILD_VECTOR node has the potential to be further optimized.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010225 AddToWorklist(BV.getNode());
Michael Liao6d106b72012-10-23 23:06:52 +000010226 // Bitcast to the desired type.
10227 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10228}
10229
Michael Liao59229792012-10-24 04:14:18 +000010230SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10231 EVT VT = N->getValueType(0);
10232
10233 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010234 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +000010235
10236 EVT SrcVT = MVT::Other;
10237 unsigned Opcode = ISD::DELETED_NODE;
10238 unsigned NumDefs = 0;
10239
10240 for (unsigned i = 0; i != NumInScalars; ++i) {
10241 SDValue In = N->getOperand(i);
10242 unsigned Opc = In.getOpcode();
10243
10244 if (Opc == ISD::UNDEF)
10245 continue;
10246
10247 // If all scalar values are floats and converted from integers.
10248 if (Opcode == ISD::DELETED_NODE &&
10249 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10250 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +000010251 }
Tom Stellard567f8862013-01-02 22:13:01 +000010252
Michael Liao59229792012-10-24 04:14:18 +000010253 if (Opc != Opcode)
10254 return SDValue();
10255
10256 EVT InVT = In.getOperand(0).getValueType();
10257
10258 // If all scalar values are typed differently, bail out. It's chosen to
10259 // simplify BUILD_VECTOR of integer types.
10260 if (SrcVT == MVT::Other)
10261 SrcVT = InVT;
10262 if (SrcVT != InVT)
10263 return SDValue();
10264 NumDefs++;
10265 }
10266
10267 // If the vector has just one element defined, it's not worth to fold it into
10268 // a vectorized one.
10269 if (NumDefs < 2)
10270 return SDValue();
10271
10272 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10273 && "Should only handle conversion from integer to float.");
10274 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10275
10276 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000010277
10278 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10279 return SDValue();
10280
Michael Liao59229792012-10-24 04:14:18 +000010281 SmallVector<SDValue, 8> Opnds;
10282 for (unsigned i = 0; i != NumInScalars; ++i) {
10283 SDValue In = N->getOperand(i);
10284
10285 if (In.getOpcode() == ISD::UNDEF)
10286 Opnds.push_back(DAG.getUNDEF(SrcVT));
10287 else
10288 Opnds.push_back(In.getOperand(0));
10289 }
Craig Topper48d114b2014-04-26 18:35:24 +000010290 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010291 AddToWorklist(BV.getNode());
Michael Liao59229792012-10-24 04:14:18 +000010292
10293 return DAG.getNode(Opcode, dl, VT, BV);
10294}
10295
Michael Liao6d106b72012-10-23 23:06:52 +000010296SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10297 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010298 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000010299 EVT VT = N->getValueType(0);
10300
10301 // A vector built entirely of undefs is undef.
10302 if (ISD::allOperandsUndef(N))
10303 return DAG.getUNDEF(VT);
10304
10305 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10306 if (V.getNode())
10307 return V;
10308
Michael Liao59229792012-10-24 04:14:18 +000010309 V = reduceBuildVecConvertToConvertBuildVec(N);
10310 if (V.getNode())
10311 return V;
10312
Dan Gohmana8665142007-06-25 16:23:39 +000010313 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10314 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10315 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010316
10317 // May only combine to shuffle after legalize if shuffle is legal.
10318 if (LegalOperations &&
10319 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10320 return SDValue();
10321
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010322 SDValue VecIn1, VecIn2;
Chris Lattnerc9992542006-03-28 20:28:38 +000010323 for (unsigned i = 0; i != NumInScalars; ++i) {
10324 // Ignore undef inputs.
10325 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010326
Dan Gohmana8665142007-06-25 16:23:39 +000010327 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000010328 // constant index, bail out.
Dan Gohmana8665142007-06-25 16:23:39 +000010329 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Chris Lattnerc9992542006-03-28 20:28:38 +000010330 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
Craig Topperc0196b12014-04-14 00:51:57 +000010331 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010332 break;
10333 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010334
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010335 // We allow up to two distinct input vectors.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010336 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010337 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10338 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010339
Craig Topperc0196b12014-04-14 00:51:57 +000010340 if (!VecIn1.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010341 VecIn1 = ExtractedFromVec;
Craig Topperc0196b12014-04-14 00:51:57 +000010342 } else if (!VecIn2.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010343 VecIn2 = ExtractedFromVec;
10344 } else {
10345 // Too many inputs.
Craig Topperc0196b12014-04-14 00:51:57 +000010346 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010347 break;
10348 }
10349 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010350
Jim Grosbach2eb60fd2014-04-29 22:41:50 +000010351 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010352 if (VecIn1.getNode()) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010353 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000010354 for (unsigned i = 0; i != NumInScalars; ++i) {
10355 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010356 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010357 continue;
10358 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010359
Rafael Espindolab93db662009-04-24 12:40:33 +000010360 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010361 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000010362 SDValue ExtVal = Extract.getOperand(1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010363 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000010364 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10365 if (ExtIndex > VT.getVectorNumElements())
10366 return SDValue();
Wesley Peck527da1b2010-11-23 03:31:01 +000010367
Nate Begeman5f829d82009-04-29 05:20:52 +000010368 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000010369 continue;
10370 }
10371
10372 // Otherwise, use InIdx + VecSize
Mon P Wang523c0852009-03-17 06:33:10 +000010373 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010374 Mask.push_back(Idx+NumInScalars);
Chris Lattnerc9992542006-03-28 20:28:38 +000010375 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010376
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010377 // We can't generate a shuffle node with mismatched input and output types.
10378 // Attempt to transform a single input vector to the correct type.
10379 if ((VT != VecIn1.getValueType())) {
10380 // We don't support shuffeling between TWO values of different types.
Craig Topperc0196b12014-04-14 00:51:57 +000010381 if (VecIn2.getNode())
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010382 return SDValue();
10383
10384 // We only support widening of vectors which are half the size of the
10385 // output registers. For example XMM->YMM widening on X86 with AVX.
10386 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10387 return SDValue();
10388
James Molloy1e5c6112012-09-10 14:01:21 +000010389 // If the input vector type has a different base type to the output
10390 // vector type, bail out.
10391 if (VecIn1.getValueType().getVectorElementType() !=
10392 VT.getVectorElementType())
10393 return SDValue();
10394
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010395 // Widen the input vector by adding undef values.
Michael Liao6d106b72012-10-23 23:06:52 +000010396 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010397 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010398 }
10399
10400 // If VecIn2 is unused then change it to undef.
10401 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10402
Nadav Rotem841c9a82012-09-20 08:53:31 +000010403 // Check that we were able to transform all incoming values to the same
10404 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000010405 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10406 VecIn1.getValueType() != VT)
10407 return SDValue();
10408
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010409 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
Nadav Rotem0c650642012-02-13 12:42:26 +000010410 if (!isTypeLegal(VT))
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010411 return SDValue();
10412
Dan Gohmana8665142007-06-25 16:23:39 +000010413 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010414 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000010415 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010416 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000010417 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000010418 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010419
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010420 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000010421}
10422
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010423SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000010424 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10425 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10426 // inputs come from at most two distinct vectors, turn this into a shuffle
10427 // node.
10428
10429 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000010430 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000010431 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010432
Nadav Rotem01892102012-07-14 21:30:27 +000010433 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010434 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010435 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010436 return DAG.getUNDEF(VT);
10437
10438 // Optimize concat_vectors where one of the vectors is undef.
10439 if (N->getNumOperands() == 2 &&
10440 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10441 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000010442 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010443
10444 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10445 if (In->getOpcode() == ISD::BITCAST &&
10446 !In->getOperand(0)->getValueType(0).isVector()) {
10447 SDValue Scalar = In->getOperand(0);
10448 EVT SclTy = Scalar->getValueType(0);
10449
10450 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10451 return SDValue();
10452
10453 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10454 VT.getSizeInBits() / SclTy.getSizeInBits());
10455 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10456 return SDValue();
10457
10458 SDLoc dl = SDLoc(N);
10459 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10460 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10461 }
10462 }
Nadav Rotem01892102012-07-14 21:30:27 +000010463
Robert Lougher7d9084f2014-02-11 15:42:46 +000010464 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10465 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10466 if (N->getNumOperands() == 2 &&
10467 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10468 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10469 EVT VT = N->getValueType(0);
10470 SDValue N0 = N->getOperand(0);
10471 SDValue N1 = N->getOperand(1);
10472 SmallVector<SDValue, 8> Opnds;
10473 unsigned BuildVecNumElts = N0.getNumOperands();
10474
Hao Liu71224b02014-07-10 03:41:50 +000010475 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10476 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10477 if (SclTy0.isFloatingPoint()) {
10478 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10479 Opnds.push_back(N0.getOperand(i));
10480 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10481 Opnds.push_back(N1.getOperand(i));
10482 } else {
10483 // If BUILD_VECTOR are from built from integer, they may have different
10484 // operand types. Get the smaller type and truncate all operands to it.
10485 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10486 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10487 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10488 N0.getOperand(i)));
10489 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10490 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10491 N1.getOperand(i)));
10492 }
Robert Lougher7d9084f2014-02-11 15:42:46 +000010493
Craig Topper48d114b2014-04-26 18:35:24 +000010494 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Robert Lougher7d9084f2014-02-11 15:42:46 +000010495 }
10496
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010497 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10498 // nodes often generate nop CONCAT_VECTOR nodes.
10499 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10500 // place the incoming vectors at the exact same location.
10501 SDValue SingleSource = SDValue();
10502 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10503
10504 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10505 SDValue Op = N->getOperand(i);
10506
10507 if (Op.getOpcode() == ISD::UNDEF)
10508 continue;
10509
10510 // Check if this is the identity extract:
10511 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10512 return SDValue();
10513
10514 // Find the single incoming vector for the extract_subvector.
10515 if (SingleSource.getNode()) {
10516 if (Op.getOperand(0) != SingleSource)
10517 return SDValue();
10518 } else {
10519 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000010520
10521 // Check the source type is the same as the type of the result.
10522 // If not, this concat may extend the vector, so we can not
10523 // optimize it away.
10524 if (SingleSource.getValueType() != N->getValueType(0))
10525 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010526 }
10527
10528 unsigned IdentityIndex = i * PartNumElem;
10529 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10530 // The extract index must be constant.
10531 if (!CS)
10532 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000010533
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010534 // Check that we are reading from the identity index.
10535 if (CS->getZExtValue() != IdentityIndex)
10536 return SDValue();
10537 }
10538
10539 if (SingleSource.getNode())
10540 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000010541
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010542 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000010543}
10544
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010545SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10546 EVT NVT = N->getValueType(0);
10547 SDValue V = N->getOperand(0);
10548
Michael Liao7a442c802012-10-17 20:48:33 +000010549 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10550 // Combine:
10551 // (extract_subvec (concat V1, V2, ...), i)
10552 // Into:
10553 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000010554 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10555 // type.
Michael Liao2c235802012-10-19 03:17:00 +000010556 if (V->getOperand(0).getValueType() != NVT)
10557 return SDValue();
Michael Liao7a442c802012-10-17 20:48:33 +000010558 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10559 unsigned NumElems = NVT.getVectorNumElements();
10560 assert((Idx % NumElems) == 0 &&
10561 "IDX in concat is not a multiple of the result vector length.");
10562 return V->getOperand(Idx / NumElems);
10563 }
10564
Michael Liaobb05a1d2013-03-25 23:47:35 +000010565 // Skip bitcasting
10566 if (V->getOpcode() == ISD::BITCAST)
10567 V = V.getOperand(0);
10568
10569 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010570 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000010571 // Handle only simple case where vector being inserted and vector
10572 // being extracted are of same type, and are half size of larger vectors.
10573 EVT BigVT = V->getOperand(0).getValueType();
10574 EVT SmallVT = V->getOperand(1).getValueType();
10575 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10576 return SDValue();
10577
10578 // Only handle cases where both indexes are constants with the same type.
10579 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10580 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10581
10582 if (InsIdx && ExtIdx &&
10583 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10584 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10585 // Combine:
10586 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10587 // Into:
10588 // indices are equal or bit offsets are equal => V1
10589 // otherwise => (extract_subvec V1, ExtIdx)
10590 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10591 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10592 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10593 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10594 DAG.getNode(ISD::BITCAST, dl,
10595 N->getOperand(0).getValueType(),
10596 V->getOperand(0)), N->getOperand(1));
10597 }
10598 }
10599
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010600 return SDValue();
10601}
10602
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010603// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10604static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10605 EVT VT = N->getValueType(0);
10606 unsigned NumElts = VT.getVectorNumElements();
10607
10608 SDValue N0 = N->getOperand(0);
10609 SDValue N1 = N->getOperand(1);
10610 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10611
10612 SmallVector<SDValue, 4> Ops;
10613 EVT ConcatVT = N0.getOperand(0).getValueType();
10614 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10615 unsigned NumConcats = NumElts / NumElemsPerConcat;
10616
10617 // Look at every vector that's inserted. We're looking for exact
10618 // subvector-sized copies from a concatenated vector
10619 for (unsigned I = 0; I != NumConcats; ++I) {
10620 // Make sure we're dealing with a copy.
10621 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000010622 bool AllUndef = true, NoUndef = true;
10623 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10624 if (SVN->getMaskElt(J) >= 0)
10625 AllUndef = false;
10626 else
10627 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010628 }
10629
Hao Liubc601962013-05-13 02:07:05 +000010630 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000010631 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10632 return SDValue();
10633
10634 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10635 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10636 return SDValue();
10637
10638 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10639 if (FirstElt < N0.getNumOperands())
10640 Ops.push_back(N0.getOperand(FirstElt));
10641 else
10642 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10643
10644 } else if (AllUndef) {
10645 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10646 } else { // Mixed with general masks and undefs, can't do optimization.
10647 return SDValue();
10648 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010649 }
10650
Craig Topper48d114b2014-04-26 18:35:24 +000010651 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010652}
10653
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010654SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010655 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010656 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010657
Mon P Wang25f01062008-11-10 04:46:22 +000010658 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000010659 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000010660
Craig Topper5894fe42012-04-09 05:16:56 +000010661 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000010662
Craig Topper279c77b2012-01-04 08:07:43 +000010663 // Canonicalize shuffle undef, undef -> undef
10664 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10665 return DAG.getUNDEF(VT);
10666
10667 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10668
10669 // Canonicalize shuffle v, v -> v, undef
10670 if (N0 == N1) {
10671 SmallVector<int, 8> NewMask;
10672 for (unsigned i = 0; i != NumElts; ++i) {
10673 int Idx = SVN->getMaskElt(i);
10674 if (Idx >= (int)NumElts) Idx -= NumElts;
10675 NewMask.push_back(Idx);
10676 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010677 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010678 &NewMask[0]);
10679 }
10680
10681 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10682 if (N0.getOpcode() == ISD::UNDEF) {
10683 SmallVector<int, 8> NewMask;
10684 for (unsigned i = 0; i != NumElts; ++i) {
10685 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000010686 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000010687 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000010688 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000010689 else
10690 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000010691 }
10692 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000010693 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010694 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010695 &NewMask[0]);
10696 }
10697
10698 // Remove references to rhs if it is undef
10699 if (N1.getOpcode() == ISD::UNDEF) {
10700 bool Changed = false;
10701 SmallVector<int, 8> NewMask;
10702 for (unsigned i = 0; i != NumElts; ++i) {
10703 int Idx = SVN->getMaskElt(i);
10704 if (Idx >= (int)NumElts) {
10705 Idx = -1;
10706 Changed = true;
10707 }
10708 NewMask.push_back(Idx);
10709 }
10710 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000010711 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000010712 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000010713
Bob Wilsonf63da122010-10-28 17:06:14 +000010714 // If it is a splat, check if the argument vector is another splat or a
10715 // build_vector with all scalar elements the same.
Bob Wilsonf63da122010-10-28 17:06:14 +000010716 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000010717 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000010718
Dan Gohmana8665142007-06-25 16:23:39 +000010719 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000010720 // not the number of vector elements, look through it. Be careful not to
10721 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000010722 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010723 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000010724 if (ConvInput.getValueType().isVector() &&
10725 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000010726 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000010727 }
10728
Dan Gohmana8665142007-06-25 16:23:39 +000010729 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000010730 assert(V->getNumOperands() == NumElts &&
10731 "BUILD_VECTOR has wrong number of operands");
10732 SDValue Base;
10733 bool AllSame = true;
10734 for (unsigned i = 0; i != NumElts; ++i) {
10735 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10736 Base = V->getOperand(i);
10737 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000010738 }
Evan Cheng7c970b92006-07-21 08:25:53 +000010739 }
Bob Wilsonf63da122010-10-28 17:06:14 +000010740 // Splat of <u, u, u, u>, return <u, u, u, u>
10741 if (!Base.getNode())
10742 return N0;
10743 for (unsigned i = 0; i != NumElts; ++i) {
10744 if (V->getOperand(i) != Base) {
10745 AllSame = false;
10746 break;
10747 }
10748 }
10749 // Splat of <x, x, x, x>, return <x, x, x, x>
10750 if (AllSame)
10751 return N0;
Evan Cheng7c970b92006-07-21 08:25:53 +000010752 }
10753 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010754
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010755 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10756 Level < AfterLegalizeVectorOps &&
10757 (N1.getOpcode() == ISD::UNDEF ||
10758 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10759 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10760 SDValue V = partitionShuffleOfConcats(N, DAG);
10761
10762 if (V.getNode())
10763 return V;
10764 }
10765
Nadav Rotemb0783502012-04-01 19:31:22 +000010766 // If this shuffle node is simply a swizzle of another shuffle node,
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010767 // then try to simplify it.
Nadav Rotemb0783502012-04-01 19:31:22 +000010768 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10769 N1.getOpcode() == ISD::UNDEF) {
10770
Nadav Rotemb0783502012-04-01 19:31:22 +000010771 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10772
Craig Topper5894fe42012-04-09 05:16:56 +000010773 // The incoming shuffle must be of the same type as the result of the
10774 // current shuffle.
10775 assert(OtherSV->getOperand(0).getValueType() == VT &&
10776 "Shuffle types don't match");
Nadav Rotemb0783502012-04-01 19:31:22 +000010777
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010778 SmallVector<int, 4> Mask;
10779 // Compute the combined shuffle mask.
Nadav Rotemb0783502012-04-01 19:31:22 +000010780 for (unsigned i = 0; i != NumElts; ++i) {
10781 int Idx = SVN->getMaskElt(i);
Craig Topper5894fe42012-04-09 05:16:56 +000010782 assert(Idx < (int)NumElts && "Index references undef operand");
Nadav Rotemb0783502012-04-01 19:31:22 +000010783 // Next, this index comes from the first value, which is the incoming
10784 // shuffle. Adopt the incoming index.
10785 if (Idx >= 0)
10786 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010787 Mask.push_back(Idx);
Nadav Rotemb0783502012-04-01 19:31:22 +000010788 }
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010789
10790 bool CommuteOperands = false;
10791 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10792 // To be valid, the combine shuffle mask should only reference elements
10793 // from one of the two vectors in input to the inner shufflevector.
10794 bool IsValidMask = true;
10795 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10796 // See if the combined mask only reference undefs or elements coming
10797 // from the first shufflevector operand.
10798 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010799
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010800 if (!IsValidMask) {
10801 IsValidMask = true;
10802 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10803 // Check that all the elements come from the second shuffle operand.
10804 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10805 CommuteOperands = IsValidMask;
10806 }
10807
10808 // Early exit if the combined shuffle mask is not valid.
10809 if (!IsValidMask)
10810 return SDValue();
10811 }
10812
10813 // See if this pair of shuffles can be safely folded according to either
10814 // of the following rules:
10815 // shuffle(shuffle(x, y), undef) -> x
10816 // shuffle(shuffle(x, undef), undef) -> x
10817 // shuffle(shuffle(x, y), undef) -> y
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010818 bool IsIdentityMask = true;
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010819 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010820 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10821 // Skip Undefs.
10822 if (Mask[i] < 0)
10823 continue;
10824
10825 // The combined shuffle must map each index to itself.
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010826 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010827 }
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010828
10829 if (IsIdentityMask) {
10830 if (CommuteOperands)
10831 // optimize shuffle(shuffle(x, y), undef) -> y.
10832 return OtherSV->getOperand(1);
10833
10834 // optimize shuffle(shuffle(x, undef), undef) -> x
10835 // optimize shuffle(shuffle(x, y), undef) -> x
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010836 return OtherSV->getOperand(0);
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010837 }
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010838
10839 // It may still be beneficial to combine the two shuffles if the
10840 // resulting shuffle is legal.
Andrea Di Biagio67d8b2e2014-07-13 21:02:14 +000010841 if (TLI.isTypeLegal(VT) && TLI.isShuffleMaskLegal(Mask, VT)) {
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010842 if (!CommuteOperands)
10843 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10844 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10845 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10846 &Mask[0]);
10847
10848 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(undef, y, M3)
10849 return DAG.getVectorShuffle(VT, SDLoc(N), N1, N0->getOperand(1),
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010850 &Mask[0]);
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010851 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010852 }
10853
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000010854 // Canonicalize shuffles according to rules:
10855 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10856 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10857 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10858 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10859 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10860 TLI.isTypeLegal(VT)) {
10861 // The incoming shuffle must be of the same type as the result of the
10862 // current shuffle.
10863 assert(N1->getOperand(0).getValueType() == VT &&
10864 "Shuffle types don't match");
10865
10866 SDValue SV0 = N1->getOperand(0);
10867 SDValue SV1 = N1->getOperand(1);
10868 bool HasSameOp0 = N0 == SV0;
10869 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10870 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10871 // Commute the operands of this shuffle so that next rule
10872 // will trigger.
10873 return DAG.getCommutedVectorShuffle(*SVN);
10874 }
10875
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010876 // Try to fold according to rules:
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010877 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10878 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10879 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10880 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010881 // Don't try to fold shuffles with illegal type.
10882 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010883 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010884 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10885
10886 // The incoming shuffle must be of the same type as the result of the
10887 // current shuffle.
10888 assert(OtherSV->getOperand(0).getValueType() == VT &&
10889 "Shuffle types don't match");
10890
10891 SDValue SV0 = OtherSV->getOperand(0);
10892 SDValue SV1 = OtherSV->getOperand(1);
10893 bool HasSameOp0 = N1 == SV0;
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010894 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10895 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010896 // Early exit.
10897 return SDValue();
10898
10899 SmallVector<int, 4> Mask;
10900 // Compute the combined shuffle mask for a shuffle with SV0 as the first
10901 // operand, and SV1 as the second operand.
10902 for (unsigned i = 0; i != NumElts; ++i) {
10903 int Idx = SVN->getMaskElt(i);
10904 if (Idx < 0) {
10905 // Propagate Undef.
10906 Mask.push_back(Idx);
10907 continue;
10908 }
10909
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010910 if (Idx < (int)NumElts) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010911 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010912 if (IsSV1Undef && Idx >= (int) NumElts)
10913 Idx = -1; // Propagate Undef.
10914 } else
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010915 Idx = HasSameOp0 ? Idx - NumElts : Idx;
10916
10917 Mask.push_back(Idx);
10918 }
10919
10920 // Avoid introducing shuffles with illegal mask.
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010921 if (TLI.isShuffleMaskLegal(Mask, VT)) {
10922 if (IsSV1Undef)
10923 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10924 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10925 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010926 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010927 }
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010928 }
10929
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010930 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010931}
10932
Manman Ren413a6cb2014-01-31 01:10:35 +000010933SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10934 SDValue N0 = N->getOperand(0);
10935 SDValue N2 = N->getOperand(2);
10936
10937 // If the input vector is a concatenation, and the insert replaces
10938 // one of the halves, we can optimize into a single concat_vectors.
10939 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10940 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10941 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10942 EVT VT = N->getValueType(0);
10943
10944 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10945 // (concat_vectors Z, Y)
10946 if (InsIdx == 0)
10947 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10948 N->getOperand(1), N0.getOperand(1));
10949
10950 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10951 // (concat_vectors X, Z)
10952 if (InsIdx == VT.getVectorNumElements()/2)
10953 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10954 N0.getOperand(0), N->getOperand(1));
10955 }
10956
10957 return SDValue();
10958}
10959
Evan Chenga320abc2006-04-20 08:56:16 +000010960/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
Dan Gohmana8665142007-06-25 16:23:39 +000010961/// an AND to a vector_shuffle with the destination vector and a zero vector.
10962/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000010963/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010964SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010965 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010966 SDLoc dl(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010967 SDValue LHS = N->getOperand(0);
10968 SDValue RHS = N->getOperand(1);
Dan Gohmana8665142007-06-25 16:23:39 +000010969 if (N->getOpcode() == ISD::AND) {
Wesley Peck527da1b2010-11-23 03:31:01 +000010970 if (RHS.getOpcode() == ISD::BITCAST)
Evan Chenga320abc2006-04-20 08:56:16 +000010971 RHS = RHS.getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010972 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010973 SmallVector<int, 8> Indices;
10974 unsigned NumElts = RHS.getNumOperands();
Evan Chenga320abc2006-04-20 08:56:16 +000010975 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010976 SDValue Elt = RHS.getOperand(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010977 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010978 return SDValue();
Craig Toppere5893f62012-04-09 05:59:53 +000010979
10980 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010981 Indices.push_back(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010982 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010983 Indices.push_back(NumElts);
Evan Chenga320abc2006-04-20 08:56:16 +000010984 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010985 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010986 }
10987
10988 // Let's see if the target supports this vector_shuffle.
Owen Anderson53aa7a92009-08-10 22:56:29 +000010989 EVT RVT = RHS.getValueType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010990 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010991 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010992
Dan Gohmana8665142007-06-25 16:23:39 +000010993 // Return the new VECTOR_SHUFFLE node.
Dan Gohman08c0a952009-09-23 21:02:20 +000010994 EVT EltVT = RVT.getVectorElementType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010995 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman08c0a952009-09-23 21:02:20 +000010996 DAG.getConstant(0, EltVT));
Craig Topper48d114b2014-04-26 18:35:24 +000010997 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
Wesley Peck527da1b2010-11-23 03:31:01 +000010998 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010999 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peck527da1b2010-11-23 03:31:01 +000011000 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000011001 }
11002 }
Bill Wendling31b50992009-01-30 23:59:18 +000011003
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011004 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000011005}
11006
Dan Gohmana8665142007-06-25 16:23:39 +000011007/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011008SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000011009 assert(N->getValueType(0).isVector() &&
11010 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000011011
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011012 SDValue LHS = N->getOperand(0);
11013 SDValue RHS = N->getOperand(1);
11014 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011015 if (Shuffle.getNode()) return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000011016
Dan Gohmana8665142007-06-25 16:23:39 +000011017 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000011018 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011019 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000011020 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000011021 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000011022 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11023 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000011024 return SDValue();
11025
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011026 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000011027 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011028 SDValue LHSOp = LHS.getOperand(i);
11029 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000011030
Evan Cheng64d28462006-05-31 06:08:35 +000011031 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000011032 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11033 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000011034 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000011035 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000011036 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000011037 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000011038 break;
11039 }
Bill Wendling31b50992009-01-30 23:59:18 +000011040
Bob Wilson54081442010-12-17 23:06:49 +000011041 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000011042 EVT RVT = RHSOp.getValueType();
11043 if (RVT != VT) {
11044 // Integer BUILD_VECTOR operands may have types larger than the element
11045 // size (e.g., when the element type is not legal). Prior to type
11046 // legalization, the types may not match between the two BUILD_VECTORS.
11047 // Truncate one of the operands to make them match.
11048 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011049 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000011050 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011051 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000011052 VT = RVT;
11053 }
11054 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000011055 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000011056 LHSOp, RHSOp);
11057 if (FoldOp.getOpcode() != ISD::UNDEF &&
11058 FoldOp.getOpcode() != ISD::Constant &&
11059 FoldOp.getOpcode() != ISD::ConstantFP)
11060 break;
11061 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011062 AddToWorklist(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000011063 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011064
Bob Wilson54081442010-12-17 23:06:49 +000011065 if (Ops.size() == LHS.getNumOperands())
Craig Topper48d114b2014-04-26 18:35:24 +000011066 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
Chris Lattner0442a182006-04-02 03:25:57 +000011067 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011068
Andrea Di Biagio446a5272014-05-30 23:17:53 +000011069 // Type legalization might introduce new shuffles in the DAG.
11070 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11071 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
11072 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11073 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11074 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11075 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11076 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11077 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11078
11079 if (SVN0->getMask().equals(SVN1->getMask())) {
11080 EVT VT = N->getValueType(0);
11081 SDValue UndefVector = LHS.getOperand(1);
11082 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11083 LHS.getOperand(0), RHS.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011084 AddUsersToWorklist(N);
Andrea Di Biagio446a5272014-05-30 23:17:53 +000011085 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11086 &SVN0->getMask()[0]);
11087 }
11088 }
11089
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011090 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000011091}
11092
Craig Topper82384612012-09-11 01:45:21 +000011093/// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
11094SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topper82384612012-09-11 01:45:21 +000011095 assert(N->getValueType(0).isVector() &&
11096 "SimplifyVUnaryOp only works on vectors!");
11097
11098 SDValue N0 = N->getOperand(0);
11099
11100 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11101 return SDValue();
11102
11103 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11104 SmallVector<SDValue, 8> Ops;
11105 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11106 SDValue Op = N0.getOperand(i);
11107 if (Op.getOpcode() != ISD::UNDEF &&
11108 Op.getOpcode() != ISD::ConstantFP)
11109 break;
11110 EVT EltVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011111 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topper82384612012-09-11 01:45:21 +000011112 if (FoldOp.getOpcode() != ISD::UNDEF &&
11113 FoldOp.getOpcode() != ISD::ConstantFP)
11114 break;
11115 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011116 AddToWorklist(FoldOp.getNode());
Craig Topper82384612012-09-11 01:45:21 +000011117 }
11118
11119 if (Ops.size() != N0.getNumOperands())
11120 return SDValue();
11121
Craig Topper48d114b2014-04-26 18:35:24 +000011122 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
Craig Topper82384612012-09-11 01:45:21 +000011123}
11124
Andrew Trickef9de2a2013-05-25 02:42:55 +000011125SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011126 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000011127 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000011128
Bill Wendling31b50992009-01-30 23:59:18 +000011129 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000011130 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000011131
Nate Begeman2042aa52005-10-08 00:29:44 +000011132 // If we got a simplified select_cc node back from SimplifySelectCC, then
11133 // break it down into a new SETCC node, and a new SELECT node, and then return
11134 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000011135 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000011136 // Check to see if we got a select_cc back (to turn into setcc/select).
11137 // Otherwise, just return whatever node we got back, like fabs.
11138 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011139 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011140 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000011141 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000011142 SCC.getOperand(4));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011143 AddToWorklist(SETCC.getNode());
Chandler Carruth40dbd382014-08-04 21:29:59 +000011144 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11145 SCC.getOperand(2), SCC.getOperand(3));
Nate Begeman2042aa52005-10-08 00:29:44 +000011146 }
Bill Wendling31b50992009-01-30 23:59:18 +000011147
Nate Begeman2042aa52005-10-08 00:29:44 +000011148 return SCC;
11149 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011150 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011151}
11152
Chris Lattner6c14c352005-10-18 06:04:22 +000011153/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11154/// are the two values being selected between, see if we can simplify the
Chris Lattner8f872d22006-05-27 00:43:02 +000011155/// select. Callers of this should assume that TheSelect is deleted if this
11156/// returns true. As such, they should return the appropriate thing (e.g. the
11157/// node) back to the top-level of the DAG combiner loop to avoid it being
11158/// looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011159bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011160 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011161
Nadav Rotema49a02a2011-02-11 19:57:47 +000011162 // Cannot simplify select with vector condition
11163 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11164
Chris Lattner6c14c352005-10-18 06:04:22 +000011165 // If this is a select from two identical things, try to pull the operation
11166 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000011167 if (LHS.getOpcode() != RHS.getOpcode() ||
11168 !LHS.hasOneUse() || !RHS.hasOneUse())
11169 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011170
Chris Lattner254c4452010-09-21 15:46:59 +000011171 // If this is a load and the token chain is identical, replace the select
11172 // of two loads with a load through a select of the address to load from.
11173 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11174 // constants have been dropped into the constant pool.
11175 if (LHS.getOpcode() == ISD::LOAD) {
11176 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11177 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000011178
Chris Lattner254c4452010-09-21 15:46:59 +000011179 // Token chains must be identical.
11180 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000011181 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000011182 LLD->isVolatile() || RLD->isVolatile() ||
11183 // If this is an EXTLOAD, the VT's must match.
11184 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000011185 // If this is an EXTLOAD, the kind of extension must match.
11186 (LLD->getExtensionType() != RLD->getExtensionType() &&
11187 // The only exception is if one of the extensions is anyext.
11188 LLD->getExtensionType() != ISD::EXTLOAD &&
11189 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000011190 // FIXME: this discards src value information. This is
11191 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000011192 // both potential memory locations. Since we are discarding
11193 // src value info, don't do the transformation if the memory
11194 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000011195 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000011196 RLD->getPointerInfo().getAddrSpace() != 0 ||
11197 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11198 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000011199 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011200
Chris Lattnere3267522010-09-21 15:58:55 +000011201 // Check that the select condition doesn't reach either load. If so,
11202 // folding this will induce a cycle into the DAG. If not, this is safe to
11203 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000011204 SDValue Addr;
11205 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000011206 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11207 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11208 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11209 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000011210 // The loads must not depend on one another.
11211 if (LLD->isPredecessorOf(RLD) ||
11212 RLD->isPredecessorOf(LLD))
11213 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011214 Addr = DAG.getSelect(SDLoc(TheSelect),
11215 LLD->getBasePtr().getValueType(),
11216 TheSelect->getOperand(0), LLD->getBasePtr(),
11217 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000011218 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000011219 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11220 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11221
11222 if ((LLD->hasAnyUseOfValue(1) &&
11223 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000011224 (RLD->hasAnyUseOfValue(1) &&
11225 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000011226 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011227
Andrew Trickef9de2a2013-05-25 02:42:55 +000011228 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000011229 LLD->getBasePtr().getValueType(),
11230 TheSelect->getOperand(0),
11231 TheSelect->getOperand(1),
11232 LLD->getBasePtr(), RLD->getBasePtr(),
11233 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000011234 }
11235
Chris Lattnere3267522010-09-21 15:58:55 +000011236 SDValue Load;
Louis Gerbarg4fc09b32014-07-30 18:24:41 +000011237 // It is safe to replace the two loads if they have different alignments,
11238 // but the new load must be the minimum (most restrictive) alignment of the
11239 // inputs.
Louis Gerbarg67474e32014-07-31 21:45:05 +000011240 bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
Louis Gerbarg09b8cde2014-07-31 22:57:46 +000011241 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000011242 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11243 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000011244 SDLoc(TheSelect),
Hal Finkelcc39b672014-07-24 12:16:19 +000011245 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000011246 LLD->getChain(), Addr, MachinePointerInfo(),
11247 LLD->isVolatile(), LLD->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000011248 isInvariant, Alignment);
Chris Lattnere3267522010-09-21 15:58:55 +000011249 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000011250 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11251 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000011252 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000011253 TheSelect->getValueType(0),
Hal Finkelcc39b672014-07-24 12:16:19 +000011254 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000011255 LLD->getChain(), Addr, MachinePointerInfo(),
11256 LLD->getMemoryVT(), LLD->isVolatile(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000011257 LLD->isNonTemporal(), isInvariant, Alignment);
Chris Lattner6c14c352005-10-18 06:04:22 +000011258 }
Chris Lattnere3267522010-09-21 15:58:55 +000011259
11260 // Users of the select now use the result of the load.
11261 CombineTo(TheSelect, Load);
11262
11263 // Users of the old loads now use the new load's chain. We know the
11264 // old-load value is dead now.
11265 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11266 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11267 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000011268 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011269
Chris Lattner6c14c352005-10-18 06:04:22 +000011270 return false;
11271}
11272
Chris Lattner43d63772009-03-11 05:08:08 +000011273/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11274/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000011275SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011276 SDValue N2, SDValue N3,
11277 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000011278 // (x ? y : y) -> y.
11279 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000011280
Owen Anderson53aa7a92009-08-10 22:56:29 +000011281 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000011282 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11283 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11284 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011285
11286 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000011287 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000011288 N0, N1, CC, DL, false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011289 if (SCC.getNode()) AddToWorklist(SCC.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +000011290 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011291
11292 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000011293 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000011294 return N2;
11295 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000011296 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000011297 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011298
Nate Begeman2042aa52005-10-08 00:29:44 +000011299 // Check to see if we can simplify the select into an fabs node
11300 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11301 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000011302 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000011303 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11304 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11305 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11306 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000011307 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011308
Nate Begeman2042aa52005-10-08 00:29:44 +000011309 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11310 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11311 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11312 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000011313 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000011314 }
11315 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011316
Chris Lattner43d63772009-03-11 05:08:08 +000011317 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11318 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11319 // in it. This is a win when the constant is not otherwise available because
11320 // it replaces two constant pool loads with one. We only do this if the FP
11321 // type is known to be legal, because if it isn't, then we are before legalize
11322 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000011323 // messing with soft float) and if the ConstantFP is not legal, because if
11324 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000011325 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11326 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11327 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000011328 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
Tim Northover863a7892014-04-16 09:03:09 +000011329 TargetLowering::Legal &&
11330 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11331 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
Chris Lattner43d63772009-03-11 05:08:08 +000011332 // If both constants have multiple uses, then we won't need to do an
11333 // extra load, they are likely around in registers for other users.
11334 (TV->hasOneUse() || FV->hasOneUse())) {
11335 Constant *Elts[] = {
11336 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11337 const_cast<ConstantFP*>(TV->getConstantFPValue())
11338 };
Chris Lattner229907c2011-07-18 04:54:35 +000011339 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000011340 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000011341
Chris Lattner43d63772009-03-11 05:08:08 +000011342 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000011343 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000011344 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11345 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000011346 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000011347
11348 // Get the offsets to the 0 and 1 element of the array so that we can
11349 // select between them.
11350 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000011351 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000011352 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000011353
Chris Lattner43d63772009-03-11 05:08:08 +000011354 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000011355 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000011356 N0, N1, CC);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011357 AddToWorklist(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011358 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11359 Cond, One, Zero);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011360 AddToWorklist(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000011361 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000011362 CstOffset);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011363 AddToWorklist(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000011364 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000011365 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000011366 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000011367
11368 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011369 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011370
Nate Begeman2042aa52005-10-08 00:29:44 +000011371 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000011372 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000011373 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000011374 (N1C->isNullValue() || // (a < 0) ? b : 0
11375 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000011376 EVT XType = N0.getValueType();
11377 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000011378 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000011379 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000011380 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011381 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11382 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000011383 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000011384 SDValue ShCt = DAG.getConstant(ShCtV,
11385 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011386 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011387 XType, N0, ShCt);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011388 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011389
Duncan Sands11dd4242008-06-08 20:54:56 +000011390 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011391 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011392 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011393 }
Bill Wendling31b50992009-01-30 23:59:18 +000011394
11395 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011396 }
Bill Wendling31b50992009-01-30 23:59:18 +000011397
Andrew Trickef9de2a2013-05-25 02:42:55 +000011398 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011399 XType, N0,
11400 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011401 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011402 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011403
Duncan Sands11dd4242008-06-08 20:54:56 +000011404 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011405 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011406 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011407 }
Bill Wendling31b50992009-01-30 23:59:18 +000011408
11409 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011410 }
11411 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011412
Owen Anderson3231d132010-09-22 22:58:22 +000011413 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11414 // where y is has a single bit set.
11415 // A plaintext description would be, we can turn the SELECT_CC into an AND
11416 // when the condition can be materialized as an all-ones register. Any
11417 // single bit-test can be materialized as an all-ones register with
11418 // shift-left and shift-right-arith.
11419 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11420 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000011421 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000011422 N2C && N2C->isNullValue()) {
11423 SDValue AndLHS = N0->getOperand(0);
11424 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11425 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11426 // Shift the tested bit over the sign bit.
11427 APInt AndMask = ConstAndRHS->getAPIntValue();
11428 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011429 DAG.getConstant(AndMask.countLeadingZeros(),
11430 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011431 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011432
Owen Anderson3231d132010-09-22 22:58:22 +000011433 // Now arithmetic right shift it all the way over, so the result is either
11434 // all-ones, or zero.
11435 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011436 DAG.getConstant(AndMask.getBitWidth()-1,
11437 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011438 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011439
Owen Anderson3231d132010-09-22 22:58:22 +000011440 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11441 }
11442 }
11443
Nate Begeman6828ed92005-10-10 21:26:48 +000011444 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000011445 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +000011446 TLI.getBooleanContents(N0.getValueType()) ==
11447 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011448
Chris Lattnera083ffc2007-04-11 06:50:51 +000011449 // If the caller doesn't want us to simplify this into a zext of a compare,
11450 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011451 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011452 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011453
Nate Begeman6828ed92005-10-10 21:26:48 +000011454 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011455 // NOTE: Don't create a SETCC if it's not legal on this target.
11456 if (!LegalOperations ||
11457 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000011458 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011459 SDValue Temp, SCC;
11460 // cast from setcc result type to select result type
11461 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000011462 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011463 N0, N1, CC);
11464 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000011465 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011466 N2.getValueType());
11467 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000011468 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011469 N2.getValueType(), SCC);
11470 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011471 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11472 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000011473 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011474 }
11475
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011476 AddToWorklist(SCC.getNode());
11477 AddToWorklist(Temp.getNode());
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011478
11479 if (N2C->getAPIntValue() == 1)
11480 return Temp;
11481
11482 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000011483 return DAG.getNode(
11484 ISD::SHL, DL, N2.getValueType(), Temp,
11485 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11486 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000011487 }
Nate Begeman6828ed92005-10-10 21:26:48 +000011488 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011489
Nate Begeman2042aa52005-10-08 00:29:44 +000011490 // Check to see if this is the equivalent of setcc
11491 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11492 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011493 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011494 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011495 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000011496 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11497 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000011498 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000011499 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000011500 return Res;
11501 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011502
Bill Wendling31b50992009-01-30 23:59:18 +000011503 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011504 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011505 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000011506 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011507 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011508 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000011509 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000011510 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000011511 }
Bill Wendling31b50992009-01-30 23:59:18 +000011512 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011513 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011514 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011515 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011516 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000011517 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000011518 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000011519 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011520 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000011521 }
Bill Wendling31b50992009-01-30 23:59:18 +000011522 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000011523 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011524 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011525 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011526 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000011527 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000011528 }
11529 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011530
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011531 // Check to see if this is an integer abs.
11532 // select_cc setg[te] X, 0, X, -X ->
11533 // select_cc setgt X, -1, X, -X ->
11534 // select_cc setl[te] X, 0, -X, X ->
11535 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000011536 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011537 if (N1C) {
Craig Topperc0196b12014-04-14 00:51:57 +000011538 ConstantSDNode *SubC = nullptr;
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011539 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11540 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11541 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11542 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11543 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11544 (N1C->isOne() && CC == ISD::SETLT)) &&
11545 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11546 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11547
Owen Anderson53aa7a92009-08-10 22:56:29 +000011548 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011549 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011550 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011551 N0,
11552 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011553 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011554 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011555 XType, N0, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011556 AddToWorklist(Shift.getNode());
11557 AddToWorklist(Add.getNode());
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011558 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000011559 }
11560 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011561
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011562 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011563}
11564
Evan Cheng92658d52007-02-08 22:13:59 +000011565/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011566SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011567 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000011568 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011569 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000011570 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000011571 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000011572}
11573
Chad Rosier17020f92014-07-23 14:57:52 +000011574/// BuildSDIV - Given an ISD::SDIV node expressing a divide by constant, return
11575/// a DAG expression to select that will generate the same value by multiplying
11576/// by a magic number. See:
Nate Begemanc6f067a2005-10-20 02:15:44 +000011577/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011578SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011579 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11580 if (!C)
11581 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011582
11583 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011584 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011585 return SDValue();
11586
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011587 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011588 SDValue S =
11589 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011590
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011591 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011592 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011593 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011594}
11595
Chad Rosier17020f92014-07-23 14:57:52 +000011596/// BuildSDIVPow2 - Given an ISD::SDIV node expressing a divide by constant
11597/// power of 2, return a DAG expression to select that will generate the same
11598/// value by right shifting.
11599SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11600 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11601 if (!C)
11602 return SDValue();
11603
11604 // Avoid division by zero.
11605 if (!C->getAPIntValue())
11606 return SDValue();
11607
11608 std::vector<SDNode *> Built;
11609 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11610
11611 for (SDNode *N : Built)
11612 AddToWorklist(N);
11613 return S;
11614}
11615
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011616/// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
Nate Begemanc6f067a2005-10-20 02:15:44 +000011617/// return a DAG expression to select that will generate the same value by
11618/// multiplying by a magic number. See:
11619/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011620SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011621 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11622 if (!C)
11623 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011624
11625 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011626 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011627 return SDValue();
11628
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011629 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011630 SDValue S =
11631 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000011632
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011633 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011634 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011635 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011636}
11637
Nate Begeman18150d52009-09-25 06:05:26 +000011638/// FindBaseOffset - Return true if base is a frame index, which is known not
Eric Christopherd9e8eac2010-12-09 04:48:06 +000011639// to alias with anything but itself. Provides base object and offset as
11640// results.
Nate Begeman18150d52009-09-25 06:05:26 +000011641static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000011642 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000011643 // Assume it is a primitive operation.
Craig Topperc0196b12014-04-14 00:51:57 +000011644 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011645
Jim Laskey0463e082006-10-07 23:37:56 +000011646 // If it's an adding a simple constant then integrate the offset.
11647 if (Base.getOpcode() == ISD::ADD) {
11648 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11649 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000011650 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000011651 }
11652 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011653
Nate Begeman18150d52009-09-25 06:05:26 +000011654 // Return the underlying GlobalValue, and update the Offset. Return false
11655 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11656 // by multiple nodes with different offsets.
11657 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11658 GV = G->getGlobal();
11659 Offset += G->getOffset();
11660 return false;
11661 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011662
Nate Begeman18150d52009-09-25 06:05:26 +000011663 // Return the underlying Constant value, and update the Offset. Return false
11664 // for ConstantSDNodes since the same constant pool entry may be represented
11665 // by multiple nodes with different offsets.
11666 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000011667 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11668 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000011669 Offset += C->getOffset();
11670 return false;
11671 }
Jim Laskey0463e082006-10-07 23:37:56 +000011672 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000011673 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000011674}
11675
11676/// isAlias - Return true if there is any possibility that the two addresses
11677/// overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011678bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
Jim Laskey0463e082006-10-07 23:37:56 +000011679 // If they are the same then they must be aliases.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011680 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011681
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011682 // If they are both volatile then they cannot be reordered.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011683 if (Op0->isVolatile() && Op1->isVolatile()) return true;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011684
Jim Laskey0463e082006-10-07 23:37:56 +000011685 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011686 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000011687 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000011688 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000011689 const void *CV1, *CV2;
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011690 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11691 Base1, Offset1, GV1, CV1);
11692 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11693 Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011694
Nate Begeman18150d52009-09-25 06:05:26 +000011695 // If they have a same base address then check to see if they overlap.
11696 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011697 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11698 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011699
Owen Anderson272ff942010-09-20 20:39:59 +000011700 // It is possible for different frame indices to alias each other, mostly
11701 // when tail call optimization reuses return address slots for arguments.
11702 // To catch this case, look up the actual index of frame indices to compute
11703 // the real alias relationship.
11704 if (isFrameIndex1 && isFrameIndex2) {
11705 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11706 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11707 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011708 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11709 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Owen Anderson272ff942010-09-20 20:39:59 +000011710 }
11711
Wesley Peck527da1b2010-11-23 03:31:01 +000011712 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000011713 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000011714 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11715 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011716
Nate Begeman879d8f12009-09-15 00:18:30 +000011717 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11718 // compared to the size and offset of the access, we may be able to prove they
11719 // do not alias. This check is conservative for now to catch cases created by
11720 // splitting vector types.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011721 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11722 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11723 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11724 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11725 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11726 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11727 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
Wesley Peck527da1b2010-11-23 03:31:01 +000011728
Nate Begeman879d8f12009-09-15 00:18:30 +000011729 // There is no overlap between these relatively aligned accesses of similar
11730 // size, return no alias.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011731 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11732 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
Nate Begeman879d8f12009-09-15 00:18:30 +000011733 return false;
11734 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011735
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000011736 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11737 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000011738#ifndef NDEBUG
11739 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11740 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11741 UseAA = false;
11742#endif
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011743 if (UseAA &&
11744 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000011745 // Use alias analysis information.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011746 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11747 Op1->getSrcValueOffset());
11748 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11749 Op0->getSrcValueOffset() - MinOffset;
11750 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11751 Op1->getSrcValueOffset() - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011752 AliasAnalysis::AliasResult AAResult =
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011753 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11754 Overlap1,
Hal Finkelcc39b672014-07-24 12:16:19 +000011755 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011756 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11757 Overlap2,
Hal Finkelcc39b672014-07-24 12:16:19 +000011758 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
Jim Laskey55e4dca2006-10-18 19:08:31 +000011759 if (AAResult == AliasAnalysis::NoAlias)
11760 return false;
11761 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011762
11763 // Otherwise we have to assume they alias.
11764 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000011765}
11766
Jim Laskey708d0db2006-10-04 16:53:27 +000011767/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11768/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011769void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000011770 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011771 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000011772 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011773
Jim Laskeyd07be232006-09-25 16:29:54 +000011774 // Get alias information for node.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011775 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
Jim Laskeyd07be232006-09-25 16:29:54 +000011776
Jim Laskey708d0db2006-10-04 16:53:27 +000011777 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000011778 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011779 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000011780
Jim Laskey6549d222006-10-05 15:07:25 +000011781 // Look at each chain and determine if it is an alias. If so, add it to the
11782 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000011783 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000011784 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011785 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000011786 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000011787
11788 // For TokenFactor nodes, look at each operand and only continue up the
11789 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011790 // find more and revert to original chain since the xform is unlikely to be
11791 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000011792 //
11793 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011794 // chain we found before we hit a tokenfactor rather than the original
11795 // chain.
11796 if (Depth > 6 || Aliases.size() == 2) {
11797 Aliases.clear();
11798 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000011799 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011800 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011801
Nate Begeman879d8f12009-09-15 00:18:30 +000011802 // Don't bother if we've been before.
11803 if (!Visited.insert(Chain.getNode()))
11804 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011805
Jim Laskey6549d222006-10-05 15:07:25 +000011806 switch (Chain.getOpcode()) {
11807 case ISD::EntryToken:
11808 // Entry token is ideal chain operand, but handled in FindBetterChain.
11809 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011810
Jim Laskey6549d222006-10-05 15:07:25 +000011811 case ISD::LOAD:
11812 case ISD::STORE: {
11813 // Get alias information for Chain.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011814 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11815 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011816
Jim Laskey6549d222006-10-05 15:07:25 +000011817 // If chain is alias then stop here.
11818 if (!(IsLoad && IsOpLoad) &&
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011819 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
Jim Laskey6549d222006-10-05 15:07:25 +000011820 Aliases.push_back(Chain);
11821 } else {
11822 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011823 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011824 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000011825 }
Jim Laskey6549d222006-10-05 15:07:25 +000011826 break;
11827 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011828
Jim Laskey6549d222006-10-05 15:07:25 +000011829 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000011830 // We have to check each of the operands of the token factor for "small"
11831 // token factors, so we queue them up. Adding the operands to the queue
11832 // (stack) in reverse order maintains the original order and increases the
11833 // likelihood that getNode will find a matching token factor (CSE.)
11834 if (Chain.getNumOperands() > 16) {
11835 Aliases.push_back(Chain);
11836 break;
11837 }
Jim Laskey6549d222006-10-05 15:07:25 +000011838 for (unsigned n = Chain.getNumOperands(); n;)
11839 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011840 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000011841 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011842
Jim Laskey6549d222006-10-05 15:07:25 +000011843 default:
11844 // For all other instructions we will just have to take what we can get.
11845 Aliases.push_back(Chain);
11846 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000011847 }
11848 }
Hal Finkel51a98382014-01-24 20:12:02 +000011849
11850 // We need to be careful here to also search for aliases through the
11851 // value operand of a store, etc. Consider the following situation:
11852 // Token1 = ...
11853 // L1 = load Token1, %52
11854 // S1 = store Token1, L1, %51
11855 // L2 = load Token1, %52+8
11856 // S2 = store Token1, L2, %51+8
11857 // Token2 = Token(S1, S2)
11858 // L3 = load Token2, %53
11859 // S3 = store Token2, L3, %52
11860 // L4 = load Token2, %53+8
11861 // S4 = store Token2, L4, %52+8
11862 // If we search for aliases of S3 (which loads address %52), and we look
11863 // only through the chain, then we'll miss the trivial dependence on L1
11864 // (which also loads from %52). We then might change all loads and
11865 // stores to use Token1 as their chain operand, which could result in
11866 // copying %53 into %52 before copying %52 into %51 (which should
11867 // happen first).
11868 //
11869 // The problem is, however, that searching for such data dependencies
11870 // can become expensive, and the cost is not directly related to the
11871 // chain depth. Instead, we'll rule out such configurations here by
11872 // insisting that we've visited all chain users (except for users
11873 // of the original chain, which is not necessary). When doing this,
11874 // we need to look through nodes we don't care about (otherwise, things
11875 // like register copies will interfere with trivial cases).
11876
11877 SmallVector<const SDNode *, 16> Worklist;
11878 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11879 IE = Visited.end(); I != IE; ++I)
11880 if (*I != OriginalChain.getNode())
11881 Worklist.push_back(*I);
11882
11883 while (!Worklist.empty()) {
11884 const SDNode *M = Worklist.pop_back_val();
11885
11886 // We have already visited M, and want to make sure we've visited any uses
11887 // of M that we care about. For uses that we've not visisted, and don't
11888 // care about, queue them to the worklist.
11889
11890 for (SDNode::use_iterator UI = M->use_begin(),
11891 UIE = M->use_end(); UI != UIE; ++UI)
11892 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11893 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11894 // We've not visited this use, and we care about it (it could have an
11895 // ordering dependency with the original node).
11896 Aliases.clear();
11897 Aliases.push_back(OriginalChain);
11898 return;
11899 }
11900
11901 // We've not visited this use, but we don't care about it. Mark it as
11902 // visited and enqueue it to the worklist.
11903 Worklist.push_back(*UI);
11904 }
11905 }
Jim Laskey708d0db2006-10-04 16:53:27 +000011906}
11907
11908/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11909/// for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011910SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11911 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011912
Jim Laskey708d0db2006-10-04 16:53:27 +000011913 // Accumulate all the aliases to this node.
11914 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011915
Dan Gohman4298df62011-05-17 22:20:36 +000011916 // If no operands then chain to entry token.
11917 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000011918 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000011919
11920 // If a single operand then chain to it. We don't need to revisit it.
11921 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000011922 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000011923
Jim Laskey708d0db2006-10-04 16:53:27 +000011924 // Construct a custom tailored token factor.
Craig Topper48d114b2014-04-26 18:35:24 +000011925 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
Jim Laskeyd07be232006-09-25 16:29:54 +000011926}
11927
Nate Begeman21158fc2005-09-01 00:19:25 +000011928// SelectionDAG::Combine - This is the entry point for the file.
11929//
Bill Wendling084669a2009-04-29 00:15:41 +000011930void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000011931 CodeGenOpt::Level OptLevel) {
Nate Begeman21158fc2005-09-01 00:19:25 +000011932 /// run - This is the main entry point to this class.
11933 ///
Bill Wendling084669a2009-04-29 00:15:41 +000011934 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000011935}