blob: 74405374665c491c9ba65ed653e709a25e280762 [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 Parzyszek55772972017-09-15 15:46:05 +0000244 case MVT::v128i8:
245 case MVT::v64i16:
246 case MVT::v32i32:
247 case MVT::v16i64:
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000248 if (isAlignedMemNode(LD)) {
249 if (LD->isNonTemporal())
250 Opcode = IsValidInc ? Hexagon::V6_vL32b_nt_pi : Hexagon::V6_vL32b_nt_ai;
251 else
252 Opcode = IsValidInc ? Hexagon::V6_vL32b_pi : Hexagon::V6_vL32b_ai;
253 } else {
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000254 Opcode = IsValidInc ? Hexagon::V6_vL32Ub_pi : Hexagon::V6_vL32Ub_ai;
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000255 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000256 break;
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000257 default:
258 llvm_unreachable("Unexpected memory type in indexed load");
Justin Bognerec37a022016-05-12 21:46:18 +0000259 }
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000260
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000261 SDValue IncV = CurDAG->getTargetConstant(Inc, dl, MVT::i32);
262 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
263 MemOp[0] = LD->getMemOperand();
264
265 auto getExt64 = [this,ExtType] (MachineSDNode *N, const SDLoc &dl)
266 -> MachineSDNode* {
267 if (ExtType == ISD::ZEXTLOAD || ExtType == ISD::EXTLOAD) {
268 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
269 return CurDAG->getMachineNode(Hexagon::A4_combineir, dl, MVT::i64,
270 Zero, SDValue(N, 0));
Krzysztof Parzyszek08ff8882015-11-26 18:38:27 +0000271 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000272 if (ExtType == ISD::SEXTLOAD)
273 return CurDAG->getMachineNode(Hexagon::A2_sxtw, dl, MVT::i64,
274 SDValue(N, 0));
275 return N;
276 };
277
278 // Loaded value Next address Chain
279 SDValue From[3] = { SDValue(LD,0), SDValue(LD,1), SDValue(LD,2) };
280 SDValue To[3];
281
282 EVT ValueVT = LD->getValueType(0);
283 if (ValueVT == MVT::i64 && ExtType != ISD::NON_EXTLOAD) {
284 // A load extending to i64 will actually produce i32, which will then
285 // need to be extended to i64.
286 assert(LoadedVT.getSizeInBits() <= 32);
287 ValueVT = MVT::i32;
288 }
289
290 if (IsValidInc) {
291 MachineSDNode *L = CurDAG->getMachineNode(Opcode, dl, ValueVT,
292 MVT::i32, MVT::Other, Base,
293 IncV, Chain);
294 L->setMemRefs(MemOp, MemOp+1);
295 To[1] = SDValue(L, 1); // Next address.
296 To[2] = SDValue(L, 2); // Chain.
297 // Handle special case for extension to i64.
298 if (LD->getValueType(0) == MVT::i64)
299 L = getExt64(L, dl);
300 To[0] = SDValue(L, 0); // Loaded (extended) value.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000301 } else {
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000302 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
303 MachineSDNode *L = CurDAG->getMachineNode(Opcode, dl, ValueVT, MVT::Other,
304 Base, Zero, Chain);
305 L->setMemRefs(MemOp, MemOp+1);
306 To[2] = SDValue(L, 1); // Chain.
307 MachineSDNode *A = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
308 Base, IncV);
309 To[1] = SDValue(A, 0); // Next address.
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 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000315 ReplaceUses(From, To, 3);
316 CurDAG->RemoveDeadNode(LD);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000317}
318
319
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000320MachineSDNode *HexagonDAGToDAGISel::LoadInstrForLoadIntrinsic(SDNode *IntN) {
321 if (IntN->getOpcode() != ISD::INTRINSIC_W_CHAIN)
322 return nullptr;
323
324 SDLoc dl(IntN);
325 unsigned IntNo = cast<ConstantSDNode>(IntN->getOperand(1))->getZExtValue();
326
327 static std::map<unsigned,unsigned> LoadPciMap = {
328 { Intrinsic::hexagon_circ_ldb, Hexagon::L2_loadrb_pci },
329 { Intrinsic::hexagon_circ_ldub, Hexagon::L2_loadrub_pci },
330 { Intrinsic::hexagon_circ_ldh, Hexagon::L2_loadrh_pci },
331 { Intrinsic::hexagon_circ_lduh, Hexagon::L2_loadruh_pci },
332 { Intrinsic::hexagon_circ_ldw, Hexagon::L2_loadri_pci },
333 { Intrinsic::hexagon_circ_ldd, Hexagon::L2_loadrd_pci },
334 };
335 auto FLC = LoadPciMap.find(IntNo);
336 if (FLC != LoadPciMap.end()) {
337 SDNode *Mod = CurDAG->getMachineNode(Hexagon::A2_tfrrcr, dl, MVT::i32,
338 IntN->getOperand(4));
339 EVT ValTy = (IntNo == Intrinsic::hexagon_circ_ldd) ? MVT::i64 : MVT::i32;
340 EVT RTys[] = { ValTy, MVT::i32, MVT::Other };
341 // Operands: { Base, Increment, Modifier, Chain }
342 auto Inc = cast<ConstantSDNode>(IntN->getOperand(5));
343 SDValue I = CurDAG->getTargetConstant(Inc->getSExtValue(), dl, MVT::i32);
344 MachineSDNode *Res = CurDAG->getMachineNode(FLC->second, dl, RTys,
345 { IntN->getOperand(2), I, SDValue(Mod,0), IntN->getOperand(0) });
346 return Res;
347 }
348
349 static std::map<unsigned,unsigned> LoadPbrMap = {
350 { Intrinsic::hexagon_brev_ldb, Hexagon::L2_loadrb_pbr },
351 { Intrinsic::hexagon_brev_ldub, Hexagon::L2_loadrub_pbr },
352 { Intrinsic::hexagon_brev_ldh, Hexagon::L2_loadrh_pbr },
353 { Intrinsic::hexagon_brev_lduh, Hexagon::L2_loadruh_pbr },
354 { Intrinsic::hexagon_brev_ldw, Hexagon::L2_loadri_pbr },
355 { Intrinsic::hexagon_brev_ldd, Hexagon::L2_loadrd_pbr },
356 };
357 auto FLB = LoadPbrMap.find(IntNo);
358 if (FLB != LoadPbrMap.end()) {
359 SDNode *Mod = CurDAG->getMachineNode(Hexagon::A2_tfrrcr, dl, MVT::i32,
360 IntN->getOperand(4));
361 EVT ValTy = (IntNo == Intrinsic::hexagon_brev_ldd) ? MVT::i64 : MVT::i32;
362 EVT RTys[] = { ValTy, MVT::i32, MVT::Other };
363 // Operands: { Base, Modifier, Chain }
364 MachineSDNode *Res = CurDAG->getMachineNode(FLB->second, dl, RTys,
365 { IntN->getOperand(2), SDValue(Mod,0), IntN->getOperand(0) });
366 return Res;
367 }
368
369 return nullptr;
370}
371
372SDNode *HexagonDAGToDAGISel::StoreInstrForLoadIntrinsic(MachineSDNode *LoadN,
373 SDNode *IntN) {
374 // The "LoadN" is just a machine load instruction. The intrinsic also
375 // involves storing it. Generate an appropriate store to the location
376 // given in the intrinsic's operand(3).
377 uint64_t F = HII->get(LoadN->getMachineOpcode()).TSFlags;
378 unsigned SizeBits = (F >> HexagonII::MemAccessSizePos) &
379 HexagonII::MemAccesSizeMask;
380 unsigned Size = 1U << (SizeBits-1);
381
382 SDLoc dl(IntN);
383 MachinePointerInfo PI;
384 SDValue TS;
385 SDValue Loc = IntN->getOperand(3);
386
387 if (Size >= 4)
Justin Lebar9c375812016-07-15 18:27:10 +0000388 TS = CurDAG->getStore(SDValue(LoadN, 2), dl, SDValue(LoadN, 0), Loc, PI,
389 Size);
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000390 else
Justin Lebar9c375812016-07-15 18:27:10 +0000391 TS = CurDAG->getTruncStore(SDValue(LoadN, 2), dl, SDValue(LoadN, 0), Loc,
392 PI, MVT::getIntegerVT(Size * 8), Size);
Justin Bognerdcb7a822016-05-10 20:31:53 +0000393
394 SDNode *StoreN;
395 {
396 HandleSDNode Handle(TS);
397 SelectStore(TS.getNode());
398 StoreN = Handle.getValue().getNode();
399 }
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000400
401 // Load's results are { Loaded value, Updated pointer, Chain }
402 ReplaceUses(SDValue(IntN, 0), SDValue(LoadN, 1));
403 ReplaceUses(SDValue(IntN, 1), SDValue(StoreN, 0));
404 return StoreN;
405}
406
Justin Bognerec37a022016-05-12 21:46:18 +0000407bool HexagonDAGToDAGISel::tryLoadOfLoadIntrinsic(LoadSDNode *N) {
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000408 // The intrinsics for load circ/brev perform two operations:
409 // 1. Load a value V from the specified location, using the addressing
410 // mode corresponding to the intrinsic.
411 // 2. Store V into a specified location. This location is typically a
412 // local, temporary object.
413 // In many cases, the program using these intrinsics will immediately
414 // load V again from the local object. In those cases, when certain
415 // conditions are met, the last load can be removed.
416 // This function identifies and optimizes this pattern. If the pattern
417 // cannot be optimized, it returns nullptr, which will cause the load
418 // to be selected separately from the intrinsic (which will be handled
419 // in SelectIntrinsicWChain).
420
421 SDValue Ch = N->getOperand(0);
422 SDValue Loc = N->getOperand(1);
423
424 // Assume that the load and the intrinsic are connected directly with a
425 // chain:
426 // t1: i32,ch = int.load ..., ..., ..., Loc, ... // <-- C
427 // t2: i32,ch = load t1:1, Loc, ...
428 SDNode *C = Ch.getNode();
429
430 if (C->getOpcode() != ISD::INTRINSIC_W_CHAIN)
Justin Bognerec37a022016-05-12 21:46:18 +0000431 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000432
433 // The second load can only be eliminated if its extension type matches
434 // that of the load instruction corresponding to the intrinsic. The user
435 // can provide an address of an unsigned variable to store the result of
436 // a sign-extending intrinsic into (or the other way around).
437 ISD::LoadExtType IntExt;
438 switch (cast<ConstantSDNode>(C->getOperand(1))->getZExtValue()) {
439 case Intrinsic::hexagon_brev_ldub:
440 case Intrinsic::hexagon_brev_lduh:
441 case Intrinsic::hexagon_circ_ldub:
442 case Intrinsic::hexagon_circ_lduh:
443 IntExt = ISD::ZEXTLOAD;
444 break;
445 case Intrinsic::hexagon_brev_ldw:
446 case Intrinsic::hexagon_brev_ldd:
447 case Intrinsic::hexagon_circ_ldw:
448 case Intrinsic::hexagon_circ_ldd:
449 IntExt = ISD::NON_EXTLOAD;
450 break;
451 default:
452 IntExt = ISD::SEXTLOAD;
453 break;
454 }
455 if (N->getExtensionType() != IntExt)
Justin Bognerec37a022016-05-12 21:46:18 +0000456 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000457
458 // Make sure the target location for the loaded value in the load intrinsic
459 // is the location from which LD (or N) is loading.
460 if (C->getNumOperands() < 4 || Loc.getNode() != C->getOperand(3).getNode())
Justin Bognerec37a022016-05-12 21:46:18 +0000461 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000462
463 if (MachineSDNode *L = LoadInstrForLoadIntrinsic(C)) {
464 SDNode *S = StoreInstrForLoadIntrinsic(L, C);
465 SDValue F[] = { SDValue(N,0), SDValue(N,1), SDValue(C,0), SDValue(C,1) };
466 SDValue T[] = { SDValue(L,0), SDValue(S,0), SDValue(L,1), SDValue(S,0) };
467 ReplaceUses(F, T, array_lengthof(T));
468 // This transformation will leave the intrinsic dead. If it remains in
469 // the DAG, the selection code will see it again, but without the load,
470 // and it will generate a store that is normally required for it.
Krzysztof Parzyszek0f791f42016-05-13 18:48:15 +0000471 CurDAG->RemoveDeadNode(C);
Justin Bognerec37a022016-05-12 21:46:18 +0000472 return true;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000473 }
474
Justin Bognerec37a022016-05-12 21:46:18 +0000475 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000476}
477
Justin Bognerec37a022016-05-12 21:46:18 +0000478void HexagonDAGToDAGISel::SelectLoad(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000479 SDLoc dl(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000480 LoadSDNode *LD = cast<LoadSDNode>(N);
481 ISD::MemIndexedMode AM = LD->getAddressingMode();
482
483 // Handle indexed loads.
Justin Bognerec37a022016-05-12 21:46:18 +0000484 if (AM != ISD::UNINDEXED) {
485 SelectIndexedLoad(LD, dl);
486 return;
487 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000488
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000489 // Handle patterns using circ/brev load intrinsics.
Justin Bognerec37a022016-05-12 21:46:18 +0000490 if (tryLoadOfLoadIntrinsic(LD))
491 return;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000492
Justin Bognerec37a022016-05-12 21:46:18 +0000493 SelectCode(LD);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000494}
495
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000496void HexagonDAGToDAGISel::SelectIndexedStore(StoreSDNode *ST, const SDLoc &dl) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000497 SDValue Chain = ST->getChain();
498 SDValue Base = ST->getBasePtr();
499 SDValue Offset = ST->getOffset();
500 SDValue Value = ST->getValue();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000501 // Get the constant value.
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000502 int32_t Inc = cast<ConstantSDNode>(Offset.getNode())->getSExtValue();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000503 EVT StoredVT = ST->getMemoryVT();
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000504 EVT ValueVT = Value.getValueType();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000505
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000506 bool IsValidInc = HII->isValidAutoIncImm(StoredVT, Inc);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000507 unsigned Opcode = 0;
508
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000509 assert(StoredVT.isSimple());
510 switch (StoredVT.getSimpleVT().SimpleTy) {
511 case MVT::i8:
512 Opcode = IsValidInc ? Hexagon::S2_storerb_pi : Hexagon::S2_storerb_io;
513 break;
514 case MVT::i16:
515 Opcode = IsValidInc ? Hexagon::S2_storerh_pi : Hexagon::S2_storerh_io;
516 break;
517 case MVT::i32:
518 Opcode = IsValidInc ? Hexagon::S2_storeri_pi : Hexagon::S2_storeri_io;
519 break;
520 case MVT::i64:
521 Opcode = IsValidInc ? Hexagon::S2_storerd_pi : Hexagon::S2_storerd_io;
522 break;
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000523 case MVT::v64i8:
524 case MVT::v32i16:
525 case MVT::v16i32:
526 case MVT::v8i64:
Krzysztof Parzyszek55772972017-09-15 15:46:05 +0000527 case MVT::v128i8:
528 case MVT::v64i16:
529 case MVT::v32i32:
530 case MVT::v16i64:
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000531 if (isAlignedMemNode(ST)) {
532 if (ST->isNonTemporal())
533 Opcode = IsValidInc ? Hexagon::V6_vS32b_nt_pi : Hexagon::V6_vS32b_nt_ai;
534 else
535 Opcode = IsValidInc ? Hexagon::V6_vS32b_pi : Hexagon::V6_vS32b_ai;
536 } else {
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000537 Opcode = IsValidInc ? Hexagon::V6_vS32Ub_pi : Hexagon::V6_vS32Ub_ai;
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000538 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000539 break;
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000540 default:
541 llvm_unreachable("Unexpected memory type in indexed store");
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +0000542 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000543
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000544 if (ST->isTruncatingStore() && ValueVT.getSizeInBits() == 64) {
545 assert(StoredVT.getSizeInBits() < 64 && "Not a truncating store");
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +0000546 Value = CurDAG->getTargetExtractSubreg(Hexagon::isub_lo,
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000547 dl, MVT::i32, Value);
548 }
549
550 SDValue IncV = CurDAG->getTargetConstant(Inc, dl, MVT::i32);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000551 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
552 MemOp[0] = ST->getMemOperand();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000553
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000554 // Next address Chain
555 SDValue From[2] = { SDValue(ST,0), SDValue(ST,1) };
556 SDValue To[2];
557
558 if (IsValidInc) {
559 // Build post increment store.
560 SDValue Ops[] = { Base, IncV, Value, Chain };
561 MachineSDNode *S = CurDAG->getMachineNode(Opcode, dl, MVT::i32, MVT::Other,
562 Ops);
563 S->setMemRefs(MemOp, MemOp + 1);
564 To[0] = SDValue(S, 0);
565 To[1] = SDValue(S, 1);
566 } else {
567 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
568 SDValue Ops[] = { Base, Zero, Value, Chain };
569 MachineSDNode *S = CurDAG->getMachineNode(Opcode, dl, MVT::Other, Ops);
570 S->setMemRefs(MemOp, MemOp + 1);
571 To[1] = SDValue(S, 0);
572 MachineSDNode *A = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
573 Base, IncV);
574 To[0] = SDValue(A, 0);
575 }
576
577 ReplaceUses(From, To, 2);
Justin Bognerdcb7a822016-05-10 20:31:53 +0000578 CurDAG->RemoveDeadNode(ST);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000579}
580
Justin Bognerec37a022016-05-12 21:46:18 +0000581void HexagonDAGToDAGISel::SelectStore(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000582 SDLoc dl(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000583 StoreSDNode *ST = cast<StoreSDNode>(N);
584 ISD::MemIndexedMode AM = ST->getAddressingMode();
585
586 // Handle indexed stores.
587 if (AM != ISD::UNINDEXED) {
Justin Bognerec37a022016-05-12 21:46:18 +0000588 SelectIndexedStore(ST, dl);
589 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000590 }
Sirish Pandec92c3162012-05-03 16:18:50 +0000591
Justin Bognerec37a022016-05-12 21:46:18 +0000592 SelectCode(ST);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000593}
594
Justin Bognerec37a022016-05-12 21:46:18 +0000595void HexagonDAGToDAGISel::SelectSHL(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000596 SDLoc dl(N);
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000597 SDValue Shl_0 = N->getOperand(0);
598 SDValue Shl_1 = N->getOperand(1);
Krzysztof Parzyszekd978ae22016-08-01 20:00:33 +0000599
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000600 auto Default = [this,N] () -> void { SelectCode(N); };
601
602 if (N->getValueType(0) != MVT::i32 || Shl_1.getOpcode() != ISD::Constant)
603 return Default();
604
605 // RHS is const.
606 int32_t ShlConst = cast<ConstantSDNode>(Shl_1)->getSExtValue();
607
608 if (Shl_0.getOpcode() == ISD::MUL) {
609 SDValue Mul_0 = Shl_0.getOperand(0); // Val
610 SDValue Mul_1 = Shl_0.getOperand(1); // Const
611 // RHS of mul is const.
612 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mul_1)) {
613 int32_t ValConst = C->getSExtValue() << ShlConst;
614 if (isInt<9>(ValConst)) {
615 SDValue Val = CurDAG->getTargetConstant(ValConst, dl, MVT::i32);
616 SDNode *Result = CurDAG->getMachineNode(Hexagon::M2_mpysmi, dl,
617 MVT::i32, Mul_0, Val);
618 ReplaceNode(N, Result);
619 return;
620 }
621 }
622 return Default();
623 }
624
625 if (Shl_0.getOpcode() == ISD::SUB) {
626 SDValue Sub_0 = Shl_0.getOperand(0); // Const 0
627 SDValue Sub_1 = Shl_0.getOperand(1); // Val
628 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Sub_0)) {
629 if (C1->getSExtValue() != 0 || Sub_1.getOpcode() != ISD::SHL)
630 return Default();
631 SDValue Shl2_0 = Sub_1.getOperand(0); // Val
632 SDValue Shl2_1 = Sub_1.getOperand(1); // Const
633 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(Shl2_1)) {
634 int32_t ValConst = 1 << (ShlConst + C2->getSExtValue());
635 if (isInt<9>(-ValConst)) {
636 SDValue Val = CurDAG->getTargetConstant(-ValConst, dl, MVT::i32);
637 SDNode *Result = CurDAG->getMachineNode(Hexagon::M2_mpysmi, dl,
638 MVT::i32, Shl2_0, Val);
639 ReplaceNode(N, Result);
640 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000641 }
642 }
643 }
644 }
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000645
646 return Default();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000647}
648
649
650//
651// If there is an zero_extend followed an intrinsic in DAG (this means - the
652// result of the intrinsic is predicate); convert the zero_extend to
653// transfer instruction.
654//
655// Zero extend -> transfer is lowered here. Otherwise, zero_extend will be
656// converted into a MUX as predicate registers defined as 1 bit in the
657// compiler. Architecture defines them as 8-bit registers.
658// We want to preserve all the lower 8-bits and, not just 1 LSB bit.
659//
Justin Bognerec37a022016-05-12 21:46:18 +0000660void HexagonDAGToDAGISel::SelectZeroExtend(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000661 SDLoc dl(N);
Krzysztof Parzyszek42113342015-03-19 16:33:08 +0000662
663 SDValue Op0 = N->getOperand(0);
664 EVT OpVT = Op0.getValueType();
665 unsigned OpBW = OpVT.getSizeInBits();
666
667 // Special handling for zero-extending a vector of booleans.
668 if (OpVT.isVector() && OpVT.getVectorElementType() == MVT::i1 && OpBW <= 64) {
669 SDNode *Mask = CurDAG->getMachineNode(Hexagon::C2_mask, dl, MVT::i64, Op0);
670 unsigned NE = OpVT.getVectorNumElements();
671 EVT ExVT = N->getValueType(0);
Sanjay Patel1ed771f2016-09-14 16:37:15 +0000672 unsigned ES = ExVT.getScalarSizeInBits();
Krzysztof Parzyszek42113342015-03-19 16:33:08 +0000673 uint64_t MV = 0, Bit = 1;
674 for (unsigned i = 0; i < NE; ++i) {
675 MV |= Bit;
676 Bit <<= ES;
677 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000678 SDValue Ones = CurDAG->getTargetConstant(MV, dl, MVT::i64);
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +0000679 SDNode *OnesReg = CurDAG->getMachineNode(Hexagon::CONST64, dl,
Krzysztof Parzyszek42113342015-03-19 16:33:08 +0000680 MVT::i64, Ones);
681 if (ExVT.getSizeInBits() == 32) {
682 SDNode *And = CurDAG->getMachineNode(Hexagon::A2_andp, dl, MVT::i64,
683 SDValue(Mask,0), SDValue(OnesReg,0));
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +0000684 SDValue SubR = CurDAG->getTargetConstant(Hexagon::isub_lo, dl, MVT::i32);
Justin Bognerec37a022016-05-12 21:46:18 +0000685 ReplaceNode(N, CurDAG->getMachineNode(Hexagon::EXTRACT_SUBREG, dl, ExVT,
686 SDValue(And, 0), SubR));
687 return;
Krzysztof Parzyszek42113342015-03-19 16:33:08 +0000688 }
Justin Bognerec37a022016-05-12 21:46:18 +0000689 ReplaceNode(N,
690 CurDAG->getMachineNode(Hexagon::A2_andp, dl, ExVT,
691 SDValue(Mask, 0), SDValue(OnesReg, 0)));
692 return;
Krzysztof Parzyszek42113342015-03-19 16:33:08 +0000693 }
694
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000695 SDNode *Int = N->getOperand(0).getNode();
696 if ((Int->getOpcode() == ISD::INTRINSIC_WO_CHAIN)) {
697 unsigned ID = cast<ConstantSDNode>(Int->getOperand(0))->getZExtValue();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000698 if (doesIntrinsicReturnPredicate(ID)) {
699 // Now we need to differentiate target data types.
700 if (N->getValueType(0) == MVT::i64) {
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000701 // Convert the zero_extend to Rs = Pd followed by A2_combinew(0,Rs).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000702 SDValue TargetConst0 = CurDAG->getTargetConstant(0, dl, MVT::i32);
Colin LeMahieu30dcb232014-12-09 18:16:49 +0000703 SDNode *Result_1 = CurDAG->getMachineNode(Hexagon::C2_tfrpr, dl,
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000704 MVT::i32, SDValue(Int, 0));
Colin LeMahieu4af437f2014-12-09 20:23:30 +0000705 SDNode *Result_2 = CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl,
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000706 MVT::i32, TargetConst0);
Colin LeMahieub580d7d2014-12-09 19:23:45 +0000707 SDNode *Result_3 = CurDAG->getMachineNode(Hexagon::A2_combinew, dl,
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000708 MVT::i64, MVT::Other,
709 SDValue(Result_2, 0),
710 SDValue(Result_1, 0));
Justin Bognerec37a022016-05-12 21:46:18 +0000711 ReplaceNode(N, Result_3);
712 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000713 }
714 if (N->getValueType(0) == MVT::i32) {
715 // Convert the zero_extend to Rs = Pd
Colin LeMahieu30dcb232014-12-09 18:16:49 +0000716 SDNode* RsPd = CurDAG->getMachineNode(Hexagon::C2_tfrpr, dl,
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000717 MVT::i32, SDValue(Int, 0));
Justin Bognerec37a022016-05-12 21:46:18 +0000718 ReplaceNode(N, RsPd);
719 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000720 }
Craig Toppere55c5562012-02-07 02:50:20 +0000721 llvm_unreachable("Unexpected value type");
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000722 }
723 }
Justin Bognerec37a022016-05-12 21:46:18 +0000724 SelectCode(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000725}
726
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000727
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000728//
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000729// Handling intrinsics for circular load and bitreverse load.
Krzysztof Parzyszek47ab1f22015-03-18 16:23:44 +0000730//
Justin Bognerec37a022016-05-12 21:46:18 +0000731void HexagonDAGToDAGISel::SelectIntrinsicWChain(SDNode *N) {
732 if (MachineSDNode *L = LoadInstrForLoadIntrinsic(N)) {
733 StoreInstrForLoadIntrinsic(L, N);
Krzysztof Parzyszek0f791f42016-05-13 18:48:15 +0000734 CurDAG->RemoveDeadNode(N);
Justin Bognerec37a022016-05-12 21:46:18 +0000735 return;
736 }
737 SelectCode(N);
Krzysztof Parzyszek47ab1f22015-03-18 16:23:44 +0000738}
739
Justin Bognerec37a022016-05-12 21:46:18 +0000740void HexagonDAGToDAGISel::SelectIntrinsicWOChain(SDNode *N) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000741 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
742 unsigned Bits;
743 switch (IID) {
744 case Intrinsic::hexagon_S2_vsplatrb:
745 Bits = 8;
746 break;
747 case Intrinsic::hexagon_S2_vsplatrh:
748 Bits = 16;
749 break;
750 default:
Justin Bognerec37a022016-05-12 21:46:18 +0000751 SelectCode(N);
752 return;
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000753 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000754
Krzysztof Parzyszeke60e5fe2016-05-12 17:21:40 +0000755 SDValue V = N->getOperand(1);
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000756 SDValue U;
Krzysztof Parzyszekef580172017-05-30 17:47:51 +0000757 if (keepsLowBits(V, Bits, U)) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000758 SDValue R = CurDAG->getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
Krzysztof Parzyszeke60e5fe2016-05-12 17:21:40 +0000759 N->getOperand(0), U);
Justin Bognerd82025b2016-05-12 21:24:23 +0000760 ReplaceNode(N, R.getNode());
Justin Bognerec37a022016-05-12 21:46:18 +0000761 SelectCode(R.getNode());
762 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000763 }
Justin Bognerec37a022016-05-12 21:46:18 +0000764 SelectCode(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000765}
766
Sirish Pande69295b82012-05-10 20:20:25 +0000767//
768// Map floating point constant values.
769//
Justin Bognerec37a022016-05-12 21:46:18 +0000770void HexagonDAGToDAGISel::SelectConstantFP(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000771 SDLoc dl(N);
Sirish Pande69295b82012-05-10 20:20:25 +0000772 ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N);
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +0000773 APInt A = CN->getValueAPF().bitcastToAPInt();
Sirish Pande69295b82012-05-10 20:20:25 +0000774 if (N->getValueType(0) == MVT::f32) {
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +0000775 SDValue V = CurDAG->getTargetConstant(A.getZExtValue(), dl, MVT::i32);
776 ReplaceNode(N, CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl, MVT::f32, V));
Justin Bognerec37a022016-05-12 21:46:18 +0000777 return;
Sirish Pande69295b82012-05-10 20:20:25 +0000778 }
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000779 if (N->getValueType(0) == MVT::f64) {
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +0000780 SDValue V = CurDAG->getTargetConstant(A.getZExtValue(), dl, MVT::i64);
781 ReplaceNode(N, CurDAG->getMachineNode(Hexagon::CONST64, dl, MVT::f64, V));
Justin Bognerec37a022016-05-12 21:46:18 +0000782 return;
Sirish Pande69295b82012-05-10 20:20:25 +0000783 }
784
Justin Bognerec37a022016-05-12 21:46:18 +0000785 SelectCode(N);
Sirish Pande69295b82012-05-10 20:20:25 +0000786}
787
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000788//
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000789// Map boolean values.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000790//
Justin Bognerec37a022016-05-12 21:46:18 +0000791void HexagonDAGToDAGISel::SelectConstant(SDNode *N) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000792 if (N->getValueType(0) == MVT::i1) {
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000793 assert(!(cast<ConstantSDNode>(N)->getZExtValue() >> 1));
794 unsigned Opc = (cast<ConstantSDNode>(N)->getSExtValue() != 0)
795 ? Hexagon::PS_true
796 : Hexagon::PS_false;
797 ReplaceNode(N, CurDAG->getMachineNode(Opc, SDLoc(N), MVT::i1));
798 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000799 }
800
Justin Bognerec37a022016-05-12 21:46:18 +0000801 SelectCode(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000802}
803
804
Justin Bognerec37a022016-05-12 21:46:18 +0000805void HexagonDAGToDAGISel::SelectFrameIndex(SDNode *N) {
Matthias Braun941a7052016-07-28 18:40:00 +0000806 MachineFrameInfo &MFI = MF->getFrameInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000807 const HexagonFrameLowering *HFI = HST->getFrameLowering();
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000808 int FX = cast<FrameIndexSDNode>(N)->getIndex();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000809 unsigned StkA = HFI->getStackAlignment();
Matthias Braun941a7052016-07-28 18:40:00 +0000810 unsigned MaxA = MFI.getMaxAlignment();
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000811 SDValue FI = CurDAG->getTargetFrameIndex(FX, MVT::i32);
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000812 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000813 SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000814 SDNode *R = nullptr;
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000815
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000816 // Use PS_fi when:
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000817 // - the object is fixed, or
818 // - there are no objects with higher-than-default alignment, or
819 // - there are no dynamically allocated objects.
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000820 // Otherwise, use PS_fia.
Matthias Braun941a7052016-07-28 18:40:00 +0000821 if (FX < 0 || MaxA <= StkA || !MFI.hasVarSizedObjects()) {
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000822 R = CurDAG->getMachineNode(Hexagon::PS_fi, DL, MVT::i32, FI, Zero);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000823 } else {
824 auto &HMFI = *MF->getInfo<HexagonMachineFunctionInfo>();
825 unsigned AR = HMFI.getStackAlignBaseVReg();
826 SDValue CH = CurDAG->getEntryNode();
827 SDValue Ops[] = { CurDAG->getCopyFromReg(CH, DL, AR, MVT::i32), FI, Zero };
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000828 R = CurDAG->getMachineNode(Hexagon::PS_fia, DL, MVT::i32, Ops);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000829 }
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000830
Justin Bognerec37a022016-05-12 21:46:18 +0000831 ReplaceNode(N, R);
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000832}
833
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000834
Krzysztof Parzyszek5da24e52016-06-27 15:08:22 +0000835void HexagonDAGToDAGISel::SelectBitcast(SDNode *N) {
836 EVT SVT = N->getOperand(0).getValueType();
837 EVT DVT = N->getValueType(0);
838 if (!SVT.isVector() || !DVT.isVector() ||
839 SVT.getVectorElementType() == MVT::i1 ||
840 DVT.getVectorElementType() == MVT::i1 ||
841 SVT.getSizeInBits() != DVT.getSizeInBits()) {
842 SelectCode(N);
843 return;
844 }
845
846 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N,0), N->getOperand(0));
847 CurDAG->RemoveDeadNode(N);
848}
849
850
Justin Bognerec37a022016-05-12 21:46:18 +0000851void HexagonDAGToDAGISel::Select(SDNode *N) {
Krzysztof Parzyszekbe5028a2017-02-24 23:00:40 +0000852 if (N->isMachineOpcode())
853 return N->setNodeId(-1); // Already selected.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000854
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000855 switch (N->getOpcode()) {
Krzysztof Parzyszekbe5028a2017-02-24 23:00:40 +0000856 case ISD::Constant: return SelectConstant(N);
857 case ISD::ConstantFP: return SelectConstantFP(N);
858 case ISD::FrameIndex: return SelectFrameIndex(N);
859 case ISD::BITCAST: return SelectBitcast(N);
860 case ISD::SHL: return SelectSHL(N);
861 case ISD::LOAD: return SelectLoad(N);
862 case ISD::STORE: return SelectStore(N);
Krzysztof Parzyszekbe5028a2017-02-24 23:00:40 +0000863 case ISD::ZERO_EXTEND: return SelectZeroExtend(N);
864 case ISD::INTRINSIC_W_CHAIN: return SelectIntrinsicWChain(N);
865 case ISD::INTRINSIC_WO_CHAIN: return SelectIntrinsicWOChain(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000866 }
867
Justin Bognerec37a022016-05-12 21:46:18 +0000868 SelectCode(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000869}
870
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000871bool HexagonDAGToDAGISel::
Daniel Sanders60f1db02015-03-13 12:45:09 +0000872SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000873 std::vector<SDValue> &OutOps) {
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000874 SDValue Inp = Op, Res;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000875
Daniel Sanders60f1db02015-03-13 12:45:09 +0000876 switch (ConstraintID) {
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000877 default:
878 return true;
Daniel Sanders49f643c2015-03-17 14:37:39 +0000879 case InlineAsm::Constraint_i:
880 case InlineAsm::Constraint_o: // Offsetable.
881 case InlineAsm::Constraint_v: // Not offsetable.
882 case InlineAsm::Constraint_m: // Memory.
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000883 if (SelectAddrFI(Inp, Res))
884 OutOps.push_back(Res);
885 else
886 OutOps.push_back(Inp);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000887 break;
888 }
889
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000890 OutOps.push_back(CurDAG->getTargetConstant(0, SDLoc(Op), MVT::i32));
Jyotsna Vermad9225242013-02-13 21:38:46 +0000891 return false;
892}
Colin LeMahieuc7522f32015-01-14 23:07:36 +0000893
Colin LeMahieu79ec0652015-06-12 19:57:32 +0000894
Krzysztof Parzyszek78c4fcf2017-03-09 16:29:30 +0000895static bool isMemOPCandidate(SDNode *I, SDNode *U) {
896 // I is an operand of U. Check if U is an arithmetic (binary) operation
897 // usable in a memop, where the other operand is a loaded value, and the
898 // result of U is stored in the same location.
899
900 if (!U->hasOneUse())
901 return false;
902 unsigned Opc = U->getOpcode();
903 switch (Opc) {
904 case ISD::ADD:
905 case ISD::SUB:
906 case ISD::AND:
907 case ISD::OR:
908 break;
909 default:
910 return false;
911 }
912
913 SDValue S0 = U->getOperand(0);
914 SDValue S1 = U->getOperand(1);
915 SDValue SY = (S0.getNode() == I) ? S1 : S0;
916
917 SDNode *UUse = *U->use_begin();
918 if (UUse->getNumValues() != 1)
919 return false;
920
921 // Check if one of the inputs to U is a load instruction and the output
922 // is used by a store instruction. If so and they also have the same
923 // base pointer, then don't preoprocess this node sequence as it
924 // can be matched to a memop.
925 SDNode *SYNode = SY.getNode();
926 if (UUse->getOpcode() == ISD::STORE && SYNode->getOpcode() == ISD::LOAD) {
927 SDValue LDBasePtr = cast<MemSDNode>(SYNode)->getBasePtr();
928 SDValue STBasePtr = cast<MemSDNode>(UUse)->getBasePtr();
929 if (LDBasePtr == STBasePtr)
930 return true;
931 }
932 return false;
933}
934
935
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +0000936// Transform: (or (select c x 0) z) -> (select c (or x z) z)
937// (or (select c 0 y) z) -> (select c z (or y z))
938void HexagonDAGToDAGISel::ppSimplifyOrSelect0(std::vector<SDNode*> &&Nodes) {
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000939 SelectionDAG &DAG = *CurDAG;
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000940
Krzysztof Parzyszekf7f70682016-06-22 20:08:27 +0000941 for (auto I : Nodes) {
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000942 if (I->getOpcode() != ISD::OR)
943 continue;
944
945 auto IsZero = [] (const SDValue &V) -> bool {
946 if (ConstantSDNode *SC = dyn_cast<ConstantSDNode>(V.getNode()))
947 return SC->isNullValue();
948 return false;
949 };
950 auto IsSelect0 = [IsZero] (const SDValue &Op) -> bool {
951 if (Op.getOpcode() != ISD::SELECT)
952 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000953 return IsZero(Op.getOperand(1)) || IsZero(Op.getOperand(2));
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000954 };
955
956 SDValue N0 = I->getOperand(0), N1 = I->getOperand(1);
957 EVT VT = I->getValueType(0);
958 bool SelN0 = IsSelect0(N0);
959 SDValue SOp = SelN0 ? N0 : N1;
960 SDValue VOp = SelN0 ? N1 : N0;
961
962 if (SOp.getOpcode() == ISD::SELECT && SOp.getNode()->hasOneUse()) {
963 SDValue SC = SOp.getOperand(0);
964 SDValue SX = SOp.getOperand(1);
965 SDValue SY = SOp.getOperand(2);
966 SDLoc DLS = SOp;
967 if (IsZero(SY)) {
968 SDValue NewOr = DAG.getNode(ISD::OR, DLS, VT, SX, VOp);
969 SDValue NewSel = DAG.getNode(ISD::SELECT, DLS, VT, SC, NewOr, VOp);
970 DAG.ReplaceAllUsesWith(I, NewSel.getNode());
971 } else if (IsZero(SX)) {
972 SDValue NewOr = DAG.getNode(ISD::OR, DLS, VT, SY, VOp);
973 SDValue NewSel = DAG.getNode(ISD::SELECT, DLS, VT, SC, VOp, NewOr);
974 DAG.ReplaceAllUsesWith(I, NewSel.getNode());
975 }
976 }
977 }
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +0000978}
Krzysztof Parzyszekf7f70682016-06-22 20:08:27 +0000979
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +0000980// Transform: (store ch val (add x (add (shl y c) e)))
981// to: (store ch val (add x (shl (add y d) c))),
982// where e = (shl d c) for some integer d.
983// The purpose of this is to enable generation of loads/stores with
984// shifted addressing mode, i.e. mem(x+y<<#c). For that, the shift
985// value c must be 0, 1 or 2.
986void HexagonDAGToDAGISel::ppAddrReorderAddShl(std::vector<SDNode*> &&Nodes) {
987 SelectionDAG &DAG = *CurDAG;
988
Krzysztof Parzyszekf7f70682016-06-22 20:08:27 +0000989 for (auto I : Nodes) {
990 if (I->getOpcode() != ISD::STORE)
991 continue;
992
Krzysztof Parzyszek0d67b102017-02-24 23:34:24 +0000993 // I matched: (store ch val Off)
Krzysztof Parzyszekf7f70682016-06-22 20:08:27 +0000994 SDValue Off = I->getOperand(2);
995 // Off needs to match: (add x (add (shl y c) (shl d c))))
996 if (Off.getOpcode() != ISD::ADD)
997 continue;
998 // Off matched: (add x T0)
999 SDValue T0 = Off.getOperand(1);
1000 // T0 needs to match: (add T1 T2):
1001 if (T0.getOpcode() != ISD::ADD)
1002 continue;
1003 // T0 matched: (add T1 T2)
1004 SDValue T1 = T0.getOperand(0);
1005 SDValue T2 = T0.getOperand(1);
1006 // T1 needs to match: (shl y c)
1007 if (T1.getOpcode() != ISD::SHL)
1008 continue;
1009 SDValue C = T1.getOperand(1);
1010 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(C.getNode());
1011 if (CN == nullptr)
1012 continue;
1013 unsigned CV = CN->getZExtValue();
1014 if (CV > 2)
1015 continue;
1016 // T2 needs to match e, where e = (shl d c) for some d.
1017 ConstantSDNode *EN = dyn_cast<ConstantSDNode>(T2.getNode());
1018 if (EN == nullptr)
1019 continue;
1020 unsigned EV = EN->getZExtValue();
1021 if (EV % (1 << CV) != 0)
1022 continue;
1023 unsigned DV = EV / (1 << CV);
1024
1025 // Replace T0 with: (shl (add y d) c)
1026 SDLoc DL = SDLoc(I);
1027 EVT VT = T0.getValueType();
1028 SDValue D = DAG.getConstant(DV, DL, VT);
1029 // NewAdd = (add y d)
1030 SDValue NewAdd = DAG.getNode(ISD::ADD, DL, VT, T1.getOperand(0), D);
1031 // NewShl = (shl NewAdd c)
1032 SDValue NewShl = DAG.getNode(ISD::SHL, DL, VT, NewAdd, C);
1033 ReplaceNode(T0.getNode(), NewShl.getNode());
1034 }
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001035}
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001036
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001037// Transform: (load ch (add x (and (srl y c) Mask)))
1038// to: (load ch (add x (shl (srl y d) d-c)))
1039// where
1040// Mask = 00..0 111..1 0.0
1041// | | +-- d-c 0s, and d-c is 0, 1 or 2.
1042// | +-------- 1s
1043// +-------------- at most c 0s
1044// Motivating example:
1045// DAG combiner optimizes (add x (shl (srl y 5) 2))
1046// to (add x (and (srl y 3) 1FFFFFFC))
1047// which results in a constant-extended and(##...,lsr). This transformation
1048// undoes this simplification for cases where the shl can be folded into
1049// an addressing mode.
1050void HexagonDAGToDAGISel::ppAddrRewriteAndSrl(std::vector<SDNode*> &&Nodes) {
1051 SelectionDAG &DAG = *CurDAG;
1052
Krzysztof Parzyszek0d67b102017-02-24 23:34:24 +00001053 for (SDNode *N : Nodes) {
1054 unsigned Opc = N->getOpcode();
1055 if (Opc != ISD::LOAD && Opc != ISD::STORE)
1056 continue;
1057 SDValue Addr = Opc == ISD::LOAD ? N->getOperand(1) : N->getOperand(2);
1058 // Addr must match: (add x T0)
1059 if (Addr.getOpcode() != ISD::ADD)
1060 continue;
1061 SDValue T0 = Addr.getOperand(1);
1062 // T0 must match: (and T1 Mask)
1063 if (T0.getOpcode() != ISD::AND)
1064 continue;
1065
1066 // We have an AND.
1067 //
1068 // Check the first operand. It must be: (srl y c).
1069 SDValue S = T0.getOperand(0);
1070 if (S.getOpcode() != ISD::SRL)
1071 continue;
1072 ConstantSDNode *SN = dyn_cast<ConstantSDNode>(S.getOperand(1).getNode());
1073 if (SN == nullptr)
1074 continue;
1075 if (SN->getAPIntValue().getBitWidth() != 32)
1076 continue;
1077 uint32_t CV = SN->getZExtValue();
1078
1079 // Check the second operand: the supposed mask.
1080 ConstantSDNode *MN = dyn_cast<ConstantSDNode>(T0.getOperand(1).getNode());
1081 if (MN == nullptr)
1082 continue;
1083 if (MN->getAPIntValue().getBitWidth() != 32)
1084 continue;
1085 uint32_t Mask = MN->getZExtValue();
1086 // Examine the mask.
1087 uint32_t TZ = countTrailingZeros(Mask);
1088 uint32_t M1 = countTrailingOnes(Mask >> TZ);
1089 uint32_t LZ = countLeadingZeros(Mask);
1090 // Trailing zeros + middle ones + leading zeros must equal the width.
1091 if (TZ + M1 + LZ != 32)
1092 continue;
1093 // The number of trailing zeros will be encoded in the addressing mode.
1094 if (TZ > 2)
1095 continue;
1096 // The number of leading zeros must be at most c.
1097 if (LZ > CV)
1098 continue;
1099
1100 // All looks good.
1101 SDValue Y = S.getOperand(0);
1102 EVT VT = Addr.getValueType();
1103 SDLoc dl(S);
1104 // TZ = D-C, so D = TZ+C.
1105 SDValue D = DAG.getConstant(TZ+CV, dl, VT);
1106 SDValue DC = DAG.getConstant(TZ, dl, VT);
1107 SDValue NewSrl = DAG.getNode(ISD::SRL, dl, VT, Y, D);
1108 SDValue NewShl = DAG.getNode(ISD::SHL, dl, VT, NewSrl, DC);
1109 ReplaceNode(T0.getNode(), NewShl.getNode());
1110 }
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001111}
Krzysztof Parzyszek0d67b102017-02-24 23:34:24 +00001112
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001113// Transform: (op ... (zext i1 c) ...) -> (select c (op ... 0 ...)
1114// (op ... 1 ...))
1115void HexagonDAGToDAGISel::ppHoistZextI1(std::vector<SDNode*> &&Nodes) {
1116 SelectionDAG &DAG = *CurDAG;
1117
Krzysztof Parzyszek78c4fcf2017-03-09 16:29:30 +00001118 for (SDNode *N : Nodes) {
1119 unsigned Opc = N->getOpcode();
1120 if (Opc != ISD::ZERO_EXTEND)
1121 continue;
1122 SDValue OpI1 = N->getOperand(0);
1123 EVT OpVT = OpI1.getValueType();
1124 if (!OpVT.isSimple() || OpVT.getSimpleVT() != MVT::i1)
1125 continue;
1126 for (auto I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1127 SDNode *U = *I;
1128 if (U->getNumValues() != 1)
1129 continue;
1130 EVT UVT = U->getValueType(0);
1131 if (!UVT.isSimple() || !UVT.isInteger() || UVT.getSimpleVT() == MVT::i1)
1132 continue;
1133 if (isMemOPCandidate(N, U))
1134 continue;
1135
1136 // Potentially simplifiable operation.
1137 unsigned I1N = I.getOperandNo();
1138 SmallVector<SDValue,2> Ops(U->getNumOperands());
1139 for (unsigned i = 0, n = U->getNumOperands(); i != n; ++i)
1140 Ops[i] = U->getOperand(i);
1141 EVT BVT = Ops[I1N].getValueType();
1142
1143 SDLoc dl(U);
1144 SDValue C0 = DAG.getConstant(0, dl, BVT);
1145 SDValue C1 = DAG.getConstant(1, dl, BVT);
1146 SDValue If0, If1;
1147
1148 if (isa<MachineSDNode>(U)) {
1149 unsigned UseOpc = U->getMachineOpcode();
1150 Ops[I1N] = C0;
1151 If0 = SDValue(DAG.getMachineNode(UseOpc, dl, UVT, Ops), 0);
1152 Ops[I1N] = C1;
1153 If1 = SDValue(DAG.getMachineNode(UseOpc, dl, UVT, Ops), 0);
1154 } else {
1155 unsigned UseOpc = U->getOpcode();
1156 Ops[I1N] = C0;
1157 If0 = DAG.getNode(UseOpc, dl, UVT, Ops);
1158 Ops[I1N] = C1;
1159 If1 = DAG.getNode(UseOpc, dl, UVT, Ops);
1160 }
1161 SDValue Sel = DAG.getNode(ISD::SELECT, dl, UVT, OpI1, If1, If0);
1162 DAG.ReplaceAllUsesWith(U, Sel.getNode());
1163 }
1164 }
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001165}
1166
1167void HexagonDAGToDAGISel::PreprocessISelDAG() {
1168 // Repack all nodes before calling each preprocessing function,
1169 // because each of them can modify the set of nodes.
1170 auto getNodes = [this] () -> std::vector<SDNode*> {
1171 std::vector<SDNode*> T;
1172 T.reserve(CurDAG->allnodes_size());
1173 for (SDNode &N : CurDAG->allnodes())
1174 T.push_back(&N);
1175 return T;
1176 };
1177
1178 // Transform: (or (select c x 0) z) -> (select c (or x z) z)
1179 // (or (select c 0 y) z) -> (select c z (or y z))
1180 ppSimplifyOrSelect0(getNodes());
1181
1182 // Transform: (store ch val (add x (add (shl y c) e)))
1183 // to: (store ch val (add x (shl (add y d) c))),
1184 // where e = (shl d c) for some integer d.
1185 // The purpose of this is to enable generation of loads/stores with
1186 // shifted addressing mode, i.e. mem(x+y<<#c). For that, the shift
1187 // value c must be 0, 1 or 2.
1188 ppAddrReorderAddShl(getNodes());
1189
1190 // Transform: (load ch (add x (and (srl y c) Mask)))
1191 // to: (load ch (add x (shl (srl y d) d-c)))
1192 // where
1193 // Mask = 00..0 111..1 0.0
1194 // | | +-- d-c 0s, and d-c is 0, 1 or 2.
1195 // | +-------- 1s
1196 // +-------------- at most c 0s
1197 // Motivating example:
1198 // DAG combiner optimizes (add x (shl (srl y 5) 2))
1199 // to (add x (and (srl y 3) 1FFFFFFC))
1200 // which results in a constant-extended and(##...,lsr). This transformation
1201 // undoes this simplification for cases where the shl can be folded into
1202 // an addressing mode.
1203 ppAddrRewriteAndSrl(getNodes());
1204
1205 // Transform: (op ... (zext i1 c) ...) -> (select c (op ... 0 ...)
1206 // (op ... 1 ...))
1207 ppHoistZextI1(getNodes());
Krzysztof Parzyszek78c4fcf2017-03-09 16:29:30 +00001208
1209 DEBUG_WITH_TYPE("isel", {
1210 dbgs() << "Preprocessed (Hexagon) selection DAG:";
1211 CurDAG->dump();
1212 });
1213
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001214 if (EnableAddressRebalancing) {
1215 rebalanceAddressTrees();
1216
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001217 DEBUG_WITH_TYPE("isel", {
1218 dbgs() << "Address tree balanced selection DAG:";
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001219 CurDAG->dump();
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001220 });
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001221 }
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +00001222}
1223
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001224void HexagonDAGToDAGISel::EmitFunctionEntryCode() {
1225 auto &HST = static_cast<const HexagonSubtarget&>(MF->getSubtarget());
1226 auto &HFI = *HST.getFrameLowering();
1227 if (!HFI.needsAligna(*MF))
1228 return;
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +00001229
Matthias Braun941a7052016-07-28 18:40:00 +00001230 MachineFrameInfo &MFI = MF->getFrameInfo();
Duncan P. N. Exon Smitha72c6e22015-10-20 00:46:39 +00001231 MachineBasicBlock *EntryBB = &MF->front();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001232 unsigned AR = FuncInfo->CreateReg(MVT::i32);
Matthias Braun941a7052016-07-28 18:40:00 +00001233 unsigned MaxA = MFI.getMaxAlignment();
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +00001234 BuildMI(EntryBB, DebugLoc(), HII->get(Hexagon::PS_aligna), AR)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001235 .addImm(MaxA);
1236 MF->getInfo<HexagonMachineFunctionInfo>()->setStackAlignBaseVReg(AR);
1237}
1238
1239// Match a frame index that can be used in an addressing mode.
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001240bool HexagonDAGToDAGISel::SelectAddrFI(SDValue &N, SDValue &R) {
Colin LeMahieuc7522f32015-01-14 23:07:36 +00001241 if (N.getOpcode() != ISD::FrameIndex)
1242 return false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001243 auto &HFI = *HST->getFrameLowering();
Matthias Braun941a7052016-07-28 18:40:00 +00001244 MachineFrameInfo &MFI = MF->getFrameInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001245 int FX = cast<FrameIndexSDNode>(N)->getIndex();
Matthias Braun941a7052016-07-28 18:40:00 +00001246 if (!MFI.isFixedObjectIndex(FX) && HFI.needsAligna(*MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001247 return false;
1248 R = CurDAG->getTargetFrameIndex(FX, MVT::i32);
Colin LeMahieuc7522f32015-01-14 23:07:36 +00001249 return true;
1250}
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001251
Colin LeMahieu987b0942015-02-04 20:38:01 +00001252inline bool HexagonDAGToDAGISel::SelectAddrGA(SDValue &N, SDValue &R) {
1253 return SelectGlobalAddress(N, R, false);
1254}
1255
Colin LeMahieu51491352015-02-04 22:36:28 +00001256inline bool HexagonDAGToDAGISel::SelectAddrGP(SDValue &N, SDValue &R) {
1257 return SelectGlobalAddress(N, R, true);
1258}
1259
Colin LeMahieu987b0942015-02-04 20:38:01 +00001260bool HexagonDAGToDAGISel::SelectGlobalAddress(SDValue &N, SDValue &R,
1261 bool UseGP) {
1262 switch (N.getOpcode()) {
1263 case ISD::ADD: {
1264 SDValue N0 = N.getOperand(0);
1265 SDValue N1 = N.getOperand(1);
1266 unsigned GAOpc = N0.getOpcode();
1267 if (UseGP && GAOpc != HexagonISD::CONST32_GP)
1268 return false;
1269 if (!UseGP && GAOpc != HexagonISD::CONST32)
1270 return false;
1271 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N1)) {
1272 SDValue Addr = N0.getOperand(0);
1273 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Addr)) {
1274 if (GA->getOpcode() == ISD::TargetGlobalAddress) {
1275 uint64_t NewOff = GA->getOffset() + (uint64_t)Const->getSExtValue();
1276 R = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(Const),
1277 N.getValueType(), NewOff);
1278 return true;
1279 }
1280 }
1281 }
1282 break;
1283 }
1284 case HexagonISD::CONST32:
1285 // The operand(0) of CONST32 is TargetGlobalAddress, which is what we
1286 // want in the instruction.
1287 if (!UseGP)
1288 R = N.getOperand(0);
1289 return !UseGP;
1290 case HexagonISD::CONST32_GP:
1291 if (UseGP)
1292 R = N.getOperand(0);
1293 return UseGP;
1294 default:
1295 return false;
1296 }
1297
1298 return false;
1299}
1300
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001301bool HexagonDAGToDAGISel::DetectUseSxtw(SDValue &N, SDValue &R) {
1302 // This (complex pattern) function is meant to detect a sign-extension
1303 // i32->i64 on a per-operand basis. This would allow writing single
1304 // patterns that would cover a number of combinations of different ways
1305 // a sign-extensions could be written. For example:
1306 // (mul (DetectUseSxtw x) (DetectUseSxtw y)) -> (M2_dpmpyss_s0 x y)
1307 // could match either one of these:
1308 // (mul (sext x) (sext_inreg y))
1309 // (mul (sext-load *p) (sext_inreg y))
1310 // (mul (sext_inreg x) (sext y))
1311 // etc.
1312 //
1313 // The returned value will have type i64 and its low word will
1314 // contain the value being extended. The high bits are not specified.
1315 // The returned type is i64 because the original type of N was i64,
1316 // but the users of this function should only use the low-word of the
1317 // result, e.g.
1318 // (mul sxtw:x, sxtw:y) -> (M2_dpmpyss_s0 (LoReg sxtw:x), (LoReg sxtw:y))
1319
1320 if (N.getValueType() != MVT::i64)
1321 return false;
1322 EVT SrcVT;
1323 unsigned Opc = N.getOpcode();
1324 switch (Opc) {
1325 case ISD::SIGN_EXTEND:
1326 case ISD::SIGN_EXTEND_INREG: {
1327 // sext_inreg has the source type as a separate operand.
1328 EVT T = Opc == ISD::SIGN_EXTEND
1329 ? N.getOperand(0).getValueType()
1330 : cast<VTSDNode>(N.getOperand(1))->getVT();
1331 if (T.getSizeInBits() != 32)
1332 return false;
1333 R = N.getOperand(0);
1334 break;
1335 }
1336 case ISD::LOAD: {
1337 LoadSDNode *L = cast<LoadSDNode>(N);
1338 if (L->getExtensionType() != ISD::SEXTLOAD)
1339 return false;
1340 // All extending loads extend to i32, so even if the value in
1341 // memory is shorter than 32 bits, it will be i32 after the load.
1342 if (L->getMemoryVT().getSizeInBits() > 32)
1343 return false;
1344 R = N;
1345 break;
1346 }
1347 default:
1348 return false;
1349 }
1350 EVT RT = R.getValueType();
1351 if (RT == MVT::i64)
1352 return true;
1353 assert(RT == MVT::i32);
1354 // This is only to produce a value of type i64. Do not rely on the
1355 // high bits produced by this.
1356 const SDLoc &dl(N);
1357 SDValue Ops[] = {
1358 CurDAG->getTargetConstant(Hexagon::DoubleRegsRegClassID, dl, MVT::i32),
1359 R, CurDAG->getTargetConstant(Hexagon::isub_hi, dl, MVT::i32),
1360 R, CurDAG->getTargetConstant(Hexagon::isub_lo, dl, MVT::i32)
1361 };
1362 SDNode *T = CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl,
1363 MVT::i64, Ops);
1364 R = SDValue(T, 0);
1365 return true;
1366}
1367
1368bool HexagonDAGToDAGISel::keepsLowBits(const SDValue &Val, unsigned NumBits,
1369 SDValue &Src) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001370 unsigned Opc = Val.getOpcode();
1371 switch (Opc) {
1372 case ISD::SIGN_EXTEND:
1373 case ISD::ZERO_EXTEND:
1374 case ISD::ANY_EXTEND: {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001375 const SDValue &Op0 = Val.getOperand(0);
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001376 EVT T = Op0.getValueType();
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001377 if (T.isInteger() && T.getSizeInBits() == NumBits) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001378 Src = Op0;
1379 return true;
1380 }
1381 break;
1382 }
1383 case ISD::SIGN_EXTEND_INREG:
1384 case ISD::AssertSext:
1385 case ISD::AssertZext:
1386 if (Val.getOperand(0).getValueType().isInteger()) {
1387 VTSDNode *T = cast<VTSDNode>(Val.getOperand(1));
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001388 if (T->getVT().getSizeInBits() == NumBits) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001389 Src = Val.getOperand(0);
1390 return true;
1391 }
1392 }
1393 break;
1394 case ISD::AND: {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001395 // Check if this is an AND with NumBits of lower bits set to 1.
1396 uint64_t Mask = (1 << NumBits) - 1;
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001397 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(0))) {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001398 if (C->getZExtValue() == Mask) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001399 Src = Val.getOperand(1);
1400 return true;
1401 }
1402 }
1403 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(1))) {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001404 if (C->getZExtValue() == Mask) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001405 Src = Val.getOperand(0);
1406 return true;
1407 }
1408 }
1409 break;
1410 }
1411 case ISD::OR:
1412 case ISD::XOR: {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001413 // OR/XOR with the lower NumBits bits set to 0.
1414 uint64_t Mask = (1 << NumBits) - 1;
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001415 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(0))) {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001416 if ((C->getZExtValue() & Mask) == 0) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001417 Src = Val.getOperand(1);
1418 return true;
1419 }
1420 }
1421 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(1))) {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001422 if ((C->getZExtValue() & Mask) == 0) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001423 Src = Val.getOperand(0);
1424 return true;
1425 }
1426 }
1427 }
1428 default:
1429 break;
1430 }
1431 return false;
1432}
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001433
Krzysztof Parzyszekbba0bf72016-07-15 15:35:52 +00001434
Krzysztof Parzyszekb16a4e52016-11-14 20:53:09 +00001435bool HexagonDAGToDAGISel::isOrEquivalentToAdd(const SDNode *N) const {
Krzysztof Parzyszekbba0bf72016-07-15 15:35:52 +00001436 assert(N->getOpcode() == ISD::OR);
1437 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
1438 assert(C);
1439
1440 // Detect when "or" is used to add an offset to a stack object.
1441 if (auto *FN = dyn_cast<FrameIndexSDNode>(N->getOperand(0))) {
Matthias Braun941a7052016-07-28 18:40:00 +00001442 MachineFrameInfo &MFI = MF->getFrameInfo();
1443 unsigned A = MFI.getObjectAlignment(FN->getIndex());
Krzysztof Parzyszekbba0bf72016-07-15 15:35:52 +00001444 assert(isPowerOf2_32(A));
1445 int32_t Off = C->getSExtValue();
1446 // If the alleged offset fits in the zero bits guaranteed by
1447 // the alignment, then this or is really an add.
1448 return (Off >= 0) && (((A-1) & Off) == unsigned(Off));
1449 }
1450 return false;
1451}
1452
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001453bool HexagonDAGToDAGISel::isAlignedMemNode(const MemSDNode *N) const {
1454 return N->getAlignment() >= N->getMemoryVT().getStoreSize();
1455}
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001456
Krzysztof Parzyszekb3a8d202017-06-13 17:10:16 +00001457bool HexagonDAGToDAGISel::isSmallStackStore(const StoreSDNode *N) const {
1458 unsigned StackSize = MF->getFrameInfo().estimateStackSize(*MF);
1459 switch (N->getMemoryVT().getStoreSize()) {
1460 case 1:
1461 return StackSize <= 56; // 1*2^6 - 8
1462 case 2:
1463 return StackSize <= 120; // 2*2^6 - 8
1464 case 4:
1465 return StackSize <= 248; // 4*2^6 - 8
1466 default:
1467 return false;
1468 }
1469}
1470
Krzysztof Parzyszek2839b292016-11-05 21:44:50 +00001471// Return true when the given node fits in a positive half word.
1472bool HexagonDAGToDAGISel::isPositiveHalfWord(const SDNode *N) const {
1473 if (const ConstantSDNode *CN = dyn_cast<const ConstantSDNode>(N)) {
1474 int64_t V = CN->getSExtValue();
1475 return V > 0 && isInt<16>(V);
1476 }
1477 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG) {
1478 const VTSDNode *VN = dyn_cast<const VTSDNode>(N->getOperand(1));
1479 return VN->getVT().getSizeInBits() <= 16;
1480 }
1481 return false;
1482}
1483
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001484////////////////////////////////////////////////////////////////////////////////
1485// Rebalancing of address calculation trees
1486
1487static bool isOpcodeHandled(const SDNode *N) {
1488 switch (N->getOpcode()) {
1489 case ISD::ADD:
1490 case ISD::MUL:
1491 return true;
1492 case ISD::SHL:
1493 // We only handle constant shifts because these can be easily flattened
1494 // into multiplications by 2^Op1.
1495 return isa<ConstantSDNode>(N->getOperand(1).getNode());
1496 default:
1497 return false;
1498 }
1499}
1500
1501/// \brief Return the weight of an SDNode
1502int HexagonDAGToDAGISel::getWeight(SDNode *N) {
1503 if (!isOpcodeHandled(N))
1504 return 1;
1505 assert(RootWeights.count(N) && "Cannot get weight of unseen root!");
1506 assert(RootWeights[N] != -1 && "Cannot get weight of unvisited root!");
1507 assert(RootWeights[N] != -2 && "Cannot get weight of RAWU'd root!");
1508 return RootWeights[N];
1509}
1510
1511int HexagonDAGToDAGISel::getHeight(SDNode *N) {
1512 if (!isOpcodeHandled(N))
1513 return 0;
1514 assert(RootWeights.count(N) && RootWeights[N] >= 0 &&
1515 "Cannot query height of unvisited/RAUW'd node!");
1516 return RootHeights[N];
1517}
1518
Benjamin Kramerb7d33112016-08-06 11:13:10 +00001519namespace {
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001520struct WeightedLeaf {
1521 SDValue Value;
1522 int Weight;
1523 int InsertionOrder;
1524
1525 WeightedLeaf() : Value(SDValue()) { }
1526
1527 WeightedLeaf(SDValue Value, int Weight, int InsertionOrder) :
1528 Value(Value), Weight(Weight), InsertionOrder(InsertionOrder) {
1529 assert(Weight >= 0 && "Weight must be >= 0");
1530 }
1531
1532 static bool Compare(const WeightedLeaf &A, const WeightedLeaf &B) {
1533 assert(A.Value.getNode() && B.Value.getNode());
1534 return A.Weight == B.Weight ?
1535 (A.InsertionOrder > B.InsertionOrder) :
1536 (A.Weight > B.Weight);
1537 }
1538};
1539
1540/// A specialized priority queue for WeigthedLeaves. It automatically folds
1541/// constants and allows removal of non-top elements while maintaining the
1542/// priority order.
1543class LeafPrioQueue {
1544 SmallVector<WeightedLeaf, 8> Q;
1545 bool HaveConst;
1546 WeightedLeaf ConstElt;
1547 unsigned Opcode;
1548
1549public:
1550 bool empty() {
1551 return (!HaveConst && Q.empty());
1552 }
1553
1554 size_t size() {
1555 return Q.size() + HaveConst;
1556 }
1557
1558 bool hasConst() {
1559 return HaveConst;
1560 }
1561
1562 const WeightedLeaf &top() {
1563 if (HaveConst)
1564 return ConstElt;
1565 return Q.front();
1566 }
1567
1568 WeightedLeaf pop() {
1569 if (HaveConst) {
1570 HaveConst = false;
1571 return ConstElt;
1572 }
1573 std::pop_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1574 return Q.pop_back_val();
1575 }
1576
1577 void push(WeightedLeaf L, bool SeparateConst=true) {
1578 if (!HaveConst && SeparateConst && isa<ConstantSDNode>(L.Value)) {
1579 if (Opcode == ISD::MUL &&
1580 cast<ConstantSDNode>(L.Value)->getSExtValue() == 1)
1581 return;
1582 if (Opcode == ISD::ADD &&
1583 cast<ConstantSDNode>(L.Value)->getSExtValue() == 0)
1584 return;
1585
1586 HaveConst = true;
1587 ConstElt = L;
1588 } else {
1589 Q.push_back(L);
1590 std::push_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1591 }
1592 }
1593
1594 /// Push L to the bottom of the queue regardless of its weight. If L is
1595 /// constant, it will not be folded with other constants in the queue.
1596 void pushToBottom(WeightedLeaf L) {
1597 L.Weight = 1000;
1598 push(L, false);
1599 }
1600
1601 /// Search for a SHL(x, [<=MaxAmount]) subtree in the queue, return the one of
1602 /// lowest weight and remove it from the queue.
1603 WeightedLeaf findSHL(uint64_t MaxAmount);
1604
1605 WeightedLeaf findMULbyConst();
1606
1607 LeafPrioQueue(unsigned Opcode) :
1608 HaveConst(false), Opcode(Opcode) { }
1609};
Benjamin Kramerb7d33112016-08-06 11:13:10 +00001610} // end anonymous namespace
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001611
1612WeightedLeaf LeafPrioQueue::findSHL(uint64_t MaxAmount) {
1613 int ResultPos;
1614 WeightedLeaf Result;
1615
1616 for (int Pos = 0, End = Q.size(); Pos != End; ++Pos) {
1617 const WeightedLeaf &L = Q[Pos];
1618 const SDValue &Val = L.Value;
1619 if (Val.getOpcode() != ISD::SHL ||
1620 !isa<ConstantSDNode>(Val.getOperand(1)) ||
1621 Val.getConstantOperandVal(1) > MaxAmount)
1622 continue;
1623 if (!Result.Value.getNode() || Result.Weight > L.Weight ||
1624 (Result.Weight == L.Weight && Result.InsertionOrder > L.InsertionOrder))
1625 {
1626 Result = L;
1627 ResultPos = Pos;
1628 }
1629 }
1630
1631 if (Result.Value.getNode()) {
1632 Q.erase(&Q[ResultPos]);
1633 std::make_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1634 }
1635
1636 return Result;
1637}
1638
1639WeightedLeaf LeafPrioQueue::findMULbyConst() {
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::MUL ||
1647 !isa<ConstantSDNode>(Val.getOperand(1)) ||
1648 Val.getConstantOperandVal(1) > 127)
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
1666SDValue HexagonDAGToDAGISel::getMultiplierForSHL(SDNode *N) {
Simon Pilgrim7c858622016-07-29 18:43:59 +00001667 uint64_t MulFactor = 1ull << N->getConstantOperandVal(1);
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001668 return CurDAG->getConstant(MulFactor, SDLoc(N),
1669 N->getOperand(1).getValueType());
1670}
1671
1672/// @returns the value x for which 2^x is a factor of Val
1673static unsigned getPowerOf2Factor(SDValue Val) {
1674 if (Val.getOpcode() == ISD::MUL) {
1675 unsigned MaxFactor = 0;
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00001676 for (int i = 0; i < 2; ++i) {
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001677 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(i));
1678 if (!C)
1679 continue;
1680 const APInt &CInt = C->getAPIntValue();
1681 if (CInt.getBoolValue())
1682 MaxFactor = CInt.countTrailingZeros();
1683 }
1684 return MaxFactor;
1685 }
1686 if (Val.getOpcode() == ISD::SHL) {
1687 if (!isa<ConstantSDNode>(Val.getOperand(1).getNode()))
1688 return 0;
1689 return (unsigned) Val.getConstantOperandVal(1);
1690 }
1691
1692 return 0;
1693}
1694
1695/// @returns true if V>>Amount will eliminate V's operation on its child
1696static bool willShiftRightEliminate(SDValue V, unsigned Amount) {
1697 if (V.getOpcode() == ISD::MUL) {
1698 SDValue Ops[] = { V.getOperand(0), V.getOperand(1) };
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00001699 for (int i = 0; i < 2; ++i)
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001700 if (isa<ConstantSDNode>(Ops[i].getNode()) &&
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00001701 V.getConstantOperandVal(i) % (1ULL << Amount) == 0) {
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001702 uint64_t NewConst = V.getConstantOperandVal(i) >> Amount;
1703 return (NewConst == 1);
1704 }
1705 } else if (V.getOpcode() == ISD::SHL) {
1706 return (Amount == V.getConstantOperandVal(1));
1707 }
1708
1709 return false;
1710}
1711
1712SDValue HexagonDAGToDAGISel::factorOutPowerOf2(SDValue V, unsigned Power) {
1713 SDValue Ops[] = { V.getOperand(0), V.getOperand(1) };
1714 if (V.getOpcode() == ISD::MUL) {
1715 for (int i=0; i < 2; ++i) {
1716 if (isa<ConstantSDNode>(Ops[i].getNode()) &&
1717 V.getConstantOperandVal(i) % ((uint64_t)1 << Power) == 0) {
1718 uint64_t NewConst = V.getConstantOperandVal(i) >> Power;
1719 if (NewConst == 1)
1720 return Ops[!i];
1721 Ops[i] = CurDAG->getConstant(NewConst,
1722 SDLoc(V), V.getValueType());
1723 break;
1724 }
1725 }
1726 } else if (V.getOpcode() == ISD::SHL) {
1727 uint64_t ShiftAmount = V.getConstantOperandVal(1);
1728 if (ShiftAmount == Power)
1729 return Ops[0];
1730 Ops[1] = CurDAG->getConstant(ShiftAmount - Power,
1731 SDLoc(V), V.getValueType());
1732 }
1733
1734 return CurDAG->getNode(V.getOpcode(), SDLoc(V), V.getValueType(), Ops);
1735}
1736
1737static bool isTargetConstant(const SDValue &V) {
1738 return V.getOpcode() == HexagonISD::CONST32 ||
1739 V.getOpcode() == HexagonISD::CONST32_GP;
1740}
1741
1742unsigned HexagonDAGToDAGISel::getUsesInFunction(const Value *V) {
1743 if (GAUsesInFunction.count(V))
1744 return GAUsesInFunction[V];
1745
1746 unsigned Result = 0;
1747 const Function *CurF = CurDAG->getMachineFunction().getFunction();
1748 for (const User *U : V->users()) {
1749 if (isa<Instruction>(U) &&
1750 cast<Instruction>(U)->getParent()->getParent() == CurF)
1751 ++Result;
1752 }
1753
1754 GAUsesInFunction[V] = Result;
1755
1756 return Result;
1757}
1758
1759/// Note - After calling this, N may be dead. It may have been replaced by a
1760/// new node, so always use the returned value in place of N.
1761///
1762/// @returns The SDValue taking the place of N (which could be N if it is
1763/// unchanged)
1764SDValue HexagonDAGToDAGISel::balanceSubTree(SDNode *N, bool TopLevel) {
1765 assert(RootWeights.count(N) && "Cannot balance non-root node.");
1766 assert(RootWeights[N] != -2 && "This node was RAUW'd!");
1767 assert(!TopLevel || N->getOpcode() == ISD::ADD);
1768
1769 // Return early if this node was already visited
1770 if (RootWeights[N] != -1)
1771 return SDValue(N, 0);
1772
1773 assert(isOpcodeHandled(N));
1774
1775 SDValue Op0 = N->getOperand(0);
1776 SDValue Op1 = N->getOperand(1);
1777
1778 // Return early if the operands will remain unchanged or are all roots
1779 if ((!isOpcodeHandled(Op0.getNode()) || RootWeights.count(Op0.getNode())) &&
1780 (!isOpcodeHandled(Op1.getNode()) || RootWeights.count(Op1.getNode()))) {
1781 SDNode *Op0N = Op0.getNode();
1782 int Weight;
1783 if (isOpcodeHandled(Op0N) && RootWeights[Op0N] == -1) {
1784 Weight = getWeight(balanceSubTree(Op0N).getNode());
1785 // Weight = calculateWeight(Op0N);
1786 } else
1787 Weight = getWeight(Op0N);
1788
1789 SDNode *Op1N = N->getOperand(1).getNode(); // Op1 may have been RAUWd
1790 if (isOpcodeHandled(Op1N) && RootWeights[Op1N] == -1) {
1791 Weight += getWeight(balanceSubTree(Op1N).getNode());
1792 // Weight += calculateWeight(Op1N);
1793 } else
1794 Weight += getWeight(Op1N);
1795
1796 RootWeights[N] = Weight;
1797 RootHeights[N] = std::max(getHeight(N->getOperand(0).getNode()),
1798 getHeight(N->getOperand(1).getNode())) + 1;
1799
1800 DEBUG(dbgs() << "--> No need to balance root (Weight=" << Weight
1801 << " Height=" << RootHeights[N] << "): ");
1802 DEBUG(N->dump());
1803
1804 return SDValue(N, 0);
1805 }
1806
1807 DEBUG(dbgs() << "** Balancing root node: ");
1808 DEBUG(N->dump());
1809
1810 unsigned NOpcode = N->getOpcode();
1811
1812 LeafPrioQueue Leaves(NOpcode);
1813 SmallVector<SDValue, 4> Worklist;
1814 Worklist.push_back(SDValue(N, 0));
1815
1816 // SHL nodes will be converted to MUL nodes
1817 if (NOpcode == ISD::SHL)
1818 NOpcode = ISD::MUL;
1819
1820 bool CanFactorize = false;
1821 WeightedLeaf Mul1, Mul2;
1822 unsigned MaxPowerOf2 = 0;
1823 WeightedLeaf GA;
1824
1825 // Do not try to factor out a shift if there is already a shift at the tip of
1826 // the tree.
1827 bool HaveTopLevelShift = false;
1828 if (TopLevel &&
1829 ((isOpcodeHandled(Op0.getNode()) && Op0.getOpcode() == ISD::SHL &&
1830 Op0.getConstantOperandVal(1) < 4) ||
1831 (isOpcodeHandled(Op1.getNode()) && Op1.getOpcode() == ISD::SHL &&
1832 Op1.getConstantOperandVal(1) < 4)))
1833 HaveTopLevelShift = true;
1834
1835 // Flatten the subtree into an ordered list of leaves; at the same time
1836 // determine whether the tree is already balanced.
1837 int InsertionOrder = 0;
1838 SmallDenseMap<SDValue, int> NodeHeights;
1839 bool Imbalanced = false;
1840 int CurrentWeight = 0;
1841 while (!Worklist.empty()) {
1842 SDValue Child = Worklist.pop_back_val();
1843
1844 if (Child.getNode() != N && RootWeights.count(Child.getNode())) {
1845 // CASE 1: Child is a root note
1846
1847 int Weight = RootWeights[Child.getNode()];
1848 if (Weight == -1) {
1849 Child = balanceSubTree(Child.getNode());
1850 // calculateWeight(Child.getNode());
1851 Weight = getWeight(Child.getNode());
1852 } else if (Weight == -2) {
1853 // Whoops, this node was RAUWd by one of the balanceSubTree calls we
1854 // made. Our worklist isn't up to date anymore.
1855 // Restart the whole process.
1856 DEBUG(dbgs() << "--> Subtree was RAUWd. Restarting...\n");
1857 return balanceSubTree(N, TopLevel);
1858 }
1859
1860 NodeHeights[Child] = 1;
1861 CurrentWeight += Weight;
1862
1863 unsigned PowerOf2;
1864 if (TopLevel && !CanFactorize && !HaveTopLevelShift &&
1865 (Child.getOpcode() == ISD::MUL || Child.getOpcode() == ISD::SHL) &&
1866 Child.hasOneUse() && (PowerOf2 = getPowerOf2Factor(Child))) {
1867 // Try to identify two factorizable MUL/SHL children greedily. Leave
1868 // them out of the priority queue for now so we can deal with them
1869 // after.
1870 if (!Mul1.Value.getNode()) {
1871 Mul1 = WeightedLeaf(Child, Weight, InsertionOrder++);
1872 MaxPowerOf2 = PowerOf2;
1873 } else {
1874 Mul2 = WeightedLeaf(Child, Weight, InsertionOrder++);
1875 MaxPowerOf2 = std::min(MaxPowerOf2, PowerOf2);
1876
1877 // Our addressing modes can only shift by a maximum of 3
1878 if (MaxPowerOf2 > 3)
1879 MaxPowerOf2 = 3;
1880
1881 CanFactorize = true;
1882 }
1883 } else
1884 Leaves.push(WeightedLeaf(Child, Weight, InsertionOrder++));
1885 } else if (!isOpcodeHandled(Child.getNode())) {
1886 // CASE 2: Child is an unhandled kind of node (e.g. constant)
1887 int Weight = getWeight(Child.getNode());
1888
1889 NodeHeights[Child] = getHeight(Child.getNode());
1890 CurrentWeight += Weight;
1891
1892 if (isTargetConstant(Child) && !GA.Value.getNode())
1893 GA = WeightedLeaf(Child, Weight, InsertionOrder++);
1894 else
1895 Leaves.push(WeightedLeaf(Child, Weight, InsertionOrder++));
1896 } else {
1897 // CASE 3: Child is a subtree of same opcode
1898 // Visit children first, then flatten.
1899 unsigned ChildOpcode = Child.getOpcode();
1900 assert(ChildOpcode == NOpcode ||
1901 (NOpcode == ISD::MUL && ChildOpcode == ISD::SHL));
1902
1903 // Convert SHL to MUL
1904 SDValue Op1;
1905 if (ChildOpcode == ISD::SHL)
1906 Op1 = getMultiplierForSHL(Child.getNode());
1907 else
1908 Op1 = Child->getOperand(1);
1909
1910 if (!NodeHeights.count(Op1) || !NodeHeights.count(Child->getOperand(0))) {
1911 assert(!NodeHeights.count(Child) && "Parent visited before children?");
1912 // Visit children first, then re-visit this node
1913 Worklist.push_back(Child);
1914 Worklist.push_back(Op1);
1915 Worklist.push_back(Child->getOperand(0));
1916 } else {
1917 // Back at this node after visiting the children
1918 if (std::abs(NodeHeights[Op1] - NodeHeights[Child->getOperand(0)]) > 1)
1919 Imbalanced = true;
1920
1921 NodeHeights[Child] = std::max(NodeHeights[Op1],
1922 NodeHeights[Child->getOperand(0)]) + 1;
1923 }
1924 }
1925 }
1926
1927 DEBUG(dbgs() << "--> Current height=" << NodeHeights[SDValue(N, 0)]
1928 << " weight=" << CurrentWeight << " imbalanced="
1929 << Imbalanced << "\n");
1930
1931 // Transform MUL(x, C * 2^Y) + SHL(z, Y) -> SHL(ADD(MUL(x, C), z), Y)
1932 // This factors out a shift in order to match memw(a<<Y+b).
1933 if (CanFactorize && (willShiftRightEliminate(Mul1.Value, MaxPowerOf2) ||
1934 willShiftRightEliminate(Mul2.Value, MaxPowerOf2))) {
1935 DEBUG(dbgs() << "--> Found common factor for two MUL children!\n");
1936 int Weight = Mul1.Weight + Mul2.Weight;
1937 int Height = std::max(NodeHeights[Mul1.Value], NodeHeights[Mul2.Value]) + 1;
1938 SDValue Mul1Factored = factorOutPowerOf2(Mul1.Value, MaxPowerOf2);
1939 SDValue Mul2Factored = factorOutPowerOf2(Mul2.Value, MaxPowerOf2);
1940 SDValue Sum = CurDAG->getNode(ISD::ADD, SDLoc(N), Mul1.Value.getValueType(),
1941 Mul1Factored, Mul2Factored);
1942 SDValue Const = CurDAG->getConstant(MaxPowerOf2, SDLoc(N),
1943 Mul1.Value.getValueType());
1944 SDValue New = CurDAG->getNode(ISD::SHL, SDLoc(N), Mul1.Value.getValueType(),
1945 Sum, Const);
1946 NodeHeights[New] = Height;
1947 Leaves.push(WeightedLeaf(New, Weight, Mul1.InsertionOrder));
1948 } else if (Mul1.Value.getNode()) {
1949 // We failed to factorize two MULs, so now the Muls are left outside the
1950 // queue... add them back.
1951 Leaves.push(Mul1);
1952 if (Mul2.Value.getNode())
1953 Leaves.push(Mul2);
1954 CanFactorize = false;
1955 }
1956
1957 // Combine GA + Constant -> GA+Offset, but only if GA is not used elsewhere
1958 // and the root node itself is not used more than twice. This reduces the
1959 // amount of additional constant extenders introduced by this optimization.
1960 bool CombinedGA = false;
1961 if (NOpcode == ISD::ADD && GA.Value.getNode() && Leaves.hasConst() &&
1962 GA.Value.hasOneUse() && N->use_size() < 3) {
1963 GlobalAddressSDNode *GANode =
1964 cast<GlobalAddressSDNode>(GA.Value.getOperand(0));
1965 ConstantSDNode *Offset = cast<ConstantSDNode>(Leaves.top().Value);
1966
1967 if (getUsesInFunction(GANode->getGlobal()) == 1 && Offset->hasOneUse() &&
1968 getTargetLowering()->isOffsetFoldingLegal(GANode)) {
1969 DEBUG(dbgs() << "--> Combining GA and offset (" << Offset->getSExtValue()
1970 << "): ");
1971 DEBUG(GANode->dump());
1972
1973 SDValue NewTGA =
1974 CurDAG->getTargetGlobalAddress(GANode->getGlobal(), SDLoc(GA.Value),
1975 GANode->getValueType(0),
1976 GANode->getOffset() + (uint64_t)Offset->getSExtValue());
1977 GA.Value = CurDAG->getNode(GA.Value.getOpcode(), SDLoc(GA.Value),
1978 GA.Value.getValueType(), NewTGA);
1979 GA.Weight += Leaves.top().Weight;
1980
1981 NodeHeights[GA.Value] = getHeight(GA.Value.getNode());
1982 CombinedGA = true;
1983
1984 Leaves.pop(); // Remove the offset constant from the queue
1985 }
1986 }
1987
1988 if ((RebalanceOnlyForOptimizations && !CanFactorize && !CombinedGA) ||
1989 (RebalanceOnlyImbalancedTrees && !Imbalanced)) {
1990 RootWeights[N] = CurrentWeight;
1991 RootHeights[N] = NodeHeights[SDValue(N, 0)];
1992
1993 return SDValue(N, 0);
1994 }
1995
1996 // Combine GA + SHL(x, C<=31) so we will match Rx=add(#u8,asl(Rx,#U5))
1997 if (NOpcode == ISD::ADD && GA.Value.getNode()) {
1998 WeightedLeaf SHL = Leaves.findSHL(31);
1999 if (SHL.Value.getNode()) {
2000 int Height = std::max(NodeHeights[GA.Value], NodeHeights[SHL.Value]) + 1;
2001 GA.Value = CurDAG->getNode(ISD::ADD, SDLoc(GA.Value),
2002 GA.Value.getValueType(),
2003 GA.Value, SHL.Value);
2004 GA.Weight = SHL.Weight; // Specifically ignore the GA weight here
2005 NodeHeights[GA.Value] = Height;
2006 }
2007 }
2008
2009 if (GA.Value.getNode())
2010 Leaves.push(GA);
2011
2012 // If this is the top level and we haven't factored out a shift, we should try
2013 // to move a constant to the bottom to match addressing modes like memw(rX+C)
2014 if (TopLevel && !CanFactorize && Leaves.hasConst()) {
2015 DEBUG(dbgs() << "--> Pushing constant to tip of tree.");
2016 Leaves.pushToBottom(Leaves.pop());
2017 }
2018
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00002019 const DataLayout &DL = CurDAG->getDataLayout();
2020 const TargetLowering &TLI = *getTargetLowering();
2021
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002022 // Rebuild the tree using Huffman's algorithm
2023 while (Leaves.size() > 1) {
2024 WeightedLeaf L0 = Leaves.pop();
2025
2026 // See whether we can grab a MUL to form an add(Rx,mpyi(Ry,#u6)),
2027 // otherwise just get the next leaf
2028 WeightedLeaf L1 = Leaves.findMULbyConst();
2029 if (!L1.Value.getNode())
2030 L1 = Leaves.pop();
2031
2032 assert(L0.Weight <= L1.Weight && "Priority queue is broken!");
2033
2034 SDValue V0 = L0.Value;
2035 int V0Weight = L0.Weight;
2036 SDValue V1 = L1.Value;
2037 int V1Weight = L1.Weight;
2038
2039 // Make sure that none of these nodes have been RAUW'd
2040 if ((RootWeights.count(V0.getNode()) && RootWeights[V0.getNode()] == -2) ||
2041 (RootWeights.count(V1.getNode()) && RootWeights[V1.getNode()] == -2)) {
2042 DEBUG(dbgs() << "--> Subtree was RAUWd. Restarting...\n");
2043 return balanceSubTree(N, TopLevel);
2044 }
2045
2046 ConstantSDNode *V0C = dyn_cast<ConstantSDNode>(V0);
2047 ConstantSDNode *V1C = dyn_cast<ConstantSDNode>(V1);
2048 EVT VT = N->getValueType(0);
2049 SDValue NewNode;
2050
2051 if (V0C && !V1C) {
2052 std::swap(V0, V1);
2053 std::swap(V0C, V1C);
2054 }
2055
2056 // Calculate height of this node
2057 assert(NodeHeights.count(V0) && NodeHeights.count(V1) &&
2058 "Children must have been visited before re-combining them!");
2059 int Height = std::max(NodeHeights[V0], NodeHeights[V1]) + 1;
2060
2061 // Rebuild this node (and restore SHL from MUL if needed)
2062 if (V1C && NOpcode == ISD::MUL && V1C->getAPIntValue().isPowerOf2())
2063 NewNode = CurDAG->getNode(
2064 ISD::SHL, SDLoc(V0), VT, V0,
2065 CurDAG->getConstant(
2066 V1C->getAPIntValue().logBase2(), SDLoc(N),
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00002067 TLI.getScalarShiftAmountTy(DL, V0.getValueType())));
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002068 else
2069 NewNode = CurDAG->getNode(NOpcode, SDLoc(N), VT, V0, V1);
2070
2071 NodeHeights[NewNode] = Height;
2072
2073 int Weight = V0Weight + V1Weight;
2074 Leaves.push(WeightedLeaf(NewNode, Weight, L0.InsertionOrder));
2075
2076 DEBUG(dbgs() << "--> Built new node (Weight=" << Weight << ",Height="
2077 << Height << "):\n");
2078 DEBUG(NewNode.dump());
2079 }
2080
2081 assert(Leaves.size() == 1);
2082 SDValue NewRoot = Leaves.top().Value;
2083
2084 assert(NodeHeights.count(NewRoot));
2085 int Height = NodeHeights[NewRoot];
2086
2087 // Restore SHL if we earlier converted it to a MUL
2088 if (NewRoot.getOpcode() == ISD::MUL) {
2089 ConstantSDNode *V1C = dyn_cast<ConstantSDNode>(NewRoot.getOperand(1));
2090 if (V1C && V1C->getAPIntValue().isPowerOf2()) {
2091 EVT VT = NewRoot.getValueType();
2092 SDValue V0 = NewRoot.getOperand(0);
2093 NewRoot = CurDAG->getNode(
2094 ISD::SHL, SDLoc(NewRoot), VT, V0,
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00002095 CurDAG->getConstant(
2096 V1C->getAPIntValue().logBase2(), SDLoc(NewRoot),
2097 TLI.getScalarShiftAmountTy(DL, V0.getValueType())));
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002098 }
2099 }
2100
2101 if (N != NewRoot.getNode()) {
2102 DEBUG(dbgs() << "--> Root is now: ");
2103 DEBUG(NewRoot.dump());
2104
2105 // Replace all uses of old root by new root
2106 CurDAG->ReplaceAllUsesWith(N, NewRoot.getNode());
2107 // Mark that we have RAUW'd N
2108 RootWeights[N] = -2;
2109 } else {
2110 DEBUG(dbgs() << "--> Root unchanged.\n");
2111 }
2112
2113 RootWeights[NewRoot.getNode()] = Leaves.top().Weight;
2114 RootHeights[NewRoot.getNode()] = Height;
2115
2116 return NewRoot;
2117}
2118
2119void HexagonDAGToDAGISel::rebalanceAddressTrees() {
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00002120 for (auto I = CurDAG->allnodes_begin(), E = CurDAG->allnodes_end(); I != E;) {
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002121 SDNode *N = &*I++;
2122 if (N->getOpcode() != ISD::LOAD && N->getOpcode() != ISD::STORE)
2123 continue;
2124
2125 SDValue BasePtr = cast<MemSDNode>(N)->getBasePtr();
2126 if (BasePtr.getOpcode() != ISD::ADD)
2127 continue;
2128
2129 // We've already processed this node
2130 if (RootWeights.count(BasePtr.getNode()))
2131 continue;
2132
2133 DEBUG(dbgs() << "** Rebalancing address calculation in node: ");
2134 DEBUG(N->dump());
2135
2136 // FindRoots
2137 SmallVector<SDNode *, 4> Worklist;
2138
2139 Worklist.push_back(BasePtr.getOperand(0).getNode());
2140 Worklist.push_back(BasePtr.getOperand(1).getNode());
2141
2142 while (!Worklist.empty()) {
2143 SDNode *N = Worklist.pop_back_val();
2144 unsigned Opcode = N->getOpcode();
2145
2146 if (!isOpcodeHandled(N))
2147 continue;
2148
2149 Worklist.push_back(N->getOperand(0).getNode());
2150 Worklist.push_back(N->getOperand(1).getNode());
2151
2152 // Not a root if it has only one use and same opcode as its parent
2153 if (N->hasOneUse() && Opcode == N->use_begin()->getOpcode())
2154 continue;
2155
2156 // This root node has already been processed
2157 if (RootWeights.count(N))
2158 continue;
2159
2160 RootWeights[N] = -1;
2161 }
2162
2163 // Balance node itself
2164 RootWeights[BasePtr.getNode()] = -1;
2165 SDValue NewBasePtr = balanceSubTree(BasePtr.getNode(), /*TopLevel=*/ true);
2166
2167 if (N->getOpcode() == ISD::LOAD)
2168 N = CurDAG->UpdateNodeOperands(N, N->getOperand(0),
2169 NewBasePtr, N->getOperand(2));
2170 else
2171 N = CurDAG->UpdateNodeOperands(N, N->getOperand(0), N->getOperand(1),
2172 NewBasePtr, N->getOperand(3));
2173
2174 DEBUG(dbgs() << "--> Final node: ");
2175 DEBUG(N->dump());
2176 }
2177
2178 CurDAG->RemoveDeadNodes();
2179 GAUsesInFunction.clear();
2180 RootHeights.clear();
2181 RootWeights.clear();
2182}
2183