blob: 0163b2e2bdc46ee56598ba58ccdc723b775e7b7c [file] [log] [blame]
Jia Liub22310f2012-02-18 12:03:15 +00001//===-- HexagonISelDAGToDAG.cpp - A dag to dag inst selector for Hexagon --===//
Tony Linthicum1213a7a2011-12-12 21:14:40 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines an instruction selector for the Hexagon target.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruthed0881b2012-12-03 16:50:05 +000014#include "Hexagon.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000015#include "HexagonISelLowering.h"
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000016#include "HexagonMachineFunctionInfo.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000017#include "HexagonTargetMachine.h"
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000018#include "llvm/CodeGen/FunctionLoweringInfo.h"
19#include "llvm/CodeGen/MachineInstrBuilder.h"
Jyotsna Vermad9225242013-02-13 21:38:46 +000020#include "llvm/CodeGen/SelectionDAGISel.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000021#include "llvm/IR/Intrinsics.h"
Jyotsna Vermad9225242013-02-13 21:38:46 +000022#include "llvm/Support/CommandLine.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000023#include "llvm/Support/Debug.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000024using namespace llvm;
25
Chandler Carruth84e68b22014-04-22 02:41:26 +000026#define DEBUG_TYPE "hexagon-isel"
27
Jyotsna Vermad9225242013-02-13 21:38:46 +000028static
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +000029cl::opt<bool>
30EnableAddressRebalancing("isel-rebalance-addr", cl::Hidden, cl::init(true),
31 cl::desc("Rebalance address calculation trees to improve "
32 "instruction selection"));
33
34// Rebalance only if this allows e.g. combining a GA with an offset or
35// factoring out a shift.
36static
37cl::opt<bool>
38RebalanceOnlyForOptimizations("rebalance-only-opt", cl::Hidden, cl::init(false),
39 cl::desc("Rebalance address tree only if this allows optimizations"));
40
41static
42cl::opt<bool>
43RebalanceOnlyImbalancedTrees("rebalance-only-imbal", cl::Hidden,
44 cl::init(false), cl::desc("Rebalance address tree only if it is imbalanced"));
45
Tony Linthicum1213a7a2011-12-12 21:14:40 +000046//===----------------------------------------------------------------------===//
47// Instruction Selector Implementation
48//===----------------------------------------------------------------------===//
49
50//===--------------------------------------------------------------------===//
51/// HexagonDAGToDAGISel - Hexagon specific code to select Hexagon machine
52/// instructions for SelectionDAG operations.
53///
54namespace {
55class HexagonDAGToDAGISel : public SelectionDAGISel {
Eric Christopher23a7d1e2015-03-21 03:12:59 +000056 const HexagonSubtarget *HST;
Krzysztof Parzyszek08ff8882015-11-26 18:38:27 +000057 const HexagonInstrInfo *HII;
58 const HexagonRegisterInfo *HRI;
Tony Linthicum1213a7a2011-12-12 21:14:40 +000059public:
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +000060 explicit HexagonDAGToDAGISel(HexagonTargetMachine &tm,
Jyotsna Vermad9225242013-02-13 21:38:46 +000061 CodeGenOpt::Level OptLevel)
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +000062 : SelectionDAGISel(tm, OptLevel), HST(nullptr), HII(nullptr),
Chandler Carruth9ac86ef2016-06-03 10:13:31 +000063 HRI(nullptr) {}
Eric Christopher23a7d1e2015-03-21 03:12:59 +000064
65 bool runOnMachineFunction(MachineFunction &MF) override {
66 // Reset the subtarget each time through.
67 HST = &MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek08ff8882015-11-26 18:38:27 +000068 HII = HST->getInstrInfo();
69 HRI = HST->getRegisterInfo();
Eric Christopher23a7d1e2015-03-21 03:12:59 +000070 SelectionDAGISel::runOnMachineFunction(MF);
71 return true;
72 }
73
Krzysztof Parzyszekef580172017-05-30 17:47:51 +000074 bool ComplexPatternFuncMutatesDAG() const override {
75 return true;
76 }
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +000077 void PreprocessISelDAG() override;
78 void EmitFunctionEntryCode() override;
Tony Linthicum1213a7a2011-12-12 21:14:40 +000079
Justin Bognerec37a022016-05-12 21:46:18 +000080 void Select(SDNode *N) override;
Tony Linthicum1213a7a2011-12-12 21:14:40 +000081
82 // Complex Pattern Selectors.
Colin LeMahieu987b0942015-02-04 20:38:01 +000083 inline bool SelectAddrGA(SDValue &N, SDValue &R);
Colin LeMahieu51491352015-02-04 22:36:28 +000084 inline bool SelectAddrGP(SDValue &N, SDValue &R);
Colin LeMahieu987b0942015-02-04 20:38:01 +000085 bool SelectGlobalAddress(SDValue &N, SDValue &R, bool UseGP);
Colin LeMahieuc7522f32015-01-14 23:07:36 +000086 bool SelectAddrFI(SDValue &N, SDValue &R);
Krzysztof Parzyszekef580172017-05-30 17:47:51 +000087 bool DetectUseSxtw(SDValue &N, SDValue &R);
Colin LeMahieuc7522f32015-01-14 23:07:36 +000088
Mehdi Amini117296c2016-10-01 02:56:57 +000089 StringRef getPassName() const override {
Tony Linthicum1213a7a2011-12-12 21:14:40 +000090 return "Hexagon DAG->DAG Pattern Instruction Selection";
91 }
92
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +000093 // Generate a machine instruction node corresponding to the circ/brev
94 // load intrinsic.
95 MachineSDNode *LoadInstrForLoadIntrinsic(SDNode *IntN);
96 // Given the circ/brev load intrinsic and the already generated machine
97 // instruction, generate the appropriate store (that is a part of the
98 // intrinsic's functionality).
99 SDNode *StoreInstrForLoadIntrinsic(MachineSDNode *LoadN, SDNode *IntN);
100
Justin Bognerec37a022016-05-12 21:46:18 +0000101 void SelectFrameIndex(SDNode *N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000102 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
103 /// inline asm expressions.
Craig Topper906c2cd2014-04-29 07:58:16 +0000104 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
Daniel Sanders60f1db02015-03-13 12:45:09 +0000105 unsigned ConstraintID,
Craig Topper906c2cd2014-04-29 07:58:16 +0000106 std::vector<SDValue> &OutOps) override;
Justin Bognerec37a022016-05-12 21:46:18 +0000107 bool tryLoadOfLoadIntrinsic(LoadSDNode *N);
108 void SelectLoad(SDNode *N);
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000109 void SelectIndexedLoad(LoadSDNode *LD, const SDLoc &dl);
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000110 void SelectIndexedStore(StoreSDNode *ST, const SDLoc &dl);
Justin Bognerec37a022016-05-12 21:46:18 +0000111 void SelectStore(SDNode *N);
112 void SelectSHL(SDNode *N);
Justin Bognerec37a022016-05-12 21:46:18 +0000113 void SelectZeroExtend(SDNode *N);
114 void SelectIntrinsicWChain(SDNode *N);
115 void SelectIntrinsicWOChain(SDNode *N);
116 void SelectConstant(SDNode *N);
117 void SelectConstantFP(SDNode *N);
Krzysztof Parzyszek5da24e52016-06-27 15:08:22 +0000118 void SelectBitcast(SDNode *N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000119
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000120 // Include the pieces autogenerated from the target description.
121 #include "HexagonGenDAGISel.inc"
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000122
123private:
Krzysztof Parzyszekef580172017-05-30 17:47:51 +0000124 bool keepsLowBits(const SDValue &Val, unsigned NumBits, SDValue &Src);
Krzysztof Parzyszekb16a4e52016-11-14 20:53:09 +0000125 bool isOrEquivalentToAdd(const SDNode *N) const;
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +0000126 bool isAlignedMemNode(const MemSDNode *N) const;
Krzysztof Parzyszekb3a8d202017-06-13 17:10:16 +0000127 bool isSmallStackStore(const StoreSDNode *N) const;
Krzysztof Parzyszek2839b292016-11-05 21:44:50 +0000128 bool isPositiveHalfWord(const SDNode *N) const;
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +0000129
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +0000130 // DAG preprocessing functions.
131 void ppSimplifyOrSelect0(std::vector<SDNode*> &&Nodes);
132 void ppAddrReorderAddShl(std::vector<SDNode*> &&Nodes);
133 void ppAddrRewriteAndSrl(std::vector<SDNode*> &&Nodes);
134 void ppHoistZextI1(std::vector<SDNode*> &&Nodes);
135
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +0000136 SmallDenseMap<SDNode *,int> RootWeights;
137 SmallDenseMap<SDNode *,int> RootHeights;
138 SmallDenseMap<const Value *,int> GAUsesInFunction;
139 int getWeight(SDNode *N);
140 int getHeight(SDNode *N);
141 SDValue getMultiplierForSHL(SDNode *N);
142 SDValue factorOutPowerOf2(SDValue V, unsigned Power);
143 unsigned getUsesInFunction(const Value *V);
144 SDValue balanceSubTree(SDNode *N, bool Factorize = false);
145 void rebalanceAddressTrees();
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000146}; // end HexagonDAGToDAGISel
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000147} // end anonymous namespace
148
149
150/// createHexagonISelDag - This pass converts a legalized DAG into a
151/// Hexagon-specific DAG, ready for instruction scheduling.
152///
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000153namespace llvm {
154FunctionPass *createHexagonISelDag(HexagonTargetMachine &TM,
155 CodeGenOpt::Level OptLevel) {
Jyotsna Vermad9225242013-02-13 21:38:46 +0000156 return new HexagonDAGToDAGISel(TM, OptLevel);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000157}
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000158}
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000159
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000160// Intrinsics that return a a predicate.
Krzysztof Parzyszek08ff8882015-11-26 18:38:27 +0000161static bool doesIntrinsicReturnPredicate(unsigned ID) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000162 switch (ID) {
163 default:
Krzysztof Parzyszek08ff8882015-11-26 18:38:27 +0000164 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000165 case Intrinsic::hexagon_C2_cmpeq:
166 case Intrinsic::hexagon_C2_cmpgt:
167 case Intrinsic::hexagon_C2_cmpgtu:
168 case Intrinsic::hexagon_C2_cmpgtup:
169 case Intrinsic::hexagon_C2_cmpgtp:
170 case Intrinsic::hexagon_C2_cmpeqp:
171 case Intrinsic::hexagon_C2_bitsset:
172 case Intrinsic::hexagon_C2_bitsclr:
173 case Intrinsic::hexagon_C2_cmpeqi:
174 case Intrinsic::hexagon_C2_cmpgti:
175 case Intrinsic::hexagon_C2_cmpgtui:
176 case Intrinsic::hexagon_C2_cmpgei:
177 case Intrinsic::hexagon_C2_cmpgeui:
178 case Intrinsic::hexagon_C2_cmplt:
179 case Intrinsic::hexagon_C2_cmpltu:
180 case Intrinsic::hexagon_C2_bitsclri:
181 case Intrinsic::hexagon_C2_and:
182 case Intrinsic::hexagon_C2_or:
183 case Intrinsic::hexagon_C2_xor:
184 case Intrinsic::hexagon_C2_andn:
185 case Intrinsic::hexagon_C2_not:
186 case Intrinsic::hexagon_C2_orn:
187 case Intrinsic::hexagon_C2_pxfer_map:
188 case Intrinsic::hexagon_C2_any8:
189 case Intrinsic::hexagon_C2_all8:
190 case Intrinsic::hexagon_A2_vcmpbeq:
191 case Intrinsic::hexagon_A2_vcmpbgtu:
192 case Intrinsic::hexagon_A2_vcmpheq:
193 case Intrinsic::hexagon_A2_vcmphgt:
194 case Intrinsic::hexagon_A2_vcmphgtu:
195 case Intrinsic::hexagon_A2_vcmpweq:
196 case Intrinsic::hexagon_A2_vcmpwgt:
197 case Intrinsic::hexagon_A2_vcmpwgtu:
198 case Intrinsic::hexagon_C2_tfrrp:
199 case Intrinsic::hexagon_S2_tstbit_i:
200 case Intrinsic::hexagon_S2_tstbit_r:
Krzysztof Parzyszek08ff8882015-11-26 18:38:27 +0000201 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000202 }
203}
204
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000205void HexagonDAGToDAGISel::SelectIndexedLoad(LoadSDNode *LD, const SDLoc &dl) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000206 SDValue Chain = LD->getChain();
207 SDValue Base = LD->getBasePtr();
208 SDValue Offset = LD->getOffset();
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000209 int32_t Inc = cast<ConstantSDNode>(Offset.getNode())->getSExtValue();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000210 EVT LoadedVT = LD->getMemoryVT();
211 unsigned Opcode = 0;
212
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000213 // Check for zero extended loads. Treat any-extend loads as zero extended
214 // loads.
215 ISD::LoadExtType ExtType = LD->getExtensionType();
216 bool IsZeroExt = (ExtType == ISD::ZEXTLOAD || ExtType == ISD::EXTLOAD);
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000217 bool IsValidInc = HII->isValidAutoIncImm(LoadedVT, Inc);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000218
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000219 assert(LoadedVT.isSimple());
220 switch (LoadedVT.getSimpleVT().SimpleTy) {
221 case MVT::i8:
222 if (IsZeroExt)
223 Opcode = IsValidInc ? Hexagon::L2_loadrub_pi : Hexagon::L2_loadrub_io;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000224 else
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000225 Opcode = IsValidInc ? Hexagon::L2_loadrb_pi : Hexagon::L2_loadrb_io;
226 break;
227 case MVT::i16:
228 if (IsZeroExt)
229 Opcode = IsValidInc ? Hexagon::L2_loadruh_pi : Hexagon::L2_loadruh_io;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000230 else
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000231 Opcode = IsValidInc ? Hexagon::L2_loadrh_pi : Hexagon::L2_loadrh_io;
232 break;
233 case MVT::i32:
234 Opcode = IsValidInc ? Hexagon::L2_loadri_pi : Hexagon::L2_loadri_io;
235 break;
236 case MVT::i64:
237 Opcode = IsValidInc ? Hexagon::L2_loadrd_pi : Hexagon::L2_loadrd_io;
238 break;
239 // 64B
240 case MVT::v64i8:
241 case MVT::v32i16:
242 case MVT::v16i32:
243 case MVT::v8i64:
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000244 if (isAlignedMemNode(LD)) {
245 if (LD->isNonTemporal())
246 Opcode = IsValidInc ? Hexagon::V6_vL32b_nt_pi : Hexagon::V6_vL32b_nt_ai;
247 else
248 Opcode = IsValidInc ? Hexagon::V6_vL32b_pi : Hexagon::V6_vL32b_ai;
249 } else {
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000250 Opcode = IsValidInc ? Hexagon::V6_vL32Ub_pi : Hexagon::V6_vL32Ub_ai;
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000251 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000252 break;
Krzysztof Parzyszek08ff8882015-11-26 18:38:27 +0000253 // 128B
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000254 case MVT::v128i8:
255 case MVT::v64i16:
256 case MVT::v32i32:
257 case MVT::v16i64:
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000258 if (isAlignedMemNode(LD)) {
259 if (LD->isNonTemporal())
260 Opcode = IsValidInc ? Hexagon::V6_vL32b_nt_pi_128B
261 : Hexagon::V6_vL32b_nt_ai_128B;
262 else
263 Opcode = IsValidInc ? Hexagon::V6_vL32b_pi_128B
264 : Hexagon::V6_vL32b_ai_128B;
265 } else {
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000266 Opcode = IsValidInc ? Hexagon::V6_vL32Ub_pi_128B
267 : Hexagon::V6_vL32Ub_ai_128B;
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000268 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000269 break;
270 default:
271 llvm_unreachable("Unexpected memory type in indexed load");
Justin Bognerec37a022016-05-12 21:46:18 +0000272 }
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000273
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000274 SDValue IncV = CurDAG->getTargetConstant(Inc, dl, MVT::i32);
275 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
276 MemOp[0] = LD->getMemOperand();
277
278 auto getExt64 = [this,ExtType] (MachineSDNode *N, const SDLoc &dl)
279 -> MachineSDNode* {
280 if (ExtType == ISD::ZEXTLOAD || ExtType == ISD::EXTLOAD) {
281 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
282 return CurDAG->getMachineNode(Hexagon::A4_combineir, dl, MVT::i64,
283 Zero, SDValue(N, 0));
Krzysztof Parzyszek08ff8882015-11-26 18:38:27 +0000284 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000285 if (ExtType == ISD::SEXTLOAD)
286 return CurDAG->getMachineNode(Hexagon::A2_sxtw, dl, MVT::i64,
287 SDValue(N, 0));
288 return N;
289 };
290
291 // Loaded value Next address Chain
292 SDValue From[3] = { SDValue(LD,0), SDValue(LD,1), SDValue(LD,2) };
293 SDValue To[3];
294
295 EVT ValueVT = LD->getValueType(0);
296 if (ValueVT == MVT::i64 && ExtType != ISD::NON_EXTLOAD) {
297 // A load extending to i64 will actually produce i32, which will then
298 // need to be extended to i64.
299 assert(LoadedVT.getSizeInBits() <= 32);
300 ValueVT = MVT::i32;
301 }
302
303 if (IsValidInc) {
304 MachineSDNode *L = CurDAG->getMachineNode(Opcode, dl, ValueVT,
305 MVT::i32, MVT::Other, Base,
306 IncV, Chain);
307 L->setMemRefs(MemOp, MemOp+1);
308 To[1] = SDValue(L, 1); // Next address.
309 To[2] = SDValue(L, 2); // Chain.
310 // Handle special case for extension to i64.
311 if (LD->getValueType(0) == MVT::i64)
312 L = getExt64(L, dl);
313 To[0] = SDValue(L, 0); // Loaded (extended) value.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000314 } else {
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000315 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
316 MachineSDNode *L = CurDAG->getMachineNode(Opcode, dl, ValueVT, MVT::Other,
317 Base, Zero, Chain);
318 L->setMemRefs(MemOp, MemOp+1);
319 To[2] = SDValue(L, 1); // Chain.
320 MachineSDNode *A = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
321 Base, IncV);
322 To[1] = SDValue(A, 0); // Next address.
323 // Handle special case for extension to i64.
324 if (LD->getValueType(0) == MVT::i64)
325 L = getExt64(L, dl);
326 To[0] = SDValue(L, 0); // Loaded (extended) value.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000327 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000328 ReplaceUses(From, To, 3);
329 CurDAG->RemoveDeadNode(LD);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000330}
331
332
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000333MachineSDNode *HexagonDAGToDAGISel::LoadInstrForLoadIntrinsic(SDNode *IntN) {
334 if (IntN->getOpcode() != ISD::INTRINSIC_W_CHAIN)
335 return nullptr;
336
337 SDLoc dl(IntN);
338 unsigned IntNo = cast<ConstantSDNode>(IntN->getOperand(1))->getZExtValue();
339
340 static std::map<unsigned,unsigned> LoadPciMap = {
341 { Intrinsic::hexagon_circ_ldb, Hexagon::L2_loadrb_pci },
342 { Intrinsic::hexagon_circ_ldub, Hexagon::L2_loadrub_pci },
343 { Intrinsic::hexagon_circ_ldh, Hexagon::L2_loadrh_pci },
344 { Intrinsic::hexagon_circ_lduh, Hexagon::L2_loadruh_pci },
345 { Intrinsic::hexagon_circ_ldw, Hexagon::L2_loadri_pci },
346 { Intrinsic::hexagon_circ_ldd, Hexagon::L2_loadrd_pci },
347 };
348 auto FLC = LoadPciMap.find(IntNo);
349 if (FLC != LoadPciMap.end()) {
350 SDNode *Mod = CurDAG->getMachineNode(Hexagon::A2_tfrrcr, dl, MVT::i32,
351 IntN->getOperand(4));
352 EVT ValTy = (IntNo == Intrinsic::hexagon_circ_ldd) ? MVT::i64 : MVT::i32;
353 EVT RTys[] = { ValTy, MVT::i32, MVT::Other };
354 // Operands: { Base, Increment, Modifier, Chain }
355 auto Inc = cast<ConstantSDNode>(IntN->getOperand(5));
356 SDValue I = CurDAG->getTargetConstant(Inc->getSExtValue(), dl, MVT::i32);
357 MachineSDNode *Res = CurDAG->getMachineNode(FLC->second, dl, RTys,
358 { IntN->getOperand(2), I, SDValue(Mod,0), IntN->getOperand(0) });
359 return Res;
360 }
361
362 static std::map<unsigned,unsigned> LoadPbrMap = {
363 { Intrinsic::hexagon_brev_ldb, Hexagon::L2_loadrb_pbr },
364 { Intrinsic::hexagon_brev_ldub, Hexagon::L2_loadrub_pbr },
365 { Intrinsic::hexagon_brev_ldh, Hexagon::L2_loadrh_pbr },
366 { Intrinsic::hexagon_brev_lduh, Hexagon::L2_loadruh_pbr },
367 { Intrinsic::hexagon_brev_ldw, Hexagon::L2_loadri_pbr },
368 { Intrinsic::hexagon_brev_ldd, Hexagon::L2_loadrd_pbr },
369 };
370 auto FLB = LoadPbrMap.find(IntNo);
371 if (FLB != LoadPbrMap.end()) {
372 SDNode *Mod = CurDAG->getMachineNode(Hexagon::A2_tfrrcr, dl, MVT::i32,
373 IntN->getOperand(4));
374 EVT ValTy = (IntNo == Intrinsic::hexagon_brev_ldd) ? MVT::i64 : MVT::i32;
375 EVT RTys[] = { ValTy, MVT::i32, MVT::Other };
376 // Operands: { Base, Modifier, Chain }
377 MachineSDNode *Res = CurDAG->getMachineNode(FLB->second, dl, RTys,
378 { IntN->getOperand(2), SDValue(Mod,0), IntN->getOperand(0) });
379 return Res;
380 }
381
382 return nullptr;
383}
384
385SDNode *HexagonDAGToDAGISel::StoreInstrForLoadIntrinsic(MachineSDNode *LoadN,
386 SDNode *IntN) {
387 // The "LoadN" is just a machine load instruction. The intrinsic also
388 // involves storing it. Generate an appropriate store to the location
389 // given in the intrinsic's operand(3).
390 uint64_t F = HII->get(LoadN->getMachineOpcode()).TSFlags;
391 unsigned SizeBits = (F >> HexagonII::MemAccessSizePos) &
392 HexagonII::MemAccesSizeMask;
393 unsigned Size = 1U << (SizeBits-1);
394
395 SDLoc dl(IntN);
396 MachinePointerInfo PI;
397 SDValue TS;
398 SDValue Loc = IntN->getOperand(3);
399
400 if (Size >= 4)
Justin Lebar9c375812016-07-15 18:27:10 +0000401 TS = CurDAG->getStore(SDValue(LoadN, 2), dl, SDValue(LoadN, 0), Loc, PI,
402 Size);
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000403 else
Justin Lebar9c375812016-07-15 18:27:10 +0000404 TS = CurDAG->getTruncStore(SDValue(LoadN, 2), dl, SDValue(LoadN, 0), Loc,
405 PI, MVT::getIntegerVT(Size * 8), Size);
Justin Bognerdcb7a822016-05-10 20:31:53 +0000406
407 SDNode *StoreN;
408 {
409 HandleSDNode Handle(TS);
410 SelectStore(TS.getNode());
411 StoreN = Handle.getValue().getNode();
412 }
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000413
414 // Load's results are { Loaded value, Updated pointer, Chain }
415 ReplaceUses(SDValue(IntN, 0), SDValue(LoadN, 1));
416 ReplaceUses(SDValue(IntN, 1), SDValue(StoreN, 0));
417 return StoreN;
418}
419
Justin Bognerec37a022016-05-12 21:46:18 +0000420bool HexagonDAGToDAGISel::tryLoadOfLoadIntrinsic(LoadSDNode *N) {
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000421 // The intrinsics for load circ/brev perform two operations:
422 // 1. Load a value V from the specified location, using the addressing
423 // mode corresponding to the intrinsic.
424 // 2. Store V into a specified location. This location is typically a
425 // local, temporary object.
426 // In many cases, the program using these intrinsics will immediately
427 // load V again from the local object. In those cases, when certain
428 // conditions are met, the last load can be removed.
429 // This function identifies and optimizes this pattern. If the pattern
430 // cannot be optimized, it returns nullptr, which will cause the load
431 // to be selected separately from the intrinsic (which will be handled
432 // in SelectIntrinsicWChain).
433
434 SDValue Ch = N->getOperand(0);
435 SDValue Loc = N->getOperand(1);
436
437 // Assume that the load and the intrinsic are connected directly with a
438 // chain:
439 // t1: i32,ch = int.load ..., ..., ..., Loc, ... // <-- C
440 // t2: i32,ch = load t1:1, Loc, ...
441 SDNode *C = Ch.getNode();
442
443 if (C->getOpcode() != ISD::INTRINSIC_W_CHAIN)
Justin Bognerec37a022016-05-12 21:46:18 +0000444 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000445
446 // The second load can only be eliminated if its extension type matches
447 // that of the load instruction corresponding to the intrinsic. The user
448 // can provide an address of an unsigned variable to store the result of
449 // a sign-extending intrinsic into (or the other way around).
450 ISD::LoadExtType IntExt;
451 switch (cast<ConstantSDNode>(C->getOperand(1))->getZExtValue()) {
452 case Intrinsic::hexagon_brev_ldub:
453 case Intrinsic::hexagon_brev_lduh:
454 case Intrinsic::hexagon_circ_ldub:
455 case Intrinsic::hexagon_circ_lduh:
456 IntExt = ISD::ZEXTLOAD;
457 break;
458 case Intrinsic::hexagon_brev_ldw:
459 case Intrinsic::hexagon_brev_ldd:
460 case Intrinsic::hexagon_circ_ldw:
461 case Intrinsic::hexagon_circ_ldd:
462 IntExt = ISD::NON_EXTLOAD;
463 break;
464 default:
465 IntExt = ISD::SEXTLOAD;
466 break;
467 }
468 if (N->getExtensionType() != IntExt)
Justin Bognerec37a022016-05-12 21:46:18 +0000469 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000470
471 // Make sure the target location for the loaded value in the load intrinsic
472 // is the location from which LD (or N) is loading.
473 if (C->getNumOperands() < 4 || Loc.getNode() != C->getOperand(3).getNode())
Justin Bognerec37a022016-05-12 21:46:18 +0000474 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000475
476 if (MachineSDNode *L = LoadInstrForLoadIntrinsic(C)) {
477 SDNode *S = StoreInstrForLoadIntrinsic(L, C);
478 SDValue F[] = { SDValue(N,0), SDValue(N,1), SDValue(C,0), SDValue(C,1) };
479 SDValue T[] = { SDValue(L,0), SDValue(S,0), SDValue(L,1), SDValue(S,0) };
480 ReplaceUses(F, T, array_lengthof(T));
481 // This transformation will leave the intrinsic dead. If it remains in
482 // the DAG, the selection code will see it again, but without the load,
483 // and it will generate a store that is normally required for it.
Krzysztof Parzyszek0f791f42016-05-13 18:48:15 +0000484 CurDAG->RemoveDeadNode(C);
Justin Bognerec37a022016-05-12 21:46:18 +0000485 return true;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000486 }
487
Justin Bognerec37a022016-05-12 21:46:18 +0000488 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000489}
490
Justin Bognerec37a022016-05-12 21:46:18 +0000491void HexagonDAGToDAGISel::SelectLoad(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000492 SDLoc dl(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000493 LoadSDNode *LD = cast<LoadSDNode>(N);
494 ISD::MemIndexedMode AM = LD->getAddressingMode();
495
496 // Handle indexed loads.
Justin Bognerec37a022016-05-12 21:46:18 +0000497 if (AM != ISD::UNINDEXED) {
498 SelectIndexedLoad(LD, dl);
499 return;
500 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000501
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000502 // Handle patterns using circ/brev load intrinsics.
Justin Bognerec37a022016-05-12 21:46:18 +0000503 if (tryLoadOfLoadIntrinsic(LD))
504 return;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000505
Justin Bognerec37a022016-05-12 21:46:18 +0000506 SelectCode(LD);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000507}
508
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000509void HexagonDAGToDAGISel::SelectIndexedStore(StoreSDNode *ST, const SDLoc &dl) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000510 SDValue Chain = ST->getChain();
511 SDValue Base = ST->getBasePtr();
512 SDValue Offset = ST->getOffset();
513 SDValue Value = ST->getValue();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000514 // Get the constant value.
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000515 int32_t Inc = cast<ConstantSDNode>(Offset.getNode())->getSExtValue();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000516 EVT StoredVT = ST->getMemoryVT();
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000517 EVT ValueVT = Value.getValueType();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000518
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000519 bool IsValidInc = HII->isValidAutoIncImm(StoredVT, Inc);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000520 unsigned Opcode = 0;
521
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000522 assert(StoredVT.isSimple());
523 switch (StoredVT.getSimpleVT().SimpleTy) {
524 case MVT::i8:
525 Opcode = IsValidInc ? Hexagon::S2_storerb_pi : Hexagon::S2_storerb_io;
526 break;
527 case MVT::i16:
528 Opcode = IsValidInc ? Hexagon::S2_storerh_pi : Hexagon::S2_storerh_io;
529 break;
530 case MVT::i32:
531 Opcode = IsValidInc ? Hexagon::S2_storeri_pi : Hexagon::S2_storeri_io;
532 break;
533 case MVT::i64:
534 Opcode = IsValidInc ? Hexagon::S2_storerd_pi : Hexagon::S2_storerd_io;
535 break;
536 // 64B
537 case MVT::v64i8:
538 case MVT::v32i16:
539 case MVT::v16i32:
540 case MVT::v8i64:
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000541 if (isAlignedMemNode(ST)) {
542 if (ST->isNonTemporal())
543 Opcode = IsValidInc ? Hexagon::V6_vS32b_nt_pi : Hexagon::V6_vS32b_nt_ai;
544 else
545 Opcode = IsValidInc ? Hexagon::V6_vS32b_pi : Hexagon::V6_vS32b_ai;
546 } else {
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000547 Opcode = IsValidInc ? Hexagon::V6_vS32Ub_pi : Hexagon::V6_vS32Ub_ai;
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000548 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000549 break;
Krzysztof Parzyszek08ff8882015-11-26 18:38:27 +0000550 // 128B
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000551 case MVT::v128i8:
552 case MVT::v64i16:
553 case MVT::v32i32:
554 case MVT::v16i64:
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000555 if (isAlignedMemNode(ST)) {
556 if (ST->isNonTemporal())
557 Opcode = IsValidInc ? Hexagon::V6_vS32b_nt_pi_128B
558 : Hexagon::V6_vS32b_nt_ai_128B;
559 else
560 Opcode = IsValidInc ? Hexagon::V6_vS32b_pi_128B
561 : Hexagon::V6_vS32b_ai_128B;
562 } else {
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000563 Opcode = IsValidInc ? Hexagon::V6_vS32Ub_pi_128B
564 : Hexagon::V6_vS32Ub_ai_128B;
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000565 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000566 break;
567 default:
568 llvm_unreachable("Unexpected memory type in indexed store");
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +0000569 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000570
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000571 if (ST->isTruncatingStore() && ValueVT.getSizeInBits() == 64) {
572 assert(StoredVT.getSizeInBits() < 64 && "Not a truncating store");
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +0000573 Value = CurDAG->getTargetExtractSubreg(Hexagon::isub_lo,
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000574 dl, MVT::i32, Value);
575 }
576
577 SDValue IncV = CurDAG->getTargetConstant(Inc, dl, MVT::i32);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000578 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
579 MemOp[0] = ST->getMemOperand();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000580
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000581 // Next address Chain
582 SDValue From[2] = { SDValue(ST,0), SDValue(ST,1) };
583 SDValue To[2];
584
585 if (IsValidInc) {
586 // Build post increment store.
587 SDValue Ops[] = { Base, IncV, Value, Chain };
588 MachineSDNode *S = CurDAG->getMachineNode(Opcode, dl, MVT::i32, MVT::Other,
589 Ops);
590 S->setMemRefs(MemOp, MemOp + 1);
591 To[0] = SDValue(S, 0);
592 To[1] = SDValue(S, 1);
593 } else {
594 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
595 SDValue Ops[] = { Base, Zero, Value, Chain };
596 MachineSDNode *S = CurDAG->getMachineNode(Opcode, dl, MVT::Other, Ops);
597 S->setMemRefs(MemOp, MemOp + 1);
598 To[1] = SDValue(S, 0);
599 MachineSDNode *A = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
600 Base, IncV);
601 To[0] = SDValue(A, 0);
602 }
603
604 ReplaceUses(From, To, 2);
Justin Bognerdcb7a822016-05-10 20:31:53 +0000605 CurDAG->RemoveDeadNode(ST);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000606}
607
Justin Bognerec37a022016-05-12 21:46:18 +0000608void HexagonDAGToDAGISel::SelectStore(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000609 SDLoc dl(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000610 StoreSDNode *ST = cast<StoreSDNode>(N);
611 ISD::MemIndexedMode AM = ST->getAddressingMode();
612
613 // Handle indexed stores.
614 if (AM != ISD::UNINDEXED) {
Justin Bognerec37a022016-05-12 21:46:18 +0000615 SelectIndexedStore(ST, dl);
616 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000617 }
Sirish Pandec92c3162012-05-03 16:18:50 +0000618
Justin Bognerec37a022016-05-12 21:46:18 +0000619 SelectCode(ST);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000620}
621
Justin Bognerec37a022016-05-12 21:46:18 +0000622void HexagonDAGToDAGISel::SelectSHL(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000623 SDLoc dl(N);
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000624 SDValue Shl_0 = N->getOperand(0);
625 SDValue Shl_1 = N->getOperand(1);
Krzysztof Parzyszekd978ae22016-08-01 20:00:33 +0000626
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000627 auto Default = [this,N] () -> void { SelectCode(N); };
628
629 if (N->getValueType(0) != MVT::i32 || Shl_1.getOpcode() != ISD::Constant)
630 return Default();
631
632 // RHS is const.
633 int32_t ShlConst = cast<ConstantSDNode>(Shl_1)->getSExtValue();
634
635 if (Shl_0.getOpcode() == ISD::MUL) {
636 SDValue Mul_0 = Shl_0.getOperand(0); // Val
637 SDValue Mul_1 = Shl_0.getOperand(1); // Const
638 // RHS of mul is const.
639 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mul_1)) {
640 int32_t ValConst = C->getSExtValue() << ShlConst;
641 if (isInt<9>(ValConst)) {
642 SDValue Val = CurDAG->getTargetConstant(ValConst, dl, MVT::i32);
643 SDNode *Result = CurDAG->getMachineNode(Hexagon::M2_mpysmi, dl,
644 MVT::i32, Mul_0, Val);
645 ReplaceNode(N, Result);
646 return;
647 }
648 }
649 return Default();
650 }
651
652 if (Shl_0.getOpcode() == ISD::SUB) {
653 SDValue Sub_0 = Shl_0.getOperand(0); // Const 0
654 SDValue Sub_1 = Shl_0.getOperand(1); // Val
655 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Sub_0)) {
656 if (C1->getSExtValue() != 0 || Sub_1.getOpcode() != ISD::SHL)
657 return Default();
658 SDValue Shl2_0 = Sub_1.getOperand(0); // Val
659 SDValue Shl2_1 = Sub_1.getOperand(1); // Const
660 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(Shl2_1)) {
661 int32_t ValConst = 1 << (ShlConst + C2->getSExtValue());
662 if (isInt<9>(-ValConst)) {
663 SDValue Val = CurDAG->getTargetConstant(-ValConst, dl, MVT::i32);
664 SDNode *Result = CurDAG->getMachineNode(Hexagon::M2_mpysmi, dl,
665 MVT::i32, Shl2_0, Val);
666 ReplaceNode(N, Result);
667 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000668 }
669 }
670 }
671 }
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000672
673 return Default();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000674}
675
676
677//
678// If there is an zero_extend followed an intrinsic in DAG (this means - the
679// result of the intrinsic is predicate); convert the zero_extend to
680// transfer instruction.
681//
682// Zero extend -> transfer is lowered here. Otherwise, zero_extend will be
683// converted into a MUX as predicate registers defined as 1 bit in the
684// compiler. Architecture defines them as 8-bit registers.
685// We want to preserve all the lower 8-bits and, not just 1 LSB bit.
686//
Justin Bognerec37a022016-05-12 21:46:18 +0000687void HexagonDAGToDAGISel::SelectZeroExtend(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000688 SDLoc dl(N);
Krzysztof Parzyszek42113342015-03-19 16:33:08 +0000689
690 SDValue Op0 = N->getOperand(0);
691 EVT OpVT = Op0.getValueType();
692 unsigned OpBW = OpVT.getSizeInBits();
693
694 // Special handling for zero-extending a vector of booleans.
695 if (OpVT.isVector() && OpVT.getVectorElementType() == MVT::i1 && OpBW <= 64) {
696 SDNode *Mask = CurDAG->getMachineNode(Hexagon::C2_mask, dl, MVT::i64, Op0);
697 unsigned NE = OpVT.getVectorNumElements();
698 EVT ExVT = N->getValueType(0);
Sanjay Patel1ed771f2016-09-14 16:37:15 +0000699 unsigned ES = ExVT.getScalarSizeInBits();
Krzysztof Parzyszek42113342015-03-19 16:33:08 +0000700 uint64_t MV = 0, Bit = 1;
701 for (unsigned i = 0; i < NE; ++i) {
702 MV |= Bit;
703 Bit <<= ES;
704 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000705 SDValue Ones = CurDAG->getTargetConstant(MV, dl, MVT::i64);
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +0000706 SDNode *OnesReg = CurDAG->getMachineNode(Hexagon::CONST64, dl,
Krzysztof Parzyszek42113342015-03-19 16:33:08 +0000707 MVT::i64, Ones);
708 if (ExVT.getSizeInBits() == 32) {
709 SDNode *And = CurDAG->getMachineNode(Hexagon::A2_andp, dl, MVT::i64,
710 SDValue(Mask,0), SDValue(OnesReg,0));
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +0000711 SDValue SubR = CurDAG->getTargetConstant(Hexagon::isub_lo, dl, MVT::i32);
Justin Bognerec37a022016-05-12 21:46:18 +0000712 ReplaceNode(N, CurDAG->getMachineNode(Hexagon::EXTRACT_SUBREG, dl, ExVT,
713 SDValue(And, 0), SubR));
714 return;
Krzysztof Parzyszek42113342015-03-19 16:33:08 +0000715 }
Justin Bognerec37a022016-05-12 21:46:18 +0000716 ReplaceNode(N,
717 CurDAG->getMachineNode(Hexagon::A2_andp, dl, ExVT,
718 SDValue(Mask, 0), SDValue(OnesReg, 0)));
719 return;
Krzysztof Parzyszek42113342015-03-19 16:33:08 +0000720 }
721
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000722 SDNode *Int = N->getOperand(0).getNode();
723 if ((Int->getOpcode() == ISD::INTRINSIC_WO_CHAIN)) {
724 unsigned ID = cast<ConstantSDNode>(Int->getOperand(0))->getZExtValue();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000725 if (doesIntrinsicReturnPredicate(ID)) {
726 // Now we need to differentiate target data types.
727 if (N->getValueType(0) == MVT::i64) {
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000728 // Convert the zero_extend to Rs = Pd followed by A2_combinew(0,Rs).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000729 SDValue TargetConst0 = CurDAG->getTargetConstant(0, dl, MVT::i32);
Colin LeMahieu30dcb232014-12-09 18:16:49 +0000730 SDNode *Result_1 = CurDAG->getMachineNode(Hexagon::C2_tfrpr, dl,
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000731 MVT::i32, SDValue(Int, 0));
Colin LeMahieu4af437f2014-12-09 20:23:30 +0000732 SDNode *Result_2 = CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl,
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000733 MVT::i32, TargetConst0);
Colin LeMahieub580d7d2014-12-09 19:23:45 +0000734 SDNode *Result_3 = CurDAG->getMachineNode(Hexagon::A2_combinew, dl,
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000735 MVT::i64, MVT::Other,
736 SDValue(Result_2, 0),
737 SDValue(Result_1, 0));
Justin Bognerec37a022016-05-12 21:46:18 +0000738 ReplaceNode(N, Result_3);
739 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000740 }
741 if (N->getValueType(0) == MVT::i32) {
742 // Convert the zero_extend to Rs = Pd
Colin LeMahieu30dcb232014-12-09 18:16:49 +0000743 SDNode* RsPd = CurDAG->getMachineNode(Hexagon::C2_tfrpr, dl,
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000744 MVT::i32, SDValue(Int, 0));
Justin Bognerec37a022016-05-12 21:46:18 +0000745 ReplaceNode(N, RsPd);
746 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000747 }
Craig Toppere55c5562012-02-07 02:50:20 +0000748 llvm_unreachable("Unexpected value type");
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000749 }
750 }
Justin Bognerec37a022016-05-12 21:46:18 +0000751 SelectCode(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000752}
753
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000754
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000755//
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000756// Handling intrinsics for circular load and bitreverse load.
Krzysztof Parzyszek47ab1f22015-03-18 16:23:44 +0000757//
Justin Bognerec37a022016-05-12 21:46:18 +0000758void HexagonDAGToDAGISel::SelectIntrinsicWChain(SDNode *N) {
759 if (MachineSDNode *L = LoadInstrForLoadIntrinsic(N)) {
760 StoreInstrForLoadIntrinsic(L, N);
Krzysztof Parzyszek0f791f42016-05-13 18:48:15 +0000761 CurDAG->RemoveDeadNode(N);
Justin Bognerec37a022016-05-12 21:46:18 +0000762 return;
763 }
764 SelectCode(N);
Krzysztof Parzyszek47ab1f22015-03-18 16:23:44 +0000765}
766
Justin Bognerec37a022016-05-12 21:46:18 +0000767void HexagonDAGToDAGISel::SelectIntrinsicWOChain(SDNode *N) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000768 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
769 unsigned Bits;
770 switch (IID) {
771 case Intrinsic::hexagon_S2_vsplatrb:
772 Bits = 8;
773 break;
774 case Intrinsic::hexagon_S2_vsplatrh:
775 Bits = 16;
776 break;
777 default:
Justin Bognerec37a022016-05-12 21:46:18 +0000778 SelectCode(N);
779 return;
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000780 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000781
Krzysztof Parzyszeke60e5fe2016-05-12 17:21:40 +0000782 SDValue V = N->getOperand(1);
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000783 SDValue U;
Krzysztof Parzyszekef580172017-05-30 17:47:51 +0000784 if (keepsLowBits(V, Bits, U)) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000785 SDValue R = CurDAG->getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
Krzysztof Parzyszeke60e5fe2016-05-12 17:21:40 +0000786 N->getOperand(0), U);
Justin Bognerd82025b2016-05-12 21:24:23 +0000787 ReplaceNode(N, R.getNode());
Justin Bognerec37a022016-05-12 21:46:18 +0000788 SelectCode(R.getNode());
789 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000790 }
Justin Bognerec37a022016-05-12 21:46:18 +0000791 SelectCode(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000792}
793
Sirish Pande69295b82012-05-10 20:20:25 +0000794//
795// Map floating point constant values.
796//
Justin Bognerec37a022016-05-12 21:46:18 +0000797void HexagonDAGToDAGISel::SelectConstantFP(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000798 SDLoc dl(N);
Sirish Pande69295b82012-05-10 20:20:25 +0000799 ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N);
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +0000800 APInt A = CN->getValueAPF().bitcastToAPInt();
Sirish Pande69295b82012-05-10 20:20:25 +0000801 if (N->getValueType(0) == MVT::f32) {
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +0000802 SDValue V = CurDAG->getTargetConstant(A.getZExtValue(), dl, MVT::i32);
803 ReplaceNode(N, CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl, MVT::f32, V));
Justin Bognerec37a022016-05-12 21:46:18 +0000804 return;
Sirish Pande69295b82012-05-10 20:20:25 +0000805 }
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000806 if (N->getValueType(0) == MVT::f64) {
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +0000807 SDValue V = CurDAG->getTargetConstant(A.getZExtValue(), dl, MVT::i64);
808 ReplaceNode(N, CurDAG->getMachineNode(Hexagon::CONST64, dl, MVT::f64, V));
Justin Bognerec37a022016-05-12 21:46:18 +0000809 return;
Sirish Pande69295b82012-05-10 20:20:25 +0000810 }
811
Justin Bognerec37a022016-05-12 21:46:18 +0000812 SelectCode(N);
Sirish Pande69295b82012-05-10 20:20:25 +0000813}
814
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000815//
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000816// Map boolean values.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000817//
Justin Bognerec37a022016-05-12 21:46:18 +0000818void HexagonDAGToDAGISel::SelectConstant(SDNode *N) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000819 if (N->getValueType(0) == MVT::i1) {
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000820 assert(!(cast<ConstantSDNode>(N)->getZExtValue() >> 1));
821 unsigned Opc = (cast<ConstantSDNode>(N)->getSExtValue() != 0)
822 ? Hexagon::PS_true
823 : Hexagon::PS_false;
824 ReplaceNode(N, CurDAG->getMachineNode(Opc, SDLoc(N), MVT::i1));
825 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000826 }
827
Justin Bognerec37a022016-05-12 21:46:18 +0000828 SelectCode(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000829}
830
831
Justin Bognerec37a022016-05-12 21:46:18 +0000832void HexagonDAGToDAGISel::SelectFrameIndex(SDNode *N) {
Matthias Braun941a7052016-07-28 18:40:00 +0000833 MachineFrameInfo &MFI = MF->getFrameInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000834 const HexagonFrameLowering *HFI = HST->getFrameLowering();
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000835 int FX = cast<FrameIndexSDNode>(N)->getIndex();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000836 unsigned StkA = HFI->getStackAlignment();
Matthias Braun941a7052016-07-28 18:40:00 +0000837 unsigned MaxA = MFI.getMaxAlignment();
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000838 SDValue FI = CurDAG->getTargetFrameIndex(FX, MVT::i32);
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000839 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000840 SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000841 SDNode *R = nullptr;
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000842
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000843 // Use PS_fi when:
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000844 // - the object is fixed, or
845 // - there are no objects with higher-than-default alignment, or
846 // - there are no dynamically allocated objects.
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000847 // Otherwise, use PS_fia.
Matthias Braun941a7052016-07-28 18:40:00 +0000848 if (FX < 0 || MaxA <= StkA || !MFI.hasVarSizedObjects()) {
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000849 R = CurDAG->getMachineNode(Hexagon::PS_fi, DL, MVT::i32, FI, Zero);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000850 } else {
851 auto &HMFI = *MF->getInfo<HexagonMachineFunctionInfo>();
852 unsigned AR = HMFI.getStackAlignBaseVReg();
853 SDValue CH = CurDAG->getEntryNode();
854 SDValue Ops[] = { CurDAG->getCopyFromReg(CH, DL, AR, MVT::i32), FI, Zero };
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000855 R = CurDAG->getMachineNode(Hexagon::PS_fia, DL, MVT::i32, Ops);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000856 }
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000857
Justin Bognerec37a022016-05-12 21:46:18 +0000858 ReplaceNode(N, R);
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000859}
860
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000861
Krzysztof Parzyszek5da24e52016-06-27 15:08:22 +0000862void HexagonDAGToDAGISel::SelectBitcast(SDNode *N) {
863 EVT SVT = N->getOperand(0).getValueType();
864 EVT DVT = N->getValueType(0);
865 if (!SVT.isVector() || !DVT.isVector() ||
866 SVT.getVectorElementType() == MVT::i1 ||
867 DVT.getVectorElementType() == MVT::i1 ||
868 SVT.getSizeInBits() != DVT.getSizeInBits()) {
869 SelectCode(N);
870 return;
871 }
872
873 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N,0), N->getOperand(0));
874 CurDAG->RemoveDeadNode(N);
875}
876
877
Justin Bognerec37a022016-05-12 21:46:18 +0000878void HexagonDAGToDAGISel::Select(SDNode *N) {
Krzysztof Parzyszekbe5028a2017-02-24 23:00:40 +0000879 if (N->isMachineOpcode())
880 return N->setNodeId(-1); // Already selected.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000881
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000882 switch (N->getOpcode()) {
Krzysztof Parzyszekbe5028a2017-02-24 23:00:40 +0000883 case ISD::Constant: return SelectConstant(N);
884 case ISD::ConstantFP: return SelectConstantFP(N);
885 case ISD::FrameIndex: return SelectFrameIndex(N);
886 case ISD::BITCAST: return SelectBitcast(N);
887 case ISD::SHL: return SelectSHL(N);
888 case ISD::LOAD: return SelectLoad(N);
889 case ISD::STORE: return SelectStore(N);
Krzysztof Parzyszekbe5028a2017-02-24 23:00:40 +0000890 case ISD::ZERO_EXTEND: return SelectZeroExtend(N);
891 case ISD::INTRINSIC_W_CHAIN: return SelectIntrinsicWChain(N);
892 case ISD::INTRINSIC_WO_CHAIN: return SelectIntrinsicWOChain(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000893 }
894
Justin Bognerec37a022016-05-12 21:46:18 +0000895 SelectCode(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000896}
897
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000898bool HexagonDAGToDAGISel::
Daniel Sanders60f1db02015-03-13 12:45:09 +0000899SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000900 std::vector<SDValue> &OutOps) {
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000901 SDValue Inp = Op, Res;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000902
Daniel Sanders60f1db02015-03-13 12:45:09 +0000903 switch (ConstraintID) {
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000904 default:
905 return true;
Daniel Sanders49f643c2015-03-17 14:37:39 +0000906 case InlineAsm::Constraint_i:
907 case InlineAsm::Constraint_o: // Offsetable.
908 case InlineAsm::Constraint_v: // Not offsetable.
909 case InlineAsm::Constraint_m: // Memory.
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000910 if (SelectAddrFI(Inp, Res))
911 OutOps.push_back(Res);
912 else
913 OutOps.push_back(Inp);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000914 break;
915 }
916
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000917 OutOps.push_back(CurDAG->getTargetConstant(0, SDLoc(Op), MVT::i32));
Jyotsna Vermad9225242013-02-13 21:38:46 +0000918 return false;
919}
Colin LeMahieuc7522f32015-01-14 23:07:36 +0000920
Colin LeMahieu79ec0652015-06-12 19:57:32 +0000921
Krzysztof Parzyszek78c4fcf2017-03-09 16:29:30 +0000922static bool isMemOPCandidate(SDNode *I, SDNode *U) {
923 // I is an operand of U. Check if U is an arithmetic (binary) operation
924 // usable in a memop, where the other operand is a loaded value, and the
925 // result of U is stored in the same location.
926
927 if (!U->hasOneUse())
928 return false;
929 unsigned Opc = U->getOpcode();
930 switch (Opc) {
931 case ISD::ADD:
932 case ISD::SUB:
933 case ISD::AND:
934 case ISD::OR:
935 break;
936 default:
937 return false;
938 }
939
940 SDValue S0 = U->getOperand(0);
941 SDValue S1 = U->getOperand(1);
942 SDValue SY = (S0.getNode() == I) ? S1 : S0;
943
944 SDNode *UUse = *U->use_begin();
945 if (UUse->getNumValues() != 1)
946 return false;
947
948 // Check if one of the inputs to U is a load instruction and the output
949 // is used by a store instruction. If so and they also have the same
950 // base pointer, then don't preoprocess this node sequence as it
951 // can be matched to a memop.
952 SDNode *SYNode = SY.getNode();
953 if (UUse->getOpcode() == ISD::STORE && SYNode->getOpcode() == ISD::LOAD) {
954 SDValue LDBasePtr = cast<MemSDNode>(SYNode)->getBasePtr();
955 SDValue STBasePtr = cast<MemSDNode>(UUse)->getBasePtr();
956 if (LDBasePtr == STBasePtr)
957 return true;
958 }
959 return false;
960}
961
962
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +0000963// Transform: (or (select c x 0) z) -> (select c (or x z) z)
964// (or (select c 0 y) z) -> (select c z (or y z))
965void HexagonDAGToDAGISel::ppSimplifyOrSelect0(std::vector<SDNode*> &&Nodes) {
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000966 SelectionDAG &DAG = *CurDAG;
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000967
Krzysztof Parzyszekf7f70682016-06-22 20:08:27 +0000968 for (auto I : Nodes) {
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000969 if (I->getOpcode() != ISD::OR)
970 continue;
971
972 auto IsZero = [] (const SDValue &V) -> bool {
973 if (ConstantSDNode *SC = dyn_cast<ConstantSDNode>(V.getNode()))
974 return SC->isNullValue();
975 return false;
976 };
977 auto IsSelect0 = [IsZero] (const SDValue &Op) -> bool {
978 if (Op.getOpcode() != ISD::SELECT)
979 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000980 return IsZero(Op.getOperand(1)) || IsZero(Op.getOperand(2));
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000981 };
982
983 SDValue N0 = I->getOperand(0), N1 = I->getOperand(1);
984 EVT VT = I->getValueType(0);
985 bool SelN0 = IsSelect0(N0);
986 SDValue SOp = SelN0 ? N0 : N1;
987 SDValue VOp = SelN0 ? N1 : N0;
988
989 if (SOp.getOpcode() == ISD::SELECT && SOp.getNode()->hasOneUse()) {
990 SDValue SC = SOp.getOperand(0);
991 SDValue SX = SOp.getOperand(1);
992 SDValue SY = SOp.getOperand(2);
993 SDLoc DLS = SOp;
994 if (IsZero(SY)) {
995 SDValue NewOr = DAG.getNode(ISD::OR, DLS, VT, SX, VOp);
996 SDValue NewSel = DAG.getNode(ISD::SELECT, DLS, VT, SC, NewOr, VOp);
997 DAG.ReplaceAllUsesWith(I, NewSel.getNode());
998 } else if (IsZero(SX)) {
999 SDValue NewOr = DAG.getNode(ISD::OR, DLS, VT, SY, VOp);
1000 SDValue NewSel = DAG.getNode(ISD::SELECT, DLS, VT, SC, VOp, NewOr);
1001 DAG.ReplaceAllUsesWith(I, NewSel.getNode());
1002 }
1003 }
1004 }
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001005}
Krzysztof Parzyszekf7f70682016-06-22 20:08:27 +00001006
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001007// Transform: (store ch val (add x (add (shl y c) e)))
1008// to: (store ch val (add x (shl (add y d) c))),
1009// where e = (shl d c) for some integer d.
1010// The purpose of this is to enable generation of loads/stores with
1011// shifted addressing mode, i.e. mem(x+y<<#c). For that, the shift
1012// value c must be 0, 1 or 2.
1013void HexagonDAGToDAGISel::ppAddrReorderAddShl(std::vector<SDNode*> &&Nodes) {
1014 SelectionDAG &DAG = *CurDAG;
1015
Krzysztof Parzyszekf7f70682016-06-22 20:08:27 +00001016 for (auto I : Nodes) {
1017 if (I->getOpcode() != ISD::STORE)
1018 continue;
1019
Krzysztof Parzyszek0d67b102017-02-24 23:34:24 +00001020 // I matched: (store ch val Off)
Krzysztof Parzyszekf7f70682016-06-22 20:08:27 +00001021 SDValue Off = I->getOperand(2);
1022 // Off needs to match: (add x (add (shl y c) (shl d c))))
1023 if (Off.getOpcode() != ISD::ADD)
1024 continue;
1025 // Off matched: (add x T0)
1026 SDValue T0 = Off.getOperand(1);
1027 // T0 needs to match: (add T1 T2):
1028 if (T0.getOpcode() != ISD::ADD)
1029 continue;
1030 // T0 matched: (add T1 T2)
1031 SDValue T1 = T0.getOperand(0);
1032 SDValue T2 = T0.getOperand(1);
1033 // T1 needs to match: (shl y c)
1034 if (T1.getOpcode() != ISD::SHL)
1035 continue;
1036 SDValue C = T1.getOperand(1);
1037 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(C.getNode());
1038 if (CN == nullptr)
1039 continue;
1040 unsigned CV = CN->getZExtValue();
1041 if (CV > 2)
1042 continue;
1043 // T2 needs to match e, where e = (shl d c) for some d.
1044 ConstantSDNode *EN = dyn_cast<ConstantSDNode>(T2.getNode());
1045 if (EN == nullptr)
1046 continue;
1047 unsigned EV = EN->getZExtValue();
1048 if (EV % (1 << CV) != 0)
1049 continue;
1050 unsigned DV = EV / (1 << CV);
1051
1052 // Replace T0 with: (shl (add y d) c)
1053 SDLoc DL = SDLoc(I);
1054 EVT VT = T0.getValueType();
1055 SDValue D = DAG.getConstant(DV, DL, VT);
1056 // NewAdd = (add y d)
1057 SDValue NewAdd = DAG.getNode(ISD::ADD, DL, VT, T1.getOperand(0), D);
1058 // NewShl = (shl NewAdd c)
1059 SDValue NewShl = DAG.getNode(ISD::SHL, DL, VT, NewAdd, C);
1060 ReplaceNode(T0.getNode(), NewShl.getNode());
1061 }
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001062}
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001063
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001064// Transform: (load ch (add x (and (srl y c) Mask)))
1065// to: (load ch (add x (shl (srl y d) d-c)))
1066// where
1067// Mask = 00..0 111..1 0.0
1068// | | +-- d-c 0s, and d-c is 0, 1 or 2.
1069// | +-------- 1s
1070// +-------------- at most c 0s
1071// Motivating example:
1072// DAG combiner optimizes (add x (shl (srl y 5) 2))
1073// to (add x (and (srl y 3) 1FFFFFFC))
1074// which results in a constant-extended and(##...,lsr). This transformation
1075// undoes this simplification for cases where the shl can be folded into
1076// an addressing mode.
1077void HexagonDAGToDAGISel::ppAddrRewriteAndSrl(std::vector<SDNode*> &&Nodes) {
1078 SelectionDAG &DAG = *CurDAG;
1079
Krzysztof Parzyszek0d67b102017-02-24 23:34:24 +00001080 for (SDNode *N : Nodes) {
1081 unsigned Opc = N->getOpcode();
1082 if (Opc != ISD::LOAD && Opc != ISD::STORE)
1083 continue;
1084 SDValue Addr = Opc == ISD::LOAD ? N->getOperand(1) : N->getOperand(2);
1085 // Addr must match: (add x T0)
1086 if (Addr.getOpcode() != ISD::ADD)
1087 continue;
1088 SDValue T0 = Addr.getOperand(1);
1089 // T0 must match: (and T1 Mask)
1090 if (T0.getOpcode() != ISD::AND)
1091 continue;
1092
1093 // We have an AND.
1094 //
1095 // Check the first operand. It must be: (srl y c).
1096 SDValue S = T0.getOperand(0);
1097 if (S.getOpcode() != ISD::SRL)
1098 continue;
1099 ConstantSDNode *SN = dyn_cast<ConstantSDNode>(S.getOperand(1).getNode());
1100 if (SN == nullptr)
1101 continue;
1102 if (SN->getAPIntValue().getBitWidth() != 32)
1103 continue;
1104 uint32_t CV = SN->getZExtValue();
1105
1106 // Check the second operand: the supposed mask.
1107 ConstantSDNode *MN = dyn_cast<ConstantSDNode>(T0.getOperand(1).getNode());
1108 if (MN == nullptr)
1109 continue;
1110 if (MN->getAPIntValue().getBitWidth() != 32)
1111 continue;
1112 uint32_t Mask = MN->getZExtValue();
1113 // Examine the mask.
1114 uint32_t TZ = countTrailingZeros(Mask);
1115 uint32_t M1 = countTrailingOnes(Mask >> TZ);
1116 uint32_t LZ = countLeadingZeros(Mask);
1117 // Trailing zeros + middle ones + leading zeros must equal the width.
1118 if (TZ + M1 + LZ != 32)
1119 continue;
1120 // The number of trailing zeros will be encoded in the addressing mode.
1121 if (TZ > 2)
1122 continue;
1123 // The number of leading zeros must be at most c.
1124 if (LZ > CV)
1125 continue;
1126
1127 // All looks good.
1128 SDValue Y = S.getOperand(0);
1129 EVT VT = Addr.getValueType();
1130 SDLoc dl(S);
1131 // TZ = D-C, so D = TZ+C.
1132 SDValue D = DAG.getConstant(TZ+CV, dl, VT);
1133 SDValue DC = DAG.getConstant(TZ, dl, VT);
1134 SDValue NewSrl = DAG.getNode(ISD::SRL, dl, VT, Y, D);
1135 SDValue NewShl = DAG.getNode(ISD::SHL, dl, VT, NewSrl, DC);
1136 ReplaceNode(T0.getNode(), NewShl.getNode());
1137 }
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001138}
Krzysztof Parzyszek0d67b102017-02-24 23:34:24 +00001139
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001140// Transform: (op ... (zext i1 c) ...) -> (select c (op ... 0 ...)
1141// (op ... 1 ...))
1142void HexagonDAGToDAGISel::ppHoistZextI1(std::vector<SDNode*> &&Nodes) {
1143 SelectionDAG &DAG = *CurDAG;
1144
Krzysztof Parzyszek78c4fcf2017-03-09 16:29:30 +00001145 for (SDNode *N : Nodes) {
1146 unsigned Opc = N->getOpcode();
1147 if (Opc != ISD::ZERO_EXTEND)
1148 continue;
1149 SDValue OpI1 = N->getOperand(0);
1150 EVT OpVT = OpI1.getValueType();
1151 if (!OpVT.isSimple() || OpVT.getSimpleVT() != MVT::i1)
1152 continue;
1153 for (auto I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1154 SDNode *U = *I;
1155 if (U->getNumValues() != 1)
1156 continue;
1157 EVT UVT = U->getValueType(0);
1158 if (!UVT.isSimple() || !UVT.isInteger() || UVT.getSimpleVT() == MVT::i1)
1159 continue;
1160 if (isMemOPCandidate(N, U))
1161 continue;
1162
1163 // Potentially simplifiable operation.
1164 unsigned I1N = I.getOperandNo();
1165 SmallVector<SDValue,2> Ops(U->getNumOperands());
1166 for (unsigned i = 0, n = U->getNumOperands(); i != n; ++i)
1167 Ops[i] = U->getOperand(i);
1168 EVT BVT = Ops[I1N].getValueType();
1169
1170 SDLoc dl(U);
1171 SDValue C0 = DAG.getConstant(0, dl, BVT);
1172 SDValue C1 = DAG.getConstant(1, dl, BVT);
1173 SDValue If0, If1;
1174
1175 if (isa<MachineSDNode>(U)) {
1176 unsigned UseOpc = U->getMachineOpcode();
1177 Ops[I1N] = C0;
1178 If0 = SDValue(DAG.getMachineNode(UseOpc, dl, UVT, Ops), 0);
1179 Ops[I1N] = C1;
1180 If1 = SDValue(DAG.getMachineNode(UseOpc, dl, UVT, Ops), 0);
1181 } else {
1182 unsigned UseOpc = U->getOpcode();
1183 Ops[I1N] = C0;
1184 If0 = DAG.getNode(UseOpc, dl, UVT, Ops);
1185 Ops[I1N] = C1;
1186 If1 = DAG.getNode(UseOpc, dl, UVT, Ops);
1187 }
1188 SDValue Sel = DAG.getNode(ISD::SELECT, dl, UVT, OpI1, If1, If0);
1189 DAG.ReplaceAllUsesWith(U, Sel.getNode());
1190 }
1191 }
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001192}
1193
1194void HexagonDAGToDAGISel::PreprocessISelDAG() {
1195 // Repack all nodes before calling each preprocessing function,
1196 // because each of them can modify the set of nodes.
1197 auto getNodes = [this] () -> std::vector<SDNode*> {
1198 std::vector<SDNode*> T;
1199 T.reserve(CurDAG->allnodes_size());
1200 for (SDNode &N : CurDAG->allnodes())
1201 T.push_back(&N);
1202 return T;
1203 };
1204
1205 // Transform: (or (select c x 0) z) -> (select c (or x z) z)
1206 // (or (select c 0 y) z) -> (select c z (or y z))
1207 ppSimplifyOrSelect0(getNodes());
1208
1209 // Transform: (store ch val (add x (add (shl y c) e)))
1210 // to: (store ch val (add x (shl (add y d) c))),
1211 // where e = (shl d c) for some integer d.
1212 // The purpose of this is to enable generation of loads/stores with
1213 // shifted addressing mode, i.e. mem(x+y<<#c). For that, the shift
1214 // value c must be 0, 1 or 2.
1215 ppAddrReorderAddShl(getNodes());
1216
1217 // Transform: (load ch (add x (and (srl y c) Mask)))
1218 // to: (load ch (add x (shl (srl y d) d-c)))
1219 // where
1220 // Mask = 00..0 111..1 0.0
1221 // | | +-- d-c 0s, and d-c is 0, 1 or 2.
1222 // | +-------- 1s
1223 // +-------------- at most c 0s
1224 // Motivating example:
1225 // DAG combiner optimizes (add x (shl (srl y 5) 2))
1226 // to (add x (and (srl y 3) 1FFFFFFC))
1227 // which results in a constant-extended and(##...,lsr). This transformation
1228 // undoes this simplification for cases where the shl can be folded into
1229 // an addressing mode.
1230 ppAddrRewriteAndSrl(getNodes());
1231
1232 // Transform: (op ... (zext i1 c) ...) -> (select c (op ... 0 ...)
1233 // (op ... 1 ...))
1234 ppHoistZextI1(getNodes());
Krzysztof Parzyszek78c4fcf2017-03-09 16:29:30 +00001235
1236 DEBUG_WITH_TYPE("isel", {
1237 dbgs() << "Preprocessed (Hexagon) selection DAG:";
1238 CurDAG->dump();
1239 });
1240
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001241 if (EnableAddressRebalancing) {
1242 rebalanceAddressTrees();
1243
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001244 DEBUG_WITH_TYPE("isel", {
1245 dbgs() << "Address tree balanced selection DAG:";
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001246 CurDAG->dump();
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001247 });
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001248 }
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +00001249}
1250
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001251void HexagonDAGToDAGISel::EmitFunctionEntryCode() {
1252 auto &HST = static_cast<const HexagonSubtarget&>(MF->getSubtarget());
1253 auto &HFI = *HST.getFrameLowering();
1254 if (!HFI.needsAligna(*MF))
1255 return;
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +00001256
Matthias Braun941a7052016-07-28 18:40:00 +00001257 MachineFrameInfo &MFI = MF->getFrameInfo();
Duncan P. N. Exon Smitha72c6e22015-10-20 00:46:39 +00001258 MachineBasicBlock *EntryBB = &MF->front();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001259 unsigned AR = FuncInfo->CreateReg(MVT::i32);
Matthias Braun941a7052016-07-28 18:40:00 +00001260 unsigned MaxA = MFI.getMaxAlignment();
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +00001261 BuildMI(EntryBB, DebugLoc(), HII->get(Hexagon::PS_aligna), AR)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001262 .addImm(MaxA);
1263 MF->getInfo<HexagonMachineFunctionInfo>()->setStackAlignBaseVReg(AR);
1264}
1265
1266// Match a frame index that can be used in an addressing mode.
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001267bool HexagonDAGToDAGISel::SelectAddrFI(SDValue &N, SDValue &R) {
Colin LeMahieuc7522f32015-01-14 23:07:36 +00001268 if (N.getOpcode() != ISD::FrameIndex)
1269 return false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001270 auto &HFI = *HST->getFrameLowering();
Matthias Braun941a7052016-07-28 18:40:00 +00001271 MachineFrameInfo &MFI = MF->getFrameInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001272 int FX = cast<FrameIndexSDNode>(N)->getIndex();
Matthias Braun941a7052016-07-28 18:40:00 +00001273 if (!MFI.isFixedObjectIndex(FX) && HFI.needsAligna(*MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001274 return false;
1275 R = CurDAG->getTargetFrameIndex(FX, MVT::i32);
Colin LeMahieuc7522f32015-01-14 23:07:36 +00001276 return true;
1277}
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001278
Colin LeMahieu987b0942015-02-04 20:38:01 +00001279inline bool HexagonDAGToDAGISel::SelectAddrGA(SDValue &N, SDValue &R) {
1280 return SelectGlobalAddress(N, R, false);
1281}
1282
Colin LeMahieu51491352015-02-04 22:36:28 +00001283inline bool HexagonDAGToDAGISel::SelectAddrGP(SDValue &N, SDValue &R) {
1284 return SelectGlobalAddress(N, R, true);
1285}
1286
Colin LeMahieu987b0942015-02-04 20:38:01 +00001287bool HexagonDAGToDAGISel::SelectGlobalAddress(SDValue &N, SDValue &R,
1288 bool UseGP) {
1289 switch (N.getOpcode()) {
1290 case ISD::ADD: {
1291 SDValue N0 = N.getOperand(0);
1292 SDValue N1 = N.getOperand(1);
1293 unsigned GAOpc = N0.getOpcode();
1294 if (UseGP && GAOpc != HexagonISD::CONST32_GP)
1295 return false;
1296 if (!UseGP && GAOpc != HexagonISD::CONST32)
1297 return false;
1298 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N1)) {
1299 SDValue Addr = N0.getOperand(0);
1300 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Addr)) {
1301 if (GA->getOpcode() == ISD::TargetGlobalAddress) {
1302 uint64_t NewOff = GA->getOffset() + (uint64_t)Const->getSExtValue();
1303 R = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(Const),
1304 N.getValueType(), NewOff);
1305 return true;
1306 }
1307 }
1308 }
1309 break;
1310 }
1311 case HexagonISD::CONST32:
1312 // The operand(0) of CONST32 is TargetGlobalAddress, which is what we
1313 // want in the instruction.
1314 if (!UseGP)
1315 R = N.getOperand(0);
1316 return !UseGP;
1317 case HexagonISD::CONST32_GP:
1318 if (UseGP)
1319 R = N.getOperand(0);
1320 return UseGP;
1321 default:
1322 return false;
1323 }
1324
1325 return false;
1326}
1327
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001328bool HexagonDAGToDAGISel::DetectUseSxtw(SDValue &N, SDValue &R) {
1329 // This (complex pattern) function is meant to detect a sign-extension
1330 // i32->i64 on a per-operand basis. This would allow writing single
1331 // patterns that would cover a number of combinations of different ways
1332 // a sign-extensions could be written. For example:
1333 // (mul (DetectUseSxtw x) (DetectUseSxtw y)) -> (M2_dpmpyss_s0 x y)
1334 // could match either one of these:
1335 // (mul (sext x) (sext_inreg y))
1336 // (mul (sext-load *p) (sext_inreg y))
1337 // (mul (sext_inreg x) (sext y))
1338 // etc.
1339 //
1340 // The returned value will have type i64 and its low word will
1341 // contain the value being extended. The high bits are not specified.
1342 // The returned type is i64 because the original type of N was i64,
1343 // but the users of this function should only use the low-word of the
1344 // result, e.g.
1345 // (mul sxtw:x, sxtw:y) -> (M2_dpmpyss_s0 (LoReg sxtw:x), (LoReg sxtw:y))
1346
1347 if (N.getValueType() != MVT::i64)
1348 return false;
1349 EVT SrcVT;
1350 unsigned Opc = N.getOpcode();
1351 switch (Opc) {
1352 case ISD::SIGN_EXTEND:
1353 case ISD::SIGN_EXTEND_INREG: {
1354 // sext_inreg has the source type as a separate operand.
1355 EVT T = Opc == ISD::SIGN_EXTEND
1356 ? N.getOperand(0).getValueType()
1357 : cast<VTSDNode>(N.getOperand(1))->getVT();
1358 if (T.getSizeInBits() != 32)
1359 return false;
1360 R = N.getOperand(0);
1361 break;
1362 }
1363 case ISD::LOAD: {
1364 LoadSDNode *L = cast<LoadSDNode>(N);
1365 if (L->getExtensionType() != ISD::SEXTLOAD)
1366 return false;
1367 // All extending loads extend to i32, so even if the value in
1368 // memory is shorter than 32 bits, it will be i32 after the load.
1369 if (L->getMemoryVT().getSizeInBits() > 32)
1370 return false;
1371 R = N;
1372 break;
1373 }
1374 default:
1375 return false;
1376 }
1377 EVT RT = R.getValueType();
1378 if (RT == MVT::i64)
1379 return true;
1380 assert(RT == MVT::i32);
1381 // This is only to produce a value of type i64. Do not rely on the
1382 // high bits produced by this.
1383 const SDLoc &dl(N);
1384 SDValue Ops[] = {
1385 CurDAG->getTargetConstant(Hexagon::DoubleRegsRegClassID, dl, MVT::i32),
1386 R, CurDAG->getTargetConstant(Hexagon::isub_hi, dl, MVT::i32),
1387 R, CurDAG->getTargetConstant(Hexagon::isub_lo, dl, MVT::i32)
1388 };
1389 SDNode *T = CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl,
1390 MVT::i64, Ops);
1391 R = SDValue(T, 0);
1392 return true;
1393}
1394
1395bool HexagonDAGToDAGISel::keepsLowBits(const SDValue &Val, unsigned NumBits,
1396 SDValue &Src) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001397 unsigned Opc = Val.getOpcode();
1398 switch (Opc) {
1399 case ISD::SIGN_EXTEND:
1400 case ISD::ZERO_EXTEND:
1401 case ISD::ANY_EXTEND: {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001402 const SDValue &Op0 = Val.getOperand(0);
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001403 EVT T = Op0.getValueType();
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001404 if (T.isInteger() && T.getSizeInBits() == NumBits) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001405 Src = Op0;
1406 return true;
1407 }
1408 break;
1409 }
1410 case ISD::SIGN_EXTEND_INREG:
1411 case ISD::AssertSext:
1412 case ISD::AssertZext:
1413 if (Val.getOperand(0).getValueType().isInteger()) {
1414 VTSDNode *T = cast<VTSDNode>(Val.getOperand(1));
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001415 if (T->getVT().getSizeInBits() == NumBits) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001416 Src = Val.getOperand(0);
1417 return true;
1418 }
1419 }
1420 break;
1421 case ISD::AND: {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001422 // Check if this is an AND with NumBits of lower bits set to 1.
1423 uint64_t Mask = (1 << NumBits) - 1;
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001424 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(0))) {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001425 if (C->getZExtValue() == Mask) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001426 Src = Val.getOperand(1);
1427 return true;
1428 }
1429 }
1430 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(1))) {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001431 if (C->getZExtValue() == Mask) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001432 Src = Val.getOperand(0);
1433 return true;
1434 }
1435 }
1436 break;
1437 }
1438 case ISD::OR:
1439 case ISD::XOR: {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001440 // OR/XOR with the lower NumBits bits set to 0.
1441 uint64_t Mask = (1 << NumBits) - 1;
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001442 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(0))) {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001443 if ((C->getZExtValue() & Mask) == 0) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001444 Src = Val.getOperand(1);
1445 return true;
1446 }
1447 }
1448 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(1))) {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001449 if ((C->getZExtValue() & Mask) == 0) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001450 Src = Val.getOperand(0);
1451 return true;
1452 }
1453 }
1454 }
1455 default:
1456 break;
1457 }
1458 return false;
1459}
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001460
Krzysztof Parzyszekbba0bf72016-07-15 15:35:52 +00001461
Krzysztof Parzyszekb16a4e52016-11-14 20:53:09 +00001462bool HexagonDAGToDAGISel::isOrEquivalentToAdd(const SDNode *N) const {
Krzysztof Parzyszekbba0bf72016-07-15 15:35:52 +00001463 assert(N->getOpcode() == ISD::OR);
1464 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
1465 assert(C);
1466
1467 // Detect when "or" is used to add an offset to a stack object.
1468 if (auto *FN = dyn_cast<FrameIndexSDNode>(N->getOperand(0))) {
Matthias Braun941a7052016-07-28 18:40:00 +00001469 MachineFrameInfo &MFI = MF->getFrameInfo();
1470 unsigned A = MFI.getObjectAlignment(FN->getIndex());
Krzysztof Parzyszekbba0bf72016-07-15 15:35:52 +00001471 assert(isPowerOf2_32(A));
1472 int32_t Off = C->getSExtValue();
1473 // If the alleged offset fits in the zero bits guaranteed by
1474 // the alignment, then this or is really an add.
1475 return (Off >= 0) && (((A-1) & Off) == unsigned(Off));
1476 }
1477 return false;
1478}
1479
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001480bool HexagonDAGToDAGISel::isAlignedMemNode(const MemSDNode *N) const {
1481 return N->getAlignment() >= N->getMemoryVT().getStoreSize();
1482}
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001483
Krzysztof Parzyszekb3a8d202017-06-13 17:10:16 +00001484bool HexagonDAGToDAGISel::isSmallStackStore(const StoreSDNode *N) const {
1485 unsigned StackSize = MF->getFrameInfo().estimateStackSize(*MF);
1486 switch (N->getMemoryVT().getStoreSize()) {
1487 case 1:
1488 return StackSize <= 56; // 1*2^6 - 8
1489 case 2:
1490 return StackSize <= 120; // 2*2^6 - 8
1491 case 4:
1492 return StackSize <= 248; // 4*2^6 - 8
1493 default:
1494 return false;
1495 }
1496}
1497
Krzysztof Parzyszek2839b292016-11-05 21:44:50 +00001498// Return true when the given node fits in a positive half word.
1499bool HexagonDAGToDAGISel::isPositiveHalfWord(const SDNode *N) const {
1500 if (const ConstantSDNode *CN = dyn_cast<const ConstantSDNode>(N)) {
1501 int64_t V = CN->getSExtValue();
1502 return V > 0 && isInt<16>(V);
1503 }
1504 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG) {
1505 const VTSDNode *VN = dyn_cast<const VTSDNode>(N->getOperand(1));
1506 return VN->getVT().getSizeInBits() <= 16;
1507 }
1508 return false;
1509}
1510
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001511////////////////////////////////////////////////////////////////////////////////
1512// Rebalancing of address calculation trees
1513
1514static bool isOpcodeHandled(const SDNode *N) {
1515 switch (N->getOpcode()) {
1516 case ISD::ADD:
1517 case ISD::MUL:
1518 return true;
1519 case ISD::SHL:
1520 // We only handle constant shifts because these can be easily flattened
1521 // into multiplications by 2^Op1.
1522 return isa<ConstantSDNode>(N->getOperand(1).getNode());
1523 default:
1524 return false;
1525 }
1526}
1527
1528/// \brief Return the weight of an SDNode
1529int HexagonDAGToDAGISel::getWeight(SDNode *N) {
1530 if (!isOpcodeHandled(N))
1531 return 1;
1532 assert(RootWeights.count(N) && "Cannot get weight of unseen root!");
1533 assert(RootWeights[N] != -1 && "Cannot get weight of unvisited root!");
1534 assert(RootWeights[N] != -2 && "Cannot get weight of RAWU'd root!");
1535 return RootWeights[N];
1536}
1537
1538int HexagonDAGToDAGISel::getHeight(SDNode *N) {
1539 if (!isOpcodeHandled(N))
1540 return 0;
1541 assert(RootWeights.count(N) && RootWeights[N] >= 0 &&
1542 "Cannot query height of unvisited/RAUW'd node!");
1543 return RootHeights[N];
1544}
1545
Benjamin Kramerb7d33112016-08-06 11:13:10 +00001546namespace {
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001547struct WeightedLeaf {
1548 SDValue Value;
1549 int Weight;
1550 int InsertionOrder;
1551
1552 WeightedLeaf() : Value(SDValue()) { }
1553
1554 WeightedLeaf(SDValue Value, int Weight, int InsertionOrder) :
1555 Value(Value), Weight(Weight), InsertionOrder(InsertionOrder) {
1556 assert(Weight >= 0 && "Weight must be >= 0");
1557 }
1558
1559 static bool Compare(const WeightedLeaf &A, const WeightedLeaf &B) {
1560 assert(A.Value.getNode() && B.Value.getNode());
1561 return A.Weight == B.Weight ?
1562 (A.InsertionOrder > B.InsertionOrder) :
1563 (A.Weight > B.Weight);
1564 }
1565};
1566
1567/// A specialized priority queue for WeigthedLeaves. It automatically folds
1568/// constants and allows removal of non-top elements while maintaining the
1569/// priority order.
1570class LeafPrioQueue {
1571 SmallVector<WeightedLeaf, 8> Q;
1572 bool HaveConst;
1573 WeightedLeaf ConstElt;
1574 unsigned Opcode;
1575
1576public:
1577 bool empty() {
1578 return (!HaveConst && Q.empty());
1579 }
1580
1581 size_t size() {
1582 return Q.size() + HaveConst;
1583 }
1584
1585 bool hasConst() {
1586 return HaveConst;
1587 }
1588
1589 const WeightedLeaf &top() {
1590 if (HaveConst)
1591 return ConstElt;
1592 return Q.front();
1593 }
1594
1595 WeightedLeaf pop() {
1596 if (HaveConst) {
1597 HaveConst = false;
1598 return ConstElt;
1599 }
1600 std::pop_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1601 return Q.pop_back_val();
1602 }
1603
1604 void push(WeightedLeaf L, bool SeparateConst=true) {
1605 if (!HaveConst && SeparateConst && isa<ConstantSDNode>(L.Value)) {
1606 if (Opcode == ISD::MUL &&
1607 cast<ConstantSDNode>(L.Value)->getSExtValue() == 1)
1608 return;
1609 if (Opcode == ISD::ADD &&
1610 cast<ConstantSDNode>(L.Value)->getSExtValue() == 0)
1611 return;
1612
1613 HaveConst = true;
1614 ConstElt = L;
1615 } else {
1616 Q.push_back(L);
1617 std::push_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1618 }
1619 }
1620
1621 /// Push L to the bottom of the queue regardless of its weight. If L is
1622 /// constant, it will not be folded with other constants in the queue.
1623 void pushToBottom(WeightedLeaf L) {
1624 L.Weight = 1000;
1625 push(L, false);
1626 }
1627
1628 /// Search for a SHL(x, [<=MaxAmount]) subtree in the queue, return the one of
1629 /// lowest weight and remove it from the queue.
1630 WeightedLeaf findSHL(uint64_t MaxAmount);
1631
1632 WeightedLeaf findMULbyConst();
1633
1634 LeafPrioQueue(unsigned Opcode) :
1635 HaveConst(false), Opcode(Opcode) { }
1636};
Benjamin Kramerb7d33112016-08-06 11:13:10 +00001637} // end anonymous namespace
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001638
1639WeightedLeaf LeafPrioQueue::findSHL(uint64_t MaxAmount) {
1640 int ResultPos;
1641 WeightedLeaf Result;
1642
1643 for (int Pos = 0, End = Q.size(); Pos != End; ++Pos) {
1644 const WeightedLeaf &L = Q[Pos];
1645 const SDValue &Val = L.Value;
1646 if (Val.getOpcode() != ISD::SHL ||
1647 !isa<ConstantSDNode>(Val.getOperand(1)) ||
1648 Val.getConstantOperandVal(1) > MaxAmount)
1649 continue;
1650 if (!Result.Value.getNode() || Result.Weight > L.Weight ||
1651 (Result.Weight == L.Weight && Result.InsertionOrder > L.InsertionOrder))
1652 {
1653 Result = L;
1654 ResultPos = Pos;
1655 }
1656 }
1657
1658 if (Result.Value.getNode()) {
1659 Q.erase(&Q[ResultPos]);
1660 std::make_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1661 }
1662
1663 return Result;
1664}
1665
1666WeightedLeaf LeafPrioQueue::findMULbyConst() {
1667 int ResultPos;
1668 WeightedLeaf Result;
1669
1670 for (int Pos = 0, End = Q.size(); Pos != End; ++Pos) {
1671 const WeightedLeaf &L = Q[Pos];
1672 const SDValue &Val = L.Value;
1673 if (Val.getOpcode() != ISD::MUL ||
1674 !isa<ConstantSDNode>(Val.getOperand(1)) ||
1675 Val.getConstantOperandVal(1) > 127)
1676 continue;
1677 if (!Result.Value.getNode() || Result.Weight > L.Weight ||
1678 (Result.Weight == L.Weight && Result.InsertionOrder > L.InsertionOrder))
1679 {
1680 Result = L;
1681 ResultPos = Pos;
1682 }
1683 }
1684
1685 if (Result.Value.getNode()) {
1686 Q.erase(&Q[ResultPos]);
1687 std::make_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1688 }
1689
1690 return Result;
1691}
1692
1693SDValue HexagonDAGToDAGISel::getMultiplierForSHL(SDNode *N) {
Simon Pilgrim7c858622016-07-29 18:43:59 +00001694 uint64_t MulFactor = 1ull << N->getConstantOperandVal(1);
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001695 return CurDAG->getConstant(MulFactor, SDLoc(N),
1696 N->getOperand(1).getValueType());
1697}
1698
1699/// @returns the value x for which 2^x is a factor of Val
1700static unsigned getPowerOf2Factor(SDValue Val) {
1701 if (Val.getOpcode() == ISD::MUL) {
1702 unsigned MaxFactor = 0;
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00001703 for (int i = 0; i < 2; ++i) {
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001704 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(i));
1705 if (!C)
1706 continue;
1707 const APInt &CInt = C->getAPIntValue();
1708 if (CInt.getBoolValue())
1709 MaxFactor = CInt.countTrailingZeros();
1710 }
1711 return MaxFactor;
1712 }
1713 if (Val.getOpcode() == ISD::SHL) {
1714 if (!isa<ConstantSDNode>(Val.getOperand(1).getNode()))
1715 return 0;
1716 return (unsigned) Val.getConstantOperandVal(1);
1717 }
1718
1719 return 0;
1720}
1721
1722/// @returns true if V>>Amount will eliminate V's operation on its child
1723static bool willShiftRightEliminate(SDValue V, unsigned Amount) {
1724 if (V.getOpcode() == ISD::MUL) {
1725 SDValue Ops[] = { V.getOperand(0), V.getOperand(1) };
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00001726 for (int i = 0; i < 2; ++i)
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001727 if (isa<ConstantSDNode>(Ops[i].getNode()) &&
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00001728 V.getConstantOperandVal(i) % (1ULL << Amount) == 0) {
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001729 uint64_t NewConst = V.getConstantOperandVal(i) >> Amount;
1730 return (NewConst == 1);
1731 }
1732 } else if (V.getOpcode() == ISD::SHL) {
1733 return (Amount == V.getConstantOperandVal(1));
1734 }
1735
1736 return false;
1737}
1738
1739SDValue HexagonDAGToDAGISel::factorOutPowerOf2(SDValue V, unsigned Power) {
1740 SDValue Ops[] = { V.getOperand(0), V.getOperand(1) };
1741 if (V.getOpcode() == ISD::MUL) {
1742 for (int i=0; i < 2; ++i) {
1743 if (isa<ConstantSDNode>(Ops[i].getNode()) &&
1744 V.getConstantOperandVal(i) % ((uint64_t)1 << Power) == 0) {
1745 uint64_t NewConst = V.getConstantOperandVal(i) >> Power;
1746 if (NewConst == 1)
1747 return Ops[!i];
1748 Ops[i] = CurDAG->getConstant(NewConst,
1749 SDLoc(V), V.getValueType());
1750 break;
1751 }
1752 }
1753 } else if (V.getOpcode() == ISD::SHL) {
1754 uint64_t ShiftAmount = V.getConstantOperandVal(1);
1755 if (ShiftAmount == Power)
1756 return Ops[0];
1757 Ops[1] = CurDAG->getConstant(ShiftAmount - Power,
1758 SDLoc(V), V.getValueType());
1759 }
1760
1761 return CurDAG->getNode(V.getOpcode(), SDLoc(V), V.getValueType(), Ops);
1762}
1763
1764static bool isTargetConstant(const SDValue &V) {
1765 return V.getOpcode() == HexagonISD::CONST32 ||
1766 V.getOpcode() == HexagonISD::CONST32_GP;
1767}
1768
1769unsigned HexagonDAGToDAGISel::getUsesInFunction(const Value *V) {
1770 if (GAUsesInFunction.count(V))
1771 return GAUsesInFunction[V];
1772
1773 unsigned Result = 0;
1774 const Function *CurF = CurDAG->getMachineFunction().getFunction();
1775 for (const User *U : V->users()) {
1776 if (isa<Instruction>(U) &&
1777 cast<Instruction>(U)->getParent()->getParent() == CurF)
1778 ++Result;
1779 }
1780
1781 GAUsesInFunction[V] = Result;
1782
1783 return Result;
1784}
1785
1786/// Note - After calling this, N may be dead. It may have been replaced by a
1787/// new node, so always use the returned value in place of N.
1788///
1789/// @returns The SDValue taking the place of N (which could be N if it is
1790/// unchanged)
1791SDValue HexagonDAGToDAGISel::balanceSubTree(SDNode *N, bool TopLevel) {
1792 assert(RootWeights.count(N) && "Cannot balance non-root node.");
1793 assert(RootWeights[N] != -2 && "This node was RAUW'd!");
1794 assert(!TopLevel || N->getOpcode() == ISD::ADD);
1795
1796 // Return early if this node was already visited
1797 if (RootWeights[N] != -1)
1798 return SDValue(N, 0);
1799
1800 assert(isOpcodeHandled(N));
1801
1802 SDValue Op0 = N->getOperand(0);
1803 SDValue Op1 = N->getOperand(1);
1804
1805 // Return early if the operands will remain unchanged or are all roots
1806 if ((!isOpcodeHandled(Op0.getNode()) || RootWeights.count(Op0.getNode())) &&
1807 (!isOpcodeHandled(Op1.getNode()) || RootWeights.count(Op1.getNode()))) {
1808 SDNode *Op0N = Op0.getNode();
1809 int Weight;
1810 if (isOpcodeHandled(Op0N) && RootWeights[Op0N] == -1) {
1811 Weight = getWeight(balanceSubTree(Op0N).getNode());
1812 // Weight = calculateWeight(Op0N);
1813 } else
1814 Weight = getWeight(Op0N);
1815
1816 SDNode *Op1N = N->getOperand(1).getNode(); // Op1 may have been RAUWd
1817 if (isOpcodeHandled(Op1N) && RootWeights[Op1N] == -1) {
1818 Weight += getWeight(balanceSubTree(Op1N).getNode());
1819 // Weight += calculateWeight(Op1N);
1820 } else
1821 Weight += getWeight(Op1N);
1822
1823 RootWeights[N] = Weight;
1824 RootHeights[N] = std::max(getHeight(N->getOperand(0).getNode()),
1825 getHeight(N->getOperand(1).getNode())) + 1;
1826
1827 DEBUG(dbgs() << "--> No need to balance root (Weight=" << Weight
1828 << " Height=" << RootHeights[N] << "): ");
1829 DEBUG(N->dump());
1830
1831 return SDValue(N, 0);
1832 }
1833
1834 DEBUG(dbgs() << "** Balancing root node: ");
1835 DEBUG(N->dump());
1836
1837 unsigned NOpcode = N->getOpcode();
1838
1839 LeafPrioQueue Leaves(NOpcode);
1840 SmallVector<SDValue, 4> Worklist;
1841 Worklist.push_back(SDValue(N, 0));
1842
1843 // SHL nodes will be converted to MUL nodes
1844 if (NOpcode == ISD::SHL)
1845 NOpcode = ISD::MUL;
1846
1847 bool CanFactorize = false;
1848 WeightedLeaf Mul1, Mul2;
1849 unsigned MaxPowerOf2 = 0;
1850 WeightedLeaf GA;
1851
1852 // Do not try to factor out a shift if there is already a shift at the tip of
1853 // the tree.
1854 bool HaveTopLevelShift = false;
1855 if (TopLevel &&
1856 ((isOpcodeHandled(Op0.getNode()) && Op0.getOpcode() == ISD::SHL &&
1857 Op0.getConstantOperandVal(1) < 4) ||
1858 (isOpcodeHandled(Op1.getNode()) && Op1.getOpcode() == ISD::SHL &&
1859 Op1.getConstantOperandVal(1) < 4)))
1860 HaveTopLevelShift = true;
1861
1862 // Flatten the subtree into an ordered list of leaves; at the same time
1863 // determine whether the tree is already balanced.
1864 int InsertionOrder = 0;
1865 SmallDenseMap<SDValue, int> NodeHeights;
1866 bool Imbalanced = false;
1867 int CurrentWeight = 0;
1868 while (!Worklist.empty()) {
1869 SDValue Child = Worklist.pop_back_val();
1870
1871 if (Child.getNode() != N && RootWeights.count(Child.getNode())) {
1872 // CASE 1: Child is a root note
1873
1874 int Weight = RootWeights[Child.getNode()];
1875 if (Weight == -1) {
1876 Child = balanceSubTree(Child.getNode());
1877 // calculateWeight(Child.getNode());
1878 Weight = getWeight(Child.getNode());
1879 } else if (Weight == -2) {
1880 // Whoops, this node was RAUWd by one of the balanceSubTree calls we
1881 // made. Our worklist isn't up to date anymore.
1882 // Restart the whole process.
1883 DEBUG(dbgs() << "--> Subtree was RAUWd. Restarting...\n");
1884 return balanceSubTree(N, TopLevel);
1885 }
1886
1887 NodeHeights[Child] = 1;
1888 CurrentWeight += Weight;
1889
1890 unsigned PowerOf2;
1891 if (TopLevel && !CanFactorize && !HaveTopLevelShift &&
1892 (Child.getOpcode() == ISD::MUL || Child.getOpcode() == ISD::SHL) &&
1893 Child.hasOneUse() && (PowerOf2 = getPowerOf2Factor(Child))) {
1894 // Try to identify two factorizable MUL/SHL children greedily. Leave
1895 // them out of the priority queue for now so we can deal with them
1896 // after.
1897 if (!Mul1.Value.getNode()) {
1898 Mul1 = WeightedLeaf(Child, Weight, InsertionOrder++);
1899 MaxPowerOf2 = PowerOf2;
1900 } else {
1901 Mul2 = WeightedLeaf(Child, Weight, InsertionOrder++);
1902 MaxPowerOf2 = std::min(MaxPowerOf2, PowerOf2);
1903
1904 // Our addressing modes can only shift by a maximum of 3
1905 if (MaxPowerOf2 > 3)
1906 MaxPowerOf2 = 3;
1907
1908 CanFactorize = true;
1909 }
1910 } else
1911 Leaves.push(WeightedLeaf(Child, Weight, InsertionOrder++));
1912 } else if (!isOpcodeHandled(Child.getNode())) {
1913 // CASE 2: Child is an unhandled kind of node (e.g. constant)
1914 int Weight = getWeight(Child.getNode());
1915
1916 NodeHeights[Child] = getHeight(Child.getNode());
1917 CurrentWeight += Weight;
1918
1919 if (isTargetConstant(Child) && !GA.Value.getNode())
1920 GA = WeightedLeaf(Child, Weight, InsertionOrder++);
1921 else
1922 Leaves.push(WeightedLeaf(Child, Weight, InsertionOrder++));
1923 } else {
1924 // CASE 3: Child is a subtree of same opcode
1925 // Visit children first, then flatten.
1926 unsigned ChildOpcode = Child.getOpcode();
1927 assert(ChildOpcode == NOpcode ||
1928 (NOpcode == ISD::MUL && ChildOpcode == ISD::SHL));
1929
1930 // Convert SHL to MUL
1931 SDValue Op1;
1932 if (ChildOpcode == ISD::SHL)
1933 Op1 = getMultiplierForSHL(Child.getNode());
1934 else
1935 Op1 = Child->getOperand(1);
1936
1937 if (!NodeHeights.count(Op1) || !NodeHeights.count(Child->getOperand(0))) {
1938 assert(!NodeHeights.count(Child) && "Parent visited before children?");
1939 // Visit children first, then re-visit this node
1940 Worklist.push_back(Child);
1941 Worklist.push_back(Op1);
1942 Worklist.push_back(Child->getOperand(0));
1943 } else {
1944 // Back at this node after visiting the children
1945 if (std::abs(NodeHeights[Op1] - NodeHeights[Child->getOperand(0)]) > 1)
1946 Imbalanced = true;
1947
1948 NodeHeights[Child] = std::max(NodeHeights[Op1],
1949 NodeHeights[Child->getOperand(0)]) + 1;
1950 }
1951 }
1952 }
1953
1954 DEBUG(dbgs() << "--> Current height=" << NodeHeights[SDValue(N, 0)]
1955 << " weight=" << CurrentWeight << " imbalanced="
1956 << Imbalanced << "\n");
1957
1958 // Transform MUL(x, C * 2^Y) + SHL(z, Y) -> SHL(ADD(MUL(x, C), z), Y)
1959 // This factors out a shift in order to match memw(a<<Y+b).
1960 if (CanFactorize && (willShiftRightEliminate(Mul1.Value, MaxPowerOf2) ||
1961 willShiftRightEliminate(Mul2.Value, MaxPowerOf2))) {
1962 DEBUG(dbgs() << "--> Found common factor for two MUL children!\n");
1963 int Weight = Mul1.Weight + Mul2.Weight;
1964 int Height = std::max(NodeHeights[Mul1.Value], NodeHeights[Mul2.Value]) + 1;
1965 SDValue Mul1Factored = factorOutPowerOf2(Mul1.Value, MaxPowerOf2);
1966 SDValue Mul2Factored = factorOutPowerOf2(Mul2.Value, MaxPowerOf2);
1967 SDValue Sum = CurDAG->getNode(ISD::ADD, SDLoc(N), Mul1.Value.getValueType(),
1968 Mul1Factored, Mul2Factored);
1969 SDValue Const = CurDAG->getConstant(MaxPowerOf2, SDLoc(N),
1970 Mul1.Value.getValueType());
1971 SDValue New = CurDAG->getNode(ISD::SHL, SDLoc(N), Mul1.Value.getValueType(),
1972 Sum, Const);
1973 NodeHeights[New] = Height;
1974 Leaves.push(WeightedLeaf(New, Weight, Mul1.InsertionOrder));
1975 } else if (Mul1.Value.getNode()) {
1976 // We failed to factorize two MULs, so now the Muls are left outside the
1977 // queue... add them back.
1978 Leaves.push(Mul1);
1979 if (Mul2.Value.getNode())
1980 Leaves.push(Mul2);
1981 CanFactorize = false;
1982 }
1983
1984 // Combine GA + Constant -> GA+Offset, but only if GA is not used elsewhere
1985 // and the root node itself is not used more than twice. This reduces the
1986 // amount of additional constant extenders introduced by this optimization.
1987 bool CombinedGA = false;
1988 if (NOpcode == ISD::ADD && GA.Value.getNode() && Leaves.hasConst() &&
1989 GA.Value.hasOneUse() && N->use_size() < 3) {
1990 GlobalAddressSDNode *GANode =
1991 cast<GlobalAddressSDNode>(GA.Value.getOperand(0));
1992 ConstantSDNode *Offset = cast<ConstantSDNode>(Leaves.top().Value);
1993
1994 if (getUsesInFunction(GANode->getGlobal()) == 1 && Offset->hasOneUse() &&
1995 getTargetLowering()->isOffsetFoldingLegal(GANode)) {
1996 DEBUG(dbgs() << "--> Combining GA and offset (" << Offset->getSExtValue()
1997 << "): ");
1998 DEBUG(GANode->dump());
1999
2000 SDValue NewTGA =
2001 CurDAG->getTargetGlobalAddress(GANode->getGlobal(), SDLoc(GA.Value),
2002 GANode->getValueType(0),
2003 GANode->getOffset() + (uint64_t)Offset->getSExtValue());
2004 GA.Value = CurDAG->getNode(GA.Value.getOpcode(), SDLoc(GA.Value),
2005 GA.Value.getValueType(), NewTGA);
2006 GA.Weight += Leaves.top().Weight;
2007
2008 NodeHeights[GA.Value] = getHeight(GA.Value.getNode());
2009 CombinedGA = true;
2010
2011 Leaves.pop(); // Remove the offset constant from the queue
2012 }
2013 }
2014
2015 if ((RebalanceOnlyForOptimizations && !CanFactorize && !CombinedGA) ||
2016 (RebalanceOnlyImbalancedTrees && !Imbalanced)) {
2017 RootWeights[N] = CurrentWeight;
2018 RootHeights[N] = NodeHeights[SDValue(N, 0)];
2019
2020 return SDValue(N, 0);
2021 }
2022
2023 // Combine GA + SHL(x, C<=31) so we will match Rx=add(#u8,asl(Rx,#U5))
2024 if (NOpcode == ISD::ADD && GA.Value.getNode()) {
2025 WeightedLeaf SHL = Leaves.findSHL(31);
2026 if (SHL.Value.getNode()) {
2027 int Height = std::max(NodeHeights[GA.Value], NodeHeights[SHL.Value]) + 1;
2028 GA.Value = CurDAG->getNode(ISD::ADD, SDLoc(GA.Value),
2029 GA.Value.getValueType(),
2030 GA.Value, SHL.Value);
2031 GA.Weight = SHL.Weight; // Specifically ignore the GA weight here
2032 NodeHeights[GA.Value] = Height;
2033 }
2034 }
2035
2036 if (GA.Value.getNode())
2037 Leaves.push(GA);
2038
2039 // If this is the top level and we haven't factored out a shift, we should try
2040 // to move a constant to the bottom to match addressing modes like memw(rX+C)
2041 if (TopLevel && !CanFactorize && Leaves.hasConst()) {
2042 DEBUG(dbgs() << "--> Pushing constant to tip of tree.");
2043 Leaves.pushToBottom(Leaves.pop());
2044 }
2045
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00002046 const DataLayout &DL = CurDAG->getDataLayout();
2047 const TargetLowering &TLI = *getTargetLowering();
2048
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002049 // Rebuild the tree using Huffman's algorithm
2050 while (Leaves.size() > 1) {
2051 WeightedLeaf L0 = Leaves.pop();
2052
2053 // See whether we can grab a MUL to form an add(Rx,mpyi(Ry,#u6)),
2054 // otherwise just get the next leaf
2055 WeightedLeaf L1 = Leaves.findMULbyConst();
2056 if (!L1.Value.getNode())
2057 L1 = Leaves.pop();
2058
2059 assert(L0.Weight <= L1.Weight && "Priority queue is broken!");
2060
2061 SDValue V0 = L0.Value;
2062 int V0Weight = L0.Weight;
2063 SDValue V1 = L1.Value;
2064 int V1Weight = L1.Weight;
2065
2066 // Make sure that none of these nodes have been RAUW'd
2067 if ((RootWeights.count(V0.getNode()) && RootWeights[V0.getNode()] == -2) ||
2068 (RootWeights.count(V1.getNode()) && RootWeights[V1.getNode()] == -2)) {
2069 DEBUG(dbgs() << "--> Subtree was RAUWd. Restarting...\n");
2070 return balanceSubTree(N, TopLevel);
2071 }
2072
2073 ConstantSDNode *V0C = dyn_cast<ConstantSDNode>(V0);
2074 ConstantSDNode *V1C = dyn_cast<ConstantSDNode>(V1);
2075 EVT VT = N->getValueType(0);
2076 SDValue NewNode;
2077
2078 if (V0C && !V1C) {
2079 std::swap(V0, V1);
2080 std::swap(V0C, V1C);
2081 }
2082
2083 // Calculate height of this node
2084 assert(NodeHeights.count(V0) && NodeHeights.count(V1) &&
2085 "Children must have been visited before re-combining them!");
2086 int Height = std::max(NodeHeights[V0], NodeHeights[V1]) + 1;
2087
2088 // Rebuild this node (and restore SHL from MUL if needed)
2089 if (V1C && NOpcode == ISD::MUL && V1C->getAPIntValue().isPowerOf2())
2090 NewNode = CurDAG->getNode(
2091 ISD::SHL, SDLoc(V0), VT, V0,
2092 CurDAG->getConstant(
2093 V1C->getAPIntValue().logBase2(), SDLoc(N),
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00002094 TLI.getScalarShiftAmountTy(DL, V0.getValueType())));
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002095 else
2096 NewNode = CurDAG->getNode(NOpcode, SDLoc(N), VT, V0, V1);
2097
2098 NodeHeights[NewNode] = Height;
2099
2100 int Weight = V0Weight + V1Weight;
2101 Leaves.push(WeightedLeaf(NewNode, Weight, L0.InsertionOrder));
2102
2103 DEBUG(dbgs() << "--> Built new node (Weight=" << Weight << ",Height="
2104 << Height << "):\n");
2105 DEBUG(NewNode.dump());
2106 }
2107
2108 assert(Leaves.size() == 1);
2109 SDValue NewRoot = Leaves.top().Value;
2110
2111 assert(NodeHeights.count(NewRoot));
2112 int Height = NodeHeights[NewRoot];
2113
2114 // Restore SHL if we earlier converted it to a MUL
2115 if (NewRoot.getOpcode() == ISD::MUL) {
2116 ConstantSDNode *V1C = dyn_cast<ConstantSDNode>(NewRoot.getOperand(1));
2117 if (V1C && V1C->getAPIntValue().isPowerOf2()) {
2118 EVT VT = NewRoot.getValueType();
2119 SDValue V0 = NewRoot.getOperand(0);
2120 NewRoot = CurDAG->getNode(
2121 ISD::SHL, SDLoc(NewRoot), VT, V0,
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00002122 CurDAG->getConstant(
2123 V1C->getAPIntValue().logBase2(), SDLoc(NewRoot),
2124 TLI.getScalarShiftAmountTy(DL, V0.getValueType())));
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002125 }
2126 }
2127
2128 if (N != NewRoot.getNode()) {
2129 DEBUG(dbgs() << "--> Root is now: ");
2130 DEBUG(NewRoot.dump());
2131
2132 // Replace all uses of old root by new root
2133 CurDAG->ReplaceAllUsesWith(N, NewRoot.getNode());
2134 // Mark that we have RAUW'd N
2135 RootWeights[N] = -2;
2136 } else {
2137 DEBUG(dbgs() << "--> Root unchanged.\n");
2138 }
2139
2140 RootWeights[NewRoot.getNode()] = Leaves.top().Weight;
2141 RootHeights[NewRoot.getNode()] = Height;
2142
2143 return NewRoot;
2144}
2145
2146void HexagonDAGToDAGISel::rebalanceAddressTrees() {
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00002147 for (auto I = CurDAG->allnodes_begin(), E = CurDAG->allnodes_end(); I != E;) {
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002148 SDNode *N = &*I++;
2149 if (N->getOpcode() != ISD::LOAD && N->getOpcode() != ISD::STORE)
2150 continue;
2151
2152 SDValue BasePtr = cast<MemSDNode>(N)->getBasePtr();
2153 if (BasePtr.getOpcode() != ISD::ADD)
2154 continue;
2155
2156 // We've already processed this node
2157 if (RootWeights.count(BasePtr.getNode()))
2158 continue;
2159
2160 DEBUG(dbgs() << "** Rebalancing address calculation in node: ");
2161 DEBUG(N->dump());
2162
2163 // FindRoots
2164 SmallVector<SDNode *, 4> Worklist;
2165
2166 Worklist.push_back(BasePtr.getOperand(0).getNode());
2167 Worklist.push_back(BasePtr.getOperand(1).getNode());
2168
2169 while (!Worklist.empty()) {
2170 SDNode *N = Worklist.pop_back_val();
2171 unsigned Opcode = N->getOpcode();
2172
2173 if (!isOpcodeHandled(N))
2174 continue;
2175
2176 Worklist.push_back(N->getOperand(0).getNode());
2177 Worklist.push_back(N->getOperand(1).getNode());
2178
2179 // Not a root if it has only one use and same opcode as its parent
2180 if (N->hasOneUse() && Opcode == N->use_begin()->getOpcode())
2181 continue;
2182
2183 // This root node has already been processed
2184 if (RootWeights.count(N))
2185 continue;
2186
2187 RootWeights[N] = -1;
2188 }
2189
2190 // Balance node itself
2191 RootWeights[BasePtr.getNode()] = -1;
2192 SDValue NewBasePtr = balanceSubTree(BasePtr.getNode(), /*TopLevel=*/ true);
2193
2194 if (N->getOpcode() == ISD::LOAD)
2195 N = CurDAG->UpdateNodeOperands(N, N->getOperand(0),
2196 NewBasePtr, N->getOperand(2));
2197 else
2198 N = CurDAG->UpdateNodeOperands(N, N->getOperand(0), N->getOperand(1),
2199 NewBasePtr, N->getOperand(3));
2200
2201 DEBUG(dbgs() << "--> Final node: ");
2202 DEBUG(N->dump());
2203 }
2204
2205 CurDAG->RemoveDeadNodes();
2206 GAUsesInFunction.clear();
2207 RootHeights.clear();
2208 RootWeights.clear();
2209}
2210