blob: e0732fa693180d5b742d8f4d20ef0d60f26fe48d [file] [log] [blame]
Nate Begeman4ebd8052005-09-01 23:24:04 +00001//===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
Nate Begeman1d4d4142005-09-01 00:19:25 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Nate Begeman1d4d4142005-09-01 00:19:25 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11// both before and after the DAG is legalized.
Scott Michelfdc40a02009-02-17 22:15:04 +000012//
Dan Gohman41287002009-04-25 17:09:45 +000013// This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14// primarily intended to handle simplification opportunities that are implicit
15// in the LLVM IR and exposed by the various codegen lowering phases.
16//
Nate Begeman1d4d4142005-09-01 00:19:25 +000017//===----------------------------------------------------------------------===//
18
19#define DEBUG_TYPE "dagcombine"
Nate Begeman1d4d4142005-09-01 00:19:25 +000020#include "llvm/CodeGen/SelectionDAG.h"
Chris Lattnerc76d4412007-05-16 06:37:59 +000021#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/Statistic.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000023#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/LLVMContext.h"
Jim Laskeyd1aed7a2006-09-21 16:28:59 +000030#include "llvm/Support/CommandLine.h"
Chris Lattnerc76d4412007-05-16 06:37:59 +000031#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000032#include "llvm/Support/ErrorHandling.h"
Chris Lattnerc76d4412007-05-16 06:37:59 +000033#include "llvm/Support/MathExtras.h"
Chris Lattnerbbbfa992009-08-23 06:35:02 +000034#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000035#include "llvm/Target/TargetLowering.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetOptions.h"
Quentin Colombet83f743a2013-10-11 18:29:42 +000038#include "llvm/Target/TargetRegisterInfo.h"
Hal Finkel253acef2013-08-29 03:29:55 +000039#include "llvm/Target/TargetSubtargetInfo.h"
Chris Lattnera500fc62005-09-09 23:53:39 +000040#include <algorithm>
Nate Begeman1d4d4142005-09-01 00:19:25 +000041using namespace llvm;
42
Chris Lattnercd3245a2006-12-19 22:41:21 +000043STATISTIC(NodesCombined , "Number of dag nodes combined");
44STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
45STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
Evan Cheng8b944d32009-05-28 00:35:15 +000046STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
Evan Cheng31959b12011-02-02 01:06:55 +000047STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
Quentin Colombet83f743a2013-10-11 18:29:42 +000048STATISTIC(SlicedLoads, "Number of load sliced");
Chris Lattnercd3245a2006-12-19 22:41:21 +000049
Nate Begeman1d4d4142005-09-01 00:19:25 +000050namespace {
Jim Laskey71382342006-10-07 23:37:56 +000051 static cl::opt<bool>
Owen Anderson0dcc8142010-09-19 21:01:26 +000052 CombinerAA("combiner-alias-analysis", cl::Hidden,
Jim Laskey26f7fa72006-10-17 19:33:52 +000053 cl::desc("Turn on alias analysis during testing"));
Jim Laskey3ad175b2006-10-12 15:22:24 +000054
Jim Laskey07a27092006-10-18 19:08:31 +000055 static cl::opt<bool>
56 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
57 cl::desc("Include global information in alias analysis"));
58
Quentin Colombet83f743a2013-10-11 18:29:42 +000059 /// Hidden option to stress test load slicing, i.e., when this option
60 /// is enabled, load slicing bypasses most of its profitability guards.
61 static cl::opt<bool>
62 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
63 cl::desc("Bypass the profitability model of load "
64 "slicing"),
65 cl::init(false));
66
Jim Laskeybc588b82006-10-05 15:07:25 +000067//------------------------------ DAGCombiner ---------------------------------//
68
Nick Lewycky6726b6d2009-10-25 06:33:48 +000069 class DAGCombiner {
Nate Begeman1d4d4142005-09-01 00:19:25 +000070 SelectionDAG &DAG;
Dan Gohman79ce2762009-01-15 19:20:50 +000071 const TargetLowering &TLI;
Duncan Sands25cf2272008-11-24 14:53:14 +000072 CombineLevel Level;
Bill Wendling98a366d2009-04-29 23:29:43 +000073 CodeGenOpt::Level OptLevel;
Duncan Sands25cf2272008-11-24 14:53:14 +000074 bool LegalOperations;
75 bool LegalTypes;
Quentin Colombet83f743a2013-10-11 18:29:42 +000076 bool ForCodeSize;
Nate Begeman1d4d4142005-09-01 00:19:25 +000077
78 // Worklist of all of the nodes that need to be simplified.
James Molloy6660c052012-02-16 09:17:04 +000079 //
80 // This has the semantics that when adding to the worklist,
81 // the item added must be next to be processed. It should
82 // also only appear once. The naive approach to this takes
83 // linear time.
84 //
85 // To reduce the insert/remove time to logarithmic, we use
86 // a set and a vector to maintain our worklist.
87 //
88 // The set contains the items on the worklist, but does not
89 // maintain the order they should be visited.
90 //
91 // The vector maintains the order nodes should be visited, but may
92 // contain duplicate or removed nodes. When choosing a node to
93 // visit, we pop off the order stack until we find an item that is
94 // also in the contents set. All operations are O(log N).
95 SmallPtrSet<SDNode*, 64> WorkListContents;
Benjamin Kramerd5f76902012-03-10 00:23:58 +000096 SmallVector<SDNode*, 64> WorkListOrder;
Nate Begeman1d4d4142005-09-01 00:19:25 +000097
Jim Laskeyc7c3f112006-10-16 20:52:31 +000098 // AA - Used for DAG load/store alias analysis.
99 AliasAnalysis &AA;
100
Nate Begeman1d4d4142005-09-01 00:19:25 +0000101 /// AddUsersToWorkList - When an instruction is simplified, add all users of
102 /// the instruction to the work lists because they might get more simplified
103 /// now.
104 ///
105 void AddUsersToWorkList(SDNode *N) {
106 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
Nate Begeman4ebd8052005-09-01 23:24:04 +0000107 UI != UE; ++UI)
Dan Gohman89684502008-07-27 20:43:25 +0000108 AddToWorkList(*UI);
Nate Begeman1d4d4142005-09-01 00:19:25 +0000109 }
110
Dan Gohman389079b2007-10-08 17:57:15 +0000111 /// visit - call the node-specific routine that knows how to fold each
112 /// particular type of node.
Dan Gohman475871a2008-07-27 21:46:04 +0000113 SDValue visit(SDNode *N);
Dan Gohman389079b2007-10-08 17:57:15 +0000114
Chris Lattner24664722006-03-01 04:53:38 +0000115 public:
James Molloy6afa3f72012-02-16 09:48:07 +0000116 /// AddToWorkList - Add to the work list making sure its instance is at the
James Molloy6660c052012-02-16 09:17:04 +0000117 /// back (next to be processed.)
Chris Lattner5750df92006-03-01 04:03:14 +0000118 void AddToWorkList(SDNode *N) {
James Molloy6660c052012-02-16 09:17:04 +0000119 WorkListContents.insert(N);
120 WorkListOrder.push_back(N);
Chris Lattner5750df92006-03-01 04:03:14 +0000121 }
Jim Laskey6ff23e52006-10-04 16:53:27 +0000122
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000123 /// removeFromWorkList - remove all instances of N from the worklist.
124 ///
125 void removeFromWorkList(SDNode *N) {
James Molloy6660c052012-02-16 09:17:04 +0000126 WorkListContents.erase(N);
Chris Lattner01a22022005-10-10 22:04:48 +0000127 }
Scott Michelfdc40a02009-02-17 22:15:04 +0000128
Dan Gohman475871a2008-07-27 21:46:04 +0000129 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
Evan Cheng0b0cd912009-03-28 05:57:29 +0000130 bool AddTo = true);
Scott Michelfdc40a02009-02-17 22:15:04 +0000131
Dan Gohman475871a2008-07-27 21:46:04 +0000132 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
Jim Laskey274062c2006-10-13 23:32:28 +0000133 return CombineTo(N, &Res, 1, AddTo);
Chris Lattner24664722006-03-01 04:53:38 +0000134 }
Scott Michelfdc40a02009-02-17 22:15:04 +0000135
Dan Gohman475871a2008-07-27 21:46:04 +0000136 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
Evan Cheng0b0cd912009-03-28 05:57:29 +0000137 bool AddTo = true) {
Dan Gohman475871a2008-07-27 21:46:04 +0000138 SDValue To[] = { Res0, Res1 };
Jim Laskey274062c2006-10-13 23:32:28 +0000139 return CombineTo(N, To, 2, AddTo);
Chris Lattner24664722006-03-01 04:53:38 +0000140 }
Dan Gohmane5af2d32009-01-29 01:59:02 +0000141
142 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
Scott Michelfdc40a02009-02-17 22:15:04 +0000143
144 private:
145
Chris Lattner012f2412006-02-17 21:58:01 +0000146 /// SimplifyDemandedBits - Check the specified integer node value to see if
Chris Lattnerb2742f42006-03-01 19:55:35 +0000147 /// it can be simplified or if things it uses can be simplified by bit
Chris Lattner012f2412006-02-17 21:58:01 +0000148 /// propagation. If so, return true.
Dan Gohman475871a2008-07-27 21:46:04 +0000149 bool SimplifyDemandedBits(SDValue Op) {
Dan Gohman87862e72009-12-11 21:31:27 +0000150 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
151 APInt Demanded = APInt::getAllOnesValue(BitWidth);
Dan Gohman7b8d4a92008-02-27 00:25:32 +0000152 return SimplifyDemandedBits(Op, Demanded);
153 }
154
Dan Gohman475871a2008-07-27 21:46:04 +0000155 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
Chris Lattner87514ca2005-10-10 22:31:19 +0000156
Chris Lattner448f2192006-11-11 00:39:41 +0000157 bool CombineToPreIndexedLoadStore(SDNode *N);
158 bool CombineToPostIndexedLoadStore(SDNode *N);
Quentin Colombet83f743a2013-10-11 18:29:42 +0000159 bool SliceUpLoad(SDNode *N);
Scott Michelfdc40a02009-02-17 22:15:04 +0000160
Evan Cheng95c57ea2010-04-24 04:43:44 +0000161 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
162 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
163 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
164 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
Evan Cheng64b7bf72010-04-16 06:14:10 +0000165 SDValue PromoteIntBinOp(SDValue Op);
Evan Cheng07c4e102010-04-22 20:19:46 +0000166 SDValue PromoteIntShiftOp(SDValue Op);
Evan Cheng4c26e932010-04-19 19:29:22 +0000167 SDValue PromoteExtend(SDValue Op);
168 bool PromoteLoad(SDValue Op);
Scott Michelfdc40a02009-02-17 22:15:04 +0000169
Craig Topper6c64fba2013-07-13 07:43:40 +0000170 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickac6d9be2013-05-25 02:42:55 +0000171 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +0000172 ISD::NodeType ExtType);
173
Dan Gohman389079b2007-10-08 17:57:15 +0000174 /// combine - call the node-specific routine that knows how to fold each
175 /// particular type of node. If that doesn't do anything, try the
176 /// target-specific DAG combines.
Dan Gohman475871a2008-07-27 21:46:04 +0000177 SDValue combine(SDNode *N);
Nate Begeman1d4d4142005-09-01 00:19:25 +0000178
179 // Visitation implementation - Implement dag node combining for different
180 // node types. The semantics are as follows:
181 // Return Value:
Evan Cheng17a568b2008-08-29 22:21:44 +0000182 // SDValue.getNode() == 0 - No change was made
183 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
184 // otherwise - N should be replaced by the returned Operand.
Nate Begeman1d4d4142005-09-01 00:19:25 +0000185 //
Dan Gohman475871a2008-07-27 21:46:04 +0000186 SDValue visitTokenFactor(SDNode *N);
187 SDValue visitMERGE_VALUES(SDNode *N);
188 SDValue visitADD(SDNode *N);
189 SDValue visitSUB(SDNode *N);
190 SDValue visitADDC(SDNode *N);
Craig Toppercc274522012-01-07 09:06:39 +0000191 SDValue visitSUBC(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000192 SDValue visitADDE(SDNode *N);
Craig Toppercc274522012-01-07 09:06:39 +0000193 SDValue visitSUBE(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000194 SDValue visitMUL(SDNode *N);
195 SDValue visitSDIV(SDNode *N);
196 SDValue visitUDIV(SDNode *N);
197 SDValue visitSREM(SDNode *N);
198 SDValue visitUREM(SDNode *N);
199 SDValue visitMULHU(SDNode *N);
200 SDValue visitMULHS(SDNode *N);
201 SDValue visitSMUL_LOHI(SDNode *N);
202 SDValue visitUMUL_LOHI(SDNode *N);
Benjamin Kramerf55d26e2011-05-21 18:31:55 +0000203 SDValue visitSMULO(SDNode *N);
204 SDValue visitUMULO(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000205 SDValue visitSDIVREM(SDNode *N);
206 SDValue visitUDIVREM(SDNode *N);
207 SDValue visitAND(SDNode *N);
208 SDValue visitOR(SDNode *N);
209 SDValue visitXOR(SDNode *N);
210 SDValue SimplifyVBinOp(SDNode *N);
Craig Topperdd201ff2012-09-11 01:45:21 +0000211 SDValue SimplifyVUnaryOp(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000212 SDValue visitSHL(SDNode *N);
213 SDValue visitSRA(SDNode *N);
214 SDValue visitSRL(SDNode *N);
215 SDValue visitCTLZ(SDNode *N);
Chandler Carruth63974b22011-12-13 01:56:10 +0000216 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000217 SDValue visitCTTZ(SDNode *N);
Chandler Carruth63974b22011-12-13 01:56:10 +0000218 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000219 SDValue visitCTPOP(SDNode *N);
220 SDValue visitSELECT(SDNode *N);
Benjamin Kramer6242fda2013-04-26 09:19:19 +0000221 SDValue visitVSELECT(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000222 SDValue visitSELECT_CC(SDNode *N);
223 SDValue visitSETCC(SDNode *N);
224 SDValue visitSIGN_EXTEND(SDNode *N);
225 SDValue visitZERO_EXTEND(SDNode *N);
226 SDValue visitANY_EXTEND(SDNode *N);
227 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
228 SDValue visitTRUNCATE(SDNode *N);
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000229 SDValue visitBITCAST(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000230 SDValue visitBUILD_PAIR(SDNode *N);
231 SDValue visitFADD(SDNode *N);
232 SDValue visitFSUB(SDNode *N);
233 SDValue visitFMUL(SDNode *N);
Owen Anderson062c0a52012-05-02 22:17:40 +0000234 SDValue visitFMA(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000235 SDValue visitFDIV(SDNode *N);
236 SDValue visitFREM(SDNode *N);
237 SDValue visitFCOPYSIGN(SDNode *N);
238 SDValue visitSINT_TO_FP(SDNode *N);
239 SDValue visitUINT_TO_FP(SDNode *N);
240 SDValue visitFP_TO_SINT(SDNode *N);
241 SDValue visitFP_TO_UINT(SDNode *N);
242 SDValue visitFP_ROUND(SDNode *N);
243 SDValue visitFP_ROUND_INREG(SDNode *N);
244 SDValue visitFP_EXTEND(SDNode *N);
245 SDValue visitFNEG(SDNode *N);
246 SDValue visitFABS(SDNode *N);
Owen Anderson7c626d32012-08-13 23:32:49 +0000247 SDValue visitFCEIL(SDNode *N);
248 SDValue visitFTRUNC(SDNode *N);
249 SDValue visitFFLOOR(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000250 SDValue visitBRCOND(SDNode *N);
251 SDValue visitBR_CC(SDNode *N);
252 SDValue visitLOAD(SDNode *N);
253 SDValue visitSTORE(SDNode *N);
254 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
255 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
256 SDValue visitBUILD_VECTOR(SDNode *N);
257 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopese97190f2011-09-20 23:19:33 +0000258 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000259 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Chris Lattner01a22022005-10-10 22:04:48 +0000260
Dan Gohman475871a2008-07-27 21:46:04 +0000261 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickac6d9be2013-05-25 02:42:55 +0000262 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelfdc40a02009-02-17 22:15:04 +0000263
Dan Gohman475871a2008-07-27 21:46:04 +0000264 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
Chris Lattnere70da202007-12-06 07:33:36 +0000265
Dan Gohman475871a2008-07-27 21:46:04 +0000266 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
267 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickac6d9be2013-05-25 02:42:55 +0000268 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
269 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelfdc40a02009-02-17 22:15:04 +0000270 SDValue N3, ISD::CondCode CC,
Bill Wendling836ca7d2009-01-30 23:59:18 +0000271 bool NotExtCompare = false);
Owen Andersone50ed302009-08-10 22:56:29 +0000272 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickac6d9be2013-05-25 02:42:55 +0000273 SDLoc DL, bool foldBooleans = true);
Scott Michelfdc40a02009-02-17 22:15:04 +0000274 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner5eee4272008-01-26 01:09:19 +0000275 unsigned HiOp);
Owen Andersone50ed302009-08-10 22:56:29 +0000276 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000277 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman475871a2008-07-27 21:46:04 +0000278 SDValue BuildSDIV(SDNode *N);
279 SDValue BuildUDIV(SDNode *N);
Evan Cheng9568e5c2011-06-21 06:01:08 +0000280 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
281 bool DemandHighBits = true);
282 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Andrew Trickac6d9be2013-05-25 02:42:55 +0000283 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman475871a2008-07-27 21:46:04 +0000284 SDValue ReduceLoadWidth(SDNode *N);
Evan Cheng8b944d32009-05-28 00:35:15 +0000285 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Cheng31959b12011-02-02 01:06:55 +0000286 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liaofac14ab2012-10-23 23:06:52 +0000287 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao1a5cc712012-10-24 04:14:18 +0000288 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelfdc40a02009-02-17 22:15:04 +0000289
Dan Gohman475871a2008-07-27 21:46:04 +0000290 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelfdc40a02009-02-17 22:15:04 +0000291
Jim Laskey6ff23e52006-10-04 16:53:27 +0000292 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
293 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman475871a2008-07-27 21:46:04 +0000294 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Toppera0ec3f92013-07-14 04:42:23 +0000295 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey6ff23e52006-10-04 16:53:27 +0000296
Jim Laskey096c22e2006-10-18 12:29:57 +0000297 /// isAlias - Return true if there is any possibility that the two addresses
298 /// overlap.
Richard Sandiforda7be36c2013-10-28 12:00:00 +0000299 bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
Jim Laskey096c22e2006-10-18 12:29:57 +0000300 const Value *SrcValue1, int SrcValueOffset1,
Nate Begemanb6aef5c2009-09-15 00:18:30 +0000301 unsigned SrcValueAlign1,
Dan Gohmanf96e4bd2010-10-20 00:31:05 +0000302 const MDNode *TBAAInfo1,
Richard Sandiforda7be36c2013-10-28 12:00:00 +0000303 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
Nate Begemanb6aef5c2009-09-15 00:18:30 +0000304 const Value *SrcValue2, int SrcValueOffset2,
Dan Gohmanf96e4bd2010-10-20 00:31:05 +0000305 unsigned SrcValueAlign2,
306 const MDNode *TBAAInfo2) const;
Scott Michelfdc40a02009-02-17 22:15:04 +0000307
Nadav Rotem90e11dc2012-11-29 00:00:08 +0000308 /// isAlias - Return true if there is any possibility that the two addresses
309 /// overlap.
310 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
311
Jim Laskey7ca56af2006-10-11 13:47:09 +0000312 /// FindAliasInfo - Extracts the relevant alias information from the memory
313 /// node. Returns true if the operand was a load.
314 bool FindAliasInfo(SDNode *N,
Richard Sandiforda7be36c2013-10-28 12:00:00 +0000315 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
Nate Begemanb6aef5c2009-09-15 00:18:30 +0000316 const Value *&SrcValue, int &SrcValueOffset,
Dan Gohmanf96e4bd2010-10-20 00:31:05 +0000317 unsigned &SrcValueAlignment,
318 const MDNode *&TBAAInfo) const;
Scott Michelfdc40a02009-02-17 22:15:04 +0000319
Jim Laskey279f0532006-09-25 16:29:54 +0000320 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
Jim Laskey6ff23e52006-10-04 16:53:27 +0000321 /// looking for a better chain (aliasing node.)
Dan Gohman475871a2008-07-27 21:46:04 +0000322 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands92abc622009-01-31 15:50:11 +0000323
Nadav Rotemc653de62012-10-03 16:11:15 +0000324 /// Merge consecutive store operations into a wide store.
325 /// This optimization uses wide integers or vectors when possible.
326 /// \return True if some memory operations were changed.
327 bool MergeConsecutiveStores(StoreSDNode *N);
328
Chris Lattner2392ae72010-04-15 04:48:01 +0000329 public:
Bill Wendling98a366d2009-04-29 23:29:43 +0000330 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombet83f743a2013-10-11 18:29:42 +0000331 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
332 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
333 AttributeSet FnAttrs =
334 DAG.getMachineFunction().getFunction()->getAttributes();
335 ForCodeSize =
336 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
337 Attribute::OptimizeForSize) ||
338 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
339 }
Scott Michelfdc40a02009-02-17 22:15:04 +0000340
Nate Begeman1d4d4142005-09-01 00:19:25 +0000341 /// Run - runs the dag combiner on all nodes in the work list
Duncan Sands25cf2272008-11-24 14:53:14 +0000342 void Run(CombineLevel AtLevel);
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000343
Chris Lattner2392ae72010-04-15 04:48:01 +0000344 SelectionDAG &getDAG() const { return DAG; }
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000345
Chris Lattner2392ae72010-04-15 04:48:01 +0000346 /// getShiftAmountTy - Returns a type large enough to hold any valid
347 /// shift amount - before type legalization these can be huge.
Owen Anderson95771af2011-02-25 21:41:48 +0000348 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky87070fe2013-06-26 10:55:03 +0000349 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
350 if (LHSTy.isVector())
351 return LHSTy;
Jack Carteradbd3ae2013-10-17 01:34:33 +0000352 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
353 : TLI.getPointerTy();
Chris Lattner2392ae72010-04-15 04:48:01 +0000354 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000355
Chris Lattner2392ae72010-04-15 04:48:01 +0000356 /// isTypeLegal - This method returns true if we are running before type
357 /// legalization or if the specified VT is legal.
358 bool isTypeLegal(const EVT &VT) {
359 if (!LegalTypes) return true;
360 return TLI.isTypeLegal(VT);
361 }
Matt Arsenault225ed702013-05-18 00:21:46 +0000362
363 /// getSetCCResultType - Convenience wrapper around
364 /// TargetLowering::getSetCCResultType
365 EVT getSetCCResultType(EVT VT) const {
366 return TLI.getSetCCResultType(*DAG.getContext(), VT);
367 }
Nate Begeman1d4d4142005-09-01 00:19:25 +0000368 };
369}
370
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000371
372namespace {
373/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
374/// nodes from the worklist.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000375class WorkListRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000376 DAGCombiner &DC;
377public:
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +0000378 explicit WorkListRemover(DAGCombiner &dc)
379 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelfdc40a02009-02-17 22:15:04 +0000380
Duncan Sandsedfcf592008-06-11 11:42:12 +0000381 virtual void NodeDeleted(SDNode *N, SDNode *E) {
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000382 DC.removeFromWorkList(N);
383 }
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000384};
385}
386
Chris Lattner24664722006-03-01 04:53:38 +0000387//===----------------------------------------------------------------------===//
388// TargetLowering::DAGCombinerInfo implementation
389//===----------------------------------------------------------------------===//
390
391void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
392 ((DAGCombiner*)DC)->AddToWorkList(N);
393}
394
Cameron Zwariched3caf92011-04-02 02:40:26 +0000395void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
396 ((DAGCombiner*)DC)->removeFromWorkList(N);
397}
398
Dan Gohman475871a2008-07-27 21:46:04 +0000399SDValue TargetLowering::DAGCombinerInfo::
Evan Cheng0b0cd912009-03-28 05:57:29 +0000400CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
401 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattner24664722006-03-01 04:53:38 +0000402}
403
Dan Gohman475871a2008-07-27 21:46:04 +0000404SDValue TargetLowering::DAGCombinerInfo::
Evan Cheng0b0cd912009-03-28 05:57:29 +0000405CombineTo(SDNode *N, SDValue Res, bool AddTo) {
406 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattner24664722006-03-01 04:53:38 +0000407}
408
409
Dan Gohman475871a2008-07-27 21:46:04 +0000410SDValue TargetLowering::DAGCombinerInfo::
Evan Cheng0b0cd912009-03-28 05:57:29 +0000411CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
412 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattner24664722006-03-01 04:53:38 +0000413}
414
Dan Gohmane5af2d32009-01-29 01:59:02 +0000415void TargetLowering::DAGCombinerInfo::
416CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
417 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
418}
Chris Lattner24664722006-03-01 04:53:38 +0000419
Chris Lattner24664722006-03-01 04:53:38 +0000420//===----------------------------------------------------------------------===//
Chris Lattner29446522007-05-14 22:04:50 +0000421// Helper Functions
422//===----------------------------------------------------------------------===//
423
424/// isNegatibleForFree - Return 1 if we can compute the negated form of the
425/// specified expression for the same cost as the expression itself, or 2 if we
426/// can compute the negated form more cheaply than the expression itself.
Duncan Sands25cf2272008-11-24 14:53:14 +0000427static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Andersonafd3d562012-03-06 00:29:31 +0000428 const TargetLowering &TLI,
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000429 const TargetOptions *Options,
Chris Lattner0254e702008-02-26 07:04:54 +0000430 unsigned Depth = 0) {
Chris Lattner29446522007-05-14 22:04:50 +0000431 // fneg is removable even if it has multiple uses.
432 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelfdc40a02009-02-17 22:15:04 +0000433
Chris Lattner29446522007-05-14 22:04:50 +0000434 // Don't allow anything with multiple uses.
435 if (!Op.hasOneUse()) return 0;
Scott Michelfdc40a02009-02-17 22:15:04 +0000436
Chris Lattner3adf9512007-05-25 02:19:06 +0000437 // Don't recurse exponentially.
438 if (Depth > 6) return 0;
Scott Michelfdc40a02009-02-17 22:15:04 +0000439
Chris Lattner29446522007-05-14 22:04:50 +0000440 switch (Op.getOpcode()) {
441 default: return false;
442 case ISD::ConstantFP:
Chris Lattner0254e702008-02-26 07:04:54 +0000443 // Don't invert constant FP values after legalize. The negated constant
444 // isn't necessarily legal.
Duncan Sands25cf2272008-11-24 14:53:14 +0000445 return LegalOperations ? 0 : 1;
Chris Lattner29446522007-05-14 22:04:50 +0000446 case ISD::FADD:
447 // FIXME: determine better conditions for this xform.
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000448 if (!Options->UnsafeFPMath) return 0;
Scott Michelfdc40a02009-02-17 22:15:04 +0000449
Owen Andersonafd3d562012-03-06 00:29:31 +0000450 // After operation legalization, it might not be legal to create new FSUBs.
451 if (LegalOperations &&
452 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
453 return 0;
454
Craig Topper956342b2012-09-09 22:58:45 +0000455 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Andersonafd3d562012-03-06 00:29:31 +0000456 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
457 Options, Depth + 1))
Chris Lattner29446522007-05-14 22:04:50 +0000458 return V;
Bill Wendlingd34470c2009-01-30 23:10:18 +0000459 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Andersonafd3d562012-03-06 00:29:31 +0000460 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000461 Depth + 1);
Chris Lattner29446522007-05-14 22:04:50 +0000462 case ISD::FSUB:
Scott Michelfdc40a02009-02-17 22:15:04 +0000463 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000464 if (!Options->UnsafeFPMath) return 0;
Scott Michelfdc40a02009-02-17 22:15:04 +0000465
Bill Wendlingd34470c2009-01-30 23:10:18 +0000466 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattner29446522007-05-14 22:04:50 +0000467 return 1;
Scott Michelfdc40a02009-02-17 22:15:04 +0000468
Chris Lattner29446522007-05-14 22:04:50 +0000469 case ISD::FMUL:
470 case ISD::FDIV:
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000471 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelfdc40a02009-02-17 22:15:04 +0000472
Bill Wendlingd34470c2009-01-30 23:10:18 +0000473 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Andersonafd3d562012-03-06 00:29:31 +0000474 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
475 Options, Depth + 1))
Chris Lattner29446522007-05-14 22:04:50 +0000476 return V;
Scott Michelfdc40a02009-02-17 22:15:04 +0000477
Owen Andersonafd3d562012-03-06 00:29:31 +0000478 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000479 Depth + 1);
Scott Michelfdc40a02009-02-17 22:15:04 +0000480
Chris Lattner29446522007-05-14 22:04:50 +0000481 case ISD::FP_EXTEND:
482 case ISD::FP_ROUND:
483 case ISD::FSIN:
Owen Andersonafd3d562012-03-06 00:29:31 +0000484 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000485 Depth + 1);
Chris Lattner29446522007-05-14 22:04:50 +0000486 }
487}
488
489/// GetNegatedExpression - If isNegatibleForFree returns true, this function
490/// returns the newly negated expression.
Dan Gohman475871a2008-07-27 21:46:04 +0000491static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sands25cf2272008-11-24 14:53:14 +0000492 bool LegalOperations, unsigned Depth = 0) {
Chris Lattner29446522007-05-14 22:04:50 +0000493 // fneg is removable even if it has multiple uses.
494 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelfdc40a02009-02-17 22:15:04 +0000495
Chris Lattner29446522007-05-14 22:04:50 +0000496 // Don't allow anything with multiple uses.
497 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelfdc40a02009-02-17 22:15:04 +0000498
Chris Lattner3adf9512007-05-25 02:19:06 +0000499 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattner29446522007-05-14 22:04:50 +0000500 switch (Op.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000501 default: llvm_unreachable("Unknown code");
Dale Johannesenc4dd3c32007-08-31 23:34:27 +0000502 case ISD::ConstantFP: {
503 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
504 V.changeSign();
505 return DAG.getConstantFP(V, Op.getValueType());
506 }
Chris Lattner29446522007-05-14 22:04:50 +0000507 case ISD::FADD:
508 // FIXME: determine better conditions for this xform.
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000509 assert(DAG.getTarget().Options.UnsafeFPMath);
Scott Michelfdc40a02009-02-17 22:15:04 +0000510
Bill Wendlingd34470c2009-01-30 23:10:18 +0000511 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000512 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Andersonafd3d562012-03-06 00:29:31 +0000513 DAG.getTargetLoweringInfo(),
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000514 &DAG.getTarget().Options, Depth+1))
Andrew Trickac6d9be2013-05-25 02:42:55 +0000515 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelfdc40a02009-02-17 22:15:04 +0000516 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sands25cf2272008-11-24 14:53:14 +0000517 LegalOperations, Depth+1),
Chris Lattner29446522007-05-14 22:04:50 +0000518 Op.getOperand(1));
Bill Wendlingd34470c2009-01-30 23:10:18 +0000519 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickac6d9be2013-05-25 02:42:55 +0000520 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelfdc40a02009-02-17 22:15:04 +0000521 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sands25cf2272008-11-24 14:53:14 +0000522 LegalOperations, Depth+1),
Chris Lattner29446522007-05-14 22:04:50 +0000523 Op.getOperand(0));
524 case ISD::FSUB:
Scott Michelfdc40a02009-02-17 22:15:04 +0000525 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000526 assert(DAG.getTarget().Options.UnsafeFPMath);
Dan Gohman23ff1822007-07-02 15:48:56 +0000527
Bill Wendlingd34470c2009-01-30 23:10:18 +0000528 // fold (fneg (fsub 0, B)) -> B
Dan Gohman23ff1822007-07-02 15:48:56 +0000529 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesenc4dd3c32007-08-31 23:34:27 +0000530 if (N0CFP->getValueAPF().isZero())
Dan Gohman23ff1822007-07-02 15:48:56 +0000531 return Op.getOperand(1);
Scott Michelfdc40a02009-02-17 22:15:04 +0000532
Bill Wendlingd34470c2009-01-30 23:10:18 +0000533 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickac6d9be2013-05-25 02:42:55 +0000534 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendling35247c32009-01-30 00:45:56 +0000535 Op.getOperand(1), Op.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +0000536
Chris Lattner29446522007-05-14 22:04:50 +0000537 case ISD::FMUL:
538 case ISD::FDIV:
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000539 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
Scott Michelfdc40a02009-02-17 22:15:04 +0000540
Bill Wendlingd34470c2009-01-30 23:10:18 +0000541 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000542 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Andersonafd3d562012-03-06 00:29:31 +0000543 DAG.getTargetLoweringInfo(),
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000544 &DAG.getTarget().Options, Depth+1))
Andrew Trickac6d9be2013-05-25 02:42:55 +0000545 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelfdc40a02009-02-17 22:15:04 +0000546 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sands25cf2272008-11-24 14:53:14 +0000547 LegalOperations, Depth+1),
Chris Lattner29446522007-05-14 22:04:50 +0000548 Op.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +0000549
Bill Wendlingd34470c2009-01-30 23:10:18 +0000550 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickac6d9be2013-05-25 02:42:55 +0000551 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattner29446522007-05-14 22:04:50 +0000552 Op.getOperand(0),
Chris Lattner0254e702008-02-26 07:04:54 +0000553 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sands25cf2272008-11-24 14:53:14 +0000554 LegalOperations, Depth+1));
Scott Michelfdc40a02009-02-17 22:15:04 +0000555
Chris Lattner29446522007-05-14 22:04:50 +0000556 case ISD::FP_EXTEND:
Chris Lattner29446522007-05-14 22:04:50 +0000557 case ISD::FSIN:
Andrew Trickac6d9be2013-05-25 02:42:55 +0000558 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelfdc40a02009-02-17 22:15:04 +0000559 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sands25cf2272008-11-24 14:53:14 +0000560 LegalOperations, Depth+1));
Chris Lattner0bd48932008-01-17 07:00:52 +0000561 case ISD::FP_ROUND:
Andrew Trickac6d9be2013-05-25 02:42:55 +0000562 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelfdc40a02009-02-17 22:15:04 +0000563 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sands25cf2272008-11-24 14:53:14 +0000564 LegalOperations, Depth+1),
Chris Lattner0bd48932008-01-17 07:00:52 +0000565 Op.getOperand(1));
Chris Lattner29446522007-05-14 22:04:50 +0000566 }
567}
Chris Lattner24664722006-03-01 04:53:38 +0000568
569
Nate Begeman4ebd8052005-09-01 23:24:04 +0000570// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
571// that selects between the values 1 and 0, making it equivalent to a setcc.
Scott Michelfdc40a02009-02-17 22:15:04 +0000572// Also, set the incoming LHS, RHS, and CC references to the appropriate
Nate Begeman646d7e22005-09-02 21:18:40 +0000573// nodes based on the type of node we are checking. This simplifies life a
574// bit for the callers.
Dan Gohman475871a2008-07-27 21:46:04 +0000575static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
576 SDValue &CC) {
Nate Begeman646d7e22005-09-02 21:18:40 +0000577 if (N.getOpcode() == ISD::SETCC) {
578 LHS = N.getOperand(0);
579 RHS = N.getOperand(1);
580 CC = N.getOperand(2);
Nate Begeman4ebd8052005-09-01 23:24:04 +0000581 return true;
Nate Begeman646d7e22005-09-02 21:18:40 +0000582 }
Scott Michelfdc40a02009-02-17 22:15:04 +0000583 if (N.getOpcode() == ISD::SELECT_CC &&
Nate Begeman1d4d4142005-09-01 00:19:25 +0000584 N.getOperand(2).getOpcode() == ISD::Constant &&
585 N.getOperand(3).getOpcode() == ISD::Constant &&
Dan Gohman002e5d02008-03-13 22:13:53 +0000586 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
Nate Begeman646d7e22005-09-02 21:18:40 +0000587 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
588 LHS = N.getOperand(0);
589 RHS = N.getOperand(1);
590 CC = N.getOperand(4);
Nate Begeman1d4d4142005-09-01 00:19:25 +0000591 return true;
Nate Begeman646d7e22005-09-02 21:18:40 +0000592 }
Nate Begeman1d4d4142005-09-01 00:19:25 +0000593 return false;
594}
595
Nate Begeman99801192005-09-07 23:25:52 +0000596// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
597// one use. If this is true, it allows the users to invert the operation for
598// free when it is profitable to do so.
Dan Gohman475871a2008-07-27 21:46:04 +0000599static bool isOneUseSetCC(SDValue N) {
600 SDValue N0, N1, N2;
Gabor Greifba36cb52008-08-28 21:40:38 +0000601 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman4ebd8052005-09-01 23:24:04 +0000602 return true;
603 return false;
604}
605
Andrew Trickac6d9be2013-05-25 02:42:55 +0000606SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendling35247c32009-01-30 00:45:56 +0000607 SDValue N0, SDValue N1) {
Owen Andersone50ed302009-08-10 22:56:29 +0000608 EVT VT = N0.getValueType();
Nate Begemancd4d58c2006-02-03 06:46:56 +0000609 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
610 if (isa<ConstantSDNode>(N1)) {
Bill Wendling35247c32009-01-30 00:45:56 +0000611 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
Bill Wendling6af76182009-01-30 20:50:00 +0000612 SDValue OpNode =
613 DAG.FoldConstantArithmetic(Opc, VT,
614 cast<ConstantSDNode>(N0.getOperand(1)),
615 cast<ConstantSDNode>(N1));
Bill Wendlingd69c3142009-01-30 02:23:43 +0000616 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
Dan Gohman71dc7c92011-05-17 22:20:36 +0000617 }
618 if (N0.hasOneUse()) {
Sylvestre Ledru94c22712012-09-27 10:14:43 +0000619 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
Andrew Trickac6d9be2013-05-25 02:42:55 +0000620 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
Bill Wendling35247c32009-01-30 00:45:56 +0000621 N0.getOperand(0), N1);
Gabor Greifba36cb52008-08-28 21:40:38 +0000622 AddToWorkList(OpNode.getNode());
Bill Wendling35247c32009-01-30 00:45:56 +0000623 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Nate Begemancd4d58c2006-02-03 06:46:56 +0000624 }
625 }
Bill Wendling35247c32009-01-30 00:45:56 +0000626
Nate Begemancd4d58c2006-02-03 06:46:56 +0000627 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
628 if (isa<ConstantSDNode>(N0)) {
Bill Wendling35247c32009-01-30 00:45:56 +0000629 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
Bill Wendling6af76182009-01-30 20:50:00 +0000630 SDValue OpNode =
631 DAG.FoldConstantArithmetic(Opc, VT,
632 cast<ConstantSDNode>(N1.getOperand(1)),
633 cast<ConstantSDNode>(N0));
Bill Wendlingd69c3142009-01-30 02:23:43 +0000634 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
Dan Gohman71dc7c92011-05-17 22:20:36 +0000635 }
636 if (N1.hasOneUse()) {
Sylvestre Ledru94c22712012-09-27 10:14:43 +0000637 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
Andrew Trickac6d9be2013-05-25 02:42:55 +0000638 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
Bill Wendling35247c32009-01-30 00:45:56 +0000639 N1.getOperand(0), N0);
Gabor Greifba36cb52008-08-28 21:40:38 +0000640 AddToWorkList(OpNode.getNode());
Bill Wendling35247c32009-01-30 00:45:56 +0000641 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
Nate Begemancd4d58c2006-02-03 06:46:56 +0000642 }
643 }
Bill Wendling35247c32009-01-30 00:45:56 +0000644
Dan Gohman475871a2008-07-27 21:46:04 +0000645 return SDValue();
Nate Begemancd4d58c2006-02-03 06:46:56 +0000646}
647
Dan Gohman475871a2008-07-27 21:46:04 +0000648SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
649 bool AddTo) {
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000650 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
651 ++NodesCombined;
David Greenef1090292010-01-05 01:25:00 +0000652 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000653 N->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +0000654 dbgs() << "\nWith: ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000655 To[0].getNode()->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +0000656 dbgs() << " and " << NumTo-1 << " other values\n";
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000657 for (unsigned i = 0, e = NumTo; i != e; ++i)
Jakob Stoklund Olesen9f0d4e62009-12-03 05:15:35 +0000658 assert((!To[i].getNode() ||
659 N->getValueType(i) == To[i].getValueType()) &&
Dan Gohman764fd0c2009-01-21 15:17:51 +0000660 "Cannot combine value to value of different type!"));
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000661 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +0000662 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000663 if (AddTo) {
664 // Push the new nodes and any users onto the worklist
665 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattnerd1980a52009-03-12 06:52:53 +0000666 if (To[i].getNode()) {
667 AddToWorkList(To[i].getNode());
668 AddUsersToWorkList(To[i].getNode());
669 }
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000670 }
671 }
Scott Michelfdc40a02009-02-17 22:15:04 +0000672
Dan Gohmandbe664a2009-01-19 21:44:21 +0000673 // Finally, if the node is now dead, remove it from the graph. The node
674 // may not be dead if the replacement process recursively simplified to
675 // something else needing this node.
676 if (N->use_empty()) {
677 // Nodes can be reintroduced into the worklist. Make sure we do not
678 // process a node that has been replaced.
679 removeFromWorkList(N);
Scott Michelfdc40a02009-02-17 22:15:04 +0000680
Dan Gohmandbe664a2009-01-19 21:44:21 +0000681 // Finally, since the node is now dead, remove it from the graph.
682 DAG.DeleteNode(N);
683 }
Dan Gohman475871a2008-07-27 21:46:04 +0000684 return SDValue(N, 0);
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000685}
686
Evan Chenge5b51ac2010-04-17 06:13:15 +0000687void DAGCombiner::
688CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelfdc40a02009-02-17 22:15:04 +0000689 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000690 // are deleted, make sure to remove them from our worklist.
691 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +0000692 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane5af2d32009-01-29 01:59:02 +0000693
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000694 // Push the new node and any (possibly new) users onto the worklist.
Gabor Greifba36cb52008-08-28 21:40:38 +0000695 AddToWorkList(TLO.New.getNode());
696 AddUsersToWorkList(TLO.New.getNode());
Scott Michelfdc40a02009-02-17 22:15:04 +0000697
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000698 // Finally, if the node is now dead, remove it from the graph. The node
699 // may not be dead if the replacement process recursively simplified to
700 // something else needing this node.
Gabor Greifba36cb52008-08-28 21:40:38 +0000701 if (TLO.Old.getNode()->use_empty()) {
702 removeFromWorkList(TLO.Old.getNode());
Scott Michelfdc40a02009-02-17 22:15:04 +0000703
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000704 // If the operands of this node are only used by the node, they will now
705 // be dead. Make sure to visit them first to delete dead nodes early.
Gabor Greifba36cb52008-08-28 21:40:38 +0000706 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
707 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
708 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
Scott Michelfdc40a02009-02-17 22:15:04 +0000709
Gabor Greifba36cb52008-08-28 21:40:38 +0000710 DAG.DeleteNode(TLO.Old.getNode());
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000711 }
Dan Gohmane5af2d32009-01-29 01:59:02 +0000712}
713
714/// SimplifyDemandedBits - Check the specified integer node value to see if
715/// it can be simplified or if things it uses can be simplified by bit
716/// propagation. If so, return true.
717bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chenge5b51ac2010-04-17 06:13:15 +0000718 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane5af2d32009-01-29 01:59:02 +0000719 APInt KnownZero, KnownOne;
720 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
721 return false;
Scott Michelfdc40a02009-02-17 22:15:04 +0000722
Dan Gohmane5af2d32009-01-29 01:59:02 +0000723 // Revisit the node.
724 AddToWorkList(Op.getNode());
Scott Michelfdc40a02009-02-17 22:15:04 +0000725
Dan Gohmane5af2d32009-01-29 01:59:02 +0000726 // Replace the old value with the new one.
727 ++NodesCombined;
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000728 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000729 TLO.Old.getNode()->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +0000730 dbgs() << "\nWith: ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000731 TLO.New.getNode()->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +0000732 dbgs() << '\n');
Scott Michelfdc40a02009-02-17 22:15:04 +0000733
Dan Gohmane5af2d32009-01-29 01:59:02 +0000734 CommitTargetLoweringOpt(TLO);
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000735 return true;
736}
737
Evan Cheng95c57ea2010-04-24 04:43:44 +0000738void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickac6d9be2013-05-25 02:42:55 +0000739 SDLoc dl(Load);
Evan Cheng95c57ea2010-04-24 04:43:44 +0000740 EVT VT = Load->getValueType(0);
741 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Cheng4c26e932010-04-19 19:29:22 +0000742
Evan Cheng95c57ea2010-04-24 04:43:44 +0000743 DEBUG(dbgs() << "\nReplacing.9 ";
744 Load->dump(&DAG);
745 dbgs() << "\nWith: ";
746 Trunc.getNode()->dump(&DAG);
747 dbgs() << '\n');
748 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +0000749 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
750 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Evan Cheng95c57ea2010-04-24 04:43:44 +0000751 removeFromWorkList(Load);
752 DAG.DeleteNode(Load);
Evan Chengac7eae52010-04-27 19:48:13 +0000753 AddToWorkList(Trunc.getNode());
Evan Cheng95c57ea2010-04-24 04:43:44 +0000754}
755
756SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
757 Replace = false;
Andrew Trickac6d9be2013-05-25 02:42:55 +0000758 SDLoc dl(Op);
Evan Chenge5b51ac2010-04-17 06:13:15 +0000759 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chengac7eae52010-04-27 19:48:13 +0000760 EVT MemVT = LD->getMemoryVT();
761 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Anderson95771af2011-02-25 21:41:48 +0000762 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopher503a64d2010-12-09 04:48:06 +0000763 : ISD::EXTLOAD)
Evan Chengac7eae52010-04-27 19:48:13 +0000764 : LD->getExtensionType();
Evan Cheng95c57ea2010-04-24 04:43:44 +0000765 Replace = true;
Stuart Hastingsa9011292011-02-16 16:23:55 +0000766 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge5b51ac2010-04-17 06:13:15 +0000767 LD->getChain(), LD->getBasePtr(),
Richard Sandiford66589dc2013-10-28 11:17:59 +0000768 MemVT, LD->getMemOperand());
Evan Chenge5b51ac2010-04-17 06:13:15 +0000769 }
770
Evan Cheng4c26e932010-04-19 19:29:22 +0000771 unsigned Opc = Op.getOpcode();
Evan Chengcaf77402010-04-23 19:10:30 +0000772 switch (Opc) {
773 default: break;
774 case ISD::AssertSext:
Evan Cheng4c26e932010-04-19 19:29:22 +0000775 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng95c57ea2010-04-24 04:43:44 +0000776 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Cheng4c26e932010-04-19 19:29:22 +0000777 Op.getOperand(1));
Evan Chengcaf77402010-04-23 19:10:30 +0000778 case ISD::AssertZext:
Evan Cheng4c26e932010-04-19 19:29:22 +0000779 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng95c57ea2010-04-24 04:43:44 +0000780 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Cheng4c26e932010-04-19 19:29:22 +0000781 Op.getOperand(1));
Evan Chengcaf77402010-04-23 19:10:30 +0000782 case ISD::Constant: {
783 unsigned ExtOpc =
Evan Cheng4c26e932010-04-19 19:29:22 +0000784 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengcaf77402010-04-23 19:10:30 +0000785 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000786 }
Evan Chengcaf77402010-04-23 19:10:30 +0000787 }
788
789 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chenge5b51ac2010-04-17 06:13:15 +0000790 return SDValue();
Evan Chengcaf77402010-04-23 19:10:30 +0000791 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Cheng64b7bf72010-04-16 06:14:10 +0000792}
793
Evan Cheng95c57ea2010-04-24 04:43:44 +0000794SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chenge5b51ac2010-04-17 06:13:15 +0000795 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
796 return SDValue();
797 EVT OldVT = Op.getValueType();
Andrew Trickac6d9be2013-05-25 02:42:55 +0000798 SDLoc dl(Op);
Evan Cheng95c57ea2010-04-24 04:43:44 +0000799 bool Replace = false;
800 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
801 if (NewOp.getNode() == 0)
Evan Chenge5b51ac2010-04-17 06:13:15 +0000802 return SDValue();
Evan Chengac7eae52010-04-27 19:48:13 +0000803 AddToWorkList(NewOp.getNode());
Evan Cheng95c57ea2010-04-24 04:43:44 +0000804
805 if (Replace)
806 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
807 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chenge5b51ac2010-04-17 06:13:15 +0000808 DAG.getValueType(OldVT));
809}
810
Evan Cheng95c57ea2010-04-24 04:43:44 +0000811SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chenge5b51ac2010-04-17 06:13:15 +0000812 EVT OldVT = Op.getValueType();
Andrew Trickac6d9be2013-05-25 02:42:55 +0000813 SDLoc dl(Op);
Evan Cheng95c57ea2010-04-24 04:43:44 +0000814 bool Replace = false;
815 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
816 if (NewOp.getNode() == 0)
Evan Chenge5b51ac2010-04-17 06:13:15 +0000817 return SDValue();
Evan Chengac7eae52010-04-27 19:48:13 +0000818 AddToWorkList(NewOp.getNode());
Evan Cheng95c57ea2010-04-24 04:43:44 +0000819
820 if (Replace)
821 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
822 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chenge5b51ac2010-04-17 06:13:15 +0000823}
824
Evan Cheng64b7bf72010-04-16 06:14:10 +0000825/// PromoteIntBinOp - Promote the specified integer binary operation if the
826/// target indicates it is beneficial. e.g. On x86, it's usually better to
827/// promote i16 operations to i32 since i16 instructions are longer.
828SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
829 if (!LegalOperations)
830 return SDValue();
831
832 EVT VT = Op.getValueType();
833 if (VT.isVector() || !VT.isInteger())
834 return SDValue();
835
Evan Chenge5b51ac2010-04-17 06:13:15 +0000836 // If operation type is 'undesirable', e.g. i16 on x86, consider
837 // promoting it.
838 unsigned Opc = Op.getOpcode();
839 if (TLI.isTypeDesirableForOp(Opc, VT))
840 return SDValue();
841
Evan Cheng64b7bf72010-04-16 06:14:10 +0000842 EVT PVT = VT;
Evan Chenge5b51ac2010-04-17 06:13:15 +0000843 // Consult target whether it is a good idea to promote this operation and
844 // what's the right type to promote it to.
845 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Cheng64b7bf72010-04-16 06:14:10 +0000846 assert(PVT != VT && "Don't know what type to promote to!");
847
Evan Cheng95c57ea2010-04-24 04:43:44 +0000848 bool Replace0 = false;
849 SDValue N0 = Op.getOperand(0);
850 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
851 if (NN0.getNode() == 0)
Evan Cheng07c4e102010-04-22 20:19:46 +0000852 return SDValue();
853
Evan Cheng95c57ea2010-04-24 04:43:44 +0000854 bool Replace1 = false;
855 SDValue N1 = Op.getOperand(1);
Evan Chengaad753b2010-05-10 19:03:57 +0000856 SDValue NN1;
857 if (N0 == N1)
858 NN1 = NN0;
859 else {
860 NN1 = PromoteOperand(N1, PVT, Replace1);
861 if (NN1.getNode() == 0)
862 return SDValue();
863 }
Evan Cheng07c4e102010-04-22 20:19:46 +0000864
Evan Cheng95c57ea2010-04-24 04:43:44 +0000865 AddToWorkList(NN0.getNode());
Evan Chengaad753b2010-05-10 19:03:57 +0000866 if (NN1.getNode())
867 AddToWorkList(NN1.getNode());
Evan Cheng95c57ea2010-04-24 04:43:44 +0000868
869 if (Replace0)
870 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
871 if (Replace1)
872 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Cheng07c4e102010-04-22 20:19:46 +0000873
Evan Chengac7eae52010-04-27 19:48:13 +0000874 DEBUG(dbgs() << "\nPromoting ";
875 Op.getNode()->dump(&DAG));
Andrew Trickac6d9be2013-05-25 02:42:55 +0000876 SDLoc dl(Op);
Evan Cheng07c4e102010-04-22 20:19:46 +0000877 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng95c57ea2010-04-24 04:43:44 +0000878 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Cheng07c4e102010-04-22 20:19:46 +0000879 }
880 return SDValue();
881}
882
883/// PromoteIntShiftOp - Promote the specified integer shift operation if the
884/// target indicates it is beneficial. e.g. On x86, it's usually better to
885/// promote i16 operations to i32 since i16 instructions are longer.
886SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
887 if (!LegalOperations)
888 return SDValue();
889
890 EVT VT = Op.getValueType();
891 if (VT.isVector() || !VT.isInteger())
892 return SDValue();
893
894 // If operation type is 'undesirable', e.g. i16 on x86, consider
895 // promoting it.
896 unsigned Opc = Op.getOpcode();
897 if (TLI.isTypeDesirableForOp(Opc, VT))
898 return SDValue();
899
900 EVT PVT = VT;
901 // Consult target whether it is a good idea to promote this operation and
902 // what's the right type to promote it to.
903 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
904 assert(PVT != VT && "Don't know what type to promote to!");
905
Evan Cheng95c57ea2010-04-24 04:43:44 +0000906 bool Replace = false;
Evan Chenge5b51ac2010-04-17 06:13:15 +0000907 SDValue N0 = Op.getOperand(0);
908 if (Opc == ISD::SRA)
Evan Cheng95c57ea2010-04-24 04:43:44 +0000909 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chenge5b51ac2010-04-17 06:13:15 +0000910 else if (Opc == ISD::SRL)
Evan Cheng95c57ea2010-04-24 04:43:44 +0000911 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chenge5b51ac2010-04-17 06:13:15 +0000912 else
Evan Cheng95c57ea2010-04-24 04:43:44 +0000913 N0 = PromoteOperand(N0, PVT, Replace);
Evan Chenge5b51ac2010-04-17 06:13:15 +0000914 if (N0.getNode() == 0)
915 return SDValue();
Evan Cheng95c57ea2010-04-24 04:43:44 +0000916
Evan Chenge5b51ac2010-04-17 06:13:15 +0000917 AddToWorkList(N0.getNode());
Evan Cheng95c57ea2010-04-24 04:43:44 +0000918 if (Replace)
919 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Cheng64b7bf72010-04-16 06:14:10 +0000920
Evan Chengac7eae52010-04-27 19:48:13 +0000921 DEBUG(dbgs() << "\nPromoting ";
922 Op.getNode()->dump(&DAG));
Andrew Trickac6d9be2013-05-25 02:42:55 +0000923 SDLoc dl(Op);
Evan Cheng64b7bf72010-04-16 06:14:10 +0000924 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng07c4e102010-04-22 20:19:46 +0000925 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Cheng64b7bf72010-04-16 06:14:10 +0000926 }
927 return SDValue();
928}
929
Evan Cheng4c26e932010-04-19 19:29:22 +0000930SDValue DAGCombiner::PromoteExtend(SDValue Op) {
931 if (!LegalOperations)
932 return SDValue();
933
934 EVT VT = Op.getValueType();
935 if (VT.isVector() || !VT.isInteger())
936 return SDValue();
937
938 // If operation type is 'undesirable', e.g. i16 on x86, consider
939 // promoting it.
940 unsigned Opc = Op.getOpcode();
941 if (TLI.isTypeDesirableForOp(Opc, VT))
942 return SDValue();
943
944 EVT PVT = VT;
945 // Consult target whether it is a good idea to promote this operation and
946 // what's the right type to promote it to.
947 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
948 assert(PVT != VT && "Don't know what type to promote to!");
949 // fold (aext (aext x)) -> (aext x)
950 // fold (aext (zext x)) -> (zext x)
951 // fold (aext (sext x)) -> (sext x)
Evan Chengac7eae52010-04-27 19:48:13 +0000952 DEBUG(dbgs() << "\nPromoting ";
953 Op.getNode()->dump(&DAG));
Andrew Trickac6d9be2013-05-25 02:42:55 +0000954 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Cheng4c26e932010-04-19 19:29:22 +0000955 }
956 return SDValue();
957}
958
959bool DAGCombiner::PromoteLoad(SDValue Op) {
960 if (!LegalOperations)
961 return false;
962
963 EVT VT = Op.getValueType();
964 if (VT.isVector() || !VT.isInteger())
965 return false;
966
967 // If operation type is 'undesirable', e.g. i16 on x86, consider
968 // promoting it.
969 unsigned Opc = Op.getOpcode();
970 if (TLI.isTypeDesirableForOp(Opc, VT))
971 return false;
972
973 EVT PVT = VT;
974 // Consult target whether it is a good idea to promote this operation and
975 // what's the right type to promote it to.
976 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
977 assert(PVT != VT && "Don't know what type to promote to!");
978
Andrew Trickac6d9be2013-05-25 02:42:55 +0000979 SDLoc dl(Op);
Evan Cheng4c26e932010-04-19 19:29:22 +0000980 SDNode *N = Op.getNode();
981 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chengac7eae52010-04-27 19:48:13 +0000982 EVT MemVT = LD->getMemoryVT();
983 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Anderson95771af2011-02-25 21:41:48 +0000984 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopher503a64d2010-12-09 04:48:06 +0000985 : ISD::EXTLOAD)
Evan Chengac7eae52010-04-27 19:48:13 +0000986 : LD->getExtensionType();
Stuart Hastingsa9011292011-02-16 16:23:55 +0000987 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Cheng4c26e932010-04-19 19:29:22 +0000988 LD->getChain(), LD->getBasePtr(),
Richard Sandiford66589dc2013-10-28 11:17:59 +0000989 MemVT, LD->getMemOperand());
Evan Cheng4c26e932010-04-19 19:29:22 +0000990 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
991
Evan Cheng95c57ea2010-04-24 04:43:44 +0000992 DEBUG(dbgs() << "\nPromoting ";
Evan Cheng4c26e932010-04-19 19:29:22 +0000993 N->dump(&DAG);
Evan Cheng95c57ea2010-04-24 04:43:44 +0000994 dbgs() << "\nTo: ";
Evan Cheng4c26e932010-04-19 19:29:22 +0000995 Result.getNode()->dump(&DAG);
996 dbgs() << '\n');
997 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +0000998 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
999 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Evan Cheng4c26e932010-04-19 19:29:22 +00001000 removeFromWorkList(N);
1001 DAG.DeleteNode(N);
Evan Chengac7eae52010-04-27 19:48:13 +00001002 AddToWorkList(Result.getNode());
Evan Cheng4c26e932010-04-19 19:29:22 +00001003 return true;
1004 }
1005 return false;
1006}
1007
Evan Chenge5b51ac2010-04-17 06:13:15 +00001008
Chris Lattner29446522007-05-14 22:04:50 +00001009//===----------------------------------------------------------------------===//
1010// Main DAG Combiner implementation
1011//===----------------------------------------------------------------------===//
1012
Duncan Sands25cf2272008-11-24 14:53:14 +00001013void DAGCombiner::Run(CombineLevel AtLevel) {
1014 // set the instance variables, so that the various visit routines may use it.
1015 Level = AtLevel;
Eli Friedman50185242011-11-12 00:35:34 +00001016 LegalOperations = Level >= AfterLegalizeVectorOps;
1017 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman4ebd8052005-09-01 23:24:04 +00001018
Evan Cheng17a568b2008-08-29 22:21:44 +00001019 // Add all the dag nodes to the worklist.
Evan Cheng17a568b2008-08-29 22:21:44 +00001020 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1021 E = DAG.allnodes_end(); I != E; ++I)
James Molloy6660c052012-02-16 09:17:04 +00001022 AddToWorkList(I);
Duncan Sands25cf2272008-11-24 14:53:14 +00001023
Evan Cheng17a568b2008-08-29 22:21:44 +00001024 // Create a dummy node (which is not added to allnodes), that adds a reference
1025 // to the root node, preventing it from being deleted, and tracking any
1026 // changes of the root.
1027 HandleSDNode Dummy(DAG.getRoot());
Scott Michelfdc40a02009-02-17 22:15:04 +00001028
Jim Laskey26f7fa72006-10-17 19:33:52 +00001029 // The root of the dag may dangle to deleted nodes until the dag combiner is
1030 // done. Set it to null to avoid confusion.
Dan Gohman475871a2008-07-27 21:46:04 +00001031 DAG.setRoot(SDValue());
Scott Michelfdc40a02009-02-17 22:15:04 +00001032
James Molloy6660c052012-02-16 09:17:04 +00001033 // while the worklist isn't empty, find a node and
Evan Cheng17a568b2008-08-29 22:21:44 +00001034 // try and combine it.
James Molloy6660c052012-02-16 09:17:04 +00001035 while (!WorkListContents.empty()) {
1036 SDNode *N;
Jack Carteradbd3ae2013-10-17 01:34:33 +00001037 // The WorkListOrder holds the SDNodes in order, but it may contain
1038 // duplicates.
James Molloy6660c052012-02-16 09:17:04 +00001039 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1040 // worklist *should* contain, and check the node we want to visit is should
1041 // actually be visited.
1042 do {
Benjamin Kramerd5f76902012-03-10 00:23:58 +00001043 N = WorkListOrder.pop_back_val();
James Molloy6660c052012-02-16 09:17:04 +00001044 } while (!WorkListContents.erase(N));
Scott Michelfdc40a02009-02-17 22:15:04 +00001045
Evan Cheng17a568b2008-08-29 22:21:44 +00001046 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1047 // N is deleted from the DAG, since they too may now be dead or may have a
1048 // reduced number of uses, allowing other xforms.
1049 if (N->use_empty() && N != &Dummy) {
1050 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1051 AddToWorkList(N->getOperand(i).getNode());
Scott Michelfdc40a02009-02-17 22:15:04 +00001052
Evan Cheng17a568b2008-08-29 22:21:44 +00001053 DAG.DeleteNode(N);
1054 continue;
Nate Begeman1d4d4142005-09-01 00:19:25 +00001055 }
Scott Michelfdc40a02009-02-17 22:15:04 +00001056
Evan Cheng17a568b2008-08-29 22:21:44 +00001057 SDValue RV = combine(N);
Scott Michelfdc40a02009-02-17 22:15:04 +00001058
Evan Cheng17a568b2008-08-29 22:21:44 +00001059 if (RV.getNode() == 0)
1060 continue;
Scott Michelfdc40a02009-02-17 22:15:04 +00001061
Evan Cheng17a568b2008-08-29 22:21:44 +00001062 ++NodesCombined;
Scott Michelfdc40a02009-02-17 22:15:04 +00001063
Evan Cheng17a568b2008-08-29 22:21:44 +00001064 // If we get back the same node we passed in, rather than a new node or
1065 // zero, we know that the node must have defined multiple values and
Scott Michelfdc40a02009-02-17 22:15:04 +00001066 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng17a568b2008-08-29 22:21:44 +00001067 // mechanics for us, we have no work to do in this case.
1068 if (RV.getNode() == N)
1069 continue;
Scott Michelfdc40a02009-02-17 22:15:04 +00001070
Evan Cheng17a568b2008-08-29 22:21:44 +00001071 assert(N->getOpcode() != ISD::DELETED_NODE &&
1072 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1073 "Node was deleted but visit returned new node!");
Chris Lattner729c6d12006-05-27 00:43:02 +00001074
Wesley Peckbf17cfa2010-11-23 03:31:01 +00001075 DEBUG(dbgs() << "\nReplacing.3 ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001076 N->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00001077 dbgs() << "\nWith: ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001078 RV.getNode()->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00001079 dbgs() << '\n');
Eric Christopher7332e6e2011-07-14 01:12:15 +00001080
Devang Patel9728ea22011-05-23 22:04:42 +00001081 // Transfer debug value.
1082 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng17a568b2008-08-29 22:21:44 +00001083 WorkListRemover DeadNodes(*this);
1084 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00001085 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng17a568b2008-08-29 22:21:44 +00001086 else {
1087 assert(N->getValueType(0) == RV.getValueType() &&
1088 N->getNumValues() == 1 && "Type mismatch");
1089 SDValue OpV = RV;
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00001090 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng17a568b2008-08-29 22:21:44 +00001091 }
Scott Michelfdc40a02009-02-17 22:15:04 +00001092
Evan Cheng17a568b2008-08-29 22:21:44 +00001093 // Push the new node and any users onto the worklist
1094 AddToWorkList(RV.getNode());
1095 AddUsersToWorkList(RV.getNode());
Scott Michelfdc40a02009-02-17 22:15:04 +00001096
Evan Cheng17a568b2008-08-29 22:21:44 +00001097 // Add any uses of the old node to the worklist in case this node is the
1098 // last one that uses them. They may become dead after this node is
1099 // deleted.
1100 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1101 AddToWorkList(N->getOperand(i).getNode());
Scott Michelfdc40a02009-02-17 22:15:04 +00001102
Dan Gohmandbe664a2009-01-19 21:44:21 +00001103 // Finally, if the node is now dead, remove it from the graph. The node
1104 // may not be dead if the replacement process recursively simplified to
1105 // something else needing this node.
1106 if (N->use_empty()) {
1107 // Nodes can be reintroduced into the worklist. Make sure we do not
1108 // process a node that has been replaced.
1109 removeFromWorkList(N);
Scott Michelfdc40a02009-02-17 22:15:04 +00001110
Dan Gohmandbe664a2009-01-19 21:44:21 +00001111 // Finally, since the node is now dead, remove it from the graph.
1112 DAG.DeleteNode(N);
1113 }
Evan Cheng17a568b2008-08-29 22:21:44 +00001114 }
Scott Michelfdc40a02009-02-17 22:15:04 +00001115
Chris Lattner95038592005-10-05 06:35:28 +00001116 // If the root changed (e.g. it was a dead load, update the root).
1117 DAG.setRoot(Dummy.getValue());
Hal Finkel31490ba2012-04-16 03:33:22 +00001118 DAG.RemoveDeadNodes();
Nate Begeman1d4d4142005-09-01 00:19:25 +00001119}
1120
Dan Gohman475871a2008-07-27 21:46:04 +00001121SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengb3a3d5e2010-04-28 07:10:39 +00001122 switch (N->getOpcode()) {
Nate Begeman1d4d4142005-09-01 00:19:25 +00001123 default: break;
Nate Begeman4942a962005-09-01 00:33:32 +00001124 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattnerfec42eb2008-02-13 07:25:05 +00001125 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001126 case ISD::ADD: return visitADD(N);
1127 case ISD::SUB: return visitSUB(N);
Chris Lattner91153682007-03-04 20:03:15 +00001128 case ISD::ADDC: return visitADDC(N);
Craig Toppercc274522012-01-07 09:06:39 +00001129 case ISD::SUBC: return visitSUBC(N);
Chris Lattner91153682007-03-04 20:03:15 +00001130 case ISD::ADDE: return visitADDE(N);
Craig Toppercc274522012-01-07 09:06:39 +00001131 case ISD::SUBE: return visitSUBE(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001132 case ISD::MUL: return visitMUL(N);
1133 case ISD::SDIV: return visitSDIV(N);
1134 case ISD::UDIV: return visitUDIV(N);
1135 case ISD::SREM: return visitSREM(N);
1136 case ISD::UREM: return visitUREM(N);
1137 case ISD::MULHU: return visitMULHU(N);
1138 case ISD::MULHS: return visitMULHS(N);
Dan Gohman389079b2007-10-08 17:57:15 +00001139 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1140 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramerf55d26e2011-05-21 18:31:55 +00001141 case ISD::SMULO: return visitSMULO(N);
1142 case ISD::UMULO: return visitUMULO(N);
Dan Gohman389079b2007-10-08 17:57:15 +00001143 case ISD::SDIVREM: return visitSDIVREM(N);
1144 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001145 case ISD::AND: return visitAND(N);
1146 case ISD::OR: return visitOR(N);
1147 case ISD::XOR: return visitXOR(N);
1148 case ISD::SHL: return visitSHL(N);
1149 case ISD::SRA: return visitSRA(N);
1150 case ISD::SRL: return visitSRL(N);
1151 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth63974b22011-12-13 01:56:10 +00001152 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001153 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth63974b22011-12-13 01:56:10 +00001154 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001155 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman452d7be2005-09-16 00:54:12 +00001156 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramer6242fda2013-04-26 09:19:19 +00001157 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman452d7be2005-09-16 00:54:12 +00001158 case ISD::SELECT_CC: return visitSELECT_CC(N);
1159 case ISD::SETCC: return visitSETCC(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001160 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1161 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner5ffc0662006-05-05 05:58:59 +00001162 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001163 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1164 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peckbf17cfa2010-11-23 03:31:01 +00001165 case ISD::BITCAST: return visitBITCAST(N);
Evan Cheng9bfa03c2008-05-12 23:04:07 +00001166 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner01b3d732005-09-28 22:28:18 +00001167 case ISD::FADD: return visitFADD(N);
1168 case ISD::FSUB: return visitFSUB(N);
1169 case ISD::FMUL: return visitFMUL(N);
Owen Anderson062c0a52012-05-02 22:17:40 +00001170 case ISD::FMA: return visitFMA(N);
Chris Lattner01b3d732005-09-28 22:28:18 +00001171 case ISD::FDIV: return visitFDIV(N);
1172 case ISD::FREM: return visitFREM(N);
Chris Lattner12d83032006-03-05 05:30:57 +00001173 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001174 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1175 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1176 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1177 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1178 case ISD::FP_ROUND: return visitFP_ROUND(N);
1179 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1180 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1181 case ISD::FNEG: return visitFNEG(N);
1182 case ISD::FABS: return visitFABS(N);
Owen Anderson7c626d32012-08-13 23:32:49 +00001183 case ISD::FFLOOR: return visitFFLOOR(N);
1184 case ISD::FCEIL: return visitFCEIL(N);
1185 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begeman44728a72005-09-19 22:34:01 +00001186 case ISD::BRCOND: return visitBRCOND(N);
Nate Begeman44728a72005-09-19 22:34:01 +00001187 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattner01a22022005-10-10 22:04:48 +00001188 case ISD::LOAD: return visitLOAD(N);
Chris Lattner87514ca2005-10-10 22:31:19 +00001189 case ISD::STORE: return visitSTORE(N);
Chris Lattnerca242442006-03-19 01:27:56 +00001190 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng513da432007-10-06 08:19:55 +00001191 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohman7f321562007-06-25 16:23:39 +00001192 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1193 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopese97190f2011-09-20 23:19:33 +00001194 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattner66445d32006-03-28 22:11:53 +00001195 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Nate Begeman1d4d4142005-09-01 00:19:25 +00001196 }
Dan Gohman475871a2008-07-27 21:46:04 +00001197 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00001198}
1199
Dan Gohman475871a2008-07-27 21:46:04 +00001200SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman475871a2008-07-27 21:46:04 +00001201 SDValue RV = visit(N);
Dan Gohman389079b2007-10-08 17:57:15 +00001202
1203 // If nothing happened, try a target-specific DAG combine.
Gabor Greifba36cb52008-08-28 21:40:38 +00001204 if (RV.getNode() == 0) {
Dan Gohman389079b2007-10-08 17:57:15 +00001205 assert(N->getOpcode() != ISD::DELETED_NODE &&
1206 "Node was deleted but visit returned NULL!");
1207
1208 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1209 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1210
1211 // Expose the DAG combiner to the target combiner impls.
Scott Michelfdc40a02009-02-17 22:15:04 +00001212 TargetLowering::DAGCombinerInfo
Nadav Rotem444b4bf2012-12-27 06:47:41 +00001213 DagCombineInfo(DAG, Level, false, this);
Dan Gohman389079b2007-10-08 17:57:15 +00001214
1215 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1216 }
1217 }
1218
Evan Chengb3a3d5e2010-04-28 07:10:39 +00001219 // If nothing happened still, try promoting the operation.
1220 if (RV.getNode() == 0) {
1221 switch (N->getOpcode()) {
1222 default: break;
1223 case ISD::ADD:
1224 case ISD::SUB:
1225 case ISD::MUL:
1226 case ISD::AND:
1227 case ISD::OR:
1228 case ISD::XOR:
1229 RV = PromoteIntBinOp(SDValue(N, 0));
1230 break;
1231 case ISD::SHL:
1232 case ISD::SRA:
1233 case ISD::SRL:
1234 RV = PromoteIntShiftOp(SDValue(N, 0));
1235 break;
1236 case ISD::SIGN_EXTEND:
1237 case ISD::ZERO_EXTEND:
1238 case ISD::ANY_EXTEND:
1239 RV = PromoteExtend(SDValue(N, 0));
1240 break;
1241 case ISD::LOAD:
1242 if (PromoteLoad(SDValue(N, 0)))
1243 RV = SDValue(N, 0);
1244 break;
1245 }
1246 }
1247
Scott Michelfdc40a02009-02-17 22:15:04 +00001248 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng08b11732008-03-22 01:55:50 +00001249 // sdisel CSE.
Scott Michelfdc40a02009-02-17 22:15:04 +00001250 if (RV.getNode() == 0 &&
Evan Cheng08b11732008-03-22 01:55:50 +00001251 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1252 N->getNumValues() == 1) {
Dan Gohman475871a2008-07-27 21:46:04 +00001253 SDValue N0 = N->getOperand(0);
1254 SDValue N1 = N->getOperand(1);
Bill Wendling5c71acf2009-01-30 01:13:16 +00001255
Evan Cheng08b11732008-03-22 01:55:50 +00001256 // Constant operands are canonicalized to RHS.
1257 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Dan Gohman475871a2008-07-27 21:46:04 +00001258 SDValue Ops[] = { N1, N0 };
Evan Cheng08b11732008-03-22 01:55:50 +00001259 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1260 Ops, 2);
Evan Chengea100462008-03-24 23:55:16 +00001261 if (CSENode)
Dan Gohman475871a2008-07-27 21:46:04 +00001262 return SDValue(CSENode, 0);
Evan Cheng08b11732008-03-22 01:55:50 +00001263 }
1264 }
1265
Dan Gohman389079b2007-10-08 17:57:15 +00001266 return RV;
Scott Michelfdc40a02009-02-17 22:15:04 +00001267}
Dan Gohman389079b2007-10-08 17:57:15 +00001268
Chris Lattner6270f682006-10-08 22:57:01 +00001269/// getInputChainForNode - Given a node, return its input chain if it has one,
1270/// otherwise return a null sd operand.
Dan Gohman475871a2008-07-27 21:46:04 +00001271static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner6270f682006-10-08 22:57:01 +00001272 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001273 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner6270f682006-10-08 22:57:01 +00001274 return N->getOperand(0);
Stephen Linb4940152013-07-09 00:44:49 +00001275 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner6270f682006-10-08 22:57:01 +00001276 return N->getOperand(NumOps-1);
1277 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson825b72b2009-08-11 20:47:22 +00001278 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner6270f682006-10-08 22:57:01 +00001279 return N->getOperand(i);
1280 }
Bill Wendling5c71acf2009-01-30 01:13:16 +00001281 return SDValue();
Chris Lattner6270f682006-10-08 22:57:01 +00001282}
1283
Dan Gohman475871a2008-07-27 21:46:04 +00001284SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner6270f682006-10-08 22:57:01 +00001285 // If N has two operands, where one has an input chain equal to the other,
1286 // the 'other' chain is redundant.
1287 if (N->getNumOperands() == 2) {
Gabor Greifba36cb52008-08-28 21:40:38 +00001288 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner6270f682006-10-08 22:57:01 +00001289 return N->getOperand(0);
Gabor Greifba36cb52008-08-28 21:40:38 +00001290 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner6270f682006-10-08 22:57:01 +00001291 return N->getOperand(1);
1292 }
Scott Michelfdc40a02009-02-17 22:15:04 +00001293
Chris Lattnerc76d4412007-05-16 06:37:59 +00001294 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman475871a2008-07-27 21:46:04 +00001295 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelfdc40a02009-02-17 22:15:04 +00001296 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattnerc76d4412007-05-16 06:37:59 +00001297 bool Changed = false; // If we should replace this token factor.
Scott Michelfdc40a02009-02-17 22:15:04 +00001298
Jim Laskey6ff23e52006-10-04 16:53:27 +00001299 // Start out with this token factor.
Jim Laskey279f0532006-09-25 16:29:54 +00001300 TFs.push_back(N);
Scott Michelfdc40a02009-02-17 22:15:04 +00001301
Jim Laskey71382342006-10-07 23:37:56 +00001302 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskeybc588b82006-10-05 15:07:25 +00001303 // encountered.
1304 for (unsigned i = 0; i < TFs.size(); ++i) {
1305 SDNode *TF = TFs[i];
Scott Michelfdc40a02009-02-17 22:15:04 +00001306
Jim Laskey6ff23e52006-10-04 16:53:27 +00001307 // Check each of the operands.
1308 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00001309 SDValue Op = TF->getOperand(i);
Scott Michelfdc40a02009-02-17 22:15:04 +00001310
Jim Laskey6ff23e52006-10-04 16:53:27 +00001311 switch (Op.getOpcode()) {
1312 case ISD::EntryToken:
Jim Laskeybc588b82006-10-05 15:07:25 +00001313 // Entry tokens don't need to be added to the list. They are
1314 // rededundant.
1315 Changed = true;
Jim Laskey6ff23e52006-10-04 16:53:27 +00001316 break;
Scott Michelfdc40a02009-02-17 22:15:04 +00001317
Jim Laskey6ff23e52006-10-04 16:53:27 +00001318 case ISD::TokenFactor:
Nate Begemanb6aef5c2009-09-15 00:18:30 +00001319 if (Op.hasOneUse() &&
Gabor Greifba36cb52008-08-28 21:40:38 +00001320 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey6ff23e52006-10-04 16:53:27 +00001321 // Queue up for processing.
Gabor Greifba36cb52008-08-28 21:40:38 +00001322 TFs.push_back(Op.getNode());
Jim Laskey6ff23e52006-10-04 16:53:27 +00001323 // Clean up in case the token factor is removed.
Gabor Greifba36cb52008-08-28 21:40:38 +00001324 AddToWorkList(Op.getNode());
Jim Laskey6ff23e52006-10-04 16:53:27 +00001325 Changed = true;
1326 break;
Jim Laskey279f0532006-09-25 16:29:54 +00001327 }
Jim Laskey6ff23e52006-10-04 16:53:27 +00001328 // Fall thru
Scott Michelfdc40a02009-02-17 22:15:04 +00001329
Jim Laskey6ff23e52006-10-04 16:53:27 +00001330 default:
Chris Lattnerc76d4412007-05-16 06:37:59 +00001331 // Only add if it isn't already in the list.
Gabor Greifba36cb52008-08-28 21:40:38 +00001332 if (SeenOps.insert(Op.getNode()))
Jim Laskeybc588b82006-10-05 15:07:25 +00001333 Ops.push_back(Op);
Chris Lattnerc76d4412007-05-16 06:37:59 +00001334 else
1335 Changed = true;
Jim Laskey6ff23e52006-10-04 16:53:27 +00001336 break;
Jim Laskey279f0532006-09-25 16:29:54 +00001337 }
1338 }
Jim Laskey6ff23e52006-10-04 16:53:27 +00001339 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00001340
Dan Gohman475871a2008-07-27 21:46:04 +00001341 SDValue Result;
Jim Laskey6ff23e52006-10-04 16:53:27 +00001342
1343 // If we've change things around then replace token factor.
1344 if (Changed) {
Dan Gohman30359592008-01-29 13:02:09 +00001345 if (Ops.empty()) {
Jim Laskey6ff23e52006-10-04 16:53:27 +00001346 // The entry token is the only possible outcome.
1347 Result = DAG.getEntryNode();
1348 } else {
1349 // New and improved token factor.
Andrew Trickac6d9be2013-05-25 02:42:55 +00001350 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson825b72b2009-08-11 20:47:22 +00001351 MVT::Other, &Ops[0], Ops.size());
Nate Begemanded49632005-10-13 03:11:28 +00001352 }
Bill Wendling5c71acf2009-01-30 01:13:16 +00001353
Jim Laskey274062c2006-10-13 23:32:28 +00001354 // Don't add users to work list.
1355 return CombineTo(N, Result, false);
Nate Begemanded49632005-10-13 03:11:28 +00001356 }
Scott Michelfdc40a02009-02-17 22:15:04 +00001357
Jim Laskey6ff23e52006-10-04 16:53:27 +00001358 return Result;
Nate Begeman1d4d4142005-09-01 00:19:25 +00001359}
1360
Chris Lattnerfec42eb2008-02-13 07:25:05 +00001361/// MERGE_VALUES can always be eliminated.
Dan Gohman475871a2008-07-27 21:46:04 +00001362SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chris Lattnerfec42eb2008-02-13 07:25:05 +00001363 WorkListRemover DeadNodes(*this);
Dan Gohman00edf392009-08-10 23:43:19 +00001364 // Replacing results may cause a different MERGE_VALUES to suddenly
1365 // be CSE'd with N, and carry its uses with it. Iterate until no
1366 // uses remain, to ensure that the node can be safely deleted.
Pete Cooper3affd9e2012-06-20 19:35:43 +00001367 // First add the users of this node to the work list so that they
1368 // can be tried again once they have new operands.
1369 AddUsersToWorkList(N);
Dan Gohman00edf392009-08-10 23:43:19 +00001370 do {
1371 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00001372 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman00edf392009-08-10 23:43:19 +00001373 } while (!N->use_empty());
Chris Lattnerfec42eb2008-02-13 07:25:05 +00001374 removeFromWorkList(N);
1375 DAG.DeleteNode(N);
Dan Gohman475871a2008-07-27 21:46:04 +00001376 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattnerfec42eb2008-02-13 07:25:05 +00001377}
1378
Evan Cheng42d7ccf2007-01-19 17:51:44 +00001379static
Andrew Trickac6d9be2013-05-25 02:42:55 +00001380SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
Bill Wendlingd69c3142009-01-30 02:23:43 +00001381 SelectionDAG &DAG) {
Owen Andersone50ed302009-08-10 22:56:29 +00001382 EVT VT = N0.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00001383 SDValue N00 = N0.getOperand(0);
1384 SDValue N01 = N0.getOperand(1);
Evan Cheng42d7ccf2007-01-19 17:51:44 +00001385 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
Bill Wendlingd69c3142009-01-30 02:23:43 +00001386
Gabor Greifba36cb52008-08-28 21:40:38 +00001387 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
Evan Cheng42d7ccf2007-01-19 17:51:44 +00001388 isa<ConstantSDNode>(N00.getOperand(1))) {
Bill Wendlingd69c3142009-01-30 02:23:43 +00001389 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Andrew Trickac6d9be2013-05-25 02:42:55 +00001390 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1391 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
Bill Wendlingd69c3142009-01-30 02:23:43 +00001392 N00.getOperand(0), N01),
Andrew Trickac6d9be2013-05-25 02:42:55 +00001393 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
Bill Wendlingd69c3142009-01-30 02:23:43 +00001394 N00.getOperand(1), N01));
1395 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
Evan Cheng42d7ccf2007-01-19 17:51:44 +00001396 }
Bill Wendlingd69c3142009-01-30 02:23:43 +00001397
Dan Gohman475871a2008-07-27 21:46:04 +00001398 return SDValue();
Evan Cheng42d7ccf2007-01-19 17:51:44 +00001399}
1400
Dan Gohman475871a2008-07-27 21:46:04 +00001401SDValue DAGCombiner::visitADD(SDNode *N) {
1402 SDValue N0 = N->getOperand(0);
1403 SDValue N1 = N->getOperand(1);
Nate Begeman646d7e22005-09-02 21:18:40 +00001404 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1405 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00001406 EVT VT = N0.getValueType();
Dan Gohman7f321562007-06-25 16:23:39 +00001407
1408 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00001409 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00001410 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00001411 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper48b509c2012-12-10 08:12:29 +00001412
1413 // fold (add x, 0) -> x, vector edition
1414 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1415 return N0;
1416 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1417 return N1;
Dan Gohman05d92fe2007-07-13 20:03:40 +00001418 }
Bill Wendling2476e5d2008-12-10 22:36:00 +00001419
Dan Gohman613e0d82007-07-03 14:03:57 +00001420 // fold (add x, undef) -> undef
Dan Gohman70fb1ae2007-07-10 15:19:29 +00001421 if (N0.getOpcode() == ISD::UNDEF)
1422 return N0;
1423 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman613e0d82007-07-03 14:03:57 +00001424 return N1;
Nate Begeman1d4d4142005-09-01 00:19:25 +00001425 // fold (add c1, c2) -> c1+c2
Nate Begeman646d7e22005-09-02 21:18:40 +00001426 if (N0C && N1C)
Bill Wendlingf3cbca22008-09-24 10:25:02 +00001427 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman99801192005-09-07 23:25:52 +00001428 // canonicalize constant to RHS
Nate Begemana0e221d2005-10-18 00:28:13 +00001429 if (N0C && !N1C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001430 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00001431 // fold (add x, 0) -> x
Nate Begeman646d7e22005-09-02 21:18:40 +00001432 if (N1C && N1C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00001433 return N0;
Dan Gohman6520e202008-10-18 02:06:02 +00001434 // fold (add Sym, c) -> Sym+c
1435 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sands25cf2272008-11-24 14:53:14 +00001436 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman6520e202008-10-18 02:06:02 +00001437 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001438 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman6520e202008-10-18 02:06:02 +00001439 GA->getOffset() +
1440 (uint64_t)N1C->getSExtValue());
Chris Lattner4aafb4f2006-01-12 20:22:43 +00001441 // fold ((c1-A)+c2) -> (c1+c2)-A
1442 if (N1C && N0.getOpcode() == ISD::SUB)
1443 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001444 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohman002e5d02008-03-13 22:13:53 +00001445 DAG.getConstant(N1C->getAPIntValue()+
1446 N0C->getAPIntValue(), VT),
Chris Lattner4aafb4f2006-01-12 20:22:43 +00001447 N0.getOperand(1));
Nate Begemancd4d58c2006-02-03 06:46:56 +00001448 // reassociate add
Andrew Trickac6d9be2013-05-25 02:42:55 +00001449 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Gabor Greifba36cb52008-08-28 21:40:38 +00001450 if (RADD.getNode() != 0)
Nate Begemancd4d58c2006-02-03 06:46:56 +00001451 return RADD;
Nate Begeman1d4d4142005-09-01 00:19:25 +00001452 // fold ((0-A) + B) -> B-A
1453 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1454 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickac6d9be2013-05-25 02:42:55 +00001455 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman1d4d4142005-09-01 00:19:25 +00001456 // fold (A + (0-B)) -> A-B
1457 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1458 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickac6d9be2013-05-25 02:42:55 +00001459 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner01b3d732005-09-28 22:28:18 +00001460 // fold (A+(B-A)) -> B
1461 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begeman83e75ec2005-09-06 04:43:02 +00001462 return N1.getOperand(0);
Dale Johannesen56eca912008-11-27 00:43:21 +00001463 // fold ((B-A)+A) -> B
1464 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1465 return N0.getOperand(0);
Dale Johannesen221cd2f2008-12-02 01:30:54 +00001466 // fold (A+(B-(A+C))) to (B-C)
1467 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingf4eb2262009-01-30 02:31:17 +00001468 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001469 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen221cd2f2008-12-02 01:30:54 +00001470 N1.getOperand(1).getOperand(1));
Dale Johannesen221cd2f2008-12-02 01:30:54 +00001471 // fold (A+(B-(C+A))) to (B-C)
1472 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingf4eb2262009-01-30 02:31:17 +00001473 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001474 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen221cd2f2008-12-02 01:30:54 +00001475 N1.getOperand(1).getOperand(0));
Dale Johannesen7c7bc722008-12-23 23:47:22 +00001476 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen34d79852008-12-02 18:40:40 +00001477 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1478 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingf4eb2262009-01-30 02:31:17 +00001479 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001480 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingf4eb2262009-01-30 02:31:17 +00001481 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen34d79852008-12-02 18:40:40 +00001482
Dale Johannesen221cd2f2008-12-02 01:30:54 +00001483 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1484 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1485 SDValue N00 = N0.getOperand(0);
1486 SDValue N01 = N0.getOperand(1);
1487 SDValue N10 = N1.getOperand(0);
1488 SDValue N11 = N1.getOperand(1);
Bill Wendlingf4eb2262009-01-30 02:31:17 +00001489
1490 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001491 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1492 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1493 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen221cd2f2008-12-02 01:30:54 +00001494 }
Chris Lattner947c2892006-03-13 06:51:27 +00001495
Dan Gohman475871a2008-07-27 21:46:04 +00001496 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1497 return SDValue(N, 0);
Scott Michelfdc40a02009-02-17 22:15:04 +00001498
Sylvestre Ledru94c22712012-09-27 10:14:43 +00001499 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001500 if (VT.isInteger() && !VT.isVector()) {
Dan Gohman948d8ea2008-02-20 16:33:30 +00001501 APInt LHSZero, LHSOne;
1502 APInt RHSZero, RHSOne;
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00001503 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
Bill Wendlingf4eb2262009-01-30 02:31:17 +00001504
Dan Gohman948d8ea2008-02-20 16:33:30 +00001505 if (LHSZero.getBoolValue()) {
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00001506 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
Scott Michelfdc40a02009-02-17 22:15:04 +00001507
Chris Lattner947c2892006-03-13 06:51:27 +00001508 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1509 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00001510 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001511 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
Chris Lattner947c2892006-03-13 06:51:27 +00001512 }
1513 }
Evan Cheng3ef554d2006-11-06 08:14:30 +00001514
Evan Cheng42d7ccf2007-01-19 17:51:44 +00001515 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Gabor Greifba36cb52008-08-28 21:40:38 +00001516 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00001517 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
Gabor Greifba36cb52008-08-28 21:40:38 +00001518 if (Result.getNode()) return Result;
Evan Cheng42d7ccf2007-01-19 17:51:44 +00001519 }
Gabor Greifba36cb52008-08-28 21:40:38 +00001520 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00001521 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
Gabor Greifba36cb52008-08-28 21:40:38 +00001522 if (Result.getNode()) return Result;
Evan Cheng42d7ccf2007-01-19 17:51:44 +00001523 }
1524
Dan Gohmancd9e1552010-01-19 23:30:49 +00001525 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1526 if (N1.getOpcode() == ISD::SHL &&
1527 N1.getOperand(0).getOpcode() == ISD::SUB)
1528 if (ConstantSDNode *C =
1529 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1530 if (C->getAPIntValue() == 0)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001531 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1532 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohmancd9e1552010-01-19 23:30:49 +00001533 N1.getOperand(0).getOperand(1),
1534 N1.getOperand(1)));
1535 if (N0.getOpcode() == ISD::SHL &&
1536 N0.getOperand(0).getOpcode() == ISD::SUB)
1537 if (ConstantSDNode *C =
1538 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1539 if (C->getAPIntValue() == 0)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001540 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1541 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohmancd9e1552010-01-19 23:30:49 +00001542 N0.getOperand(0).getOperand(1),
1543 N0.getOperand(1)));
1544
Owen Andersonbc146b02010-09-21 20:42:50 +00001545 if (N1.getOpcode() == ISD::AND) {
1546 SDValue AndOp0 = N1.getOperand(0);
Wesley Peckbf17cfa2010-11-23 03:31:01 +00001547 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Andersonbc146b02010-09-21 20:42:50 +00001548 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1549 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peckbf17cfa2010-11-23 03:31:01 +00001550
Owen Andersonbc146b02010-09-21 20:42:50 +00001551 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1552 // and similar xforms where the inner op is either ~0 or 0.
1553 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00001554 SDLoc DL(N);
Owen Andersonbc146b02010-09-21 20:42:50 +00001555 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1556 }
1557 }
1558
Benjamin Kramerf50125e2010-12-22 23:17:45 +00001559 // add (sext i1), X -> sub X, (zext i1)
1560 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1561 N0.getOperand(0).getValueType() == MVT::i1 &&
1562 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00001563 SDLoc DL(N);
Benjamin Kramerf50125e2010-12-22 23:17:45 +00001564 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1565 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1566 }
1567
Evan Chengb3a3d5e2010-04-28 07:10:39 +00001568 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00001569}
1570
Dan Gohman475871a2008-07-27 21:46:04 +00001571SDValue DAGCombiner::visitADDC(SDNode *N) {
1572 SDValue N0 = N->getOperand(0);
1573 SDValue N1 = N->getOperand(1);
Chris Lattner91153682007-03-04 20:03:15 +00001574 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1575 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00001576 EVT VT = N0.getValueType();
Scott Michelfdc40a02009-02-17 22:15:04 +00001577
Chris Lattner91153682007-03-04 20:03:15 +00001578 // If the flag result is dead, turn this into an ADD.
Craig Topper704e1a02012-01-07 18:31:09 +00001579 if (!N->hasAnyUseOfValue(1))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001580 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen874ae252009-06-02 03:12:52 +00001581 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickac6d9be2013-05-25 02:42:55 +00001582 SDLoc(N), MVT::Glue));
Scott Michelfdc40a02009-02-17 22:15:04 +00001583
Chris Lattner91153682007-03-04 20:03:15 +00001584 // canonicalize constant to RHS.
Dan Gohman0a4627d2008-06-23 15:29:14 +00001585 if (N0C && !N1C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001586 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +00001587
Chris Lattnerb6541762007-03-04 20:40:38 +00001588 // fold (addc x, 0) -> x + no carry out
1589 if (N1C && N1C->isNullValue())
Dale Johannesen874ae252009-06-02 03:12:52 +00001590 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickac6d9be2013-05-25 02:42:55 +00001591 SDLoc(N), MVT::Glue));
Scott Michelfdc40a02009-02-17 22:15:04 +00001592
Sylvestre Ledru94c22712012-09-27 10:14:43 +00001593 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohman948d8ea2008-02-20 16:33:30 +00001594 APInt LHSZero, LHSOne;
1595 APInt RHSZero, RHSOne;
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00001596 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
Bill Wendling14036c02009-01-30 02:38:00 +00001597
Dan Gohman948d8ea2008-02-20 16:33:30 +00001598 if (LHSZero.getBoolValue()) {
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00001599 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
Scott Michelfdc40a02009-02-17 22:15:04 +00001600
Chris Lattnerb6541762007-03-04 20:40:38 +00001601 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1602 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00001603 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001604 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen874ae252009-06-02 03:12:52 +00001605 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickac6d9be2013-05-25 02:42:55 +00001606 SDLoc(N), MVT::Glue));
Chris Lattnerb6541762007-03-04 20:40:38 +00001607 }
Scott Michelfdc40a02009-02-17 22:15:04 +00001608
Dan Gohman475871a2008-07-27 21:46:04 +00001609 return SDValue();
Chris Lattner91153682007-03-04 20:03:15 +00001610}
1611
Dan Gohman475871a2008-07-27 21:46:04 +00001612SDValue DAGCombiner::visitADDE(SDNode *N) {
1613 SDValue N0 = N->getOperand(0);
1614 SDValue N1 = N->getOperand(1);
1615 SDValue CarryIn = N->getOperand(2);
Chris Lattner91153682007-03-04 20:03:15 +00001616 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1617 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelfdc40a02009-02-17 22:15:04 +00001618
Chris Lattner91153682007-03-04 20:03:15 +00001619 // canonicalize constant to RHS
Dan Gohman0a4627d2008-06-23 15:29:14 +00001620 if (N0C && !N1C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001621 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling14036c02009-01-30 02:38:00 +00001622 N1, N0, CarryIn);
Scott Michelfdc40a02009-02-17 22:15:04 +00001623
Chris Lattnerb6541762007-03-04 20:40:38 +00001624 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen874ae252009-06-02 03:12:52 +00001625 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001626 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelfdc40a02009-02-17 22:15:04 +00001627
Dan Gohman475871a2008-07-27 21:46:04 +00001628 return SDValue();
Chris Lattner91153682007-03-04 20:03:15 +00001629}
1630
Eric Christopher7bccf6a2011-02-16 04:50:12 +00001631// Since it may not be valid to emit a fold to zero for vector initializers
1632// check if we can before folding.
Andrew Trickac6d9be2013-05-25 02:42:55 +00001633static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkelbd6f1f62013-07-09 17:02:45 +00001634 SelectionDAG &DAG,
1635 bool LegalOperations, bool LegalTypes) {
Stephen Linb4940152013-07-09 00:44:49 +00001636 if (!VT.isVector())
Eric Christopher7bccf6a2011-02-16 04:50:12 +00001637 return DAG.getConstant(0, VT);
Dan Gohman71dc7c92011-05-17 22:20:36 +00001638 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
Eric Christopher7bccf6a2011-02-16 04:50:12 +00001639 // Produce a vector of zeros.
Hal Finkelbd6f1f62013-07-09 17:02:45 +00001640 EVT ElemTy = VT.getVectorElementType();
1641 if (LegalTypes && TLI.getTypeAction(*DAG.getContext(), ElemTy) ==
1642 TargetLowering::TypePromoteInteger)
1643 ElemTy = TLI.getTypeToTransformTo(*DAG.getContext(), ElemTy);
1644 assert((!LegalTypes || TLI.isTypeLegal(ElemTy)) &&
1645 "Type for zero vector elements is not legal");
1646 SDValue El = DAG.getConstant(0, ElemTy);
Eric Christopher7bccf6a2011-02-16 04:50:12 +00001647 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1648 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1649 &Ops[0], Ops.size());
1650 }
1651 return SDValue();
1652}
1653
Dan Gohman475871a2008-07-27 21:46:04 +00001654SDValue DAGCombiner::visitSUB(SDNode *N) {
1655 SDValue N0 = N->getOperand(0);
1656 SDValue N1 = N->getOperand(1);
Gabor Greifba36cb52008-08-28 21:40:38 +00001657 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1658 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Eric Christopher7332e6e2011-07-14 01:12:15 +00001659 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1660 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Andersone50ed302009-08-10 22:56:29 +00001661 EVT VT = N0.getValueType();
Scott Michelfdc40a02009-02-17 22:15:04 +00001662
Dan Gohman7f321562007-06-25 16:23:39 +00001663 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00001664 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00001665 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00001666 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper48b509c2012-12-10 08:12:29 +00001667
1668 // fold (sub x, 0) -> x, vector edition
1669 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1670 return N0;
Dan Gohman05d92fe2007-07-13 20:03:40 +00001671 }
Bill Wendling2476e5d2008-12-10 22:36:00 +00001672
Chris Lattner854077d2005-10-17 01:07:11 +00001673 // fold (sub x, x) -> 0
Eric Christopher169e1552011-02-16 01:10:03 +00001674 // FIXME: Refactor this and xor and other similar operations together.
Eric Christopher7bccf6a2011-02-16 04:50:12 +00001675 if (N0 == N1)
Hal Finkelbd6f1f62013-07-09 17:02:45 +00001676 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman1d4d4142005-09-01 00:19:25 +00001677 // fold (sub c1, c2) -> c1-c2
Nate Begeman646d7e22005-09-02 21:18:40 +00001678 if (N0C && N1C)
Bill Wendlingf3cbca22008-09-24 10:25:02 +00001679 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattner05b57432005-10-11 06:07:15 +00001680 // fold (sub x, c) -> (add x, -c)
1681 if (N1C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001682 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohman002e5d02008-03-13 22:13:53 +00001683 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng1ad0e8b2010-01-18 21:38:44 +00001684 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1685 if (N0C && N0C->isAllOnesValue())
Andrew Trickac6d9be2013-05-25 02:42:55 +00001686 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer2c94b422011-01-29 12:34:05 +00001687 // fold A-(A-B) -> B
1688 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1689 return N1.getOperand(1);
Nate Begeman1d4d4142005-09-01 00:19:25 +00001690 // fold (A+B)-A -> B
Chris Lattner01b3d732005-09-28 22:28:18 +00001691 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begeman83e75ec2005-09-06 04:43:02 +00001692 return N0.getOperand(1);
Nate Begeman1d4d4142005-09-01 00:19:25 +00001693 // fold (A+B)-B -> A
Chris Lattner01b3d732005-09-28 22:28:18 +00001694 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelfdc40a02009-02-17 22:15:04 +00001695 return N0.getOperand(0);
Eric Christopher7332e6e2011-07-14 01:12:15 +00001696 // fold C2-(A+C1) -> (C2-C1)-A
1697 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem6dfabb62012-09-20 08:53:31 +00001698 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1699 VT);
Andrew Trickac6d9be2013-05-25 02:42:55 +00001700 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendling96cb1122012-07-19 00:04:14 +00001701 N1.getOperand(0));
Eric Christopher7332e6e2011-07-14 01:12:15 +00001702 }
Dale Johannesen7c7bc722008-12-23 23:47:22 +00001703 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenfd3b7b72008-12-16 22:13:49 +00001704 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenf9cbc1f2008-12-23 23:01:27 +00001705 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1706 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenfd3b7b72008-12-16 22:13:49 +00001707 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001708 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendlingb0702e02009-01-30 02:42:10 +00001709 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenf9cbc1f2008-12-23 23:01:27 +00001710 // fold ((A+(C+B))-B) -> A+C
1711 if (N0.getOpcode() == ISD::ADD &&
1712 N0.getOperand(1).getOpcode() == ISD::ADD &&
1713 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001714 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendlingb0702e02009-01-30 02:42:10 +00001715 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesen58e39b02008-12-23 01:59:54 +00001716 // fold ((A-(B-C))-C) -> A-B
1717 if (N0.getOpcode() == ISD::SUB &&
1718 N0.getOperand(1).getOpcode() == ISD::SUB &&
1719 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001720 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendlingb0702e02009-01-30 02:42:10 +00001721 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendlingb0702e02009-01-30 02:42:10 +00001722
Dan Gohman613e0d82007-07-03 14:03:57 +00001723 // If either operand of a sub is undef, the result is undef
Dan Gohman70fb1ae2007-07-10 15:19:29 +00001724 if (N0.getOpcode() == ISD::UNDEF)
1725 return N0;
1726 if (N1.getOpcode() == ISD::UNDEF)
1727 return N1;
Dan Gohman7f321562007-06-25 16:23:39 +00001728
Dan Gohman6520e202008-10-18 02:06:02 +00001729 // If the relocation model supports it, consider symbol offsets.
1730 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sands25cf2272008-11-24 14:53:14 +00001731 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman6520e202008-10-18 02:06:02 +00001732 // fold (sub Sym, c) -> Sym-c
1733 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001734 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman6520e202008-10-18 02:06:02 +00001735 GA->getOffset() -
1736 (uint64_t)N1C->getSExtValue());
1737 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1738 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1739 if (GA->getGlobal() == GB->getGlobal())
1740 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1741 VT);
1742 }
1743
Evan Chengb3a3d5e2010-04-28 07:10:39 +00001744 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00001745}
1746
Craig Toppercc274522012-01-07 09:06:39 +00001747SDValue DAGCombiner::visitSUBC(SDNode *N) {
1748 SDValue N0 = N->getOperand(0);
1749 SDValue N1 = N->getOperand(1);
1750 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1751 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1752 EVT VT = N0.getValueType();
1753
1754 // If the flag result is dead, turn this into an SUB.
Craig Topper704e1a02012-01-07 18:31:09 +00001755 if (!N->hasAnyUseOfValue(1))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001756 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1757 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Toppercc274522012-01-07 09:06:39 +00001758 MVT::Glue));
1759
1760 // fold (subc x, x) -> 0 + no borrow
1761 if (N0 == N1)
1762 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickac6d9be2013-05-25 02:42:55 +00001763 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Toppercc274522012-01-07 09:06:39 +00001764 MVT::Glue));
1765
1766 // fold (subc x, 0) -> x + no borrow
1767 if (N1C && N1C->isNullValue())
Andrew Trickac6d9be2013-05-25 02:42:55 +00001768 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Toppercc274522012-01-07 09:06:39 +00001769 MVT::Glue));
1770
1771 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1772 if (N0C && N0C->isAllOnesValue())
Andrew Trickac6d9be2013-05-25 02:42:55 +00001773 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1774 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Toppercc274522012-01-07 09:06:39 +00001775 MVT::Glue));
1776
1777 return SDValue();
1778}
1779
1780SDValue DAGCombiner::visitSUBE(SDNode *N) {
1781 SDValue N0 = N->getOperand(0);
1782 SDValue N1 = N->getOperand(1);
1783 SDValue CarryIn = N->getOperand(2);
1784
1785 // fold (sube x, y, false) -> (subc x, y)
1786 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001787 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Toppercc274522012-01-07 09:06:39 +00001788
1789 return SDValue();
1790}
1791
Jack Carteradbd3ae2013-10-17 01:34:33 +00001792/// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
1793/// elements are all the same constant or undefined.
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001794static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1795 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1796 if (!C)
1797 return false;
1798
1799 APInt SplatUndef;
1800 unsigned SplatBitSize;
1801 bool HasAnyUndefs;
1802 EVT EltVT = N->getValueType(0).getVectorElementType();
1803 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1804 HasAnyUndefs) &&
1805 EltVT.getSizeInBits() >= SplatBitSize);
1806}
1807
Dan Gohman475871a2008-07-27 21:46:04 +00001808SDValue DAGCombiner::visitMUL(SDNode *N) {
1809 SDValue N0 = N->getOperand(0);
1810 SDValue N1 = N->getOperand(1);
Owen Andersone50ed302009-08-10 22:56:29 +00001811 EVT VT = N0.getValueType();
Scott Michelfdc40a02009-02-17 22:15:04 +00001812
Dan Gohman613e0d82007-07-03 14:03:57 +00001813 // fold (mul x, undef) -> 0
Dan Gohmand595b5f2007-07-10 14:20:37 +00001814 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman613e0d82007-07-03 14:03:57 +00001815 return DAG.getConstant(0, VT);
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001816
1817 bool N0IsConst = false;
1818 bool N1IsConst = false;
1819 APInt ConstValue0, ConstValue1;
1820 // fold vector ops
1821 if (VT.isVector()) {
1822 SDValue FoldedVOp = SimplifyVBinOp(N);
1823 if (FoldedVOp.getNode()) return FoldedVOp;
1824
1825 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1826 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1827 } else {
1828 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
Jack Carteradbd3ae2013-10-17 01:34:33 +00001829 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1830 : APInt();
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001831 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
Jack Carteradbd3ae2013-10-17 01:34:33 +00001832 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1833 : APInt();
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001834 }
1835
Nate Begeman1d4d4142005-09-01 00:19:25 +00001836 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001837 if (N0IsConst && N1IsConst)
1838 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1839
Nate Begeman99801192005-09-07 23:25:52 +00001840 // canonicalize constant to RHS
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001841 if (N0IsConst && !N1IsConst)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001842 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00001843 // fold (mul x, 0) -> 0
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001844 if (N1IsConst && ConstValue1 == 0)
Nate Begeman83e75ec2005-09-06 04:43:02 +00001845 return N1;
Benjamin Kramer530d09a2013-09-19 13:28:20 +00001846 // We require a splat of the entire scalar bit width for non-contiguous
1847 // bit patterns.
1848 bool IsFullSplat =
1849 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001850 // fold (mul x, 1) -> x
Benjamin Kramer530d09a2013-09-19 13:28:20 +00001851 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001852 return N0;
Nate Begeman1d4d4142005-09-01 00:19:25 +00001853 // fold (mul x, -1) -> 0-x
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001854 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickac6d9be2013-05-25 02:42:55 +00001855 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling9c8148a2009-01-30 02:45:56 +00001856 DAG.getConstant(0, VT), N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00001857 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramer530d09a2013-09-19 13:28:20 +00001858 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001859 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001860 DAG.getConstant(ConstValue1.logBase2(),
Owen Anderson95771af2011-02-25 21:41:48 +00001861 getShiftAmountTy(N0.getValueType())));
Chris Lattner3e6099b2005-10-30 06:41:49 +00001862 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramer530d09a2013-09-19 13:28:20 +00001863 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001864 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelfdc40a02009-02-17 22:15:04 +00001865 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattner3e6099b2005-10-30 06:41:49 +00001866 // single-use add), we should put the negate there.
Andrew Trickac6d9be2013-05-25 02:42:55 +00001867 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling9c8148a2009-01-30 02:45:56 +00001868 DAG.getConstant(0, VT),
Andrew Trickac6d9be2013-05-25 02:42:55 +00001869 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Anderson95771af2011-02-25 21:41:48 +00001870 DAG.getConstant(Log2Val,
1871 getShiftAmountTy(N0.getValueType()))));
Chris Lattner66b8bc32009-03-09 20:22:18 +00001872 }
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001873
1874 APInt Val;
Chris Lattner0b1a85f2006-03-01 03:44:24 +00001875 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lin155615d2013-07-08 00:37:03 +00001876 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001877 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1878 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00001879 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling9c8148a2009-01-30 02:45:56 +00001880 N1, N0.getOperand(1));
Gabor Greifba36cb52008-08-28 21:40:38 +00001881 AddToWorkList(C3.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00001882 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling9c8148a2009-01-30 02:45:56 +00001883 N0.getOperand(0), C3);
Chris Lattner0b1a85f2006-03-01 03:44:24 +00001884 }
Scott Michelfdc40a02009-02-17 22:15:04 +00001885
Chris Lattner0b1a85f2006-03-01 03:44:24 +00001886 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1887 // use.
1888 {
Dan Gohman475871a2008-07-27 21:46:04 +00001889 SDValue Sh(0,0), Y(0,0);
Chris Lattner0b1a85f2006-03-01 03:44:24 +00001890 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lin155615d2013-07-08 00:37:03 +00001891 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001892 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1893 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greifba36cb52008-08-28 21:40:38 +00001894 N0.getNode()->hasOneUse()) {
Chris Lattner0b1a85f2006-03-01 03:44:24 +00001895 Sh = N0; Y = N1;
Scott Michelfdc40a02009-02-17 22:15:04 +00001896 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greif12632d22008-08-30 19:29:20 +00001897 isa<ConstantSDNode>(N1.getOperand(1)) &&
1898 N1.getNode()->hasOneUse()) {
Chris Lattner0b1a85f2006-03-01 03:44:24 +00001899 Sh = N1; Y = N0;
1900 }
Bill Wendling73e16b22009-01-30 02:49:26 +00001901
Gabor Greifba36cb52008-08-28 21:40:38 +00001902 if (Sh.getNode()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00001903 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling9c8148a2009-01-30 02:45:56 +00001904 Sh.getOperand(0), Y);
Andrew Trickac6d9be2013-05-25 02:42:55 +00001905 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling9c8148a2009-01-30 02:45:56 +00001906 Mul, Sh.getOperand(1));
Chris Lattner0b1a85f2006-03-01 03:44:24 +00001907 }
1908 }
Bill Wendling73e16b22009-01-30 02:49:26 +00001909
Chris Lattnera1deca32006-03-04 23:33:26 +00001910 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001911 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1912 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1913 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001914 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1915 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling9c8148a2009-01-30 02:45:56 +00001916 N0.getOperand(0), N1),
Andrew Trickac6d9be2013-05-25 02:42:55 +00001917 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling9c8148a2009-01-30 02:45:56 +00001918 N0.getOperand(1), N1));
Scott Michelfdc40a02009-02-17 22:15:04 +00001919
Nate Begemancd4d58c2006-02-03 06:46:56 +00001920 // reassociate mul
Andrew Trickac6d9be2013-05-25 02:42:55 +00001921 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Gabor Greifba36cb52008-08-28 21:40:38 +00001922 if (RMUL.getNode() != 0)
Nate Begemancd4d58c2006-02-03 06:46:56 +00001923 return RMUL;
Dan Gohman7f321562007-06-25 16:23:39 +00001924
Evan Chengb3a3d5e2010-04-28 07:10:39 +00001925 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00001926}
1927
Dan Gohman475871a2008-07-27 21:46:04 +00001928SDValue DAGCombiner::visitSDIV(SDNode *N) {
1929 SDValue N0 = N->getOperand(0);
1930 SDValue N1 = N->getOperand(1);
Gabor Greifba36cb52008-08-28 21:40:38 +00001931 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1932 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Owen Andersone50ed302009-08-10 22:56:29 +00001933 EVT VT = N->getValueType(0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00001934
Dan Gohman7f321562007-06-25 16:23:39 +00001935 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00001936 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00001937 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00001938 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman05d92fe2007-07-13 20:03:40 +00001939 }
Scott Michelfdc40a02009-02-17 22:15:04 +00001940
Nate Begeman1d4d4142005-09-01 00:19:25 +00001941 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman646d7e22005-09-02 21:18:40 +00001942 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingf3cbca22008-09-24 10:25:02 +00001943 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman405e3ec2005-10-21 00:02:42 +00001944 // fold (sdiv X, 1) -> X
Eli Friedmanfd58cd72011-10-27 02:06:39 +00001945 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman405e3ec2005-10-21 00:02:42 +00001946 return N0;
1947 // fold (sdiv X, -1) -> 0-X
1948 if (N1C && N1C->isAllOnesValue())
Andrew Trickac6d9be2013-05-25 02:42:55 +00001949 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling944d34b2009-01-30 02:52:17 +00001950 DAG.getConstant(0, VT), N0);
Chris Lattner094c8fc2005-10-07 06:10:46 +00001951 // If we know the sign bits of both operands are zero, strength reduce to a
1952 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands83ec4b62008-06-06 12:08:01 +00001953 if (!VT.isVector()) {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001954 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001955 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling944d34b2009-01-30 02:52:17 +00001956 N0, N1);
Chris Lattnerf32aac32008-01-27 23:32:17 +00001957 }
Nate Begemancd6a6ed2006-02-17 07:26:20 +00001958 // fold (sdiv X, pow2) -> simple ops after legalize
Eli Friedman1c663fe2011-12-07 03:55:52 +00001959 if (N1C && !N1C->isNullValue() &&
Eli Friedmanfd58cd72011-10-27 02:06:39 +00001960 (N1C->getAPIntValue().isPowerOf2() ||
1961 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman405e3ec2005-10-21 00:02:42 +00001962 // If dividing by powers of two is cheap, then don't perform the following
1963 // fold.
1964 if (TLI.isPow2DivCheap())
Dan Gohman475871a2008-07-27 21:46:04 +00001965 return SDValue();
Bill Wendling944d34b2009-01-30 02:52:17 +00001966
Eli Friedmanfd58cd72011-10-27 02:06:39 +00001967 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling944d34b2009-01-30 02:52:17 +00001968
Chris Lattner8f4880b2006-02-16 08:02:36 +00001969 // Splat the sign bit into the register
Andrew Trickac6d9be2013-05-25 02:42:55 +00001970 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
Bill Wendling944d34b2009-01-30 02:52:17 +00001971 DAG.getConstant(VT.getSizeInBits()-1,
Owen Anderson95771af2011-02-25 21:41:48 +00001972 getShiftAmountTy(N0.getValueType())));
Gabor Greifba36cb52008-08-28 21:40:38 +00001973 AddToWorkList(SGN.getNode());
Bill Wendling944d34b2009-01-30 02:52:17 +00001974
Chris Lattner8f4880b2006-02-16 08:02:36 +00001975 // Add (N0 < 0) ? abs2 - 1 : 0;
Andrew Trickac6d9be2013-05-25 02:42:55 +00001976 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
Bill Wendling944d34b2009-01-30 02:52:17 +00001977 DAG.getConstant(VT.getSizeInBits() - lg2,
Owen Anderson95771af2011-02-25 21:41:48 +00001978 getShiftAmountTy(SGN.getValueType())));
Andrew Trickac6d9be2013-05-25 02:42:55 +00001979 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Gabor Greifba36cb52008-08-28 21:40:38 +00001980 AddToWorkList(SRL.getNode());
1981 AddToWorkList(ADD.getNode()); // Divide by pow2
Andrew Trickac6d9be2013-05-25 02:42:55 +00001982 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Anderson95771af2011-02-25 21:41:48 +00001983 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling944d34b2009-01-30 02:52:17 +00001984
Nate Begeman405e3ec2005-10-21 00:02:42 +00001985 // If we're dividing by a positive value, we're done. Otherwise, we must
1986 // negate the result.
Eli Friedmanfd58cd72011-10-27 02:06:39 +00001987 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman405e3ec2005-10-21 00:02:42 +00001988 return SRA;
Bill Wendling944d34b2009-01-30 02:52:17 +00001989
Gabor Greifba36cb52008-08-28 21:40:38 +00001990 AddToWorkList(SRA.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00001991 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling944d34b2009-01-30 02:52:17 +00001992 DAG.getConstant(0, VT), SRA);
Nate Begeman405e3ec2005-10-21 00:02:42 +00001993 }
Bill Wendling944d34b2009-01-30 02:52:17 +00001994
Nate Begeman69575232005-10-20 02:15:44 +00001995 // if integer divide is expensive and we satisfy the requirements, emit an
1996 // alternate sequence.
Eli Friedmanfd58cd72011-10-27 02:06:39 +00001997 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
Dan Gohman475871a2008-07-27 21:46:04 +00001998 SDValue Op = BuildSDIV(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00001999 if (Op.getNode()) return Op;
Nate Begeman69575232005-10-20 02:15:44 +00002000 }
Dan Gohman7f321562007-06-25 16:23:39 +00002001
Dan Gohman613e0d82007-07-03 14:03:57 +00002002 // undef / X -> 0
2003 if (N0.getOpcode() == ISD::UNDEF)
2004 return DAG.getConstant(0, VT);
2005 // X / undef -> undef
2006 if (N1.getOpcode() == ISD::UNDEF)
2007 return N1;
Dan Gohman7f321562007-06-25 16:23:39 +00002008
Dan Gohman475871a2008-07-27 21:46:04 +00002009 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00002010}
2011
Dan Gohman475871a2008-07-27 21:46:04 +00002012SDValue DAGCombiner::visitUDIV(SDNode *N) {
2013 SDValue N0 = N->getOperand(0);
2014 SDValue N1 = N->getOperand(1);
Gabor Greifba36cb52008-08-28 21:40:38 +00002015 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2016 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Owen Andersone50ed302009-08-10 22:56:29 +00002017 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00002018
Dan Gohman7f321562007-06-25 16:23:39 +00002019 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00002020 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00002021 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00002022 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman05d92fe2007-07-13 20:03:40 +00002023 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002024
Nate Begeman1d4d4142005-09-01 00:19:25 +00002025 // fold (udiv c1, c2) -> c1/c2
Nate Begeman646d7e22005-09-02 21:18:40 +00002026 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingf3cbca22008-09-24 10:25:02 +00002027 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman1d4d4142005-09-01 00:19:25 +00002028 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohman002e5d02008-03-13 22:13:53 +00002029 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickac6d9be2013-05-25 02:42:55 +00002030 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohman002e5d02008-03-13 22:13:53 +00002031 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Anderson95771af2011-02-25 21:41:48 +00002032 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002033 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begemanfb5e4bd2006-02-05 07:20:23 +00002034 if (N1.getOpcode() == ISD::SHL) {
2035 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohman002e5d02008-03-13 22:13:53 +00002036 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Andersone50ed302009-08-10 22:56:29 +00002037 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickac6d9be2013-05-25 02:42:55 +00002038 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendling07d85142009-01-30 02:55:25 +00002039 N1.getOperand(1),
2040 DAG.getConstant(SHC->getAPIntValue()
2041 .logBase2(),
2042 ADDVT));
Gabor Greifba36cb52008-08-28 21:40:38 +00002043 AddToWorkList(Add.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002044 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begemanfb5e4bd2006-02-05 07:20:23 +00002045 }
2046 }
2047 }
Nate Begeman69575232005-10-20 02:15:44 +00002048 // fold (udiv x, c) -> alternate
Dan Gohman002e5d02008-03-13 22:13:53 +00002049 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
Dan Gohman475871a2008-07-27 21:46:04 +00002050 SDValue Op = BuildUDIV(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00002051 if (Op.getNode()) return Op;
Chris Lattnere9936d12005-10-22 18:50:15 +00002052 }
Dan Gohman7f321562007-06-25 16:23:39 +00002053
Dan Gohman613e0d82007-07-03 14:03:57 +00002054 // undef / X -> 0
2055 if (N0.getOpcode() == ISD::UNDEF)
2056 return DAG.getConstant(0, VT);
2057 // X / undef -> undef
2058 if (N1.getOpcode() == ISD::UNDEF)
2059 return N1;
Dan Gohman7f321562007-06-25 16:23:39 +00002060
Dan Gohman475871a2008-07-27 21:46:04 +00002061 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00002062}
2063
Dan Gohman475871a2008-07-27 21:46:04 +00002064SDValue DAGCombiner::visitSREM(SDNode *N) {
2065 SDValue N0 = N->getOperand(0);
2066 SDValue N1 = N->getOperand(1);
Nate Begeman646d7e22005-09-02 21:18:40 +00002067 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2068 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00002069 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00002070
Nate Begeman1d4d4142005-09-01 00:19:25 +00002071 // fold (srem c1, c2) -> c1%c2
Nate Begeman646d7e22005-09-02 21:18:40 +00002072 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingf3cbca22008-09-24 10:25:02 +00002073 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman07ed4172005-10-10 21:26:48 +00002074 // If we know the sign bits of both operands are zero, strength reduce to a
2075 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands83ec4b62008-06-06 12:08:01 +00002076 if (!VT.isVector()) {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00002077 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00002078 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattneree339f42008-01-27 23:21:58 +00002079 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002080
Dan Gohman77003042007-11-26 23:46:11 +00002081 // If X/C can be simplified by the division-by-constant logic, lower
2082 // X%C to the equivalent of X-X/C*C.
Chris Lattner26d29902006-10-12 20:58:32 +00002083 if (N1C && !N1C->isNullValue()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002084 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Gabor Greifba36cb52008-08-28 21:40:38 +00002085 AddToWorkList(Div.getNode());
2086 SDValue OptimizedDiv = combine(Div.getNode());
2087 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002088 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling6d3bf8c2009-01-30 02:57:00 +00002089 OptimizedDiv, N1);
Andrew Trickac6d9be2013-05-25 02:42:55 +00002090 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greifba36cb52008-08-28 21:40:38 +00002091 AddToWorkList(Mul.getNode());
Dan Gohman77003042007-11-26 23:46:11 +00002092 return Sub;
2093 }
Chris Lattner26d29902006-10-12 20:58:32 +00002094 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002095
Dan Gohman613e0d82007-07-03 14:03:57 +00002096 // undef % X -> 0
2097 if (N0.getOpcode() == ISD::UNDEF)
2098 return DAG.getConstant(0, VT);
2099 // X % undef -> undef
2100 if (N1.getOpcode() == ISD::UNDEF)
2101 return N1;
Dan Gohman7f321562007-06-25 16:23:39 +00002102
Dan Gohman475871a2008-07-27 21:46:04 +00002103 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00002104}
2105
Dan Gohman475871a2008-07-27 21:46:04 +00002106SDValue DAGCombiner::visitUREM(SDNode *N) {
2107 SDValue N0 = N->getOperand(0);
2108 SDValue N1 = N->getOperand(1);
Nate Begeman646d7e22005-09-02 21:18:40 +00002109 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2110 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00002111 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00002112
Nate Begeman1d4d4142005-09-01 00:19:25 +00002113 // fold (urem c1, c2) -> c1%c2
Nate Begeman646d7e22005-09-02 21:18:40 +00002114 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingf3cbca22008-09-24 10:25:02 +00002115 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman07ed4172005-10-10 21:26:48 +00002116 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohman002e5d02008-03-13 22:13:53 +00002117 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickac6d9be2013-05-25 02:42:55 +00002118 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohman002e5d02008-03-13 22:13:53 +00002119 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc031e332006-02-05 07:36:48 +00002120 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2121 if (N1.getOpcode() == ISD::SHL) {
2122 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohman002e5d02008-03-13 22:13:53 +00002123 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman475871a2008-07-27 21:46:04 +00002124 SDValue Add =
Andrew Trickac6d9be2013-05-25 02:42:55 +00002125 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands83ec4b62008-06-06 12:08:01 +00002126 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohman002e5d02008-03-13 22:13:53 +00002127 VT));
Gabor Greifba36cb52008-08-28 21:40:38 +00002128 AddToWorkList(Add.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002129 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc031e332006-02-05 07:36:48 +00002130 }
2131 }
2132 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002133
Dan Gohman77003042007-11-26 23:46:11 +00002134 // If X/C can be simplified by the division-by-constant logic, lower
2135 // X%C to the equivalent of X-X/C*C.
Chris Lattner26d29902006-10-12 20:58:32 +00002136 if (N1C && !N1C->isNullValue()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002137 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Dan Gohman942ca7f2008-09-08 16:59:01 +00002138 AddToWorkList(Div.getNode());
Gabor Greifba36cb52008-08-28 21:40:38 +00002139 SDValue OptimizedDiv = combine(Div.getNode());
2140 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002141 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling6d3bf8c2009-01-30 02:57:00 +00002142 OptimizedDiv, N1);
Andrew Trickac6d9be2013-05-25 02:42:55 +00002143 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greifba36cb52008-08-28 21:40:38 +00002144 AddToWorkList(Mul.getNode());
Dan Gohman77003042007-11-26 23:46:11 +00002145 return Sub;
2146 }
Chris Lattner26d29902006-10-12 20:58:32 +00002147 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002148
Dan Gohman613e0d82007-07-03 14:03:57 +00002149 // undef % X -> 0
2150 if (N0.getOpcode() == ISD::UNDEF)
2151 return DAG.getConstant(0, VT);
2152 // X % undef -> undef
2153 if (N1.getOpcode() == ISD::UNDEF)
2154 return N1;
Dan Gohman7f321562007-06-25 16:23:39 +00002155
Dan Gohman475871a2008-07-27 21:46:04 +00002156 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00002157}
2158
Dan Gohman475871a2008-07-27 21:46:04 +00002159SDValue DAGCombiner::visitMULHS(SDNode *N) {
2160 SDValue N0 = N->getOperand(0);
2161 SDValue N1 = N->getOperand(1);
Nate Begeman646d7e22005-09-02 21:18:40 +00002162 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00002163 EVT VT = N->getValueType(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00002164 SDLoc DL(N);
Scott Michelfdc40a02009-02-17 22:15:04 +00002165
Nate Begeman1d4d4142005-09-01 00:19:25 +00002166 // fold (mulhs x, 0) -> 0
Nate Begeman646d7e22005-09-02 21:18:40 +00002167 if (N1C && N1C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00002168 return N1;
Nate Begeman1d4d4142005-09-01 00:19:25 +00002169 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohman002e5d02008-03-13 22:13:53 +00002170 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickac6d9be2013-05-25 02:42:55 +00002171 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendling326411d2009-01-30 03:00:18 +00002172 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Anderson95771af2011-02-25 21:41:48 +00002173 getShiftAmountTy(N0.getValueType())));
Dan Gohman613e0d82007-07-03 14:03:57 +00002174 // fold (mulhs x, undef) -> 0
Dan Gohmand595b5f2007-07-10 14:20:37 +00002175 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman613e0d82007-07-03 14:03:57 +00002176 return DAG.getConstant(0, VT);
Dan Gohman7f321562007-06-25 16:23:39 +00002177
Chris Lattnerde1c3602010-12-13 08:39:01 +00002178 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2179 // plus a shift.
2180 if (VT.isSimple() && !VT.isVector()) {
2181 MVT Simple = VT.getSimpleVT();
2182 unsigned SimpleSize = Simple.getSizeInBits();
2183 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2184 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2185 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2186 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2187 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattner1a0fbe22010-12-15 05:51:39 +00002188 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Anderson95771af2011-02-25 21:41:48 +00002189 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattnerde1c3602010-12-13 08:39:01 +00002190 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2191 }
2192 }
Owen Anderson95771af2011-02-25 21:41:48 +00002193
Dan Gohman475871a2008-07-27 21:46:04 +00002194 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00002195}
2196
Dan Gohman475871a2008-07-27 21:46:04 +00002197SDValue DAGCombiner::visitMULHU(SDNode *N) {
2198 SDValue N0 = N->getOperand(0);
2199 SDValue N1 = N->getOperand(1);
Nate Begeman646d7e22005-09-02 21:18:40 +00002200 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00002201 EVT VT = N->getValueType(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00002202 SDLoc DL(N);
Scott Michelfdc40a02009-02-17 22:15:04 +00002203
Nate Begeman1d4d4142005-09-01 00:19:25 +00002204 // fold (mulhu x, 0) -> 0
Nate Begeman646d7e22005-09-02 21:18:40 +00002205 if (N1C && N1C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00002206 return N1;
Nate Begeman1d4d4142005-09-01 00:19:25 +00002207 // fold (mulhu x, 1) -> 0
Dan Gohman002e5d02008-03-13 22:13:53 +00002208 if (N1C && N1C->getAPIntValue() == 1)
Nate Begeman83e75ec2005-09-06 04:43:02 +00002209 return DAG.getConstant(0, N0.getValueType());
Dan Gohman613e0d82007-07-03 14:03:57 +00002210 // fold (mulhu x, undef) -> 0
Dan Gohmand595b5f2007-07-10 14:20:37 +00002211 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman613e0d82007-07-03 14:03:57 +00002212 return DAG.getConstant(0, VT);
Dan Gohman7f321562007-06-25 16:23:39 +00002213
Chris Lattnerde1c3602010-12-13 08:39:01 +00002214 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2215 // plus a shift.
2216 if (VT.isSimple() && !VT.isVector()) {
2217 MVT Simple = VT.getSimpleVT();
2218 unsigned SimpleSize = Simple.getSizeInBits();
2219 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2220 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2221 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2222 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2223 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2224 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Anderson95771af2011-02-25 21:41:48 +00002225 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattnerde1c3602010-12-13 08:39:01 +00002226 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2227 }
2228 }
Owen Anderson95771af2011-02-25 21:41:48 +00002229
Dan Gohman475871a2008-07-27 21:46:04 +00002230 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00002231}
2232
Dan Gohman389079b2007-10-08 17:57:15 +00002233/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2234/// compute two values. LoOp and HiOp give the opcodes for the two computations
2235/// that are being performed. Return true if a simplification was made.
2236///
Scott Michelfdc40a02009-02-17 22:15:04 +00002237SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman475871a2008-07-27 21:46:04 +00002238 unsigned HiOp) {
Dan Gohman389079b2007-10-08 17:57:15 +00002239 // If the high half is not needed, just compute the low half.
Evan Cheng44711942007-11-08 09:25:29 +00002240 bool HiExists = N->hasAnyUseOfValue(1);
2241 if (!HiExists &&
Duncan Sands25cf2272008-11-24 14:53:14 +00002242 (!LegalOperations ||
Dan Gohman389079b2007-10-08 17:57:15 +00002243 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002244 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Bill Wendling826d1142009-01-30 03:08:40 +00002245 N->op_begin(), N->getNumOperands());
Chris Lattner5eee4272008-01-26 01:09:19 +00002246 return CombineTo(N, Res, Res);
Dan Gohman389079b2007-10-08 17:57:15 +00002247 }
2248
2249 // If the low half is not needed, just compute the high half.
Evan Cheng44711942007-11-08 09:25:29 +00002250 bool LoExists = N->hasAnyUseOfValue(0);
2251 if (!LoExists &&
Duncan Sands25cf2272008-11-24 14:53:14 +00002252 (!LegalOperations ||
Dan Gohman389079b2007-10-08 17:57:15 +00002253 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002254 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Bill Wendling826d1142009-01-30 03:08:40 +00002255 N->op_begin(), N->getNumOperands());
Chris Lattner5eee4272008-01-26 01:09:19 +00002256 return CombineTo(N, Res, Res);
Dan Gohman389079b2007-10-08 17:57:15 +00002257 }
2258
Evan Cheng44711942007-11-08 09:25:29 +00002259 // If both halves are used, return as it is.
2260 if (LoExists && HiExists)
Dan Gohman475871a2008-07-27 21:46:04 +00002261 return SDValue();
Evan Cheng44711942007-11-08 09:25:29 +00002262
2263 // If the two computed results can be simplified separately, separate them.
Evan Cheng44711942007-11-08 09:25:29 +00002264 if (LoExists) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002265 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Bill Wendling826d1142009-01-30 03:08:40 +00002266 N->op_begin(), N->getNumOperands());
Gabor Greifba36cb52008-08-28 21:40:38 +00002267 AddToWorkList(Lo.getNode());
2268 SDValue LoOpt = combine(Lo.getNode());
2269 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sands25cf2272008-11-24 14:53:14 +00002270 (!LegalOperations ||
Duncan Sandsd4b9c172008-06-13 19:07:40 +00002271 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner5eee4272008-01-26 01:09:19 +00002272 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman389079b2007-10-08 17:57:15 +00002273 }
2274
Evan Cheng44711942007-11-08 09:25:29 +00002275 if (HiExists) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002276 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Duncan Sands25cf2272008-11-24 14:53:14 +00002277 N->op_begin(), N->getNumOperands());
Gabor Greifba36cb52008-08-28 21:40:38 +00002278 AddToWorkList(Hi.getNode());
2279 SDValue HiOpt = combine(Hi.getNode());
2280 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sands25cf2272008-11-24 14:53:14 +00002281 (!LegalOperations ||
Duncan Sandsd4b9c172008-06-13 19:07:40 +00002282 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner5eee4272008-01-26 01:09:19 +00002283 return CombineTo(N, HiOpt, HiOpt);
Evan Cheng44711942007-11-08 09:25:29 +00002284 }
Bill Wendling826d1142009-01-30 03:08:40 +00002285
Dan Gohman475871a2008-07-27 21:46:04 +00002286 return SDValue();
Dan Gohman389079b2007-10-08 17:57:15 +00002287}
2288
Dan Gohman475871a2008-07-27 21:46:04 +00002289SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2290 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greifba36cb52008-08-28 21:40:38 +00002291 if (Res.getNode()) return Res;
Dan Gohman389079b2007-10-08 17:57:15 +00002292
Chris Lattner33e77d32010-12-15 06:04:19 +00002293 EVT VT = N->getValueType(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00002294 SDLoc DL(N);
Chris Lattner33e77d32010-12-15 06:04:19 +00002295
2296 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2297 // plus a shift.
2298 if (VT.isSimple() && !VT.isVector()) {
2299 MVT Simple = VT.getSimpleVT();
2300 unsigned SimpleSize = Simple.getSizeInBits();
2301 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2302 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2303 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2304 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2305 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2306 // Compute the high part as N1.
2307 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Anderson95771af2011-02-25 21:41:48 +00002308 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner33e77d32010-12-15 06:04:19 +00002309 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2310 // Compute the low part as N0.
2311 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2312 return CombineTo(N, Lo, Hi);
2313 }
2314 }
Owen Anderson95771af2011-02-25 21:41:48 +00002315
Dan Gohman475871a2008-07-27 21:46:04 +00002316 return SDValue();
Dan Gohman389079b2007-10-08 17:57:15 +00002317}
2318
Dan Gohman475871a2008-07-27 21:46:04 +00002319SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2320 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greifba36cb52008-08-28 21:40:38 +00002321 if (Res.getNode()) return Res;
Dan Gohman389079b2007-10-08 17:57:15 +00002322
Chris Lattner33e77d32010-12-15 06:04:19 +00002323 EVT VT = N->getValueType(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00002324 SDLoc DL(N);
Owen Anderson95771af2011-02-25 21:41:48 +00002325
Chris Lattner33e77d32010-12-15 06:04:19 +00002326 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2327 // plus a shift.
2328 if (VT.isSimple() && !VT.isVector()) {
2329 MVT Simple = VT.getSimpleVT();
2330 unsigned SimpleSize = Simple.getSizeInBits();
2331 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2332 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2333 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2334 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2335 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2336 // Compute the high part as N1.
2337 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Anderson95771af2011-02-25 21:41:48 +00002338 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner33e77d32010-12-15 06:04:19 +00002339 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2340 // Compute the low part as N0.
2341 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2342 return CombineTo(N, Lo, Hi);
2343 }
2344 }
Owen Anderson95771af2011-02-25 21:41:48 +00002345
Dan Gohman475871a2008-07-27 21:46:04 +00002346 return SDValue();
Dan Gohman389079b2007-10-08 17:57:15 +00002347}
2348
Benjamin Kramerf55d26e2011-05-21 18:31:55 +00002349SDValue DAGCombiner::visitSMULO(SDNode *N) {
2350 // (smulo x, 2) -> (saddo x, x)
2351 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2352 if (C2->getAPIntValue() == 2)
Andrew Trickac6d9be2013-05-25 02:42:55 +00002353 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramerf55d26e2011-05-21 18:31:55 +00002354 N->getOperand(0), N->getOperand(0));
2355
2356 return SDValue();
2357}
2358
2359SDValue DAGCombiner::visitUMULO(SDNode *N) {
2360 // (umulo x, 2) -> (uaddo x, x)
2361 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2362 if (C2->getAPIntValue() == 2)
Andrew Trickac6d9be2013-05-25 02:42:55 +00002363 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramerf55d26e2011-05-21 18:31:55 +00002364 N->getOperand(0), N->getOperand(0));
2365
2366 return SDValue();
2367}
2368
Dan Gohman475871a2008-07-27 21:46:04 +00002369SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2370 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greifba36cb52008-08-28 21:40:38 +00002371 if (Res.getNode()) return Res;
Scott Michelfdc40a02009-02-17 22:15:04 +00002372
Dan Gohman475871a2008-07-27 21:46:04 +00002373 return SDValue();
Dan Gohman389079b2007-10-08 17:57:15 +00002374}
2375
Dan Gohman475871a2008-07-27 21:46:04 +00002376SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2377 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greifba36cb52008-08-28 21:40:38 +00002378 if (Res.getNode()) return Res;
Scott Michelfdc40a02009-02-17 22:15:04 +00002379
Dan Gohman475871a2008-07-27 21:46:04 +00002380 return SDValue();
Dan Gohman389079b2007-10-08 17:57:15 +00002381}
2382
Chris Lattner35e5c142006-05-05 05:51:50 +00002383/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2384/// two operands of the same opcode, try to simplify it.
Dan Gohman475871a2008-07-27 21:46:04 +00002385SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2386 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Andersone50ed302009-08-10 22:56:29 +00002387 EVT VT = N0.getValueType();
Chris Lattner35e5c142006-05-05 05:51:50 +00002388 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelfdc40a02009-02-17 22:15:04 +00002389
Dan Gohmanff00a552010-01-14 03:08:49 +00002390 // Bail early if none of these transforms apply.
2391 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2392
Chris Lattner540121f2006-05-05 06:31:05 +00002393 // For each of OP in AND/OR/XOR:
2394 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2395 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2396 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Dan Gohman4e39e9d2010-06-24 14:30:44 +00002397 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman93e0ed32009-12-03 07:11:29 +00002398 //
2399 // do not sink logical op inside of a vector extend, since it may combine
2400 // into a vsetcc.
Evan Chengd40d03e2010-01-06 19:38:29 +00002401 EVT Op0VT = N0.getOperand(0).getValueType();
2402 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohman97121ba2009-04-08 00:15:30 +00002403 N0.getOpcode() == ISD::SIGN_EXTEND ||
Evan Chenge5b51ac2010-04-17 06:13:15 +00002404 // Avoid infinite looping with PromoteIntBinOp.
2405 (N0.getOpcode() == ISD::ANY_EXTEND &&
2406 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman4e39e9d2010-06-24 14:30:44 +00002407 (N0.getOpcode() == ISD::TRUNCATE &&
2408 (!TLI.isZExtFree(VT, Op0VT) ||
2409 !TLI.isTruncateFree(Op0VT, VT)) &&
2410 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman93e0ed32009-12-03 07:11:29 +00002411 !VT.isVector() &&
Evan Chengd40d03e2010-01-06 19:38:29 +00002412 Op0VT == N1.getOperand(0).getValueType() &&
2413 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002414 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendlingb74c8672009-01-30 19:25:47 +00002415 N0.getOperand(0).getValueType(),
2416 N0.getOperand(0), N1.getOperand(0));
Gabor Greifba36cb52008-08-28 21:40:38 +00002417 AddToWorkList(ORNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002418 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner35e5c142006-05-05 05:51:50 +00002419 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002420
Chris Lattnera3dc3f62006-05-05 06:10:43 +00002421 // For each of OP in SHL/SRL/SRA/AND...
2422 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2423 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2424 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner35e5c142006-05-05 05:51:50 +00002425 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattnera3dc3f62006-05-05 06:10:43 +00002426 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner35e5c142006-05-05 05:51:50 +00002427 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002428 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendlingb74c8672009-01-30 19:25:47 +00002429 N0.getOperand(0).getValueType(),
2430 N0.getOperand(0), N1.getOperand(0));
Gabor Greifba36cb52008-08-28 21:40:38 +00002431 AddToWorkList(ORNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002432 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendlingb74c8672009-01-30 19:25:47 +00002433 ORNode, N0.getOperand(1));
Chris Lattner35e5c142006-05-05 05:51:50 +00002434 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002435
Nadav Rotem4ac90812012-04-01 19:31:22 +00002436 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2437 // Only perform this optimization after type legalization and before
2438 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2439 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2440 // we don't want to undo this promotion.
2441 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2442 // on scalars.
Nadav Rotem6dfabb62012-09-20 08:53:31 +00002443 if ((N0.getOpcode() == ISD::BITCAST ||
2444 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2445 Level == AfterLegalizeTypes) {
Nadav Rotem4ac90812012-04-01 19:31:22 +00002446 SDValue In0 = N0.getOperand(0);
2447 SDValue In1 = N1.getOperand(0);
2448 EVT In0Ty = In0.getValueType();
2449 EVT In1Ty = In1.getValueType();
Andrew Trickac6d9be2013-05-25 02:42:55 +00002450 SDLoc DL(N);
Nadav Rotem6dfabb62012-09-20 08:53:31 +00002451 // If both incoming values are integers, and the original types are the
2452 // same.
Nadav Rotem4ac90812012-04-01 19:31:22 +00002453 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem6dfabb62012-09-20 08:53:31 +00002454 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2455 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Nadav Rotem4ac90812012-04-01 19:31:22 +00002456 AddToWorkList(Op.getNode());
2457 return BC;
2458 }
2459 }
2460
2461 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2462 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2463 // If both shuffles use the same mask, and both shuffle within a single
2464 // vector, then it is worthwhile to move the swizzle after the operation.
2465 // The type-legalizer generates this pattern when loading illegal
2466 // vector types from memory. In many cases this allows additional shuffle
2467 // optimizations.
Craig Topperf9204232012-04-09 07:19:09 +00002468 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2469 N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2470 N1.getOperand(1).getOpcode() == ISD::UNDEF) {
Nadav Rotem4ac90812012-04-01 19:31:22 +00002471 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2472 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topperf9204232012-04-09 07:19:09 +00002473
2474 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2475 "Inputs to shuffles are not the same type");
Nadav Rotem4ac90812012-04-01 19:31:22 +00002476
2477 unsigned NumElts = VT.getVectorNumElements();
Nadav Rotem4ac90812012-04-01 19:31:22 +00002478
2479 // Check that both shuffles use the same mask. The masks are known to be of
2480 // the same length because the result vector type is the same.
2481 bool SameMask = true;
2482 for (unsigned i = 0; i != NumElts; ++i) {
2483 int Idx0 = SVN0->getMaskElt(i);
2484 int Idx1 = SVN1->getMaskElt(i);
2485 if (Idx0 != Idx1) {
2486 SameMask = false;
2487 break;
2488 }
2489 }
2490
Craig Topperf9204232012-04-09 07:19:09 +00002491 if (SameMask) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002492 SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
Craig Topperf9204232012-04-09 07:19:09 +00002493 N0.getOperand(0), N1.getOperand(0));
Nadav Rotem4ac90812012-04-01 19:31:22 +00002494 AddToWorkList(Op.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002495 return DAG.getVectorShuffle(VT, SDLoc(N), Op,
Craig Topperf9204232012-04-09 07:19:09 +00002496 DAG.getUNDEF(VT), &SVN0->getMask()[0]);
Nadav Rotem4ac90812012-04-01 19:31:22 +00002497 }
2498 }
Craig Topperf9204232012-04-09 07:19:09 +00002499
Dan Gohman475871a2008-07-27 21:46:04 +00002500 return SDValue();
Chris Lattner35e5c142006-05-05 05:51:50 +00002501}
2502
Dan Gohman475871a2008-07-27 21:46:04 +00002503SDValue DAGCombiner::visitAND(SDNode *N) {
2504 SDValue N0 = N->getOperand(0);
2505 SDValue N1 = N->getOperand(1);
2506 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman646d7e22005-09-02 21:18:40 +00002507 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2508 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00002509 EVT VT = N1.getValueType();
Dan Gohman6900a392010-03-04 00:23:16 +00002510 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelfdc40a02009-02-17 22:15:04 +00002511
Dan Gohman7f321562007-06-25 16:23:39 +00002512 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00002513 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00002514 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00002515 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper9472b4f2012-12-08 22:49:19 +00002516
2517 // fold (and x, 0) -> 0, vector edition
2518 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2519 return N0;
2520 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2521 return N1;
2522
2523 // fold (and x, -1) -> x, vector edition
2524 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2525 return N1;
2526 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2527 return N0;
Dan Gohman05d92fe2007-07-13 20:03:40 +00002528 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002529
Dan Gohman613e0d82007-07-03 14:03:57 +00002530 // fold (and x, undef) -> 0
Dan Gohmand595b5f2007-07-10 14:20:37 +00002531 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman613e0d82007-07-03 14:03:57 +00002532 return DAG.getConstant(0, VT);
Nate Begeman1d4d4142005-09-01 00:19:25 +00002533 // fold (and c1, c2) -> c1&c2
Nate Begeman646d7e22005-09-02 21:18:40 +00002534 if (N0C && N1C)
Bill Wendlingf3cbca22008-09-24 10:25:02 +00002535 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman99801192005-09-07 23:25:52 +00002536 // canonicalize constant to RHS
Nate Begemana0e221d2005-10-18 00:28:13 +00002537 if (N0C && !N1C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00002538 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00002539 // fold (and x, -1) -> x
Nate Begeman646d7e22005-09-02 21:18:40 +00002540 if (N1C && N1C->isAllOnesValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00002541 return N0;
2542 // if (and x, c) is known to be zero, return 0
Dan Gohman475871a2008-07-27 21:46:04 +00002543 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman2e68b6f2008-02-25 21:11:39 +00002544 APInt::getAllOnesValue(BitWidth)))
Nate Begeman83e75ec2005-09-06 04:43:02 +00002545 return DAG.getConstant(0, VT);
Nate Begemancd4d58c2006-02-03 06:46:56 +00002546 // reassociate and
Andrew Trickac6d9be2013-05-25 02:42:55 +00002547 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Gabor Greifba36cb52008-08-28 21:40:38 +00002548 if (RAND.getNode() != 0)
Nate Begemancd4d58c2006-02-03 06:46:56 +00002549 return RAND;
Bill Wendling7d9f2b92010-03-03 00:35:56 +00002550 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begeman5dc7e862005-11-02 18:42:59 +00002551 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman1d4d4142005-09-01 00:19:25 +00002552 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman002e5d02008-03-13 22:13:53 +00002553 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00002554 return N1;
Chris Lattner3603cd62006-02-02 07:17:31 +00002555 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2556 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman475871a2008-07-27 21:46:04 +00002557 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman2e68b6f2008-02-25 21:11:39 +00002558 APInt Mask = ~N1C->getAPIntValue();
Jay Foad40f8f622010-12-07 08:25:19 +00002559 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman2e68b6f2008-02-25 21:11:39 +00002560 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002561 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling2627a882009-01-30 20:43:18 +00002562 N0.getValueType(), N0Op0);
Scott Michelfdc40a02009-02-17 22:15:04 +00002563
Chris Lattner1ec05d12006-03-01 21:47:21 +00002564 // Replace uses of the AND with uses of the Zero extend node.
2565 CombineTo(N, Zext);
Scott Michelfdc40a02009-02-17 22:15:04 +00002566
Chris Lattner3603cd62006-02-02 07:17:31 +00002567 // We actually want to replace all uses of the any_extend with the
2568 // zero_extend, to avoid duplicating things. This will later cause this
2569 // AND to be folded.
Gabor Greifba36cb52008-08-28 21:40:38 +00002570 CombineTo(N0.getNode(), Zext);
Dan Gohman475871a2008-07-27 21:46:04 +00002571 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3603cd62006-02-02 07:17:31 +00002572 }
2573 }
Stephen Lin155615d2013-07-08 00:37:03 +00002574 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy6259dcd2012-02-20 12:02:38 +00002575 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2576 // already be zero by virtue of the width of the base type of the load.
2577 //
2578 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2579 // more cases.
2580 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2581 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2582 N0.getOpcode() == ISD::LOAD) {
2583 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2584 N0 : N0.getOperand(0) );
2585
2586 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2587 // This can be a pure constant or a vector splat, in which case we treat the
2588 // vector as a scalar and use the splat value.
2589 APInt Constant = APInt::getNullValue(1);
2590 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2591 Constant = C->getAPIntValue();
2592 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2593 APInt SplatValue, SplatUndef;
2594 unsigned SplatBitSize;
2595 bool HasAnyUndefs;
2596 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2597 SplatBitSize, HasAnyUndefs);
2598 if (IsSplat) {
2599 // Undef bits can contribute to a possible optimisation if set, so
2600 // set them.
2601 SplatValue |= SplatUndef;
2602
2603 // The splat value may be something like "0x00FFFFFF", which means 0 for
2604 // the first vector value and FF for the rest, repeating. We need a mask
2605 // that will apply equally to all members of the vector, so AND all the
2606 // lanes of the constant together.
2607 EVT VT = Vector->getValueType(0);
2608 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3d5e1612012-09-05 08:57:21 +00002609
2610 // If the splat value has been compressed to a bitlength lower
2611 // than the size of the vector lane, we need to re-expand it to
2612 // the lane size.
2613 if (BitWidth > SplatBitSize)
2614 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2615 SplatBitSize < BitWidth;
2616 SplatBitSize = SplatBitSize * 2)
2617 SplatValue |= SplatValue.shl(SplatBitSize);
2618
James Molloy6259dcd2012-02-20 12:02:38 +00002619 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3d5e1612012-09-05 08:57:21 +00002620 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy6259dcd2012-02-20 12:02:38 +00002621 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2622 }
2623 }
2624
2625 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2626 // actually legal and isn't going to get expanded, else this is a false
2627 // optimisation.
2628 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2629 Load->getMemoryVT());
2630
2631 // Resize the constant to the same size as the original memory access before
2632 // extension. If it is still the AllOnesValue then this AND is completely
2633 // unneeded.
2634 Constant =
2635 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2636
2637 bool B;
2638 switch (Load->getExtensionType()) {
2639 default: B = false; break;
2640 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2641 case ISD::ZEXTLOAD:
2642 case ISD::NON_EXTLOAD: B = true; break;
2643 }
2644
2645 if (B && Constant.isAllOnesValue()) {
2646 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2647 // preserve semantics once we get rid of the AND.
2648 SDValue NewLoad(Load, 0);
2649 if (Load->getExtensionType() == ISD::EXTLOAD) {
2650 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickac6d9be2013-05-25 02:42:55 +00002651 Load->getValueType(0), SDLoc(Load),
James Molloy6259dcd2012-02-20 12:02:38 +00002652 Load->getChain(), Load->getBasePtr(),
2653 Load->getOffset(), Load->getMemoryVT(),
2654 Load->getMemOperand());
2655 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkeld65e4632012-06-20 15:42:48 +00002656 if (Load->getNumValues() == 3) {
2657 // PRE/POST_INC loads have 3 values.
2658 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2659 NewLoad.getValue(2) };
2660 CombineTo(Load, To, 3, true);
2661 } else {
2662 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2663 }
James Molloy6259dcd2012-02-20 12:02:38 +00002664 }
2665
2666 // Fold the AND away, taking care not to fold to the old load node if we
2667 // replaced it.
2668 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2669
2670 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2671 }
2672 }
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002673 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2674 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2675 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2676 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelfdc40a02009-02-17 22:15:04 +00002677
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002678 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands83ec4b62008-06-06 12:08:01 +00002679 LL.getValueType().isInteger()) {
Bill Wendling2627a882009-01-30 20:43:18 +00002680 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Dan Gohman002e5d02008-03-13 22:13:53 +00002681 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002682 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling2627a882009-01-30 20:43:18 +00002683 LR.getValueType(), LL, RL);
Gabor Greifba36cb52008-08-28 21:40:38 +00002684 AddToWorkList(ORNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002685 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002686 }
Bill Wendling2627a882009-01-30 20:43:18 +00002687 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002688 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002689 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling2627a882009-01-30 20:43:18 +00002690 LR.getValueType(), LL, RL);
Gabor Greifba36cb52008-08-28 21:40:38 +00002691 AddToWorkList(ANDNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002692 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002693 }
Bill Wendling2627a882009-01-30 20:43:18 +00002694 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002695 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002696 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling2627a882009-01-30 20:43:18 +00002697 LR.getValueType(), LL, RL);
Gabor Greifba36cb52008-08-28 21:40:38 +00002698 AddToWorkList(ORNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002699 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002700 }
2701 }
Jim Grosbach51a02802013-08-13 21:30:58 +00002702 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2703 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2704 Op0 == Op1 && LL.getValueType().isInteger() &&
2705 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2706 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2707 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2708 cast<ConstantSDNode>(RR)->isNullValue()))) {
2709 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2710 LL, DAG.getConstant(1, LL.getValueType()));
2711 AddToWorkList(ADDNode.getNode());
2712 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2713 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2714 }
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002715 // canonicalize equivalent to ll == rl
2716 if (LL == RR && LR == RL) {
2717 Op1 = ISD::getSetCCSwappedOperands(Op1);
2718 std::swap(RL, RR);
2719 }
2720 if (LL == RL && LR == RR) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00002721 bool isInteger = LL.getValueType().isInteger();
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002722 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner6e1c6232008-10-28 07:11:07 +00002723 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundfdbeb052012-12-19 10:19:55 +00002724 (!LegalOperations ||
Owen Anderson39125d92013-02-14 09:07:33 +00002725 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2726 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault225ed702013-05-18 00:21:46 +00002727 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickac6d9be2013-05-25 02:42:55 +00002728 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling2627a882009-01-30 20:43:18 +00002729 LL, LR, Result);
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002730 }
2731 }
Chris Lattner35e5c142006-05-05 05:51:50 +00002732
Bill Wendling2627a882009-01-30 20:43:18 +00002733 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner35e5c142006-05-05 05:51:50 +00002734 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman475871a2008-07-27 21:46:04 +00002735 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00002736 if (Tmp.getNode()) return Tmp;
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002737 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002738
Nate Begemande996292006-02-03 22:24:05 +00002739 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2740 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands83ec4b62008-06-06 12:08:01 +00002741 if (!VT.isVector() &&
Dan Gohman475871a2008-07-27 21:46:04 +00002742 SimplifyDemandedBits(SDValue(N, 0)))
2743 return SDValue(N, 0);
Evan Chengd40d03e2010-01-06 19:38:29 +00002744
Nate Begemanded49632005-10-13 03:11:28 +00002745 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greifba36cb52008-08-28 21:40:38 +00002746 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Cheng466685d2006-10-09 20:57:25 +00002747 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman8a55ce42009-09-23 21:02:20 +00002748 EVT MemVT = LN0->getMemoryVT();
Nate Begemanbfd65a02005-10-13 18:34:58 +00002749 // If we zero all the possible extended bits, then we can turn this into
2750 // a zextload if we are running before legalize or the operation is legal.
Dan Gohman6900a392010-03-04 00:23:16 +00002751 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman2e68b6f2008-02-25 21:11:39 +00002752 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohman6900a392010-03-04 00:23:16 +00002753 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sands25cf2272008-11-24 14:53:14 +00002754 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman8a55ce42009-09-23 21:02:20 +00002755 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002756 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling2627a882009-01-30 20:43:18 +00002757 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00002758 MemVT, LN0->getMemOperand());
Chris Lattner5750df92006-03-01 04:03:14 +00002759 AddToWorkList(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00002760 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman475871a2008-07-27 21:46:04 +00002761 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begemanded49632005-10-13 03:11:28 +00002762 }
2763 }
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002764 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greifba36cb52008-08-28 21:40:38 +00002765 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng83060c52007-03-07 08:07:03 +00002766 N0.hasOneUse()) {
Evan Cheng466685d2006-10-09 20:57:25 +00002767 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman8a55ce42009-09-23 21:02:20 +00002768 EVT MemVT = LN0->getMemoryVT();
Nate Begemanbfd65a02005-10-13 18:34:58 +00002769 // If we zero all the possible extended bits, then we can turn this into
2770 // a zextload if we are running before legalize or the operation is legal.
Dan Gohman6900a392010-03-04 00:23:16 +00002771 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman2e68b6f2008-02-25 21:11:39 +00002772 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohman6900a392010-03-04 00:23:16 +00002773 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sands25cf2272008-11-24 14:53:14 +00002774 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman8a55ce42009-09-23 21:02:20 +00002775 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002776 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford66589dc2013-10-28 11:17:59 +00002777 LN0->getChain(), LN0->getBasePtr(),
2778 MemVT, LN0->getMemOperand());
Chris Lattner5750df92006-03-01 04:03:14 +00002779 AddToWorkList(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00002780 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman475871a2008-07-27 21:46:04 +00002781 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begemanded49632005-10-13 03:11:28 +00002782 }
2783 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002784
Chris Lattner35a9f5a2006-02-28 06:49:37 +00002785 // fold (and (load x), 255) -> (zextload x, i8)
2786 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Chengd40d03e2010-01-06 19:38:29 +00002787 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2788 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2789 (N0.getOpcode() == ISD::ANY_EXTEND &&
2790 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2791 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2792 LoadSDNode *LN0 = HasAnyExt
2793 ? cast<LoadSDNode>(N0.getOperand(0))
2794 : cast<LoadSDNode>(N0);
Evan Cheng466685d2006-10-09 20:57:25 +00002795 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover5bce67a2013-07-02 09:58:53 +00002796 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands8eab8a22008-06-09 11:32:28 +00002797 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Chengd40d03e2010-01-06 19:38:29 +00002798 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2799 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2800 EVT LoadedVT = LN0->getMemoryVT();
Duncan Sands8eab8a22008-06-09 11:32:28 +00002801
Evan Chengd40d03e2010-01-06 19:38:29 +00002802 if (ExtVT == LoadedVT &&
2803 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
Chris Lattneref7634c2010-01-07 21:53:27 +00002804 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Wesley Peckbf17cfa2010-11-23 03:31:01 +00002805
2806 SDValue NewLoad =
Andrew Trickac6d9be2013-05-25 02:42:55 +00002807 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford66589dc2013-10-28 11:17:59 +00002808 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2809 LN0->getMemOperand());
Chris Lattneref7634c2010-01-07 21:53:27 +00002810 AddToWorkList(N);
2811 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2812 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2813 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00002814
Chris Lattneref7634c2010-01-07 21:53:27 +00002815 // Do not change the width of a volatile load.
2816 // Do not generate loads of non-round integer types since these can
2817 // be expensive (and would be wrong if the type is not byte sized).
2818 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2819 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2820 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling2627a882009-01-30 20:43:18 +00002821
Chris Lattneref7634c2010-01-07 21:53:27 +00002822 unsigned Alignment = LN0->getAlignment();
2823 SDValue NewPtr = LN0->getBasePtr();
2824
2825 // For big endian targets, we need to add an offset to the pointer
2826 // to load the correct bytes. For little endian systems, we merely
2827 // need to read fewer bytes from the same pointer.
2828 if (TLI.isBigEndian()) {
Evan Chengd40d03e2010-01-06 19:38:29 +00002829 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2830 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2831 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickac6d9be2013-05-25 02:42:55 +00002832 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattneref7634c2010-01-07 21:53:27 +00002833 NewPtr, DAG.getConstant(PtrOff, PtrType));
2834 Alignment = MinAlign(Alignment, PtrOff);
Evan Chengd40d03e2010-01-06 19:38:29 +00002835 }
Chris Lattneref7634c2010-01-07 21:53:27 +00002836
2837 AddToWorkList(NewPtr.getNode());
Wesley Peckbf17cfa2010-11-23 03:31:01 +00002838
Chris Lattneref7634c2010-01-07 21:53:27 +00002839 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2840 SDValue Load =
Andrew Trickac6d9be2013-05-25 02:42:55 +00002841 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattneref7634c2010-01-07 21:53:27 +00002842 LN0->getChain(), NewPtr,
Chris Lattner3d6ccfb2010-09-21 17:04:51 +00002843 LN0->getPointerInfo(),
David Greene1e559442010-02-15 17:00:31 +00002844 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00002845 Alignment, LN0->getTBAAInfo());
Chris Lattneref7634c2010-01-07 21:53:27 +00002846 AddToWorkList(N);
2847 CombineTo(LN0, Load, Load.getValue(1));
2848 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sandsdc846502007-10-28 12:59:45 +00002849 }
Evan Cheng466685d2006-10-09 20:57:25 +00002850 }
Chris Lattner15045b62006-02-28 06:35:35 +00002851 }
2852 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002853
Evan Chenga9e13ba2012-07-17 18:54:11 +00002854 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2855 VT.getSizeInBits() <= 64) {
2856 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2857 APInt ADDC = ADDI->getAPIntValue();
2858 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2859 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2860 // immediate for an add, but it is legal if its top c2 bits are set,
2861 // transform the ADD so the immediate doesn't need to be materialized
2862 // in a register.
2863 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2864 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2865 SRLI->getZExtValue());
2866 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2867 ADDC |= Mask;
2868 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2869 SDValue NewAdd =
Andrew Trickac6d9be2013-05-25 02:42:55 +00002870 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenga9e13ba2012-07-17 18:54:11 +00002871 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2872 CombineTo(N0.getNode(), NewAdd);
2873 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2874 }
2875 }
2876 }
2877 }
2878 }
2879 }
Evan Chenga9e13ba2012-07-17 18:54:11 +00002880
Tim Northover5d8c2e42013-08-27 13:46:45 +00002881 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2882 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2883 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2884 N0.getOperand(1), false);
2885 if (BSwap.getNode())
2886 return BSwap;
2887 }
2888
Evan Chengb3a3d5e2010-04-28 07:10:39 +00002889 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00002890}
2891
Evan Cheng9568e5c2011-06-21 06:01:08 +00002892/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2893///
2894SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2895 bool DemandHighBits) {
2896 if (!LegalOperations)
2897 return SDValue();
2898
2899 EVT VT = N->getValueType(0);
2900 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2901 return SDValue();
2902 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2903 return SDValue();
2904
2905 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2906 bool LookPassAnd0 = false;
2907 bool LookPassAnd1 = false;
2908 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2909 std::swap(N0, N1);
2910 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2911 std::swap(N0, N1);
2912 if (N0.getOpcode() == ISD::AND) {
2913 if (!N0.getNode()->hasOneUse())
2914 return SDValue();
2915 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2916 if (!N01C || N01C->getZExtValue() != 0xFF00)
2917 return SDValue();
2918 N0 = N0.getOperand(0);
2919 LookPassAnd0 = true;
2920 }
2921
2922 if (N1.getOpcode() == ISD::AND) {
2923 if (!N1.getNode()->hasOneUse())
2924 return SDValue();
2925 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2926 if (!N11C || N11C->getZExtValue() != 0xFF)
2927 return SDValue();
2928 N1 = N1.getOperand(0);
2929 LookPassAnd1 = true;
2930 }
2931
2932 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2933 std::swap(N0, N1);
2934 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2935 return SDValue();
2936 if (!N0.getNode()->hasOneUse() ||
2937 !N1.getNode()->hasOneUse())
2938 return SDValue();
2939
2940 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2941 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2942 if (!N01C || !N11C)
2943 return SDValue();
2944 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2945 return SDValue();
2946
2947 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2948 SDValue N00 = N0->getOperand(0);
2949 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2950 if (!N00.getNode()->hasOneUse())
2951 return SDValue();
2952 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2953 if (!N001C || N001C->getZExtValue() != 0xFF)
2954 return SDValue();
2955 N00 = N00.getOperand(0);
2956 LookPassAnd0 = true;
2957 }
2958
2959 SDValue N10 = N1->getOperand(0);
2960 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2961 if (!N10.getNode()->hasOneUse())
2962 return SDValue();
2963 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2964 if (!N101C || N101C->getZExtValue() != 0xFF00)
2965 return SDValue();
2966 N10 = N10.getOperand(0);
2967 LookPassAnd1 = true;
2968 }
2969
2970 if (N00 != N10)
2971 return SDValue();
2972
Tim Northover5d8c2e42013-08-27 13:46:45 +00002973 // Make sure everything beyond the low halfword gets set to zero since the SRL
2974 // 16 will clear the top bits.
Evan Cheng9568e5c2011-06-21 06:01:08 +00002975 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover5d8c2e42013-08-27 13:46:45 +00002976 if (DemandHighBits && OpSizeInBits > 16) {
2977 // If the left-shift isn't masked out then the only way this is a bswap is
2978 // if all bits beyond the low 8 are 0. In that case the entire pattern
2979 // reduces to a left shift anyway: leave it for other parts of the combiner.
2980 if (!LookPassAnd0)
2981 return SDValue();
2982
2983 // However, if the right shift isn't masked out then it might be because
2984 // it's not needed. See if we can spot that too.
2985 if (!LookPassAnd1 &&
2986 !DAG.MaskedValueIsZero(
2987 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
2988 return SDValue();
2989 }
Eric Christopher7332e6e2011-07-14 01:12:15 +00002990
Andrew Trickac6d9be2013-05-25 02:42:55 +00002991 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng9568e5c2011-06-21 06:01:08 +00002992 if (OpSizeInBits > 16)
Andrew Trickac6d9be2013-05-25 02:42:55 +00002993 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng9568e5c2011-06-21 06:01:08 +00002994 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2995 return Res;
2996}
2997
2998/// isBSwapHWordElement - Return true if the specified node is an element
2999/// that makes up a 32-bit packed halfword byteswap. i.e.
3000/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
Craig Toppera0ec3f92013-07-14 04:42:23 +00003001static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
Evan Cheng9568e5c2011-06-21 06:01:08 +00003002 if (!N.getNode()->hasOneUse())
3003 return false;
3004
3005 unsigned Opc = N.getOpcode();
3006 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3007 return false;
3008
3009 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3010 if (!N1C)
3011 return false;
3012
3013 unsigned Num;
3014 switch (N1C->getZExtValue()) {
3015 default:
3016 return false;
3017 case 0xFF: Num = 0; break;
3018 case 0xFF00: Num = 1; break;
3019 case 0xFF0000: Num = 2; break;
3020 case 0xFF000000: Num = 3; break;
3021 }
3022
3023 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3024 SDValue N0 = N.getOperand(0);
3025 if (Opc == ISD::AND) {
3026 if (Num == 0 || Num == 2) {
3027 // (x >> 8) & 0xff
3028 // (x >> 8) & 0xff0000
3029 if (N0.getOpcode() != ISD::SRL)
3030 return false;
3031 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3032 if (!C || C->getZExtValue() != 8)
3033 return false;
3034 } else {
3035 // (x << 8) & 0xff00
3036 // (x << 8) & 0xff000000
3037 if (N0.getOpcode() != ISD::SHL)
3038 return false;
3039 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3040 if (!C || C->getZExtValue() != 8)
3041 return false;
3042 }
3043 } else if (Opc == ISD::SHL) {
3044 // (x & 0xff) << 8
3045 // (x & 0xff0000) << 8
3046 if (Num != 0 && Num != 2)
3047 return false;
3048 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3049 if (!C || C->getZExtValue() != 8)
3050 return false;
3051 } else { // Opc == ISD::SRL
3052 // (x & 0xff00) >> 8
3053 // (x & 0xff000000) >> 8
3054 if (Num != 1 && Num != 3)
3055 return false;
3056 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3057 if (!C || C->getZExtValue() != 8)
3058 return false;
3059 }
3060
3061 if (Parts[Num])
3062 return false;
3063
3064 Parts[Num] = N0.getOperand(0).getNode();
3065 return true;
3066}
3067
3068/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3069/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3070/// => (rotl (bswap x), 16)
3071SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3072 if (!LegalOperations)
3073 return SDValue();
3074
3075 EVT VT = N->getValueType(0);
3076 if (VT != MVT::i32)
3077 return SDValue();
3078 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3079 return SDValue();
3080
3081 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3082 // Look for either
3083 // (or (or (and), (and)), (or (and), (and)))
3084 // (or (or (or (and), (and)), (and)), (and))
3085 if (N0.getOpcode() != ISD::OR)
3086 return SDValue();
3087 SDValue N00 = N0.getOperand(0);
3088 SDValue N01 = N0.getOperand(1);
3089
Evan Cheng9a65a012012-12-13 01:34:32 +00003090 if (N1.getOpcode() == ISD::OR &&
3091 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng9568e5c2011-06-21 06:01:08 +00003092 // (or (or (and), (and)), (or (and), (and)))
3093 SDValue N000 = N00.getOperand(0);
3094 if (!isBSwapHWordElement(N000, Parts))
3095 return SDValue();
3096
3097 SDValue N001 = N00.getOperand(1);
3098 if (!isBSwapHWordElement(N001, Parts))
3099 return SDValue();
3100 SDValue N010 = N01.getOperand(0);
3101 if (!isBSwapHWordElement(N010, Parts))
3102 return SDValue();
3103 SDValue N011 = N01.getOperand(1);
3104 if (!isBSwapHWordElement(N011, Parts))
3105 return SDValue();
3106 } else {
3107 // (or (or (or (and), (and)), (and)), (and))
3108 if (!isBSwapHWordElement(N1, Parts))
3109 return SDValue();
3110 if (!isBSwapHWordElement(N01, Parts))
3111 return SDValue();
3112 if (N00.getOpcode() != ISD::OR)
3113 return SDValue();
3114 SDValue N000 = N00.getOperand(0);
3115 if (!isBSwapHWordElement(N000, Parts))
3116 return SDValue();
3117 SDValue N001 = N00.getOperand(1);
3118 if (!isBSwapHWordElement(N001, Parts))
3119 return SDValue();
3120 }
3121
3122 // Make sure the parts are all coming from the same node.
3123 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3124 return SDValue();
3125
Andrew Trickac6d9be2013-05-25 02:42:55 +00003126 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng9568e5c2011-06-21 06:01:08 +00003127 SDValue(Parts[0],0));
3128
Kay Tiong Khoo670711e2013-09-23 18:43:51 +00003129 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng9568e5c2011-06-21 06:01:08 +00003130 // do (x << 16) | (x >> 16).
3131 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3132 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickac6d9be2013-05-25 02:42:55 +00003133 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper0eb5dad2012-09-29 07:18:53 +00003134 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickac6d9be2013-05-25 02:42:55 +00003135 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3136 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3137 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3138 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng9568e5c2011-06-21 06:01:08 +00003139}
3140
Dan Gohman475871a2008-07-27 21:46:04 +00003141SDValue DAGCombiner::visitOR(SDNode *N) {
3142 SDValue N0 = N->getOperand(0);
3143 SDValue N1 = N->getOperand(1);
3144 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman646d7e22005-09-02 21:18:40 +00003145 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3146 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00003147 EVT VT = N1.getValueType();
Scott Michelfdc40a02009-02-17 22:15:04 +00003148
Dan Gohman7f321562007-06-25 16:23:39 +00003149 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00003150 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003151 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00003152 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper9472b4f2012-12-08 22:49:19 +00003153
3154 // fold (or x, 0) -> x, vector edition
3155 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3156 return N1;
3157 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3158 return N0;
3159
3160 // fold (or x, -1) -> -1, vector edition
3161 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3162 return N0;
3163 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3164 return N1;
Dan Gohman05d92fe2007-07-13 20:03:40 +00003165 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003166
Dan Gohman613e0d82007-07-03 14:03:57 +00003167 // fold (or x, undef) -> -1
Bob Wilson86749492010-06-28 23:40:25 +00003168 if (!LegalOperations &&
3169 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman93e0ed32009-12-03 07:11:29 +00003170 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3171 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3172 }
Nate Begeman1d4d4142005-09-01 00:19:25 +00003173 // fold (or c1, c2) -> c1|c2
Nate Begeman646d7e22005-09-02 21:18:40 +00003174 if (N0C && N1C)
Bill Wendlingf3cbca22008-09-24 10:25:02 +00003175 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman99801192005-09-07 23:25:52 +00003176 // canonicalize constant to RHS
Nate Begemana0e221d2005-10-18 00:28:13 +00003177 if (N0C && !N1C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00003178 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00003179 // fold (or x, 0) -> x
Nate Begeman646d7e22005-09-02 21:18:40 +00003180 if (N1C && N1C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00003181 return N0;
Nate Begeman1d4d4142005-09-01 00:19:25 +00003182 // fold (or x, -1) -> -1
Nate Begeman646d7e22005-09-02 21:18:40 +00003183 if (N1C && N1C->isAllOnesValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00003184 return N1;
Sylvestre Ledru94c22712012-09-27 10:14:43 +00003185 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman2e68b6f2008-02-25 21:11:39 +00003186 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begeman83e75ec2005-09-06 04:43:02 +00003187 return N1;
Evan Cheng9568e5c2011-06-21 06:01:08 +00003188
3189 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3190 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3191 if (BSwap.getNode() != 0)
3192 return BSwap;
3193 BSwap = MatchBSwapHWordLow(N, N0, N1);
3194 if (BSwap.getNode() != 0)
3195 return BSwap;
3196
Nate Begemancd4d58c2006-02-03 06:46:56 +00003197 // reassociate or
Andrew Trickac6d9be2013-05-25 02:42:55 +00003198 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Gabor Greifba36cb52008-08-28 21:40:38 +00003199 if (ROR.getNode() != 0)
Nate Begemancd4d58c2006-02-03 06:46:56 +00003200 return ROR;
3201 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru94c22712012-09-27 10:14:43 +00003202 // iff (c1 & c2) == 0.
Gabor Greifba36cb52008-08-28 21:40:38 +00003203 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattner731d3482005-10-27 05:06:38 +00003204 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattner731d3482005-10-27 05:06:38 +00003205 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Bill Wendling32f9eb22010-03-03 01:58:01 +00003206 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
Andrew Trickac6d9be2013-05-25 02:42:55 +00003207 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3208 DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendling7d9f2b92010-03-03 00:35:56 +00003209 N0.getOperand(0), N1),
3210 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
Nate Begeman223df222005-09-08 20:18:10 +00003211 }
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003212 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3213 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3214 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3215 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelfdc40a02009-02-17 22:15:04 +00003216
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003217 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands83ec4b62008-06-06 12:08:01 +00003218 LL.getValueType().isInteger()) {
Bill Wendling09025642009-01-30 20:59:34 +00003219 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3220 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelfdc40a02009-02-17 22:15:04 +00003221 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003222 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00003223 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendling09025642009-01-30 20:59:34 +00003224 LR.getValueType(), LL, RL);
Gabor Greifba36cb52008-08-28 21:40:38 +00003225 AddToWorkList(ORNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00003226 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003227 }
Bill Wendling09025642009-01-30 20:59:34 +00003228 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3229 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelfdc40a02009-02-17 22:15:04 +00003230 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003231 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00003232 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendling09025642009-01-30 20:59:34 +00003233 LR.getValueType(), LL, RL);
Gabor Greifba36cb52008-08-28 21:40:38 +00003234 AddToWorkList(ANDNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00003235 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003236 }
3237 }
3238 // canonicalize equivalent to ll == rl
3239 if (LL == RR && LR == RL) {
3240 Op1 = ISD::getSetCCSwappedOperands(Op1);
3241 std::swap(RL, RR);
3242 }
3243 if (LL == RL && LR == RR) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003244 bool isInteger = LL.getValueType().isInteger();
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003245 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner6e1c6232008-10-28 07:11:07 +00003246 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundfdbeb052012-12-19 10:19:55 +00003247 (!LegalOperations ||
Owen Anderson39125d92013-02-14 09:07:33 +00003248 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3249 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault225ed702013-05-18 00:21:46 +00003250 getSetCCResultType(N0.getValueType())))))
Andrew Trickac6d9be2013-05-25 02:42:55 +00003251 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling09025642009-01-30 20:59:34 +00003252 LL, LR, Result);
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003253 }
3254 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003255
Bill Wendling09025642009-01-30 20:59:34 +00003256 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner35e5c142006-05-05 05:51:50 +00003257 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003258 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00003259 if (Tmp.getNode()) return Tmp;
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003260 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003261
Bill Wendling09025642009-01-30 20:59:34 +00003262 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner1ec72732006-09-14 21:11:37 +00003263 if (N0.getOpcode() == ISD::AND &&
3264 N1.getOpcode() == ISD::AND &&
3265 N0.getOperand(1).getOpcode() == ISD::Constant &&
3266 N1.getOperand(1).getOpcode() == ISD::Constant &&
3267 // Don't increase # computations.
Gabor Greifba36cb52008-08-28 21:40:38 +00003268 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner1ec72732006-09-14 21:11:37 +00003269 // We can only do this xform if we know that bits from X that are set in C2
3270 // but not in C1 are already zero. Likewise for Y.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00003271 const APInt &LHSMask =
3272 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3273 const APInt &RHSMask =
3274 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelfdc40a02009-02-17 22:15:04 +00003275
Dan Gohmanea859be2007-06-22 14:59:07 +00003276 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3277 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00003278 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendling09025642009-01-30 20:59:34 +00003279 N0.getOperand(0), N1.getOperand(0));
Andrew Trickac6d9be2013-05-25 02:42:55 +00003280 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendling09025642009-01-30 20:59:34 +00003281 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner1ec72732006-09-14 21:11:37 +00003282 }
3283 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003284
Chris Lattner516b9622006-09-14 20:50:57 +00003285 // See if this is some rotate idiom.
Andrew Trickac6d9be2013-05-25 02:42:55 +00003286 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman475871a2008-07-27 21:46:04 +00003287 return SDValue(Rot, 0);
Chris Lattner35e5c142006-05-05 05:51:50 +00003288
Dan Gohman4e39e9d2010-06-24 14:30:44 +00003289 // Simplify the operands using demanded-bits information.
3290 if (!VT.isVector() &&
3291 SimplifyDemandedBits(SDValue(N, 0)))
3292 return SDValue(N, 0);
3293
Evan Chengb3a3d5e2010-04-28 07:10:39 +00003294 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00003295}
3296
Chris Lattner516b9622006-09-14 20:50:57 +00003297/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman475871a2008-07-27 21:46:04 +00003298static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner516b9622006-09-14 20:50:57 +00003299 if (Op.getOpcode() == ISD::AND) {
Reid Spencer3ed469c2006-11-02 20:25:50 +00003300 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner516b9622006-09-14 20:50:57 +00003301 Mask = Op.getOperand(1);
3302 Op = Op.getOperand(0);
3303 } else {
3304 return false;
3305 }
3306 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003307
Chris Lattner516b9622006-09-14 20:50:57 +00003308 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3309 Shift = Op;
3310 return true;
3311 }
Bill Wendling09025642009-01-30 20:59:34 +00003312
Scott Michelfdc40a02009-02-17 22:15:04 +00003313 return false;
Chris Lattner516b9622006-09-14 20:50:57 +00003314}
3315
Chris Lattner516b9622006-09-14 20:50:57 +00003316// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3317// idioms for rotate, and if the target supports rotation instructions, generate
3318// a rot[lr].
Andrew Trickac6d9be2013-05-25 02:42:55 +00003319SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sandsd4b9c172008-06-13 19:07:40 +00003320 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Andersone50ed302009-08-10 22:56:29 +00003321 EVT VT = LHS.getValueType();
Chris Lattner516b9622006-09-14 20:50:57 +00003322 if (!TLI.isTypeLegal(VT)) return 0;
3323
3324 // The target must have at least one rotate flavor.
Dan Gohmanf560ffa2009-01-28 17:46:25 +00003325 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3326 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Chris Lattner516b9622006-09-14 20:50:57 +00003327 if (!HasROTL && !HasROTR) return 0;
Duncan Sandsd4b9c172008-06-13 19:07:40 +00003328
Chris Lattner516b9622006-09-14 20:50:57 +00003329 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman475871a2008-07-27 21:46:04 +00003330 SDValue LHSShift; // The shift.
3331 SDValue LHSMask; // AND value if any.
Chris Lattner516b9622006-09-14 20:50:57 +00003332 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3333 return 0; // Not part of a rotate.
3334
Dan Gohman475871a2008-07-27 21:46:04 +00003335 SDValue RHSShift; // The shift.
3336 SDValue RHSMask; // AND value if any.
Chris Lattner516b9622006-09-14 20:50:57 +00003337 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3338 return 0; // Not part of a rotate.
Scott Michelfdc40a02009-02-17 22:15:04 +00003339
Chris Lattner516b9622006-09-14 20:50:57 +00003340 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3341 return 0; // Not shifting the same value.
3342
3343 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3344 return 0; // Shifts must disagree.
Scott Michelfdc40a02009-02-17 22:15:04 +00003345
Chris Lattner516b9622006-09-14 20:50:57 +00003346 // Canonicalize shl to left side in a shl/srl pair.
3347 if (RHSShift.getOpcode() == ISD::SHL) {
3348 std::swap(LHS, RHS);
3349 std::swap(LHSShift, RHSShift);
3350 std::swap(LHSMask , RHSMask );
3351 }
3352
Duncan Sands83ec4b62008-06-06 12:08:01 +00003353 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman475871a2008-07-27 21:46:04 +00003354 SDValue LHSShiftArg = LHSShift.getOperand(0);
3355 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nackeceb3b462013-09-19 23:00:28 +00003356 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman475871a2008-07-27 21:46:04 +00003357 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner516b9622006-09-14 20:50:57 +00003358
3359 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3360 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michelc9dc1142007-04-02 21:36:32 +00003361 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3362 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003363 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3364 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner516b9622006-09-14 20:50:57 +00003365 if ((LShVal + RShVal) != OpSizeInBits)
3366 return 0;
3367
Craig Topper32b73432012-09-29 06:54:22 +00003368 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3369 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelfdc40a02009-02-17 22:15:04 +00003370
Chris Lattner516b9622006-09-14 20:50:57 +00003371 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greifba36cb52008-08-28 21:40:38 +00003372 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohman220a8232008-03-03 23:51:38 +00003373 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelfdc40a02009-02-17 22:15:04 +00003374
Gabor Greifba36cb52008-08-28 21:40:38 +00003375 if (LHSMask.getNode()) {
Dan Gohman220a8232008-03-03 23:51:38 +00003376 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3377 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner516b9622006-09-14 20:50:57 +00003378 }
Gabor Greifba36cb52008-08-28 21:40:38 +00003379 if (RHSMask.getNode()) {
Dan Gohman220a8232008-03-03 23:51:38 +00003380 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3381 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner516b9622006-09-14 20:50:57 +00003382 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003383
Bill Wendling317bd702009-01-30 21:14:50 +00003384 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner516b9622006-09-14 20:50:57 +00003385 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003386
Gabor Greifba36cb52008-08-28 21:40:38 +00003387 return Rot.getNode();
Chris Lattner516b9622006-09-14 20:50:57 +00003388 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003389
Chris Lattner516b9622006-09-14 20:50:57 +00003390 // If there is a mask here, and we have a variable shift, we can't be sure
3391 // that we're masking out the right stuff.
Gabor Greifba36cb52008-08-28 21:40:38 +00003392 if (LHSMask.getNode() || RHSMask.getNode())
Chris Lattner516b9622006-09-14 20:50:57 +00003393 return 0;
Scott Michelfdc40a02009-02-17 22:15:04 +00003394
Benjamin Kramercd216b22013-09-24 14:21:28 +00003395 // If the shift amount is sign/zext/any-extended just peel it off.
3396 SDValue LExtOp0 = LHSShiftAmt;
3397 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper0eb5dad2012-09-29 07:18:53 +00003398 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3399 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3400 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3401 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3402 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3403 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3404 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3405 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramercd216b22013-09-24 14:21:28 +00003406 LExtOp0 = LHSShiftAmt.getOperand(0);
3407 RExtOp0 = RHSShiftAmt.getOperand(0);
3408 }
3409
3410 if (RExtOp0.getOpcode() == ISD::SUB && RExtOp0.getOperand(1) == LExtOp0) {
3411 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3412 // (rotl x, y)
3413 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3414 // (rotr x, (sub 32, y))
3415 if (ConstantSDNode *SUBC =
3416 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
3417 if (SUBC->getAPIntValue() == OpSizeInBits) {
3418 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
3419 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3420 } else if (LHSShiftArg.getOpcode() == ISD::ZERO_EXTEND ||
Kai Nackeceb3b462013-09-19 23:00:28 +00003421 LHSShiftArg.getOpcode() == ISD::ANY_EXTEND) {
Benjamin Kramercd216b22013-09-24 14:21:28 +00003422 // fold (or (shl (*ext x), (*ext y)),
3423 // (srl (*ext x), (*ext (sub 32, y)))) ->
3424 // (*ext (rotl x, y))
3425 // fold (or (shl (*ext x), (*ext y)),
3426 // (srl (*ext x), (*ext (sub 32, y)))) ->
3427 // (*ext (rotr x, (sub 32, y)))
3428 SDValue LArgExtOp0 = LHSShiftArg.getOperand(0);
3429 EVT LArgVT = LArgExtOp0.getValueType();
Jin-Gu Kangb70a05a2013-10-03 15:58:48 +00003430 bool HasROTRWithLArg = TLI.isOperationLegalOrCustom(ISD::ROTR, LArgVT);
3431 bool HasROTLWithLArg = TLI.isOperationLegalOrCustom(ISD::ROTL, LArgVT);
3432 if (HasROTRWithLArg || HasROTLWithLArg) {
3433 if (LArgVT.getSizeInBits() == SUBC->getAPIntValue()) {
3434 SDValue V =
3435 DAG.getNode(HasROTLWithLArg ? ISD::ROTL : ISD::ROTR, DL, LArgVT,
3436 LArgExtOp0, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3437 return DAG.getNode(LHSShiftArg.getOpcode(), DL, VT, V).getNode();
Jack Carteradbd3ae2013-10-17 01:34:33 +00003438 }
3439 }
David Blaikiec2286722013-09-20 00:33:11 +00003440 }
Benjamin Kramercd216b22013-09-24 14:21:28 +00003441 }
3442 } else if (LExtOp0.getOpcode() == ISD::SUB &&
3443 RExtOp0 == LExtOp0.getOperand(1)) {
3444 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3445 // (rotr x, y)
3446 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3447 // (rotl x, (sub 32, y))
3448 if (ConstantSDNode *SUBC =
3449 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
3450 if (SUBC->getAPIntValue() == OpSizeInBits) {
3451 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg,
3452 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3453 } else if (RHSShiftArg.getOpcode() == ISD::ZERO_EXTEND ||
Kai Nackeceb3b462013-09-19 23:00:28 +00003454 RHSShiftArg.getOpcode() == ISD::ANY_EXTEND) {
Benjamin Kramercd216b22013-09-24 14:21:28 +00003455 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3456 // (srl (*ext x), (*ext y))) ->
3457 // (*ext (rotl x, y))
3458 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3459 // (srl (*ext x), (*ext y))) ->
3460 // (*ext (rotr x, (sub 32, y)))
3461 SDValue RArgExtOp0 = RHSShiftArg.getOperand(0);
3462 EVT RArgVT = RArgExtOp0.getValueType();
Jin-Gu Kangb70a05a2013-10-03 15:58:48 +00003463 bool HasROTRWithRArg = TLI.isOperationLegalOrCustom(ISD::ROTR, RArgVT);
3464 bool HasROTLWithRArg = TLI.isOperationLegalOrCustom(ISD::ROTL, RArgVT);
3465 if (HasROTRWithRArg || HasROTLWithRArg) {
3466 if (RArgVT.getSizeInBits() == SUBC->getAPIntValue()) {
3467 SDValue V =
3468 DAG.getNode(HasROTRWithRArg ? ISD::ROTR : ISD::ROTL, DL, RArgVT,
3469 RArgExtOp0, HasROTR ? RHSShiftAmt : LHSShiftAmt);
3470 return DAG.getNode(RHSShiftArg.getOpcode(), DL, VT, V).getNode();
3471 }
Kai Nackeceb3b462013-09-19 23:00:28 +00003472 }
David Blaikiec2286722013-09-20 00:33:11 +00003473 }
Chris Lattner516b9622006-09-14 20:50:57 +00003474 }
3475 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003476
Chris Lattner516b9622006-09-14 20:50:57 +00003477 return 0;
3478}
3479
Dan Gohman475871a2008-07-27 21:46:04 +00003480SDValue DAGCombiner::visitXOR(SDNode *N) {
3481 SDValue N0 = N->getOperand(0);
3482 SDValue N1 = N->getOperand(1);
3483 SDValue LHS, RHS, CC;
Nate Begeman646d7e22005-09-02 21:18:40 +00003484 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3485 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00003486 EVT VT = N0.getValueType();
Scott Michelfdc40a02009-02-17 22:15:04 +00003487
Dan Gohman7f321562007-06-25 16:23:39 +00003488 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00003489 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003490 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00003491 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper9472b4f2012-12-08 22:49:19 +00003492
3493 // fold (xor x, 0) -> x, vector edition
3494 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3495 return N1;
3496 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3497 return N0;
Dan Gohman05d92fe2007-07-13 20:03:40 +00003498 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003499
Evan Cheng26471c42008-03-25 20:08:07 +00003500 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3501 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3502 return DAG.getConstant(0, VT);
Dan Gohman613e0d82007-07-03 14:03:57 +00003503 // fold (xor x, undef) -> undef
Dan Gohman70fb1ae2007-07-10 15:19:29 +00003504 if (N0.getOpcode() == ISD::UNDEF)
3505 return N0;
3506 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman613e0d82007-07-03 14:03:57 +00003507 return N1;
Nate Begeman1d4d4142005-09-01 00:19:25 +00003508 // fold (xor c1, c2) -> c1^c2
Nate Begeman646d7e22005-09-02 21:18:40 +00003509 if (N0C && N1C)
Bill Wendlingf3cbca22008-09-24 10:25:02 +00003510 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman99801192005-09-07 23:25:52 +00003511 // canonicalize constant to RHS
Nate Begemana0e221d2005-10-18 00:28:13 +00003512 if (N0C && !N1C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00003513 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00003514 // fold (xor x, 0) -> x
Nate Begeman646d7e22005-09-02 21:18:40 +00003515 if (N1C && N1C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00003516 return N0;
Nate Begemancd4d58c2006-02-03 06:46:56 +00003517 // reassociate xor
Andrew Trickac6d9be2013-05-25 02:42:55 +00003518 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Gabor Greifba36cb52008-08-28 21:40:38 +00003519 if (RXOR.getNode() != 0)
Nate Begemancd4d58c2006-02-03 06:46:56 +00003520 return RXOR;
Bill Wendlingae89bb12008-11-11 08:25:46 +00003521
Nate Begeman1d4d4142005-09-01 00:19:25 +00003522 // fold !(x cc y) -> (x !cc y)
Dan Gohman002e5d02008-03-13 22:13:53 +00003523 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003524 bool isInt = LHS.getValueType().isInteger();
Nate Begeman646d7e22005-09-02 21:18:40 +00003525 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3526 isInt);
Bill Wendlingae89bb12008-11-11 08:25:46 +00003527
Patrik Hagglundfdbeb052012-12-19 10:19:55 +00003528 if (!LegalOperations ||
3529 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendlingae89bb12008-11-11 08:25:46 +00003530 switch (N0.getOpcode()) {
3531 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003532 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendlingae89bb12008-11-11 08:25:46 +00003533 case ISD::SETCC:
Andrew Trickac6d9be2013-05-25 02:42:55 +00003534 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendlingae89bb12008-11-11 08:25:46 +00003535 case ISD::SELECT_CC:
Andrew Trickac6d9be2013-05-25 02:42:55 +00003536 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendlingae89bb12008-11-11 08:25:46 +00003537 N0.getOperand(3), NotCC);
3538 }
3539 }
Nate Begeman1d4d4142005-09-01 00:19:25 +00003540 }
Bill Wendlingae89bb12008-11-11 08:25:46 +00003541
Chris Lattner61c5ff42007-09-10 21:39:07 +00003542 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohman002e5d02008-03-13 22:13:53 +00003543 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greif12632d22008-08-30 19:29:20 +00003544 N0.getNode()->hasOneUse() &&
3545 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman475871a2008-07-27 21:46:04 +00003546 SDValue V = N0.getOperand(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00003547 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands272dce02007-10-10 09:54:50 +00003548 DAG.getConstant(1, V.getValueType()));
Gabor Greifba36cb52008-08-28 21:40:38 +00003549 AddToWorkList(V.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00003550 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner61c5ff42007-09-10 21:39:07 +00003551 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003552
Sylvestre Ledru94c22712012-09-27 10:14:43 +00003553 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson825b72b2009-08-11 20:47:22 +00003554 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman99801192005-09-07 23:25:52 +00003555 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman475871a2008-07-27 21:46:04 +00003556 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman99801192005-09-07 23:25:52 +00003557 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3558 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickac6d9be2013-05-25 02:42:55 +00003559 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3560 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greifba36cb52008-08-28 21:40:38 +00003561 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00003562 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman1d4d4142005-09-01 00:19:25 +00003563 }
3564 }
Sylvestre Ledru94c22712012-09-27 10:14:43 +00003565 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelfdc40a02009-02-17 22:15:04 +00003566 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman99801192005-09-07 23:25:52 +00003567 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman475871a2008-07-27 21:46:04 +00003568 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman99801192005-09-07 23:25:52 +00003569 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3570 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickac6d9be2013-05-25 02:42:55 +00003571 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3572 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greifba36cb52008-08-28 21:40:38 +00003573 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00003574 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman1d4d4142005-09-01 00:19:25 +00003575 }
3576 }
David Majnemer363160a2013-05-08 06:44:42 +00003577 // fold (xor (and x, y), y) -> (and (not x), y)
3578 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerd5ae5b02013-11-17 10:40:03 +00003579 N0->getOperand(1) == N1) {
David Majnemer363160a2013-05-08 06:44:42 +00003580 SDValue X = N0->getOperand(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00003581 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
David Majnemer363160a2013-05-08 06:44:42 +00003582 AddToWorkList(NotX.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00003583 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer363160a2013-05-08 06:44:42 +00003584 }
Bill Wendling317bd702009-01-30 21:14:50 +00003585 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman223df222005-09-08 20:18:10 +00003586 if (N1C && N0.getOpcode() == ISD::XOR) {
3587 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3588 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3589 if (N00C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00003590 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling317bd702009-01-30 21:14:50 +00003591 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohman002e5d02008-03-13 22:13:53 +00003592 N00C->getAPIntValue(), VT));
Nate Begeman223df222005-09-08 20:18:10 +00003593 if (N01C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00003594 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling317bd702009-01-30 21:14:50 +00003595 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohman002e5d02008-03-13 22:13:53 +00003596 N01C->getAPIntValue(), VT));
Nate Begeman223df222005-09-08 20:18:10 +00003597 }
3598 // fold (xor x, x) -> 0
Eric Christopher7bccf6a2011-02-16 04:50:12 +00003599 if (N0 == N1)
Hal Finkelbd6f1f62013-07-09 17:02:45 +00003600 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelfdc40a02009-02-17 22:15:04 +00003601
Chris Lattner35e5c142006-05-05 05:51:50 +00003602 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3603 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003604 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00003605 if (Tmp.getNode()) return Tmp;
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003606 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003607
Chris Lattner3e104b12006-04-08 04:15:24 +00003608 // Simplify the expression using non-local knowledge.
Duncan Sands83ec4b62008-06-06 12:08:01 +00003609 if (!VT.isVector() &&
Dan Gohman475871a2008-07-27 21:46:04 +00003610 SimplifyDemandedBits(SDValue(N, 0)))
3611 return SDValue(N, 0);
Scott Michelfdc40a02009-02-17 22:15:04 +00003612
Evan Chengb3a3d5e2010-04-28 07:10:39 +00003613 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00003614}
3615
Chris Lattnere70da202007-12-06 07:33:36 +00003616/// visitShiftByConstant - Handle transforms common to the three shifts, when
3617/// the shift amount is a constant.
Dan Gohman475871a2008-07-27 21:46:04 +00003618SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
Gabor Greifba36cb52008-08-28 21:40:38 +00003619 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman475871a2008-07-27 21:46:04 +00003620 if (!LHS->hasOneUse()) return SDValue();
Scott Michelfdc40a02009-02-17 22:15:04 +00003621
Chris Lattnere70da202007-12-06 07:33:36 +00003622 // We want to pull some binops through shifts, so that we have (and (shift))
3623 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3624 // thing happens with address calculations, so it's important to canonicalize
3625 // it.
3626 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelfdc40a02009-02-17 22:15:04 +00003627
Chris Lattnere70da202007-12-06 07:33:36 +00003628 switch (LHS->getOpcode()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003629 default: return SDValue();
Chris Lattnere70da202007-12-06 07:33:36 +00003630 case ISD::OR:
3631 case ISD::XOR:
3632 HighBitSet = false; // We can only transform sra if the high bit is clear.
3633 break;
3634 case ISD::AND:
3635 HighBitSet = true; // We can only transform sra if the high bit is set.
3636 break;
3637 case ISD::ADD:
Scott Michelfdc40a02009-02-17 22:15:04 +00003638 if (N->getOpcode() != ISD::SHL)
Dan Gohman475871a2008-07-27 21:46:04 +00003639 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattnere70da202007-12-06 07:33:36 +00003640 HighBitSet = false; // We can only transform sra if the high bit is clear.
3641 break;
3642 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003643
Chris Lattnere70da202007-12-06 07:33:36 +00003644 // We require the RHS of the binop to be a constant as well.
3645 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Dan Gohman475871a2008-07-27 21:46:04 +00003646 if (!BinOpCst) return SDValue();
Bill Wendling88103372009-01-30 21:37:17 +00003647
3648 // FIXME: disable this unless the input to the binop is a shift by a constant.
3649 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnerd3fd6d22007-12-06 07:47:55 +00003650 //
Bill Wendling88103372009-01-30 21:37:17 +00003651 // void foo(int *X, int i) { X[i & 1235] = 1; }
3652 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greifba36cb52008-08-28 21:40:38 +00003653 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelfdc40a02009-02-17 22:15:04 +00003654 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnerd3fd6d22007-12-06 07:47:55 +00003655 BinOpLHSVal->getOpcode() != ISD::SRA &&
3656 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3657 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman475871a2008-07-27 21:46:04 +00003658 return SDValue();
Scott Michelfdc40a02009-02-17 22:15:04 +00003659
Owen Andersone50ed302009-08-10 22:56:29 +00003660 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00003661
Bill Wendling88103372009-01-30 21:37:17 +00003662 // If this is a signed shift right, and the high bit is modified by the
3663 // logical operation, do not perform the transformation. The highBitSet
3664 // boolean indicates the value of the high bit of the constant which would
3665 // cause it to be modified for this operation.
Chris Lattnere70da202007-12-06 07:33:36 +00003666 if (N->getOpcode() == ISD::SRA) {
Dan Gohman220a8232008-03-03 23:51:38 +00003667 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3668 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman475871a2008-07-27 21:46:04 +00003669 return SDValue();
Chris Lattnere70da202007-12-06 07:33:36 +00003670 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003671
Chris Lattnere70da202007-12-06 07:33:36 +00003672 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickac6d9be2013-05-25 02:42:55 +00003673 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendling88103372009-01-30 21:37:17 +00003674 N->getValueType(0),
3675 LHS->getOperand(1), N->getOperand(1));
Chris Lattnere70da202007-12-06 07:33:36 +00003676
3677 // Create the new shift.
Eric Christopher503a64d2010-12-09 04:48:06 +00003678 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickac6d9be2013-05-25 02:42:55 +00003679 SDLoc(LHS->getOperand(0)),
Bill Wendling88103372009-01-30 21:37:17 +00003680 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattnere70da202007-12-06 07:33:36 +00003681
3682 // Create the new binop.
Andrew Trickac6d9be2013-05-25 02:42:55 +00003683 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattnere70da202007-12-06 07:33:36 +00003684}
3685
Dan Gohman475871a2008-07-27 21:46:04 +00003686SDValue DAGCombiner::visitSHL(SDNode *N) {
3687 SDValue N0 = N->getOperand(0);
3688 SDValue N1 = N->getOperand(1);
Nate Begeman646d7e22005-09-02 21:18:40 +00003689 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3690 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00003691 EVT VT = N0.getValueType();
Dan Gohman87862e72009-12-11 21:31:27 +00003692 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelfdc40a02009-02-17 22:15:04 +00003693
Daniel Sanders028e4d22013-11-11 17:23:41 +00003694 // fold vector ops
3695 if (VT.isVector()) {
3696 SDValue FoldedVOp = SimplifyVBinOp(N);
3697 if (FoldedVOp.getNode()) return FoldedVOp;
3698 }
3699
Nate Begeman1d4d4142005-09-01 00:19:25 +00003700 // fold (shl c1, c2) -> c1<<c2
Nate Begeman646d7e22005-09-02 21:18:40 +00003701 if (N0C && N1C)
Bill Wendlingf3cbca22008-09-24 10:25:02 +00003702 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman1d4d4142005-09-01 00:19:25 +00003703 // fold (shl 0, x) -> 0
Nate Begeman646d7e22005-09-02 21:18:40 +00003704 if (N0C && N0C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00003705 return N0;
Nate Begeman1d4d4142005-09-01 00:19:25 +00003706 // fold (shl x, c >= size(x)) -> undef
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003707 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesene8d72302009-02-06 23:05:02 +00003708 return DAG.getUNDEF(VT);
Nate Begeman1d4d4142005-09-01 00:19:25 +00003709 // fold (shl x, 0) -> x
Nate Begeman646d7e22005-09-02 21:18:40 +00003710 if (N1C && N1C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00003711 return N0;
Chad Rosier92bcd962011-06-14 22:29:10 +00003712 // fold (shl undef, x) -> 0
3713 if (N0.getOpcode() == ISD::UNDEF)
3714 return DAG.getConstant(0, VT);
Nate Begeman1d4d4142005-09-01 00:19:25 +00003715 // if (shl x, c) is known to be zero, return 0
Dan Gohman475871a2008-07-27 21:46:04 +00003716 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman87862e72009-12-11 21:31:27 +00003717 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begeman83e75ec2005-09-06 04:43:02 +00003718 return DAG.getConstant(0, VT);
Duncan Sandsb0d5cdd2009-02-01 18:06:53 +00003719 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengeb9f8922008-08-30 02:03:58 +00003720 if (N1.getOpcode() == ISD::TRUNCATE &&
Evan Cheng242ebd12008-09-22 18:19:24 +00003721 N1.getOperand(0).getOpcode() == ISD::AND &&
3722 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
Evan Chengeb9f8922008-08-30 02:03:58 +00003723 SDValue N101 = N1.getOperand(0).getOperand(1);
Evan Cheng242ebd12008-09-22 18:19:24 +00003724 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
Owen Andersone50ed302009-08-10 22:56:29 +00003725 EVT TruncVT = N1.getValueType();
Evan Cheng242ebd12008-09-22 18:19:24 +00003726 SDValue N100 = N1.getOperand(0).getOperand(0);
Duncan Sandsb0d5cdd2009-02-01 18:06:53 +00003727 APInt TruncC = N101C->getAPIntValue();
Jay Foad40f8f622010-12-07 08:25:19 +00003728 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
Andrew Trickac6d9be2013-05-25 02:42:55 +00003729 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3730 DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
Bill Wendlingfc4b6772009-02-01 11:19:36 +00003731 DAG.getNode(ISD::TRUNCATE,
Andrew Trickac6d9be2013-05-25 02:42:55 +00003732 SDLoc(N),
Bill Wendlingfc4b6772009-02-01 11:19:36 +00003733 TruncVT, N100),
Dan Gohmance9bc122009-01-27 20:39:34 +00003734 DAG.getConstant(TruncC, TruncVT)));
Evan Chengeb9f8922008-08-30 02:03:58 +00003735 }
3736 }
3737
Dan Gohman475871a2008-07-27 21:46:04 +00003738 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3739 return SDValue(N, 0);
Bill Wendling88103372009-01-30 21:37:17 +00003740
3741 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Scott Michelfdc40a02009-02-17 22:15:04 +00003742 if (N1C && N0.getOpcode() == ISD::SHL &&
Nate Begeman1d4d4142005-09-01 00:19:25 +00003743 N0.getOperand(1).getOpcode() == ISD::Constant) {
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003744 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3745 uint64_t c2 = N1C->getZExtValue();
Dale Johannesenc72b18c2010-12-21 21:55:50 +00003746 if (c1 + c2 >= OpSizeInBits)
Nate Begeman83e75ec2005-09-06 04:43:02 +00003747 return DAG.getConstant(0, VT);
Andrew Trickac6d9be2013-05-25 02:42:55 +00003748 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
Nate Begeman83e75ec2005-09-06 04:43:02 +00003749 DAG.getConstant(c1 + c2, N1.getValueType()));
Nate Begeman1d4d4142005-09-01 00:19:25 +00003750 }
Dale Johannesenc72b18c2010-12-21 21:55:50 +00003751
3752 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3753 // For this to be valid, the second form must not preserve any of the bits
3754 // that are shifted out by the inner shift in the first form. This means
3755 // the outer shift size must be >= the number of bits added by the ext.
3756 // As a corollary, we don't care what kind of ext it is.
3757 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3758 N0.getOpcode() == ISD::ANY_EXTEND ||
3759 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3760 N0.getOperand(0).getOpcode() == ISD::SHL &&
3761 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Anderson95771af2011-02-25 21:41:48 +00003762 uint64_t c1 =
Dale Johannesenc72b18c2010-12-21 21:55:50 +00003763 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3764 uint64_t c2 = N1C->getZExtValue();
3765 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3766 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3767 if (c2 >= OpSizeInBits - InnerShiftSize) {
3768 if (c1 + c2 >= OpSizeInBits)
3769 return DAG.getConstant(0, VT);
Andrew Trickac6d9be2013-05-25 02:42:55 +00003770 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3771 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
Dale Johannesenc72b18c2010-12-21 21:55:50 +00003772 N0.getOperand(0)->getOperand(0)),
3773 DAG.getConstant(c1 + c2, N1.getValueType()));
3774 }
3775 }
3776
Andrea Di Biagioa9f113d2013-09-27 11:37:05 +00003777 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3778 // Only fold this if the inner zext has no other uses to avoid increasing
3779 // the total number of instructions.
3780 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3781 N0.getOperand(0).getOpcode() == ISD::SRL &&
3782 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3783 uint64_t c1 =
3784 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3785 if (c1 < VT.getSizeInBits()) {
3786 uint64_t c2 = N1C->getZExtValue();
3787 if (c1 == c2) {
3788 SDValue NewOp0 = N0.getOperand(0);
3789 EVT CountVT = NewOp0.getOperand(1).getValueType();
3790 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
3791 NewOp0, DAG.getConstant(c2, CountVT));
Andrea Di Biagio888cbad2013-10-17 11:02:58 +00003792 AddToWorkList(NewSHL.getNode());
Andrea Di Biagioa9f113d2013-09-27 11:37:05 +00003793 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
3794 }
3795 }
3796 }
3797
Eli Friedman2a6d9eb2011-06-09 22:14:44 +00003798 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3799 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruth62dfc512012-01-05 11:05:55 +00003800 // Only fold this if the inner shift has no other uses -- if it does, folding
3801 // this will increase the total number of instructions.
3802 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
Nate Begeman1d4d4142005-09-01 00:19:25 +00003803 N0.getOperand(1).getOpcode() == ISD::Constant) {
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003804 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
Evan Chengd101a722009-07-21 05:40:15 +00003805 if (c1 < VT.getSizeInBits()) {
3806 uint64_t c2 = N1C->getZExtValue();
Eli Friedman2a6d9eb2011-06-09 22:14:44 +00003807 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3808 VT.getSizeInBits() - c1);
3809 SDValue Shift;
3810 if (c2 > c1) {
3811 Mask = Mask.shl(c2-c1);
Andrew Trickac6d9be2013-05-25 02:42:55 +00003812 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
Eli Friedman2a6d9eb2011-06-09 22:14:44 +00003813 DAG.getConstant(c2-c1, N1.getValueType()));
3814 } else {
3815 Mask = Mask.lshr(c1-c2);
Andrew Trickac6d9be2013-05-25 02:42:55 +00003816 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
Eli Friedman2a6d9eb2011-06-09 22:14:44 +00003817 DAG.getConstant(c1-c2, N1.getValueType()));
3818 }
Andrew Trickac6d9be2013-05-25 02:42:55 +00003819 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
Eli Friedman2a6d9eb2011-06-09 22:14:44 +00003820 DAG.getConstant(Mask, VT));
Evan Chengd101a722009-07-21 05:40:15 +00003821 }
Nate Begeman1d4d4142005-09-01 00:19:25 +00003822 }
Bill Wendling88103372009-01-30 21:37:17 +00003823 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5cbd37e2009-08-06 09:18:59 +00003824 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3825 SDValue HiBitsMask =
3826 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3827 VT.getSizeInBits() -
3828 N1C->getZExtValue()),
3829 VT);
Andrew Trickac6d9be2013-05-25 02:42:55 +00003830 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5cbd37e2009-08-06 09:18:59 +00003831 HiBitsMask);
3832 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003833
Evan Chenge5b51ac2010-04-17 06:13:15 +00003834 if (N1C) {
3835 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3836 if (NewSHL.getNode())
3837 return NewSHL;
3838 }
3839
Evan Chengb3a3d5e2010-04-28 07:10:39 +00003840 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00003841}
3842
Dan Gohman475871a2008-07-27 21:46:04 +00003843SDValue DAGCombiner::visitSRA(SDNode *N) {
3844 SDValue N0 = N->getOperand(0);
3845 SDValue N1 = N->getOperand(1);
Nate Begeman646d7e22005-09-02 21:18:40 +00003846 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3847 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00003848 EVT VT = N0.getValueType();
Dan Gohman87862e72009-12-11 21:31:27 +00003849 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelfdc40a02009-02-17 22:15:04 +00003850
Daniel Sanders028e4d22013-11-11 17:23:41 +00003851 // fold vector ops
3852 if (VT.isVector()) {
3853 SDValue FoldedVOp = SimplifyVBinOp(N);
3854 if (FoldedVOp.getNode()) return FoldedVOp;
3855 }
3856
Bill Wendling88103372009-01-30 21:37:17 +00003857 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman646d7e22005-09-02 21:18:40 +00003858 if (N0C && N1C)
Bill Wendlingf3cbca22008-09-24 10:25:02 +00003859 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman1d4d4142005-09-01 00:19:25 +00003860 // fold (sra 0, x) -> 0
Nate Begeman646d7e22005-09-02 21:18:40 +00003861 if (N0C && N0C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00003862 return N0;
Nate Begeman1d4d4142005-09-01 00:19:25 +00003863 // fold (sra -1, x) -> -1
Nate Begeman646d7e22005-09-02 21:18:40 +00003864 if (N0C && N0C->isAllOnesValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00003865 return N0;
Bill Wendling88103372009-01-30 21:37:17 +00003866 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman87862e72009-12-11 21:31:27 +00003867 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesene8d72302009-02-06 23:05:02 +00003868 return DAG.getUNDEF(VT);
Nate Begeman1d4d4142005-09-01 00:19:25 +00003869 // fold (sra x, 0) -> x
Nate Begeman646d7e22005-09-02 21:18:40 +00003870 if (N1C && N1C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00003871 return N0;
Nate Begemanfb7217b2006-02-17 19:54:08 +00003872 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3873 // sext_inreg.
3874 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman87862e72009-12-11 21:31:27 +00003875 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohmand1996362010-01-09 02:13:55 +00003876 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3877 if (VT.isVector())
3878 ExtVT = EVT::getVectorVT(*DAG.getContext(),
3879 ExtVT, VT.getVectorNumElements());
3880 if ((!LegalOperations ||
3881 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00003882 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohmand1996362010-01-09 02:13:55 +00003883 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb7217b2006-02-17 19:54:08 +00003884 }
Duncan Sandsd4b9c172008-06-13 19:07:40 +00003885
Bill Wendling88103372009-01-30 21:37:17 +00003886 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner71d9ebc2006-02-28 06:23:04 +00003887 if (N1C && N0.getOpcode() == ISD::SRA) {
3888 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003889 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Dan Gohman87862e72009-12-11 21:31:27 +00003890 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
Andrew Trickac6d9be2013-05-25 02:42:55 +00003891 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner71d9ebc2006-02-28 06:23:04 +00003892 DAG.getConstant(Sum, N1C->getValueType(0)));
3893 }
3894 }
Christopher Lamb15cbde32008-03-19 08:30:06 +00003895
Bill Wendling88103372009-01-30 21:37:17 +00003896 // fold (sra (shl X, m), (sub result_size, n))
3897 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelfdc40a02009-02-17 22:15:04 +00003898 // result_size - n != m.
3899 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lambb9b04282008-03-20 04:31:39 +00003900 // code.
Christopher Lamb15cbde32008-03-19 08:30:06 +00003901 if (N0.getOpcode() == ISD::SHL) {
3902 // Get the two constanst of the shifts, CN0 = m, CN = n.
3903 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3904 if (N01C && N1C) {
Christopher Lambb9b04282008-03-20 04:31:39 +00003905 // Determine what the truncate's result bitsize and type would be.
Owen Andersone50ed302009-08-10 22:56:29 +00003906 EVT TruncVT =
Eric Christopher503a64d2010-12-09 04:48:06 +00003907 EVT::getIntegerVT(*DAG.getContext(),
3908 OpSizeInBits - N1C->getZExtValue());
Christopher Lambb9b04282008-03-20 04:31:39 +00003909 // Determine the residual right-shift amount.
Torok Edwin6bb49582009-05-23 17:29:48 +00003910 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sandsd4b9c172008-06-13 19:07:40 +00003911
Scott Michelfdc40a02009-02-17 22:15:04 +00003912 // If the shift is not a no-op (in which case this should be just a sign
3913 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohmanf451cb82010-02-10 16:03:48 +00003914 // on that type, and the truncate to that type is both legal and free,
Christopher Lambb9b04282008-03-20 04:31:39 +00003915 // perform the transform.
Torok Edwin6bb49582009-05-23 17:29:48 +00003916 if ((ShiftAmt > 0) &&
Dan Gohmanf560ffa2009-01-28 17:46:25 +00003917 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3918 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng260e07e2008-03-20 02:18:41 +00003919 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lambb9b04282008-03-20 04:31:39 +00003920
Owen Anderson95771af2011-02-25 21:41:48 +00003921 SDValue Amt = DAG.getConstant(ShiftAmt,
3922 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickac6d9be2013-05-25 02:42:55 +00003923 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendling88103372009-01-30 21:37:17 +00003924 N0.getOperand(0), Amt);
Andrew Trickac6d9be2013-05-25 02:42:55 +00003925 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendling88103372009-01-30 21:37:17 +00003926 Shift);
Andrew Trickac6d9be2013-05-25 02:42:55 +00003927 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendling88103372009-01-30 21:37:17 +00003928 N->getValueType(0), Trunc);
Christopher Lamb15cbde32008-03-19 08:30:06 +00003929 }
3930 }
3931 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003932
Duncan Sandsb0d5cdd2009-02-01 18:06:53 +00003933 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengeb9f8922008-08-30 02:03:58 +00003934 if (N1.getOpcode() == ISD::TRUNCATE &&
Evan Cheng242ebd12008-09-22 18:19:24 +00003935 N1.getOperand(0).getOpcode() == ISD::AND &&
3936 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
Evan Chengeb9f8922008-08-30 02:03:58 +00003937 SDValue N101 = N1.getOperand(0).getOperand(1);
Evan Cheng242ebd12008-09-22 18:19:24 +00003938 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
Owen Andersone50ed302009-08-10 22:56:29 +00003939 EVT TruncVT = N1.getValueType();
Evan Cheng242ebd12008-09-22 18:19:24 +00003940 SDValue N100 = N1.getOperand(0).getOperand(0);
Duncan Sandsb0d5cdd2009-02-01 18:06:53 +00003941 APInt TruncC = N101C->getAPIntValue();
Jay Foad40f8f622010-12-07 08:25:19 +00003942 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
Andrew Trickac6d9be2013-05-25 02:42:55 +00003943 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
3944 DAG.getNode(ISD::AND, SDLoc(N),
Bill Wendling88103372009-01-30 21:37:17 +00003945 TruncVT,
Bill Wendling9729c5a2009-01-31 03:12:48 +00003946 DAG.getNode(ISD::TRUNCATE,
Andrew Trickac6d9be2013-05-25 02:42:55 +00003947 SDLoc(N),
Bill Wendling9729c5a2009-01-31 03:12:48 +00003948 TruncVT, N100),
Dan Gohmance9bc122009-01-27 20:39:34 +00003949 DAG.getConstant(TruncC, TruncVT)));
Evan Chengeb9f8922008-08-30 02:03:58 +00003950 }
3951 }
3952
Benjamin Kramer9b108a32011-01-30 16:38:43 +00003953 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3954 // if c1 is equal to the number of bits the trunc removes
3955 if (N0.getOpcode() == ISD::TRUNCATE &&
3956 (N0.getOperand(0).getOpcode() == ISD::SRL ||
3957 N0.getOperand(0).getOpcode() == ISD::SRA) &&
3958 N0.getOperand(0).hasOneUse() &&
3959 N0.getOperand(0).getOperand(1).hasOneUse() &&
3960 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3961 EVT LargeVT = N0.getOperand(0).getValueType();
3962 ConstantSDNode *LargeShiftAmt =
3963 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3964
3965 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3966 LargeShiftAmt->getZExtValue()) {
3967 SDValue Amt =
3968 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
Owen Anderson95771af2011-02-25 21:41:48 +00003969 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
Andrew Trickac6d9be2013-05-25 02:42:55 +00003970 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
Benjamin Kramer9b108a32011-01-30 16:38:43 +00003971 N0.getOperand(0).getOperand(0), Amt);
Andrew Trickac6d9be2013-05-25 02:42:55 +00003972 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
Benjamin Kramer9b108a32011-01-30 16:38:43 +00003973 }
3974 }
3975
Scott Michelfdc40a02009-02-17 22:15:04 +00003976 // Simplify, based on bits shifted out of the LHS.
Dan Gohman475871a2008-07-27 21:46:04 +00003977 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3978 return SDValue(N, 0);
Scott Michelfdc40a02009-02-17 22:15:04 +00003979
3980
Nate Begeman1d4d4142005-09-01 00:19:25 +00003981 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00003982 if (DAG.SignBitIsZero(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00003983 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattnere70da202007-12-06 07:33:36 +00003984
Evan Chenge5b51ac2010-04-17 06:13:15 +00003985 if (N1C) {
3986 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3987 if (NewSRA.getNode())
3988 return NewSRA;
3989 }
3990
Evan Chengb3a3d5e2010-04-28 07:10:39 +00003991 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00003992}
3993
Dan Gohman475871a2008-07-27 21:46:04 +00003994SDValue DAGCombiner::visitSRL(SDNode *N) {
3995 SDValue N0 = N->getOperand(0);
3996 SDValue N1 = N->getOperand(1);
Nate Begeman646d7e22005-09-02 21:18:40 +00003997 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3998 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00003999 EVT VT = N0.getValueType();
Dan Gohman87862e72009-12-11 21:31:27 +00004000 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelfdc40a02009-02-17 22:15:04 +00004001
Daniel Sanders028e4d22013-11-11 17:23:41 +00004002 // fold vector ops
4003 if (VT.isVector()) {
4004 SDValue FoldedVOp = SimplifyVBinOp(N);
4005 if (FoldedVOp.getNode()) return FoldedVOp;
4006 }
4007
Nate Begeman1d4d4142005-09-01 00:19:25 +00004008 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman646d7e22005-09-02 21:18:40 +00004009 if (N0C && N1C)
Bill Wendlingf3cbca22008-09-24 10:25:02 +00004010 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman1d4d4142005-09-01 00:19:25 +00004011 // fold (srl 0, x) -> 0
Nate Begeman646d7e22005-09-02 21:18:40 +00004012 if (N0C && N0C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00004013 return N0;
Nate Begeman1d4d4142005-09-01 00:19:25 +00004014 // fold (srl x, c >= size(x)) -> undef
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00004015 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesene8d72302009-02-06 23:05:02 +00004016 return DAG.getUNDEF(VT);
Nate Begeman1d4d4142005-09-01 00:19:25 +00004017 // fold (srl x, 0) -> x
Nate Begeman646d7e22005-09-02 21:18:40 +00004018 if (N1C && N1C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00004019 return N0;
Nate Begeman1d4d4142005-09-01 00:19:25 +00004020 // if (srl x, c) is known to be zero, return 0
Dan Gohman475871a2008-07-27 21:46:04 +00004021 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman2e68b6f2008-02-25 21:11:39 +00004022 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begeman83e75ec2005-09-06 04:43:02 +00004023 return DAG.getConstant(0, VT);
Scott Michelfdc40a02009-02-17 22:15:04 +00004024
Bill Wendling88103372009-01-30 21:37:17 +00004025 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Scott Michelfdc40a02009-02-17 22:15:04 +00004026 if (N1C && N0.getOpcode() == ISD::SRL &&
Nate Begeman1d4d4142005-09-01 00:19:25 +00004027 N0.getOperand(1).getOpcode() == ISD::Constant) {
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00004028 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4029 uint64_t c2 = N1C->getZExtValue();
Dale Johannesenc72b18c2010-12-21 21:55:50 +00004030 if (c1 + c2 >= OpSizeInBits)
Nate Begeman83e75ec2005-09-06 04:43:02 +00004031 return DAG.getConstant(0, VT);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004032 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
Nate Begeman83e75ec2005-09-06 04:43:02 +00004033 DAG.getConstant(c1 + c2, N1.getValueType()));
Nate Begeman1d4d4142005-09-01 00:19:25 +00004034 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004035
Dale Johannesenf5daf8b2010-12-17 21:45:49 +00004036 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesenf5daf8b2010-12-17 21:45:49 +00004037 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4038 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen025cc6e2010-12-20 20:10:50 +00004039 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Anderson95771af2011-02-25 21:41:48 +00004040 uint64_t c1 =
Dale Johannesenf5daf8b2010-12-17 21:45:49 +00004041 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4042 uint64_t c2 = N1C->getZExtValue();
Dale Johannesenc72b18c2010-12-21 21:55:50 +00004043 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4044 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesenf5daf8b2010-12-17 21:45:49 +00004045 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen025cc6e2010-12-20 20:10:50 +00004046 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesenf5daf8b2010-12-17 21:45:49 +00004047 if (c1 + OpSizeInBits == InnerShiftSize) {
4048 if (c1 + c2 >= InnerShiftSize)
4049 return DAG.getConstant(0, VT);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004050 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4051 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesenf5daf8b2010-12-17 21:45:49 +00004052 N0.getOperand(0)->getOperand(0),
Dale Johannesenc72b18c2010-12-21 21:55:50 +00004053 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesenf5daf8b2010-12-17 21:45:49 +00004054 }
4055 }
4056
Chris Lattnerefcddc32010-04-15 05:28:43 +00004057 // fold (srl (shl x, c), c) -> (and x, cst2)
4058 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4059 N0.getValueSizeInBits() <= 64) {
4060 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
Andrew Trickac6d9be2013-05-25 02:42:55 +00004061 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattnerefcddc32010-04-15 05:28:43 +00004062 DAG.getConstant(~0ULL >> ShAmt, VT));
4063 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004064
Michael Liao2da86392013-06-21 18:45:27 +00004065 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner06afe072006-05-05 22:53:17 +00004066 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4067 // Shifting in all undef bits?
Owen Andersone50ed302009-08-10 22:56:29 +00004068 EVT SmallVT = N0.getOperand(0).getValueType();
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00004069 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
Dale Johannesene8d72302009-02-06 23:05:02 +00004070 return DAG.getUNDEF(VT);
Chris Lattner06afe072006-05-05 22:53:17 +00004071
Evan Chenge5b51ac2010-04-17 06:13:15 +00004072 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona34d9362011-04-14 17:30:49 +00004073 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickac6d9be2013-05-25 02:42:55 +00004074 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona34d9362011-04-14 17:30:49 +00004075 N0.getOperand(0),
4076 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Evan Chenge5b51ac2010-04-17 06:13:15 +00004077 AddToWorkList(SmallShift.getNode());
Michael Liao2da86392013-06-21 18:45:27 +00004078 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4079 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4080 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4081 DAG.getConstant(Mask, VT));
Evan Chenge5b51ac2010-04-17 06:13:15 +00004082 }
Chris Lattner06afe072006-05-05 22:53:17 +00004083 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004084
Chris Lattner3657ffe2006-10-12 20:23:19 +00004085 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4086 // bit, which is unmodified by sra.
Bill Wendling88103372009-01-30 21:37:17 +00004087 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
Chris Lattner3657ffe2006-10-12 20:23:19 +00004088 if (N0.getOpcode() == ISD::SRA)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004089 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner3657ffe2006-10-12 20:23:19 +00004090 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004091
Sylvestre Ledru94c22712012-09-27 10:14:43 +00004092 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelfdc40a02009-02-17 22:15:04 +00004093 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Duncan Sands83ec4b62008-06-06 12:08:01 +00004094 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
Dan Gohman948d8ea2008-02-20 16:33:30 +00004095 APInt KnownZero, KnownOne;
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00004096 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelfdc40a02009-02-17 22:15:04 +00004097
Chris Lattner350bec02006-04-02 06:11:11 +00004098 // If any of the input bits are KnownOne, then the input couldn't be all
4099 // zeros, thus the result of the srl will always be zero.
Dan Gohman948d8ea2008-02-20 16:33:30 +00004100 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelfdc40a02009-02-17 22:15:04 +00004101
Chris Lattner350bec02006-04-02 06:11:11 +00004102 // If all of the bits input the to ctlz node are known to be zero, then
4103 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00004104 APInt UnknownBits = ~KnownZero;
Chris Lattner350bec02006-04-02 06:11:11 +00004105 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelfdc40a02009-02-17 22:15:04 +00004106
Chris Lattner350bec02006-04-02 06:11:11 +00004107 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendling88103372009-01-30 21:37:17 +00004108 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner350bec02006-04-02 06:11:11 +00004109 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendling88103372009-01-30 21:37:17 +00004110 // could be set on input to the CTLZ node. If this bit is set, the SRL
4111 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4112 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohman948d8ea2008-02-20 16:33:30 +00004113 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman475871a2008-07-27 21:46:04 +00004114 SDValue Op = N0.getOperand(0);
Bill Wendling88103372009-01-30 21:37:17 +00004115
Chris Lattner350bec02006-04-02 06:11:11 +00004116 if (ShAmt) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00004117 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Anderson95771af2011-02-25 21:41:48 +00004118 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Gabor Greifba36cb52008-08-28 21:40:38 +00004119 AddToWorkList(Op.getNode());
Chris Lattner350bec02006-04-02 06:11:11 +00004120 }
Bill Wendling88103372009-01-30 21:37:17 +00004121
Andrew Trickac6d9be2013-05-25 02:42:55 +00004122 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling88103372009-01-30 21:37:17 +00004123 Op, DAG.getConstant(1, VT));
Chris Lattner350bec02006-04-02 06:11:11 +00004124 }
4125 }
Evan Chengeb9f8922008-08-30 02:03:58 +00004126
Duncan Sandsb0d5cdd2009-02-01 18:06:53 +00004127 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengeb9f8922008-08-30 02:03:58 +00004128 if (N1.getOpcode() == ISD::TRUNCATE &&
Evan Cheng242ebd12008-09-22 18:19:24 +00004129 N1.getOperand(0).getOpcode() == ISD::AND &&
4130 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
Evan Chengeb9f8922008-08-30 02:03:58 +00004131 SDValue N101 = N1.getOperand(0).getOperand(1);
Evan Cheng242ebd12008-09-22 18:19:24 +00004132 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
Owen Andersone50ed302009-08-10 22:56:29 +00004133 EVT TruncVT = N1.getValueType();
Evan Cheng242ebd12008-09-22 18:19:24 +00004134 SDValue N100 = N1.getOperand(0).getOperand(0);
Duncan Sandsb0d5cdd2009-02-01 18:06:53 +00004135 APInt TruncC = N101C->getAPIntValue();
Jay Foad40f8f622010-12-07 08:25:19 +00004136 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
Andrew Trickac6d9be2013-05-25 02:42:55 +00004137 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4138 DAG.getNode(ISD::AND, SDLoc(N),
Bill Wendling88103372009-01-30 21:37:17 +00004139 TruncVT,
Bill Wendling9729c5a2009-01-31 03:12:48 +00004140 DAG.getNode(ISD::TRUNCATE,
Andrew Trickac6d9be2013-05-25 02:42:55 +00004141 SDLoc(N),
Bill Wendling9729c5a2009-01-31 03:12:48 +00004142 TruncVT, N100),
Dan Gohmance9bc122009-01-27 20:39:34 +00004143 DAG.getConstant(TruncC, TruncVT)));
Evan Chengeb9f8922008-08-30 02:03:58 +00004144 }
4145 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004146
Chris Lattner61a4c072007-04-18 03:06:49 +00004147 // fold operands of srl based on knowledge that the low bits are not
4148 // demanded.
Dan Gohman475871a2008-07-27 21:46:04 +00004149 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4150 return SDValue(N, 0);
Scott Michelfdc40a02009-02-17 22:15:04 +00004151
Evan Cheng9ab2b982009-12-18 21:31:31 +00004152 if (N1C) {
4153 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4154 if (NewSRL.getNode())
4155 return NewSRL;
4156 }
4157
Dan Gohman4e39e9d2010-06-24 14:30:44 +00004158 // Attempt to convert a srl of a load into a narrower zero-extending load.
4159 SDValue NarrowLoad = ReduceLoadWidth(N);
4160 if (NarrowLoad.getNode())
4161 return NarrowLoad;
4162
Evan Cheng9ab2b982009-12-18 21:31:31 +00004163 // Here is a common situation. We want to optimize:
4164 //
4165 // %a = ...
4166 // %b = and i32 %a, 2
4167 // %c = srl i32 %b, 1
4168 // brcond i32 %c ...
4169 //
4170 // into
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004171 //
Evan Cheng9ab2b982009-12-18 21:31:31 +00004172 // %a = ...
4173 // %b = and %a, 2
4174 // %c = setcc eq %b, 0
4175 // brcond %c ...
4176 //
4177 // However when after the source operand of SRL is optimized into AND, the SRL
4178 // itself may not be optimized further. Look for it and add the BRCOND into
4179 // the worklist.
Evan Chengd40d03e2010-01-06 19:38:29 +00004180 if (N->hasOneUse()) {
4181 SDNode *Use = *N->use_begin();
4182 if (Use->getOpcode() == ISD::BRCOND)
4183 AddToWorkList(Use);
4184 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4185 // Also look pass the truncate.
4186 Use = *Use->use_begin();
4187 if (Use->getOpcode() == ISD::BRCOND)
4188 AddToWorkList(Use);
4189 }
4190 }
Evan Cheng9ab2b982009-12-18 21:31:31 +00004191
Evan Chengb3a3d5e2010-04-28 07:10:39 +00004192 return SDValue();
Evan Cheng4c26e932010-04-19 19:29:22 +00004193}
4194
Dan Gohman475871a2008-07-27 21:46:04 +00004195SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4196 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00004197 EVT VT = N->getValueType(0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00004198
4199 // fold (ctlz c1) -> c2
Chris Lattner310b5782006-05-06 23:06:26 +00004200 if (isa<ConstantSDNode>(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004201 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman475871a2008-07-27 21:46:04 +00004202 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00004203}
4204
Chandler Carruth63974b22011-12-13 01:56:10 +00004205SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4206 SDValue N0 = N->getOperand(0);
4207 EVT VT = N->getValueType(0);
4208
4209 // fold (ctlz_zero_undef c1) -> c2
4210 if (isa<ConstantSDNode>(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004211 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth63974b22011-12-13 01:56:10 +00004212 return SDValue();
4213}
4214
Dan Gohman475871a2008-07-27 21:46:04 +00004215SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4216 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00004217 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00004218
Nate Begeman1d4d4142005-09-01 00:19:25 +00004219 // fold (cttz c1) -> c2
Chris Lattner310b5782006-05-06 23:06:26 +00004220 if (isa<ConstantSDNode>(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004221 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman475871a2008-07-27 21:46:04 +00004222 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00004223}
4224
Chandler Carruth63974b22011-12-13 01:56:10 +00004225SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4226 SDValue N0 = N->getOperand(0);
4227 EVT VT = N->getValueType(0);
4228
4229 // fold (cttz_zero_undef c1) -> c2
4230 if (isa<ConstantSDNode>(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004231 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth63974b22011-12-13 01:56:10 +00004232 return SDValue();
4233}
4234
Dan Gohman475871a2008-07-27 21:46:04 +00004235SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4236 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00004237 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00004238
Nate Begeman1d4d4142005-09-01 00:19:25 +00004239 // fold (ctpop c1) -> c2
Chris Lattner310b5782006-05-06 23:06:26 +00004240 if (isa<ConstantSDNode>(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004241 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman475871a2008-07-27 21:46:04 +00004242 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00004243}
4244
Dan Gohman475871a2008-07-27 21:46:04 +00004245SDValue DAGCombiner::visitSELECT(SDNode *N) {
4246 SDValue N0 = N->getOperand(0);
4247 SDValue N1 = N->getOperand(1);
4248 SDValue N2 = N->getOperand(2);
Nate Begeman452d7be2005-09-16 00:54:12 +00004249 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4250 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4251 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Andersone50ed302009-08-10 22:56:29 +00004252 EVT VT = N->getValueType(0);
4253 EVT VT0 = N0.getValueType();
Nate Begeman44728a72005-09-19 22:34:01 +00004254
Bill Wendling34584e62009-01-30 22:02:18 +00004255 // fold (select C, X, X) -> X
Nate Begeman452d7be2005-09-16 00:54:12 +00004256 if (N1 == N2)
4257 return N1;
Bill Wendling34584e62009-01-30 22:02:18 +00004258 // fold (select true, X, Y) -> X
Nate Begeman452d7be2005-09-16 00:54:12 +00004259 if (N0C && !N0C->isNullValue())
4260 return N1;
Bill Wendling34584e62009-01-30 22:02:18 +00004261 // fold (select false, X, Y) -> Y
Nate Begeman452d7be2005-09-16 00:54:12 +00004262 if (N0C && N0C->isNullValue())
4263 return N2;
Bill Wendling34584e62009-01-30 22:02:18 +00004264 // fold (select C, 1, X) -> (or C, X)
Owen Anderson825b72b2009-08-11 20:47:22 +00004265 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004266 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendling34584e62009-01-30 22:02:18 +00004267 // fold (select C, 0, 1) -> (xor C, 1)
Bob Wilson67ba2232009-01-22 22:05:48 +00004268 if (VT.isInteger() &&
Owen Anderson825b72b2009-08-11 20:47:22 +00004269 (VT0 == MVT::i1 ||
Bob Wilson67ba2232009-01-22 22:05:48 +00004270 (VT0.isInteger() &&
Nadav Rotem6dfabb62012-09-20 08:53:31 +00004271 TLI.getBooleanContents(false) ==
4272 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohman002e5d02008-03-13 22:13:53 +00004273 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendling34584e62009-01-30 22:02:18 +00004274 SDValue XORNode;
Evan Cheng571c4782007-08-18 05:57:05 +00004275 if (VT == VT0)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004276 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendling34584e62009-01-30 22:02:18 +00004277 N0, DAG.getConstant(1, VT0));
Andrew Trickac6d9be2013-05-25 02:42:55 +00004278 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendling34584e62009-01-30 22:02:18 +00004279 N0, DAG.getConstant(1, VT0));
Gabor Greifba36cb52008-08-28 21:40:38 +00004280 AddToWorkList(XORNode.getNode());
Duncan Sands8e4eb092008-06-08 20:54:56 +00004281 if (VT.bitsGT(VT0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004282 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4283 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Cheng571c4782007-08-18 05:57:05 +00004284 }
Bill Wendling34584e62009-01-30 22:02:18 +00004285 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson825b72b2009-08-11 20:47:22 +00004286 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00004287 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilson4c245462009-01-22 17:39:32 +00004288 AddToWorkList(NOTNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00004289 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman452d7be2005-09-16 00:54:12 +00004290 }
Bill Wendling34584e62009-01-30 22:02:18 +00004291 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson825b72b2009-08-11 20:47:22 +00004292 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00004293 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilson4c245462009-01-22 17:39:32 +00004294 AddToWorkList(NOTNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00004295 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman452d7be2005-09-16 00:54:12 +00004296 }
Bill Wendling34584e62009-01-30 22:02:18 +00004297 // fold (select C, X, 0) -> (and C, X)
Owen Anderson825b72b2009-08-11 20:47:22 +00004298 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickac6d9be2013-05-25 02:42:55 +00004299 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendling34584e62009-01-30 22:02:18 +00004300 // fold (select X, X, Y) -> (or X, Y)
4301 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson825b72b2009-08-11 20:47:22 +00004302 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004303 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendling34584e62009-01-30 22:02:18 +00004304 // fold (select X, Y, X) -> (and X, Y)
4305 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson825b72b2009-08-11 20:47:22 +00004306 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004307 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelfdc40a02009-02-17 22:15:04 +00004308
Chris Lattner40c62d52005-10-18 06:04:22 +00004309 // If we can fold this based on the true/false value, do so.
4310 if (SimplifySelectOps(N, N1, N2))
Dan Gohman475871a2008-07-27 21:46:04 +00004311 return SDValue(N, 0); // Don't revisit N.
Duncan Sandsd4b9c172008-06-13 19:07:40 +00004312
Nate Begeman44728a72005-09-19 22:34:01 +00004313 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00004314 if (N0.getOpcode() == ISD::SETCC) {
Nate Begeman750ac1b2006-02-01 07:19:44 +00004315 // FIXME:
Owen Anderson825b72b2009-08-11 20:47:22 +00004316 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
Nate Begeman750ac1b2006-02-01 07:19:44 +00004317 // having to say they don't support SELECT_CC on every type the DAG knows
4318 // about, since there is no way to mark an opcode illegal at all value types
Owen Anderson825b72b2009-08-11 20:47:22 +00004319 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
Dan Gohman4ea48042009-08-02 16:19:38 +00004320 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004321 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendling34584e62009-01-30 22:02:18 +00004322 N0.getOperand(0), N0.getOperand(1),
Nate Begeman750ac1b2006-02-01 07:19:44 +00004323 N1, N2, N0.getOperand(2));
Andrew Trickac6d9be2013-05-25 02:42:55 +00004324 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00004325 }
Bill Wendling34584e62009-01-30 22:02:18 +00004326
Dan Gohman475871a2008-07-27 21:46:04 +00004327 return SDValue();
Nate Begeman452d7be2005-09-16 00:54:12 +00004328}
4329
Bill Wendlingf62b2742013-11-22 05:18:07 +00004330static
4331std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4332 SDLoc DL(N);
4333 EVT LoVT, HiVT;
4334 llvm::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4335
4336 // Split the inputs.
4337 SDValue Lo, Hi, LL, LH, RL, RH;
4338 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4339 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4340
4341 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4342 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4343
4344 return std::make_pair(Lo, Hi);
4345}
4346
Benjamin Kramer6242fda2013-04-26 09:19:19 +00004347SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4348 SDValue N0 = N->getOperand(0);
4349 SDValue N1 = N->getOperand(1);
4350 SDValue N2 = N->getOperand(2);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004351 SDLoc DL(N);
Benjamin Kramer6242fda2013-04-26 09:19:19 +00004352
4353 // Canonicalize integer abs.
4354 // vselect (setg[te] X, 0), X, -X ->
4355 // vselect (setgt X, -1), X, -X ->
4356 // vselect (setl[te] X, 0), -X, X ->
4357 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4358 if (N0.getOpcode() == ISD::SETCC) {
4359 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4360 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4361 bool isAbs = false;
4362 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4363
4364 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4365 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4366 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4367 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4368 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4369 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4370 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4371
4372 if (isAbs) {
4373 EVT VT = LHS.getValueType();
4374 SDValue Shift = DAG.getNode(
4375 ISD::SRA, DL, VT, LHS,
4376 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4377 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4378 AddToWorkList(Shift.getNode());
4379 AddToWorkList(Add.getNode());
4380 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4381 }
4382 }
4383
Bill Wendlingf62b2742013-11-22 05:18:07 +00004384 // If the VSELECT result requires splitting and the mask is provided by a
4385 // SETCC, then split both nodes and its operands before legalization. This
4386 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4387 // and enables future optimizations (e.g. min/max pattern matching on X86).
4388 if (N0.getOpcode() == ISD::SETCC) {
4389 EVT VT = N->getValueType(0);
Juergen Ributzkac7e77f92013-11-13 01:57:54 +00004390
Bill Wendlingf62b2742013-11-22 05:18:07 +00004391 // Check if any splitting is required.
4392 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4393 TargetLowering::TypeSplitVector)
4394 return SDValue();
Juergen Ributzkac7e77f92013-11-13 01:57:54 +00004395
Bill Wendlingf62b2742013-11-22 05:18:07 +00004396 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4397 llvm::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4398 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4399 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzkac7e77f92013-11-13 01:57:54 +00004400
Bill Wendlingf62b2742013-11-22 05:18:07 +00004401 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4402 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzkac7e77f92013-11-13 01:57:54 +00004403
Bill Wendlingf62b2742013-11-22 05:18:07 +00004404 // Add the new VSELECT nodes to the work list in case they need to be split
4405 // again.
4406 AddToWorkList(Lo.getNode());
4407 AddToWorkList(Hi.getNode());
4408
4409 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzkac7e77f92013-11-13 01:57:54 +00004410 }
4411
Benjamin Kramer6242fda2013-04-26 09:19:19 +00004412 return SDValue();
4413}
4414
Dan Gohman475871a2008-07-27 21:46:04 +00004415SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4416 SDValue N0 = N->getOperand(0);
4417 SDValue N1 = N->getOperand(1);
4418 SDValue N2 = N->getOperand(2);
4419 SDValue N3 = N->getOperand(3);
4420 SDValue N4 = N->getOperand(4);
Nate Begeman44728a72005-09-19 22:34:01 +00004421 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelfdc40a02009-02-17 22:15:04 +00004422
Nate Begeman44728a72005-09-19 22:34:01 +00004423 // fold select_cc lhs, rhs, x, x, cc -> x
4424 if (N2 == N3)
4425 return N2;
Scott Michelfdc40a02009-02-17 22:15:04 +00004426
Chris Lattner5f42a242006-09-20 06:19:26 +00004427 // Determine if the condition we're dealing with is constant
Matt Arsenault225ed702013-05-18 00:21:46 +00004428 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickac6d9be2013-05-25 02:42:55 +00004429 N0, N1, CC, SDLoc(N), false);
Stephen Lin7e6d6202013-06-15 04:03:33 +00004430 if (SCC.getNode()) {
4431 AddToWorkList(SCC.getNode());
Chris Lattner5f42a242006-09-20 06:19:26 +00004432
Stephen Lin7e6d6202013-06-15 04:03:33 +00004433 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4434 if (!SCCC->isNullValue())
4435 return N2; // cond always true -> true val
4436 else
4437 return N3; // cond always false -> false val
4438 }
4439
4440 // Fold to a simpler select_cc
4441 if (SCC.getOpcode() == ISD::SETCC)
4442 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4443 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4444 SCC.getOperand(2));
Chris Lattner5f42a242006-09-20 06:19:26 +00004445 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004446
Chris Lattner40c62d52005-10-18 06:04:22 +00004447 // If we can fold this based on the true/false value, do so.
4448 if (SimplifySelectOps(N, N2, N3))
Dan Gohman475871a2008-07-27 21:46:04 +00004449 return SDValue(N, 0); // Don't revisit N.
Scott Michelfdc40a02009-02-17 22:15:04 +00004450
Nate Begeman44728a72005-09-19 22:34:01 +00004451 // fold select_cc into other things, such as min/max/abs
Andrew Trickac6d9be2013-05-25 02:42:55 +00004452 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman452d7be2005-09-16 00:54:12 +00004453}
4454
Dan Gohman475871a2008-07-27 21:46:04 +00004455SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman452d7be2005-09-16 00:54:12 +00004456 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenff97d4f2009-02-03 00:47:48 +00004457 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickac6d9be2013-05-25 02:42:55 +00004458 SDLoc(N));
Nate Begeman452d7be2005-09-16 00:54:12 +00004459}
4460
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004461// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman57fc82d2009-04-09 03:51:29 +00004462// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004463// transformation. Returns true if extension are possible and the above
Scott Michelfdc40a02009-02-17 22:15:04 +00004464// mentioned transformation is profitable.
Dan Gohman475871a2008-07-27 21:46:04 +00004465static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004466 unsigned ExtOpc,
Craig Toppera0ec3f92013-07-14 04:42:23 +00004467 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman79ce2762009-01-15 19:20:50 +00004468 const TargetLowering &TLI) {
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004469 bool HasCopyToRegUses = false;
4470 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greif12632d22008-08-30 19:29:20 +00004471 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4472 UE = N0.getNode()->use_end();
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004473 UI != UE; ++UI) {
Dan Gohman89684502008-07-27 20:43:25 +00004474 SDNode *User = *UI;
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004475 if (User == N)
4476 continue;
Dan Gohman57fc82d2009-04-09 03:51:29 +00004477 if (UI.getUse().getResNo() != N0.getResNo())
4478 continue;
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004479 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman57fc82d2009-04-09 03:51:29 +00004480 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004481 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4482 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4483 // Sign bits will be lost after a zext.
4484 return false;
4485 bool Add = false;
4486 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00004487 SDValue UseOp = User->getOperand(i);
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004488 if (UseOp == N0)
4489 continue;
4490 if (!isa<ConstantSDNode>(UseOp))
4491 return false;
4492 Add = true;
4493 }
4494 if (Add)
4495 ExtendNodes.push_back(User);
Dan Gohman57fc82d2009-04-09 03:51:29 +00004496 continue;
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004497 }
Dan Gohman57fc82d2009-04-09 03:51:29 +00004498 // If truncates aren't free and there are users we can't
4499 // extend, it isn't worthwhile.
4500 if (!isTruncFree)
4501 return false;
4502 // Remember if this value is live-out.
4503 if (User->getOpcode() == ISD::CopyToReg)
4504 HasCopyToRegUses = true;
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004505 }
4506
4507 if (HasCopyToRegUses) {
4508 bool BothLiveOut = false;
4509 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4510 UI != UE; ++UI) {
Dan Gohman57fc82d2009-04-09 03:51:29 +00004511 SDUse &Use = UI.getUse();
4512 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4513 BothLiveOut = true;
4514 break;
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004515 }
4516 }
4517 if (BothLiveOut)
4518 // Both unextended and extended values are live out. There had better be
Bob Wilsonbebfbc52010-11-28 06:51:19 +00004519 // a good reason for the transformation.
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004520 return ExtendNodes.size();
4521 }
4522 return true;
4523}
4524
Craig Topper6c64fba2013-07-13 07:43:40 +00004525void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickac6d9be2013-05-25 02:42:55 +00004526 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004527 ISD::NodeType ExtType) {
4528 // Extend SetCC uses if necessary.
4529 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4530 SDNode *SetCC = SetCCs[i];
4531 SmallVector<SDValue, 4> Ops;
4532
4533 for (unsigned j = 0; j != 2; ++j) {
4534 SDValue SOp = SetCC->getOperand(j);
4535 if (SOp == Trunc)
4536 Ops.push_back(ExtLoad);
4537 else
4538 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4539 }
4540
4541 Ops.push_back(SetCC->getOperand(2));
4542 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4543 &Ops[0], Ops.size()));
4544 }
4545}
4546
Dan Gohman475871a2008-07-27 21:46:04 +00004547SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4548 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00004549 EVT VT = N->getValueType(0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00004550
Nate Begeman1d4d4142005-09-01 00:19:25 +00004551 // fold (sext c1) -> c1
Reid Spencer3ed469c2006-11-02 20:25:50 +00004552 if (isa<ConstantSDNode>(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004553 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +00004554
Nadav Rotem0c8607b2013-01-20 08:35:56 +00004555 // fold (sext (sext x)) -> (sext x)
4556 // fold (sext (aext x)) -> (sext x)
4557 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004558 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem0c8607b2013-01-20 08:35:56 +00004559 N0.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00004560
Chris Lattner22558872007-02-26 03:13:59 +00004561 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman1fdfa6a2008-05-20 20:56:33 +00004562 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4563 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greifba36cb52008-08-28 21:40:38 +00004564 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4565 if (NarrowLoad.getNode()) {
Dale Johannesen61734eb2010-05-25 17:50:03 +00004566 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4567 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greifba36cb52008-08-28 21:40:38 +00004568 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen61734eb2010-05-25 17:50:03 +00004569 // CombineTo deleted the truncate, if needed, but not what's under it.
4570 AddToWorkList(oye);
4571 }
Dan Gohmanc7b34442009-04-27 02:00:55 +00004572 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng0b063de2007-03-23 02:16:52 +00004573 }
Evan Chengc88138f2007-03-22 01:54:19 +00004574
Dan Gohman1fdfa6a2008-05-20 20:56:33 +00004575 // See if the value being truncated is already sign extended. If so, just
4576 // eliminate the trunc/sext pair.
Dan Gohman475871a2008-07-27 21:46:04 +00004577 SDValue Op = N0.getOperand(0);
Dan Gohmand1996362010-01-09 02:13:55 +00004578 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4579 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4580 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohmanea859be2007-06-22 14:59:07 +00004581 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelfdc40a02009-02-17 22:15:04 +00004582
Chris Lattner22558872007-02-26 03:13:59 +00004583 if (OpBits == DestBits) {
4584 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4585 // bits, it is already ready.
4586 if (NumSignBits > DestBits-MidBits)
4587 return Op;
4588 } else if (OpBits < DestBits) {
4589 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4590 // bits, just sext from i32.
4591 if (NumSignBits > OpBits-MidBits)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004592 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattner22558872007-02-26 03:13:59 +00004593 } else {
4594 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4595 // bits, just truncate to i32.
4596 if (NumSignBits > OpBits-MidBits)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004597 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattner6007b842006-09-21 06:00:20 +00004598 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004599
Chris Lattner22558872007-02-26 03:13:59 +00004600 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sands25cf2272008-11-24 14:53:14 +00004601 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4602 N0.getValueType())) {
Dan Gohmand1996362010-01-09 02:13:55 +00004603 if (OpBits < DestBits)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004604 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohmand1996362010-01-09 02:13:55 +00004605 else if (OpBits > DestBits)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004606 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4607 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohmand1996362010-01-09 02:13:55 +00004608 DAG.getValueType(N0.getValueType()));
Chris Lattner22558872007-02-26 03:13:59 +00004609 }
Chris Lattner6007b842006-09-21 06:00:20 +00004610 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004611
Evan Cheng110dec22005-12-14 02:19:23 +00004612 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Nadav Rotem8c20ec52011-02-24 21:01:34 +00004613 // None of the supported targets knows how to perform load and sign extend
Nadav Rotemfcd96192011-02-27 07:40:43 +00004614 // on vectors in one instruction. We only perform this transformation on
4615 // scalars.
Nadav Rotem8c20ec52011-02-24 21:01:34 +00004616 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Duncan Sands25cf2272008-11-24 14:53:14 +00004617 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng03294662008-10-14 21:26:46 +00004618 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004619 bool DoXform = true;
4620 SmallVector<SDNode*, 4> SetCCs;
4621 if (!N0.hasOneUse())
4622 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4623 if (DoXform) {
4624 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004625 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman57fc82d2009-04-09 03:51:29 +00004626 LN0->getChain(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00004627 LN0->getBasePtr(), N0.getValueType(),
4628 LN0->getMemOperand());
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004629 CombineTo(N, ExtLoad);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004630 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendling6ce610f2009-01-30 22:23:15 +00004631 N0.getValueType(), ExtLoad);
Gabor Greifba36cb52008-08-28 21:40:38 +00004632 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickac6d9be2013-05-25 02:42:55 +00004633 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004634 ISD::SIGN_EXTEND);
Dan Gohman475871a2008-07-27 21:46:04 +00004635 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004636 }
Nate Begeman3df4d522005-10-12 20:40:40 +00004637 }
Chris Lattnerad25d4e2005-12-14 19:05:06 +00004638
4639 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4640 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greifba36cb52008-08-28 21:40:38 +00004641 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4642 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Cheng466685d2006-10-09 20:57:25 +00004643 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman8a55ce42009-09-23 21:02:20 +00004644 EVT MemVT = LN0->getMemoryVT();
Duncan Sands25cf2272008-11-24 14:53:14 +00004645 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman8a55ce42009-09-23 21:02:20 +00004646 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00004647 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling6ce610f2009-01-30 22:23:15 +00004648 LN0->getChain(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00004649 LN0->getBasePtr(), MemVT,
4650 LN0->getMemOperand());
Jim Laskeyf6c4ccf2006-12-15 21:38:30 +00004651 CombineTo(N, ExtLoad);
Gabor Greif12632d22008-08-30 19:29:20 +00004652 CombineTo(N0.getNode(),
Andrew Trickac6d9be2013-05-25 02:42:55 +00004653 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendling6ce610f2009-01-30 22:23:15 +00004654 N0.getValueType(), ExtLoad),
Jim Laskeyf6c4ccf2006-12-15 21:38:30 +00004655 ExtLoad.getValue(1));
Dan Gohman475871a2008-07-27 21:46:04 +00004656 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskeyf6c4ccf2006-12-15 21:38:30 +00004657 }
Chris Lattnerad25d4e2005-12-14 19:05:06 +00004658 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004659
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004660 // fold (sext (and/or/xor (load x), cst)) ->
4661 // (and/or/xor (sextload x), (sext cst))
4662 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4663 N0.getOpcode() == ISD::XOR) &&
4664 isa<LoadSDNode>(N0.getOperand(0)) &&
4665 N0.getOperand(1).getOpcode() == ISD::Constant &&
4666 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4667 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4668 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4669 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4670 bool DoXform = true;
4671 SmallVector<SDNode*, 4> SetCCs;
4672 if (!N0.hasOneUse())
4673 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4674 SetCCs, TLI);
4675 if (DoXform) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00004676 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004677 LN0->getChain(), LN0->getBasePtr(),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004678 LN0->getMemoryVT(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00004679 LN0->getMemOperand());
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004680 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4681 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickac6d9be2013-05-25 02:42:55 +00004682 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004683 ExtLoad, DAG.getConstant(Mask, VT));
4684 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickac6d9be2013-05-25 02:42:55 +00004685 SDLoc(N0.getOperand(0)),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004686 N0.getOperand(0).getValueType(), ExtLoad);
4687 CombineTo(N, And);
4688 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickac6d9be2013-05-25 02:42:55 +00004689 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004690 ISD::SIGN_EXTEND);
4691 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4692 }
4693 }
4694 }
4695
Chris Lattner20a35c32007-04-11 05:32:27 +00004696 if (N0.getOpcode() == ISD::SETCC) {
Chris Lattner2b7a2712009-07-08 00:31:33 +00004697 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohman3ce89f42010-04-30 17:19:19 +00004698 // Only do this before legalize for now.
Owen Andersoned5707b2013-04-23 18:09:28 +00004699 if (VT.isVector() && !LegalOperations &&
Stephen Lin155615d2013-07-08 00:37:03 +00004700 TLI.getBooleanContents(true) ==
Owen Andersoned5707b2013-04-23 18:09:28 +00004701 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Dan Gohman3ce89f42010-04-30 17:19:19 +00004702 EVT N0VT = N0.getOperand(0).getValueType();
Nadav Rotem2e506192012-04-11 08:26:11 +00004703 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4704 // of the same size as the compared operands. Only optimize sext(setcc())
4705 // if this is the case.
Matt Arsenault225ed702013-05-18 00:21:46 +00004706 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem2e506192012-04-11 08:26:11 +00004707
4708 // We know that the # elements of the results is the same as the
4709 // # elements of the compare (and the # elements of the compare result
4710 // for that matter). Check to see that they are the same size. If so,
4711 // we know that the element size of the sext'd result matches the
4712 // element size of the compare operands.
4713 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickac6d9be2013-05-25 02:42:55 +00004714 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands34727662010-07-12 08:16:59 +00004715 N0.getOperand(1),
4716 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault9aa8fdf2013-05-17 21:43:43 +00004717
Dan Gohman3ce89f42010-04-30 17:19:19 +00004718 // If the desired elements are smaller or larger than the source
4719 // elements we can use a matching integer vector type and then
4720 // truncate/sign extend
Matt Arsenault9aa8fdf2013-05-17 21:43:43 +00004721 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper0eb5dad2012-09-29 07:18:53 +00004722 if (SVT == MatchingVectorType) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00004723 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper0eb5dad2012-09-29 07:18:53 +00004724 N0.getOperand(0), N0.getOperand(1),
4725 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickac6d9be2013-05-25 02:42:55 +00004726 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohman3ce89f42010-04-30 17:19:19 +00004727 }
Chris Lattner2b7a2712009-07-08 00:31:33 +00004728 }
Dan Gohman3ce89f42010-04-30 17:19:19 +00004729
Chris Lattner2b7a2712009-07-08 00:31:33 +00004730 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
Dan Gohmana7bcef12010-04-24 01:17:30 +00004731 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5cbd37e2009-08-06 09:18:59 +00004732 SDValue NegOne =
Dan Gohmana7bcef12010-04-24 01:17:30 +00004733 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelfdc40a02009-02-17 22:15:04 +00004734 SDValue SCC =
Andrew Trickac6d9be2013-05-25 02:42:55 +00004735 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5cbd37e2009-08-06 09:18:59 +00004736 NegOne, DAG.getConstant(0, VT),
Chris Lattner1eba01e2007-04-11 06:50:51 +00004737 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greifba36cb52008-08-28 21:40:38 +00004738 if (SCC.getNode()) return SCC;
Matt Arsenaultb05e4772013-06-14 22:04:37 +00004739 if (!VT.isVector() &&
4740 (!LegalOperations ||
4741 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4742 return DAG.getSelect(SDLoc(N), VT,
4743 DAG.getSetCC(SDLoc(N),
Jack Carteradbd3ae2013-10-17 01:34:33 +00004744 getSetCCResultType(VT),
4745 N0.getOperand(0), N0.getOperand(1),
4746 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Matt Arsenaultb05e4772013-06-14 22:04:37 +00004747 NegOne, DAG.getConstant(0, VT));
4748 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004749 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004750
Dan Gohman8f0ad582008-04-28 16:58:24 +00004751 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sands25cf2272008-11-24 14:53:14 +00004752 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohman187db7b2008-04-28 18:47:17 +00004753 DAG.SignBitIsZero(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004754 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +00004755
Evan Chengb3a3d5e2010-04-28 07:10:39 +00004756 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00004757}
4758
Rafael Espindoladecbc432012-04-09 16:06:03 +00004759// isTruncateOf - If N is a truncate of some other value, return true, record
4760// the value being truncated in Op and which of Op's bits are zero in KnownZero.
4761// This function computes KnownZero to avoid a duplicated call to
4762// ComputeMaskedBits in the caller.
4763static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4764 APInt &KnownZero) {
4765 APInt KnownOne;
4766 if (N->getOpcode() == ISD::TRUNCATE) {
4767 Op = N->getOperand(0);
4768 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4769 return true;
4770 }
4771
4772 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4773 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4774 return false;
4775
4776 SDValue Op0 = N->getOperand(0);
4777 SDValue Op1 = N->getOperand(1);
4778 assert(Op0.getValueType() == Op1.getValueType());
4779
4780 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4781 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindolafdb230a2012-04-10 00:16:22 +00004782 if (COp0 && COp0->isNullValue())
Rafael Espindoladecbc432012-04-09 16:06:03 +00004783 Op = Op1;
Rafael Espindolafdb230a2012-04-10 00:16:22 +00004784 else if (COp1 && COp1->isNullValue())
Rafael Espindoladecbc432012-04-09 16:06:03 +00004785 Op = Op0;
4786 else
4787 return false;
4788
4789 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4790
4791 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4792 return false;
4793
4794 return true;
4795}
4796
Dan Gohman475871a2008-07-27 21:46:04 +00004797SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4798 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00004799 EVT VT = N->getValueType(0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00004800
Nate Begeman1d4d4142005-09-01 00:19:25 +00004801 // fold (zext c1) -> c1
Reid Spencer3ed469c2006-11-02 20:25:50 +00004802 if (isa<ConstantSDNode>(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004803 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00004804 // fold (zext (zext x)) -> (zext x)
Chris Lattner310b5782006-05-06 23:06:26 +00004805 // fold (zext (aext x)) -> (zext x)
4806 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004807 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendling6ce610f2009-01-30 22:23:15 +00004808 N0.getOperand(0));
Chris Lattner6007b842006-09-21 06:00:20 +00004809
Chandler Carruthf103b3d2012-01-11 08:41:08 +00004810 // fold (zext (truncate x)) -> (zext x) or
4811 // (zext (truncate x)) -> (truncate x)
4812 // This is valid when the truncated bits of x are already zero.
4813 // FIXME: We should extend this to work for vectors too.
Rafael Espindoladecbc432012-04-09 16:06:03 +00004814 SDValue Op;
4815 APInt KnownZero;
4816 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4817 APInt TruncatedBits =
4818 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4819 APInt(Op.getValueSizeInBits(), 0) :
4820 APInt::getBitsSet(Op.getValueSizeInBits(),
4821 N0.getValueSizeInBits(),
4822 std::min(Op.getValueSizeInBits(),
4823 VT.getSizeInBits()));
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00004824 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruthf103b3d2012-01-11 08:41:08 +00004825 if (VT.bitsGT(Op.getValueType()))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004826 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruthf103b3d2012-01-11 08:41:08 +00004827 if (VT.bitsLT(Op.getValueType()))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004828 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruthf103b3d2012-01-11 08:41:08 +00004829
4830 return Op;
4831 }
4832 }
4833
Evan Chengc88138f2007-03-22 01:54:19 +00004834 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4835 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen2041a0e2007-03-30 21:38:07 +00004836 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greifba36cb52008-08-28 21:40:38 +00004837 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4838 if (NarrowLoad.getNode()) {
Dale Johannesen61734eb2010-05-25 17:50:03 +00004839 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4840 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greifba36cb52008-08-28 21:40:38 +00004841 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen61734eb2010-05-25 17:50:03 +00004842 // CombineTo deleted the truncate, if needed, but not what's under it.
4843 AddToWorkList(oye);
4844 }
Eli Friedmane545d382011-04-16 23:25:34 +00004845 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng0b063de2007-03-23 02:16:52 +00004846 }
Evan Chengc88138f2007-03-22 01:54:19 +00004847 }
4848
Chris Lattner6007b842006-09-21 06:00:20 +00004849 // fold (zext (truncate x)) -> (and x, mask)
4850 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman4e39e9d2010-06-24 14:30:44 +00004851 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman394d6292010-11-03 01:47:46 +00004852
4853 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4854 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4855 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4856 if (NarrowLoad.getNode()) {
4857 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4858 if (NarrowLoad.getNode() != N0.getNode()) {
4859 CombineTo(N0.getNode(), NarrowLoad);
4860 // CombineTo deleted the truncate, if needed, but not what's under it.
4861 AddToWorkList(oye);
4862 }
4863 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4864 }
4865
Dan Gohman475871a2008-07-27 21:46:04 +00004866 SDValue Op = N0.getOperand(0);
Duncan Sands8e4eb092008-06-08 20:54:56 +00004867 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00004868 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Elena Demikhovsky1da58672012-04-22 09:39:03 +00004869 AddToWorkList(Op.getNode());
Duncan Sands8e4eb092008-06-08 20:54:56 +00004870 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00004871 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Elena Demikhovsky1da58672012-04-22 09:39:03 +00004872 AddToWorkList(Op.getNode());
Chris Lattner6007b842006-09-21 06:00:20 +00004873 }
Andrew Trickac6d9be2013-05-25 02:42:55 +00004874 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman87862e72009-12-11 21:31:27 +00004875 N0.getValueType().getScalarType());
Chris Lattner6007b842006-09-21 06:00:20 +00004876 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004877
Dan Gohman97121ba2009-04-08 00:15:30 +00004878 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4879 // if either of the casts is not free.
Chris Lattner111c2282006-09-21 06:14:31 +00004880 if (N0.getOpcode() == ISD::AND &&
4881 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohman97121ba2009-04-08 00:15:30 +00004882 N0.getOperand(1).getOpcode() == ISD::Constant &&
4883 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4884 N0.getValueType()) ||
4885 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman475871a2008-07-27 21:46:04 +00004886 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands8e4eb092008-06-08 20:54:56 +00004887 if (X.getValueType().bitsLT(VT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00004888 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands8e4eb092008-06-08 20:54:56 +00004889 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00004890 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner111c2282006-09-21 06:14:31 +00004891 }
Dan Gohman220a8232008-03-03 23:51:38 +00004892 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad40f8f622010-12-07 08:25:19 +00004893 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickac6d9be2013-05-25 02:42:55 +00004894 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling6ce610f2009-01-30 22:23:15 +00004895 X, DAG.getConstant(Mask, VT));
Chris Lattner111c2282006-09-21 06:14:31 +00004896 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004897
Evan Cheng110dec22005-12-14 02:19:23 +00004898 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Nadav Rotemed9b9342011-02-20 12:37:50 +00004899 // None of the supported targets knows how to perform load and vector_zext
Nadav Rotemfcd96192011-02-27 07:40:43 +00004900 // on vectors in one instruction. We only perform this transformation on
4901 // scalars.
Nadav Rotemed9b9342011-02-20 12:37:50 +00004902 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Duncan Sands25cf2272008-11-24 14:53:14 +00004903 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng03294662008-10-14 21:26:46 +00004904 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004905 bool DoXform = true;
4906 SmallVector<SDNode*, 4> SetCCs;
4907 if (!N0.hasOneUse())
4908 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4909 if (DoXform) {
4910 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004911 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendling6ce610f2009-01-30 22:23:15 +00004912 LN0->getChain(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00004913 LN0->getBasePtr(), N0.getValueType(),
4914 LN0->getMemOperand());
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004915 CombineTo(N, ExtLoad);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004916 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendling6ce610f2009-01-30 22:23:15 +00004917 N0.getValueType(), ExtLoad);
Gabor Greifba36cb52008-08-28 21:40:38 +00004918 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendling6ce610f2009-01-30 22:23:15 +00004919
Andrew Trickac6d9be2013-05-25 02:42:55 +00004920 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004921 ISD::ZERO_EXTEND);
Dan Gohman475871a2008-07-27 21:46:04 +00004922 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004923 }
Evan Cheng110dec22005-12-14 02:19:23 +00004924 }
Chris Lattnerad25d4e2005-12-14 19:05:06 +00004925
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004926 // fold (zext (and/or/xor (load x), cst)) ->
4927 // (and/or/xor (zextload x), (zext cst))
4928 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4929 N0.getOpcode() == ISD::XOR) &&
4930 isa<LoadSDNode>(N0.getOperand(0)) &&
4931 N0.getOperand(1).getOpcode() == ISD::Constant &&
4932 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4933 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4934 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4935 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4936 bool DoXform = true;
4937 SmallVector<SDNode*, 4> SetCCs;
4938 if (!N0.hasOneUse())
4939 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4940 SetCCs, TLI);
4941 if (DoXform) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00004942 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004943 LN0->getChain(), LN0->getBasePtr(),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004944 LN0->getMemoryVT(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00004945 LN0->getMemOperand());
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004946 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4947 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickac6d9be2013-05-25 02:42:55 +00004948 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004949 ExtLoad, DAG.getConstant(Mask, VT));
4950 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickac6d9be2013-05-25 02:42:55 +00004951 SDLoc(N0.getOperand(0)),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004952 N0.getOperand(0).getValueType(), ExtLoad);
4953 CombineTo(N, And);
4954 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickac6d9be2013-05-25 02:42:55 +00004955 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004956 ISD::ZERO_EXTEND);
4957 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4958 }
4959 }
4960 }
4961
Chris Lattnerad25d4e2005-12-14 19:05:06 +00004962 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4963 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greifba36cb52008-08-28 21:40:38 +00004964 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4965 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Cheng466685d2006-10-09 20:57:25 +00004966 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman8a55ce42009-09-23 21:02:20 +00004967 EVT MemVT = LN0->getMemoryVT();
Duncan Sands25cf2272008-11-24 14:53:14 +00004968 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman8a55ce42009-09-23 21:02:20 +00004969 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00004970 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendling6ce610f2009-01-30 22:23:15 +00004971 LN0->getChain(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00004972 LN0->getBasePtr(), MemVT,
4973 LN0->getMemOperand());
Duncan Sandsd4b9c172008-06-13 19:07:40 +00004974 CombineTo(N, ExtLoad);
Gabor Greif12632d22008-08-30 19:29:20 +00004975 CombineTo(N0.getNode(),
Andrew Trickac6d9be2013-05-25 02:42:55 +00004976 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendling6ce610f2009-01-30 22:23:15 +00004977 ExtLoad),
Duncan Sandsd4b9c172008-06-13 19:07:40 +00004978 ExtLoad.getValue(1));
Dan Gohman475871a2008-07-27 21:46:04 +00004979 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sandsd4b9c172008-06-13 19:07:40 +00004980 }
Chris Lattnerad25d4e2005-12-14 19:05:06 +00004981 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004982
Chris Lattner20a35c32007-04-11 05:32:27 +00004983 if (N0.getOpcode() == ISD::SETCC) {
Evan Cheng0a942db2010-05-19 01:08:17 +00004984 if (!LegalOperations && VT.isVector()) {
4985 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4986 // Only do this before legalize for now.
4987 EVT N0VT = N0.getOperand(0).getValueType();
4988 EVT EltVT = VT.getVectorElementType();
4989 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4990 DAG.getConstant(1, EltVT));
Dan Gohman71dc7c92011-05-17 22:20:36 +00004991 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Cheng0a942db2010-05-19 01:08:17 +00004992 // We know that the # elements of the results is the same as the
4993 // # elements of the compare (and the # elements of the compare result
4994 // for that matter). Check to see that they are the same size. If so,
4995 // we know that the element size of the sext'd result matches the
4996 // element size of the compare operands.
Andrew Trickac6d9be2013-05-25 02:42:55 +00004997 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4998 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Cheng0a942db2010-05-19 01:08:17 +00004999 N0.getOperand(1),
5000 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickac6d9be2013-05-25 02:42:55 +00005001 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Evan Cheng0a942db2010-05-19 01:08:17 +00005002 &OneOps[0], OneOps.size()));
Dan Gohman71dc7c92011-05-17 22:20:36 +00005003
5004 // If the desired elements are smaller or larger than the source
5005 // elements we can use a matching integer vector type and then
5006 // truncate/sign extend
5007 EVT MatchingElementType =
5008 EVT::getIntegerVT(*DAG.getContext(),
5009 N0VT.getScalarType().getSizeInBits());
5010 EVT MatchingVectorType =
5011 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5012 N0VT.getVectorNumElements());
5013 SDValue VsetCC =
Andrew Trickac6d9be2013-05-25 02:42:55 +00005014 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman71dc7c92011-05-17 22:20:36 +00005015 N0.getOperand(1),
5016 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickac6d9be2013-05-25 02:42:55 +00005017 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5018 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5019 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Dan Gohman71dc7c92011-05-17 22:20:36 +00005020 &OneOps[0], OneOps.size()));
Evan Cheng0a942db2010-05-19 01:08:17 +00005021 }
5022
5023 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelfdc40a02009-02-17 22:15:04 +00005024 SDValue SCC =
Andrew Trickac6d9be2013-05-25 02:42:55 +00005025 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner20a35c32007-04-11 05:32:27 +00005026 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner1eba01e2007-04-11 06:50:51 +00005027 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greifba36cb52008-08-28 21:40:38 +00005028 if (SCC.getNode()) return SCC;
Chris Lattner20a35c32007-04-11 05:32:27 +00005029 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005030
Evan Cheng9818c042009-12-15 03:00:32 +00005031 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Cheng99b653c2009-12-15 00:41:36 +00005032 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng9818c042009-12-15 03:00:32 +00005033 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Cheng99b653c2009-12-15 00:41:36 +00005034 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5035 N0.hasOneUse()) {
Chris Lattnere0751182011-02-13 19:09:16 +00005036 SDValue ShAmt = N0.getOperand(1);
5037 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng9818c042009-12-15 03:00:32 +00005038 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere0751182011-02-13 19:09:16 +00005039 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng9818c042009-12-15 03:00:32 +00005040 // If the original shl may be shifting out bits, do not perform this
5041 // transformation.
Chris Lattnere0751182011-02-13 19:09:16 +00005042 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5043 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5044 if (ShAmtVal > KnownZeroBits)
Evan Cheng9818c042009-12-15 03:00:32 +00005045 return SDValue();
5046 }
Chris Lattnere0751182011-02-13 19:09:16 +00005047
Andrew Trickac6d9be2013-05-25 02:42:55 +00005048 SDLoc DL(N);
Owen Anderson95771af2011-02-25 21:41:48 +00005049
5050 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere0751182011-02-13 19:09:16 +00005051 if (VT.getSizeInBits() >= 256)
5052 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Anderson95771af2011-02-25 21:41:48 +00005053
Chris Lattnere0751182011-02-13 19:09:16 +00005054 return DAG.getNode(N0.getOpcode(), DL, VT,
5055 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5056 ShAmt);
Evan Cheng99b653c2009-12-15 00:41:36 +00005057 }
5058
Evan Chengb3a3d5e2010-04-28 07:10:39 +00005059 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00005060}
5061
Dan Gohman475871a2008-07-27 21:46:04 +00005062SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5063 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00005064 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00005065
Chris Lattner5ffc0662006-05-05 05:58:59 +00005066 // fold (aext c1) -> c1
Chris Lattner310b5782006-05-06 23:06:26 +00005067 if (isa<ConstantSDNode>(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00005068 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
Chris Lattner5ffc0662006-05-05 05:58:59 +00005069 // fold (aext (aext x)) -> (aext x)
5070 // fold (aext (zext x)) -> (zext x)
5071 // fold (aext (sext x)) -> (sext x)
5072 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5073 N0.getOpcode() == ISD::ZERO_EXTEND ||
5074 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickac6d9be2013-05-25 02:42:55 +00005075 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00005076
Evan Chengc88138f2007-03-22 01:54:19 +00005077 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5078 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5079 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greifba36cb52008-08-28 21:40:38 +00005080 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5081 if (NarrowLoad.getNode()) {
Dale Johannesen86234c32010-05-25 18:47:23 +00005082 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5083 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greifba36cb52008-08-28 21:40:38 +00005084 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen86234c32010-05-25 18:47:23 +00005085 // CombineTo deleted the truncate, if needed, but not what's under it.
5086 AddToWorkList(oye);
5087 }
Eli Friedmane545d382011-04-16 23:25:34 +00005088 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng0b063de2007-03-23 02:16:52 +00005089 }
Evan Chengc88138f2007-03-22 01:54:19 +00005090 }
5091
Chris Lattner84750582006-09-20 06:29:17 +00005092 // fold (aext (truncate x))
5093 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman475871a2008-07-27 21:46:04 +00005094 SDValue TruncOp = N0.getOperand(0);
Chris Lattner84750582006-09-20 06:29:17 +00005095 if (TruncOp.getValueType() == VT)
Sylvestre Ledru94c22712012-09-27 10:14:43 +00005096 return TruncOp; // x iff x size == zext size.
Duncan Sands8e4eb092008-06-08 20:54:56 +00005097 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickac6d9be2013-05-25 02:42:55 +00005098 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5099 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner84750582006-09-20 06:29:17 +00005100 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005101
Dan Gohman97121ba2009-04-08 00:15:30 +00005102 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5103 // if the trunc is not free.
Chris Lattner0e4b9222006-09-21 06:40:43 +00005104 if (N0.getOpcode() == ISD::AND &&
5105 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohman97121ba2009-04-08 00:15:30 +00005106 N0.getOperand(1).getOpcode() == ISD::Constant &&
5107 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5108 N0.getValueType())) {
Dan Gohman475871a2008-07-27 21:46:04 +00005109 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands8e4eb092008-06-08 20:54:56 +00005110 if (X.getValueType().bitsLT(VT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005111 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands8e4eb092008-06-08 20:54:56 +00005112 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005113 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner0e4b9222006-09-21 06:40:43 +00005114 }
Dan Gohman220a8232008-03-03 23:51:38 +00005115 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad40f8f622010-12-07 08:25:19 +00005116 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickac6d9be2013-05-25 02:42:55 +00005117 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling683c9572009-01-30 22:27:33 +00005118 X, DAG.getConstant(Mask, VT));
Chris Lattner0e4b9222006-09-21 06:40:43 +00005119 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005120
Chris Lattner5ffc0662006-05-05 05:58:59 +00005121 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem8c20ec52011-02-24 21:01:34 +00005122 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemfcd96192011-02-27 07:40:43 +00005123 // on vectors in one instruction. We only perform this transformation on
5124 // scalars.
Nadav Rotem8c20ec52011-02-24 21:01:34 +00005125 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Duncan Sands25cf2272008-11-24 14:53:14 +00005126 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng03294662008-10-14 21:26:46 +00005127 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Dan Gohman57fc82d2009-04-09 03:51:29 +00005128 bool DoXform = true;
5129 SmallVector<SDNode*, 4> SetCCs;
5130 if (!N0.hasOneUse())
5131 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5132 if (DoXform) {
5133 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00005134 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman57fc82d2009-04-09 03:51:29 +00005135 LN0->getChain(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005136 LN0->getBasePtr(), N0.getValueType(),
5137 LN0->getMemOperand());
Dan Gohman57fc82d2009-04-09 03:51:29 +00005138 CombineTo(N, ExtLoad);
Andrew Trickac6d9be2013-05-25 02:42:55 +00005139 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman57fc82d2009-04-09 03:51:29 +00005140 N0.getValueType(), ExtLoad);
5141 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickac6d9be2013-05-25 02:42:55 +00005142 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005143 ISD::ANY_EXTEND);
Dan Gohman57fc82d2009-04-09 03:51:29 +00005144 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5145 }
Chris Lattner5ffc0662006-05-05 05:58:59 +00005146 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005147
Chris Lattner5ffc0662006-05-05 05:58:59 +00005148 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5149 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5150 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng83060c52007-03-07 08:07:03 +00005151 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greifba36cb52008-08-28 21:40:38 +00005152 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng466685d2006-10-09 20:57:25 +00005153 N0.hasOneUse()) {
5154 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman8a55ce42009-09-23 21:02:20 +00005155 EVT MemVT = LN0->getMemoryVT();
Andrew Trickac6d9be2013-05-25 02:42:55 +00005156 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
Stuart Hastingsa9011292011-02-16 16:23:55 +00005157 VT, LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005158 MemVT, LN0->getMemOperand());
Chris Lattner5ffc0662006-05-05 05:58:59 +00005159 CombineTo(N, ExtLoad);
Evan Cheng45299662008-08-29 23:20:46 +00005160 CombineTo(N0.getNode(),
Andrew Trickac6d9be2013-05-25 02:42:55 +00005161 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendling683c9572009-01-30 22:27:33 +00005162 N0.getValueType(), ExtLoad),
Chris Lattner5ffc0662006-05-05 05:58:59 +00005163 ExtLoad.getValue(1));
Dan Gohman475871a2008-07-27 21:46:04 +00005164 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner5ffc0662006-05-05 05:58:59 +00005165 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005166
Chris Lattner20a35c32007-04-11 05:32:27 +00005167 if (N0.getOpcode() == ISD::SETCC) {
Evan Cheng0a942db2010-05-19 01:08:17 +00005168 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5169 // Only do this before legalize for now.
5170 if (VT.isVector() && !LegalOperations) {
5171 EVT N0VT = N0.getOperand(0).getValueType();
5172 // We know that the # elements of the results is the same as the
5173 // # elements of the compare (and the # elements of the compare result
5174 // for that matter). Check to see that they are the same size. If so,
5175 // we know that the element size of the sext'd result matches the
5176 // element size of the compare operands.
5177 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickac6d9be2013-05-25 02:42:55 +00005178 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands34727662010-07-12 08:16:59 +00005179 N0.getOperand(1),
5180 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Cheng0a942db2010-05-19 01:08:17 +00005181 // If the desired elements are smaller or larger than the source
5182 // elements we can use a matching integer vector type and then
5183 // truncate/sign extend
5184 else {
Duncan Sands34727662010-07-12 08:16:59 +00005185 EVT MatchingElementType =
5186 EVT::getIntegerVT(*DAG.getContext(),
5187 N0VT.getScalarType().getSizeInBits());
5188 EVT MatchingVectorType =
5189 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5190 N0VT.getVectorNumElements());
5191 SDValue VsetCC =
Andrew Trickac6d9be2013-05-25 02:42:55 +00005192 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands34727662010-07-12 08:16:59 +00005193 N0.getOperand(1),
5194 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickac6d9be2013-05-25 02:42:55 +00005195 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Cheng0a942db2010-05-19 01:08:17 +00005196 }
5197 }
5198
5199 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelfdc40a02009-02-17 22:15:04 +00005200 SDValue SCC =
Andrew Trickac6d9be2013-05-25 02:42:55 +00005201 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner1eba01e2007-04-11 06:50:51 +00005202 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnerc24bbad2007-04-11 16:51:53 +00005203 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greifba36cb52008-08-28 21:40:38 +00005204 if (SCC.getNode())
Chris Lattnerc56a81d2007-04-11 06:43:25 +00005205 return SCC;
Chris Lattner20a35c32007-04-11 05:32:27 +00005206 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005207
Evan Chengb3a3d5e2010-04-28 07:10:39 +00005208 return SDValue();
Chris Lattner5ffc0662006-05-05 05:58:59 +00005209}
5210
Chris Lattner2b4c2792007-10-13 06:35:54 +00005211/// GetDemandedBits - See if the specified operand can be simplified with the
5212/// knowledge that only the bits specified by Mask are used. If so, return the
Dan Gohman475871a2008-07-27 21:46:04 +00005213/// simpler operand, otherwise return a null SDValue.
5214SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner2b4c2792007-10-13 06:35:54 +00005215 switch (V.getOpcode()) {
5216 default: break;
Lang Hames5207bf22011-11-08 18:56:23 +00005217 case ISD::Constant: {
5218 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5219 assert(CV != 0 && "Const value should be ConstSDNode.");
5220 const APInt &CVal = CV->getAPIntValue();
5221 APInt NewVal = CVal & Mask;
Stephen Linb4940152013-07-09 00:44:49 +00005222 if (NewVal != CVal)
Lang Hames5207bf22011-11-08 18:56:23 +00005223 return DAG.getConstant(NewVal, V.getValueType());
Lang Hames5207bf22011-11-08 18:56:23 +00005224 break;
5225 }
Chris Lattner2b4c2792007-10-13 06:35:54 +00005226 case ISD::OR:
5227 case ISD::XOR:
5228 // If the LHS or RHS don't contribute bits to the or, drop them.
5229 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5230 return V.getOperand(1);
5231 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5232 return V.getOperand(0);
5233 break;
Chris Lattnere33544c2007-10-13 06:58:48 +00005234 case ISD::SRL:
5235 // Only look at single-use SRLs.
Gabor Greifba36cb52008-08-28 21:40:38 +00005236 if (!V.getNode()->hasOneUse())
Chris Lattnere33544c2007-10-13 06:58:48 +00005237 break;
5238 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5239 // See if we can recursively simplify the LHS.
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005240 unsigned Amt = RHSC->getZExtValue();
Bill Wendling8509c902009-01-30 22:33:24 +00005241
Dan Gohmancc91d632009-01-03 19:22:06 +00005242 // Watch out for shift count overflow though.
5243 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005244 APInt NewMask = Mask << Amt;
Dan Gohman475871a2008-07-27 21:46:04 +00005245 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling8509c902009-01-30 22:33:24 +00005246 if (SimplifyLHS.getNode())
Andrew Trickac6d9be2013-05-25 02:42:55 +00005247 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnere33544c2007-10-13 06:58:48 +00005248 SimplifyLHS, V.getOperand(1));
Chris Lattnere33544c2007-10-13 06:58:48 +00005249 }
Chris Lattner2b4c2792007-10-13 06:35:54 +00005250 }
Dan Gohman475871a2008-07-27 21:46:04 +00005251 return SDValue();
Chris Lattner2b4c2792007-10-13 06:35:54 +00005252}
5253
Evan Chengc88138f2007-03-22 01:54:19 +00005254/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5255/// bits and then truncated to a narrower type and where N is a multiple
5256/// of number of bits of the narrower type, transform it to a narrower load
5257/// from address + N / num of bits of new type. If the result is to be
5258/// extended, also fold the extension to form a extending load.
Dan Gohman475871a2008-07-27 21:46:04 +00005259SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Chengc88138f2007-03-22 01:54:19 +00005260 unsigned Opc = N->getOpcode();
Dan Gohman4e39e9d2010-06-24 14:30:44 +00005261
Evan Chengc88138f2007-03-22 01:54:19 +00005262 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman475871a2008-07-27 21:46:04 +00005263 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00005264 EVT VT = N->getValueType(0);
5265 EVT ExtVT = VT;
Evan Chengc88138f2007-03-22 01:54:19 +00005266
Dan Gohman7f8613e2008-08-14 20:04:46 +00005267 // This transformation isn't valid for vector loads.
5268 if (VT.isVector())
5269 return SDValue();
5270
Dan Gohmand1996362010-01-09 02:13:55 +00005271 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenge177e302007-03-23 22:13:36 +00005272 // extended to VT.
Evan Chengc88138f2007-03-22 01:54:19 +00005273 if (Opc == ISD::SIGN_EXTEND_INREG) {
5274 ExtType = ISD::SEXTLOAD;
Owen Andersone50ed302009-08-10 22:56:29 +00005275 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman4e39e9d2010-06-24 14:30:44 +00005276 } else if (Opc == ISD::SRL) {
Chris Lattner90b03642010-12-21 18:05:22 +00005277 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman4e39e9d2010-06-24 14:30:44 +00005278 ExtType = ISD::ZEXTLOAD;
5279 N0 = SDValue(N, 0);
5280 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5281 if (!N01) return SDValue();
5282 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5283 VT.getSizeInBits() - N01->getZExtValue());
Evan Chengc88138f2007-03-22 01:54:19 +00005284 }
Richard Osborne4e3740e2011-01-31 17:41:44 +00005285 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5286 return SDValue();
Evan Chengc88138f2007-03-22 01:54:19 +00005287
Owen Andersone50ed302009-08-10 22:56:29 +00005288 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Anderson95771af2011-02-25 21:41:48 +00005289
Chris Lattner7a2a7fa2010-12-22 08:01:44 +00005290 // Do not generate loads of non-round integer types since these can
5291 // be expensive (and would be wrong if the type is not byte sized).
5292 if (!ExtVT.isRound())
5293 return SDValue();
Owen Anderson95771af2011-02-25 21:41:48 +00005294
Evan Chengc88138f2007-03-22 01:54:19 +00005295 unsigned ShAmt = 0;
Chris Lattner7a2a7fa2010-12-22 08:01:44 +00005296 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Chengc88138f2007-03-22 01:54:19 +00005297 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005298 ShAmt = N01->getZExtValue();
Evan Chengc88138f2007-03-22 01:54:19 +00005299 // Is the shift amount a multiple of size of VT?
5300 if ((ShAmt & (EVTBits-1)) == 0) {
5301 N0 = N0.getOperand(0);
Eli Friedmand68eea22009-08-19 08:46:10 +00005302 // Is the load width a multiple of size of VT?
5303 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman475871a2008-07-27 21:46:04 +00005304 return SDValue();
Evan Chengc88138f2007-03-22 01:54:19 +00005305 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00005306
Chris Lattnercbf68df2010-12-22 08:02:57 +00005307 // At this point, we must have a load or else we can't do the transform.
5308 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Anderson95771af2011-02-25 21:41:48 +00005309
Chandler Carruth1c49fda2012-12-11 00:36:57 +00005310 // Because a SRL must be assumed to *need* to zero-extend the high bits
5311 // (as opposed to anyext the high bits), we can't combine the zextload
5312 // lowering of SRL and an sextload.
5313 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5314 return SDValue();
5315
Chris Lattner2831a192010-10-01 05:36:09 +00005316 // If the shift amount is larger than the input type then we're not
5317 // accessing any of the loaded bytes. If the load was a zextload/extload
5318 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercbf68df2010-12-22 08:02:57 +00005319 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattner2831a192010-10-01 05:36:09 +00005320 return SDValue();
Evan Chengc88138f2007-03-22 01:54:19 +00005321 }
5322 }
5323
Dan Gohman394d6292010-11-03 01:47:46 +00005324 // If the load is shifted left (and the result isn't shifted back right),
5325 // we can fold the truncate through the shift.
5326 unsigned ShLeftAmt = 0;
5327 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner4c32bc22010-12-22 07:36:50 +00005328 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman394d6292010-11-03 01:47:46 +00005329 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5330 ShLeftAmt = N01->getZExtValue();
5331 N0 = N0.getOperand(0);
5332 }
5333 }
Owen Anderson95771af2011-02-25 21:41:48 +00005334
Chris Lattner4c32bc22010-12-22 07:36:50 +00005335 // If we haven't found a load, we can't narrow it. Don't transform one with
5336 // multiple uses, this would require adding a new load.
Bill Schmidt89e88e32013-01-14 22:04:38 +00005337 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5338 return SDValue();
5339
5340 // Don't change the width of a volatile load.
5341 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5342 if (LN0->isVolatile())
Chris Lattner4c32bc22010-12-22 07:36:50 +00005343 return SDValue();
Owen Anderson95771af2011-02-25 21:41:48 +00005344
Chris Lattner7a2a7fa2010-12-22 08:01:44 +00005345 // Verify that we are actually reducing a load width here.
Bill Schmidt89e88e32013-01-14 22:04:38 +00005346 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner4c32bc22010-12-22 07:36:50 +00005347 return SDValue();
Owen Anderson95771af2011-02-25 21:41:48 +00005348
Bill Schmidt89e88e32013-01-14 22:04:38 +00005349 // For the transform to be legal, the load must produce only two values
5350 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lin155615d2013-07-08 00:37:03 +00005351 // load, for example, which produces an extra value. Otherwise the
Bill Schmidt89e88e32013-01-14 22:04:38 +00005352 // transformation is not equivalent, and the downstream logic to replace
5353 // uses gets things wrong.
5354 if (LN0->getNumValues() > 2)
5355 return SDValue();
5356
Benjamin Kramerf4eeab42013-07-06 14:05:09 +00005357 // If the load that we're shrinking is an extload and we're not just
5358 // discarding the extension we can't simply shrink the load. Bail.
5359 // TODO: It would be possible to merge the extensions in some cases.
5360 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5361 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5362 return SDValue();
5363
Chris Lattner4c32bc22010-12-22 07:36:50 +00005364 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling8509c902009-01-30 22:33:24 +00005365
Evan Cheng16436df2012-06-26 01:19:33 +00005366 if (PtrType == MVT::Untyped || PtrType.isExtended())
5367 // It's not possible to generate a constant of extended or untyped type.
5368 return SDValue();
5369
Chris Lattner4c32bc22010-12-22 07:36:50 +00005370 // For big endian targets, we need to adjust the offset to the pointer to
5371 // load the correct bytes.
5372 if (TLI.isBigEndian()) {
5373 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5374 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5375 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Chengc88138f2007-03-22 01:54:19 +00005376 }
5377
Chris Lattner4c32bc22010-12-22 07:36:50 +00005378 uint64_t PtrOff = ShAmt / 8;
5379 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickac6d9be2013-05-25 02:42:55 +00005380 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner4c32bc22010-12-22 07:36:50 +00005381 PtrType, LN0->getBasePtr(),
5382 DAG.getConstant(PtrOff, PtrType));
5383 AddToWorkList(NewPtr.getNode());
5384
Chris Lattner7a2a7fa2010-12-22 08:01:44 +00005385 SDValue Load;
5386 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickac6d9be2013-05-25 02:42:55 +00005387 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner7a2a7fa2010-12-22 08:01:44 +00005388 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooperd752e0f2011-11-08 18:42:53 +00005389 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005390 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
Chris Lattner7a2a7fa2010-12-22 08:01:44 +00005391 else
Andrew Trickac6d9be2013-05-25 02:42:55 +00005392 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner7a2a7fa2010-12-22 08:01:44 +00005393 LN0->getPointerInfo().getWithOffset(PtrOff),
5394 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005395 NewAlign, LN0->getTBAAInfo());
Chris Lattner4c32bc22010-12-22 07:36:50 +00005396
5397 // Replace the old load's chain with the new load's chain.
5398 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00005399 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner4c32bc22010-12-22 07:36:50 +00005400
5401 // Shift the result left, if we've swallowed a left shift.
5402 SDValue Result = Load;
5403 if (ShLeftAmt != 0) {
Owen Anderson95771af2011-02-25 21:41:48 +00005404 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner4c32bc22010-12-22 07:36:50 +00005405 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5406 ShImmTy = VT;
Paul Redmond5c974502013-02-12 15:21:21 +00005407 // If the shift amount is as large as the result size (but, presumably,
5408 // no larger than the source) then the useful bits of the result are
5409 // zero; we can't simply return the shortened shift, because the result
5410 // of that operation is undefined.
5411 if (ShLeftAmt >= VT.getSizeInBits())
5412 Result = DAG.getConstant(0, VT);
5413 else
Andrew Trickac6d9be2013-05-25 02:42:55 +00005414 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond5c974502013-02-12 15:21:21 +00005415 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner4c32bc22010-12-22 07:36:50 +00005416 }
5417
5418 // Return the new loaded value.
5419 return Result;
Evan Chengc88138f2007-03-22 01:54:19 +00005420}
5421
Dan Gohman475871a2008-07-27 21:46:04 +00005422SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5423 SDValue N0 = N->getOperand(0);
5424 SDValue N1 = N->getOperand(1);
Owen Andersone50ed302009-08-10 22:56:29 +00005425 EVT VT = N->getValueType(0);
5426 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman87862e72009-12-11 21:31:27 +00005427 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohmand1996362010-01-09 02:13:55 +00005428 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelfdc40a02009-02-17 22:15:04 +00005429
Nate Begeman1d4d4142005-09-01 00:19:25 +00005430 // fold (sext_in_reg c1) -> c1
Chris Lattnereaeda562006-05-08 20:59:41 +00005431 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickac6d9be2013-05-25 02:42:55 +00005432 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelfdc40a02009-02-17 22:15:04 +00005433
Chris Lattner541a24f2006-05-06 22:43:44 +00005434 // If the input is already sign extended, just drop the extension.
Dan Gohman87862e72009-12-11 21:31:27 +00005435 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattneree4ea922006-05-06 09:30:03 +00005436 return N0;
Scott Michelfdc40a02009-02-17 22:15:04 +00005437
Nate Begeman646d7e22005-09-02 21:18:40 +00005438 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5439 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Linb4940152013-07-09 00:44:49 +00005440 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickac6d9be2013-05-25 02:42:55 +00005441 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling8509c902009-01-30 22:33:24 +00005442 N0.getOperand(0), N1);
Chris Lattner4b37e872006-05-08 21:18:59 +00005443
Dan Gohman75dcf082008-07-31 00:50:31 +00005444 // fold (sext_in_reg (sext x)) -> (sext x)
5445 // fold (sext_in_reg (aext x)) -> (sext x)
5446 // if x is small enough.
5447 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5448 SDValue N00 = N0.getOperand(0);
Evan Cheng003d7c42010-04-16 22:26:19 +00005449 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5450 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00005451 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman75dcf082008-07-31 00:50:31 +00005452 }
5453
Chris Lattner95a5e052007-04-17 19:03:21 +00005454 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005455 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00005456 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelfdc40a02009-02-17 22:15:04 +00005457
Chris Lattner95a5e052007-04-17 19:03:21 +00005458 // fold operands of sext_in_reg based on knowledge that the top bits are not
5459 // demanded.
Dan Gohman475871a2008-07-27 21:46:04 +00005460 if (SimplifyDemandedBits(SDValue(N, 0)))
5461 return SDValue(N, 0);
Scott Michelfdc40a02009-02-17 22:15:04 +00005462
Evan Chengc88138f2007-03-22 01:54:19 +00005463 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5464 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman475871a2008-07-27 21:46:04 +00005465 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00005466 if (NarrowLoad.getNode())
Evan Chengc88138f2007-03-22 01:54:19 +00005467 return NarrowLoad;
5468
Bill Wendling8509c902009-01-30 22:33:24 +00005469 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru94c22712012-09-27 10:14:43 +00005470 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner4b37e872006-05-08 21:18:59 +00005471 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5472 if (N0.getOpcode() == ISD::SRL) {
5473 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman87862e72009-12-11 21:31:27 +00005474 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru94c22712012-09-27 10:14:43 +00005475 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner4b37e872006-05-08 21:18:59 +00005476 // extended enough.
Dan Gohmanea859be2007-06-22 14:59:07 +00005477 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman87862e72009-12-11 21:31:27 +00005478 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickac6d9be2013-05-25 02:42:55 +00005479 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling8509c902009-01-30 22:33:24 +00005480 N0.getOperand(0), N0.getOperand(1));
Chris Lattner4b37e872006-05-08 21:18:59 +00005481 }
5482 }
Evan Chengc88138f2007-03-22 01:54:19 +00005483
Nate Begemanded49632005-10-13 03:11:28 +00005484 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelfdc40a02009-02-17 22:15:04 +00005485 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greifba36cb52008-08-28 21:40:38 +00005486 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohmanb625f2f2008-01-30 00:15:11 +00005487 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sands25cf2272008-11-24 14:53:14 +00005488 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng03294662008-10-14 21:26:46 +00005489 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Cheng466685d2006-10-09 20:57:25 +00005490 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00005491 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling8509c902009-01-30 22:33:24 +00005492 LN0->getChain(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005493 LN0->getBasePtr(), EVT,
5494 LN0->getMemOperand());
Chris Lattnerd4771842005-12-14 19:25:30 +00005495 CombineTo(N, ExtLoad);
Gabor Greifba36cb52008-08-28 21:40:38 +00005496 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Elena Demikhovsky4b977312012-12-19 07:50:20 +00005497 AddToWorkList(ExtLoad.getNode());
Dan Gohman475871a2008-07-27 21:46:04 +00005498 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begemanded49632005-10-13 03:11:28 +00005499 }
Sylvestre Ledru94c22712012-09-27 10:14:43 +00005500 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greifba36cb52008-08-28 21:40:38 +00005501 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng83060c52007-03-07 08:07:03 +00005502 N0.hasOneUse() &&
Dan Gohmanb625f2f2008-01-30 00:15:11 +00005503 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sands25cf2272008-11-24 14:53:14 +00005504 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng03294662008-10-14 21:26:46 +00005505 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Cheng466685d2006-10-09 20:57:25 +00005506 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00005507 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling8509c902009-01-30 22:33:24 +00005508 LN0->getChain(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005509 LN0->getBasePtr(), EVT,
5510 LN0->getMemOperand());
Chris Lattnerd4771842005-12-14 19:25:30 +00005511 CombineTo(N, ExtLoad);
Gabor Greifba36cb52008-08-28 21:40:38 +00005512 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman475871a2008-07-27 21:46:04 +00005513 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begemanded49632005-10-13 03:11:28 +00005514 }
Evan Cheng9568e5c2011-06-21 06:01:08 +00005515
5516 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5517 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5518 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5519 N0.getOperand(1), false);
5520 if (BSwap.getNode() != 0)
Andrew Trickac6d9be2013-05-25 02:42:55 +00005521 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng9568e5c2011-06-21 06:01:08 +00005522 BSwap, N1);
5523 }
5524
Dan Gohman475871a2008-07-27 21:46:04 +00005525 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00005526}
5527
Dan Gohman475871a2008-07-27 21:46:04 +00005528SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5529 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00005530 EVT VT = N->getValueType(0);
Nadav Rotem7e413e9c2012-02-03 13:18:25 +00005531 bool isLE = TLI.isLittleEndian();
Nate Begeman1d4d4142005-09-01 00:19:25 +00005532
5533 // noop truncate
5534 if (N0.getValueType() == N->getValueType(0))
Nate Begeman83e75ec2005-09-06 04:43:02 +00005535 return N0;
Nate Begeman1d4d4142005-09-01 00:19:25 +00005536 // fold (truncate c1) -> c1
Chris Lattner310b5782006-05-06 23:06:26 +00005537 if (isa<ConstantSDNode>(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00005538 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00005539 // fold (truncate (truncate x)) -> (truncate x)
5540 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickac6d9be2013-05-25 02:42:55 +00005541 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman1d4d4142005-09-01 00:19:25 +00005542 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner7f893c02010-04-07 18:13:33 +00005543 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5544 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattnerb72773b2006-05-05 22:56:26 +00005545 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands8e4eb092008-06-08 20:54:56 +00005546 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman1d4d4142005-09-01 00:19:25 +00005547 // if the source is smaller than the dest, we still need an extend
Andrew Trickac6d9be2013-05-25 02:42:55 +00005548 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling67a67682009-01-30 22:44:24 +00005549 N0.getOperand(0));
Craig Topper0eb5dad2012-09-29 07:18:53 +00005550 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman1d4d4142005-09-01 00:19:25 +00005551 // if the source is larger than the dest, than we just need the truncate
Andrew Trickac6d9be2013-05-25 02:42:55 +00005552 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper0eb5dad2012-09-29 07:18:53 +00005553 // if the source and dest are the same type, we can drop both the extend
5554 // and the truncate.
5555 return N0.getOperand(0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00005556 }
Evan Cheng007b69e2007-03-21 20:14:05 +00005557
Nadav Rotemcc870a82012-02-05 11:39:23 +00005558 // Fold extract-and-trunc into a narrow extract. For example:
5559 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5560 // i32 y = TRUNCATE(i64 x)
5561 // -- becomes --
5562 // v16i8 b = BITCAST (v2i64 val)
5563 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5564 //
5565 // Note: We only run this optimization after type legalization (which often
Nadav Rotem7e413e9c2012-02-03 13:18:25 +00005566 // creates this pattern) and before operation legalization after which
5567 // we need to be more careful about the vector instructions that we generate.
5568 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5569 LegalTypes && !LegalOperations && N0->hasOneUse()) {
5570
5571 EVT VecTy = N0.getOperand(0).getValueType();
5572 EVT ExTy = N0.getValueType();
5573 EVT TrTy = N->getValueType(0);
5574
5575 unsigned NumElem = VecTy.getVectorNumElements();
5576 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5577
5578 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5579 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5580
5581 SDValue EltNo = N0->getOperand(1);
5582 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5583 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellard425b76c2013-08-05 22:22:01 +00005584 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem7e413e9c2012-02-03 13:18:25 +00005585 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5586
Andrew Trickac6d9be2013-05-25 02:42:55 +00005587 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem7e413e9c2012-02-03 13:18:25 +00005588 NVT, N0.getOperand(0));
5589
5590 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickac6d9be2013-05-25 02:42:55 +00005591 SDLoc(N), TrTy, V,
Jim Grosbacha249f7d2012-05-08 20:56:07 +00005592 DAG.getConstant(Index, IndexTy));
Nadav Rotem7e413e9c2012-02-03 13:18:25 +00005593 }
5594 }
5595
Arnold Schwaighoferc46e2df2013-02-20 21:33:32 +00005596 // Fold a series of buildvector, bitcast, and truncate if possible.
5597 // For example fold
5598 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5599 // (2xi32 (buildvector x, y)).
5600 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5601 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5602 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5603 N0.getOperand(0).hasOneUse()) {
5604
5605 SDValue BuildVect = N0.getOperand(0);
5606 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5607 EVT TruncVecEltTy = VT.getVectorElementType();
5608
5609 // Check that the element types match.
5610 if (BuildVectEltTy == TruncVecEltTy) {
5611 // Now we only need to compute the offset of the truncated elements.
5612 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5613 unsigned TruncVecNumElts = VT.getVectorNumElements();
5614 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5615
5616 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5617 "Invalid number of elements");
5618
5619 SmallVector<SDValue, 8> Opnds;
5620 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5621 Opnds.push_back(BuildVect.getOperand(i));
5622
Andrew Trickac6d9be2013-05-25 02:42:55 +00005623 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
Arnold Schwaighoferc46e2df2013-02-20 21:33:32 +00005624 Opnds.size());
5625 }
5626 }
5627
Chris Lattner2b4c2792007-10-13 06:35:54 +00005628 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem8c20ec52011-02-24 21:01:34 +00005629 // only the low bits are being used.
5630 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemfcd96192011-02-27 07:40:43 +00005631 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem8c20ec52011-02-24 21:01:34 +00005632 // may have different active low bits.
5633 if (!VT.isVector()) {
5634 SDValue Shorter =
5635 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5636 VT.getSizeInBits()));
5637 if (Shorter.getNode())
Andrew Trickac6d9be2013-05-25 02:42:55 +00005638 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem8c20ec52011-02-24 21:01:34 +00005639 }
Nate Begeman3df4d522005-10-12 20:40:40 +00005640 // fold (truncate (load x)) -> (smaller load x)
Evan Cheng007b69e2007-03-21 20:14:05 +00005641 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman4e39e9d2010-06-24 14:30:44 +00005642 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5643 SDValue Reduced = ReduceLoadWidth(N);
5644 if (Reduced.getNode())
5645 return Reduced;
5646 }
Michael Liao07edaf32012-10-17 23:45:54 +00005647 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5648 // where ... are all 'undef'.
5649 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5650 SmallVector<EVT, 8> VTs;
5651 SDValue V;
5652 unsigned Idx = 0;
5653 unsigned NumDefs = 0;
5654
5655 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5656 SDValue X = N0.getOperand(i);
5657 if (X.getOpcode() != ISD::UNDEF) {
5658 V = X;
5659 Idx = i;
5660 NumDefs++;
5661 }
5662 // Stop if more than one members are non-undef.
5663 if (NumDefs > 1)
5664 break;
5665 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5666 VT.getVectorElementType(),
5667 X.getValueType().getVectorNumElements()));
5668 }
5669
5670 if (NumDefs == 0)
5671 return DAG.getUNDEF(VT);
5672
5673 if (NumDefs == 1) {
5674 assert(V.getNode() && "The single defined operand is empty!");
5675 SmallVector<SDValue, 8> Opnds;
5676 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5677 if (i != Idx) {
5678 Opnds.push_back(DAG.getUNDEF(VTs[i]));
5679 continue;
5680 }
Andrew Trickac6d9be2013-05-25 02:42:55 +00005681 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Michael Liao07edaf32012-10-17 23:45:54 +00005682 AddToWorkList(NV.getNode());
5683 Opnds.push_back(NV);
5684 }
Andrew Trickac6d9be2013-05-25 02:42:55 +00005685 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
Michael Liao07edaf32012-10-17 23:45:54 +00005686 &Opnds[0], Opnds.size());
5687 }
5688 }
Dan Gohman4e39e9d2010-06-24 14:30:44 +00005689
5690 // Simplify the operands using demanded-bits information.
5691 if (!VT.isVector() &&
5692 SimplifyDemandedBits(SDValue(N, 0)))
5693 return SDValue(N, 0);
5694
Evan Chenge5b51ac2010-04-17 06:13:15 +00005695 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00005696}
5697
Evan Cheng9bfa03c2008-05-12 23:04:07 +00005698static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman475871a2008-07-27 21:46:04 +00005699 SDValue Elt = N->getOperand(i);
Evan Cheng9bfa03c2008-05-12 23:04:07 +00005700 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greifba36cb52008-08-28 21:40:38 +00005701 return Elt.getNode();
5702 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Cheng9bfa03c2008-05-12 23:04:07 +00005703}
5704
5705/// CombineConsecutiveLoads - build_pair (load, load) -> load
Scott Michelfdc40a02009-02-17 22:15:04 +00005706/// if load locations are consecutive.
Owen Andersone50ed302009-08-10 22:56:29 +00005707SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Cheng9bfa03c2008-05-12 23:04:07 +00005708 assert(N->getOpcode() == ISD::BUILD_PAIR);
5709
Nate Begemanabc01992009-06-05 21:37:30 +00005710 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5711 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerfa459012010-09-21 16:08:50 +00005712 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5713 LD1->getPointerInfo().getAddrSpace() !=
5714 LD2->getPointerInfo().getAddrSpace())
Dan Gohman475871a2008-07-27 21:46:04 +00005715 return SDValue();
Owen Andersone50ed302009-08-10 22:56:29 +00005716 EVT LD1VT = LD1->getValueType(0);
Bill Wendling67a67682009-01-30 22:44:24 +00005717
Evan Cheng9bfa03c2008-05-12 23:04:07 +00005718 if (ISD::isNON_EXTLoad(LD2) &&
5719 LD2->hasOneUse() &&
Duncan Sandsd4b9c172008-06-13 19:07:40 +00005720 // If both are volatile this would reduce the number of volatile loads.
5721 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begemanabc01992009-06-05 21:37:30 +00005722 !LD1->isVolatile() &&
5723 !LD2->isVolatile() &&
Evan Cheng64fa4a92009-12-09 01:36:00 +00005724 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begemanabc01992009-06-05 21:37:30 +00005725 unsigned Align = LD1->getAlignment();
Micah Villmow3574eca2012-10-08 16:38:25 +00005726 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson23b9b192009-08-12 00:36:31 +00005727 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling67a67682009-01-30 22:44:24 +00005728
Duncan Sandsd4b9c172008-06-13 19:07:40 +00005729 if (NewAlign <= Align &&
Duncan Sands25cf2272008-11-24 14:53:14 +00005730 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00005731 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerfa459012010-09-21 16:08:50 +00005732 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooperd752e0f2011-11-08 18:42:53 +00005733 false, false, false, Align);
Evan Cheng9bfa03c2008-05-12 23:04:07 +00005734 }
Bill Wendling67a67682009-01-30 22:44:24 +00005735
Dan Gohman475871a2008-07-27 21:46:04 +00005736 return SDValue();
Evan Cheng9bfa03c2008-05-12 23:04:07 +00005737}
5738
Wesley Peckbf17cfa2010-11-23 03:31:01 +00005739SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman475871a2008-07-27 21:46:04 +00005740 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00005741 EVT VT = N->getValueType(0);
Chris Lattner94683772005-12-23 05:30:37 +00005742
Dan Gohman7f321562007-06-25 16:23:39 +00005743 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5744 // Only do this before legalize, since afterward the target may be depending
5745 // on the bitconvert.
5746 // First check to see if this is all constant.
Duncan Sands25cf2272008-11-24 14:53:14 +00005747 if (!LegalTypes &&
Gabor Greifba36cb52008-08-28 21:40:38 +00005748 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands83ec4b62008-06-06 12:08:01 +00005749 VT.isVector()) {
Dan Gohman7f321562007-06-25 16:23:39 +00005750 bool isSimple = true;
5751 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5752 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5753 N0.getOperand(i).getOpcode() != ISD::Constant &&
5754 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
Scott Michelfdc40a02009-02-17 22:15:04 +00005755 isSimple = false;
Dan Gohman7f321562007-06-25 16:23:39 +00005756 break;
5757 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005758
Owen Andersone50ed302009-08-10 22:56:29 +00005759 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands83ec4b62008-06-06 12:08:01 +00005760 assert(!DestEltVT.isVector() &&
Dan Gohman7f321562007-06-25 16:23:39 +00005761 "Element type of vector ValueType must not be vector!");
Bill Wendling67a67682009-01-30 22:44:24 +00005762 if (isSimple)
Wesley Peckbf17cfa2010-11-23 03:31:01 +00005763 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohman7f321562007-06-25 16:23:39 +00005764 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005765
Dan Gohman3dd168d2008-09-05 01:58:21 +00005766 // If the input is a constant, let getNode fold it.
Chris Lattner94683772005-12-23 05:30:37 +00005767 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005768 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Dan Gohmana407ca12009-08-10 23:15:10 +00005769 if (Res.getNode() != N) {
5770 if (!LegalOperations ||
5771 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5772 return Res;
5773
5774 // Folding it resulted in an illegal node, and it's too late to
5775 // do that. Clean up the old node and forego the transformation.
5776 // Ideally this won't happen very often, because instcombine
5777 // and the earlier dagcombine runs (where illegal nodes are
5778 // permitted) should have folded most of them already.
5779 DAG.DeleteNode(Res.getNode());
5780 }
Chris Lattner94683772005-12-23 05:30:37 +00005781 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005782
Bill Wendling67a67682009-01-30 22:44:24 +00005783 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peckbf17cfa2010-11-23 03:31:01 +00005784 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickac6d9be2013-05-25 02:42:55 +00005785 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling67a67682009-01-30 22:44:24 +00005786 N0.getOperand(0));
Chris Lattner6258fb22006-04-02 02:53:43 +00005787
Chris Lattner57104102005-12-23 05:44:41 +00005788 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng513da432007-10-06 08:19:55 +00005789 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greifba36cb52008-08-28 21:40:38 +00005790 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sandsd4b9c172008-06-13 19:07:40 +00005791 // Do not change the width of a volatile load.
5792 !cast<LoadSDNode>(N0)->isVolatile() &&
Matt Arsenault509a4922013-11-15 04:42:23 +00005793 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
5794 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Cheng466685d2006-10-09 20:57:25 +00005795 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmow3574eca2012-10-08 16:38:25 +00005796 unsigned Align = TLI.getDataLayout()->
Owen Anderson23b9b192009-08-12 00:36:31 +00005797 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Cheng59d5b682007-05-07 21:27:48 +00005798 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling67a67682009-01-30 22:44:24 +00005799
Evan Cheng59d5b682007-05-07 21:27:48 +00005800 if (Align <= OrigAlign) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005801 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerfa459012010-09-21 16:08:50 +00005802 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene1e559442010-02-15 17:00:31 +00005803 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005804 LN0->isInvariant(), OrigAlign,
5805 LN0->getTBAAInfo());
Evan Cheng59d5b682007-05-07 21:27:48 +00005806 AddToWorkList(N);
Gabor Greif12632d22008-08-30 19:29:20 +00005807 CombineTo(N0.getNode(),
Andrew Trickac6d9be2013-05-25 02:42:55 +00005808 DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling67a67682009-01-30 22:44:24 +00005809 N0.getValueType(), Load),
Evan Cheng59d5b682007-05-07 21:27:48 +00005810 Load.getValue(1));
5811 return Load;
5812 }
Chris Lattner57104102005-12-23 05:44:41 +00005813 }
Duncan Sandsd4b9c172008-06-13 19:07:40 +00005814
Bill Wendling67a67682009-01-30 22:44:24 +00005815 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5816 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner3bd39d42008-01-27 17:42:27 +00005817 // This often reduces constant pool loads.
Tom Stellard1f67c632013-07-23 23:55:03 +00005818 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5819 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem91a7e012012-09-13 14:54:28 +00005820 N0.getNode()->hasOneUse() && VT.isInteger() &&
5821 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005822 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling67a67682009-01-30 22:44:24 +00005823 N0.getOperand(0));
Gabor Greifba36cb52008-08-28 21:40:38 +00005824 AddToWorkList(NewConv.getNode());
Scott Michelfdc40a02009-02-17 22:15:04 +00005825
Duncan Sands83ec4b62008-06-06 12:08:01 +00005826 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner3bd39d42008-01-27 17:42:27 +00005827 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickac6d9be2013-05-25 02:42:55 +00005828 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling67a67682009-01-30 22:44:24 +00005829 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner3bd39d42008-01-27 17:42:27 +00005830 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickac6d9be2013-05-25 02:42:55 +00005831 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling67a67682009-01-30 22:44:24 +00005832 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner3bd39d42008-01-27 17:42:27 +00005833 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005834
Bill Wendling67a67682009-01-30 22:44:24 +00005835 // fold (bitconvert (fcopysign cst, x)) ->
5836 // (or (and (bitconvert x), sign), (and cst, (not sign)))
5837 // Note that we don't handle (copysign x, cst) because this can always be
5838 // folded to an fneg or fabs.
Gabor Greifba36cb52008-08-28 21:40:38 +00005839 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattnerf32aac32008-01-27 23:32:17 +00005840 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands83ec4b62008-06-06 12:08:01 +00005841 VT.isInteger() && !VT.isVector()) {
5842 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson23b9b192009-08-12 00:36:31 +00005843 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner2392ae72010-04-15 04:48:01 +00005844 if (isTypeLegal(IntXVT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005845 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling67a67682009-01-30 22:44:24 +00005846 IntXVT, N0.getOperand(1));
Duncan Sands25cf2272008-11-24 14:53:14 +00005847 AddToWorkList(X.getNode());
Chris Lattner3bd39d42008-01-27 17:42:27 +00005848
Duncan Sands25cf2272008-11-24 14:53:14 +00005849 // If X has a different width than the result/lhs, sext it or truncate it.
5850 unsigned VTWidth = VT.getSizeInBits();
5851 if (OrigXWidth < VTWidth) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005852 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Duncan Sands25cf2272008-11-24 14:53:14 +00005853 AddToWorkList(X.getNode());
5854 } else if (OrigXWidth > VTWidth) {
5855 // To get the sign bit in the right place, we have to shift it right
5856 // before truncating.
Andrew Trickac6d9be2013-05-25 02:42:55 +00005857 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling67a67682009-01-30 22:44:24 +00005858 X.getValueType(), X,
Duncan Sands25cf2272008-11-24 14:53:14 +00005859 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5860 AddToWorkList(X.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00005861 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Duncan Sands25cf2272008-11-24 14:53:14 +00005862 AddToWorkList(X.getNode());
5863 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005864
Duncan Sands25cf2272008-11-24 14:53:14 +00005865 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickac6d9be2013-05-25 02:42:55 +00005866 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling67a67682009-01-30 22:44:24 +00005867 X, DAG.getConstant(SignBit, VT));
Duncan Sands25cf2272008-11-24 14:53:14 +00005868 AddToWorkList(X.getNode());
Chris Lattner3bd39d42008-01-27 17:42:27 +00005869
Andrew Trickac6d9be2013-05-25 02:42:55 +00005870 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling67a67682009-01-30 22:44:24 +00005871 VT, N0.getOperand(0));
Andrew Trickac6d9be2013-05-25 02:42:55 +00005872 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling67a67682009-01-30 22:44:24 +00005873 Cst, DAG.getConstant(~SignBit, VT));
Duncan Sands25cf2272008-11-24 14:53:14 +00005874 AddToWorkList(Cst.getNode());
Chris Lattner3bd39d42008-01-27 17:42:27 +00005875
Andrew Trickac6d9be2013-05-25 02:42:55 +00005876 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sands25cf2272008-11-24 14:53:14 +00005877 }
Chris Lattner3bd39d42008-01-27 17:42:27 +00005878 }
Evan Cheng9bfa03c2008-05-12 23:04:07 +00005879
Sylvestre Ledru94c22712012-09-27 10:14:43 +00005880 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Cheng9bfa03c2008-05-12 23:04:07 +00005881 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greifba36cb52008-08-28 21:40:38 +00005882 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5883 if (CombineLD.getNode())
Evan Cheng9bfa03c2008-05-12 23:04:07 +00005884 return CombineLD;
5885 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005886
Dan Gohman475871a2008-07-27 21:46:04 +00005887 return SDValue();
Chris Lattner94683772005-12-23 05:30:37 +00005888}
5889
Dan Gohman475871a2008-07-27 21:46:04 +00005890SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Andersone50ed302009-08-10 22:56:29 +00005891 EVT VT = N->getValueType(0);
Evan Cheng9bfa03c2008-05-12 23:04:07 +00005892 return CombineConsecutiveLoads(N, VT);
5893}
5894
Wesley Peckbf17cfa2010-11-23 03:31:01 +00005895/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
Scott Michelfdc40a02009-02-17 22:15:04 +00005896/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
Chris Lattner6258fb22006-04-02 02:53:43 +00005897/// destination element value type.
Dan Gohman475871a2008-07-27 21:46:04 +00005898SDValue DAGCombiner::
Wesley Peckbf17cfa2010-11-23 03:31:01 +00005899ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Andersone50ed302009-08-10 22:56:29 +00005900 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelfdc40a02009-02-17 22:15:04 +00005901
Chris Lattner6258fb22006-04-02 02:53:43 +00005902 // If this is already the right type, we're done.
Dan Gohman475871a2008-07-27 21:46:04 +00005903 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelfdc40a02009-02-17 22:15:04 +00005904
Duncan Sands83ec4b62008-06-06 12:08:01 +00005905 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5906 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelfdc40a02009-02-17 22:15:04 +00005907
Chris Lattner6258fb22006-04-02 02:53:43 +00005908 // If this is a conversion of N elements of one type to N elements of another
5909 // type, convert each element. This handles FP<->INT cases.
5910 if (SrcBitSize == DstBitSize) {
Nate Begemane0efc212010-07-27 18:02:18 +00005911 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5912 BV->getValueType(0).getVectorNumElements());
5913
5914 // Due to the FP element handling below calling this routine recursively,
5915 // we can end up with a scalar-to-vector node here.
5916 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickac6d9be2013-05-25 02:42:55 +00005917 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5918 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begemane0efc212010-07-27 18:02:18 +00005919 DstEltVT, BV->getOperand(0)));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00005920
Dan Gohman475871a2008-07-27 21:46:04 +00005921 SmallVector<SDValue, 8> Ops;
Dan Gohman7f321562007-06-25 16:23:39 +00005922 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilsonb1303d02009-04-13 22:05:19 +00005923 SDValue Op = BV->getOperand(i);
5924 // If the vector element type is not legal, the BUILD_VECTOR operands
5925 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonc8851652009-04-20 17:27:09 +00005926 if (Op.getValueType() != SrcEltVT)
Andrew Trickac6d9be2013-05-25 02:42:55 +00005927 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
5928 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilsonb1303d02009-04-13 22:05:19 +00005929 DstEltVT, Op));
Gabor Greifba36cb52008-08-28 21:40:38 +00005930 AddToWorkList(Ops.back().getNode());
Chris Lattner3e104b12006-04-08 04:15:24 +00005931 }
Andrew Trickac6d9be2013-05-25 02:42:55 +00005932 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga87008d2009-02-25 22:49:59 +00005933 &Ops[0], Ops.size());
Chris Lattner6258fb22006-04-02 02:53:43 +00005934 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005935
Chris Lattner6258fb22006-04-02 02:53:43 +00005936 // Otherwise, we're growing or shrinking the elements. To avoid having to
5937 // handle annoying details of growing/shrinking FP values, we convert them to
5938 // int first.
Duncan Sands83ec4b62008-06-06 12:08:01 +00005939 if (SrcEltVT.isFloatingPoint()) {
Chris Lattner6258fb22006-04-02 02:53:43 +00005940 // Convert the input float vector to a int vector where the elements are the
5941 // same sizes.
Owen Anderson825b72b2009-08-11 20:47:22 +00005942 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson23b9b192009-08-12 00:36:31 +00005943 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peckbf17cfa2010-11-23 03:31:01 +00005944 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattner6258fb22006-04-02 02:53:43 +00005945 SrcEltVT = IntVT;
5946 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005947
Chris Lattner6258fb22006-04-02 02:53:43 +00005948 // Now we know the input is an integer vector. If the output is a FP type,
5949 // convert to integer first, then to FP of the right size.
Duncan Sands83ec4b62008-06-06 12:08:01 +00005950 if (DstEltVT.isFloatingPoint()) {
Owen Anderson825b72b2009-08-11 20:47:22 +00005951 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson23b9b192009-08-12 00:36:31 +00005952 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peckbf17cfa2010-11-23 03:31:01 +00005953 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelfdc40a02009-02-17 22:15:04 +00005954
Chris Lattner6258fb22006-04-02 02:53:43 +00005955 // Next, convert to FP elements of the same size.
Wesley Peckbf17cfa2010-11-23 03:31:01 +00005956 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattner6258fb22006-04-02 02:53:43 +00005957 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005958
Chris Lattner6258fb22006-04-02 02:53:43 +00005959 // Okay, we know the src/dst types are both integers of differing types.
5960 // Handling growing first.
Duncan Sands83ec4b62008-06-06 12:08:01 +00005961 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattner6258fb22006-04-02 02:53:43 +00005962 if (SrcBitSize < DstBitSize) {
5963 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelfdc40a02009-02-17 22:15:04 +00005964
Dan Gohman475871a2008-07-27 21:46:04 +00005965 SmallVector<SDValue, 8> Ops;
Dan Gohman7f321562007-06-25 16:23:39 +00005966 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattner6258fb22006-04-02 02:53:43 +00005967 i += NumInputsPerOutput) {
5968 bool isLE = TLI.isLittleEndian();
Dan Gohman220a8232008-03-03 23:51:38 +00005969 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattner6258fb22006-04-02 02:53:43 +00005970 bool EltIsUndef = true;
5971 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5972 // Shift the previously computed bits over.
5973 NewBits <<= SrcBitSize;
Dan Gohman475871a2008-07-27 21:46:04 +00005974 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattner6258fb22006-04-02 02:53:43 +00005975 if (Op.getOpcode() == ISD::UNDEF) continue;
5976 EltIsUndef = false;
Scott Michelfdc40a02009-02-17 22:15:04 +00005977
Jay Foad40f8f622010-12-07 08:25:19 +00005978 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohman58c25872010-04-12 02:24:01 +00005979 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattner6258fb22006-04-02 02:53:43 +00005980 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005981
Chris Lattner6258fb22006-04-02 02:53:43 +00005982 if (EltIsUndef)
Dale Johannesene8d72302009-02-06 23:05:02 +00005983 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattner6258fb22006-04-02 02:53:43 +00005984 else
5985 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5986 }
5987
Owen Anderson23b9b192009-08-12 00:36:31 +00005988 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Andrew Trickac6d9be2013-05-25 02:42:55 +00005989 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga87008d2009-02-25 22:49:59 +00005990 &Ops[0], Ops.size());
Chris Lattner6258fb22006-04-02 02:53:43 +00005991 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005992
Chris Lattner6258fb22006-04-02 02:53:43 +00005993 // Finally, this must be the case where we are shrinking elements: each input
5994 // turns into multiple outputs.
Evan Chengefec7512008-02-18 23:04:32 +00005995 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattner6258fb22006-04-02 02:53:43 +00005996 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson23b9b192009-08-12 00:36:31 +00005997 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5998 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman475871a2008-07-27 21:46:04 +00005999 SmallVector<SDValue, 8> Ops;
Bill Wendlingb0162f52009-01-30 22:53:48 +00006000
Dan Gohman7f321562007-06-25 16:23:39 +00006001 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattner6258fb22006-04-02 02:53:43 +00006002 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6003 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesene8d72302009-02-06 23:05:02 +00006004 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattner6258fb22006-04-02 02:53:43 +00006005 continue;
6006 }
Bill Wendlingb0162f52009-01-30 22:53:48 +00006007
Jay Foad40f8f622010-12-07 08:25:19 +00006008 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6009 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingb0162f52009-01-30 22:53:48 +00006010
Chris Lattner6258fb22006-04-02 02:53:43 +00006011 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad40f8f622010-12-07 08:25:19 +00006012 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattner6258fb22006-04-02 02:53:43 +00006013 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad40f8f622010-12-07 08:25:19 +00006014 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Chengefec7512008-02-18 23:04:32 +00006015 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickac6d9be2013-05-25 02:42:55 +00006016 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingb0162f52009-01-30 22:53:48 +00006017 Ops[0]);
Dan Gohman220a8232008-03-03 23:51:38 +00006018 OpVal = OpVal.lshr(DstBitSize);
Chris Lattner6258fb22006-04-02 02:53:43 +00006019 }
6020
6021 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands0753fc12008-02-11 10:37:04 +00006022 if (TLI.isBigEndian())
Chris Lattner6258fb22006-04-02 02:53:43 +00006023 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6024 }
Bill Wendlingb0162f52009-01-30 22:53:48 +00006025
Andrew Trickac6d9be2013-05-25 02:42:55 +00006026 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga87008d2009-02-25 22:49:59 +00006027 &Ops[0], Ops.size());
Chris Lattner6258fb22006-04-02 02:53:43 +00006028}
6029
Dan Gohman475871a2008-07-27 21:46:04 +00006030SDValue DAGCombiner::visitFADD(SDNode *N) {
6031 SDValue N0 = N->getOperand(0);
6032 SDValue N1 = N->getOperand(1);
Nate Begemana0e221d2005-10-18 00:28:13 +00006033 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6034 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00006035 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00006036
Dan Gohman7f321562007-06-25 16:23:39 +00006037 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00006038 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00006039 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00006040 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman05d92fe2007-07-13 20:03:40 +00006041 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006042
Lang Hames01806942012-06-14 20:37:15 +00006043 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigande669c932012-10-29 18:35:49 +00006044 if (N0CFP && N1CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006045 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Nate Begemana0e221d2005-10-18 00:28:13 +00006046 // canonicalize constant to RHS
6047 if (N0CFP && !N1CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006048 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Bill Wendlingb0162f52009-01-30 22:53:48 +00006049 // fold (fadd A, 0) -> A
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006050 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6051 N1CFP->getValueAPF().isZero())
Dan Gohman760f86f2009-01-22 21:58:43 +00006052 return N0;
Bill Wendlingb0162f52009-01-30 22:53:48 +00006053 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Andersonafd3d562012-03-06 00:29:31 +00006054 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem6dfabb62012-09-20 08:53:31 +00006055 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006056 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sands25cf2272008-11-24 14:53:14 +00006057 GetNegatedExpression(N1, DAG, LegalOperations));
Bill Wendlingb0162f52009-01-30 22:53:48 +00006058 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Andersonafd3d562012-03-06 00:29:31 +00006059 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem6dfabb62012-09-20 08:53:31 +00006060 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006061 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sands25cf2272008-11-24 14:53:14 +00006062 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelfdc40a02009-02-17 22:15:04 +00006063
Chris Lattnerddae4bd2007-01-08 23:04:05 +00006064 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006065 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6066 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6067 isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006068 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6069 DAG.getNode(ISD::FADD, SDLoc(N), VT,
Bill Wendlingfc4b6772009-02-01 11:19:36 +00006070 N0.getOperand(1), N1));
Scott Michelfdc40a02009-02-17 22:15:04 +00006071
Shuxin Yang1cd1d022013-03-25 22:52:29 +00006072 // No FP constant should be created after legalization as Instruction
6073 // Selection pass has hard time in dealing with FP constant.
6074 //
6075 // We don't need test this condition for transformation like following, as
6076 // the DAG being transformed implies it is legal to take FP constant as
6077 // operand.
Stephen Lin155615d2013-07-08 00:37:03 +00006078 //
Shuxin Yang1cd1d022013-03-25 22:52:29 +00006079 // (fadd (fmul c, x), x) -> (fmul c+1, x)
Stephen Lin155615d2013-07-08 00:37:03 +00006080 //
Shuxin Yang1cd1d022013-03-25 22:52:29 +00006081 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6082
Owen Anderson607ebde2012-11-01 02:00:53 +00006083 // If allow, fold (fadd (fneg x), x) -> 0.0
Shuxin Yang1cd1d022013-03-25 22:52:29 +00006084 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Linb4940152013-07-09 00:44:49 +00006085 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
Owen Anderson607ebde2012-11-01 02:00:53 +00006086 return DAG.getConstantFP(0.0, VT);
Owen Anderson607ebde2012-11-01 02:00:53 +00006087
6088 // If allow, fold (fadd x, (fneg x)) -> 0.0
Shuxin Yang1cd1d022013-03-25 22:52:29 +00006089 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Linb4940152013-07-09 00:44:49 +00006090 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
Owen Anderson607ebde2012-11-01 02:00:53 +00006091 return DAG.getConstantFP(0.0, VT);
Owen Anderson607ebde2012-11-01 02:00:53 +00006092
Owen Anderson43da6c72012-08-30 23:35:16 +00006093 // In unsafe math mode, we can fold chains of FADD's of the same value
6094 // into multiplications. This transform is not safe in general because
6095 // we are reducing the number of rounding steps.
6096 if (DAG.getTarget().Options.UnsafeFPMath &&
6097 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6098 !N0CFP && !N1CFP) {
6099 if (N0.getOpcode() == ISD::FMUL) {
6100 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6101 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6102
Stephen Lin38103d12013-06-14 18:17:35 +00006103 // (fadd (fmul c, x), x) -> (fmul x, c+1)
Owen Anderson43da6c72012-08-30 23:35:16 +00006104 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006105 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006106 SDValue(CFP00, 0),
6107 DAG.getConstantFP(1.0, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006108 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006109 N1, NewCFP);
6110 }
6111
Stephen Lin38103d12013-06-14 18:17:35 +00006112 // (fadd (fmul x, c), x) -> (fmul x, c+1)
Owen Anderson43da6c72012-08-30 23:35:16 +00006113 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006114 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006115 SDValue(CFP01, 0),
6116 DAG.getConstantFP(1.0, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006117 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006118 N1, NewCFP);
6119 }
6120
Stephen Lin38103d12013-06-14 18:17:35 +00006121 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
Owen Anderson43da6c72012-08-30 23:35:16 +00006122 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6123 N1.getOperand(0) == N1.getOperand(1) &&
6124 N0.getOperand(1) == N1.getOperand(0)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006125 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006126 SDValue(CFP00, 0),
6127 DAG.getConstantFP(2.0, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006128 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006129 N0.getOperand(1), NewCFP);
6130 }
6131
Stephen Lin38103d12013-06-14 18:17:35 +00006132 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
Owen Anderson43da6c72012-08-30 23:35:16 +00006133 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6134 N1.getOperand(0) == N1.getOperand(1) &&
6135 N0.getOperand(0) == N1.getOperand(0)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006136 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006137 SDValue(CFP01, 0),
6138 DAG.getConstantFP(2.0, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006139 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006140 N0.getOperand(0), NewCFP);
6141 }
6142 }
6143
6144 if (N1.getOpcode() == ISD::FMUL) {
6145 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6146 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6147
Stephen Lin38103d12013-06-14 18:17:35 +00006148 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
Owen Anderson43da6c72012-08-30 23:35:16 +00006149 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006150 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006151 SDValue(CFP10, 0),
6152 DAG.getConstantFP(1.0, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006153 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006154 N0, NewCFP);
6155 }
6156
Stephen Lin38103d12013-06-14 18:17:35 +00006157 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
Owen Anderson43da6c72012-08-30 23:35:16 +00006158 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006159 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006160 SDValue(CFP11, 0),
6161 DAG.getConstantFP(1.0, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006162 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006163 N0, NewCFP);
6164 }
6165
Owen Anderson43da6c72012-08-30 23:35:16 +00006166
Stephen Lin38103d12013-06-14 18:17:35 +00006167 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6168 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6169 N0.getOperand(0) == N0.getOperand(1) &&
6170 N1.getOperand(1) == N0.getOperand(0)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006171 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006172 SDValue(CFP10, 0),
6173 DAG.getConstantFP(2.0, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006174 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Lin38103d12013-06-14 18:17:35 +00006175 N1.getOperand(1), NewCFP);
Owen Anderson43da6c72012-08-30 23:35:16 +00006176 }
6177
Stephen Lin38103d12013-06-14 18:17:35 +00006178 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6179 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6180 N0.getOperand(0) == N0.getOperand(1) &&
6181 N1.getOperand(0) == N0.getOperand(0)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006182 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006183 SDValue(CFP11, 0),
6184 DAG.getConstantFP(2.0, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006185 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Lin38103d12013-06-14 18:17:35 +00006186 N1.getOperand(0), NewCFP);
Owen Anderson43da6c72012-08-30 23:35:16 +00006187 }
6188 }
6189
Shuxin Yang1cd1d022013-03-25 22:52:29 +00006190 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yang98b93e52013-02-02 00:22:03 +00006191 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
Stephen Lina553bed2013-06-14 21:33:58 +00006192 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
Shuxin Yang98b93e52013-02-02 00:22:03 +00006193 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
Stephen Linb4940152013-07-09 00:44:49 +00006194 (N0.getOperand(0) == N1))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006195 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yang98b93e52013-02-02 00:22:03 +00006196 N1, DAG.getConstantFP(3.0, VT));
Shuxin Yang98b93e52013-02-02 00:22:03 +00006197 }
6198
Shuxin Yang1cd1d022013-03-25 22:52:29 +00006199 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yang98b93e52013-02-02 00:22:03 +00006200 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
Stephen Lina553bed2013-06-14 21:33:58 +00006201 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
Shuxin Yang98b93e52013-02-02 00:22:03 +00006202 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
Stephen Linb4940152013-07-09 00:44:49 +00006203 N1.getOperand(0) == N0)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006204 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yang98b93e52013-02-02 00:22:03 +00006205 N0, DAG.getConstantFP(3.0, VT));
Shuxin Yang98b93e52013-02-02 00:22:03 +00006206 }
6207
Stephen Lina553bed2013-06-14 21:33:58 +00006208 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
Shuxin Yang1cd1d022013-03-25 22:52:29 +00006209 if (AllowNewFpConst &&
6210 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Owen Anderson43da6c72012-08-30 23:35:16 +00006211 N0.getOperand(0) == N0.getOperand(1) &&
6212 N1.getOperand(0) == N1.getOperand(1) &&
Stephen Linb4940152013-07-09 00:44:49 +00006213 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006214 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006215 N0.getOperand(0),
6216 DAG.getConstantFP(4.0, VT));
Owen Anderson43da6c72012-08-30 23:35:16 +00006217 }
6218
Lang Hamesd693caf2012-06-19 22:51:23 +00006219 // FADD -> FMA combines:
Lang Hamese0231412012-06-22 01:09:09 +00006220 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hamesd693caf2012-06-19 22:51:23 +00006221 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Line54885a2013-07-09 18:16:56 +00006222 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6223 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hamesd693caf2012-06-19 22:51:23 +00006224
6225 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Stephen Linb4940152013-07-09 00:44:49 +00006226 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Andrew Trickac6d9be2013-05-25 02:42:55 +00006227 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hamesd693caf2012-06-19 22:51:23 +00006228 N0.getOperand(0), N0.getOperand(1), N1);
Owen Anderson43da6c72012-08-30 23:35:16 +00006229
Michael Liaob79bff52012-09-01 04:09:16 +00006230 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hamesd693caf2012-06-19 22:51:23 +00006231 // Note: Commutes FADD operands.
Stephen Linb4940152013-07-09 00:44:49 +00006232 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Andrew Trickac6d9be2013-05-25 02:42:55 +00006233 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hamesd693caf2012-06-19 22:51:23 +00006234 N1.getOperand(0), N1.getOperand(1), N0);
Lang Hamesd693caf2012-06-19 22:51:23 +00006235 }
6236
Dan Gohman475871a2008-07-27 21:46:04 +00006237 return SDValue();
Chris Lattner01b3d732005-09-28 22:28:18 +00006238}
6239
Dan Gohman475871a2008-07-27 21:46:04 +00006240SDValue DAGCombiner::visitFSUB(SDNode *N) {
6241 SDValue N0 = N->getOperand(0);
6242 SDValue N1 = N->getOperand(1);
Nate Begemana0e221d2005-10-18 00:28:13 +00006243 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6244 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00006245 EVT VT = N->getValueType(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00006246 SDLoc dl(N);
Scott Michelfdc40a02009-02-17 22:15:04 +00006247
Dan Gohman7f321562007-06-25 16:23:39 +00006248 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00006249 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00006250 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00006251 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman05d92fe2007-07-13 20:03:40 +00006252 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006253
Nate Begemana0e221d2005-10-18 00:28:13 +00006254 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigande669c932012-10-29 18:35:49 +00006255 if (N0CFP && N1CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006256 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Bill Wendlingb0162f52009-01-30 22:53:48 +00006257 // fold (fsub A, 0) -> A
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006258 if (DAG.getTarget().Options.UnsafeFPMath &&
6259 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohmana90c8e62009-01-23 19:10:37 +00006260 return N0;
Bill Wendlingb0162f52009-01-30 22:53:48 +00006261 // fold (fsub 0, B) -> -B
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006262 if (DAG.getTarget().Options.UnsafeFPMath &&
6263 N0CFP && N0CFP->getValueAPF().isZero()) {
Owen Andersonafd3d562012-03-06 00:29:31 +00006264 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Duncan Sands25cf2272008-11-24 14:53:14 +00006265 return GetNegatedExpression(N1, DAG, LegalOperations);
Dan Gohman760f86f2009-01-22 21:58:43 +00006266 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Elena Demikhovsky1503aba2012-08-01 12:06:00 +00006267 return DAG.getNode(ISD::FNEG, dl, VT, N1);
Dan Gohman23ff1822007-07-02 15:48:56 +00006268 }
Bill Wendlingb0162f52009-01-30 22:53:48 +00006269 // fold (fsub A, (fneg B)) -> (fadd A, B)
Owen Andersonafd3d562012-03-06 00:29:31 +00006270 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Elena Demikhovsky1503aba2012-08-01 12:06:00 +00006271 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sands25cf2272008-11-24 14:53:14 +00006272 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelfdc40a02009-02-17 22:15:04 +00006273
Bill Wendling5a894342012-03-15 05:12:00 +00006274 // If 'unsafe math' is enabled, fold
Owen Anderson713e9532012-05-07 20:51:25 +00006275 // (fsub x, x) -> 0.0 &
Bill Wendling5a894342012-03-15 05:12:00 +00006276 // (fsub x, (fadd x, y)) -> (fneg y) &
6277 // (fsub x, (fadd y, x)) -> (fneg y)
6278 if (DAG.getTarget().Options.UnsafeFPMath) {
Owen Anderson713e9532012-05-07 20:51:25 +00006279 if (N0 == N1)
6280 return DAG.getConstantFP(0.0f, VT);
6281
Bill Wendling5a894342012-03-15 05:12:00 +00006282 if (N1.getOpcode() == ISD::FADD) {
6283 SDValue N10 = N1->getOperand(0);
6284 SDValue N11 = N1->getOperand(1);
6285
6286 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6287 &DAG.getTarget().Options))
6288 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin75d13062013-07-10 20:47:39 +00006289
Stephen Linb4940152013-07-09 00:44:49 +00006290 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6291 &DAG.getTarget().Options))
Bill Wendling5a894342012-03-15 05:12:00 +00006292 return GetNegatedExpression(N10, DAG, LegalOperations);
6293 }
6294 }
6295
Lang Hamesd693caf2012-06-19 22:51:23 +00006296 // FSUB -> FMA combines:
Lang Hamese0231412012-06-22 01:09:09 +00006297 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hamesd693caf2012-06-19 22:51:23 +00006298 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Line54885a2013-07-09 18:16:56 +00006299 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6300 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hamesd693caf2012-06-19 22:51:23 +00006301
6302 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Stephen Linb4940152013-07-09 00:44:49 +00006303 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Elena Demikhovsky1503aba2012-08-01 12:06:00 +00006304 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hamesd693caf2012-06-19 22:51:23 +00006305 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky1503aba2012-08-01 12:06:00 +00006306 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hamesd693caf2012-06-19 22:51:23 +00006307
6308 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6309 // Note: Commutes FSUB operands.
Stephen Lin75d13062013-07-10 20:47:39 +00006310 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Elena Demikhovsky1503aba2012-08-01 12:06:00 +00006311 return DAG.getNode(ISD::FMA, dl, VT,
6312 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hamesd693caf2012-06-19 22:51:23 +00006313 N1.getOperand(0)),
6314 N1.getOperand(1), N0);
Elena Demikhovsky1503aba2012-08-01 12:06:00 +00006315
Stephen Linb4940152013-07-09 00:44:49 +00006316 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lin155615d2013-07-08 00:37:03 +00006317 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky1503aba2012-08-01 12:06:00 +00006318 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6319 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6320 SDValue N00 = N0.getOperand(0).getOperand(0);
6321 SDValue N01 = N0.getOperand(0).getOperand(1);
6322 return DAG.getNode(ISD::FMA, dl, VT,
6323 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6324 DAG.getNode(ISD::FNEG, dl, VT, N1));
6325 }
Lang Hamesd693caf2012-06-19 22:51:23 +00006326 }
6327
Dan Gohman475871a2008-07-27 21:46:04 +00006328 return SDValue();
Chris Lattner01b3d732005-09-28 22:28:18 +00006329}
6330
Dan Gohman475871a2008-07-27 21:46:04 +00006331SDValue DAGCombiner::visitFMUL(SDNode *N) {
6332 SDValue N0 = N->getOperand(0);
6333 SDValue N1 = N->getOperand(1);
Nate Begeman11af4ea2005-10-17 20:40:11 +00006334 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6335 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00006336 EVT VT = N->getValueType(0);
Owen Andersonafd3d562012-03-06 00:29:31 +00006337 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner01b3d732005-09-28 22:28:18 +00006338
Dan Gohman7f321562007-06-25 16:23:39 +00006339 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00006340 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00006341 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00006342 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman05d92fe2007-07-13 20:03:40 +00006343 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006344
Nate Begeman11af4ea2005-10-17 20:40:11 +00006345 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigande669c932012-10-29 18:35:49 +00006346 if (N0CFP && N1CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006347 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Nate Begeman11af4ea2005-10-17 20:40:11 +00006348 // canonicalize constant to RHS
Nate Begemana0e221d2005-10-18 00:28:13 +00006349 if (N0CFP && !N1CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006350 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Bill Wendlinga03e74b2009-01-30 22:57:07 +00006351 // fold (fmul A, 0) -> 0
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006352 if (DAG.getTarget().Options.UnsafeFPMath &&
6353 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman760f86f2009-01-22 21:58:43 +00006354 return N1;
Dan Gohman77b81fe2009-06-04 17:12:12 +00006355 // fold (fmul A, 0) -> 0, vector edition.
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006356 if (DAG.getTarget().Options.UnsafeFPMath &&
6357 ISD::isBuildVectorAllZeros(N1.getNode()))
Dan Gohman77b81fe2009-06-04 17:12:12 +00006358 return N1;
Owen Anderson363e4b92012-05-02 21:32:35 +00006359 // fold (fmul A, 1.0) -> A
6360 if (N1CFP && N1CFP->isExactlyValue(1.0))
6361 return N0;
Nate Begeman11af4ea2005-10-17 20:40:11 +00006362 // fold (fmul X, 2.0) -> (fadd X, X)
6363 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006364 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Dan Gohmaneb1fedc2009-08-10 16:50:32 +00006365 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattner29446522007-05-14 22:04:50 +00006366 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman760f86f2009-01-22 21:58:43 +00006367 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006368 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +00006369
Bill Wendlinga03e74b2009-01-30 22:57:07 +00006370 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Owen Andersonafd3d562012-03-06 00:29:31 +00006371 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006372 &DAG.getTarget().Options)) {
Stephen Lin155615d2013-07-08 00:37:03 +00006373 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006374 &DAG.getTarget().Options)) {
Chris Lattner29446522007-05-14 22:04:50 +00006375 // Both can be negated for free, check to see if at least one is cheaper
6376 // negated.
6377 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006378 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sands25cf2272008-11-24 14:53:14 +00006379 GetNegatedExpression(N0, DAG, LegalOperations),
6380 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattner29446522007-05-14 22:04:50 +00006381 }
6382 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006383
Chris Lattnerddae4bd2007-01-08 23:04:05 +00006384 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006385 if (DAG.getTarget().Options.UnsafeFPMath &&
6386 N1CFP && N0.getOpcode() == ISD::FMUL &&
Gabor Greifba36cb52008-08-28 21:40:38 +00006387 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006388 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6389 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Dale Johannesende064702009-02-06 21:50:26 +00006390 N0.getOperand(1), N1));
Scott Michelfdc40a02009-02-17 22:15:04 +00006391
Dan Gohman475871a2008-07-27 21:46:04 +00006392 return SDValue();
Chris Lattner01b3d732005-09-28 22:28:18 +00006393}
6394
Owen Anderson062c0a52012-05-02 22:17:40 +00006395SDValue DAGCombiner::visitFMA(SDNode *N) {
6396 SDValue N0 = N->getOperand(0);
6397 SDValue N1 = N->getOperand(1);
6398 SDValue N2 = N->getOperand(2);
6399 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6400 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6401 EVT VT = N->getValueType(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00006402 SDLoc dl(N);
Owen Anderson062c0a52012-05-02 22:17:40 +00006403
Owen Anderson607ebde2012-11-01 02:00:53 +00006404 if (DAG.getTarget().Options.UnsafeFPMath) {
6405 if (N0CFP && N0CFP->isZero())
6406 return N2;
6407 if (N1CFP && N1CFP->isZero())
6408 return N2;
6409 }
Owen Anderson062c0a52012-05-02 22:17:40 +00006410 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006411 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson062c0a52012-05-02 22:17:40 +00006412 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006413 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson062c0a52012-05-02 22:17:40 +00006414
Owen Anderson85ef6f42012-05-30 18:50:39 +00006415 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Andersonf917d202012-05-30 18:54:50 +00006416 if (N0CFP && !N1CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006417 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Anderson85ef6f42012-05-30 18:50:39 +00006418
Owen Anderson58d57292012-09-01 06:04:27 +00006419 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6420 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6421 N2.getOpcode() == ISD::FMUL &&
6422 N0 == N2.getOperand(0) &&
6423 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6424 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6425 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6426 }
6427
6428
6429 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6430 if (DAG.getTarget().Options.UnsafeFPMath &&
6431 N0.getOpcode() == ISD::FMUL && N1CFP &&
6432 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6433 return DAG.getNode(ISD::FMA, dl, VT,
6434 N0.getOperand(0),
6435 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6436 N2);
6437 }
6438
6439 // (fma x, 1, y) -> (fadd x, y)
6440 // (fma x, -1, y) -> (fadd (fneg x), y)
6441 if (N1CFP) {
6442 if (N1CFP->isExactlyValue(1.0))
6443 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6444
6445 if (N1CFP->isExactlyValue(-1.0) &&
6446 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6447 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6448 AddToWorkList(RHSNeg.getNode());
6449 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6450 }
6451 }
6452
6453 // (fma x, c, x) -> (fmul x, (c+1))
Stephen Linb4940152013-07-09 00:44:49 +00006454 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6455 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson58d57292012-09-01 06:04:27 +00006456 DAG.getNode(ISD::FADD, dl, VT,
6457 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson58d57292012-09-01 06:04:27 +00006458
6459 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6460 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
Stephen Linb4940152013-07-09 00:44:49 +00006461 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6462 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson58d57292012-09-01 06:04:27 +00006463 DAG.getNode(ISD::FADD, dl, VT,
6464 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson58d57292012-09-01 06:04:27 +00006465
6466
Owen Anderson062c0a52012-05-02 22:17:40 +00006467 return SDValue();
6468}
6469
Dan Gohman475871a2008-07-27 21:46:04 +00006470SDValue DAGCombiner::visitFDIV(SDNode *N) {
6471 SDValue N0 = N->getOperand(0);
6472 SDValue N1 = N->getOperand(1);
Nate Begemana148d982006-01-18 22:35:16 +00006473 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6474 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00006475 EVT VT = N->getValueType(0);
Owen Andersonafd3d562012-03-06 00:29:31 +00006476 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner01b3d732005-09-28 22:28:18 +00006477
Dan Gohman7f321562007-06-25 16:23:39 +00006478 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00006479 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00006480 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00006481 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman05d92fe2007-07-13 20:03:40 +00006482 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006483
Nate Begemana148d982006-01-18 22:35:16 +00006484 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigande669c932012-10-29 18:35:49 +00006485 if (N0CFP && N1CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006486 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelfdc40a02009-02-17 22:15:04 +00006487
Duncan Sands3ef3fcf2012-04-08 18:08:12 +00006488 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
Ulrich Weigande669c932012-10-29 18:35:49 +00006489 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
Duncan Sands961d6662012-04-07 20:04:00 +00006490 // Compute the reciprocal 1.0 / c2.
6491 APFloat N1APF = N1CFP->getValueAPF();
6492 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6493 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
Duncan Sands507bb7a2012-04-10 20:35:27 +00006494 // Only do the transform if the reciprocal is a legal fp immediate that
6495 // isn't too nasty (eg NaN, denormal, ...).
6496 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
Anton Korobeynikov999821c2012-04-10 13:22:49 +00006497 (!LegalOperations ||
6498 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6499 // backend)... we should handle this gracefully after Legalize.
6500 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6501 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6502 TLI.isFPImmLegal(Recip, VT)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006503 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
Duncan Sands961d6662012-04-07 20:04:00 +00006504 DAG.getConstantFP(Recip, VT));
6505 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006506
Bill Wendlinga03e74b2009-01-30 22:57:07 +00006507 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Owen Andersonafd3d562012-03-06 00:29:31 +00006508 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006509 &DAG.getTarget().Options)) {
Owen Andersonafd3d562012-03-06 00:29:31 +00006510 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006511 &DAG.getTarget().Options)) {
Chris Lattner29446522007-05-14 22:04:50 +00006512 // Both can be negated for free, check to see if at least one is cheaper
6513 // negated.
6514 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006515 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sands25cf2272008-11-24 14:53:14 +00006516 GetNegatedExpression(N0, DAG, LegalOperations),
6517 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattner29446522007-05-14 22:04:50 +00006518 }
6519 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006520
Dan Gohman475871a2008-07-27 21:46:04 +00006521 return SDValue();
Chris Lattner01b3d732005-09-28 22:28:18 +00006522}
6523
Dan Gohman475871a2008-07-27 21:46:04 +00006524SDValue DAGCombiner::visitFREM(SDNode *N) {
6525 SDValue N0 = N->getOperand(0);
6526 SDValue N1 = N->getOperand(1);
Nate Begemana148d982006-01-18 22:35:16 +00006527 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6528 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00006529 EVT VT = N->getValueType(0);
Chris Lattner01b3d732005-09-28 22:28:18 +00006530
Nate Begemana148d982006-01-18 22:35:16 +00006531 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigande669c932012-10-29 18:35:49 +00006532 if (N0CFP && N1CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006533 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohman7f321562007-06-25 16:23:39 +00006534
Dan Gohman475871a2008-07-27 21:46:04 +00006535 return SDValue();
Chris Lattner01b3d732005-09-28 22:28:18 +00006536}
6537
Dan Gohman475871a2008-07-27 21:46:04 +00006538SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6539 SDValue N0 = N->getOperand(0);
6540 SDValue N1 = N->getOperand(1);
Chris Lattner12d83032006-03-05 05:30:57 +00006541 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6542 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00006543 EVT VT = N->getValueType(0);
Chris Lattner12d83032006-03-05 05:30:57 +00006544
Ulrich Weigande669c932012-10-29 18:35:49 +00006545 if (N0CFP && N1CFP) // Constant fold
Andrew Trickac6d9be2013-05-25 02:42:55 +00006546 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelfdc40a02009-02-17 22:15:04 +00006547
Chris Lattner12d83032006-03-05 05:30:57 +00006548 if (N1CFP) {
Dale Johannesene6c17422007-08-26 01:18:27 +00006549 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru94c22712012-09-27 10:14:43 +00006550 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6551 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman760f86f2009-01-22 21:58:43 +00006552 if (!V.isNegative()) {
6553 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006554 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman760f86f2009-01-22 21:58:43 +00006555 } else {
6556 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006557 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6558 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman760f86f2009-01-22 21:58:43 +00006559 }
Chris Lattner12d83032006-03-05 05:30:57 +00006560 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006561
Chris Lattner12d83032006-03-05 05:30:57 +00006562 // copysign(fabs(x), y) -> copysign(x, y)
6563 // copysign(fneg(x), y) -> copysign(x, y)
6564 // copysign(copysign(x,z), y) -> copysign(x, y)
6565 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6566 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006567 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0225a1d2009-01-30 23:15:49 +00006568 N0.getOperand(0), N1);
Chris Lattner12d83032006-03-05 05:30:57 +00006569
6570 // copysign(x, abs(y)) -> abs(x)
6571 if (N1.getOpcode() == ISD::FABS)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006572 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +00006573
Chris Lattner12d83032006-03-05 05:30:57 +00006574 // copysign(x, copysign(y,z)) -> copysign(x, z)
6575 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006576 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0225a1d2009-01-30 23:15:49 +00006577 N0, N1.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00006578
Chris Lattner12d83032006-03-05 05:30:57 +00006579 // copysign(x, fp_extend(y)) -> copysign(x, y)
6580 // copysign(x, fp_round(y)) -> copysign(x, y)
6581 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006582 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0225a1d2009-01-30 23:15:49 +00006583 N0, N1.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00006584
Dan Gohman475871a2008-07-27 21:46:04 +00006585 return SDValue();
Chris Lattner12d83032006-03-05 05:30:57 +00006586}
6587
Dan Gohman475871a2008-07-27 21:46:04 +00006588SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6589 SDValue N0 = N->getOperand(0);
Nate Begeman646d7e22005-09-02 21:18:40 +00006590 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Andersone50ed302009-08-10 22:56:29 +00006591 EVT VT = N->getValueType(0);
6592 EVT OpVT = N0.getValueType();
Chris Lattnercda88752008-06-26 00:16:49 +00006593
Nate Begeman1d4d4142005-09-01 00:19:25 +00006594 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigande669c932012-10-29 18:35:49 +00006595 if (N0C &&
Stuart Hastings7e334182011-03-02 19:36:30 +00006596 // ...but only if the target supports immediate floating-point values
Eli Friedman50185242011-11-12 00:35:34 +00006597 (!LegalOperations ||
Evan Cheng9568e5c2011-06-21 06:01:08 +00006598 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006599 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +00006600
Chris Lattnercda88752008-06-26 00:16:49 +00006601 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6602 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohmanf560ffa2009-01-28 17:46:25 +00006603 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6604 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelfdc40a02009-02-17 22:15:04 +00006605 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnercda88752008-06-26 00:16:49 +00006606 if (DAG.SignBitIsZero(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006607 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnercda88752008-06-26 00:16:49 +00006608 }
Bill Wendling0225a1d2009-01-30 23:15:49 +00006609
Nadav Rotemed1a3352012-07-23 07:59:50 +00006610 // The next optimizations are desireable only if SELECT_CC can be lowered.
6611 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6612 // having to say they don't support SELECT_CC on every type the DAG knows
6613 // about, since there is no way to mark an opcode illegal at all value types
6614 // (See also visitSELECT)
6615 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6616 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6617 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6618 !VT.isVector() &&
6619 (!LegalOperations ||
6620 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6621 SDValue Ops[] =
6622 { N0.getOperand(0), N0.getOperand(1),
6623 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6624 N0.getOperand(2) };
Andrew Trickac6d9be2013-05-25 02:42:55 +00006625 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotemed1a3352012-07-23 07:59:50 +00006626 }
Owen Andersond9bf71f2012-07-09 20:31:12 +00006627
Nadav Rotemed1a3352012-07-23 07:59:50 +00006628 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6629 // (select_cc x, y, 1.0, 0.0,, cc)
6630 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6631 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6632 (!LegalOperations ||
6633 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6634 SDValue Ops[] =
6635 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6636 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6637 N0.getOperand(0).getOperand(2) };
Andrew Trickac6d9be2013-05-25 02:42:55 +00006638 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotemed1a3352012-07-23 07:59:50 +00006639 }
Owen Andersond9bf71f2012-07-09 20:31:12 +00006640 }
6641
Dan Gohman475871a2008-07-27 21:46:04 +00006642 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00006643}
6644
Dan Gohman475871a2008-07-27 21:46:04 +00006645SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6646 SDValue N0 = N->getOperand(0);
Nate Begeman646d7e22005-09-02 21:18:40 +00006647 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Andersone50ed302009-08-10 22:56:29 +00006648 EVT VT = N->getValueType(0);
6649 EVT OpVT = N0.getValueType();
Nate Begemana148d982006-01-18 22:35:16 +00006650
Nate Begeman1d4d4142005-09-01 00:19:25 +00006651 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigande669c932012-10-29 18:35:49 +00006652 if (N0C &&
Stuart Hastings7e334182011-03-02 19:36:30 +00006653 // ...but only if the target supports immediate floating-point values
Eli Friedman50185242011-11-12 00:35:34 +00006654 (!LegalOperations ||
Evan Cheng9568e5c2011-06-21 06:01:08 +00006655 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006656 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +00006657
Chris Lattnercda88752008-06-26 00:16:49 +00006658 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6659 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohmanf560ffa2009-01-28 17:46:25 +00006660 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6661 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelfdc40a02009-02-17 22:15:04 +00006662 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnercda88752008-06-26 00:16:49 +00006663 if (DAG.SignBitIsZero(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006664 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnercda88752008-06-26 00:16:49 +00006665 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006666
Nadav Rotemed1a3352012-07-23 07:59:50 +00006667 // The next optimizations are desireable only if SELECT_CC can be lowered.
6668 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6669 // having to say they don't support SELECT_CC on every type the DAG knows
6670 // about, since there is no way to mark an opcode illegal at all value types
6671 // (See also visitSELECT)
6672 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6673 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond9bf71f2012-07-09 20:31:12 +00006674
Nadav Rotemed1a3352012-07-23 07:59:50 +00006675 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6676 (!LegalOperations ||
6677 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6678 SDValue Ops[] =
6679 { N0.getOperand(0), N0.getOperand(1),
6680 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
6681 N0.getOperand(2) };
Andrew Trickac6d9be2013-05-25 02:42:55 +00006682 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotemed1a3352012-07-23 07:59:50 +00006683 }
6684 }
Owen Andersond9bf71f2012-07-09 20:31:12 +00006685
Dan Gohman475871a2008-07-27 21:46:04 +00006686 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00006687}
6688
Dan Gohman475871a2008-07-27 21:46:04 +00006689SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6690 SDValue N0 = N->getOperand(0);
Nate Begemana148d982006-01-18 22:35:16 +00006691 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Andersone50ed302009-08-10 22:56:29 +00006692 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00006693
Nate Begeman1d4d4142005-09-01 00:19:25 +00006694 // fold (fp_to_sint c1fp) -> c1
Nate Begeman646d7e22005-09-02 21:18:40 +00006695 if (N0CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006696 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0225a1d2009-01-30 23:15:49 +00006697
Dan Gohman475871a2008-07-27 21:46:04 +00006698 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00006699}
6700
Dan Gohman475871a2008-07-27 21:46:04 +00006701SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6702 SDValue N0 = N->getOperand(0);
Nate Begemana148d982006-01-18 22:35:16 +00006703 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Andersone50ed302009-08-10 22:56:29 +00006704 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00006705
Nate Begeman1d4d4142005-09-01 00:19:25 +00006706 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigande669c932012-10-29 18:35:49 +00006707 if (N0CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006708 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0225a1d2009-01-30 23:15:49 +00006709
Dan Gohman475871a2008-07-27 21:46:04 +00006710 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00006711}
6712
Dan Gohman475871a2008-07-27 21:46:04 +00006713SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6714 SDValue N0 = N->getOperand(0);
6715 SDValue N1 = N->getOperand(1);
Nate Begemana148d982006-01-18 22:35:16 +00006716 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Andersone50ed302009-08-10 22:56:29 +00006717 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00006718
Nate Begeman1d4d4142005-09-01 00:19:25 +00006719 // fold (fp_round c1fp) -> c1fp
Ulrich Weigande669c932012-10-29 18:35:49 +00006720 if (N0CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006721 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelfdc40a02009-02-17 22:15:04 +00006722
Chris Lattner79dbea52006-03-13 06:26:26 +00006723 // fold (fp_round (fp_extend x)) -> x
6724 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6725 return N0.getOperand(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00006726
Chris Lattner0aa5e6f2008-01-24 06:45:35 +00006727 // fold (fp_round (fp_round x)) -> (fp_round x)
6728 if (N0.getOpcode() == ISD::FP_ROUND) {
6729 // This is a value preserving truncation if both round's are.
6730 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
Gabor Greifba36cb52008-08-28 21:40:38 +00006731 N0.getNode()->getConstantOperandVal(1) == 1;
Andrew Trickac6d9be2013-05-25 02:42:55 +00006732 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0aa5e6f2008-01-24 06:45:35 +00006733 DAG.getIntPtrConstant(IsTrunc));
6734 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006735
Chris Lattner79dbea52006-03-13 06:26:26 +00006736 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greifba36cb52008-08-28 21:40:38 +00006737 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006738 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0225a1d2009-01-30 23:15:49 +00006739 N0.getOperand(0), N1);
Gabor Greifba36cb52008-08-28 21:40:38 +00006740 AddToWorkList(Tmp.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00006741 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0225a1d2009-01-30 23:15:49 +00006742 Tmp, N0.getOperand(1));
Chris Lattner79dbea52006-03-13 06:26:26 +00006743 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006744
Dan Gohman475871a2008-07-27 21:46:04 +00006745 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00006746}
6747
Dan Gohman475871a2008-07-27 21:46:04 +00006748SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6749 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00006750 EVT VT = N->getValueType(0);
6751 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman646d7e22005-09-02 21:18:40 +00006752 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelfdc40a02009-02-17 22:15:04 +00006753
Nate Begeman1d4d4142005-09-01 00:19:25 +00006754 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner2392ae72010-04-15 04:48:01 +00006755 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohman4fbd7962008-09-12 18:08:03 +00006756 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickac6d9be2013-05-25 02:42:55 +00006757 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman1d4d4142005-09-01 00:19:25 +00006758 }
Bill Wendling0225a1d2009-01-30 23:15:49 +00006759
Dan Gohman475871a2008-07-27 21:46:04 +00006760 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00006761}
6762
Dan Gohman475871a2008-07-27 21:46:04 +00006763SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6764 SDValue N0 = N->getOperand(0);
Nate Begemana148d982006-01-18 22:35:16 +00006765 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Andersone50ed302009-08-10 22:56:29 +00006766 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00006767
Chris Lattner5938bef2007-12-29 06:55:23 +00006768 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelfdc40a02009-02-17 22:15:04 +00006769 if (N->hasOneUse() &&
Dan Gohmane7852d02009-01-26 04:35:06 +00006770 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman475871a2008-07-27 21:46:04 +00006771 return SDValue();
Chris Lattner0bd48932008-01-17 07:00:52 +00006772
Nate Begeman1d4d4142005-09-01 00:19:25 +00006773 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigande669c932012-10-29 18:35:49 +00006774 if (N0CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006775 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner0bd48932008-01-17 07:00:52 +00006776
6777 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6778 // value of X.
Gabor Greif12632d22008-08-30 19:29:20 +00006779 if (N0.getOpcode() == ISD::FP_ROUND
6780 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman475871a2008-07-27 21:46:04 +00006781 SDValue In = N0.getOperand(0);
Chris Lattner0bd48932008-01-17 07:00:52 +00006782 if (In.getValueType() == VT) return In;
Duncan Sands8e4eb092008-06-08 20:54:56 +00006783 if (VT.bitsLT(In.getValueType()))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006784 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0225a1d2009-01-30 23:15:49 +00006785 In, N0.getOperand(1));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006786 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner0bd48932008-01-17 07:00:52 +00006787 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006788
Chris Lattner0bd48932008-01-17 07:00:52 +00006789 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkel03c8f8f2013-10-04 22:18:12 +00006790 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands25cf2272008-11-24 14:53:14 +00006791 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng03294662008-10-14 21:26:46 +00006792 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Evan Cheng466685d2006-10-09 20:57:25 +00006793 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00006794 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0225a1d2009-01-30 23:15:49 +00006795 LN0->getChain(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00006796 LN0->getBasePtr(), N0.getValueType(),
6797 LN0->getMemOperand());
Chris Lattnere564dbb2006-05-05 21:34:35 +00006798 CombineTo(N, ExtLoad);
Bill Wendling0225a1d2009-01-30 23:15:49 +00006799 CombineTo(N0.getNode(),
Andrew Trickac6d9be2013-05-25 02:42:55 +00006800 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0225a1d2009-01-30 23:15:49 +00006801 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattnere564dbb2006-05-05 21:34:35 +00006802 ExtLoad.getValue(1));
Dan Gohman475871a2008-07-27 21:46:04 +00006803 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattnere564dbb2006-05-05 21:34:35 +00006804 }
Duncan Sandsd4b9c172008-06-13 19:07:40 +00006805
Dan Gohman475871a2008-07-27 21:46:04 +00006806 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00006807}
6808
Dan Gohman475871a2008-07-27 21:46:04 +00006809SDValue DAGCombiner::visitFNEG(SDNode *N) {
6810 SDValue N0 = N->getOperand(0);
Anton Korobeynikov2bcf60a2009-10-20 21:37:45 +00006811 EVT VT = N->getValueType(0);
Nate Begemana148d982006-01-18 22:35:16 +00006812
Craig Topperdd201ff2012-09-11 01:45:21 +00006813 if (VT.isVector()) {
6814 SDValue FoldedVOp = SimplifyVUnaryOp(N);
6815 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper956342b2012-09-09 22:58:45 +00006816 }
6817
Owen Andersonafd3d562012-03-06 00:29:31 +00006818 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6819 &DAG.getTarget().Options))
Duncan Sands25cf2272008-11-24 14:53:14 +00006820 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman23ff1822007-07-02 15:48:56 +00006821
Chris Lattner3bd39d42008-01-27 17:42:27 +00006822 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6823 // constant pool values.
Owen Anderson29f60f32012-04-02 22:10:29 +00006824 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
Anton Korobeynikov2bcf60a2009-10-20 21:37:45 +00006825 !VT.isVector() &&
6826 N0.getNode()->hasOneUse() &&
6827 N0.getOperand(0).getValueType().isInteger()) {
Dan Gohman475871a2008-07-27 21:46:04 +00006828 SDValue Int = N0.getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00006829 EVT IntVT = Int.getValueType();
Duncan Sands83ec4b62008-06-06 12:08:01 +00006830 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006831 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Duncan Sandsb0d5cdd2009-02-01 18:06:53 +00006832 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greifba36cb52008-08-28 21:40:38 +00006833 AddToWorkList(Int.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00006834 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Anton Korobeynikov2bcf60a2009-10-20 21:37:45 +00006835 VT, Int);
Chris Lattner3bd39d42008-01-27 17:42:27 +00006836 }
6837 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006838
Owen Anderson58d57292012-09-01 06:04:27 +00006839 // (fneg (fmul c, x)) -> (fmul -c, x)
6840 if (N0.getOpcode() == ISD::FMUL) {
6841 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Stephen Linb4940152013-07-09 00:44:49 +00006842 if (CFP1)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006843 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson58d57292012-09-01 06:04:27 +00006844 N0.getOperand(0),
Andrew Trickac6d9be2013-05-25 02:42:55 +00006845 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
Owen Anderson58d57292012-09-01 06:04:27 +00006846 N0.getOperand(1)));
Owen Anderson58d57292012-09-01 06:04:27 +00006847 }
6848
Dan Gohman475871a2008-07-27 21:46:04 +00006849 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00006850}
6851
Owen Anderson7c626d32012-08-13 23:32:49 +00006852SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6853 SDValue N0 = N->getOperand(0);
6854 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6855 EVT VT = N->getValueType(0);
6856
6857 // fold (fceil c1) -> fceil(c1)
Ulrich Weigande669c932012-10-29 18:35:49 +00006858 if (N0CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006859 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
Owen Anderson7c626d32012-08-13 23:32:49 +00006860
6861 return SDValue();
6862}
6863
6864SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6865 SDValue N0 = N->getOperand(0);
6866 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6867 EVT VT = N->getValueType(0);
6868
6869 // fold (ftrunc c1) -> ftrunc(c1)
Ulrich Weigande669c932012-10-29 18:35:49 +00006870 if (N0CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006871 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
Owen Anderson7c626d32012-08-13 23:32:49 +00006872
6873 return SDValue();
6874}
6875
6876SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6877 SDValue N0 = N->getOperand(0);
6878 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6879 EVT VT = N->getValueType(0);
6880
6881 // fold (ffloor c1) -> ffloor(c1)
Ulrich Weigande669c932012-10-29 18:35:49 +00006882 if (N0CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006883 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
Owen Anderson7c626d32012-08-13 23:32:49 +00006884
6885 return SDValue();
6886}
6887
Dan Gohman475871a2008-07-27 21:46:04 +00006888SDValue DAGCombiner::visitFABS(SDNode *N) {
6889 SDValue N0 = N->getOperand(0);
Nate Begemana148d982006-01-18 22:35:16 +00006890 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Andersone50ed302009-08-10 22:56:29 +00006891 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00006892
Craig Topperdd201ff2012-09-11 01:45:21 +00006893 if (VT.isVector()) {
6894 SDValue FoldedVOp = SimplifyVUnaryOp(N);
6895 if (FoldedVOp.getNode()) return FoldedVOp;
6896 }
6897
Nate Begeman1d4d4142005-09-01 00:19:25 +00006898 // fold (fabs c1) -> fabs(c1)
Ulrich Weigande669c932012-10-29 18:35:49 +00006899 if (N0CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006900 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00006901 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner12d83032006-03-05 05:30:57 +00006902 if (N0.getOpcode() == ISD::FABS)
Nate Begeman83e75ec2005-09-06 04:43:02 +00006903 return N->getOperand(0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00006904 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner12d83032006-03-05 05:30:57 +00006905 // fold (fabs (fcopysign x, y)) -> (fabs x)
6906 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006907 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00006908
Chris Lattner3bd39d42008-01-27 17:42:27 +00006909 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6910 // constant pool values.
Stephen Lin155615d2013-07-08 00:37:03 +00006911 if (!TLI.isFAbsFree(VT) &&
Owen Anderson29f60f32012-04-02 22:10:29 +00006912 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
Duncan Sands83ec4b62008-06-06 12:08:01 +00006913 N0.getOperand(0).getValueType().isInteger() &&
6914 !N0.getOperand(0).getValueType().isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00006915 SDValue Int = N0.getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00006916 EVT IntVT = Int.getValueType();
Duncan Sands83ec4b62008-06-06 12:08:01 +00006917 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006918 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Duncan Sandsb0d5cdd2009-02-01 18:06:53 +00006919 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greifba36cb52008-08-28 21:40:38 +00006920 AddToWorkList(Int.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00006921 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Bill Wendlingc0debad2009-01-30 23:27:35 +00006922 N->getValueType(0), Int);
Chris Lattner3bd39d42008-01-27 17:42:27 +00006923 }
6924 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006925
Dan Gohman475871a2008-07-27 21:46:04 +00006926 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00006927}
6928
Dan Gohman475871a2008-07-27 21:46:04 +00006929SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6930 SDValue Chain = N->getOperand(0);
6931 SDValue N1 = N->getOperand(1);
6932 SDValue N2 = N->getOperand(2);
Scott Michelfdc40a02009-02-17 22:15:04 +00006933
Dan Gohmane0f06c72009-11-17 00:47:23 +00006934 // If N is a constant we could fold this into a fallthrough or unconditional
6935 // branch. However that doesn't happen very often in normal code, because
6936 // Instcombine/SimplifyCFG should have handled the available opportunities.
6937 // If we did this folding here, it would be necessary to update the
6938 // MachineBasicBlock CFG, which is awkward.
6939
Nate Begeman750ac1b2006-02-01 07:19:44 +00006940 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6941 // on the target.
Scott Michelfdc40a02009-02-17 22:15:04 +00006942 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellard3ef53832013-03-08 15:36:57 +00006943 TLI.isOperationLegalOrCustom(ISD::BR_CC,
6944 N1.getOperand(0).getValueType())) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006945 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendlingc0debad2009-01-30 23:27:35 +00006946 Chain, N1.getOperand(2),
Nate Begeman750ac1b2006-02-01 07:19:44 +00006947 N1.getOperand(0), N1.getOperand(1), N2);
6948 }
Bill Wendlingc0debad2009-01-30 23:27:35 +00006949
Evan Cheng2a135ae2010-10-04 22:41:01 +00006950 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6951 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6952 (N1.getOperand(0).hasOneUse() &&
6953 N1.getOperand(0).getOpcode() == ISD::SRL))) {
6954 SDNode *Trunc = 0;
6955 if (N1.getOpcode() == ISD::TRUNCATE) {
6956 // Look pass the truncate.
6957 Trunc = N1.getNode();
6958 N1 = N1.getOperand(0);
6959 }
Evan Chengd40d03e2010-01-06 19:38:29 +00006960
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00006961 // Match this pattern so that we can generate simpler code:
6962 //
6963 // %a = ...
6964 // %b = and i32 %a, 2
6965 // %c = srl i32 %b, 1
6966 // brcond i32 %c ...
6967 //
6968 // into
Wesley Peckbf17cfa2010-11-23 03:31:01 +00006969 //
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00006970 // %a = ...
Evan Chengd40d03e2010-01-06 19:38:29 +00006971 // %b = and i32 %a, 2
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00006972 // %c = setcc eq %b, 0
6973 // brcond %c ...
6974 //
6975 // This applies only when the AND constant value has one bit set and the
6976 // SRL constant is equal to the log2 of the AND constant. The back-end is
6977 // smart enough to convert the result into a TEST/JMP sequence.
6978 SDValue Op0 = N1.getOperand(0);
6979 SDValue Op1 = N1.getOperand(1);
6980
6981 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00006982 Op1.getOpcode() == ISD::Constant) {
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00006983 SDValue AndOp1 = Op0.getOperand(1);
6984
6985 if (AndOp1.getOpcode() == ISD::Constant) {
6986 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6987
6988 if (AndConst.isPowerOf2() &&
6989 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6990 SDValue SetCC =
Andrew Trickac6d9be2013-05-25 02:42:55 +00006991 DAG.getSetCC(SDLoc(N),
Matt Arsenault225ed702013-05-18 00:21:46 +00006992 getSetCCResultType(Op0.getValueType()),
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00006993 Op0, DAG.getConstant(0, Op0.getValueType()),
6994 ISD::SETNE);
6995
Andrew Trickac6d9be2013-05-25 02:42:55 +00006996 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Chengd40d03e2010-01-06 19:38:29 +00006997 MVT::Other, Chain, SetCC, N2);
6998 // Don't add the new BRCond into the worklist or else SimplifySelectCC
6999 // will convert it back to (X & C1) >> C2.
7000 CombineTo(N, NewBRCond, false);
7001 // Truncate is dead.
7002 if (Trunc) {
7003 removeFromWorkList(Trunc);
7004 DAG.DeleteNode(Trunc);
7005 }
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007006 // Replace the uses of SRL with SETCC
Evan Cheng2c755ba2010-02-27 07:36:59 +00007007 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007008 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007009 removeFromWorkList(N1.getNode());
7010 DAG.DeleteNode(N1.getNode());
Evan Chengd40d03e2010-01-06 19:38:29 +00007011 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007012 }
7013 }
7014 }
Evan Cheng2a135ae2010-10-04 22:41:01 +00007015
7016 if (Trunc)
7017 // Restore N1 if the above transformation doesn't match.
7018 N1 = N->getOperand(1);
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007019 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00007020
Evan Cheng2c755ba2010-02-27 07:36:59 +00007021 // Transform br(xor(x, y)) -> br(x != y)
7022 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7023 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7024 SDNode *TheXor = N1.getNode();
7025 SDValue Op0 = TheXor->getOperand(0);
7026 SDValue Op1 = TheXor->getOperand(1);
7027 if (Op0.getOpcode() == Op1.getOpcode()) {
7028 // Avoid missing important xor optimizations.
7029 SDValue Tmp = visitXOR(TheXor);
Evan Cheng78ec0252013-01-09 20:56:40 +00007030 if (Tmp.getNode()) {
7031 if (Tmp.getNode() != TheXor) {
7032 DEBUG(dbgs() << "\nReplacing.8 ";
7033 TheXor->dump(&DAG);
7034 dbgs() << "\nWith: ";
7035 Tmp.getNode()->dump(&DAG);
7036 dbgs() << '\n');
7037 WorkListRemover DeadNodes(*this);
7038 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7039 removeFromWorkList(TheXor);
7040 DAG.DeleteNode(TheXor);
Andrew Trickac6d9be2013-05-25 02:42:55 +00007041 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng78ec0252013-01-09 20:56:40 +00007042 MVT::Other, Chain, Tmp, N2);
7043 }
7044
Benjamin Kramer0b68b752013-03-30 21:28:18 +00007045 // visitXOR has changed XOR's operands or replaced the XOR completely,
7046 // bail out.
7047 return SDValue(N, 0);
Evan Cheng2c755ba2010-02-27 07:36:59 +00007048 }
7049 }
7050
7051 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7052 bool Equal = false;
7053 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7054 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7055 Op0.getOpcode() == ISD::XOR) {
7056 TheXor = Op0.getNode();
7057 Equal = true;
7058 }
7059
Evan Cheng2a135ae2010-10-04 22:41:01 +00007060 EVT SetCCVT = N1.getValueType();
Evan Cheng2c755ba2010-02-27 07:36:59 +00007061 if (LegalTypes)
Matt Arsenault225ed702013-05-18 00:21:46 +00007062 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickac6d9be2013-05-25 02:42:55 +00007063 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng2c755ba2010-02-27 07:36:59 +00007064 SetCCVT,
7065 Op0, Op1,
7066 Equal ? ISD::SETEQ : ISD::SETNE);
7067 // Replace the uses of XOR with SETCC
7068 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007069 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Evan Cheng2a135ae2010-10-04 22:41:01 +00007070 removeFromWorkList(N1.getNode());
7071 DAG.DeleteNode(N1.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00007072 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng2c755ba2010-02-27 07:36:59 +00007073 MVT::Other, Chain, SetCC, N2);
7074 }
7075 }
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007076
Dan Gohman475871a2008-07-27 21:46:04 +00007077 return SDValue();
Nate Begeman44728a72005-09-19 22:34:01 +00007078}
7079
Chris Lattner3ea0b472005-10-05 06:47:48 +00007080// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7081//
Dan Gohman475871a2008-07-27 21:46:04 +00007082SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattner3ea0b472005-10-05 06:47:48 +00007083 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman475871a2008-07-27 21:46:04 +00007084 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelfdc40a02009-02-17 22:15:04 +00007085
Dan Gohmane0f06c72009-11-17 00:47:23 +00007086 // If N is a constant we could fold this into a fallthrough or unconditional
7087 // branch. However that doesn't happen very often in normal code, because
7088 // Instcombine/SimplifyCFG should have handled the available opportunities.
7089 // If we did this folding here, it would be necessary to update the
7090 // MachineBasicBlock CFG, which is awkward.
7091
Duncan Sands8eab8a22008-06-09 11:32:28 +00007092 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault225ed702013-05-18 00:21:46 +00007093 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickac6d9be2013-05-25 02:42:55 +00007094 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenff97d4f2009-02-03 00:47:48 +00007095 false);
Gabor Greifba36cb52008-08-28 21:40:38 +00007096 if (Simp.getNode()) AddToWorkList(Simp.getNode());
Chris Lattner30f73e72006-10-14 03:52:46 +00007097
Nate Begemane17daeb2005-10-05 21:43:42 +00007098 // fold to a simpler setcc
Gabor Greifba36cb52008-08-28 21:40:38 +00007099 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007100 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendlingc0debad2009-01-30 23:27:35 +00007101 N->getOperand(0), Simp.getOperand(2),
7102 Simp.getOperand(0), Simp.getOperand(1),
7103 N->getOperand(4));
7104
Dan Gohman475871a2008-07-27 21:46:04 +00007105 return SDValue();
Nate Begeman44728a72005-09-19 22:34:01 +00007106}
7107
Evan Chengc4b527a2012-01-13 01:37:24 +00007108/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7109/// uses N as its base pointer and that N may be folded in the load / store
Evan Cheng03be3622012-03-06 23:33:32 +00007110/// addressing mode.
Evan Chengc4b527a2012-01-13 01:37:24 +00007111static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7112 SelectionDAG &DAG,
7113 const TargetLowering &TLI) {
7114 EVT VT;
7115 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7116 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7117 return false;
7118 VT = Use->getValueType(0);
7119 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7120 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7121 return false;
7122 VT = ST->getValue().getValueType();
7123 } else
7124 return false;
7125
Chandler Carruth56d433d2013-01-07 15:14:13 +00007126 TargetLowering::AddrMode AM;
Evan Chengc4b527a2012-01-13 01:37:24 +00007127 if (N->getOpcode() == ISD::ADD) {
7128 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7129 if (Offset)
Evan Cheng03be3622012-03-06 23:33:32 +00007130 // [reg +/- imm]
Evan Chengc4b527a2012-01-13 01:37:24 +00007131 AM.BaseOffs = Offset->getSExtValue();
7132 else
Evan Cheng03be3622012-03-06 23:33:32 +00007133 // [reg +/- reg]
7134 AM.Scale = 1;
Evan Chengc4b527a2012-01-13 01:37:24 +00007135 } else if (N->getOpcode() == ISD::SUB) {
7136 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7137 if (Offset)
Evan Cheng03be3622012-03-06 23:33:32 +00007138 // [reg +/- imm]
Evan Chengc4b527a2012-01-13 01:37:24 +00007139 AM.BaseOffs = -Offset->getSExtValue();
7140 else
Evan Cheng03be3622012-03-06 23:33:32 +00007141 // [reg +/- reg]
7142 AM.Scale = 1;
Evan Chengc4b527a2012-01-13 01:37:24 +00007143 } else
7144 return false;
7145
7146 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7147}
7148
Duncan Sandsec87aa82008-06-15 20:12:31 +00007149/// CombineToPreIndexedLoadStore - Try turning a load / store into a
7150/// pre-indexed load / store when the base pointer is an add or subtract
Chris Lattner448f2192006-11-11 00:39:41 +00007151/// and it has other uses besides the load / store. After the
7152/// transformation, the new indexed load / store has effectively folded
7153/// the add / subtract in and all of its other uses are redirected to the
7154/// new load / store.
7155bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman50185242011-11-12 00:35:34 +00007156 if (Level < AfterLegalizeDAG)
Chris Lattner448f2192006-11-11 00:39:41 +00007157 return false;
7158
7159 bool isLoad = true;
Dan Gohman475871a2008-07-27 21:46:04 +00007160 SDValue Ptr;
Owen Andersone50ed302009-08-10 22:56:29 +00007161 EVT VT;
Chris Lattner448f2192006-11-11 00:39:41 +00007162 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattnerddf89562008-01-17 19:59:44 +00007163 if (LD->isIndexed())
Evan Chenge90460e2006-12-16 06:25:23 +00007164 return false;
Dan Gohmanb625f2f2008-01-30 00:15:11 +00007165 VT = LD->getMemoryVT();
Evan Cheng83060c52007-03-07 08:07:03 +00007166 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattner448f2192006-11-11 00:39:41 +00007167 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7168 return false;
7169 Ptr = LD->getBasePtr();
7170 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattnerddf89562008-01-17 19:59:44 +00007171 if (ST->isIndexed())
Evan Chenge90460e2006-12-16 06:25:23 +00007172 return false;
Dan Gohmanb625f2f2008-01-30 00:15:11 +00007173 VT = ST->getMemoryVT();
Chris Lattner448f2192006-11-11 00:39:41 +00007174 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7175 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7176 return false;
7177 Ptr = ST->getBasePtr();
7178 isLoad = false;
Bill Wendlingc0debad2009-01-30 23:27:35 +00007179 } else {
Chris Lattner448f2192006-11-11 00:39:41 +00007180 return false;
Bill Wendlingc0debad2009-01-30 23:27:35 +00007181 }
Chris Lattner448f2192006-11-11 00:39:41 +00007182
Chris Lattner9f1794e2006-11-11 00:56:29 +00007183 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7184 // out. There is no reason to make this a preinc/predec.
7185 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greifba36cb52008-08-28 21:40:38 +00007186 Ptr.getNode()->hasOneUse())
Chris Lattner9f1794e2006-11-11 00:56:29 +00007187 return false;
Chris Lattner448f2192006-11-11 00:39:41 +00007188
Chris Lattner9f1794e2006-11-11 00:56:29 +00007189 // Ask the target to do addressing mode selection.
Dan Gohman475871a2008-07-27 21:46:04 +00007190 SDValue BasePtr;
7191 SDValue Offset;
Chris Lattner9f1794e2006-11-11 00:56:29 +00007192 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7193 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7194 return false;
Hal Finkel089a5f82013-02-08 21:35:47 +00007195
7196 // Backends without true r+i pre-indexed forms may need to pass a
7197 // constant base with a variable offset so that constant coercion
7198 // will work with the patterns in canonical form.
7199 bool Swapped = false;
7200 if (isa<ConstantSDNode>(BasePtr)) {
7201 std::swap(BasePtr, Offset);
7202 Swapped = true;
7203 }
7204
Evan Chenga7d4a042007-05-03 23:52:19 +00007205 // Don't create a indexed load / store with zero offset.
7206 if (isa<ConstantSDNode>(Offset) &&
Dan Gohman002e5d02008-03-13 22:13:53 +00007207 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Chenga7d4a042007-05-03 23:52:19 +00007208 return false;
Scott Michelfdc40a02009-02-17 22:15:04 +00007209
Chris Lattner41e53fd2006-11-11 01:00:15 +00007210 // Try turning it into a pre-indexed load / store except when:
Evan Chengc843abe2007-05-24 02:35:39 +00007211 // 1) The new base ptr is a frame index.
7212 // 2) If N is a store and the new base ptr is either the same as or is a
Chris Lattner9f1794e2006-11-11 00:56:29 +00007213 // predecessor of the value being stored.
Evan Chengc843abe2007-05-24 02:35:39 +00007214 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattner9f1794e2006-11-11 00:56:29 +00007215 // that would create a cycle.
Evan Chengc843abe2007-05-24 02:35:39 +00007216 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattner448f2192006-11-11 00:39:41 +00007217
Chris Lattner41e53fd2006-11-11 01:00:15 +00007218 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7219 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcaab1292009-05-06 18:25:01 +00007220 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattner41e53fd2006-11-11 01:00:15 +00007221 return false;
Scott Michelfdc40a02009-02-17 22:15:04 +00007222
Chris Lattner41e53fd2006-11-11 01:00:15 +00007223 // Check #2.
Chris Lattner9f1794e2006-11-11 00:56:29 +00007224 if (!isLoad) {
Dan Gohman475871a2008-07-27 21:46:04 +00007225 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greifba36cb52008-08-28 21:40:38 +00007226 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattner9f1794e2006-11-11 00:56:29 +00007227 return false;
Chris Lattner448f2192006-11-11 00:39:41 +00007228 }
Chris Lattner9f1794e2006-11-11 00:56:29 +00007229
Hal Finkel089a5f82013-02-08 21:35:47 +00007230 // If the offset is a constant, there may be other adds of constants that
7231 // can be folded with this one. We should do this to avoid having to keep
7232 // a copy of the original base pointer.
7233 SmallVector<SDNode *, 16> OtherUses;
7234 if (isa<ConstantSDNode>(Offset))
7235 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7236 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7237 SDNode *Use = *I;
7238 if (Use == Ptr.getNode())
7239 continue;
7240
7241 if (Use->isPredecessorOf(N))
7242 continue;
7243
7244 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7245 OtherUses.clear();
7246 break;
7247 }
7248
7249 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7250 if (Op1.getNode() == BasePtr.getNode())
7251 std::swap(Op0, Op1);
7252 assert(Op0.getNode() == BasePtr.getNode() &&
7253 "Use of ADD/SUB but not an operand");
7254
7255 if (!isa<ConstantSDNode>(Op1)) {
7256 OtherUses.clear();
7257 break;
7258 }
7259
7260 // FIXME: In some cases, we can be smarter about this.
7261 if (Op1.getValueType() != Offset.getValueType()) {
7262 OtherUses.clear();
7263 break;
7264 }
7265
7266 OtherUses.push_back(Use);
7267 }
7268
7269 if (Swapped)
7270 std::swap(BasePtr, Offset);
7271
Evan Chengc843abe2007-05-24 02:35:39 +00007272 // Now check for #3 and #4.
Chris Lattner9f1794e2006-11-11 00:56:29 +00007273 bool RealUse = false;
Lang Hames944520f2011-07-07 04:31:51 +00007274
7275 // Caches for hasPredecessorHelper
7276 SmallPtrSet<const SDNode *, 32> Visited;
7277 SmallVector<const SDNode *, 16> Worklist;
7278
Gabor Greifba36cb52008-08-28 21:40:38 +00007279 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7280 E = Ptr.getNode()->use_end(); I != E; ++I) {
Dan Gohman89684502008-07-27 20:43:25 +00007281 SDNode *Use = *I;
Chris Lattner9f1794e2006-11-11 00:56:29 +00007282 if (Use == N)
7283 continue;
Lang Hames944520f2011-07-07 04:31:51 +00007284 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattner9f1794e2006-11-11 00:56:29 +00007285 return false;
7286
Evan Chengc4b527a2012-01-13 01:37:24 +00007287 // If Ptr may be folded in addressing mode of other use, then it's
7288 // not profitable to do this transformation.
7289 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattner9f1794e2006-11-11 00:56:29 +00007290 RealUse = true;
7291 }
Bill Wendlingc0debad2009-01-30 23:27:35 +00007292
Chris Lattner9f1794e2006-11-11 00:56:29 +00007293 if (!RealUse)
7294 return false;
7295
Dan Gohman475871a2008-07-27 21:46:04 +00007296 SDValue Result;
Chris Lattner9f1794e2006-11-11 00:56:29 +00007297 if (isLoad)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007298 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendlingc0debad2009-01-30 23:27:35 +00007299 BasePtr, Offset, AM);
Chris Lattner9f1794e2006-11-11 00:56:29 +00007300 else
Andrew Trickac6d9be2013-05-25 02:42:55 +00007301 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendlingc0debad2009-01-30 23:27:35 +00007302 BasePtr, Offset, AM);
Chris Lattner9f1794e2006-11-11 00:56:29 +00007303 ++PreIndexedNodes;
7304 ++NodesCombined;
David Greenef1090292010-01-05 01:25:00 +00007305 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00007306 N->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00007307 dbgs() << "\nWith: ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00007308 Result.getNode()->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00007309 dbgs() << '\n');
Chris Lattnerf8dc0612008-02-03 06:49:24 +00007310 WorkListRemover DeadNodes(*this);
Chris Lattner9f1794e2006-11-11 00:56:29 +00007311 if (isLoad) {
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007312 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7313 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattner9f1794e2006-11-11 00:56:29 +00007314 } else {
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007315 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattner9f1794e2006-11-11 00:56:29 +00007316 }
7317
Chris Lattner9f1794e2006-11-11 00:56:29 +00007318 // Finally, since the node is now dead, remove it from the graph.
7319 DAG.DeleteNode(N);
7320
Hal Finkel089a5f82013-02-08 21:35:47 +00007321 if (Swapped)
7322 std::swap(BasePtr, Offset);
7323
7324 // Replace other uses of BasePtr that can be updated to use Ptr
7325 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7326 unsigned OffsetIdx = 1;
7327 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7328 OffsetIdx = 0;
7329 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7330 BasePtr.getNode() && "Expected BasePtr operand");
7331
Silviu Baranga730a5702013-04-26 15:52:24 +00007332 // We need to replace ptr0 in the following expression:
7333 // x0 * offset0 + y0 * ptr0 = t0
7334 // knowing that
7335 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lin155615d2013-07-08 00:37:03 +00007336 //
Silviu Baranga730a5702013-04-26 15:52:24 +00007337 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7338 // indexed load/store and the expresion that needs to be re-written.
7339 //
7340 // Therefore, we have:
7341 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel089a5f82013-02-08 21:35:47 +00007342
7343 ConstantSDNode *CN =
7344 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Baranga730a5702013-04-26 15:52:24 +00007345 int X0, X1, Y0, Y1;
7346 APInt Offset0 = CN->getAPIntValue();
7347 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel089a5f82013-02-08 21:35:47 +00007348
Silviu Baranga730a5702013-04-26 15:52:24 +00007349 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7350 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7351 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7352 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel089a5f82013-02-08 21:35:47 +00007353
Silviu Baranga730a5702013-04-26 15:52:24 +00007354 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7355
7356 APInt CNV = Offset0;
7357 if (X0 < 0) CNV = -CNV;
7358 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7359 else CNV = CNV - Offset1;
7360
7361 // We can now generate the new expression.
7362 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7363 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7364
7365 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickac6d9be2013-05-25 02:42:55 +00007366 SDLoc(OtherUses[i]),
Hal Finkel089a5f82013-02-08 21:35:47 +00007367 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7368 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7369 removeFromWorkList(OtherUses[i]);
7370 DAG.DeleteNode(OtherUses[i]);
7371 }
7372
Chris Lattner9f1794e2006-11-11 00:56:29 +00007373 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007374 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Gabor Greifba36cb52008-08-28 21:40:38 +00007375 removeFromWorkList(Ptr.getNode());
7376 DAG.DeleteNode(Ptr.getNode());
Chris Lattner9f1794e2006-11-11 00:56:29 +00007377
7378 return true;
Chris Lattner448f2192006-11-11 00:39:41 +00007379}
7380
Duncan Sandsec87aa82008-06-15 20:12:31 +00007381/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
Chris Lattner448f2192006-11-11 00:39:41 +00007382/// add / sub of the base pointer node into a post-indexed load / store.
7383/// The transformation folded the add / subtract into the new indexed
7384/// load / store effectively and all of its uses are redirected to the
7385/// new load / store.
7386bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman50185242011-11-12 00:35:34 +00007387 if (Level < AfterLegalizeDAG)
Chris Lattner448f2192006-11-11 00:39:41 +00007388 return false;
7389
7390 bool isLoad = true;
Dan Gohman475871a2008-07-27 21:46:04 +00007391 SDValue Ptr;
Owen Andersone50ed302009-08-10 22:56:29 +00007392 EVT VT;
Chris Lattner448f2192006-11-11 00:39:41 +00007393 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattnerddf89562008-01-17 19:59:44 +00007394 if (LD->isIndexed())
Evan Chenge90460e2006-12-16 06:25:23 +00007395 return false;
Dan Gohmanb625f2f2008-01-30 00:15:11 +00007396 VT = LD->getMemoryVT();
Chris Lattner448f2192006-11-11 00:39:41 +00007397 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7398 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7399 return false;
7400 Ptr = LD->getBasePtr();
7401 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattnerddf89562008-01-17 19:59:44 +00007402 if (ST->isIndexed())
Evan Chenge90460e2006-12-16 06:25:23 +00007403 return false;
Dan Gohmanb625f2f2008-01-30 00:15:11 +00007404 VT = ST->getMemoryVT();
Chris Lattner448f2192006-11-11 00:39:41 +00007405 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7406 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7407 return false;
7408 Ptr = ST->getBasePtr();
7409 isLoad = false;
Bill Wendlingc0debad2009-01-30 23:27:35 +00007410 } else {
Chris Lattner448f2192006-11-11 00:39:41 +00007411 return false;
Bill Wendlingc0debad2009-01-30 23:27:35 +00007412 }
Chris Lattner448f2192006-11-11 00:39:41 +00007413
Gabor Greifba36cb52008-08-28 21:40:38 +00007414 if (Ptr.getNode()->hasOneUse())
Chris Lattner9f1794e2006-11-11 00:56:29 +00007415 return false;
Scott Michelfdc40a02009-02-17 22:15:04 +00007416
Gabor Greifba36cb52008-08-28 21:40:38 +00007417 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7418 E = Ptr.getNode()->use_end(); I != E; ++I) {
Dan Gohman89684502008-07-27 20:43:25 +00007419 SDNode *Op = *I;
Chris Lattner9f1794e2006-11-11 00:56:29 +00007420 if (Op == N ||
7421 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7422 continue;
7423
Dan Gohman475871a2008-07-27 21:46:04 +00007424 SDValue BasePtr;
7425 SDValue Offset;
Chris Lattner9f1794e2006-11-11 00:56:29 +00007426 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7427 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Chenga7d4a042007-05-03 23:52:19 +00007428 // Don't create a indexed load / store with zero offset.
7429 if (isa<ConstantSDNode>(Offset) &&
Dan Gohman002e5d02008-03-13 22:13:53 +00007430 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Chenga7d4a042007-05-03 23:52:19 +00007431 continue;
Chris Lattner448f2192006-11-11 00:39:41 +00007432
Chris Lattner9f1794e2006-11-11 00:56:29 +00007433 // Try turning it into a post-indexed load / store except when
Evan Chengc4b527a2012-01-13 01:37:24 +00007434 // 1) All uses are load / store ops that use it as base ptr (and
7435 // it may be folded as addressing mmode).
Chris Lattner9f1794e2006-11-11 00:56:29 +00007436 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7437 // nor a successor of N. Otherwise, if Op is folded that would
7438 // create a cycle.
7439
Evan Chengcaab1292009-05-06 18:25:01 +00007440 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7441 continue;
7442
Chris Lattner9f1794e2006-11-11 00:56:29 +00007443 // Check for #1.
7444 bool TryNext = false;
Gabor Greifba36cb52008-08-28 21:40:38 +00007445 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7446 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
Dan Gohman89684502008-07-27 20:43:25 +00007447 SDNode *Use = *II;
Gabor Greifba36cb52008-08-28 21:40:38 +00007448 if (Use == Ptr.getNode())
Chris Lattner448f2192006-11-11 00:39:41 +00007449 continue;
7450
Chris Lattner9f1794e2006-11-11 00:56:29 +00007451 // If all the uses are load / store addresses, then don't do the
7452 // transformation.
7453 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7454 bool RealUse = false;
7455 for (SDNode::use_iterator III = Use->use_begin(),
7456 EEE = Use->use_end(); III != EEE; ++III) {
Dan Gohman89684502008-07-27 20:43:25 +00007457 SDNode *UseUse = *III;
Stephen Lin155615d2013-07-08 00:37:03 +00007458 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattner9f1794e2006-11-11 00:56:29 +00007459 RealUse = true;
7460 }
Chris Lattner448f2192006-11-11 00:39:41 +00007461
Chris Lattner9f1794e2006-11-11 00:56:29 +00007462 if (!RealUse) {
7463 TryNext = true;
7464 break;
Chris Lattner448f2192006-11-11 00:39:41 +00007465 }
7466 }
Chris Lattner9f1794e2006-11-11 00:56:29 +00007467 }
Bill Wendlingc0debad2009-01-30 23:27:35 +00007468
Chris Lattner9f1794e2006-11-11 00:56:29 +00007469 if (TryNext)
7470 continue;
Chris Lattner448f2192006-11-11 00:39:41 +00007471
Chris Lattner9f1794e2006-11-11 00:56:29 +00007472 // Check for #2
Evan Cheng917be682008-03-04 00:41:45 +00007473 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman475871a2008-07-27 21:46:04 +00007474 SDValue Result = isLoad
Andrew Trickac6d9be2013-05-25 02:42:55 +00007475 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendlingc0debad2009-01-30 23:27:35 +00007476 BasePtr, Offset, AM)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007477 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendlingc0debad2009-01-30 23:27:35 +00007478 BasePtr, Offset, AM);
Chris Lattner9f1794e2006-11-11 00:56:29 +00007479 ++PostIndexedNodes;
7480 ++NodesCombined;
David Greenef1090292010-01-05 01:25:00 +00007481 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00007482 N->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00007483 dbgs() << "\nWith: ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00007484 Result.getNode()->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00007485 dbgs() << '\n');
Chris Lattnerf8dc0612008-02-03 06:49:24 +00007486 WorkListRemover DeadNodes(*this);
Chris Lattner9f1794e2006-11-11 00:56:29 +00007487 if (isLoad) {
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007488 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7489 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattner9f1794e2006-11-11 00:56:29 +00007490 } else {
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007491 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattner448f2192006-11-11 00:39:41 +00007492 }
Chris Lattner9f1794e2006-11-11 00:56:29 +00007493
Chris Lattner9f1794e2006-11-11 00:56:29 +00007494 // Finally, since the node is now dead, remove it from the graph.
7495 DAG.DeleteNode(N);
7496
7497 // Replace the uses of Use with uses of the updated base value.
Dan Gohman475871a2008-07-27 21:46:04 +00007498 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007499 Result.getValue(isLoad ? 1 : 0));
Chris Lattner9f1794e2006-11-11 00:56:29 +00007500 removeFromWorkList(Op);
Chris Lattner9f1794e2006-11-11 00:56:29 +00007501 DAG.DeleteNode(Op);
Chris Lattner9f1794e2006-11-11 00:56:29 +00007502 return true;
Chris Lattner448f2192006-11-11 00:39:41 +00007503 }
7504 }
7505 }
Bill Wendlingc0debad2009-01-30 23:27:35 +00007506
Chris Lattner448f2192006-11-11 00:39:41 +00007507 return false;
7508}
7509
Dan Gohman475871a2008-07-27 21:46:04 +00007510SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Cheng466685d2006-10-09 20:57:25 +00007511 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman475871a2008-07-27 21:46:04 +00007512 SDValue Chain = LD->getChain();
7513 SDValue Ptr = LD->getBasePtr();
Scott Michelfdc40a02009-02-17 22:15:04 +00007514
Evan Cheng45a7ca92007-05-01 00:38:21 +00007515 // If load is not volatile and there are no uses of the loaded value (and
7516 // the updated indexed value in case of indexed loads), change uses of the
7517 // chain value into uses of the chain input (i.e. delete the dead load).
7518 if (!LD->isVolatile()) {
Owen Anderson825b72b2009-08-11 20:47:22 +00007519 if (N->getValueType(1) == MVT::Other) {
Evan Cheng498f5592007-05-01 08:53:39 +00007520 // Unindexed loads.
Craig Topper704e1a02012-01-07 18:31:09 +00007521 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng02c42852008-01-16 23:11:54 +00007522 // It's not safe to use the two value CombineTo variant here. e.g.
7523 // v1, chain2 = load chain1, loc
7524 // v2, chain3 = load chain2, loc
7525 // v3 = add v2, c
Chris Lattner125991a2008-01-24 07:57:06 +00007526 // Now we replace use of chain2 with chain1. This makes the second load
7527 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenef1090292010-01-05 01:25:00 +00007528 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00007529 N->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00007530 dbgs() << "\nWith chain: ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00007531 Chain.getNode()->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00007532 dbgs() << "\n");
Chris Lattnerf8dc0612008-02-03 06:49:24 +00007533 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007534 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendlingc0debad2009-01-30 23:27:35 +00007535
Chris Lattner125991a2008-01-24 07:57:06 +00007536 if (N->use_empty()) {
7537 removeFromWorkList(N);
7538 DAG.DeleteNode(N);
7539 }
Bill Wendlingc0debad2009-01-30 23:27:35 +00007540
Dan Gohman475871a2008-07-27 21:46:04 +00007541 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng02c42852008-01-16 23:11:54 +00007542 }
Evan Cheng498f5592007-05-01 08:53:39 +00007543 } else {
7544 // Indexed loads.
Owen Anderson825b72b2009-08-11 20:47:22 +00007545 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Craig Topper704e1a02012-01-07 18:31:09 +00007546 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
Dale Johannesene8d72302009-02-06 23:05:02 +00007547 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Evan Cheng2c755ba2010-02-27 07:36:59 +00007548 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00007549 N->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00007550 dbgs() << "\nWith: ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00007551 Undef.getNode()->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00007552 dbgs() << " and 2 other values\n");
Chris Lattnerf8dc0612008-02-03 06:49:24 +00007553 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007554 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Dan Gohman475871a2008-07-27 21:46:04 +00007555 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007556 DAG.getUNDEF(N->getValueType(1)));
7557 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Evan Cheng02c42852008-01-16 23:11:54 +00007558 removeFromWorkList(N);
Evan Cheng02c42852008-01-16 23:11:54 +00007559 DAG.DeleteNode(N);
Dan Gohman475871a2008-07-27 21:46:04 +00007560 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng45a7ca92007-05-01 00:38:21 +00007561 }
Evan Cheng45a7ca92007-05-01 00:38:21 +00007562 }
7563 }
Scott Michelfdc40a02009-02-17 22:15:04 +00007564
Chris Lattner01a22022005-10-10 22:04:48 +00007565 // If this load is directly stored, replace the load value with the stored
7566 // value.
7567 // TODO: Handle store large -> read small portion.
Jim Laskeyc2b19f32006-10-11 17:47:52 +00007568 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Cheng9ef82ce2011-03-11 00:48:56 +00007569 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greifba36cb52008-08-28 21:40:38 +00007570 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Cheng8b2794a2006-10-13 21:14:26 +00007571 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7572 if (PrevST->getBasePtr() == Ptr &&
7573 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskeyc2b19f32006-10-11 17:47:52 +00007574 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Cheng8b2794a2006-10-13 21:14:26 +00007575 }
Jim Laskeyc2b19f32006-10-11 17:47:52 +00007576 }
Scott Michelfdc40a02009-02-17 22:15:04 +00007577
Evan Cheng255f20f2010-04-01 06:04:33 +00007578 // Try to infer better alignment information than the load already has.
7579 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Chenged1c0c72011-11-28 22:37:34 +00007580 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonb48783b2013-02-05 19:24:39 +00007581 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7582 SDValue NewLoad =
Andrew Trickac6d9be2013-05-25 02:42:55 +00007583 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Chenged1c0c72011-11-28 22:37:34 +00007584 LD->getValueType(0),
7585 Chain, Ptr, LD->getPointerInfo(),
7586 LD->getMemoryVT(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00007587 LD->isVolatile(), LD->isNonTemporal(), Align,
7588 LD->getTBAAInfo());
Owen Andersonb48783b2013-02-05 19:24:39 +00007589 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7590 }
Evan Cheng255f20f2010-04-01 06:04:33 +00007591 }
7592 }
7593
Hal Finkel253acef2013-08-29 03:29:55 +00007594 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7595 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7596 if (UseAA) {
Jim Laskey279f0532006-09-25 16:29:54 +00007597 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman475871a2008-07-27 21:46:04 +00007598 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelfdc40a02009-02-17 22:15:04 +00007599
Jim Laskey6ff23e52006-10-04 16:53:27 +00007600 // If there is a better chain.
Jim Laskey279f0532006-09-25 16:29:54 +00007601 if (Chain != BetterChain) {
Dan Gohman475871a2008-07-27 21:46:04 +00007602 SDValue ReplLoad;
Jim Laskeyc2b19f32006-10-11 17:47:52 +00007603
Jim Laskey279f0532006-09-25 16:29:54 +00007604 // Replace the chain to void dependency.
Jim Laskeyc2b19f32006-10-11 17:47:52 +00007605 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00007606 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford66589dc2013-10-28 11:17:59 +00007607 BetterChain, Ptr, LD->getMemOperand());
Jim Laskeyc2b19f32006-10-11 17:47:52 +00007608 } else {
Andrew Trickac6d9be2013-05-25 02:42:55 +00007609 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastingsa9011292011-02-16 16:23:55 +00007610 LD->getValueType(0),
Richard Sandiford66589dc2013-10-28 11:17:59 +00007611 BetterChain, Ptr, LD->getMemoryVT(),
7612 LD->getMemOperand());
Jim Laskeyc2b19f32006-10-11 17:47:52 +00007613 }
Jim Laskey279f0532006-09-25 16:29:54 +00007614
Jim Laskey6ff23e52006-10-04 16:53:27 +00007615 // Create token factor to keep old chain connected.
Andrew Trickac6d9be2013-05-25 02:42:55 +00007616 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson825b72b2009-08-11 20:47:22 +00007617 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00007618
Nate Begemanb6aef5c2009-09-15 00:18:30 +00007619 // Make sure the new and old chains are cleaned up.
7620 AddToWorkList(Token.getNode());
Wesley Peckbf17cfa2010-11-23 03:31:01 +00007621
Jim Laskey274062c2006-10-13 23:32:28 +00007622 // Replace uses with load result and token factor. Don't add users
7623 // to work list.
7624 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskey279f0532006-09-25 16:29:54 +00007625 }
7626 }
7627
Evan Cheng7fc033a2006-11-03 03:06:21 +00007628 // Try transforming N to an indexed load.
Evan Chengbbd6f6e2006-11-07 09:03:05 +00007629 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman475871a2008-07-27 21:46:04 +00007630 return SDValue(N, 0);
Evan Cheng7fc033a2006-11-03 03:06:21 +00007631
Quentin Colombet83f743a2013-10-11 18:29:42 +00007632 // Try to slice up N to more direct loads if the slices are mapped to
7633 // different register banks or pairing can take place.
7634 if (SliceUpLoad(N))
7635 return SDValue(N, 0);
7636
Dan Gohman475871a2008-07-27 21:46:04 +00007637 return SDValue();
Chris Lattner01a22022005-10-10 22:04:48 +00007638}
7639
Quentin Colombet83f743a2013-10-11 18:29:42 +00007640namespace {
7641/// \brief Helper structure used to slice a load in smaller loads.
7642/// Basically a slice is obtained from the following sequence:
7643/// Origin = load Ty1, Base
7644/// Shift = srl Ty1 Origin, CstTy Amount
7645/// Inst = trunc Shift to Ty2
7646///
7647/// Then, it will be rewriten into:
7648/// Slice = load SliceTy, Base + SliceOffset
7649/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7650///
7651/// SliceTy is deduced from the number of bits that are actually used to
7652/// build Inst.
7653struct LoadedSlice {
7654 /// \brief Helper structure used to compute the cost of a slice.
7655 struct Cost {
7656 /// Are we optimizing for code size.
7657 bool ForCodeSize;
7658 /// Various cost.
7659 unsigned Loads;
7660 unsigned Truncates;
7661 unsigned CrossRegisterBanksCopies;
7662 unsigned ZExts;
7663 unsigned Shift;
7664
7665 Cost(bool ForCodeSize = false)
7666 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7667 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7668
7669 /// \brief Get the cost of one isolated slice.
7670 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7671 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7672 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7673 EVT TruncType = LS.Inst->getValueType(0);
7674 EVT LoadedType = LS.getLoadedType();
7675 if (TruncType != LoadedType &&
7676 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7677 ZExts = 1;
7678 }
7679
7680 /// \brief Account for slicing gain in the current cost.
7681 /// Slicing provide a few gains like removing a shift or a
7682 /// truncate. This method allows to grow the cost of the original
7683 /// load with the gain from this slice.
7684 void addSliceGain(const LoadedSlice &LS) {
7685 // Each slice saves a truncate.
7686 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7687 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7688 LS.Inst->getOperand(0).getValueType()))
7689 ++Truncates;
7690 // If there is a shift amount, this slice gets rid of it.
7691 if (LS.Shift)
7692 ++Shift;
7693 // If this slice can merge a cross register bank copy, account for it.
7694 if (LS.canMergeExpensiveCrossRegisterBankCopy())
7695 ++CrossRegisterBanksCopies;
7696 }
7697
7698 Cost &operator+=(const Cost &RHS) {
7699 Loads += RHS.Loads;
7700 Truncates += RHS.Truncates;
7701 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
7702 ZExts += RHS.ZExts;
7703 Shift += RHS.Shift;
7704 return *this;
7705 }
7706
7707 bool operator==(const Cost &RHS) const {
7708 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
7709 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
7710 ZExts == RHS.ZExts && Shift == RHS.Shift;
7711 }
7712
7713 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
7714
7715 bool operator<(const Cost &RHS) const {
7716 // Assume cross register banks copies are as expensive as loads.
7717 // FIXME: Do we want some more target hooks?
7718 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
7719 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
7720 // Unless we are optimizing for code size, consider the
7721 // expensive operation first.
7722 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
7723 return ExpensiveOpsLHS < ExpensiveOpsRHS;
7724 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
7725 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
7726 }
7727
7728 bool operator>(const Cost &RHS) const { return RHS < *this; }
7729
7730 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
7731
7732 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
7733 };
7734 // The last instruction that represent the slice. This should be a
7735 // truncate instruction.
7736 SDNode *Inst;
7737 // The original load instruction.
7738 LoadSDNode *Origin;
7739 // The right shift amount in bits from the original load.
7740 unsigned Shift;
7741 // The DAG from which Origin came from.
7742 // This is used to get some contextual information about legal types, etc.
7743 SelectionDAG *DAG;
7744
7745 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
7746 unsigned Shift = 0, SelectionDAG *DAG = NULL)
7747 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
7748
7749 LoadedSlice(const LoadedSlice &LS)
7750 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
7751
7752 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
7753 /// \return Result is \p BitWidth and has used bits set to 1 and
7754 /// not used bits set to 0.
7755 APInt getUsedBits() const {
7756 // Reproduce the trunc(lshr) sequence:
7757 // - Start from the truncated value.
7758 // - Zero extend to the desired bit width.
7759 // - Shift left.
7760 assert(Origin && "No original load to compare against.");
7761 unsigned BitWidth = Origin->getValueSizeInBits(0);
7762 assert(Inst && "This slice is not bound to an instruction");
7763 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
7764 "Extracted slice is bigger than the whole type!");
7765 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
7766 UsedBits.setAllBits();
7767 UsedBits = UsedBits.zext(BitWidth);
7768 UsedBits <<= Shift;
7769 return UsedBits;
7770 }
7771
7772 /// \brief Get the size of the slice to be loaded in bytes.
7773 unsigned getLoadedSize() const {
7774 unsigned SliceSize = getUsedBits().countPopulation();
7775 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
7776 return SliceSize / 8;
7777 }
7778
7779 /// \brief Get the type that will be loaded for this slice.
7780 /// Note: This may not be the final type for the slice.
7781 EVT getLoadedType() const {
7782 assert(DAG && "Missing context");
7783 LLVMContext &Ctxt = *DAG->getContext();
7784 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
7785 }
7786
7787 /// \brief Get the alignment of the load used for this slice.
7788 unsigned getAlignment() const {
7789 unsigned Alignment = Origin->getAlignment();
7790 unsigned Offset = getOffsetFromBase();
7791 if (Offset != 0)
7792 Alignment = MinAlign(Alignment, Alignment + Offset);
7793 return Alignment;
7794 }
7795
7796 /// \brief Check if this slice can be rewritten with legal operations.
7797 bool isLegal() const {
7798 // An invalid slice is not legal.
7799 if (!Origin || !Inst || !DAG)
7800 return false;
7801
7802 // Offsets are for indexed load only, we do not handle that.
7803 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
7804 return false;
7805
7806 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7807
7808 // Check that the type is legal.
7809 EVT SliceType = getLoadedType();
7810 if (!TLI.isTypeLegal(SliceType))
7811 return false;
7812
7813 // Check that the load is legal for this type.
7814 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
7815 return false;
7816
7817 // Check that the offset can be computed.
7818 // 1. Check its type.
7819 EVT PtrType = Origin->getBasePtr().getValueType();
7820 if (PtrType == MVT::Untyped || PtrType.isExtended())
7821 return false;
7822
7823 // 2. Check that it fits in the immediate.
7824 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
7825 return false;
7826
7827 // 3. Check that the computation is legal.
7828 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
7829 return false;
7830
7831 // Check that the zext is legal if it needs one.
7832 EVT TruncateType = Inst->getValueType(0);
7833 if (TruncateType != SliceType &&
7834 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
7835 return false;
7836
7837 return true;
7838 }
7839
7840 /// \brief Get the offset in bytes of this slice in the original chunk of
7841 /// bits.
7842 /// \pre DAG != NULL.
7843 uint64_t getOffsetFromBase() const {
7844 assert(DAG && "Missing context.");
7845 bool IsBigEndian =
7846 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
7847 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
7848 uint64_t Offset = Shift / 8;
7849 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
7850 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
7851 "The size of the original loaded type is not a multiple of a"
7852 " byte.");
7853 // If Offset is bigger than TySizeInBytes, it means we are loading all
7854 // zeros. This should have been optimized before in the process.
7855 assert(TySizeInBytes > Offset &&
7856 "Invalid shift amount for given loaded size");
7857 if (IsBigEndian)
7858 Offset = TySizeInBytes - Offset - getLoadedSize();
7859 return Offset;
7860 }
7861
7862 /// \brief Generate the sequence of instructions to load the slice
7863 /// represented by this object and redirect the uses of this slice to
7864 /// this new sequence of instructions.
7865 /// \pre this->Inst && this->Origin are valid Instructions and this
7866 /// object passed the legal check: LoadedSlice::isLegal returned true.
7867 /// \return The last instruction of the sequence used to load the slice.
7868 SDValue loadSlice() const {
7869 assert(Inst && Origin && "Unable to replace a non-existing slice.");
7870 const SDValue &OldBaseAddr = Origin->getBasePtr();
7871 SDValue BaseAddr = OldBaseAddr;
7872 // Get the offset in that chunk of bytes w.r.t. the endianess.
7873 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
7874 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
7875 if (Offset) {
7876 // BaseAddr = BaseAddr + Offset.
7877 EVT ArithType = BaseAddr.getValueType();
7878 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
7879 DAG->getConstant(Offset, ArithType));
7880 }
7881
7882 // Create the type of the loaded slice according to its size.
7883 EVT SliceType = getLoadedType();
7884
7885 // Create the load for the slice.
7886 SDValue LastInst = DAG->getLoad(
7887 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
7888 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
7889 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
7890 // If the final type is not the same as the loaded type, this means that
7891 // we have to pad with zero. Create a zero extend for that.
7892 EVT FinalType = Inst->getValueType(0);
7893 if (SliceType != FinalType)
7894 LastInst =
7895 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
7896 return LastInst;
7897 }
7898
7899 /// \brief Check if this slice can be merged with an expensive cross register
7900 /// bank copy. E.g.,
7901 /// i = load i32
7902 /// f = bitcast i32 i to float
7903 bool canMergeExpensiveCrossRegisterBankCopy() const {
7904 if (!Inst || !Inst->hasOneUse())
7905 return false;
7906 SDNode *Use = *Inst->use_begin();
7907 if (Use->getOpcode() != ISD::BITCAST)
7908 return false;
7909 assert(DAG && "Missing context");
7910 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7911 EVT ResVT = Use->getValueType(0);
7912 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
7913 const TargetRegisterClass *ArgRC =
7914 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
7915 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
7916 return false;
7917
7918 // At this point, we know that we perform a cross-register-bank copy.
7919 // Check if it is expensive.
7920 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
7921 // Assume bitcasts are cheap, unless both register classes do not
7922 // explicitly share a common sub class.
7923 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
7924 return false;
7925
7926 // Check if it will be merged with the load.
7927 // 1. Check the alignment constraint.
7928 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
7929 ResVT.getTypeForEVT(*DAG->getContext()));
7930
7931 if (RequiredAlignment > getAlignment())
7932 return false;
7933
7934 // 2. Check that the load is a legal operation for that type.
7935 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
7936 return false;
7937
7938 // 3. Check that we do not have a zext in the way.
7939 if (Inst->getValueType(0) != getLoadedType())
7940 return false;
7941
7942 return true;
7943 }
7944};
7945}
7946
7947/// \brief Sorts LoadedSlice according to their offset.
7948struct LoadedSliceSorter {
7949 bool operator()(const LoadedSlice &LHS, const LoadedSlice &RHS) {
7950 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
7951 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
7952 }
7953};
7954
7955/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
7956/// \p UsedBits looks like 0..0 1..1 0..0.
7957static bool areUsedBitsDense(const APInt &UsedBits) {
7958 // If all the bits are one, this is dense!
7959 if (UsedBits.isAllOnesValue())
7960 return true;
7961
7962 // Get rid of the unused bits on the right.
7963 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
7964 // Get rid of the unused bits on the left.
7965 if (NarrowedUsedBits.countLeadingZeros())
7966 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
7967 // Check that the chunk of bits is completely used.
7968 return NarrowedUsedBits.isAllOnesValue();
7969}
7970
7971/// \brief Check whether or not \p First and \p Second are next to each other
7972/// in memory. This means that there is no hole between the bits loaded
7973/// by \p First and the bits loaded by \p Second.
7974static bool areSlicesNextToEachOther(const LoadedSlice &First,
7975 const LoadedSlice &Second) {
7976 assert(First.Origin == Second.Origin && First.Origin &&
7977 "Unable to match different memory origins.");
7978 APInt UsedBits = First.getUsedBits();
7979 assert((UsedBits & Second.getUsedBits()) == 0 &&
7980 "Slices are not supposed to overlap.");
7981 UsedBits |= Second.getUsedBits();
7982 return areUsedBitsDense(UsedBits);
7983}
7984
7985/// \brief Adjust the \p GlobalLSCost according to the target
7986/// paring capabilities and the layout of the slices.
7987/// \pre \p GlobalLSCost should account for at least as many loads as
7988/// there is in the slices in \p LoadedSlices.
7989static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
7990 LoadedSlice::Cost &GlobalLSCost) {
7991 unsigned NumberOfSlices = LoadedSlices.size();
7992 // If there is less than 2 elements, no pairing is possible.
7993 if (NumberOfSlices < 2)
7994 return;
7995
7996 // Sort the slices so that elements that are likely to be next to each
7997 // other in memory are next to each other in the list.
7998 std::sort(LoadedSlices.begin(), LoadedSlices.end(), LoadedSliceSorter());
7999 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8000 // First (resp. Second) is the first (resp. Second) potentially candidate
8001 // to be placed in a paired load.
8002 const LoadedSlice *First = NULL;
8003 const LoadedSlice *Second = NULL;
8004 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8005 // Set the beginning of the pair.
8006 First = Second) {
8007
8008 Second = &LoadedSlices[CurrSlice];
8009
8010 // If First is NULL, it means we start a new pair.
8011 // Get to the next slice.
8012 if (!First)
8013 continue;
8014
8015 EVT LoadedType = First->getLoadedType();
8016
8017 // If the types of the slices are different, we cannot pair them.
8018 if (LoadedType != Second->getLoadedType())
8019 continue;
8020
8021 // Check if the target supplies paired loads for this type.
8022 unsigned RequiredAlignment = 0;
8023 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8024 // move to the next pair, this type is hopeless.
8025 Second = NULL;
8026 continue;
8027 }
8028 // Check if we meet the alignment requirement.
8029 if (RequiredAlignment > First->getAlignment())
8030 continue;
8031
8032 // Check that both loads are next to each other in memory.
8033 if (!areSlicesNextToEachOther(*First, *Second))
8034 continue;
8035
8036 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8037 --GlobalLSCost.Loads;
8038 // Move to the next pair.
8039 Second = NULL;
8040 }
8041}
8042
8043/// \brief Check the profitability of all involved LoadedSlice.
8044/// Currently, it is considered profitable if there is exactly two
8045/// involved slices (1) which are (2) next to each other in memory, and
8046/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8047///
8048/// Note: The order of the elements in \p LoadedSlices may be modified, but not
8049/// the elements themselves.
8050///
8051/// FIXME: When the cost model will be mature enough, we can relax
8052/// constraints (1) and (2).
8053static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8054 const APInt &UsedBits, bool ForCodeSize) {
8055 unsigned NumberOfSlices = LoadedSlices.size();
8056 if (StressLoadSlicing)
8057 return NumberOfSlices > 1;
8058
8059 // Check (1).
8060 if (NumberOfSlices != 2)
8061 return false;
8062
8063 // Check (2).
8064 if (!areUsedBitsDense(UsedBits))
8065 return false;
8066
8067 // Check (3).
8068 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8069 // The original code has one big load.
8070 OrigCost.Loads = 1;
8071 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8072 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8073 // Accumulate the cost of all the slices.
8074 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8075 GlobalSlicingCost += SliceCost;
8076
8077 // Account as cost in the original configuration the gain obtained
8078 // with the current slices.
8079 OrigCost.addSliceGain(LS);
8080 }
8081
8082 // If the target supports paired load, adjust the cost accordingly.
8083 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8084 return OrigCost > GlobalSlicingCost;
8085}
8086
8087/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8088/// operations, split it in the various pieces being extracted.
8089///
8090/// This sort of thing is introduced by SROA.
8091/// This slicing takes care not to insert overlapping loads.
8092/// \pre LI is a simple load (i.e., not an atomic or volatile load).
8093bool DAGCombiner::SliceUpLoad(SDNode *N) {
8094 if (Level < AfterLegalizeDAG)
8095 return false;
8096
8097 LoadSDNode *LD = cast<LoadSDNode>(N);
8098 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8099 !LD->getValueType(0).isInteger())
8100 return false;
8101
8102 // Keep track of already used bits to detect overlapping values.
8103 // In that case, we will just abort the transformation.
8104 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8105
8106 SmallVector<LoadedSlice, 4> LoadedSlices;
8107
8108 // Check if this load is used as several smaller chunks of bits.
8109 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8110 // of computation for each trunc.
8111 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8112 UI != UIEnd; ++UI) {
8113 // Skip the uses of the chain.
8114 if (UI.getUse().getResNo() != 0)
8115 continue;
8116
8117 SDNode *User = *UI;
8118 unsigned Shift = 0;
8119
8120 // Check if this is a trunc(lshr).
8121 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8122 isa<ConstantSDNode>(User->getOperand(1))) {
8123 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8124 User = *User->use_begin();
8125 }
8126
8127 // At this point, User is a Truncate, iff we encountered, trunc or
8128 // trunc(lshr).
8129 if (User->getOpcode() != ISD::TRUNCATE)
8130 return false;
8131
8132 // The width of the type must be a power of 2 and greater than 8-bits.
8133 // Otherwise the load cannot be represented in LLVM IR.
8134 // Moreover, if we shifted with a non 8-bits multiple, the slice
8135 // will be accross several bytes. We do not support that.
8136 unsigned Width = User->getValueSizeInBits(0);
8137 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8138 return 0;
8139
8140 // Build the slice for this chain of computations.
8141 LoadedSlice LS(User, LD, Shift, &DAG);
8142 APInt CurrentUsedBits = LS.getUsedBits();
8143
8144 // Check if this slice overlaps with another.
8145 if ((CurrentUsedBits & UsedBits) != 0)
8146 return false;
8147 // Update the bits used globally.
8148 UsedBits |= CurrentUsedBits;
8149
8150 // Check if the new slice would be legal.
8151 if (!LS.isLegal())
8152 return false;
8153
8154 // Record the slice.
8155 LoadedSlices.push_back(LS);
8156 }
8157
8158 // Abort slicing if it does not seem to be profitable.
8159 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8160 return false;
8161
8162 ++SlicedLoads;
8163
8164 // Rewrite each chain to use an independent load.
8165 // By construction, each chain can be represented by a unique load.
8166
8167 // Prepare the argument for the new token factor for all the slices.
8168 SmallVector<SDValue, 8> ArgChains;
8169 for (SmallVectorImpl<LoadedSlice>::const_iterator
8170 LSIt = LoadedSlices.begin(),
8171 LSItEnd = LoadedSlices.end();
8172 LSIt != LSItEnd; ++LSIt) {
8173 SDValue SliceInst = LSIt->loadSlice();
8174 CombineTo(LSIt->Inst, SliceInst, true);
8175 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8176 SliceInst = SliceInst.getOperand(0);
8177 assert(SliceInst->getOpcode() == ISD::LOAD &&
8178 "It takes more than a zext to get to the loaded slice!!");
8179 ArgChains.push_back(SliceInst.getValue(1));
8180 }
8181
8182 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8183 &ArgChains[0], ArgChains.size());
8184 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8185 return true;
8186}
8187
Chris Lattner2392ae72010-04-15 04:48:01 +00008188/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8189/// load is having specific bytes cleared out. If so, return the byte size
8190/// being masked out and the shift amount.
8191static std::pair<unsigned, unsigned>
8192CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8193 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008194
Chris Lattner2392ae72010-04-15 04:48:01 +00008195 // Check for the structure we're looking for.
8196 if (V->getOpcode() != ISD::AND ||
8197 !isa<ConstantSDNode>(V->getOperand(1)) ||
8198 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8199 return Result;
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008200
Chris Lattnere6987582010-04-15 06:10:49 +00008201 // Check the chain and pointer.
Chris Lattner2392ae72010-04-15 04:48:01 +00008202 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattnere6987582010-04-15 06:10:49 +00008203 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008204
Chris Lattnere6987582010-04-15 06:10:49 +00008205 // The store should be chained directly to the load or be an operand of a
8206 // tokenfactor.
8207 if (LD == Chain.getNode())
8208 ; // ok.
8209 else if (Chain->getOpcode() != ISD::TokenFactor)
8210 return Result; // Fail.
8211 else {
8212 bool isOk = false;
8213 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8214 if (Chain->getOperand(i).getNode() == LD) {
8215 isOk = true;
8216 break;
8217 }
8218 if (!isOk) return Result;
8219 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008220
Chris Lattner2392ae72010-04-15 04:48:01 +00008221 // This only handles simple types.
8222 if (V.getValueType() != MVT::i16 &&
8223 V.getValueType() != MVT::i32 &&
8224 V.getValueType() != MVT::i64)
8225 return Result;
8226
8227 // Check the constant mask. Invert it so that the bits being masked out are
8228 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8229 // follow the sign bit for uniformity.
8230 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerc6af2432013-05-24 22:23:49 +00008231 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner2392ae72010-04-15 04:48:01 +00008232 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerc6af2432013-05-24 22:23:49 +00008233 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner2392ae72010-04-15 04:48:01 +00008234 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8235 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008236
Chris Lattner2392ae72010-04-15 04:48:01 +00008237 // See if we have a continuous run of bits. If so, we have 0*1+0*
8238 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8239 return Result;
8240
8241 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8242 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8243 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008244
Chris Lattner2392ae72010-04-15 04:48:01 +00008245 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8246 switch (MaskedBytes) {
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008247 case 1:
8248 case 2:
Chris Lattner2392ae72010-04-15 04:48:01 +00008249 case 4: break;
8250 default: return Result; // All one mask, or 5-byte mask.
8251 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008252
Chris Lattner2392ae72010-04-15 04:48:01 +00008253 // Verify that the first bit starts at a multiple of mask so that the access
8254 // is aligned the same as the access width.
8255 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008256
Chris Lattner2392ae72010-04-15 04:48:01 +00008257 Result.first = MaskedBytes;
8258 Result.second = NotMaskTZ/8;
8259 return Result;
8260}
8261
8262
8263/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8264/// provides a value as specified by MaskInfo. If so, replace the specified
8265/// store with a narrower store of truncated IVal.
8266static SDNode *
8267ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8268 SDValue IVal, StoreSDNode *St,
8269 DAGCombiner *DC) {
8270 unsigned NumBytes = MaskInfo.first;
8271 unsigned ByteShift = MaskInfo.second;
8272 SelectionDAG &DAG = DC->getDAG();
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008273
Chris Lattner2392ae72010-04-15 04:48:01 +00008274 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8275 // that uses this. If not, this is not a replacement.
8276 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8277 ByteShift*8, (ByteShift+NumBytes)*8);
8278 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008279
Chris Lattner2392ae72010-04-15 04:48:01 +00008280 // Check that it is legal on the target to do this. It is legal if the new
8281 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8282 // legalization.
8283 MVT VT = MVT::getIntegerVT(NumBytes*8);
8284 if (!DC->isTypeLegal(VT))
8285 return 0;
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008286
Chris Lattner2392ae72010-04-15 04:48:01 +00008287 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8288 // shifted by ByteShift and truncated down to NumBytes.
8289 if (ByteShift)
Andrew Trickac6d9be2013-05-25 02:42:55 +00008290 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Anderson95771af2011-02-25 21:41:48 +00008291 DAG.getConstant(ByteShift*8,
8292 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner2392ae72010-04-15 04:48:01 +00008293
8294 // Figure out the offset for the store and the alignment of the access.
8295 unsigned StOffset;
8296 unsigned NewAlign = St->getAlignment();
8297
8298 if (DAG.getTargetLoweringInfo().isLittleEndian())
8299 StOffset = ByteShift;
8300 else
8301 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008302
Chris Lattner2392ae72010-04-15 04:48:01 +00008303 SDValue Ptr = St->getBasePtr();
8304 if (StOffset) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00008305 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner2392ae72010-04-15 04:48:01 +00008306 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8307 NewAlign = MinAlign(NewAlign, StOffset);
8308 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008309
Chris Lattner2392ae72010-04-15 04:48:01 +00008310 // Truncate down to the new size.
Andrew Trickac6d9be2013-05-25 02:42:55 +00008311 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008312
Chris Lattner2392ae72010-04-15 04:48:01 +00008313 ++OpsNarrowed;
Andrew Trickac6d9be2013-05-25 02:42:55 +00008314 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner6229d0a2010-09-21 18:41:36 +00008315 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner2392ae72010-04-15 04:48:01 +00008316 false, false, NewAlign).getNode();
8317}
8318
Evan Cheng8b944d32009-05-28 00:35:15 +00008319
8320/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8321/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8322/// of the loaded bits, try narrowing the load and store if it would end up
8323/// being a win for performance or code size.
8324SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8325 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Chengcdcecc02009-05-28 18:41:02 +00008326 if (ST->isVolatile())
8327 return SDValue();
8328
Evan Cheng8b944d32009-05-28 00:35:15 +00008329 SDValue Chain = ST->getChain();
8330 SDValue Value = ST->getValue();
8331 SDValue Ptr = ST->getBasePtr();
Owen Andersone50ed302009-08-10 22:56:29 +00008332 EVT VT = Value.getValueType();
Evan Cheng8b944d32009-05-28 00:35:15 +00008333
8334 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Chengcdcecc02009-05-28 18:41:02 +00008335 return SDValue();
Evan Cheng8b944d32009-05-28 00:35:15 +00008336
8337 unsigned Opc = Value.getOpcode();
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008338
Chris Lattner2392ae72010-04-15 04:48:01 +00008339 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8340 // is a byte mask indicating a consecutive number of bytes, check to see if
8341 // Y is known to provide just those bytes. If so, we try to replace the
8342 // load + replace + store sequence with a single (narrower) store, which makes
8343 // the load dead.
8344 if (Opc == ISD::OR) {
8345 std::pair<unsigned, unsigned> MaskedLoad;
8346 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8347 if (MaskedLoad.first)
8348 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8349 Value.getOperand(1), ST,this))
8350 return SDValue(NewST, 0);
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008351
Chris Lattner2392ae72010-04-15 04:48:01 +00008352 // Or is commutative, so try swapping X and Y.
8353 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8354 if (MaskedLoad.first)
8355 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8356 Value.getOperand(0), ST,this))
8357 return SDValue(NewST, 0);
8358 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008359
Evan Cheng8b944d32009-05-28 00:35:15 +00008360 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8361 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Chengcdcecc02009-05-28 18:41:02 +00008362 return SDValue();
Evan Cheng8b944d32009-05-28 00:35:15 +00008363
8364 SDValue N0 = Value.getOperand(0);
Dan Gohman24bde5b2010-09-02 21:18:42 +00008365 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8366 Chain == SDValue(N0.getNode(), 1)) {
Evan Cheng8b944d32009-05-28 00:35:15 +00008367 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerfa459012010-09-21 16:08:50 +00008368 if (LD->getBasePtr() != Ptr ||
8369 LD->getPointerInfo().getAddrSpace() !=
8370 ST->getPointerInfo().getAddrSpace())
Evan Chengcdcecc02009-05-28 18:41:02 +00008371 return SDValue();
Evan Cheng8b944d32009-05-28 00:35:15 +00008372
8373 // Find the type to narrow it the load / op / store to.
8374 SDValue N1 = Value.getOperand(1);
8375 unsigned BitWidth = N1.getValueSizeInBits();
8376 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8377 if (Opc == ISD::AND)
8378 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Chengd3c76bb2009-05-28 23:52:18 +00008379 if (Imm == 0 || Imm.isAllOnesValue())
8380 return SDValue();
Evan Cheng8b944d32009-05-28 00:35:15 +00008381 unsigned ShAmt = Imm.countTrailingZeros();
8382 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8383 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson23b9b192009-08-12 00:36:31 +00008384 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Cheng8b944d32009-05-28 00:35:15 +00008385 while (NewBW < BitWidth &&
Evan Chengcdcecc02009-05-28 18:41:02 +00008386 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
Evan Cheng8b944d32009-05-28 00:35:15 +00008387 TLI.isNarrowingProfitable(VT, NewVT))) {
8388 NewBW = NextPowerOf2(NewBW);
Owen Anderson23b9b192009-08-12 00:36:31 +00008389 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Cheng8b944d32009-05-28 00:35:15 +00008390 }
Evan Chengcdcecc02009-05-28 18:41:02 +00008391 if (NewBW >= BitWidth)
8392 return SDValue();
Evan Cheng8b944d32009-05-28 00:35:15 +00008393
8394 // If the lsb changed does not start at the type bitwidth boundary,
8395 // start at the previous one.
8396 if (ShAmt % NewBW)
8397 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren981b9632012-12-12 01:13:50 +00008398 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8399 std::min(BitWidth, ShAmt + NewBW));
Evan Cheng8b944d32009-05-28 00:35:15 +00008400 if ((Imm & Mask) == Imm) {
8401 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8402 if (Opc == ISD::AND)
8403 NewImm ^= APInt::getAllOnesValue(NewBW);
8404 uint64_t PtrOff = ShAmt / 8;
8405 // For big endian targets, we need to adjust the offset to the pointer to
8406 // load the correct bytes.
8407 if (TLI.isBigEndian())
Evan Chengcdcecc02009-05-28 18:41:02 +00008408 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Cheng8b944d32009-05-28 00:35:15 +00008409
8410 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00008411 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmow3574eca2012-10-08 16:38:25 +00008412 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Chengcdcecc02009-05-28 18:41:02 +00008413 return SDValue();
8414
Andrew Trickac6d9be2013-05-25 02:42:55 +00008415 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Cheng8b944d32009-05-28 00:35:15 +00008416 Ptr.getValueType(), Ptr,
8417 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickac6d9be2013-05-25 02:42:55 +00008418 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Cheng8b944d32009-05-28 00:35:15 +00008419 LD->getChain(), NewPtr,
Chris Lattnerfa459012010-09-21 16:08:50 +00008420 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene1e559442010-02-15 17:00:31 +00008421 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00008422 LD->isInvariant(), NewAlign,
8423 LD->getTBAAInfo());
Andrew Trickac6d9be2013-05-25 02:42:55 +00008424 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Cheng8b944d32009-05-28 00:35:15 +00008425 DAG.getConstant(NewImm, NewVT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00008426 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Cheng8b944d32009-05-28 00:35:15 +00008427 NewVal, NewPtr,
Chris Lattnerfa459012010-09-21 16:08:50 +00008428 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene1e559442010-02-15 17:00:31 +00008429 false, false, NewAlign);
Evan Cheng8b944d32009-05-28 00:35:15 +00008430
8431 AddToWorkList(NewPtr.getNode());
8432 AddToWorkList(NewLD.getNode());
8433 AddToWorkList(NewVal.getNode());
8434 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00008435 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Cheng8b944d32009-05-28 00:35:15 +00008436 ++OpsNarrowed;
8437 return NewST;
8438 }
8439 }
8440
Evan Chengcdcecc02009-05-28 18:41:02 +00008441 return SDValue();
Evan Cheng8b944d32009-05-28 00:35:15 +00008442}
8443
Evan Cheng31959b12011-02-02 01:06:55 +00008444/// TransformFPLoadStorePair - For a given floating point load / store pair,
8445/// if the load value isn't used by any other operations, then consider
8446/// transforming the pair to integer load / store operations if the target
8447/// deems the transformation profitable.
8448SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8449 StoreSDNode *ST = cast<StoreSDNode>(N);
8450 SDValue Chain = ST->getChain();
8451 SDValue Value = ST->getValue();
8452 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8453 Value.hasOneUse() &&
8454 Chain == SDValue(Value.getNode(), 1)) {
8455 LoadSDNode *LD = cast<LoadSDNode>(Value);
8456 EVT VT = LD->getMemoryVT();
8457 if (!VT.isFloatingPoint() ||
8458 VT != ST->getMemoryVT() ||
8459 LD->isNonTemporal() ||
8460 ST->isNonTemporal() ||
8461 LD->getPointerInfo().getAddrSpace() != 0 ||
8462 ST->getPointerInfo().getAddrSpace() != 0)
8463 return SDValue();
8464
8465 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8466 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8467 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8468 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8469 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8470 return SDValue();
8471
8472 unsigned LDAlign = LD->getAlignment();
8473 unsigned STAlign = ST->getAlignment();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00008474 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmow3574eca2012-10-08 16:38:25 +00008475 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Cheng31959b12011-02-02 01:06:55 +00008476 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8477 return SDValue();
8478
Andrew Trickac6d9be2013-05-25 02:42:55 +00008479 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Cheng31959b12011-02-02 01:06:55 +00008480 LD->getChain(), LD->getBasePtr(),
8481 LD->getPointerInfo(),
Pete Cooperd752e0f2011-11-08 18:42:53 +00008482 false, false, false, LDAlign);
Evan Cheng31959b12011-02-02 01:06:55 +00008483
Andrew Trickac6d9be2013-05-25 02:42:55 +00008484 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Cheng31959b12011-02-02 01:06:55 +00008485 NewLD, ST->getBasePtr(),
8486 ST->getPointerInfo(),
8487 false, false, STAlign);
8488
8489 AddToWorkList(NewLD.getNode());
8490 AddToWorkList(NewST.getNode());
8491 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00008492 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Cheng31959b12011-02-02 01:06:55 +00008493 ++LdStFP2Int;
8494 return NewST;
8495 }
8496
8497 return SDValue();
8498}
8499
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008500/// Helper struct to parse and store a memory address as base + index + offset.
8501/// We ignore sign extensions when it is safe to do so.
8502/// The following two expressions are not equivalent. To differentiate we need
8503/// to store whether there was a sign extension involved in the index
8504/// computation.
8505/// (load (i64 add (i64 copyfromreg %c)
8506/// (i64 signextend (add (i8 load %index)
8507/// (i8 1))))
8508/// vs
8509///
8510/// (load (i64 add (i64 copyfromreg %c)
8511/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8512/// (i32 1)))))
8513struct BaseIndexOffset {
8514 SDValue Base;
8515 SDValue Index;
8516 int64_t Offset;
8517 bool IsIndexSignExt;
8518
8519 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8520
8521 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8522 bool IsIndexSignExt) :
8523 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8524
8525 bool equalBaseIndex(const BaseIndexOffset &Other) {
8526 return Other.Base == Base && Other.Index == Index &&
8527 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotemc653de62012-10-03 16:11:15 +00008528 }
8529
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008530 /// Parses tree in Ptr for base, index, offset addresses.
8531 static BaseIndexOffset match(SDValue Ptr) {
8532 bool IsIndexSignExt = false;
8533
Juergen Ributzka915e9362013-08-21 21:53:38 +00008534 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8535 // instruction, then it could be just the BASE or everything else we don't
8536 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008537 if (Ptr->getOpcode() != ISD::ADD)
8538 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8539
Juergen Ributzka915e9362013-08-21 21:53:38 +00008540 // We know that we have at least an ADD instruction. Try to pattern match
8541 // the simple case of BASE + OFFSET.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008542 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8543 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8544 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8545 IsIndexSignExt);
8546 }
8547
Juergen Ributzka915e9362013-08-21 21:53:38 +00008548 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka2b884bc2013-08-28 22:33:58 +00008549 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka915e9362013-08-21 21:53:38 +00008550 // (i64 add (i64 %array_ptr)
8551 // (i64 mul (i64 %induction_var)
8552 // (i64 %element_size)))
Juergen Ributzka2b884bc2013-08-28 22:33:58 +00008553 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka915e9362013-08-21 21:53:38 +00008554 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka915e9362013-08-21 21:53:38 +00008555
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008556 // Look at Base + Index + Offset cases.
8557 SDValue Base = Ptr->getOperand(0);
8558 SDValue IndexOffset = Ptr->getOperand(1);
8559
8560 // Skip signextends.
8561 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8562 IndexOffset = IndexOffset->getOperand(0);
8563 IsIndexSignExt = true;
8564 }
8565
8566 // Either the case of Base + Index (no offset) or something else.
8567 if (IndexOffset->getOpcode() != ISD::ADD)
8568 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8569
8570 // Now we have the case of Base + Index + offset.
8571 SDValue Index = IndexOffset->getOperand(0);
8572 SDValue Offset = IndexOffset->getOperand(1);
8573
8574 if (!isa<ConstantSDNode>(Offset))
8575 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8576
8577 // Ignore signextends.
8578 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8579 Index = Index->getOperand(0);
8580 IsIndexSignExt = true;
8581 } else IsIndexSignExt = false;
8582
8583 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8584 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8585 }
8586};
Nadav Rotemc653de62012-10-03 16:11:15 +00008587
8588/// Holds a pointer to an LSBaseSDNode as well as information on where it
8589/// is located in a sequence of memory operations connected by a chain.
8590struct MemOpLink {
8591 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8592 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8593 // Ptr to the mem node.
8594 LSBaseSDNode *MemNode;
8595 // Offset from the base ptr.
8596 int64_t OffsetFromBase;
8597 // What is the sequence number of this mem node.
8598 // Lowest mem operand in the DAG starts at zero.
8599 unsigned SequenceNum;
8600};
8601
8602/// Sorts store nodes in a link according to their offset from a shared
8603// base ptr.
8604struct ConsecutiveMemoryChainSorter {
8605 bool operator()(MemOpLink LHS, MemOpLink RHS) {
8606 return LHS.OffsetFromBase < RHS.OffsetFromBase;
8607 }
8608};
8609
8610bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8611 EVT MemVT = St->getMemoryVT();
8612 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Nadav Rotem6cc4b8d2013-02-14 18:28:52 +00008613 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8614 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
Nadav Rotemc653de62012-10-03 16:11:15 +00008615
8616 // Don't merge vectors into wider inputs.
8617 if (MemVT.isVector() || !MemVT.isSimple())
8618 return false;
8619
8620 // Perform an early exit check. Do not bother looking at stored values that
8621 // are not constants or loads.
8622 SDValue StoredVal = St->getValue();
8623 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8624 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8625 !IsLoadSrc)
8626 return false;
8627
8628 // Only look at ends of store sequences.
8629 SDValue Chain = SDValue(St, 1);
8630 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8631 return false;
8632
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008633 // This holds the base pointer, index, and the offset in bytes from the base
8634 // pointer.
8635 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotemc653de62012-10-03 16:11:15 +00008636
8637 // We must have a base and an offset.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008638 if (!BasePtr.Base.getNode())
Nadav Rotemc653de62012-10-03 16:11:15 +00008639 return false;
8640
8641 // Do not handle stores to undef base pointers.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008642 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotemc653de62012-10-03 16:11:15 +00008643 return false;
8644
Nadav Rotem90e11dc2012-11-29 00:00:08 +00008645 // Save the LoadSDNodes that we find in the chain.
8646 // We need to make sure that these nodes do not interfere with
8647 // any of the store nodes.
8648 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8649
8650 // Save the StoreSDNodes that we find in the chain.
Nadav Rotemc653de62012-10-03 16:11:15 +00008651 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem90e11dc2012-11-29 00:00:08 +00008652
Nadav Rotemc653de62012-10-03 16:11:15 +00008653 // Walk up the chain and look for nodes with offsets from the same
8654 // base pointer. Stop when reaching an instruction with a different kind
8655 // or instruction which has a different base pointer.
8656 unsigned Seq = 0;
8657 StoreSDNode *Index = St;
8658 while (Index) {
8659 // If the chain has more than one use, then we can't reorder the mem ops.
8660 if (Index != St && !SDValue(Index, 1)->hasOneUse())
8661 break;
8662
8663 // Find the base pointer and offset for this memory node.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008664 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotemc653de62012-10-03 16:11:15 +00008665
8666 // Check that the base pointer is the same as the original one.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008667 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotemc653de62012-10-03 16:11:15 +00008668 break;
8669
8670 // Check that the alignment is the same.
8671 if (Index->getAlignment() != St->getAlignment())
8672 break;
8673
8674 // The memory operands must not be volatile.
8675 if (Index->isVolatile() || Index->isIndexed())
8676 break;
8677
8678 // No truncation.
8679 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8680 if (St->isTruncatingStore())
8681 break;
8682
8683 // The stored memory type must be the same.
8684 if (Index->getMemoryVT() != MemVT)
8685 break;
8686
8687 // We do not allow unaligned stores because we want to prevent overriding
8688 // stores.
8689 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8690 break;
8691
8692 // We found a potential memory operand to merge.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008693 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotemc653de62012-10-03 16:11:15 +00008694
Nadav Rotem90e11dc2012-11-29 00:00:08 +00008695 // Find the next memory operand in the chain. If the next operand in the
8696 // chain is a store then move up and continue the scan with the next
8697 // memory operand. If the next operand is a load save it and use alias
8698 // information to check if it interferes with anything.
8699 SDNode *NextInChain = Index->getChain().getNode();
8700 while (1) {
Nadav Rotemdde785c2012-12-06 17:34:13 +00008701 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem90e11dc2012-11-29 00:00:08 +00008702 // We found a store node. Use it for the next iteration.
Nadav Rotemdde785c2012-12-06 17:34:13 +00008703 Index = STn;
Nadav Rotem90e11dc2012-11-29 00:00:08 +00008704 break;
8705 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendlinge1679732013-11-25 05:02:20 +00008706 if (Ldn->isVolatile()) {
8707 Index = NULL;
8708 break;
8709 }
8710
Nadav Rotem90e11dc2012-11-29 00:00:08 +00008711 // Save the load node for later. Continue the scan.
8712 AliasLoadNodes.push_back(Ldn);
8713 NextInChain = Ldn->getChain().getNode();
8714 continue;
8715 } else {
8716 Index = NULL;
8717 break;
8718 }
8719 }
Nadav Rotemc653de62012-10-03 16:11:15 +00008720 }
8721
8722 // Check if there is anything to merge.
8723 if (StoreNodes.size() < 2)
8724 return false;
8725
8726 // Sort the memory operands according to their distance from the base pointer.
8727 std::sort(StoreNodes.begin(), StoreNodes.end(),
8728 ConsecutiveMemoryChainSorter());
8729
8730 // Scan the memory operations on the chain and find the first non-consecutive
8731 // store memory address.
8732 unsigned LastConsecutiveStore = 0;
8733 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemdde785c2012-12-06 17:34:13 +00008734 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8735
8736 // Check that the addresses are consecutive starting from the second
8737 // element in the list of stores.
8738 if (i > 0) {
8739 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8740 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8741 break;
8742 }
Nadav Rotemc653de62012-10-03 16:11:15 +00008743
Nadav Rotem90e11dc2012-11-29 00:00:08 +00008744 bool Alias = false;
8745 // Check if this store interferes with any of the loads that we found.
8746 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8747 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8748 Alias = true;
8749 break;
8750 }
Nadav Rotem90e11dc2012-11-29 00:00:08 +00008751 // We found a load that alias with this store. Stop the sequence.
8752 if (Alias)
8753 break;
8754
Nadav Rotemc653de62012-10-03 16:11:15 +00008755 // Mark this node as useful.
8756 LastConsecutiveStore = i;
8757 }
8758
8759 // The node with the lowest store address.
8760 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8761
8762 // Store the constants into memory as one consecutive store.
8763 if (!IsLoadSrc) {
Nadav Rotemc653de62012-10-03 16:11:15 +00008764 unsigned LastLegalType = 0;
Nadav Rotemea2c50c2012-10-04 22:35:15 +00008765 unsigned LastLegalVectorType = 0;
8766 bool NonZero = false;
Nadav Rotemc653de62012-10-03 16:11:15 +00008767 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8768 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8769 SDValue StoredVal = St->getValue();
Nadav Rotemea2c50c2012-10-04 22:35:15 +00008770
8771 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramerebd7eab2012-10-05 18:19:44 +00008772 NonZero |= !C->isNullValue();
Nadav Rotemea2c50c2012-10-04 22:35:15 +00008773 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramerebd7eab2012-10-05 18:19:44 +00008774 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemea2c50c2012-10-04 22:35:15 +00008775 } else {
8776 // Non constant.
Nadav Rotemc653de62012-10-03 16:11:15 +00008777 break;
Nadav Rotemea2c50c2012-10-04 22:35:15 +00008778 }
Nadav Rotemc653de62012-10-03 16:11:15 +00008779
Nadav Rotemc653de62012-10-03 16:11:15 +00008780 // Find a legal type for the constant store.
8781 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8782 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8783 if (TLI.isTypeLegal(StoreTy))
8784 LastLegalType = i+1;
Arnold Schwaighofere7370182013-04-02 15:58:51 +00008785 // Or check whether a truncstore is legal.
8786 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8787 TargetLowering::TypePromoteInteger) {
8788 EVT LegalizedStoredValueTy =
8789 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8790 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8791 LastLegalType = i+1;
8792 }
Nadav Rotemea2c50c2012-10-04 22:35:15 +00008793
8794 // Find a legal type for the vector store.
8795 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8796 if (TLI.isTypeLegal(Ty))
8797 LastLegalVectorType = i + 1;
Nadav Rotemc653de62012-10-03 16:11:15 +00008798 }
8799
Bob Wilson99d8e762012-12-20 01:36:20 +00008800 // We only use vectors if the constant is known to be zero and the
8801 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem6cc4b8d2013-02-14 18:28:52 +00008802 if (NonZero || NoVectors)
Nadav Rotemea2c50c2012-10-04 22:35:15 +00008803 LastLegalVectorType = 0;
8804
Nadav Rotemc653de62012-10-03 16:11:15 +00008805 // Check if we found a legal integer type to store.
Nadav Rotemea2c50c2012-10-04 22:35:15 +00008806 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotemc653de62012-10-03 16:11:15 +00008807 return false;
8808
Nadav Rotem6cc4b8d2013-02-14 18:28:52 +00008809 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemea2c50c2012-10-04 22:35:15 +00008810 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8811
8812 // Make sure we have something to merge.
8813 if (NumElem < 2)
8814 return false;
Nadav Rotemc653de62012-10-03 16:11:15 +00008815
8816 unsigned EarliestNodeUsed = 0;
8817 for (unsigned i=0; i < NumElem; ++i) {
8818 // Find a chain for the new wide-store operand. Notice that some
8819 // of the store nodes that we found may not be selected for inclusion
8820 // in the wide store. The chain we use needs to be the chain of the
8821 // earliest store node which is *used* and replaced by the wide store.
8822 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8823 EarliestNodeUsed = i;
8824 }
8825
8826 // The earliest Node in the DAG.
8827 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
Andrew Trickac6d9be2013-05-25 02:42:55 +00008828 SDLoc DL(StoreNodes[0].MemNode);
Nadav Rotemc653de62012-10-03 16:11:15 +00008829
Nadav Rotemea2c50c2012-10-04 22:35:15 +00008830 SDValue StoredVal;
8831 if (UseVector) {
8832 // Find a legal type for the vector store.
8833 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8834 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8835 StoredVal = DAG.getConstant(0, Ty);
8836 } else {
8837 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8838 APInt StoreInt(StoreBW, 0);
8839
8840 // Construct a single integer constant which is made of the smaller
8841 // constant inputs.
8842 bool IsLE = TLI.isLittleEndian();
8843 for (unsigned i = 0; i < NumElem ; ++i) {
8844 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8845 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8846 SDValue Val = St->getValue();
8847 StoreInt<<=ElementSizeBytes*8;
8848 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8849 StoreInt|=C->getAPIntValue().zext(StoreBW);
8850 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8851 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8852 } else {
8853 assert(false && "Invalid constant element type");
8854 }
Nadav Rotemc653de62012-10-03 16:11:15 +00008855 }
Nadav Rotemea2c50c2012-10-04 22:35:15 +00008856
8857 // Create the new Load and Store operations.
8858 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8859 StoredVal = DAG.getConstant(StoreInt, StoreTy);
Nadav Rotemc653de62012-10-03 16:11:15 +00008860 }
8861
Nadav Rotemea2c50c2012-10-04 22:35:15 +00008862 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
Nadav Rotemc653de62012-10-03 16:11:15 +00008863 FirstInChain->getBasePtr(),
8864 FirstInChain->getPointerInfo(),
8865 false, false,
8866 FirstInChain->getAlignment());
8867
8868 // Replace the first store with the new store
8869 CombineTo(EarliestOp, NewStore);
8870 // Erase all other stores.
8871 for (unsigned i = 0; i < NumElem ; ++i) {
8872 if (StoreNodes[i].MemNode == EarliestOp)
8873 continue;
8874 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Rafael Espindola8e2b8ae2012-11-14 05:08:56 +00008875 // ReplaceAllUsesWith will replace all uses that existed when it was
8876 // called, but graph optimizations may cause new ones to appear. For
8877 // example, the case in pr14333 looks like
8878 //
8879 // St's chain -> St -> another store -> X
8880 //
8881 // And the only difference from St to the other store is the chain.
8882 // When we change it's chain to be St's chain they become identical,
8883 // get CSEed and the net result is that X is now a use of St.
8884 // Since we know that St is redundant, just iterate.
8885 while (!St->use_empty())
8886 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
Nadav Rotemc653de62012-10-03 16:11:15 +00008887 removeFromWorkList(St);
8888 DAG.DeleteNode(St);
8889 }
8890
8891 return true;
8892 }
8893
8894 // Below we handle the case of multiple consecutive stores that
8895 // come from multiple consecutive loads. We merge them into a single
8896 // wide load and a single wide store.
8897
8898 // Look for load nodes which are used by the stored values.
8899 SmallVector<MemOpLink, 8> LoadNodes;
8900
8901 // Find acceptable loads. Loads need to have the same chain (token factor),
8902 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008903 BaseIndexOffset LdBasePtr;
Nadav Rotemc653de62012-10-03 16:11:15 +00008904 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8905 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8906 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
8907 if (!Ld) break;
8908
8909 // Loads must only have one use.
8910 if (!Ld->hasNUsesOfValue(1, 0))
8911 break;
8912
8913 // Check that the alignment is the same as the stores.
8914 if (Ld->getAlignment() != St->getAlignment())
8915 break;
8916
8917 // The memory operands must not be volatile.
8918 if (Ld->isVolatile() || Ld->isIndexed())
8919 break;
8920
8921 // We do not accept ext loads.
8922 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
8923 break;
8924
8925 // The stored memory type must be the same.
8926 if (Ld->getMemoryVT() != MemVT)
8927 break;
8928
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008929 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotemc653de62012-10-03 16:11:15 +00008930 // If this is not the first ptr that we check.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008931 if (LdBasePtr.Base.getNode()) {
Nadav Rotemc653de62012-10-03 16:11:15 +00008932 // The base ptr must be the same.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008933 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotemc653de62012-10-03 16:11:15 +00008934 break;
8935 } else {
8936 // Check that all other base pointers are the same as this one.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008937 LdBasePtr = LdPtr;
Nadav Rotemc653de62012-10-03 16:11:15 +00008938 }
8939
8940 // We found a potential memory operand to merge.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008941 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotemc653de62012-10-03 16:11:15 +00008942 }
8943
8944 if (LoadNodes.size() < 2)
8945 return false;
8946
8947 // Scan the memory operations on the chain and find the first non-consecutive
8948 // load memory address. These variables hold the index in the store node
8949 // array.
8950 unsigned LastConsecutiveLoad = 0;
8951 // This variable refers to the size and not index in the array.
8952 unsigned LastLegalVectorType = 0;
8953 unsigned LastLegalIntegerType = 0;
8954 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotem2e7d3812012-10-03 19:30:31 +00008955 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
8956 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
8957 // All loads much share the same chain.
8958 if (LoadNodes[i].MemNode->getChain() != FirstChain)
8959 break;
Nadav Rotem6cc4b8d2013-02-14 18:28:52 +00008960
Nadav Rotemc653de62012-10-03 16:11:15 +00008961 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
8962 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8963 break;
8964 LastConsecutiveLoad = i;
8965
8966 // Find a legal type for the vector store.
8967 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8968 if (TLI.isTypeLegal(StoreTy))
8969 LastLegalVectorType = i + 1;
8970
8971 // Find a legal type for the integer store.
8972 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8973 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8974 if (TLI.isTypeLegal(StoreTy))
8975 LastLegalIntegerType = i + 1;
Arnold Schwaighofere7370182013-04-02 15:58:51 +00008976 // Or check whether a truncstore and extload is legal.
8977 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8978 TargetLowering::TypePromoteInteger) {
8979 EVT LegalizedStoredValueTy =
8980 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
8981 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
8982 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
8983 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
8984 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
8985 LastLegalIntegerType = i+1;
8986 }
Nadav Rotemc653de62012-10-03 16:11:15 +00008987 }
8988
8989 // Only use vector types if the vector type is larger than the integer type.
8990 // If they are the same, use integers.
Nadav Rotem6cc4b8d2013-02-14 18:28:52 +00008991 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotemc653de62012-10-03 16:11:15 +00008992 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
8993
8994 // We add +1 here because the LastXXX variables refer to location while
8995 // the NumElem refers to array/index size.
8996 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
8997 NumElem = std::min(LastLegalType, NumElem);
8998
8999 if (NumElem < 2)
9000 return false;
9001
9002 // The earliest Node in the DAG.
9003 unsigned EarliestNodeUsed = 0;
9004 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9005 for (unsigned i=1; i<NumElem; ++i) {
9006 // Find a chain for the new wide-store operand. Notice that some
9007 // of the store nodes that we found may not be selected for inclusion
9008 // in the wide store. The chain we use needs to be the chain of the
9009 // earliest store node which is *used* and replaced by the wide store.
9010 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9011 EarliestNodeUsed = i;
9012 }
9013
9014 // Find if it is better to use vectors or integers to load and store
9015 // to memory.
9016 EVT JointMemOpVT;
9017 if (UseVectorTy) {
9018 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9019 } else {
9020 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9021 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9022 }
9023
Andrew Trickac6d9be2013-05-25 02:42:55 +00009024 SDLoc LoadDL(LoadNodes[0].MemNode);
9025 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotemc653de62012-10-03 16:11:15 +00009026
9027 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9028 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9029 FirstLoad->getChain(),
9030 FirstLoad->getBasePtr(),
9031 FirstLoad->getPointerInfo(),
9032 false, false, false,
9033 FirstLoad->getAlignment());
9034
9035 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9036 FirstInChain->getBasePtr(),
9037 FirstInChain->getPointerInfo(), false, false,
9038 FirstInChain->getAlignment());
9039
Nadav Rotem2e7d3812012-10-03 19:30:31 +00009040 // Replace one of the loads with the new load.
9041 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9042 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9043 SDValue(NewLoad.getNode(), 1));
9044
9045 // Remove the rest of the load chains.
9046 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotemc653de62012-10-03 16:11:15 +00009047 // Replace all chain users of the old load nodes with the chain of the new
9048 // load node.
9049 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotem2e7d3812012-10-03 19:30:31 +00009050 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9051 }
Nadav Rotemc653de62012-10-03 16:11:15 +00009052
Nadav Rotem2e7d3812012-10-03 19:30:31 +00009053 // Replace the first store with the new store.
9054 CombineTo(EarliestOp, NewStore);
9055 // Erase all other stores.
9056 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotemc653de62012-10-03 16:11:15 +00009057 // Remove all Store nodes.
9058 if (StoreNodes[i].MemNode == EarliestOp)
9059 continue;
9060 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9061 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9062 removeFromWorkList(St);
9063 DAG.DeleteNode(St);
9064 }
9065
9066 return true;
9067}
9068
Dan Gohman475871a2008-07-27 21:46:04 +00009069SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Cheng8b2794a2006-10-13 21:14:26 +00009070 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman475871a2008-07-27 21:46:04 +00009071 SDValue Chain = ST->getChain();
9072 SDValue Value = ST->getValue();
9073 SDValue Ptr = ST->getBasePtr();
Scott Michelfdc40a02009-02-17 22:15:04 +00009074
Evan Cheng59d5b682007-05-07 21:27:48 +00009075 // If this is a store of a bit convert, store the input value if the
Evan Cheng2c4f9432007-05-09 21:49:47 +00009076 // resultant store does not need a higher alignment than the original.
Wesley Peckbf17cfa2010-11-23 03:31:01 +00009077 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattnerddf89562008-01-17 19:59:44 +00009078 ST->isUnindexed()) {
Dan Gohman1ba519b2009-02-20 23:29:13 +00009079 unsigned OrigAlign = ST->getAlignment();
Owen Andersone50ed302009-08-10 22:56:29 +00009080 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmow3574eca2012-10-08 16:38:25 +00009081 unsigned Align = TLI.getDataLayout()->
Owen Anderson23b9b192009-08-12 00:36:31 +00009082 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sandsd4b9c172008-06-13 19:07:40 +00009083 if (Align <= OrigAlign &&
Duncan Sands25cf2272008-11-24 14:53:14 +00009084 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohmanf560ffa2009-01-28 17:46:25 +00009085 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00009086 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner6229d0a2010-09-21 18:41:36 +00009087 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00009088 ST->isNonTemporal(), OrigAlign,
9089 ST->getTBAAInfo());
Jim Laskey279f0532006-09-25 16:29:54 +00009090 }
Owen Andersona34d9362011-04-14 17:30:49 +00009091
Chris Lattnerb3452ea2011-04-09 02:32:02 +00009092 // Turn 'store undef, Ptr' -> nothing.
9093 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9094 return Chain;
Duncan Sandsd4b9c172008-06-13 19:07:40 +00009095
Nate Begeman2cbba892006-12-11 02:23:46 +00009096 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman2cbba892006-12-11 02:23:46 +00009097 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sandsd4b9c172008-06-13 19:07:40 +00009098 // NOTE: If the original store is volatile, this transform must not increase
9099 // the number of stores. For example, on x86-32 an f64 can be stored in one
9100 // processor operation but an i64 (which is not legal) requires two. So the
9101 // transform should not be done in this case.
Evan Cheng25ece662006-12-11 17:25:19 +00009102 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman475871a2008-07-27 21:46:04 +00009103 SDValue Tmp;
Craig Topper0ff11902013-08-15 02:44:19 +00009104 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009105 default: llvm_unreachable("Unknown FP type");
Pete Cooper438c0402012-06-21 18:00:39 +00009106 case MVT::f16: // We don't do this for these yet.
9107 case MVT::f80:
Owen Anderson825b72b2009-08-11 20:47:22 +00009108 case MVT::f128:
9109 case MVT::ppcf128:
Dale Johannesenc7b21d52007-09-18 18:36:59 +00009110 break;
Owen Anderson825b72b2009-08-11 20:47:22 +00009111 case MVT::f32:
Chris Lattner2392ae72010-04-15 04:48:01 +00009112 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson825b72b2009-08-11 20:47:22 +00009113 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen9d5f4562007-09-12 03:30:33 +00009114 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson825b72b2009-08-11 20:47:22 +00009115 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickac6d9be2013-05-25 02:42:55 +00009116 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford66589dc2013-10-28 11:17:59 +00009117 Ptr, ST->getMemOperand());
Chris Lattner62be1a72006-12-12 04:16:14 +00009118 }
9119 break;
Owen Anderson825b72b2009-08-11 20:47:22 +00009120 case MVT::f64:
Chris Lattner2392ae72010-04-15 04:48:01 +00009121 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohmanf560ffa2009-01-28 17:46:25 +00009122 !ST->isVolatile()) ||
Owen Anderson825b72b2009-08-11 20:47:22 +00009123 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen7111b022008-10-09 18:53:47 +00009124 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson825b72b2009-08-11 20:47:22 +00009125 getZExtValue(), MVT::i64);
Andrew Trickac6d9be2013-05-25 02:42:55 +00009126 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford66589dc2013-10-28 11:17:59 +00009127 Ptr, ST->getMemOperand());
Chris Lattnerb3452ea2011-04-09 02:32:02 +00009128 }
Owen Andersona34d9362011-04-14 17:30:49 +00009129
Chris Lattnerb3452ea2011-04-09 02:32:02 +00009130 if (!ST->isVolatile() &&
9131 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sandsdc846502007-10-28 12:59:45 +00009132 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattner62be1a72006-12-12 04:16:14 +00009133 // argument passing. Since this is so common, custom legalize the
9134 // 64-bit integer store into two 32-bit stores.
Dale Johannesen7111b022008-10-09 18:53:47 +00009135 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson825b72b2009-08-11 20:47:22 +00009136 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9137 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands0753fc12008-02-11 10:37:04 +00009138 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattner62be1a72006-12-12 04:16:14 +00009139
Dan Gohmand6fd1bc2007-07-09 22:18:38 +00009140 unsigned Alignment = ST->getAlignment();
9141 bool isVolatile = ST->isVolatile();
David Greene1e559442010-02-15 17:00:31 +00009142 bool isNonTemporal = ST->isNonTemporal();
Richard Sandiford66589dc2013-10-28 11:17:59 +00009143 const MDNode *TBAAInfo = ST->getTBAAInfo();
Dan Gohmand6fd1bc2007-07-09 22:18:38 +00009144
Andrew Trickac6d9be2013-05-25 02:42:55 +00009145 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner6229d0a2010-09-21 18:41:36 +00009146 Ptr, ST->getPointerInfo(),
David Greene1e559442010-02-15 17:00:31 +00009147 isVolatile, isNonTemporal,
Richard Sandiford66589dc2013-10-28 11:17:59 +00009148 ST->getAlignment(), TBAAInfo);
Andrew Trickac6d9be2013-05-25 02:42:55 +00009149 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattner62be1a72006-12-12 04:16:14 +00009150 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sandsdc846502007-10-28 12:59:45 +00009151 Alignment = MinAlign(Alignment, 4U);
Andrew Trickac6d9be2013-05-25 02:42:55 +00009152 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner6229d0a2010-09-21 18:41:36 +00009153 Ptr, ST->getPointerInfo().getWithOffset(4),
9154 isVolatile, isNonTemporal,
Richard Sandiford66589dc2013-10-28 11:17:59 +00009155 Alignment, TBAAInfo);
Andrew Trickac6d9be2013-05-25 02:42:55 +00009156 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendlingc144a572009-01-30 23:36:47 +00009157 St0, St1);
Chris Lattner62be1a72006-12-12 04:16:14 +00009158 }
Bill Wendlingc144a572009-01-30 23:36:47 +00009159
Chris Lattner62be1a72006-12-12 04:16:14 +00009160 break;
Evan Cheng25ece662006-12-11 17:25:19 +00009161 }
Nate Begeman2cbba892006-12-11 02:23:46 +00009162 }
Nate Begeman2cbba892006-12-11 02:23:46 +00009163 }
9164
Evan Cheng255f20f2010-04-01 06:04:33 +00009165 // Try to infer better alignment information than the store already has.
9166 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Chenged1c0c72011-11-28 22:37:34 +00009167 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9168 if (Align > ST->getAlignment())
Andrew Trickac6d9be2013-05-25 02:42:55 +00009169 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Chenged1c0c72011-11-28 22:37:34 +00009170 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00009171 ST->isVolatile(), ST->isNonTemporal(), Align,
9172 ST->getTBAAInfo());
Evan Cheng255f20f2010-04-01 06:04:33 +00009173 }
9174 }
9175
Evan Cheng31959b12011-02-02 01:06:55 +00009176 // Try transforming a pair floating point load / store ops to integer
9177 // load / store ops.
9178 SDValue NewST = TransformFPLoadStorePair(N);
9179 if (NewST.getNode())
9180 return NewST;
9181
Hal Finkel253acef2013-08-29 03:29:55 +00009182 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9183 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9184 if (UseAA) {
Jim Laskey279f0532006-09-25 16:29:54 +00009185 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman475871a2008-07-27 21:46:04 +00009186 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelfdc40a02009-02-17 22:15:04 +00009187
Jim Laskey6ff23e52006-10-04 16:53:27 +00009188 // If there is a better chain.
Jim Laskey279f0532006-09-25 16:29:54 +00009189 if (Chain != BetterChain) {
Dan Gohman475871a2008-07-27 21:46:04 +00009190 SDValue ReplStore;
Nate Begemanb6aef5c2009-09-15 00:18:30 +00009191
9192 // Replace the chain to avoid dependency.
Jim Laskeyd4edf2c2006-10-14 12:14:27 +00009193 if (ST->isTruncatingStore()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00009194 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford66589dc2013-10-28 11:17:59 +00009195 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskeyd4edf2c2006-10-14 12:14:27 +00009196 } else {
Andrew Trickac6d9be2013-05-25 02:42:55 +00009197 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford66589dc2013-10-28 11:17:59 +00009198 ST->getMemOperand());
Jim Laskeyd4edf2c2006-10-14 12:14:27 +00009199 }
Scott Michelfdc40a02009-02-17 22:15:04 +00009200
Jim Laskey279f0532006-09-25 16:29:54 +00009201 // Create token to keep both nodes around.
Andrew Trickac6d9be2013-05-25 02:42:55 +00009202 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson825b72b2009-08-11 20:47:22 +00009203 MVT::Other, Chain, ReplStore);
Bill Wendlingc144a572009-01-30 23:36:47 +00009204
Nate Begemanb6aef5c2009-09-15 00:18:30 +00009205 // Make sure the new and old chains are cleaned up.
9206 AddToWorkList(Token.getNode());
9207
Jim Laskey274062c2006-10-13 23:32:28 +00009208 // Don't add users to work list.
9209 return CombineTo(N, Token, false);
Jim Laskey279f0532006-09-25 16:29:54 +00009210 }
Jim Laskeyd1aed7a2006-09-21 16:28:59 +00009211 }
Scott Michelfdc40a02009-02-17 22:15:04 +00009212
Evan Cheng33dbedc2006-11-05 09:31:14 +00009213 // Try transforming N to an indexed store.
Evan Chengbbd6f6e2006-11-07 09:03:05 +00009214 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman475871a2008-07-27 21:46:04 +00009215 return SDValue(N, 0);
Evan Cheng33dbedc2006-11-05 09:31:14 +00009216
Chris Lattner3c872852007-12-29 06:26:16 +00009217 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattnerddf89562008-01-17 19:59:44 +00009218 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotembaff46f2011-06-15 11:19:12 +00009219 Value.getValueType().isInteger()) {
Chris Lattner2b4c2792007-10-13 06:35:54 +00009220 // See if we can simplify the input to this truncstore with knowledge that
9221 // only the low bits are being used. For example:
9222 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelfdc40a02009-02-17 22:15:04 +00009223 SDValue Shorter =
Dan Gohman2e68b6f2008-02-25 21:11:39 +00009224 GetDemandedBits(Value,
Nadav Rotembaff46f2011-06-15 11:19:12 +00009225 APInt::getLowBitsSet(
9226 Value.getValueType().getScalarType().getSizeInBits(),
9227 ST->getMemoryVT().getScalarType().getSizeInBits()));
Gabor Greifba36cb52008-08-28 21:40:38 +00009228 AddToWorkList(Value.getNode());
9229 if (Shorter.getNode())
Andrew Trickac6d9be2013-05-25 02:42:55 +00009230 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford66589dc2013-10-28 11:17:59 +00009231 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelfdc40a02009-02-17 22:15:04 +00009232
Chris Lattnere33544c2007-10-13 06:58:48 +00009233 // Otherwise, see if we can simplify the operation with
9234 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohman7b8d4a92008-02-27 00:25:32 +00009235 if (SimplifyDemandedBits(Value,
Eric Christopher503a64d2010-12-09 04:48:06 +00009236 APInt::getLowBitsSet(
9237 Value.getValueType().getScalarType().getSizeInBits(),
9238 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman475871a2008-07-27 21:46:04 +00009239 return SDValue(N, 0);
Chris Lattner2b4c2792007-10-13 06:35:54 +00009240 }
Scott Michelfdc40a02009-02-17 22:15:04 +00009241
Chris Lattner3c872852007-12-29 06:26:16 +00009242 // If this is a load followed by a store to the same location, then the store
9243 // is dead/noop.
9244 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohmanb625f2f2008-01-30 00:15:11 +00009245 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattnerddf89562008-01-17 19:59:44 +00009246 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner07649d92008-01-08 23:08:06 +00009247 // There can't be any side effects between the load and store, such as
9248 // a call or store.
Dan Gohman475871a2008-07-27 21:46:04 +00009249 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3c872852007-12-29 06:26:16 +00009250 // The store is dead, remove it.
9251 return Chain;
9252 }
9253 }
Duncan Sandsd4b9c172008-06-13 19:07:40 +00009254
Chris Lattnerddf89562008-01-17 19:59:44 +00009255 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9256 // truncating store. We can do this even if this is already a truncstore.
9257 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greifba36cb52008-08-28 21:40:38 +00009258 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattnerddf89562008-01-17 19:59:44 +00009259 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohmanb625f2f2008-01-30 00:15:11 +00009260 ST->getMemoryVT())) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00009261 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford66589dc2013-10-28 11:17:59 +00009262 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattnerddf89562008-01-17 19:59:44 +00009263 }
Duncan Sandsd4b9c172008-06-13 19:07:40 +00009264
Nadav Rotemc653de62012-10-03 16:11:15 +00009265 // Only perform this optimization before the types are legal, because we
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009266 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotema569a802012-12-02 17:14:09 +00009267 if (!LegalTypes) {
9268 bool EverChanged = false;
9269
9270 do {
9271 // There can be multiple store sequences on the same chain.
9272 // Keep trying to merge store sequences until we are unable to do so
9273 // or until we merge the last store on the chain.
9274 bool Changed = MergeConsecutiveStores(ST);
9275 EverChanged |= Changed;
9276 if (!Changed) break;
9277 } while (ST->getOpcode() != ISD::DELETED_NODE);
9278
9279 if (EverChanged)
9280 return SDValue(N, 0);
9281 }
Nadav Rotemc653de62012-10-03 16:11:15 +00009282
Evan Cheng8b944d32009-05-28 00:35:15 +00009283 return ReduceLoadOpStoreWidth(N);
Chris Lattner87514ca2005-10-10 22:31:19 +00009284}
9285
Dan Gohman475871a2008-07-27 21:46:04 +00009286SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9287 SDValue InVec = N->getOperand(0);
9288 SDValue InVal = N->getOperand(1);
9289 SDValue EltNo = N->getOperand(2);
Andrew Trickac6d9be2013-05-25 02:42:55 +00009290 SDLoc dl(N);
Scott Michelfdc40a02009-02-17 22:15:04 +00009291
Bob Wilson492fd452010-05-19 23:42:58 +00009292 // If the inserted element is an UNDEF, just use the input vector.
9293 if (InVal.getOpcode() == ISD::UNDEF)
9294 return InVec;
9295
Nadav Rotem609d54e2011-02-12 14:40:33 +00009296 EVT VT = InVec.getValueType();
9297
Owen Anderson95771af2011-02-25 21:41:48 +00009298 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotem609d54e2011-02-12 14:40:33 +00009299 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9300 return SDValue();
9301
Eli Friedman9db817f2011-09-09 21:04:06 +00009302 // Check that we know which element is being inserted
9303 if (!isa<ConstantSDNode>(EltNo))
9304 return SDValue();
9305 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelfdc40a02009-02-17 22:15:04 +00009306
Eli Friedman9db817f2011-09-09 21:04:06 +00009307 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9308 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9309 // vector elements.
9310 SmallVector<SDValue, 8> Ops;
Quentin Colombet75c94332013-07-30 00:24:09 +00009311 // Do not combine these two vectors if the output vector will not replace
9312 // the input vector.
9313 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedman9db817f2011-09-09 21:04:06 +00009314 Ops.append(InVec.getNode()->op_begin(),
9315 InVec.getNode()->op_end());
9316 } else if (InVec.getOpcode() == ISD::UNDEF) {
9317 unsigned NElts = VT.getVectorNumElements();
9318 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9319 } else {
9320 return SDValue();
Nate Begeman9008ca62009-04-27 18:41:29 +00009321 }
Eli Friedman9db817f2011-09-09 21:04:06 +00009322
9323 // Insert the element
9324 if (Elt < Ops.size()) {
9325 // All the operands of BUILD_VECTOR must have the same type;
9326 // we enforce that here.
9327 EVT OpVT = Ops[0].getValueType();
9328 if (InVal.getValueType() != OpVT)
9329 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9330 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9331 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9332 Ops[Elt] = InVal;
9333 }
9334
9335 // Return the new vector
9336 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9337 VT, &Ops[0], Ops.size());
Chris Lattnerca242442006-03-19 01:27:56 +00009338}
9339
Dan Gohman475871a2008-07-27 21:46:04 +00009340SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wang7ac9cdf2009-01-17 00:07:25 +00009341 // (vextract (scalar_to_vector val, 0) -> val
9342 SDValue InVec = N->getOperand(0);
Nadav Rotemba05c912012-01-17 21:44:01 +00009343 EVT VT = InVec.getValueType();
9344 EVT NVT = N->getValueType(0);
Mon P Wang7ac9cdf2009-01-17 00:07:25 +00009345
Duncan Sandsc356f332011-05-09 08:03:33 +00009346 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9347 // Check if the result type doesn't match the inserted element type. A
9348 // SCALAR_TO_VECTOR may truncate the inserted element and the
9349 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9350 SDValue InOp = InVec.getOperand(0);
Duncan Sandsc356f332011-05-09 08:03:33 +00009351 if (InOp.getValueType() != NVT) {
9352 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickac6d9be2013-05-25 02:42:55 +00009353 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sandsc356f332011-05-09 08:03:33 +00009354 }
9355 return InOp;
9356 }
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009357
Nadav Rotemba05c912012-01-17 21:44:01 +00009358 SDValue EltNo = N->getOperand(1);
9359 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9360
9361 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9362 // We only perform this optimization before the op legalization phase because
Nadav Rotem6dfabb62012-09-20 08:53:31 +00009363 // we may introduce new vector instructions which are not backed by TD
9364 // patterns. For example on AVX, extracting elements from a wide vector
9365 // without using extract_subvector.
Nadav Rotemba05c912012-01-17 21:44:01 +00009366 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9367 && ConstEltNo && !LegalOperations) {
9368 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9369 int NumElem = VT.getVectorNumElements();
9370 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9371 // Find the new index to extract from.
9372 int OrigElt = SVOp->getMaskElt(Elt);
9373
9374 // Extracting an undef index is undef.
9375 if (OrigElt == -1)
9376 return DAG.getUNDEF(NVT);
9377
9378 // Select the right vector half to extract from.
9379 if (OrigElt < NumElem) {
9380 InVec = InVec->getOperand(0);
9381 } else {
9382 InVec = InVec->getOperand(1);
9383 OrigElt -= NumElem;
9384 }
9385
Tom Stellard425b76c2013-08-05 22:22:01 +00009386 EVT IndexTy = TLI.getVectorIdxTy();
Andrew Trickac6d9be2013-05-25 02:42:55 +00009387 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
Jim Grosbacha249f7d2012-05-08 20:56:07 +00009388 InVec, DAG.getConstant(OrigElt, IndexTy));
Nadav Rotemba05c912012-01-17 21:44:01 +00009389 }
9390
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009391 // Perform only after legalization to ensure build_vector / vector_shuffle
9392 // optimizations have already been done.
Duncan Sands25cf2272008-11-24 14:53:14 +00009393 if (!LegalOperations) return SDValue();
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009394
Mon P Wang7ac9cdf2009-01-17 00:07:25 +00009395 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9396 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9397 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng513da432007-10-06 08:19:55 +00009398
Nadav Rotemba05c912012-01-17 21:44:01 +00009399 if (ConstEltNo) {
Eric Christophercaebdd42010-11-03 09:36:40 +00009400 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng513da432007-10-06 08:19:55 +00009401 bool NewLoad = false;
Mon P Wanga60b5232008-12-11 00:26:16 +00009402 bool BCNumEltsChanged = false;
Owen Andersone50ed302009-08-10 22:56:29 +00009403 EVT ExtVT = VT.getVectorElementType();
9404 EVT LVT = ExtVT;
Bill Wendlingc144a572009-01-30 23:36:47 +00009405
Evan Cheng84387ea2012-03-13 22:00:52 +00009406 // If the result of load has to be truncated, then it's not necessarily
9407 // profitable.
Evan Chenga03d3662012-03-13 22:16:11 +00009408 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
Evan Cheng84387ea2012-03-13 22:00:52 +00009409 return SDValue();
9410
Wesley Peckbf17cfa2010-11-23 03:31:01 +00009411 if (InVec.getOpcode() == ISD::BITCAST) {
Eli Friedmand6e25602011-12-26 22:49:32 +00009412 // Don't duplicate a load with other uses.
9413 if (!InVec.hasOneUse())
9414 return SDValue();
9415
Owen Andersone50ed302009-08-10 22:56:29 +00009416 EVT BCVT = InVec.getOperand(0).getValueType();
9417 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
Dan Gohman475871a2008-07-27 21:46:04 +00009418 return SDValue();
Mon P Wanga60b5232008-12-11 00:26:16 +00009419 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9420 BCNumEltsChanged = true;
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009421 InVec = InVec.getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00009422 ExtVT = BCVT.getVectorElementType();
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009423 NewLoad = true;
9424 }
Evan Cheng513da432007-10-06 08:19:55 +00009425
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009426 LoadSDNode *LN0 = NULL;
Nate Begeman5a5ca152009-04-29 05:20:52 +00009427 const ShuffleVectorSDNode *SVN = NULL;
Bill Wendlingc144a572009-01-30 23:36:47 +00009428 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009429 LN0 = cast<LoadSDNode>(InVec);
Bill Wendlingc144a572009-01-30 23:36:47 +00009430 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Andersone50ed302009-08-10 22:56:29 +00009431 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendlingc144a572009-01-30 23:36:47 +00009432 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmand6e25602011-12-26 22:49:32 +00009433 // Don't duplicate a load with other uses.
9434 if (!InVec.hasOneUse())
9435 return SDValue();
9436
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009437 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5a5ca152009-04-29 05:20:52 +00009438 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009439 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9440 // =>
9441 // (load $addr+1*size)
Scott Michelfdc40a02009-02-17 22:15:04 +00009442
Eli Friedmand6e25602011-12-26 22:49:32 +00009443 // Don't duplicate a load with other uses.
9444 if (!InVec.hasOneUse())
9445 return SDValue();
9446
Mon P Wanga60b5232008-12-11 00:26:16 +00009447 // If the bit convert changed the number of elements, it is unsafe
9448 // to examine the mask.
9449 if (BCNumEltsChanged)
9450 return SDValue();
Nate Begeman5a5ca152009-04-29 05:20:52 +00009451
9452 // Select the input vector, guarding against out of range extract vector.
9453 unsigned NumElems = VT.getVectorNumElements();
Eric Christophercaebdd42010-11-03 09:36:40 +00009454 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5a5ca152009-04-29 05:20:52 +00009455 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9456
Eli Friedmand6e25602011-12-26 22:49:32 +00009457 if (InVec.getOpcode() == ISD::BITCAST) {
9458 // Don't duplicate a load with other uses.
9459 if (!InVec.hasOneUse())
9460 return SDValue();
9461
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009462 InVec = InVec.getOperand(0);
Eli Friedmand6e25602011-12-26 22:49:32 +00009463 }
Gabor Greifba36cb52008-08-28 21:40:38 +00009464 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009465 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd0e88f32010-04-08 18:49:30 +00009466 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Evan Cheng513da432007-10-06 08:19:55 +00009467 }
9468 }
Bill Wendlingc144a572009-01-30 23:36:47 +00009469
Eli Friedmand6e25602011-12-26 22:49:32 +00009470 // Make sure we found a non-volatile load and the extractelement is
9471 // the only use.
Nadav Rotem42febc62011-05-11 14:40:50 +00009472 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman475871a2008-07-27 21:46:04 +00009473 return SDValue();
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009474
Eric Christopherd81f17a2010-11-03 20:44:42 +00009475 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9476 if (Elt == -1)
Eli Friedmaned4b4272011-07-25 22:25:42 +00009477 return DAG.getUNDEF(LVT);
Eric Christopherd81f17a2010-11-03 20:44:42 +00009478
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009479 unsigned Align = LN0->getAlignment();
9480 if (NewLoad) {
9481 // Check the resultant load doesn't need a higher alignment than the
9482 // original load.
Bill Wendlingc144a572009-01-30 23:36:47 +00009483 unsigned NewAlign =
Micah Villmow3574eca2012-10-08 16:38:25 +00009484 TLI.getDataLayout()
Eric Christopher503a64d2010-12-09 04:48:06 +00009485 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
Bill Wendlingc144a572009-01-30 23:36:47 +00009486
Dan Gohmanf560ffa2009-01-28 17:46:25 +00009487 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
Dan Gohman475871a2008-07-27 21:46:04 +00009488 return SDValue();
Bill Wendlingc144a572009-01-30 23:36:47 +00009489
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009490 Align = NewAlign;
9491 }
9492
Dan Gohman475871a2008-07-27 21:46:04 +00009493 SDValue NewPtr = LN0->getBasePtr();
Chris Lattnerfa459012010-09-21 16:08:50 +00009494 unsigned PtrOff = 0;
Wesley Peckbf17cfa2010-11-23 03:31:01 +00009495
Eric Christopherd81f17a2010-11-03 20:44:42 +00009496 if (Elt) {
Chris Lattnerfa459012010-09-21 16:08:50 +00009497 PtrOff = LVT.getSizeInBits() * Elt / 8;
Owen Andersone50ed302009-08-10 22:56:29 +00009498 EVT PtrType = NewPtr.getValueType();
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009499 if (TLI.isBigEndian())
Duncan Sands83ec4b62008-06-06 12:08:01 +00009500 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
Andrew Trickac6d9be2013-05-25 02:42:55 +00009501 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009502 DAG.getConstant(PtrOff, PtrType));
9503 }
Bill Wendlingc144a572009-01-30 23:36:47 +00009504
Eli Friedman4db4add2011-11-16 23:50:22 +00009505 // The replacement we need to do here is a little tricky: we need to
9506 // replace an extractelement of a load with a load.
9507 // Use ReplaceAllUsesOfValuesWith to do the replacement.
Eli Friedmand6e25602011-12-26 22:49:32 +00009508 // Note that this replacement assumes that the extractvalue is the only
9509 // use of the load; that's okay because we don't want to perform this
9510 // transformation in other cases anyway.
Evan Cheng84387ea2012-03-13 22:00:52 +00009511 SDValue Load;
Evan Chenga03d3662012-03-13 22:16:11 +00009512 SDValue Chain;
Evan Cheng84387ea2012-03-13 22:00:52 +00009513 if (NVT.bitsGT(LVT)) {
9514 // If the result type of vextract is wider than the load, then issue an
9515 // extending load instead.
9516 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9517 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
Andrew Trickac6d9be2013-05-25 02:42:55 +00009518 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
Evan Cheng84387ea2012-03-13 22:00:52 +00009519 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
Richard Sandiford66589dc2013-10-28 11:17:59 +00009520 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9521 Align, LN0->getTBAAInfo());
Evan Chenga03d3662012-03-13 22:16:11 +00009522 Chain = Load.getValue(1);
9523 } else {
Andrew Trickac6d9be2013-05-25 02:42:55 +00009524 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
Evan Cheng84387ea2012-03-13 22:00:52 +00009525 LN0->getPointerInfo().getWithOffset(PtrOff),
Stephen Lin155615d2013-07-08 00:37:03 +00009526 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00009527 LN0->isInvariant(), Align, LN0->getTBAAInfo());
Evan Chenga03d3662012-03-13 22:16:11 +00009528 Chain = Load.getValue(1);
9529 if (NVT.bitsLT(LVT))
Andrew Trickac6d9be2013-05-25 02:42:55 +00009530 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
Evan Chenga03d3662012-03-13 22:16:11 +00009531 else
Andrew Trickac6d9be2013-05-25 02:42:55 +00009532 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
Evan Chenga03d3662012-03-13 22:16:11 +00009533 }
Eli Friedman4db4add2011-11-16 23:50:22 +00009534 WorkListRemover DeadNodes(*this);
9535 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
Evan Chenga03d3662012-03-13 22:16:11 +00009536 SDValue To[] = { Load, Chain };
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00009537 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
Eli Friedman4db4add2011-11-16 23:50:22 +00009538 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9539 // worklist explicitly as well.
9540 AddToWorkList(Load.getNode());
Craig Topper0c9da212012-03-20 05:28:39 +00009541 AddUsersToWorkList(Load.getNode()); // Add users too
Eli Friedman4db4add2011-11-16 23:50:22 +00009542 // Make sure to revisit this node to clean it up; it will usually be dead.
9543 AddToWorkList(N);
9544 return SDValue(N, 0);
Evan Cheng513da432007-10-06 08:19:55 +00009545 }
Bill Wendlingc144a572009-01-30 23:36:47 +00009546
Dan Gohman475871a2008-07-27 21:46:04 +00009547 return SDValue();
Evan Cheng513da432007-10-06 08:19:55 +00009548}
Evan Cheng513da432007-10-06 08:19:55 +00009549
Michael Liaofac14ab2012-10-23 23:06:52 +00009550// Simplify (build_vec (ext )) to (bitcast (build_vec ))
9551SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9552 // We perform this optimization post type-legalization because
9553 // the type-legalizer often scalarizes integer-promoted vectors.
9554 // Performing this optimization before may create bit-casts which
9555 // will be type-legalized to complex code sequences.
9556 // We perform this optimization only before the operation legalizer because we
9557 // may introduce illegal operations.
9558 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9559 return SDValue();
9560
Dan Gohman7f321562007-06-25 16:23:39 +00009561 unsigned NumInScalars = N->getNumOperands();
Andrew Trickac6d9be2013-05-25 02:42:55 +00009562 SDLoc dl(N);
Owen Andersone50ed302009-08-10 22:56:29 +00009563 EVT VT = N->getValueType(0);
Nadav Rotemb87bdac2012-07-15 08:38:23 +00009564
Nadav Rotemb00418a2011-10-29 21:23:04 +00009565 // Check to see if this is a BUILD_VECTOR of a bunch of values
9566 // which come from any_extend or zero_extend nodes. If so, we can create
9567 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf47368b2011-10-31 20:08:25 +00009568 // optimizations. We do not handle sign-extend because we can't fill the sign
9569 // using shuffles.
Nadav Rotemb00418a2011-10-29 21:23:04 +00009570 EVT SourceType = MVT::Other;
Craig Topperd3b58892012-01-17 09:09:48 +00009571 bool AllAnyExt = true;
Nadav Rotemb87bdac2012-07-15 08:38:23 +00009572
Craig Topperd3b58892012-01-17 09:09:48 +00009573 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotemb00418a2011-10-29 21:23:04 +00009574 SDValue In = N->getOperand(i);
9575 // Ignore undef inputs.
9576 if (In.getOpcode() == ISD::UNDEF) continue;
9577
9578 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9579 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9580
Nadav Rotemf47368b2011-10-31 20:08:25 +00009581 // Abort if the element is not an extension.
Nadav Rotemb00418a2011-10-29 21:23:04 +00009582 if (!ZeroExt && !AnyExt) {
Nadav Rotemf47368b2011-10-31 20:08:25 +00009583 SourceType = MVT::Other;
Nadav Rotemb00418a2011-10-29 21:23:04 +00009584 break;
9585 }
9586
9587 // The input is a ZeroExt or AnyExt. Check the original type.
9588 EVT InTy = In.getOperand(0).getValueType();
9589
9590 // Check that all of the widened source types are the same.
9591 if (SourceType == MVT::Other)
Nadav Rotemf47368b2011-10-31 20:08:25 +00009592 // First time.
Nadav Rotemb00418a2011-10-29 21:23:04 +00009593 SourceType = InTy;
9594 else if (InTy != SourceType) {
9595 // Multiple income types. Abort.
Nadav Rotemf47368b2011-10-31 20:08:25 +00009596 SourceType = MVT::Other;
Nadav Rotemb00418a2011-10-29 21:23:04 +00009597 break;
9598 }
9599
9600 // Check if all of the extends are ANY_EXTENDs.
Craig Topperd3b58892012-01-17 09:09:48 +00009601 AllAnyExt &= AnyExt;
Nadav Rotemb00418a2011-10-29 21:23:04 +00009602 }
9603
Nadav Rotemf47368b2011-10-31 20:08:25 +00009604 // In order to have valid types, all of the inputs must be extended from the
9605 // same source type and all of the inputs must be any or zero extend.
9606 // Scalar sizes must be a power of two.
Michael Liaofac14ab2012-10-23 23:06:52 +00009607 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem2ee746b2012-02-12 15:05:31 +00009608 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf47368b2011-10-31 20:08:25 +00009609 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9610 isPowerOf2_32(SourceType.getSizeInBits());
9611
Nadav Rotem6431ff92012-03-15 08:49:06 +00009612 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9613 // turn into a single shuffle instruction.
Michael Liaofac14ab2012-10-23 23:06:52 +00009614 if (!ValidTypes)
9615 return SDValue();
Nadav Rotemb00418a2011-10-29 21:23:04 +00009616
Michael Liaofac14ab2012-10-23 23:06:52 +00009617 bool isLE = TLI.isLittleEndian();
9618 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9619 assert(ElemRatio > 1 && "Invalid element size ratio");
9620 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9621 DAG.getConstant(0, SourceType);
Nadav Rotemb00418a2011-10-29 21:23:04 +00009622
Michael Liaofac14ab2012-10-23 23:06:52 +00009623 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9624 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotemb00418a2011-10-29 21:23:04 +00009625
Michael Liaofac14ab2012-10-23 23:06:52 +00009626 // Populate the new build_vector
Jakub Staszakadf38912012-10-24 00:38:25 +00009627 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liaofac14ab2012-10-23 23:06:52 +00009628 SDValue Cast = N->getOperand(i);
9629 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9630 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9631 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9632 SDValue In;
9633 if (Cast.getOpcode() == ISD::UNDEF)
9634 In = DAG.getUNDEF(SourceType);
9635 else
9636 In = Cast->getOperand(0);
9637 unsigned Index = isLE ? (i * ElemRatio) :
9638 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotemb00418a2011-10-29 21:23:04 +00009639
Michael Liaofac14ab2012-10-23 23:06:52 +00009640 assert(Index < Ops.size() && "Invalid index");
9641 Ops[Index] = In;
Nadav Rotemb00418a2011-10-29 21:23:04 +00009642 }
Chris Lattnerca242442006-03-19 01:27:56 +00009643
Michael Liaofac14ab2012-10-23 23:06:52 +00009644 // The type of the new BUILD_VECTOR node.
9645 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9646 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9647 "Invalid vector size");
9648 // Check if the new vector type is legal.
9649 if (!isTypeLegal(VecVT)) return SDValue();
9650
9651 // Make the new BUILD_VECTOR.
9652 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9653
9654 // The new BUILD_VECTOR node has the potential to be further optimized.
9655 AddToWorkList(BV.getNode());
9656 // Bitcast to the desired type.
9657 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9658}
9659
Michael Liao1a5cc712012-10-24 04:14:18 +00009660SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9661 EVT VT = N->getValueType(0);
9662
9663 unsigned NumInScalars = N->getNumOperands();
Andrew Trickac6d9be2013-05-25 02:42:55 +00009664 SDLoc dl(N);
Michael Liao1a5cc712012-10-24 04:14:18 +00009665
9666 EVT SrcVT = MVT::Other;
9667 unsigned Opcode = ISD::DELETED_NODE;
9668 unsigned NumDefs = 0;
9669
9670 for (unsigned i = 0; i != NumInScalars; ++i) {
9671 SDValue In = N->getOperand(i);
9672 unsigned Opc = In.getOpcode();
9673
9674 if (Opc == ISD::UNDEF)
9675 continue;
9676
9677 // If all scalar values are floats and converted from integers.
9678 if (Opcode == ISD::DELETED_NODE &&
9679 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9680 Opcode = Opc;
Michael Liao1a5cc712012-10-24 04:14:18 +00009681 }
Tom Stellardd40758b2013-01-02 22:13:01 +00009682
Michael Liao1a5cc712012-10-24 04:14:18 +00009683 if (Opc != Opcode)
9684 return SDValue();
9685
9686 EVT InVT = In.getOperand(0).getValueType();
9687
9688 // If all scalar values are typed differently, bail out. It's chosen to
9689 // simplify BUILD_VECTOR of integer types.
9690 if (SrcVT == MVT::Other)
9691 SrcVT = InVT;
9692 if (SrcVT != InVT)
9693 return SDValue();
9694 NumDefs++;
9695 }
9696
9697 // If the vector has just one element defined, it's not worth to fold it into
9698 // a vectorized one.
9699 if (NumDefs < 2)
9700 return SDValue();
9701
9702 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9703 && "Should only handle conversion from integer to float.");
9704 assert(SrcVT != MVT::Other && "Cannot determine source type!");
9705
9706 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellardd40758b2013-01-02 22:13:01 +00009707
9708 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9709 return SDValue();
9710
Michael Liao1a5cc712012-10-24 04:14:18 +00009711 SmallVector<SDValue, 8> Opnds;
9712 for (unsigned i = 0; i != NumInScalars; ++i) {
9713 SDValue In = N->getOperand(i);
9714
9715 if (In.getOpcode() == ISD::UNDEF)
9716 Opnds.push_back(DAG.getUNDEF(SrcVT));
9717 else
9718 Opnds.push_back(In.getOperand(0));
9719 }
9720 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9721 &Opnds[0], Opnds.size());
9722 AddToWorkList(BV.getNode());
9723
9724 return DAG.getNode(Opcode, dl, VT, BV);
9725}
9726
Michael Liaofac14ab2012-10-23 23:06:52 +00009727SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9728 unsigned NumInScalars = N->getNumOperands();
Andrew Trickac6d9be2013-05-25 02:42:55 +00009729 SDLoc dl(N);
Michael Liaofac14ab2012-10-23 23:06:52 +00009730 EVT VT = N->getValueType(0);
9731
9732 // A vector built entirely of undefs is undef.
9733 if (ISD::allOperandsUndef(N))
9734 return DAG.getUNDEF(VT);
9735
9736 SDValue V = reduceBuildVecExtToExtBuildVec(N);
9737 if (V.getNode())
9738 return V;
9739
Michael Liao1a5cc712012-10-24 04:14:18 +00009740 V = reduceBuildVecConvertToConvertBuildVec(N);
9741 if (V.getNode())
9742 return V;
9743
Dan Gohman7f321562007-06-25 16:23:39 +00009744 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9745 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9746 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands00294ca2012-03-19 15:35:44 +00009747
9748 // May only combine to shuffle after legalize if shuffle is legal.
9749 if (LegalOperations &&
9750 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9751 return SDValue();
9752
Dan Gohman475871a2008-07-27 21:46:04 +00009753 SDValue VecIn1, VecIn2;
Chris Lattnerd7648c82006-03-28 20:28:38 +00009754 for (unsigned i = 0; i != NumInScalars; ++i) {
9755 // Ignore undef inputs.
9756 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
Scott Michelfdc40a02009-02-17 22:15:04 +00009757
Dan Gohman7f321562007-06-25 16:23:39 +00009758 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerd7648c82006-03-28 20:28:38 +00009759 // constant index, bail out.
Dan Gohman7f321562007-06-25 16:23:39 +00009760 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Chris Lattnerd7648c82006-03-28 20:28:38 +00009761 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
Dan Gohman475871a2008-07-27 21:46:04 +00009762 VecIn1 = VecIn2 = SDValue(0, 0);
Chris Lattnerd7648c82006-03-28 20:28:38 +00009763 break;
9764 }
Scott Michelfdc40a02009-02-17 22:15:04 +00009765
Nadav Rotem2ee746b2012-02-12 15:05:31 +00009766 // We allow up to two distinct input vectors.
Dan Gohman475871a2008-07-27 21:46:04 +00009767 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
Chris Lattnerd7648c82006-03-28 20:28:38 +00009768 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9769 continue;
Scott Michelfdc40a02009-02-17 22:15:04 +00009770
Gabor Greifba36cb52008-08-28 21:40:38 +00009771 if (VecIn1.getNode() == 0) {
Chris Lattnerd7648c82006-03-28 20:28:38 +00009772 VecIn1 = ExtractedFromVec;
Gabor Greifba36cb52008-08-28 21:40:38 +00009773 } else if (VecIn2.getNode() == 0) {
Chris Lattnerd7648c82006-03-28 20:28:38 +00009774 VecIn2 = ExtractedFromVec;
9775 } else {
9776 // Too many inputs.
Dan Gohman475871a2008-07-27 21:46:04 +00009777 VecIn1 = VecIn2 = SDValue(0, 0);
Chris Lattnerd7648c82006-03-28 20:28:38 +00009778 break;
9779 }
9780 }
Scott Michelfdc40a02009-02-17 22:15:04 +00009781
Nadav Rotem2ee746b2012-02-12 15:05:31 +00009782 // If everything is good, we can make a shuffle operation.
Gabor Greifba36cb52008-08-28 21:40:38 +00009783 if (VecIn1.getNode()) {
Nate Begeman9008ca62009-04-27 18:41:29 +00009784 SmallVector<int, 8> Mask;
Chris Lattnerd7648c82006-03-28 20:28:38 +00009785 for (unsigned i = 0; i != NumInScalars; ++i) {
9786 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
Nate Begeman9008ca62009-04-27 18:41:29 +00009787 Mask.push_back(-1);
Chris Lattnerd7648c82006-03-28 20:28:38 +00009788 continue;
9789 }
Scott Michelfdc40a02009-02-17 22:15:04 +00009790
Rafael Espindola15684b22009-04-24 12:40:33 +00009791 // If extracting from the first vector, just use the index directly.
Nate Begeman9008ca62009-04-27 18:41:29 +00009792 SDValue Extract = N->getOperand(i);
Mon P Wang93b74152009-03-17 06:33:10 +00009793 SDValue ExtVal = Extract.getOperand(1);
Chris Lattnerd7648c82006-03-28 20:28:38 +00009794 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5a5ca152009-04-29 05:20:52 +00009795 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9796 if (ExtIndex > VT.getVectorNumElements())
9797 return SDValue();
Wesley Peckbf17cfa2010-11-23 03:31:01 +00009798
Nate Begeman5a5ca152009-04-29 05:20:52 +00009799 Mask.push_back(ExtIndex);
Chris Lattnerd7648c82006-03-28 20:28:38 +00009800 continue;
9801 }
9802
9803 // Otherwise, use InIdx + VecSize
Mon P Wang93b74152009-03-17 06:33:10 +00009804 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Nate Begeman9008ca62009-04-27 18:41:29 +00009805 Mask.push_back(Idx+NumInScalars);
Chris Lattnerd7648c82006-03-28 20:28:38 +00009806 }
Scott Michelfdc40a02009-02-17 22:15:04 +00009807
Nadav Rotem2ee746b2012-02-12 15:05:31 +00009808 // We can't generate a shuffle node with mismatched input and output types.
9809 // Attempt to transform a single input vector to the correct type.
9810 if ((VT != VecIn1.getValueType())) {
9811 // We don't support shuffeling between TWO values of different types.
9812 if (VecIn2.getNode() != 0)
9813 return SDValue();
9814
9815 // We only support widening of vectors which are half the size of the
9816 // output registers. For example XMM->YMM widening on X86 with AVX.
9817 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9818 return SDValue();
9819
James Molloy8cd08bf2012-09-10 14:01:21 +00009820 // If the input vector type has a different base type to the output
9821 // vector type, bail out.
9822 if (VecIn1.getValueType().getVectorElementType() !=
9823 VT.getVectorElementType())
9824 return SDValue();
9825
Stepan Dyatkovskiyfdeb9fe2012-08-22 09:33:55 +00009826 // Widen the input vector by adding undef values.
Michael Liaofac14ab2012-10-23 23:06:52 +00009827 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
Stepan Dyatkovskiyfdeb9fe2012-08-22 09:33:55 +00009828 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
Nadav Rotem2ee746b2012-02-12 15:05:31 +00009829 }
9830
9831 // If VecIn2 is unused then change it to undef.
9832 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9833
Nadav Rotem6dfabb62012-09-20 08:53:31 +00009834 // Check that we were able to transform all incoming values to the same
9835 // type.
Nadav Rotem0877fdf2012-02-13 12:42:26 +00009836 if (VecIn2.getValueType() != VecIn1.getValueType() ||
9837 VecIn1.getValueType() != VT)
9838 return SDValue();
9839
Nadav Rotem2ee746b2012-02-12 15:05:31 +00009840 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
Nadav Rotem0877fdf2012-02-13 12:42:26 +00009841 if (!isTypeLegal(VT))
Duncan Sands25cf2272008-11-24 14:53:14 +00009842 return SDValue();
9843
Dan Gohman7f321562007-06-25 16:23:39 +00009844 // Return the new VECTOR_SHUFFLE node.
Nate Begeman9008ca62009-04-27 18:41:29 +00009845 SDValue Ops[2];
Chris Lattnerbd564bf2006-08-08 02:23:42 +00009846 Ops[0] = VecIn1;
Nadav Rotem2ee746b2012-02-12 15:05:31 +00009847 Ops[1] = VecIn2;
Michael Liaofac14ab2012-10-23 23:06:52 +00009848 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerd7648c82006-03-28 20:28:38 +00009849 }
Scott Michelfdc40a02009-02-17 22:15:04 +00009850
Dan Gohman475871a2008-07-27 21:46:04 +00009851 return SDValue();
Chris Lattnerd7648c82006-03-28 20:28:38 +00009852}
9853
Dan Gohman475871a2008-07-27 21:46:04 +00009854SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohman7f321562007-06-25 16:23:39 +00009855 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9856 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
9857 // inputs come from at most two distinct vectors, turn this into a shuffle
9858 // node.
9859
9860 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendlingc144a572009-01-30 23:36:47 +00009861 if (N->getNumOperands() == 1)
Dan Gohman7f321562007-06-25 16:23:39 +00009862 return N->getOperand(0);
Dan Gohman7f321562007-06-25 16:23:39 +00009863
Nadav Rotemb7e230d2012-07-14 21:30:27 +00009864 // Check if all of the operands are undefs.
Nadav Rotem97541d42013-10-25 06:41:18 +00009865 EVT VT = N->getValueType(0);
Nadav Rotemb87bdac2012-07-15 08:38:23 +00009866 if (ISD::allOperandsUndef(N))
Nadav Rotem97541d42013-10-25 06:41:18 +00009867 return DAG.getUNDEF(VT);
9868
9869 // Optimize concat_vectors where one of the vectors is undef.
9870 if (N->getNumOperands() == 2 &&
9871 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
9872 SDValue In = N->getOperand(0);
9873 assert(In->getValueType(0).isVector() && "Must concat vectors");
9874
9875 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
9876 if (In->getOpcode() == ISD::BITCAST &&
9877 !In->getOperand(0)->getValueType(0).isVector()) {
9878 SDValue Scalar = In->getOperand(0);
9879 EVT SclTy = Scalar->getValueType(0);
9880
9881 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
9882 return SDValue();
9883
9884 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
9885 VT.getSizeInBits() / SclTy.getSizeInBits());
9886 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
9887 return SDValue();
9888
9889 SDLoc dl = SDLoc(N);
9890 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
9891 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
9892 }
9893 }
Nadav Rotemb7e230d2012-07-14 21:30:27 +00009894
Nadav Rotemb2ed5fa2013-05-01 19:18:51 +00009895 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
9896 // nodes often generate nop CONCAT_VECTOR nodes.
9897 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
9898 // place the incoming vectors at the exact same location.
9899 SDValue SingleSource = SDValue();
9900 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
9901
9902 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9903 SDValue Op = N->getOperand(i);
9904
9905 if (Op.getOpcode() == ISD::UNDEF)
9906 continue;
9907
9908 // Check if this is the identity extract:
9909 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9910 return SDValue();
9911
9912 // Find the single incoming vector for the extract_subvector.
9913 if (SingleSource.getNode()) {
9914 if (Op.getOperand(0) != SingleSource)
9915 return SDValue();
9916 } else {
9917 SingleSource = Op.getOperand(0);
Michael Kuperstein27202482013-05-06 08:06:13 +00009918
9919 // Check the source type is the same as the type of the result.
9920 // If not, this concat may extend the vector, so we can not
9921 // optimize it away.
9922 if (SingleSource.getValueType() != N->getValueType(0))
9923 return SDValue();
Nadav Rotemb2ed5fa2013-05-01 19:18:51 +00009924 }
9925
9926 unsigned IdentityIndex = i * PartNumElem;
9927 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9928 // The extract index must be constant.
9929 if (!CS)
9930 return SDValue();
Stephen Lin155615d2013-07-08 00:37:03 +00009931
Nadav Rotemb2ed5fa2013-05-01 19:18:51 +00009932 // Check that we are reading from the identity index.
9933 if (CS->getZExtValue() != IdentityIndex)
9934 return SDValue();
9935 }
9936
9937 if (SingleSource.getNode())
9938 return SingleSource;
Stephen Lin155615d2013-07-08 00:37:03 +00009939
Dan Gohman475871a2008-07-27 21:46:04 +00009940 return SDValue();
Dan Gohman7f321562007-06-25 16:23:39 +00009941}
9942
Bruno Cardoso Lopese97190f2011-09-20 23:19:33 +00009943SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
9944 EVT NVT = N->getValueType(0);
9945 SDValue V = N->getOperand(0);
9946
Michael Liao13429e22012-10-17 20:48:33 +00009947 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
9948 // Combine:
9949 // (extract_subvec (concat V1, V2, ...), i)
9950 // Into:
9951 // Vi if possible
Jack Carteradbd3ae2013-10-17 01:34:33 +00009952 // Only operand 0 is checked as 'concat' assumes all inputs of the same
9953 // type.
Michael Liao9aecdb52012-10-19 03:17:00 +00009954 if (V->getOperand(0).getValueType() != NVT)
9955 return SDValue();
Michael Liao13429e22012-10-17 20:48:33 +00009956 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9957 unsigned NumElems = NVT.getVectorNumElements();
9958 assert((Idx % NumElems) == 0 &&
9959 "IDX in concat is not a multiple of the result vector length.");
9960 return V->getOperand(Idx / NumElems);
9961 }
9962
Michael Liaob4f98ea2013-03-25 23:47:35 +00009963 // Skip bitcasting
9964 if (V->getOpcode() == ISD::BITCAST)
9965 V = V.getOperand(0);
9966
9967 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00009968 SDLoc dl(N);
Michael Liaob4f98ea2013-03-25 23:47:35 +00009969 // Handle only simple case where vector being inserted and vector
9970 // being extracted are of same type, and are half size of larger vectors.
9971 EVT BigVT = V->getOperand(0).getValueType();
9972 EVT SmallVT = V->getOperand(1).getValueType();
9973 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
9974 return SDValue();
9975
9976 // Only handle cases where both indexes are constants with the same type.
9977 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9978 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
9979
9980 if (InsIdx && ExtIdx &&
9981 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
9982 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
9983 // Combine:
9984 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
9985 // Into:
9986 // indices are equal or bit offsets are equal => V1
9987 // otherwise => (extract_subvec V1, ExtIdx)
9988 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
9989 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
9990 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
9991 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
9992 DAG.getNode(ISD::BITCAST, dl,
9993 N->getOperand(0).getValueType(),
9994 V->getOperand(0)), N->getOperand(1));
9995 }
9996 }
9997
Bruno Cardoso Lopese97190f2011-09-20 23:19:33 +00009998 return SDValue();
9999}
10000
Benjamin Kramer6fac1fb2013-04-09 17:41:43 +000010001// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10002static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10003 EVT VT = N->getValueType(0);
10004 unsigned NumElts = VT.getVectorNumElements();
10005
10006 SDValue N0 = N->getOperand(0);
10007 SDValue N1 = N->getOperand(1);
10008 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10009
10010 SmallVector<SDValue, 4> Ops;
10011 EVT ConcatVT = N0.getOperand(0).getValueType();
10012 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10013 unsigned NumConcats = NumElts / NumElemsPerConcat;
10014
10015 // Look at every vector that's inserted. We're looking for exact
10016 // subvector-sized copies from a concatenated vector
10017 for (unsigned I = 0; I != NumConcats; ++I) {
10018 // Make sure we're dealing with a copy.
10019 unsigned Begin = I * NumElemsPerConcat;
Hao Liu3778c042013-05-13 02:07:05 +000010020 bool AllUndef = true, NoUndef = true;
10021 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10022 if (SVN->getMaskElt(J) >= 0)
10023 AllUndef = false;
10024 else
10025 NoUndef = false;
Benjamin Kramer6fac1fb2013-04-09 17:41:43 +000010026 }
10027
Hao Liu3778c042013-05-13 02:07:05 +000010028 if (NoUndef) {
Hao Liu3778c042013-05-13 02:07:05 +000010029 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10030 return SDValue();
10031
10032 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10033 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10034 return SDValue();
10035
10036 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10037 if (FirstElt < N0.getNumOperands())
10038 Ops.push_back(N0.getOperand(FirstElt));
10039 else
10040 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10041
10042 } else if (AllUndef) {
10043 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10044 } else { // Mixed with general masks and undefs, can't do optimization.
10045 return SDValue();
10046 }
Benjamin Kramer6fac1fb2013-04-09 17:41:43 +000010047 }
10048
Andrew Trickac6d9be2013-05-25 02:42:55 +000010049 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
Benjamin Kramer6fac1fb2013-04-09 17:41:43 +000010050 Ops.size());
10051}
10052
Dan Gohman475871a2008-07-27 21:46:04 +000010053SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Andersone50ed302009-08-10 22:56:29 +000010054 EVT VT = N->getValueType(0);
Nate Begeman9008ca62009-04-27 18:41:29 +000010055 unsigned NumElts = VT.getVectorNumElements();
Chris Lattnerf1d0c622006-03-31 22:16:43 +000010056
Mon P Wangaeb06d22008-11-10 04:46:22 +000010057 SDValue N0 = N->getOperand(0);
Craig Topper481b79c2012-01-04 08:07:43 +000010058 SDValue N1 = N->getOperand(1);
Mon P Wangaeb06d22008-11-10 04:46:22 +000010059
Craig Topperae1bec52012-04-09 05:16:56 +000010060 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wangaeb06d22008-11-10 04:46:22 +000010061
Craig Topper481b79c2012-01-04 08:07:43 +000010062 // Canonicalize shuffle undef, undef -> undef
10063 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10064 return DAG.getUNDEF(VT);
10065
10066 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10067
10068 // Canonicalize shuffle v, v -> v, undef
10069 if (N0 == N1) {
10070 SmallVector<int, 8> NewMask;
10071 for (unsigned i = 0; i != NumElts; ++i) {
10072 int Idx = SVN->getMaskElt(i);
10073 if (Idx >= (int)NumElts) Idx -= NumElts;
10074 NewMask.push_back(Idx);
10075 }
Andrew Trickac6d9be2013-05-25 02:42:55 +000010076 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper481b79c2012-01-04 08:07:43 +000010077 &NewMask[0]);
10078 }
10079
10080 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10081 if (N0.getOpcode() == ISD::UNDEF) {
10082 SmallVector<int, 8> NewMask;
10083 for (unsigned i = 0; i != NumElts; ++i) {
10084 int Idx = SVN->getMaskElt(i);
Craig Topper4b206bd2012-04-09 05:55:33 +000010085 if (Idx >= 0) {
Craig Topper01d22aa2013-08-08 07:38:55 +000010086 if (Idx >= (int)NumElts)
Craig Topper4b206bd2012-04-09 05:55:33 +000010087 Idx -= NumElts;
Craig Topper01d22aa2013-08-08 07:38:55 +000010088 else
10089 Idx = -1; // remove reference to lhs
Craig Topper4b206bd2012-04-09 05:55:33 +000010090 }
10091 NewMask.push_back(Idx);
Craig Topper481b79c2012-01-04 08:07:43 +000010092 }
Andrew Trickac6d9be2013-05-25 02:42:55 +000010093 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper481b79c2012-01-04 08:07:43 +000010094 &NewMask[0]);
10095 }
10096
10097 // Remove references to rhs if it is undef
10098 if (N1.getOpcode() == ISD::UNDEF) {
10099 bool Changed = false;
10100 SmallVector<int, 8> NewMask;
10101 for (unsigned i = 0; i != NumElts; ++i) {
10102 int Idx = SVN->getMaskElt(i);
10103 if (Idx >= (int)NumElts) {
10104 Idx = -1;
10105 Changed = true;
10106 }
10107 NewMask.push_back(Idx);
10108 }
10109 if (Changed)
Andrew Trickac6d9be2013-05-25 02:42:55 +000010110 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper481b79c2012-01-04 08:07:43 +000010111 }
Evan Chenge7bec0d2006-07-20 22:44:41 +000010112
Bob Wilson0f1db1a2010-10-28 17:06:14 +000010113 // If it is a splat, check if the argument vector is another splat or a
10114 // build_vector with all scalar elements the same.
Bob Wilson0f1db1a2010-10-28 17:06:14 +000010115 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greifba36cb52008-08-28 21:40:38 +000010116 SDNode *V = N0.getNode();
Evan Cheng917ec982006-07-21 08:25:53 +000010117
Dan Gohman7f321562007-06-25 16:23:39 +000010118 // If this is a bit convert that changes the element type of the vector but
Evan Cheng59569222006-10-16 22:49:37 +000010119 // not the number of vector elements, look through it. Be careful not to
10120 // look though conversions that change things like v4f32 to v2f64.
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010121 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman475871a2008-07-27 21:46:04 +000010122 SDValue ConvInput = V->getOperand(0);
Evan Cheng29257862008-07-22 20:42:56 +000010123 if (ConvInput.getValueType().isVector() &&
10124 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greifba36cb52008-08-28 21:40:38 +000010125 V = ConvInput.getNode();
Evan Cheng59569222006-10-16 22:49:37 +000010126 }
10127
Dan Gohman7f321562007-06-25 16:23:39 +000010128 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilson0f1db1a2010-10-28 17:06:14 +000010129 assert(V->getNumOperands() == NumElts &&
10130 "BUILD_VECTOR has wrong number of operands");
10131 SDValue Base;
10132 bool AllSame = true;
10133 for (unsigned i = 0; i != NumElts; ++i) {
10134 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10135 Base = V->getOperand(i);
10136 break;
Evan Cheng917ec982006-07-21 08:25:53 +000010137 }
Evan Cheng917ec982006-07-21 08:25:53 +000010138 }
Bob Wilson0f1db1a2010-10-28 17:06:14 +000010139 // Splat of <u, u, u, u>, return <u, u, u, u>
10140 if (!Base.getNode())
10141 return N0;
10142 for (unsigned i = 0; i != NumElts; ++i) {
10143 if (V->getOperand(i) != Base) {
10144 AllSame = false;
10145 break;
10146 }
10147 }
10148 // Splat of <x, x, x, x>, return <x, x, x, x>
10149 if (AllSame)
10150 return N0;
Evan Cheng917ec982006-07-21 08:25:53 +000010151 }
10152 }
Nadav Rotem4ac90812012-04-01 19:31:22 +000010153
Benjamin Kramer6fac1fb2013-04-09 17:41:43 +000010154 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10155 Level < AfterLegalizeVectorOps &&
10156 (N1.getOpcode() == ISD::UNDEF ||
10157 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10158 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10159 SDValue V = partitionShuffleOfConcats(N, DAG);
10160
10161 if (V.getNode())
10162 return V;
10163 }
10164
Nadav Rotem4ac90812012-04-01 19:31:22 +000010165 // If this shuffle node is simply a swizzle of another shuffle node,
Nadav Rotemd16c8d02012-04-07 21:19:08 +000010166 // and it reverses the swizzle of the previous shuffle then we can
10167 // optimize shuffle(shuffle(x, undef), undef) -> x.
Nadav Rotem4ac90812012-04-01 19:31:22 +000010168 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10169 N1.getOpcode() == ISD::UNDEF) {
10170
Nadav Rotem4ac90812012-04-01 19:31:22 +000010171 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10172
Nadav Rotemd16c8d02012-04-07 21:19:08 +000010173 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10174 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10175 return SDValue();
10176
Craig Topperae1bec52012-04-09 05:16:56 +000010177 // The incoming shuffle must be of the same type as the result of the
10178 // current shuffle.
10179 assert(OtherSV->getOperand(0).getValueType() == VT &&
10180 "Shuffle types don't match");
Nadav Rotem4ac90812012-04-01 19:31:22 +000010181
10182 for (unsigned i = 0; i != NumElts; ++i) {
10183 int Idx = SVN->getMaskElt(i);
Craig Topperae1bec52012-04-09 05:16:56 +000010184 assert(Idx < (int)NumElts && "Index references undef operand");
Nadav Rotem4ac90812012-04-01 19:31:22 +000010185 // Next, this index comes from the first value, which is the incoming
10186 // shuffle. Adopt the incoming index.
10187 if (Idx >= 0)
10188 Idx = OtherSV->getMaskElt(Idx);
10189
Nadav Rotemd16c8d02012-04-07 21:19:08 +000010190 // The combined shuffle must map each index to itself.
Craig Topperae1bec52012-04-09 05:16:56 +000010191 if (Idx >= 0 && (unsigned)Idx != i)
Nadav Rotemd16c8d02012-04-07 21:19:08 +000010192 return SDValue();
Nadav Rotem4ac90812012-04-01 19:31:22 +000010193 }
Nadav Rotemd16c8d02012-04-07 21:19:08 +000010194
10195 return OtherSV->getOperand(0);
Nadav Rotem4ac90812012-04-01 19:31:22 +000010196 }
10197
Dan Gohman475871a2008-07-27 21:46:04 +000010198 return SDValue();
Chris Lattnerf1d0c622006-03-31 22:16:43 +000010199}
10200
Evan Cheng44f1f092006-04-20 08:56:16 +000010201/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
Dan Gohman7f321562007-06-25 16:23:39 +000010202/// an AND to a vector_shuffle with the destination vector and a zero vector.
10203/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Cheng44f1f092006-04-20 08:56:16 +000010204/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman475871a2008-07-27 21:46:04 +000010205SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Andersone50ed302009-08-10 22:56:29 +000010206 EVT VT = N->getValueType(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +000010207 SDLoc dl(N);
Dan Gohman475871a2008-07-27 21:46:04 +000010208 SDValue LHS = N->getOperand(0);
10209 SDValue RHS = N->getOperand(1);
Dan Gohman7f321562007-06-25 16:23:39 +000010210 if (N->getOpcode() == ISD::AND) {
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010211 if (RHS.getOpcode() == ISD::BITCAST)
Evan Cheng44f1f092006-04-20 08:56:16 +000010212 RHS = RHS.getOperand(0);
Dan Gohman7f321562007-06-25 16:23:39 +000010213 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman9008ca62009-04-27 18:41:29 +000010214 SmallVector<int, 8> Indices;
10215 unsigned NumElts = RHS.getNumOperands();
Evan Cheng44f1f092006-04-20 08:56:16 +000010216 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +000010217 SDValue Elt = RHS.getOperand(i);
Evan Cheng44f1f092006-04-20 08:56:16 +000010218 if (!isa<ConstantSDNode>(Elt))
Dan Gohman475871a2008-07-27 21:46:04 +000010219 return SDValue();
Craig Topperb7135e52012-04-09 05:59:53 +000010220
10221 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman9008ca62009-04-27 18:41:29 +000010222 Indices.push_back(i);
Evan Cheng44f1f092006-04-20 08:56:16 +000010223 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Nate Begeman9008ca62009-04-27 18:41:29 +000010224 Indices.push_back(NumElts);
Evan Cheng44f1f092006-04-20 08:56:16 +000010225 else
Dan Gohman475871a2008-07-27 21:46:04 +000010226 return SDValue();
Evan Cheng44f1f092006-04-20 08:56:16 +000010227 }
10228
10229 // Let's see if the target supports this vector_shuffle.
Owen Andersone50ed302009-08-10 22:56:29 +000010230 EVT RVT = RHS.getValueType();
Nate Begeman9008ca62009-04-27 18:41:29 +000010231 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman475871a2008-07-27 21:46:04 +000010232 return SDValue();
Evan Cheng44f1f092006-04-20 08:56:16 +000010233
Dan Gohman7f321562007-06-25 16:23:39 +000010234 // Return the new VECTOR_SHUFFLE node.
Dan Gohman8a55ce42009-09-23 21:02:20 +000010235 EVT EltVT = RVT.getVectorElementType();
Nate Begeman9008ca62009-04-27 18:41:29 +000010236 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman8a55ce42009-09-23 21:02:20 +000010237 DAG.getConstant(0, EltVT));
Andrew Trickac6d9be2013-05-25 02:42:55 +000010238 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Nate Begeman9008ca62009-04-27 18:41:29 +000010239 RVT, &ZeroOps[0], ZeroOps.size());
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010240 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman9008ca62009-04-27 18:41:29 +000010241 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010242 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Cheng44f1f092006-04-20 08:56:16 +000010243 }
10244 }
Bill Wendling836ca7d2009-01-30 23:59:18 +000010245
Dan Gohman475871a2008-07-27 21:46:04 +000010246 return SDValue();
Evan Cheng44f1f092006-04-20 08:56:16 +000010247}
10248
Dan Gohman7f321562007-06-25 16:23:39 +000010249/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
Dan Gohman475871a2008-07-27 21:46:04 +000010250SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilsond7273432010-12-17 23:06:49 +000010251 assert(N->getValueType(0).isVector() &&
10252 "SimplifyVBinOp only works on vectors!");
Dan Gohman7f321562007-06-25 16:23:39 +000010253
Dan Gohman475871a2008-07-27 21:46:04 +000010254 SDValue LHS = N->getOperand(0);
10255 SDValue RHS = N->getOperand(1);
10256 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greifba36cb52008-08-28 21:40:38 +000010257 if (Shuffle.getNode()) return Shuffle;
Evan Cheng44f1f092006-04-20 08:56:16 +000010258
Dan Gohman7f321562007-06-25 16:23:39 +000010259 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattneredab1b92006-04-02 03:25:57 +000010260 // this operation.
Scott Michelfdc40a02009-02-17 22:15:04 +000010261 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohman7f321562007-06-25 16:23:39 +000010262 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Dan Gohman475871a2008-07-27 21:46:04 +000010263 SmallVector<SDValue, 8> Ops;
Dan Gohman7f321562007-06-25 16:23:39 +000010264 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +000010265 SDValue LHSOp = LHS.getOperand(i);
10266 SDValue RHSOp = RHS.getOperand(i);
Chris Lattneredab1b92006-04-02 03:25:57 +000010267 // If these two elements can't be folded, bail out.
10268 if ((LHSOp.getOpcode() != ISD::UNDEF &&
10269 LHSOp.getOpcode() != ISD::Constant &&
10270 LHSOp.getOpcode() != ISD::ConstantFP) ||
10271 (RHSOp.getOpcode() != ISD::UNDEF &&
10272 RHSOp.getOpcode() != ISD::Constant &&
10273 RHSOp.getOpcode() != ISD::ConstantFP))
10274 break;
Bill Wendling836ca7d2009-01-30 23:59:18 +000010275
Evan Cheng7b336a82006-05-31 06:08:35 +000010276 // Can't fold divide by zero.
Dan Gohman7f321562007-06-25 16:23:39 +000010277 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10278 N->getOpcode() == ISD::FDIV) {
Evan Cheng7b336a82006-05-31 06:08:35 +000010279 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greifba36cb52008-08-28 21:40:38 +000010280 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng7b336a82006-05-31 06:08:35 +000010281 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greifba36cb52008-08-28 21:40:38 +000010282 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng7b336a82006-05-31 06:08:35 +000010283 break;
10284 }
Bill Wendling836ca7d2009-01-30 23:59:18 +000010285
Bob Wilsond7273432010-12-17 23:06:49 +000010286 EVT VT = LHSOp.getValueType();
Bob Wilsondb2b18f2011-10-18 17:34:47 +000010287 EVT RVT = RHSOp.getValueType();
10288 if (RVT != VT) {
10289 // Integer BUILD_VECTOR operands may have types larger than the element
10290 // size (e.g., when the element type is not legal). Prior to type
10291 // legalization, the types may not match between the two BUILD_VECTORS.
10292 // Truncate one of the operands to make them match.
10293 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +000010294 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilsondb2b18f2011-10-18 17:34:47 +000010295 } else {
Andrew Trickac6d9be2013-05-25 02:42:55 +000010296 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilsondb2b18f2011-10-18 17:34:47 +000010297 VT = RVT;
10298 }
10299 }
Andrew Trickac6d9be2013-05-25 02:42:55 +000010300 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Chenga0839882010-05-18 00:03:40 +000010301 LHSOp, RHSOp);
10302 if (FoldOp.getOpcode() != ISD::UNDEF &&
10303 FoldOp.getOpcode() != ISD::Constant &&
10304 FoldOp.getOpcode() != ISD::ConstantFP)
10305 break;
10306 Ops.push_back(FoldOp);
10307 AddToWorkList(FoldOp.getNode());
Chris Lattneredab1b92006-04-02 03:25:57 +000010308 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010309
Bob Wilsond7273432010-12-17 23:06:49 +000010310 if (Ops.size() == LHS.getNumOperands())
Andrew Trickac6d9be2013-05-25 02:42:55 +000010311 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Bob Wilsond7273432010-12-17 23:06:49 +000010312 LHS.getValueType(), &Ops[0], Ops.size());
Chris Lattneredab1b92006-04-02 03:25:57 +000010313 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010314
Dan Gohman475871a2008-07-27 21:46:04 +000010315 return SDValue();
Chris Lattneredab1b92006-04-02 03:25:57 +000010316}
10317
Craig Topperdd201ff2012-09-11 01:45:21 +000010318/// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10319SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topperdd201ff2012-09-11 01:45:21 +000010320 assert(N->getValueType(0).isVector() &&
10321 "SimplifyVUnaryOp only works on vectors!");
10322
10323 SDValue N0 = N->getOperand(0);
10324
10325 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10326 return SDValue();
10327
10328 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10329 SmallVector<SDValue, 8> Ops;
10330 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10331 SDValue Op = N0.getOperand(i);
10332 if (Op.getOpcode() != ISD::UNDEF &&
10333 Op.getOpcode() != ISD::ConstantFP)
10334 break;
10335 EVT EltVT = Op.getValueType();
Andrew Trickac6d9be2013-05-25 02:42:55 +000010336 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topperdd201ff2012-09-11 01:45:21 +000010337 if (FoldOp.getOpcode() != ISD::UNDEF &&
10338 FoldOp.getOpcode() != ISD::ConstantFP)
10339 break;
10340 Ops.push_back(FoldOp);
10341 AddToWorkList(FoldOp.getNode());
10342 }
10343
10344 if (Ops.size() != N0.getNumOperands())
10345 return SDValue();
10346
Andrew Trickac6d9be2013-05-25 02:42:55 +000010347 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Craig Topperdd201ff2012-09-11 01:45:21 +000010348 N0.getValueType(), &Ops[0], Ops.size());
10349}
10350
Andrew Trickac6d9be2013-05-25 02:42:55 +000010351SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling836ca7d2009-01-30 23:59:18 +000010352 SDValue N1, SDValue N2){
Nate Begemanf845b452005-10-08 00:29:44 +000010353 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelfdc40a02009-02-17 22:15:04 +000010354
Bill Wendling836ca7d2009-01-30 23:59:18 +000010355 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begemanf845b452005-10-08 00:29:44 +000010356 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling836ca7d2009-01-30 23:59:18 +000010357
Nate Begemanf845b452005-10-08 00:29:44 +000010358 // If we got a simplified select_cc node back from SimplifySelectCC, then
10359 // break it down into a new SETCC node, and a new SELECT node, and then return
10360 // the SELECT node, since we were called with a SELECT node.
Gabor Greifba36cb52008-08-28 21:40:38 +000010361 if (SCC.getNode()) {
Nate Begemanf845b452005-10-08 00:29:44 +000010362 // Check to see if we got a select_cc back (to turn into setcc/select).
10363 // Otherwise, just return whatever node we got back, like fabs.
10364 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickac6d9be2013-05-25 02:42:55 +000010365 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling836ca7d2009-01-30 23:59:18 +000010366 N0.getValueType(),
Scott Michelfdc40a02009-02-17 22:15:04 +000010367 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling836ca7d2009-01-30 23:59:18 +000010368 SCC.getOperand(4));
Gabor Greifba36cb52008-08-28 21:40:38 +000010369 AddToWorkList(SETCC.getNode());
Matt Arsenaultb05e4772013-06-14 22:04:37 +000010370 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10371 SCC.getOperand(2), SCC.getOperand(3), SETCC);
Nate Begemanf845b452005-10-08 00:29:44 +000010372 }
Bill Wendling836ca7d2009-01-30 23:59:18 +000010373
Nate Begemanf845b452005-10-08 00:29:44 +000010374 return SCC;
10375 }
Dan Gohman475871a2008-07-27 21:46:04 +000010376 return SDValue();
Nate Begeman44728a72005-09-19 22:34:01 +000010377}
10378
Chris Lattner40c62d52005-10-18 06:04:22 +000010379/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10380/// are the two values being selected between, see if we can simplify the
Chris Lattner729c6d12006-05-27 00:43:02 +000010381/// select. Callers of this should assume that TheSelect is deleted if this
10382/// returns true. As such, they should return the appropriate thing (e.g. the
10383/// node) back to the top-level of the DAG combiner loop to avoid it being
10384/// looked at.
Scott Michelfdc40a02009-02-17 22:15:04 +000010385bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman475871a2008-07-27 21:46:04 +000010386 SDValue RHS) {
Scott Michelfdc40a02009-02-17 22:15:04 +000010387
Nadav Rotemf94fdb62011-02-11 19:57:47 +000010388 // Cannot simplify select with vector condition
10389 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10390
Chris Lattner40c62d52005-10-18 06:04:22 +000010391 // If this is a select from two identical things, try to pull the operation
10392 // through the select.
Chris Lattner18061612010-09-21 15:46:59 +000010393 if (LHS.getOpcode() != RHS.getOpcode() ||
10394 !LHS.hasOneUse() || !RHS.hasOneUse())
10395 return false;
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010396
Chris Lattner18061612010-09-21 15:46:59 +000010397 // If this is a load and the token chain is identical, replace the select
10398 // of two loads with a load through a select of the address to load from.
10399 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10400 // constants have been dropped into the constant pool.
10401 if (LHS.getOpcode() == ISD::LOAD) {
10402 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10403 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010404
Chris Lattner18061612010-09-21 15:46:59 +000010405 // Token chains must be identical.
10406 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sandsd4b9c172008-06-13 19:07:40 +000010407 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner18061612010-09-21 15:46:59 +000010408 LLD->isVolatile() || RLD->isVolatile() ||
10409 // If this is an EXTLOAD, the VT's must match.
10410 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sandsdcfd3a72010-11-18 20:05:18 +000010411 // If this is an EXTLOAD, the kind of extension must match.
10412 (LLD->getExtensionType() != RLD->getExtensionType() &&
10413 // The only exception is if one of the extensions is anyext.
10414 LLD->getExtensionType() != ISD::EXTLOAD &&
10415 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohman75832d72009-10-31 14:14:04 +000010416 // FIXME: this discards src value information. This is
10417 // over-conservative. It would be beneficial to be able to remember
Mon P Wangfe240b12010-01-11 20:12:49 +000010418 // both potential memory locations. Since we are discarding
10419 // src value info, don't do the transformation if the memory
10420 // locations are not in the default address space.
Chris Lattner18061612010-09-21 15:46:59 +000010421 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooperb0fde6d2013-02-12 03:14:50 +000010422 RLD->getPointerInfo().getAddrSpace() != 0 ||
10423 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10424 LLD->getBasePtr().getValueType()))
Chris Lattner18061612010-09-21 15:46:59 +000010425 return false;
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010426
Chris Lattnerf1658062010-09-21 15:58:55 +000010427 // Check that the select condition doesn't reach either load. If so,
10428 // folding this will induce a cycle into the DAG. If not, this is safe to
10429 // xform, so create a select of the addresses.
Chris Lattner18061612010-09-21 15:46:59 +000010430 SDValue Addr;
10431 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnerf1658062010-09-21 15:58:55 +000010432 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10433 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10434 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10435 return false;
Nadav Rotem1c5bf3f2012-10-18 18:06:48 +000010436 // The loads must not depend on one another.
10437 if (LLD->isPredecessorOf(RLD) ||
10438 RLD->isPredecessorOf(LLD))
10439 return false;
Matt Arsenaultb05e4772013-06-14 22:04:37 +000010440 Addr = DAG.getSelect(SDLoc(TheSelect),
10441 LLD->getBasePtr().getValueType(),
10442 TheSelect->getOperand(0), LLD->getBasePtr(),
10443 RLD->getBasePtr());
Chris Lattner18061612010-09-21 15:46:59 +000010444 } else { // Otherwise SELECT_CC
Chris Lattnerf1658062010-09-21 15:58:55 +000010445 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10446 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10447
10448 if ((LLD->hasAnyUseOfValue(1) &&
10449 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner77d95212012-03-27 16:27:21 +000010450 (RLD->hasAnyUseOfValue(1) &&
10451 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnerf1658062010-09-21 15:58:55 +000010452 return false;
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010453
Andrew Trickac6d9be2013-05-25 02:42:55 +000010454 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnerf1658062010-09-21 15:58:55 +000010455 LLD->getBasePtr().getValueType(),
10456 TheSelect->getOperand(0),
10457 TheSelect->getOperand(1),
10458 LLD->getBasePtr(), RLD->getBasePtr(),
10459 TheSelect->getOperand(4));
Chris Lattner18061612010-09-21 15:46:59 +000010460 }
10461
Chris Lattnerf1658062010-09-21 15:58:55 +000010462 SDValue Load;
10463 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10464 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickac6d9be2013-05-25 02:42:55 +000010465 SDLoc(TheSelect),
Richard Sandiford66589dc2013-10-28 11:17:59 +000010466 // FIXME: Discards pointer and TBAA info.
Chris Lattnerf1658062010-09-21 15:58:55 +000010467 LLD->getChain(), Addr, MachinePointerInfo(),
10468 LLD->isVolatile(), LLD->isNonTemporal(),
Pete Cooperd752e0f2011-11-08 18:42:53 +000010469 LLD->isInvariant(), LLD->getAlignment());
Chris Lattnerf1658062010-09-21 15:58:55 +000010470 } else {
Duncan Sandsb9064bb2010-11-18 21:16:28 +000010471 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10472 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickac6d9be2013-05-25 02:42:55 +000010473 SDLoc(TheSelect),
Stuart Hastingsa9011292011-02-16 16:23:55 +000010474 TheSelect->getValueType(0),
Richard Sandiford66589dc2013-10-28 11:17:59 +000010475 // FIXME: Discards pointer and TBAA info.
Chris Lattnerf1658062010-09-21 15:58:55 +000010476 LLD->getChain(), Addr, MachinePointerInfo(),
10477 LLD->getMemoryVT(), LLD->isVolatile(),
10478 LLD->isNonTemporal(), LLD->getAlignment());
Chris Lattner40c62d52005-10-18 06:04:22 +000010479 }
Chris Lattnerf1658062010-09-21 15:58:55 +000010480
10481 // Users of the select now use the result of the load.
10482 CombineTo(TheSelect, Load);
10483
10484 // Users of the old loads now use the new load's chain. We know the
10485 // old-load value is dead now.
10486 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10487 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10488 return true;
Chris Lattner40c62d52005-10-18 06:04:22 +000010489 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010490
Chris Lattner40c62d52005-10-18 06:04:22 +000010491 return false;
10492}
10493
Chris Lattner600fec32009-03-11 05:08:08 +000010494/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10495/// where 'cond' is the comparison specified by CC.
Andrew Trickac6d9be2013-05-25 02:42:55 +000010496SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman475871a2008-07-27 21:46:04 +000010497 SDValue N2, SDValue N3,
10498 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner600fec32009-03-11 05:08:08 +000010499 // (x ? y : y) -> y.
10500 if (N2 == N3) return N2;
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010501
Owen Andersone50ed302009-08-10 22:56:29 +000010502 EVT VT = N2.getValueType();
Gabor Greifba36cb52008-08-28 21:40:38 +000010503 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10504 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10505 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begemanf845b452005-10-08 00:29:44 +000010506
10507 // Determine if the condition we're dealing with is constant
Matt Arsenault225ed702013-05-18 00:21:46 +000010508 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenff97d4f2009-02-03 00:47:48 +000010509 N0, N1, CC, DL, false);
Gabor Greifba36cb52008-08-28 21:40:38 +000010510 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10511 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begemanf845b452005-10-08 00:29:44 +000010512
10513 // fold select_cc true, x, y -> x
Dan Gohman002e5d02008-03-13 22:13:53 +000010514 if (SCCC && !SCCC->isNullValue())
Nate Begemanf845b452005-10-08 00:29:44 +000010515 return N2;
10516 // fold select_cc false, x, y -> y
Dan Gohman002e5d02008-03-13 22:13:53 +000010517 if (SCCC && SCCC->isNullValue())
Nate Begemanf845b452005-10-08 00:29:44 +000010518 return N3;
Scott Michelfdc40a02009-02-17 22:15:04 +000010519
Nate Begemanf845b452005-10-08 00:29:44 +000010520 // Check to see if we can simplify the select into an fabs node
10521 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10522 // Allow either -0.0 or 0.0
Dale Johannesen87503a62007-08-25 22:10:57 +000010523 if (CFP->getValueAPF().isZero()) {
Nate Begemanf845b452005-10-08 00:29:44 +000010524 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10525 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10526 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10527 N2 == N3.getOperand(0))
Bill Wendling836ca7d2009-01-30 23:59:18 +000010528 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +000010529
Nate Begemanf845b452005-10-08 00:29:44 +000010530 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10531 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10532 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10533 N2.getOperand(0) == N3)
Bill Wendling836ca7d2009-01-30 23:59:18 +000010534 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begemanf845b452005-10-08 00:29:44 +000010535 }
10536 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010537
Chris Lattner600fec32009-03-11 05:08:08 +000010538 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10539 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10540 // in it. This is a win when the constant is not otherwise available because
10541 // it replaces two constant pool loads with one. We only do this if the FP
10542 // type is known to be legal, because if it isn't, then we are before legalize
10543 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wang0b7a7862009-03-14 00:25:19 +000010544 // messing with soft float) and if the ConstantFP is not legal, because if
10545 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner600fec32009-03-11 05:08:08 +000010546 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10547 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10548 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wang0b7a7862009-03-14 00:25:19 +000010549 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10550 TargetLowering::Legal) &&
Chris Lattner600fec32009-03-11 05:08:08 +000010551 // If both constants have multiple uses, then we won't need to do an
10552 // extra load, they are likely around in registers for other users.
10553 (TV->hasOneUse() || FV->hasOneUse())) {
10554 Constant *Elts[] = {
10555 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10556 const_cast<ConstantFP*>(TV->getConstantFPValue())
10557 };
Chris Lattnerdb125cf2011-07-18 04:54:35 +000010558 Type *FPTy = Elts[0]->getType();
Micah Villmow3574eca2012-10-08 16:38:25 +000010559 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010560
Chris Lattner600fec32009-03-11 05:08:08 +000010561 // Create a ConstantArray of the two constants.
Jay Foad26701082011-06-22 09:24:39 +000010562 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner600fec32009-03-11 05:08:08 +000010563 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10564 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1606e8e2009-03-13 07:51:59 +000010565 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner600fec32009-03-11 05:08:08 +000010566
10567 // Get the offsets to the 0 and 1 element of the array so that we can
10568 // select between them.
10569 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sands777d2302009-05-09 07:06:46 +000010570 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner600fec32009-03-11 05:08:08 +000010571 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010572
Chris Lattner600fec32009-03-11 05:08:08 +000010573 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault225ed702013-05-18 00:21:46 +000010574 getSetCCResultType(N0.getValueType()),
Chris Lattner600fec32009-03-11 05:08:08 +000010575 N0, N1, CC);
Dan Gohman7b316c92011-09-22 23:01:29 +000010576 AddToWorkList(Cond.getNode());
Matt Arsenaultb05e4772013-06-14 22:04:37 +000010577 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10578 Cond, One, Zero);
Dan Gohman7b316c92011-09-22 23:01:29 +000010579 AddToWorkList(CstOffset.getNode());
Tom Stellardedd08f72013-08-26 15:06:10 +000010580 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner600fec32009-03-11 05:08:08 +000010581 CstOffset);
Dan Gohman7b316c92011-09-22 23:01:29 +000010582 AddToWorkList(CPIdx.getNode());
Chris Lattner600fec32009-03-11 05:08:08 +000010583 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattner85ca1062010-09-21 07:32:19 +000010584 MachinePointerInfo::getConstantPool(), false,
Pete Cooperd752e0f2011-11-08 18:42:53 +000010585 false, false, Alignment);
Chris Lattner600fec32009-03-11 05:08:08 +000010586
10587 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010588 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010589
Nate Begemanf845b452005-10-08 00:29:44 +000010590 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling836ca7d2009-01-30 23:59:18 +000010591 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnere3152e52006-09-20 06:41:35 +000010592 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohman002e5d02008-03-13 22:13:53 +000010593 (N1C->isNullValue() || // (a < 0) ? b : 0
10594 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Andersone50ed302009-08-10 22:56:29 +000010595 EVT XType = N0.getValueType();
10596 EVT AType = N2.getValueType();
Duncan Sands8e4eb092008-06-08 20:54:56 +000010597 if (XType.bitsGE(AType)) {
Sylvestre Ledru94c22712012-09-27 10:14:43 +000010598 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman07ed4172005-10-10 21:26:48 +000010599 // single-bit constant.
Dan Gohman002e5d02008-03-13 22:13:53 +000010600 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10601 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands83ec4b62008-06-06 12:08:01 +000010602 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Anderson95771af2011-02-25 21:41:48 +000010603 SDValue ShCt = DAG.getConstant(ShCtV,
10604 getShiftAmountTy(N0.getValueType()));
Andrew Trickac6d9be2013-05-25 02:42:55 +000010605 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling836ca7d2009-01-30 23:59:18 +000010606 XType, N0, ShCt);
Gabor Greifba36cb52008-08-28 21:40:38 +000010607 AddToWorkList(Shift.getNode());
Bill Wendling836ca7d2009-01-30 23:59:18 +000010608
Duncan Sands8e4eb092008-06-08 20:54:56 +000010609 if (XType.bitsGT(AType)) {
Bill Wendling9729c5a2009-01-31 03:12:48 +000010610 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greifba36cb52008-08-28 21:40:38 +000010611 AddToWorkList(Shift.getNode());
Nate Begemanf845b452005-10-08 00:29:44 +000010612 }
Bill Wendling836ca7d2009-01-30 23:59:18 +000010613
10614 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begemanf845b452005-10-08 00:29:44 +000010615 }
Bill Wendling836ca7d2009-01-30 23:59:18 +000010616
Andrew Trickac6d9be2013-05-25 02:42:55 +000010617 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling836ca7d2009-01-30 23:59:18 +000010618 XType, N0,
10619 DAG.getConstant(XType.getSizeInBits()-1,
Owen Anderson95771af2011-02-25 21:41:48 +000010620 getShiftAmountTy(N0.getValueType())));
Gabor Greifba36cb52008-08-28 21:40:38 +000010621 AddToWorkList(Shift.getNode());
Bill Wendling836ca7d2009-01-30 23:59:18 +000010622
Duncan Sands8e4eb092008-06-08 20:54:56 +000010623 if (XType.bitsGT(AType)) {
Bill Wendling9729c5a2009-01-31 03:12:48 +000010624 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greifba36cb52008-08-28 21:40:38 +000010625 AddToWorkList(Shift.getNode());
Nate Begemanf845b452005-10-08 00:29:44 +000010626 }
Bill Wendling836ca7d2009-01-30 23:59:18 +000010627
10628 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begemanf845b452005-10-08 00:29:44 +000010629 }
10630 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010631
Owen Andersoned1088a2010-09-22 22:58:22 +000010632 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10633 // where y is has a single bit set.
10634 // A plaintext description would be, we can turn the SELECT_CC into an AND
10635 // when the condition can be materialized as an all-ones register. Any
10636 // single bit-test can be materialized as an all-ones register with
10637 // shift-left and shift-right-arith.
10638 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10639 N0->getValueType(0) == VT &&
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010640 N1C && N1C->isNullValue() &&
Owen Andersoned1088a2010-09-22 22:58:22 +000010641 N2C && N2C->isNullValue()) {
10642 SDValue AndLHS = N0->getOperand(0);
10643 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10644 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10645 // Shift the tested bit over the sign bit.
10646 APInt AndMask = ConstAndRHS->getAPIntValue();
10647 SDValue ShlAmt =
Owen Anderson95771af2011-02-25 21:41:48 +000010648 DAG.getConstant(AndMask.countLeadingZeros(),
10649 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickac6d9be2013-05-25 02:42:55 +000010650 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010651
Owen Andersoned1088a2010-09-22 22:58:22 +000010652 // Now arithmetic right shift it all the way over, so the result is either
10653 // all-ones, or zero.
10654 SDValue ShrAmt =
Owen Anderson95771af2011-02-25 21:41:48 +000010655 DAG.getConstant(AndMask.getBitWidth()-1,
10656 getShiftAmountTy(Shl.getValueType()));
Andrew Trickac6d9be2013-05-25 02:42:55 +000010657 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010658
Owen Andersoned1088a2010-09-22 22:58:22 +000010659 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10660 }
10661 }
10662
Nate Begeman07ed4172005-10-10 21:26:48 +000010663 // fold select C, 16, 0 -> shl C, 4
Dan Gohman002e5d02008-03-13 22:13:53 +000010664 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Duncan Sands28b77e92011-09-06 19:07:46 +000010665 TLI.getBooleanContents(N0.getValueType().isVector()) ==
10666 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelfdc40a02009-02-17 22:15:04 +000010667
Chris Lattner1eba01e2007-04-11 06:50:51 +000010668 // If the caller doesn't want us to simplify this into a zext of a compare,
10669 // don't do it.
Dan Gohman002e5d02008-03-13 22:13:53 +000010670 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman475871a2008-07-27 21:46:04 +000010671 return SDValue();
Scott Michelfdc40a02009-02-17 22:15:04 +000010672
Nate Begeman07ed4172005-10-10 21:26:48 +000010673 // Get a SetCC of the condition
Owen Andersonefcc1ae2012-11-03 00:17:26 +000010674 // NOTE: Don't create a SETCC if it's not legal on this target.
10675 if (!LegalOperations ||
10676 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault225ed702013-05-18 00:21:46 +000010677 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Andersonefcc1ae2012-11-03 00:17:26 +000010678 SDValue Temp, SCC;
10679 // cast from setcc result type to select result type
10680 if (LegalTypes) {
Matt Arsenault225ed702013-05-18 00:21:46 +000010681 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Andersonefcc1ae2012-11-03 00:17:26 +000010682 N0, N1, CC);
10683 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickac6d9be2013-05-25 02:42:55 +000010684 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Andersonefcc1ae2012-11-03 00:17:26 +000010685 N2.getValueType());
10686 else
Andrew Trickac6d9be2013-05-25 02:42:55 +000010687 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Andersonefcc1ae2012-11-03 00:17:26 +000010688 N2.getValueType(), SCC);
10689 } else {
Andrew Trickac6d9be2013-05-25 02:42:55 +000010690 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10691 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling836ca7d2009-01-30 23:59:18 +000010692 N2.getValueType(), SCC);
Owen Andersonefcc1ae2012-11-03 00:17:26 +000010693 }
10694
10695 AddToWorkList(SCC.getNode());
10696 AddToWorkList(Temp.getNode());
10697
10698 if (N2C->getAPIntValue() == 1)
10699 return Temp;
10700
10701 // shl setcc result by log2 n2c
Jack Carteradbd3ae2013-10-17 01:34:33 +000010702 return DAG.getNode(
10703 ISD::SHL, DL, N2.getValueType(), Temp,
10704 DAG.getConstant(N2C->getAPIntValue().logBase2(),
10705 getShiftAmountTy(Temp.getValueType())));
Nate Begemanb0d04a72006-02-18 02:40:58 +000010706 }
Nate Begeman07ed4172005-10-10 21:26:48 +000010707 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010708
Nate Begemanf845b452005-10-08 00:29:44 +000010709 // Check to see if this is the equivalent of setcc
10710 // FIXME: Turn all of these into setcc if setcc if setcc is legal
10711 // otherwise, go ahead with the folds.
Dan Gohman002e5d02008-03-13 22:13:53 +000010712 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Andersone50ed302009-08-10 22:56:29 +000010713 EVT XType = N0.getValueType();
Duncan Sands25cf2272008-11-24 14:53:14 +000010714 if (!LegalOperations ||
Matt Arsenault225ed702013-05-18 00:21:46 +000010715 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10716 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begemanf845b452005-10-08 00:29:44 +000010717 if (Res.getValueType() != VT)
Bill Wendling836ca7d2009-01-30 23:59:18 +000010718 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begemanf845b452005-10-08 00:29:44 +000010719 return Res;
10720 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010721
Bill Wendling836ca7d2009-01-30 23:59:18 +000010722 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelfdc40a02009-02-17 22:15:04 +000010723 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sands25cf2272008-11-24 14:53:14 +000010724 (!LegalOperations ||
Duncan Sands184a8762008-06-14 17:48:34 +000010725 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickac6d9be2013-05-25 02:42:55 +000010726 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +000010727 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands83ec4b62008-06-06 12:08:01 +000010728 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Anderson95771af2011-02-25 21:41:48 +000010729 getShiftAmountTy(Ctlz.getValueType())));
Nate Begemanf845b452005-10-08 00:29:44 +000010730 }
Bill Wendling836ca7d2009-01-30 23:59:18 +000010731 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelfdc40a02009-02-17 22:15:04 +000010732 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickac6d9be2013-05-25 02:42:55 +000010733 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling836ca7d2009-01-30 23:59:18 +000010734 XType, DAG.getConstant(0, XType), N0);
Andrew Trickac6d9be2013-05-25 02:42:55 +000010735 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling836ca7d2009-01-30 23:59:18 +000010736 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlingfc4b6772009-02-01 11:19:36 +000010737 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands83ec4b62008-06-06 12:08:01 +000010738 DAG.getConstant(XType.getSizeInBits()-1,
Owen Anderson95771af2011-02-25 21:41:48 +000010739 getShiftAmountTy(XType)));
Nate Begemanf845b452005-10-08 00:29:44 +000010740 }
Bill Wendling836ca7d2009-01-30 23:59:18 +000010741 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begemanf845b452005-10-08 00:29:44 +000010742 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickac6d9be2013-05-25 02:42:55 +000010743 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling836ca7d2009-01-30 23:59:18 +000010744 DAG.getConstant(XType.getSizeInBits()-1,
Owen Anderson95771af2011-02-25 21:41:48 +000010745 getShiftAmountTy(N0.getValueType())));
Bill Wendling836ca7d2009-01-30 23:59:18 +000010746 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begemanf845b452005-10-08 00:29:44 +000010747 }
10748 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010749
Benjamin Kramercde51102010-07-08 12:09:56 +000010750 // Check to see if this is an integer abs.
10751 // select_cc setg[te] X, 0, X, -X ->
10752 // select_cc setgt X, -1, X, -X ->
10753 // select_cc setl[te] X, 0, -X, X ->
10754 // select_cc setlt X, 1, -X, X ->
Nate Begemanf845b452005-10-08 00:29:44 +000010755 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramercde51102010-07-08 12:09:56 +000010756 if (N1C) {
10757 ConstantSDNode *SubC = NULL;
10758 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10759 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10760 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10761 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10762 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10763 (N1C->isOne() && CC == ISD::SETLT)) &&
10764 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10765 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10766
Owen Andersone50ed302009-08-10 22:56:29 +000010767 EVT XType = N0.getValueType();
Benjamin Kramercde51102010-07-08 12:09:56 +000010768 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +000010769 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramercde51102010-07-08 12:09:56 +000010770 N0,
10771 DAG.getConstant(XType.getSizeInBits()-1,
Owen Anderson95771af2011-02-25 21:41:48 +000010772 getShiftAmountTy(N0.getValueType())));
Andrew Trickac6d9be2013-05-25 02:42:55 +000010773 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramercde51102010-07-08 12:09:56 +000010774 XType, N0, Shift);
10775 AddToWorkList(Shift.getNode());
10776 AddToWorkList(Add.getNode());
10777 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begemanf845b452005-10-08 00:29:44 +000010778 }
10779 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010780
Dan Gohman475871a2008-07-27 21:46:04 +000010781 return SDValue();
Nate Begeman44728a72005-09-19 22:34:01 +000010782}
10783
Evan Chengfa1eb272007-02-08 22:13:59 +000010784/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
Owen Andersone50ed302009-08-10 22:56:29 +000010785SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman475871a2008-07-27 21:46:04 +000010786 SDValue N1, ISD::CondCode Cond,
Andrew Trickac6d9be2013-05-25 02:42:55 +000010787 SDLoc DL, bool foldBooleans) {
Scott Michelfdc40a02009-02-17 22:15:04 +000010788 TargetLowering::DAGCombinerInfo
Nadav Rotem444b4bf2012-12-27 06:47:41 +000010789 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenff97d4f2009-02-03 00:47:48 +000010790 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman452d7be2005-09-16 00:54:12 +000010791}
10792
Nate Begeman69575232005-10-20 02:15:44 +000010793/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10794/// return a DAG expression to select that will generate the same value by
10795/// multiplying by a magic number. See:
10796/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman475871a2008-07-27 21:46:04 +000010797SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Andrew Lenharth232c9102006-06-12 16:07:18 +000010798 std::vector<SDNode*> Built;
Richard Osborne19a4daf2011-11-07 17:09:05 +000010799 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
Andrew Lenharthdae9cbe2006-05-16 17:42:15 +000010800
Andrew Lenharth232c9102006-06-12 16:07:18 +000010801 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
Andrew Lenharthdae9cbe2006-05-16 17:42:15 +000010802 ii != ee; ++ii)
10803 AddToWorkList(*ii);
10804 return S;
Nate Begeman69575232005-10-20 02:15:44 +000010805}
10806
10807/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10808/// return a DAG expression to select that will generate the same value by
10809/// multiplying by a magic number. See:
10810/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman475871a2008-07-27 21:46:04 +000010811SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Andrew Lenharth232c9102006-06-12 16:07:18 +000010812 std::vector<SDNode*> Built;
Richard Osborne19a4daf2011-11-07 17:09:05 +000010813 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
Nate Begeman69575232005-10-20 02:15:44 +000010814
Andrew Lenharth232c9102006-06-12 16:07:18 +000010815 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
Andrew Lenharthdae9cbe2006-05-16 17:42:15 +000010816 ii != ee; ++ii)
10817 AddToWorkList(*ii);
10818 return S;
Nate Begeman69575232005-10-20 02:15:44 +000010819}
10820
Nate Begemancc66cdd2009-09-25 06:05:26 +000010821/// FindBaseOffset - Return true if base is a frame index, which is known not
Eric Christopher503a64d2010-12-09 04:48:06 +000010822// to alias with anything but itself. Provides base object and offset as
10823// results.
Nate Begemancc66cdd2009-09-25 06:05:26 +000010824static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky2943e372012-09-05 22:15:49 +000010825 const GlobalValue *&GV, const void *&CV) {
Jim Laskey71382342006-10-07 23:37:56 +000010826 // Assume it is a primitive operation.
Nate Begemancc66cdd2009-09-25 06:05:26 +000010827 Base = Ptr; Offset = 0; GV = 0; CV = 0;
Scott Michelfdc40a02009-02-17 22:15:04 +000010828
Jim Laskey71382342006-10-07 23:37:56 +000010829 // If it's an adding a simple constant then integrate the offset.
10830 if (Base.getOpcode() == ISD::ADD) {
10831 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10832 Base = Base.getOperand(0);
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +000010833 Offset += C->getZExtValue();
Jim Laskey71382342006-10-07 23:37:56 +000010834 }
10835 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010836
Nate Begemancc66cdd2009-09-25 06:05:26 +000010837 // Return the underlying GlobalValue, and update the Offset. Return false
10838 // for GlobalAddressSDNode since the same GlobalAddress may be represented
10839 // by multiple nodes with different offsets.
10840 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10841 GV = G->getGlobal();
10842 Offset += G->getOffset();
10843 return false;
10844 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010845
Nate Begemancc66cdd2009-09-25 06:05:26 +000010846 // Return the underlying Constant value, and update the Offset. Return false
10847 // for ConstantSDNodes since the same constant pool entry may be represented
10848 // by multiple nodes with different offsets.
10849 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky2943e372012-09-05 22:15:49 +000010850 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10851 : (const void *)C->getConstVal();
Nate Begemancc66cdd2009-09-25 06:05:26 +000010852 Offset += C->getOffset();
10853 return false;
10854 }
Jim Laskey71382342006-10-07 23:37:56 +000010855 // If it's any of the following then it can't alias with anything but itself.
Nate Begemancc66cdd2009-09-25 06:05:26 +000010856 return isa<FrameIndexSDNode>(Base);
Jim Laskey71382342006-10-07 23:37:56 +000010857}
10858
10859/// isAlias - Return true if there is any possibility that the two addresses
10860/// overlap.
Richard Sandiforda7be36c2013-10-28 12:00:00 +000010861bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
Jim Laskey096c22e2006-10-18 12:29:57 +000010862 const Value *SrcValue1, int SrcValueOffset1,
Nate Begemanb6aef5c2009-09-15 00:18:30 +000010863 unsigned SrcValueAlign1,
Dan Gohmanf96e4bd2010-10-20 00:31:05 +000010864 const MDNode *TBAAInfo1,
Richard Sandiforda7be36c2013-10-28 12:00:00 +000010865 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
Nate Begemanb6aef5c2009-09-15 00:18:30 +000010866 const Value *SrcValue2, int SrcValueOffset2,
Dan Gohmanf96e4bd2010-10-20 00:31:05 +000010867 unsigned SrcValueAlign2,
10868 const MDNode *TBAAInfo2) const {
Jim Laskey71382342006-10-07 23:37:56 +000010869 // If they are the same then they must be aliases.
10870 if (Ptr1 == Ptr2) return true;
Scott Michelfdc40a02009-02-17 22:15:04 +000010871
Richard Sandiforda7be36c2013-10-28 12:00:00 +000010872 // If they are both volatile then they cannot be reordered.
10873 if (IsVolatile1 && IsVolatile2) return true;
10874
Jim Laskey71382342006-10-07 23:37:56 +000010875 // Gather base node and offset information.
Dan Gohman475871a2008-07-27 21:46:04 +000010876 SDValue Base1, Base2;
Jim Laskey71382342006-10-07 23:37:56 +000010877 int64_t Offset1, Offset2;
Dan Gohman46510a72010-04-15 01:51:59 +000010878 const GlobalValue *GV1, *GV2;
Roman Divacky2943e372012-09-05 22:15:49 +000010879 const void *CV1, *CV2;
Nate Begemancc66cdd2009-09-25 06:05:26 +000010880 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
10881 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
Scott Michelfdc40a02009-02-17 22:15:04 +000010882
Nate Begemancc66cdd2009-09-25 06:05:26 +000010883 // If they have a same base address then check to see if they overlap.
10884 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Bill Wendling836ca7d2009-01-30 23:59:18 +000010885 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
Scott Michelfdc40a02009-02-17 22:15:04 +000010886
Owen Anderson4a9f1502010-09-20 20:39:59 +000010887 // It is possible for different frame indices to alias each other, mostly
10888 // when tail call optimization reuses return address slots for arguments.
10889 // To catch this case, look up the actual index of frame indices to compute
10890 // the real alias relationship.
10891 if (isFrameIndex1 && isFrameIndex2) {
10892 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10893 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
10894 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
10895 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10896 }
10897
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010898 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson4a9f1502010-09-20 20:39:59 +000010899 // we know they cannot alias.
Nate Begemancc66cdd2009-09-25 06:05:26 +000010900 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
10901 return false;
Jim Laskey096c22e2006-10-18 12:29:57 +000010902
Nate Begemanb6aef5c2009-09-15 00:18:30 +000010903 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
10904 // compared to the size and offset of the access, we may be able to prove they
10905 // do not alias. This check is conservative for now to catch cases created by
10906 // splitting vector types.
10907 if ((SrcValueAlign1 == SrcValueAlign2) &&
10908 (SrcValueOffset1 != SrcValueOffset2) &&
10909 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
10910 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
10911 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010912
Nate Begemanb6aef5c2009-09-15 00:18:30 +000010913 // There is no overlap between these relatively aligned accesses of similar
10914 // size, return no alias.
10915 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
10916 return false;
10917 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010918
Hal Finkel253acef2013-08-29 03:29:55 +000010919 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
10920 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel77364b72013-09-15 02:19:49 +000010921 if (UseAA && SrcValue1 && SrcValue2) {
Jim Laskey07a27092006-10-18 19:08:31 +000010922 // Use alias analysis information.
Dan Gohmane9c8fa02007-08-27 16:32:11 +000010923 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
10924 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
10925 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
Scott Michelfdc40a02009-02-17 22:15:04 +000010926 AliasAnalysis::AliasResult AAResult =
Dan Gohmanf96e4bd2010-10-20 00:31:05 +000010927 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
10928 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
Jim Laskey07a27092006-10-18 19:08:31 +000010929 if (AAResult == AliasAnalysis::NoAlias)
10930 return false;
10931 }
Jim Laskey096c22e2006-10-18 12:29:57 +000010932
10933 // Otherwise we have to assume they alias.
10934 return true;
Jim Laskey71382342006-10-07 23:37:56 +000010935}
10936
Nadav Rotem90e11dc2012-11-29 00:00:08 +000010937bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
10938 SDValue Ptr0, Ptr1;
10939 int64_t Size0, Size1;
Richard Sandiforda7be36c2013-10-28 12:00:00 +000010940 bool IsVolatile0, IsVolatile1;
Nadav Rotem90e11dc2012-11-29 00:00:08 +000010941 const Value *SrcValue0, *SrcValue1;
10942 int SrcValueOffset0, SrcValueOffset1;
10943 unsigned SrcValueAlign0, SrcValueAlign1;
10944 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
Richard Sandiforda7be36c2013-10-28 12:00:00 +000010945 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
Nadav Rotem90e11dc2012-11-29 00:00:08 +000010946 SrcValueAlign0, SrcTBAAInfo0);
Richard Sandiforda7be36c2013-10-28 12:00:00 +000010947 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
Nadav Rotem90e11dc2012-11-29 00:00:08 +000010948 SrcValueAlign1, SrcTBAAInfo1);
Richard Sandiforda7be36c2013-10-28 12:00:00 +000010949 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
Nadav Rotemdde785c2012-12-06 17:34:13 +000010950 SrcValueAlign0, SrcTBAAInfo0,
Richard Sandiforda7be36c2013-10-28 12:00:00 +000010951 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
Nadav Rotemdde785c2012-12-06 17:34:13 +000010952 SrcValueAlign1, SrcTBAAInfo1);
Nadav Rotem90e11dc2012-11-29 00:00:08 +000010953}
10954
Jim Laskey71382342006-10-07 23:37:56 +000010955/// FindAliasInfo - Extracts the relevant alias information from the memory
Richard Sandiforda7be36c2013-10-28 12:00:00 +000010956/// node. Returns true if the operand was a nonvolatile load.
Jim Laskey7ca56af2006-10-11 13:47:09 +000010957bool DAGCombiner::FindAliasInfo(SDNode *N,
Richard Sandiforda7be36c2013-10-28 12:00:00 +000010958 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
Benjamin Kramerae4746b2012-01-15 11:50:43 +000010959 const Value *&SrcValue,
10960 int &SrcValueOffset,
10961 unsigned &SrcValueAlign,
10962 const MDNode *&TBAAInfo) const {
10963 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
10964
10965 Ptr = LS->getBasePtr();
10966 Size = LS->getMemoryVT().getSizeInBits() >> 3;
Richard Sandiforda7be36c2013-10-28 12:00:00 +000010967 IsVolatile = LS->isVolatile();
Benjamin Kramerae4746b2012-01-15 11:50:43 +000010968 SrcValue = LS->getSrcValue();
10969 SrcValueOffset = LS->getSrcValueOffset();
10970 SrcValueAlign = LS->getOriginalAlignment();
10971 TBAAInfo = LS->getTBAAInfo();
Richard Sandiforda7be36c2013-10-28 12:00:00 +000010972 return isa<LoadSDNode>(LS) && !IsVolatile;
Jim Laskey71382342006-10-07 23:37:56 +000010973}
10974
Jim Laskey6ff23e52006-10-04 16:53:27 +000010975/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
10976/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman475871a2008-07-27 21:46:04 +000010977void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Toppera0ec3f92013-07-14 04:42:23 +000010978 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman475871a2008-07-27 21:46:04 +000010979 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begemanb6aef5c2009-09-15 00:18:30 +000010980 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelfdc40a02009-02-17 22:15:04 +000010981
Jim Laskey279f0532006-09-25 16:29:54 +000010982 // Get alias information for node.
Dan Gohman475871a2008-07-27 21:46:04 +000010983 SDValue Ptr;
Nate Begemanb6aef5c2009-09-15 00:18:30 +000010984 int64_t Size;
Richard Sandiforda7be36c2013-10-28 12:00:00 +000010985 bool IsVolatile;
Nate Begemanb6aef5c2009-09-15 00:18:30 +000010986 const Value *SrcValue;
10987 int SrcValueOffset;
10988 unsigned SrcValueAlign;
Dan Gohmanf96e4bd2010-10-20 00:31:05 +000010989 const MDNode *SrcTBAAInfo;
Richard Sandiforda7be36c2013-10-28 12:00:00 +000010990 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
10991 SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
Jim Laskey279f0532006-09-25 16:29:54 +000010992
Jim Laskey6ff23e52006-10-04 16:53:27 +000010993 // Starting off.
Jim Laskeybc588b82006-10-05 15:07:25 +000010994 Chains.push_back(OriginalChain);
Nate Begeman677c89d2009-10-12 05:53:58 +000010995 unsigned Depth = 0;
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010996
Jim Laskeybc588b82006-10-05 15:07:25 +000010997 // Look at each chain and determine if it is an alias. If so, add it to the
10998 // aliases list. If not, then continue up the chain looking for the next
Scott Michelfdc40a02009-02-17 22:15:04 +000010999 // candidate.
Jim Laskeybc588b82006-10-05 15:07:25 +000011000 while (!Chains.empty()) {
Dan Gohman475871a2008-07-27 21:46:04 +000011001 SDValue Chain = Chains.back();
Jim Laskeybc588b82006-10-05 15:07:25 +000011002 Chains.pop_back();
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011003
11004 // For TokenFactor nodes, look at each operand and only continue up the
11005 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begeman677c89d2009-10-12 05:53:58 +000011006 // find more and revert to original chain since the xform is unlikely to be
11007 // profitable.
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011008 //
11009 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begeman677c89d2009-10-12 05:53:58 +000011010 // chain we found before we hit a tokenfactor rather than the original
11011 // chain.
11012 if (Depth > 6 || Aliases.size() == 2) {
11013 Aliases.clear();
11014 Aliases.push_back(OriginalChain);
11015 break;
11016 }
Scott Michelfdc40a02009-02-17 22:15:04 +000011017
Nate Begemanb6aef5c2009-09-15 00:18:30 +000011018 // Don't bother if we've been before.
11019 if (!Visited.insert(Chain.getNode()))
11020 continue;
Scott Michelfdc40a02009-02-17 22:15:04 +000011021
Jim Laskeybc588b82006-10-05 15:07:25 +000011022 switch (Chain.getOpcode()) {
11023 case ISD::EntryToken:
11024 // Entry token is ideal chain operand, but handled in FindBetterChain.
11025 break;
Scott Michelfdc40a02009-02-17 22:15:04 +000011026
Jim Laskeybc588b82006-10-05 15:07:25 +000011027 case ISD::LOAD:
11028 case ISD::STORE: {
11029 // Get alias information for Chain.
Dan Gohman475871a2008-07-27 21:46:04 +000011030 SDValue OpPtr;
Nate Begemanb6aef5c2009-09-15 00:18:30 +000011031 int64_t OpSize;
Richard Sandiforda7be36c2013-10-28 12:00:00 +000011032 bool OpIsVolatile;
Nate Begemanb6aef5c2009-09-15 00:18:30 +000011033 const Value *OpSrcValue;
11034 int OpSrcValueOffset;
11035 unsigned OpSrcValueAlign;
Dan Gohmanf96e4bd2010-10-20 00:31:05 +000011036 const MDNode *OpSrcTBAAInfo;
Gabor Greifba36cb52008-08-28 21:40:38 +000011037 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
Richard Sandiforda7be36c2013-10-28 12:00:00 +000011038 OpIsVolatile, OpSrcValue, OpSrcValueOffset,
Dan Gohmanf96e4bd2010-10-20 00:31:05 +000011039 OpSrcValueAlign,
11040 OpSrcTBAAInfo);
Scott Michelfdc40a02009-02-17 22:15:04 +000011041
Jim Laskeybc588b82006-10-05 15:07:25 +000011042 // If chain is alias then stop here.
11043 if (!(IsLoad && IsOpLoad) &&
Richard Sandiforda7be36c2013-10-28 12:00:00 +000011044 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11045 SrcValueAlign, SrcTBAAInfo,
11046 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
Dan Gohmanf96e4bd2010-10-20 00:31:05 +000011047 OpSrcValueAlign, OpSrcTBAAInfo)) {
Jim Laskeybc588b82006-10-05 15:07:25 +000011048 Aliases.push_back(Chain);
11049 } else {
11050 // Look further up the chain.
Scott Michelfdc40a02009-02-17 22:15:04 +000011051 Chains.push_back(Chain.getOperand(0));
Nate Begeman677c89d2009-10-12 05:53:58 +000011052 ++Depth;
Jim Laskey279f0532006-09-25 16:29:54 +000011053 }
Jim Laskeybc588b82006-10-05 15:07:25 +000011054 break;
11055 }
Scott Michelfdc40a02009-02-17 22:15:04 +000011056
Jim Laskeybc588b82006-10-05 15:07:25 +000011057 case ISD::TokenFactor:
Nate Begemanb6aef5c2009-09-15 00:18:30 +000011058 // We have to check each of the operands of the token factor for "small"
11059 // token factors, so we queue them up. Adding the operands to the queue
11060 // (stack) in reverse order maintains the original order and increases the
11061 // likelihood that getNode will find a matching token factor (CSE.)
11062 if (Chain.getNumOperands() > 16) {
11063 Aliases.push_back(Chain);
11064 break;
11065 }
Jim Laskeybc588b82006-10-05 15:07:25 +000011066 for (unsigned n = Chain.getNumOperands(); n;)
11067 Chains.push_back(Chain.getOperand(--n));
Nate Begeman677c89d2009-10-12 05:53:58 +000011068 ++Depth;
Jim Laskeybc588b82006-10-05 15:07:25 +000011069 break;
Scott Michelfdc40a02009-02-17 22:15:04 +000011070
Jim Laskeybc588b82006-10-05 15:07:25 +000011071 default:
11072 // For all other instructions we will just have to take what we can get.
11073 Aliases.push_back(Chain);
11074 break;
Jim Laskey279f0532006-09-25 16:29:54 +000011075 }
11076 }
Jim Laskey6ff23e52006-10-04 16:53:27 +000011077}
11078
11079/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11080/// for a better chain (aliasing node.)
Dan Gohman475871a2008-07-27 21:46:04 +000011081SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11082 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelfdc40a02009-02-17 22:15:04 +000011083
Jim Laskey6ff23e52006-10-04 16:53:27 +000011084 // Accumulate all the aliases to this node.
11085 GatherAllAliases(N, OldChain, Aliases);
Scott Michelfdc40a02009-02-17 22:15:04 +000011086
Dan Gohman71dc7c92011-05-17 22:20:36 +000011087 // If no operands then chain to entry token.
11088 if (Aliases.size() == 0)
Jim Laskey6ff23e52006-10-04 16:53:27 +000011089 return DAG.getEntryNode();
Dan Gohman71dc7c92011-05-17 22:20:36 +000011090
11091 // If a single operand then chain to it. We don't need to revisit it.
11092 if (Aliases.size() == 1)
Jim Laskey6ff23e52006-10-04 16:53:27 +000011093 return Aliases[0];
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011094
Jim Laskey6ff23e52006-10-04 16:53:27 +000011095 // Construct a custom tailored token factor.
Andrew Trickac6d9be2013-05-25 02:42:55 +000011096 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Nate Begemanb6aef5c2009-09-15 00:18:30 +000011097 &Aliases[0], Aliases.size());
Jim Laskey279f0532006-09-25 16:29:54 +000011098}
11099
Nate Begeman1d4d4142005-09-01 00:19:25 +000011100// SelectionDAG::Combine - This is the entry point for the file.
11101//
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +000011102void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling98a366d2009-04-29 23:29:43 +000011103 CodeGenOpt::Level OptLevel) {
Nate Begeman1d4d4142005-09-01 00:19:25 +000011104 /// run - This is the main entry point to this class.
11105 ///
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +000011106 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman1d4d4142005-09-01 00:19:25 +000011107}