blob: 7a997c67b721983ea920d93212cc1792877240fd [file] [log] [blame]
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001//===-- HexagonHardwareLoops.cpp - Identify and generate hardware loops ---===//
2//
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 pass identifies loops where we can generate the Hexagon hardware
11// loop instruction. The hardware loop can perform loop branches with a
12// zero-cycle overhead.
13//
14// The pattern that defines the induction variable can changed depending on
15// prior optimizations. For example, the IndVarSimplify phase run by 'opt'
16// normalizes induction variables, and the Loop Strength Reduction pass
17// run by 'llc' may also make changes to the induction variable.
18// The pattern detected by this phase is due to running Strength Reduction.
19//
20// Criteria for hardware loops:
21// - Countable loops (w/ ind. var for a trip count)
22// - Assumes loops are normalized by IndVarSimplify
23// - Try inner-most loops first
24// - No nested hardware loops.
25// - No function calls in loops.
26//
27//===----------------------------------------------------------------------===//
28
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000029#include "llvm/ADT/SmallSet.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000030#include "Hexagon.h"
Eric Christopher2c44f432015-02-02 19:05:28 +000031#include "HexagonSubtarget.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000032#include "llvm/ADT/Statistic.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000033#include "llvm/CodeGen/MachineDominators.h"
34#include "llvm/CodeGen/MachineFunction.h"
35#include "llvm/CodeGen/MachineFunctionPass.h"
36#include "llvm/CodeGen/MachineInstrBuilder.h"
37#include "llvm/CodeGen/MachineLoopInfo.h"
38#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000039#include "llvm/PassSupport.h"
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000040#include "llvm/Support/CommandLine.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000041#include "llvm/Support/Debug.h"
42#include "llvm/Support/raw_ostream.h"
43#include "llvm/Target/TargetInstrInfo.h"
44#include <algorithm>
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000045#include <vector>
Tony Linthicum1213a7a2011-12-12 21:14:40 +000046
47using namespace llvm;
48
Chandler Carruth84e68b22014-04-22 02:41:26 +000049#define DEBUG_TYPE "hwloops"
50
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000051#ifndef NDEBUG
52static cl::opt<int> HWLoopLimit("max-hwloop", cl::Hidden, cl::init(-1));
53#endif
54
Tony Linthicum1213a7a2011-12-12 21:14:40 +000055STATISTIC(NumHWLoops, "Number of loops converted to hardware loops");
56
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000057namespace llvm {
58 void initializeHexagonHardwareLoopsPass(PassRegistry&);
59}
60
Tony Linthicum1213a7a2011-12-12 21:14:40 +000061namespace {
62 class CountValue;
63 struct HexagonHardwareLoops : public MachineFunctionPass {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000064 MachineLoopInfo *MLI;
65 MachineRegisterInfo *MRI;
66 MachineDominatorTree *MDT;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000067 const HexagonInstrInfo *TII;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000068#ifndef NDEBUG
69 static int Counter;
70#endif
Tony Linthicum1213a7a2011-12-12 21:14:40 +000071
72 public:
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000073 static char ID;
Tony Linthicum1213a7a2011-12-12 21:14:40 +000074
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000075 HexagonHardwareLoops() : MachineFunctionPass(ID) {
76 initializeHexagonHardwareLoopsPass(*PassRegistry::getPassRegistry());
77 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +000078
Craig Topper906c2cd2014-04-29 07:58:16 +000079 bool runOnMachineFunction(MachineFunction &MF) override;
Tony Linthicum1213a7a2011-12-12 21:14:40 +000080
Craig Topper906c2cd2014-04-29 07:58:16 +000081 const char *getPassName() const override { return "Hexagon Hardware Loops"; }
Tony Linthicum1213a7a2011-12-12 21:14:40 +000082
Craig Topper906c2cd2014-04-29 07:58:16 +000083 void getAnalysisUsage(AnalysisUsage &AU) const override {
Tony Linthicum1213a7a2011-12-12 21:14:40 +000084 AU.addRequired<MachineDominatorTree>();
Tony Linthicum1213a7a2011-12-12 21:14:40 +000085 AU.addRequired<MachineLoopInfo>();
Tony Linthicum1213a7a2011-12-12 21:14:40 +000086 MachineFunctionPass::getAnalysisUsage(AU);
87 }
88
89 private:
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000090 /// Kinds of comparisons in the compare instructions.
91 struct Comparison {
92 enum Kind {
93 EQ = 0x01,
94 NE = 0x02,
95 L = 0x04, // Less-than property.
96 G = 0x08, // Greater-than property.
97 U = 0x40, // Unsigned property.
98 LTs = L,
99 LEs = L | EQ,
100 GTs = G,
101 GEs = G | EQ,
102 LTu = L | U,
103 LEu = L | EQ | U,
104 GTu = G | U,
105 GEu = G | EQ | U
106 };
107
108 static Kind getSwappedComparison(Kind Cmp) {
109 assert ((!((Cmp & L) && (Cmp & G))) && "Malformed comparison operator");
110 if ((Cmp & L) || (Cmp & G))
111 return (Kind)(Cmp ^ (L|G));
112 return Cmp;
113 }
114 };
115
116 /// \brief Find the register that contains the loop controlling
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000117 /// induction variable.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000118 /// If successful, it will return true and set the \p Reg, \p IVBump
119 /// and \p IVOp arguments. Otherwise it will return false.
120 /// The returned induction register is the register R that follows the
121 /// following induction pattern:
122 /// loop:
123 /// R = phi ..., [ R.next, LatchBlock ]
124 /// R.next = R + #bump
125 /// if (R.next < #N) goto loop
126 /// IVBump is the immediate value added to R, and IVOp is the instruction
127 /// "R.next = R + #bump".
128 bool findInductionRegister(MachineLoop *L, unsigned &Reg,
129 int64_t &IVBump, MachineInstr *&IVOp) const;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000130
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000131 /// \brief Analyze the statements in a loop to determine if the loop
132 /// has a computable trip count and, if so, return a value that represents
133 /// the trip count expression.
134 CountValue *getLoopTripCount(MachineLoop *L,
Craig Topperb94011f2013-07-14 04:42:23 +0000135 SmallVectorImpl<MachineInstr *> &OldInsts);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000136
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000137 /// \brief Return the expression that represents the number of times
138 /// a loop iterates. The function takes the operands that represent the
139 /// loop start value, loop end value, and induction value. Based upon
140 /// these operands, the function attempts to compute the trip count.
141 /// If the trip count is not directly available (as an immediate value,
142 /// or a register), the function will attempt to insert computation of it
143 /// to the loop's preheader.
144 CountValue *computeCount(MachineLoop *Loop,
145 const MachineOperand *Start,
146 const MachineOperand *End,
147 unsigned IVReg,
148 int64_t IVBump,
149 Comparison::Kind Cmp) const;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000150
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000151 /// \brief Return true if the instruction is not valid within a hardware
152 /// loop.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000153 bool isInvalidLoopOperation(const MachineInstr *MI) const;
154
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000155 /// \brief Return true if the loop contains an instruction that inhibits
156 /// using the hardware loop.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000157 bool containsInvalidInstruction(MachineLoop *L) const;
158
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000159 /// \brief Given a loop, check if we can convert it to a hardware loop.
160 /// If so, then perform the conversion and return true.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000161 bool convertToHardwareLoop(MachineLoop *L);
162
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000163 /// \brief Return true if the instruction is now dead.
164 bool isDead(const MachineInstr *MI,
Craig Topperb94011f2013-07-14 04:42:23 +0000165 SmallVectorImpl<MachineInstr *> &DeadPhis) const;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000166
167 /// \brief Remove the instruction if it is now dead.
168 void removeIfDead(MachineInstr *MI);
169
170 /// \brief Make sure that the "bump" instruction executes before the
171 /// compare. We need that for the IV fixup, so that the compare
172 /// instruction would not use a bumped value that has not yet been
173 /// defined. If the instructions are out of order, try to reorder them.
174 bool orderBumpCompare(MachineInstr *BumpI, MachineInstr *CmpI);
175
176 /// \brief Get the instruction that loads an immediate value into \p R,
177 /// or 0 if such an instruction does not exist.
178 MachineInstr *defWithImmediate(unsigned R);
179
180 /// \brief Get the immediate value referenced to by \p MO, either for
181 /// immediate operands, or for register operands, where the register
182 /// was defined with an immediate value.
183 int64_t getImmediate(MachineOperand &MO);
184
185 /// \brief Reset the given machine operand to now refer to a new immediate
186 /// value. Assumes that the operand was already referencing an immediate
187 /// value, either directly, or via a register.
188 void setImmediate(MachineOperand &MO, int64_t Val);
189
190 /// \brief Fix the data flow of the induction varible.
191 /// The desired flow is: phi ---> bump -+-> comparison-in-latch.
192 /// |
193 /// +-> back to phi
194 /// where "bump" is the increment of the induction variable:
195 /// iv = iv + #const.
196 /// Due to some prior code transformations, the actual flow may look
197 /// like this:
198 /// phi -+-> bump ---> back to phi
199 /// |
200 /// +-> comparison-in-latch (against upper_bound-bump),
201 /// i.e. the comparison that controls the loop execution may be using
202 /// the value of the induction variable from before the increment.
203 ///
204 /// Return true if the loop's flow is the desired one (i.e. it's
205 /// either been fixed, or no fixing was necessary).
206 /// Otherwise, return false. This can happen if the induction variable
207 /// couldn't be identified, or if the value in the latch's comparison
208 /// cannot be adjusted to reflect the post-bump value.
209 bool fixupInductionVariable(MachineLoop *L);
210
211 /// \brief Given a loop, if it does not have a preheader, create one.
212 /// Return the block that is the preheader.
213 MachineBasicBlock *createPreheaderForLoop(MachineLoop *L);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000214 };
215
216 char HexagonHardwareLoops::ID = 0;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000217#ifndef NDEBUG
218 int HexagonHardwareLoops::Counter = 0;
219#endif
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000220
Sid Manning67a89362014-08-28 14:16:32 +0000221 /// \brief Abstraction for a trip count of a loop. A smaller version
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000222 /// of the MachineOperand class without the concerns of changing the
223 /// operand representation.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000224 class CountValue {
225 public:
226 enum CountValueType {
227 CV_Register,
228 CV_Immediate
229 };
230 private:
231 CountValueType Kind;
232 union Values {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000233 struct {
234 unsigned Reg;
235 unsigned Sub;
236 } R;
237 unsigned ImmVal;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000238 } Contents;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000239
240 public:
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000241 explicit CountValue(CountValueType t, unsigned v, unsigned u = 0) {
242 Kind = t;
243 if (Kind == CV_Register) {
244 Contents.R.Reg = v;
245 Contents.R.Sub = u;
246 } else {
247 Contents.ImmVal = v;
248 }
249 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000250 bool isReg() const { return Kind == CV_Register; }
251 bool isImm() const { return Kind == CV_Immediate; }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000252
253 unsigned getReg() const {
254 assert(isReg() && "Wrong CountValue accessor");
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000255 return Contents.R.Reg;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000256 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000257 unsigned getSubReg() const {
258 assert(isReg() && "Wrong CountValue accessor");
259 return Contents.R.Sub;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000260 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000261 unsigned getImm() const {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000262 assert(isImm() && "Wrong CountValue accessor");
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000263 return Contents.ImmVal;
264 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000265
Eric Christopher2c44f432015-02-02 19:05:28 +0000266 void print(raw_ostream &OS, const TargetRegisterInfo *TRI = nullptr) const {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000267 if (isReg()) { OS << PrintReg(Contents.R.Reg, TRI, Contents.R.Sub); }
268 if (isImm()) { OS << Contents.ImmVal; }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000269 }
270 };
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000271} // end anonymous namespace
272
273
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000274INITIALIZE_PASS_BEGIN(HexagonHardwareLoops, "hwloops",
275 "Hexagon Hardware Loops", false, false)
276INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
277INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
278INITIALIZE_PASS_END(HexagonHardwareLoops, "hwloops",
279 "Hexagon Hardware Loops", false, false)
280
281
282/// \brief Returns true if the instruction is a hardware loop instruction.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000283static bool isHardwareLoop(const MachineInstr *MI) {
Colin LeMahieu5ccbb122014-12-19 00:06:53 +0000284 return MI->getOpcode() == Hexagon::J2_loop0r ||
285 MI->getOpcode() == Hexagon::J2_loop0i;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000286}
287
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000288FunctionPass *llvm::createHexagonHardwareLoops() {
289 return new HexagonHardwareLoops();
290}
291
292
293bool HexagonHardwareLoops::runOnMachineFunction(MachineFunction &MF) {
294 DEBUG(dbgs() << "********* Hexagon Hardware Loops *********\n");
295
296 bool Changed = false;
297
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000298 MLI = &getAnalysis<MachineLoopInfo>();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000299 MRI = &MF.getRegInfo();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000300 MDT = &getAnalysis<MachineDominatorTree>();
Eric Christopher2c44f432015-02-02 19:05:28 +0000301 TII = MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000302
303 for (MachineLoopInfo::iterator I = MLI->begin(), E = MLI->end();
304 I != E; ++I) {
305 MachineLoop *L = *I;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000306 if (!L->getParentLoop())
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000307 Changed |= convertToHardwareLoop(L);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000308 }
309
310 return Changed;
311}
312
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000313
314bool HexagonHardwareLoops::findInductionRegister(MachineLoop *L,
315 unsigned &Reg,
316 int64_t &IVBump,
317 MachineInstr *&IVOp
318 ) const {
319 MachineBasicBlock *Header = L->getHeader();
320 MachineBasicBlock *Preheader = L->getLoopPreheader();
321 MachineBasicBlock *Latch = L->getLoopLatch();
322 if (!Header || !Preheader || !Latch)
323 return false;
324
325 // This pair represents an induction register together with an immediate
326 // value that will be added to it in each loop iteration.
327 typedef std::pair<unsigned,int64_t> RegisterBump;
328
329 // Mapping: R.next -> (R, bump), where R, R.next and bump are derived
330 // from an induction operation
331 // R.next = R + bump
332 // where bump is an immediate value.
333 typedef std::map<unsigned,RegisterBump> InductionMap;
334
335 InductionMap IndMap;
336
337 typedef MachineBasicBlock::instr_iterator instr_iterator;
338 for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
339 I != E && I->isPHI(); ++I) {
340 MachineInstr *Phi = &*I;
341
342 // Have a PHI instruction. Get the operand that corresponds to the
343 // latch block, and see if is a result of an addition of form "reg+imm",
344 // where the "reg" is defined by the PHI node we are looking at.
345 for (unsigned i = 1, n = Phi->getNumOperands(); i < n; i += 2) {
346 if (Phi->getOperand(i+1).getMBB() != Latch)
347 continue;
348
349 unsigned PhiOpReg = Phi->getOperand(i).getReg();
350 MachineInstr *DI = MRI->getVRegDef(PhiOpReg);
351 unsigned UpdOpc = DI->getOpcode();
Colin LeMahieuf297dbe2015-02-05 17:49:13 +0000352 bool isAdd = (UpdOpc == Hexagon::A2_addi);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000353
354 if (isAdd) {
355 // If the register operand to the add is the PHI we're
356 // looking at, this meets the induction pattern.
357 unsigned IndReg = DI->getOperand(1).getReg();
358 if (MRI->getVRegDef(IndReg) == Phi) {
359 unsigned UpdReg = DI->getOperand(0).getReg();
360 int64_t V = DI->getOperand(2).getImm();
361 IndMap.insert(std::make_pair(UpdReg, std::make_pair(IndReg, V)));
362 }
363 }
364 } // for (i)
365 } // for (instr)
366
367 SmallVector<MachineOperand,2> Cond;
Craig Topper062a2ba2014-04-25 05:30:21 +0000368 MachineBasicBlock *TB = nullptr, *FB = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000369 bool NotAnalyzed = TII->AnalyzeBranch(*Latch, TB, FB, Cond, false);
370 if (NotAnalyzed)
371 return false;
Brendon Cahoondf43e682015-05-08 16:16:29 +0000372
373 unsigned PredR, PredPos, PredRegFlags;
374 if (!TII->getPredReg(Cond, PredR, PredPos, PredRegFlags))
375 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000376
377 MachineInstr *PredI = MRI->getVRegDef(PredR);
378 if (!PredI->isCompare())
379 return false;
380
381 unsigned CmpReg1 = 0, CmpReg2 = 0;
382 int CmpImm = 0, CmpMask = 0;
383 bool CmpAnalyzed = TII->analyzeCompare(PredI, CmpReg1, CmpReg2,
384 CmpMask, CmpImm);
385 // Fail if the compare was not analyzed, or it's not comparing a register
386 // with an immediate value. Not checking the mask here, since we handle
387 // the individual compare opcodes (including CMPb) later on.
388 if (!CmpAnalyzed)
389 return false;
390
391 // Exactly one of the input registers to the comparison should be among
392 // the induction registers.
393 InductionMap::iterator IndMapEnd = IndMap.end();
394 InductionMap::iterator F = IndMapEnd;
395 if (CmpReg1 != 0) {
396 InductionMap::iterator F1 = IndMap.find(CmpReg1);
397 if (F1 != IndMapEnd)
398 F = F1;
399 }
400 if (CmpReg2 != 0) {
401 InductionMap::iterator F2 = IndMap.find(CmpReg2);
402 if (F2 != IndMapEnd) {
403 if (F != IndMapEnd)
404 return false;
405 F = F2;
406 }
407 }
408 if (F == IndMapEnd)
409 return false;
410
411 Reg = F->second.first;
412 IVBump = F->second.second;
413 IVOp = MRI->getVRegDef(F->first);
414 return true;
415}
416
417
418/// \brief Analyze the statements in a loop to determine if the loop has
419/// a computable trip count and, if so, return a value that represents
420/// the trip count expression.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000421///
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000422/// This function iterates over the phi nodes in the loop to check for
423/// induction variable patterns that are used in the calculation for
424/// the number of time the loop is executed.
425CountValue *HexagonHardwareLoops::getLoopTripCount(MachineLoop *L,
Craig Topperb94011f2013-07-14 04:42:23 +0000426 SmallVectorImpl<MachineInstr *> &OldInsts) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000427 MachineBasicBlock *TopMBB = L->getTopBlock();
428 MachineBasicBlock::pred_iterator PI = TopMBB->pred_begin();
429 assert(PI != TopMBB->pred_end() &&
430 "Loop must have more than one incoming edge!");
431 MachineBasicBlock *Backedge = *PI++;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000432 if (PI == TopMBB->pred_end()) // dead loop?
Craig Topper062a2ba2014-04-25 05:30:21 +0000433 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000434 MachineBasicBlock *Incoming = *PI++;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000435 if (PI != TopMBB->pred_end()) // multiple backedges?
Craig Topper062a2ba2014-04-25 05:30:21 +0000436 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000437
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000438 // Make sure there is one incoming and one backedge and determine which
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000439 // is which.
440 if (L->contains(Incoming)) {
441 if (L->contains(Backedge))
Craig Topper062a2ba2014-04-25 05:30:21 +0000442 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000443 std::swap(Incoming, Backedge);
444 } else if (!L->contains(Backedge))
Craig Topper062a2ba2014-04-25 05:30:21 +0000445 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000446
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000447 // Look for the cmp instruction to determine if we can get a useful trip
448 // count. The trip count can be either a register or an immediate. The
449 // location of the value depends upon the type (reg or imm).
450 MachineBasicBlock *Latch = L->getLoopLatch();
451 if (!Latch)
Craig Topper062a2ba2014-04-25 05:30:21 +0000452 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000453
454 unsigned IVReg = 0;
455 int64_t IVBump = 0;
456 MachineInstr *IVOp;
457 bool FoundIV = findInductionRegister(L, IVReg, IVBump, IVOp);
458 if (!FoundIV)
Craig Topper062a2ba2014-04-25 05:30:21 +0000459 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000460
461 MachineBasicBlock *Preheader = L->getLoopPreheader();
462
Craig Topper062a2ba2014-04-25 05:30:21 +0000463 MachineOperand *InitialValue = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000464 MachineInstr *IV_Phi = MRI->getVRegDef(IVReg);
465 for (unsigned i = 1, n = IV_Phi->getNumOperands(); i < n; i += 2) {
466 MachineBasicBlock *MBB = IV_Phi->getOperand(i+1).getMBB();
467 if (MBB == Preheader)
468 InitialValue = &IV_Phi->getOperand(i);
469 else if (MBB == Latch)
470 IVReg = IV_Phi->getOperand(i).getReg(); // Want IV reg after bump.
471 }
472 if (!InitialValue)
Craig Topper062a2ba2014-04-25 05:30:21 +0000473 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000474
475 SmallVector<MachineOperand,2> Cond;
Craig Topper062a2ba2014-04-25 05:30:21 +0000476 MachineBasicBlock *TB = nullptr, *FB = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000477 bool NotAnalyzed = TII->AnalyzeBranch(*Latch, TB, FB, Cond, false);
478 if (NotAnalyzed)
Craig Topper062a2ba2014-04-25 05:30:21 +0000479 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000480
481 MachineBasicBlock *Header = L->getHeader();
482 // TB must be non-null. If FB is also non-null, one of them must be
483 // the header. Otherwise, branch to TB could be exiting the loop, and
484 // the fall through can go to the header.
485 assert (TB && "Latch block without a branch?");
486 assert ((!FB || TB == Header || FB == Header) && "Branches not to header?");
487 if (!TB || (FB && TB != Header && FB != Header))
Craig Topper062a2ba2014-04-25 05:30:21 +0000488 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000489
490 // Branches of form "if (!P) ..." cause HexagonInstrInfo::AnalyzeBranch
491 // to put imm(0), followed by P in the vector Cond.
492 // If TB is not the header, it means that the "not-taken" path must lead
493 // to the header.
Brendon Cahoondf43e682015-05-08 16:16:29 +0000494 bool Negated = TII->predOpcodeHasNot(Cond) ^ (TB != Header);
495 unsigned PredReg, PredPos, PredRegFlags;
496 if (!TII->getPredReg(Cond, PredReg, PredPos, PredRegFlags))
497 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000498 MachineInstr *CondI = MRI->getVRegDef(PredReg);
499 unsigned CondOpc = CondI->getOpcode();
500
501 unsigned CmpReg1 = 0, CmpReg2 = 0;
502 int Mask = 0, ImmValue = 0;
503 bool AnalyzedCmp = TII->analyzeCompare(CondI, CmpReg1, CmpReg2,
504 Mask, ImmValue);
505 if (!AnalyzedCmp)
Craig Topper062a2ba2014-04-25 05:30:21 +0000506 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000507
508 // The comparison operator type determines how we compute the loop
509 // trip count.
510 OldInsts.push_back(CondI);
511 OldInsts.push_back(IVOp);
512
513 // Sadly, the following code gets information based on the position
514 // of the operands in the compare instruction. This has to be done
515 // this way, because the comparisons check for a specific relationship
516 // between the operands (e.g. is-less-than), rather than to find out
517 // what relationship the operands are in (as on PPC).
518 Comparison::Kind Cmp;
519 bool isSwapped = false;
520 const MachineOperand &Op1 = CondI->getOperand(1);
521 const MachineOperand &Op2 = CondI->getOperand(2);
Craig Topper062a2ba2014-04-25 05:30:21 +0000522 const MachineOperand *EndValue = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000523
524 if (Op1.isReg()) {
525 if (Op2.isImm() || Op1.getReg() == IVReg)
526 EndValue = &Op2;
527 else {
528 EndValue = &Op1;
529 isSwapped = true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000530 }
531 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000532
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000533 if (!EndValue)
Craig Topper062a2ba2014-04-25 05:30:21 +0000534 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000535
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000536 switch (CondOpc) {
Colin LeMahieu6e0f9f82014-11-26 19:43:12 +0000537 case Hexagon::C2_cmpeqi:
Colin LeMahieu902157c2014-11-25 18:20:52 +0000538 case Hexagon::C2_cmpeq:
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000539 Cmp = !Negated ? Comparison::EQ : Comparison::NE;
540 break;
Colin LeMahieu6e0f9f82014-11-26 19:43:12 +0000541 case Hexagon::C2_cmpgtui:
Colin LeMahieu902157c2014-11-25 18:20:52 +0000542 case Hexagon::C2_cmpgtu:
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000543 Cmp = !Negated ? Comparison::GTu : Comparison::LEu;
544 break;
Colin LeMahieu6e0f9f82014-11-26 19:43:12 +0000545 case Hexagon::C2_cmpgti:
Colin LeMahieu902157c2014-11-25 18:20:52 +0000546 case Hexagon::C2_cmpgt:
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000547 Cmp = !Negated ? Comparison::GTs : Comparison::LEs;
548 break;
549 // Very limited support for byte/halfword compares.
Colin LeMahieufa947902015-01-14 16:49:12 +0000550 case Hexagon::A4_cmpbeqi:
Colin LeMahieuc91fabc2015-01-14 18:26:14 +0000551 case Hexagon::A4_cmpheqi: {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000552 if (IVBump != 1)
Craig Topper062a2ba2014-04-25 05:30:21 +0000553 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000554
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000555 int64_t InitV, EndV;
556 // Since the comparisons are "ri", the EndValue should be an
557 // immediate. Check it just in case.
558 assert(EndValue->isImm() && "Unrecognized latch comparison");
559 EndV = EndValue->getImm();
560 // Allow InitialValue to be a register defined with an immediate.
561 if (InitialValue->isReg()) {
562 if (!defWithImmediate(InitialValue->getReg()))
Craig Topper062a2ba2014-04-25 05:30:21 +0000563 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000564 InitV = getImmediate(*InitialValue);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000565 } else {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000566 assert(InitialValue->isImm());
567 InitV = InitialValue->getImm();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000568 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000569 if (InitV >= EndV)
Craig Topper062a2ba2014-04-25 05:30:21 +0000570 return nullptr;
Colin LeMahieufa947902015-01-14 16:49:12 +0000571 if (CondOpc == Hexagon::A4_cmpbeqi) {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000572 if (!isInt<8>(InitV) || !isInt<8>(EndV))
Craig Topper062a2ba2014-04-25 05:30:21 +0000573 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000574 } else { // Hexagon::CMPhEQri_V4
575 if (!isInt<16>(InitV) || !isInt<16>(EndV))
Craig Topper062a2ba2014-04-25 05:30:21 +0000576 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000577 }
578 Cmp = !Negated ? Comparison::EQ : Comparison::NE;
579 break;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000580 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000581 default:
Craig Topper062a2ba2014-04-25 05:30:21 +0000582 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000583 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000584
585 if (isSwapped)
586 Cmp = Comparison::getSwappedComparison(Cmp);
587
588 if (InitialValue->isReg()) {
589 unsigned R = InitialValue->getReg();
590 MachineBasicBlock *DefBB = MRI->getVRegDef(R)->getParent();
591 if (!MDT->properlyDominates(DefBB, Header))
Craig Topper062a2ba2014-04-25 05:30:21 +0000592 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000593 OldInsts.push_back(MRI->getVRegDef(R));
594 }
595 if (EndValue->isReg()) {
596 unsigned R = EndValue->getReg();
597 MachineBasicBlock *DefBB = MRI->getVRegDef(R)->getParent();
598 if (!MDT->properlyDominates(DefBB, Header))
Craig Topper062a2ba2014-04-25 05:30:21 +0000599 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000600 }
601
602 return computeCount(L, InitialValue, EndValue, IVReg, IVBump, Cmp);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000603}
604
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000605/// \brief Helper function that returns the expression that represents the
606/// number of times a loop iterates. The function takes the operands that
607/// represent the loop start value, loop end value, and induction value.
608/// Based upon these operands, the function attempts to compute the trip count.
609CountValue *HexagonHardwareLoops::computeCount(MachineLoop *Loop,
610 const MachineOperand *Start,
611 const MachineOperand *End,
612 unsigned IVReg,
613 int64_t IVBump,
614 Comparison::Kind Cmp) const {
615 // Cannot handle comparison EQ, i.e. while (A == B).
616 if (Cmp == Comparison::EQ)
Craig Topper062a2ba2014-04-25 05:30:21 +0000617 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000618
619 // Check if either the start or end values are an assignment of an immediate.
620 // If so, use the immediate value rather than the register.
621 if (Start->isReg()) {
622 const MachineInstr *StartValInstr = MRI->getVRegDef(Start->getReg());
Colin LeMahieu4af437f2014-12-09 20:23:30 +0000623 if (StartValInstr && StartValInstr->getOpcode() == Hexagon::A2_tfrsi)
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000624 Start = &StartValInstr->getOperand(1);
625 }
626 if (End->isReg()) {
627 const MachineInstr *EndValInstr = MRI->getVRegDef(End->getReg());
Colin LeMahieu4af437f2014-12-09 20:23:30 +0000628 if (EndValInstr && EndValInstr->getOpcode() == Hexagon::A2_tfrsi)
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000629 End = &EndValInstr->getOperand(1);
630 }
631
632 assert (Start->isReg() || Start->isImm());
633 assert (End->isReg() || End->isImm());
634
635 bool CmpLess = Cmp & Comparison::L;
636 bool CmpGreater = Cmp & Comparison::G;
637 bool CmpHasEqual = Cmp & Comparison::EQ;
638
639 // Avoid certain wrap-arounds. This doesn't detect all wrap-arounds.
640 // If loop executes while iv is "less" with the iv value going down, then
641 // the iv must wrap.
642 if (CmpLess && IVBump < 0)
Craig Topper062a2ba2014-04-25 05:30:21 +0000643 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000644 // If loop executes while iv is "greater" with the iv value going up, then
645 // the iv must wrap.
646 if (CmpGreater && IVBump > 0)
Craig Topper062a2ba2014-04-25 05:30:21 +0000647 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000648
649 if (Start->isImm() && End->isImm()) {
650 // Both, start and end are immediates.
651 int64_t StartV = Start->getImm();
652 int64_t EndV = End->getImm();
653 int64_t Dist = EndV - StartV;
654 if (Dist == 0)
Craig Topper062a2ba2014-04-25 05:30:21 +0000655 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000656
657 bool Exact = (Dist % IVBump) == 0;
658
659 if (Cmp == Comparison::NE) {
660 if (!Exact)
Craig Topper062a2ba2014-04-25 05:30:21 +0000661 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000662 if ((Dist < 0) ^ (IVBump < 0))
Craig Topper062a2ba2014-04-25 05:30:21 +0000663 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000664 }
665
666 // For comparisons that include the final value (i.e. include equality
667 // with the final value), we need to increase the distance by 1.
668 if (CmpHasEqual)
669 Dist = Dist > 0 ? Dist+1 : Dist-1;
670
671 // assert (CmpLess => Dist > 0);
672 assert ((!CmpLess || Dist > 0) && "Loop should never iterate!");
673 // assert (CmpGreater => Dist < 0);
674 assert ((!CmpGreater || Dist < 0) && "Loop should never iterate!");
675
676 // "Normalized" distance, i.e. with the bump set to +-1.
677 int64_t Dist1 = (IVBump > 0) ? (Dist + (IVBump-1)) / IVBump
678 : (-Dist + (-IVBump-1)) / (-IVBump);
679 assert (Dist1 > 0 && "Fishy thing. Both operands have the same sign.");
680
681 uint64_t Count = Dist1;
682
683 if (Count > 0xFFFFFFFFULL)
Craig Topper062a2ba2014-04-25 05:30:21 +0000684 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000685
686 return new CountValue(CountValue::CV_Immediate, Count);
687 }
688
689 // A general case: Start and End are some values, but the actual
690 // iteration count may not be available. If it is not, insert
691 // a computation of it into the preheader.
692
693 // If the induction variable bump is not a power of 2, quit.
694 // Othwerise we'd need a general integer division.
Benjamin Kramer7bd1f7c2015-03-09 20:20:16 +0000695 if (!isPowerOf2_64(std::abs(IVBump)))
Craig Topper062a2ba2014-04-25 05:30:21 +0000696 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000697
698 MachineBasicBlock *PH = Loop->getLoopPreheader();
699 assert (PH && "Should have a preheader by now");
700 MachineBasicBlock::iterator InsertPos = PH->getFirstTerminator();
701 DebugLoc DL = (InsertPos != PH->end()) ? InsertPos->getDebugLoc()
702 : DebugLoc();
703
704 // If Start is an immediate and End is a register, the trip count
705 // will be "reg - imm". Hexagon's "subtract immediate" instruction
706 // is actually "reg + -imm".
707
708 // If the loop IV is going downwards, i.e. if the bump is negative,
709 // then the iteration count (computed as End-Start) will need to be
710 // negated. To avoid the negation, just swap Start and End.
711 if (IVBump < 0) {
712 std::swap(Start, End);
713 IVBump = -IVBump;
714 }
715 // Cmp may now have a wrong direction, e.g. LEs may now be GEs.
716 // Signedness, and "including equality" are preserved.
717
718 bool RegToImm = Start->isReg() && End->isImm(); // for (reg..imm)
719 bool RegToReg = Start->isReg() && End->isReg(); // for (reg..reg)
720
721 int64_t StartV = 0, EndV = 0;
722 if (Start->isImm())
723 StartV = Start->getImm();
724 if (End->isImm())
725 EndV = End->getImm();
726
727 int64_t AdjV = 0;
728 // To compute the iteration count, we would need this computation:
729 // Count = (End - Start + (IVBump-1)) / IVBump
730 // or, when CmpHasEqual:
731 // Count = (End - Start + (IVBump-1)+1) / IVBump
732 // The "IVBump-1" part is the adjustment (AdjV). We can avoid
733 // generating an instruction specifically to add it if we can adjust
734 // the immediate values for Start or End.
735
736 if (CmpHasEqual) {
737 // Need to add 1 to the total iteration count.
738 if (Start->isImm())
739 StartV--;
740 else if (End->isImm())
741 EndV++;
742 else
743 AdjV += 1;
744 }
745
746 if (Cmp != Comparison::NE) {
747 if (Start->isImm())
748 StartV -= (IVBump-1);
749 else if (End->isImm())
750 EndV += (IVBump-1);
751 else
752 AdjV += (IVBump-1);
753 }
754
755 unsigned R = 0, SR = 0;
756 if (Start->isReg()) {
757 R = Start->getReg();
758 SR = Start->getSubReg();
759 } else {
760 R = End->getReg();
761 SR = End->getSubReg();
762 }
763 const TargetRegisterClass *RC = MRI->getRegClass(R);
764 // Hardware loops cannot handle 64-bit registers. If it's a double
765 // register, it has to have a subregister.
766 if (!SR && RC == &Hexagon::DoubleRegsRegClass)
Craig Topper062a2ba2014-04-25 05:30:21 +0000767 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000768 const TargetRegisterClass *IntRC = &Hexagon::IntRegsRegClass;
769
770 // Compute DistR (register with the distance between Start and End).
771 unsigned DistR, DistSR;
772
773 // Avoid special case, where the start value is an imm(0).
774 if (Start->isImm() && StartV == 0) {
775 DistR = End->getReg();
776 DistSR = End->getSubReg();
777 } else {
Colin LeMahieue88447d2014-11-21 21:19:18 +0000778 const MCInstrDesc &SubD = RegToReg ? TII->get(Hexagon::A2_sub) :
Colin LeMahieu27d50072015-02-05 18:38:08 +0000779 (RegToImm ? TII->get(Hexagon::A2_subri) :
Colin LeMahieuf297dbe2015-02-05 17:49:13 +0000780 TII->get(Hexagon::A2_addi));
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000781 unsigned SubR = MRI->createVirtualRegister(IntRC);
782 MachineInstrBuilder SubIB =
783 BuildMI(*PH, InsertPos, DL, SubD, SubR);
784
785 if (RegToReg) {
786 SubIB.addReg(End->getReg(), 0, End->getSubReg())
787 .addReg(Start->getReg(), 0, Start->getSubReg());
788 } else if (RegToImm) {
789 SubIB.addImm(EndV)
790 .addReg(Start->getReg(), 0, Start->getSubReg());
791 } else { // ImmToReg
792 SubIB.addReg(End->getReg(), 0, End->getSubReg())
793 .addImm(-StartV);
794 }
795 DistR = SubR;
796 DistSR = 0;
797 }
798
799 // From DistR, compute AdjR (register with the adjusted distance).
800 unsigned AdjR, AdjSR;
801
802 if (AdjV == 0) {
803 AdjR = DistR;
804 AdjSR = DistSR;
805 } else {
806 // Generate CountR = ADD DistR, AdjVal
807 unsigned AddR = MRI->createVirtualRegister(IntRC);
Colin LeMahieuf297dbe2015-02-05 17:49:13 +0000808 MCInstrDesc const &AddD = TII->get(Hexagon::A2_addi);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000809 BuildMI(*PH, InsertPos, DL, AddD, AddR)
810 .addReg(DistR, 0, DistSR)
811 .addImm(AdjV);
812
813 AdjR = AddR;
814 AdjSR = 0;
815 }
816
817 // From AdjR, compute CountR (register with the final count).
818 unsigned CountR, CountSR;
819
820 if (IVBump == 1) {
821 CountR = AdjR;
822 CountSR = AdjSR;
823 } else {
824 // The IV bump is a power of two. Log_2(IV bump) is the shift amount.
825 unsigned Shift = Log2_32(IVBump);
826
827 // Generate NormR = LSR DistR, Shift.
828 unsigned LsrR = MRI->createVirtualRegister(IntRC);
Colin LeMahieuaa1bade2014-12-16 23:36:15 +0000829 const MCInstrDesc &LsrD = TII->get(Hexagon::S2_lsr_i_r);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000830 BuildMI(*PH, InsertPos, DL, LsrD, LsrR)
831 .addReg(AdjR, 0, AdjSR)
832 .addImm(Shift);
833
834 CountR = LsrR;
835 CountSR = 0;
836 }
837
838 return new CountValue(CountValue::CV_Register, CountR, CountSR);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000839}
840
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000841
842/// \brief Return true if the operation is invalid within hardware loop.
843bool HexagonHardwareLoops::isInvalidLoopOperation(
844 const MachineInstr *MI) const {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000845
846 // call is not allowed because the callee may use a hardware loop
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000847 if (MI->getDesc().isCall())
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000848 return true;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000849
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000850 // do not allow nested hardware loops
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000851 if (isHardwareLoop(MI))
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000852 return true;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000853
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000854 // check if the instruction defines a hardware loop register
855 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
856 const MachineOperand &MO = MI->getOperand(i);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000857 if (!MO.isReg() || !MO.isDef())
858 continue;
859 unsigned R = MO.getReg();
860 if (R == Hexagon::LC0 || R == Hexagon::LC1 ||
861 R == Hexagon::SA0 || R == Hexagon::SA1)
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000862 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000863 }
864 return false;
865}
866
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000867
868/// \brief - Return true if the loop contains an instruction that inhibits
869/// the use of the hardware loop function.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000870bool HexagonHardwareLoops::containsInvalidInstruction(MachineLoop *L) const {
Benjamin Kramer7d605262013-09-15 22:04:42 +0000871 const std::vector<MachineBasicBlock *> &Blocks = L->getBlocks();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000872 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
873 MachineBasicBlock *MBB = Blocks[i];
874 for (MachineBasicBlock::iterator
875 MII = MBB->begin(), E = MBB->end(); MII != E; ++MII) {
876 const MachineInstr *MI = &*MII;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000877 if (isInvalidLoopOperation(MI))
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000878 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000879 }
880 }
881 return false;
882}
883
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000884
885/// \brief Returns true if the instruction is dead. This was essentially
886/// copied from DeadMachineInstructionElim::isDead, but with special cases
887/// for inline asm, physical registers and instructions with side effects
888/// removed.
889bool HexagonHardwareLoops::isDead(const MachineInstr *MI,
Craig Topperb94011f2013-07-14 04:42:23 +0000890 SmallVectorImpl<MachineInstr *> &DeadPhis) const {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000891 // Examine each operand.
892 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
893 const MachineOperand &MO = MI->getOperand(i);
894 if (!MO.isReg() || !MO.isDef())
895 continue;
896
897 unsigned Reg = MO.getReg();
898 if (MRI->use_nodbg_empty(Reg))
899 continue;
900
901 typedef MachineRegisterInfo::use_nodbg_iterator use_nodbg_iterator;
902
903 // This instruction has users, but if the only user is the phi node for the
904 // parent block, and the only use of that phi node is this instruction, then
905 // this instruction is dead: both it (and the phi node) can be removed.
906 use_nodbg_iterator I = MRI->use_nodbg_begin(Reg);
907 use_nodbg_iterator End = MRI->use_nodbg_end();
Owen Anderson16c6bf42014-03-13 23:12:04 +0000908 if (std::next(I) != End || !I->getParent()->isPHI())
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000909 return false;
910
Owen Anderson16c6bf42014-03-13 23:12:04 +0000911 MachineInstr *OnePhi = I->getParent();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000912 for (unsigned j = 0, f = OnePhi->getNumOperands(); j != f; ++j) {
913 const MachineOperand &OPO = OnePhi->getOperand(j);
914 if (!OPO.isReg() || !OPO.isDef())
915 continue;
916
917 unsigned OPReg = OPO.getReg();
918 use_nodbg_iterator nextJ;
919 for (use_nodbg_iterator J = MRI->use_nodbg_begin(OPReg);
920 J != End; J = nextJ) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000921 nextJ = std::next(J);
Owen Anderson16c6bf42014-03-13 23:12:04 +0000922 MachineOperand &Use = *J;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000923 MachineInstr *UseMI = Use.getParent();
924
925 // If the phi node has a user that is not MI, bail...
926 if (MI != UseMI)
927 return false;
928 }
929 }
930 DeadPhis.push_back(OnePhi);
931 }
932
933 // If there are no defs with uses, the instruction is dead.
934 return true;
935}
936
937void HexagonHardwareLoops::removeIfDead(MachineInstr *MI) {
938 // This procedure was essentially copied from DeadMachineInstructionElim.
939
940 SmallVector<MachineInstr*, 1> DeadPhis;
941 if (isDead(MI, DeadPhis)) {
942 DEBUG(dbgs() << "HW looping will remove: " << *MI);
943
944 // It is possible that some DBG_VALUE instructions refer to this
945 // instruction. Examine each def operand for such references;
946 // if found, mark the DBG_VALUE as undef (but don't delete it).
947 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
948 const MachineOperand &MO = MI->getOperand(i);
949 if (!MO.isReg() || !MO.isDef())
950 continue;
951 unsigned Reg = MO.getReg();
952 MachineRegisterInfo::use_iterator nextI;
953 for (MachineRegisterInfo::use_iterator I = MRI->use_begin(Reg),
954 E = MRI->use_end(); I != E; I = nextI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000955 nextI = std::next(I); // I is invalidated by the setReg
Owen Anderson16c6bf42014-03-13 23:12:04 +0000956 MachineOperand &Use = *I;
957 MachineInstr *UseMI = I->getParent();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000958 if (UseMI == MI)
959 continue;
960 if (Use.isDebug())
961 UseMI->getOperand(0).setReg(0U);
962 // This may also be a "instr -> phi -> instr" case which can
963 // be removed too.
964 }
965 }
966
967 MI->eraseFromParent();
968 for (unsigned i = 0; i < DeadPhis.size(); ++i)
969 DeadPhis[i]->eraseFromParent();
970 }
971}
972
973/// \brief Check if the loop is a candidate for converting to a hardware
974/// loop. If so, then perform the transformation.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000975///
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000976/// This function works on innermost loops first. A loop can be converted
977/// if it is a counting loop; either a register value or an immediate.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000978///
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000979/// The code makes several assumptions about the representation of the loop
980/// in llvm.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000981bool HexagonHardwareLoops::convertToHardwareLoop(MachineLoop *L) {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000982 // This is just for sanity.
983 assert(L->getHeader() && "Loop without a header?");
984
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000985 bool Changed = false;
986 // Process nested loops first.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000987 for (MachineLoop::iterator I = L->begin(), E = L->end(); I != E; ++I)
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000988 Changed |= convertToHardwareLoop(*I);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000989
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000990 // If a nested loop has been converted, then we can't convert this loop.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000991 if (Changed)
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000992 return Changed;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000993
994#ifndef NDEBUG
995 // Stop trying after reaching the limit (if any).
996 int Limit = HWLoopLimit;
997 if (Limit >= 0) {
998 if (Counter >= HWLoopLimit)
999 return false;
1000 Counter++;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001001 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001002#endif
1003
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001004 // Does the loop contain any invalid instructions?
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001005 if (containsInvalidInstruction(L))
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001006 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001007
1008 // Is the induction variable bump feeding the latch condition?
1009 if (!fixupInductionVariable(L))
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001010 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001011
1012 MachineBasicBlock *LastMBB = L->getExitingBlock();
1013 // Don't generate hw loop if the loop has more than one exit.
Craig Topper062a2ba2014-04-25 05:30:21 +00001014 if (!LastMBB)
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001015 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001016
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001017 MachineBasicBlock::iterator LastI = LastMBB->getFirstTerminator();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001018 if (LastI == LastMBB->end())
Matthew Curtis7a938112012-12-07 21:03:15 +00001019 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001020
1021 // Ensure the loop has a preheader: the loop instruction will be
1022 // placed there.
1023 bool NewPreheader = false;
1024 MachineBasicBlock *Preheader = L->getLoopPreheader();
1025 if (!Preheader) {
1026 Preheader = createPreheaderForLoop(L);
1027 if (!Preheader)
1028 return false;
1029 NewPreheader = true;
1030 }
1031 MachineBasicBlock::iterator InsertPos = Preheader->getFirstTerminator();
1032
1033 SmallVector<MachineInstr*, 2> OldInsts;
1034 // Are we able to determine the trip count for the loop?
1035 CountValue *TripCount = getLoopTripCount(L, OldInsts);
Craig Topper062a2ba2014-04-25 05:30:21 +00001036 if (!TripCount)
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001037 return false;
1038
1039 // Is the trip count available in the preheader?
1040 if (TripCount->isReg()) {
1041 // There will be a use of the register inserted into the preheader,
1042 // so make sure that the register is actually defined at that point.
1043 MachineInstr *TCDef = MRI->getVRegDef(TripCount->getReg());
1044 MachineBasicBlock *BBDef = TCDef->getParent();
1045 if (!NewPreheader) {
1046 if (!MDT->dominates(BBDef, Preheader))
1047 return false;
1048 } else {
1049 // If we have just created a preheader, the dominator tree won't be
1050 // aware of it. Check if the definition of the register dominates
1051 // the header, but is not the header itself.
1052 if (!MDT->properlyDominates(BBDef, L->getHeader()))
1053 return false;
1054 }
Matthew Curtis7a938112012-12-07 21:03:15 +00001055 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001056
1057 // Determine the loop start.
1058 MachineBasicBlock *LoopStart = L->getTopBlock();
1059 if (L->getLoopLatch() != LastMBB) {
1060 // When the exit and latch are not the same, use the latch block as the
1061 // start.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001062 // The loop start address is used only after the 1st iteration, and the
1063 // loop latch may contains instrs. that need to be executed after the
1064 // first iteration.
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001065 LoopStart = L->getLoopLatch();
1066 // Make sure the latch is a successor of the exit, otherwise it won't work.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001067 if (!LastMBB->isSuccessor(LoopStart))
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001068 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001069 }
1070
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001071 // Convert the loop to a hardware loop.
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001072 DEBUG(dbgs() << "Change to hardware loop at "; L->dump());
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001073 DebugLoc DL;
Matthew Curtis7a938112012-12-07 21:03:15 +00001074 if (InsertPos != Preheader->end())
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001075 DL = InsertPos->getDebugLoc();
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001076
1077 if (TripCount->isReg()) {
1078 // Create a copy of the loop count register.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001079 unsigned CountReg = MRI->createVirtualRegister(&Hexagon::IntRegsRegClass);
1080 BuildMI(*Preheader, InsertPos, DL, TII->get(TargetOpcode::COPY), CountReg)
1081 .addReg(TripCount->getReg(), 0, TripCount->getSubReg());
Benjamin Kramerbde91762012-06-02 10:20:22 +00001082 // Add the Loop instruction to the beginning of the loop.
Colin LeMahieu5ccbb122014-12-19 00:06:53 +00001083 BuildMI(*Preheader, InsertPos, DL, TII->get(Hexagon::J2_loop0r))
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001084 .addMBB(LoopStart)
1085 .addReg(CountReg);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001086 } else {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001087 assert(TripCount->isImm() && "Expecting immediate value for trip count");
1088 // Add the Loop immediate instruction to the beginning of the loop,
1089 // if the immediate fits in the instructions. Otherwise, we need to
1090 // create a new virtual register.
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001091 int64_t CountImm = TripCount->getImm();
Colin LeMahieu5ccbb122014-12-19 00:06:53 +00001092 if (!TII->isValidOffset(Hexagon::J2_loop0i, CountImm)) {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001093 unsigned CountReg = MRI->createVirtualRegister(&Hexagon::IntRegsRegClass);
Colin LeMahieu4af437f2014-12-09 20:23:30 +00001094 BuildMI(*Preheader, InsertPos, DL, TII->get(Hexagon::A2_tfrsi), CountReg)
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001095 .addImm(CountImm);
Colin LeMahieu5ccbb122014-12-19 00:06:53 +00001096 BuildMI(*Preheader, InsertPos, DL, TII->get(Hexagon::J2_loop0r))
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001097 .addMBB(LoopStart).addReg(CountReg);
1098 } else
Colin LeMahieu5ccbb122014-12-19 00:06:53 +00001099 BuildMI(*Preheader, InsertPos, DL, TII->get(Hexagon::J2_loop0i))
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001100 .addMBB(LoopStart).addImm(CountImm);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001101 }
1102
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001103 // Make sure the loop start always has a reference in the CFG. We need
1104 // to create a BlockAddress operand to get this mechanism to work both the
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001105 // MachineBasicBlock and BasicBlock objects need the flag set.
1106 LoopStart->setHasAddressTaken();
1107 // This line is needed to set the hasAddressTaken flag on the BasicBlock
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001108 // object.
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001109 BlockAddress::get(const_cast<BasicBlock *>(LoopStart->getBasicBlock()));
1110
1111 // Replace the loop branch with an endloop instruction.
Matthew Curtis7a938112012-12-07 21:03:15 +00001112 DebugLoc LastIDL = LastI->getDebugLoc();
1113 BuildMI(*LastMBB, LastI, LastIDL,
1114 TII->get(Hexagon::ENDLOOP0)).addMBB(LoopStart);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001115
1116 // The loop ends with either:
1117 // - a conditional branch followed by an unconditional branch, or
1118 // - a conditional branch to the loop start.
Colin LeMahieudb0b13c2014-12-10 21:24:10 +00001119 if (LastI->getOpcode() == Hexagon::J2_jumpt ||
1120 LastI->getOpcode() == Hexagon::J2_jumpf) {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001121 // Delete one and change/add an uncond. branch to out of the loop.
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001122 MachineBasicBlock *BranchTarget = LastI->getOperand(1).getMBB();
1123 LastI = LastMBB->erase(LastI);
1124 if (!L->contains(BranchTarget)) {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001125 if (LastI != LastMBB->end())
1126 LastI = LastMBB->erase(LastI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001127 SmallVector<MachineOperand, 0> Cond;
Craig Topper062a2ba2014-04-25 05:30:21 +00001128 TII->InsertBranch(*LastMBB, BranchTarget, nullptr, Cond, LastIDL);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001129 }
1130 } else {
1131 // Conditional branch to loop start; just delete it.
1132 LastMBB->erase(LastI);
1133 }
1134 delete TripCount;
1135
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001136 // The induction operation and the comparison may now be
1137 // unneeded. If these are unneeded, then remove them.
1138 for (unsigned i = 0; i < OldInsts.size(); ++i)
1139 removeIfDead(OldInsts[i]);
1140
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001141 ++NumHWLoops;
1142 return true;
1143}
1144
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001145
1146bool HexagonHardwareLoops::orderBumpCompare(MachineInstr *BumpI,
1147 MachineInstr *CmpI) {
1148 assert (BumpI != CmpI && "Bump and compare in the same instruction?");
1149
1150 MachineBasicBlock *BB = BumpI->getParent();
1151 if (CmpI->getParent() != BB)
1152 return false;
1153
1154 typedef MachineBasicBlock::instr_iterator instr_iterator;
1155 // Check if things are in order to begin with.
1156 for (instr_iterator I = BumpI, E = BB->instr_end(); I != E; ++I)
1157 if (&*I == CmpI)
1158 return true;
1159
1160 // Out of order.
1161 unsigned PredR = CmpI->getOperand(0).getReg();
1162 bool FoundBump = false;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001163 instr_iterator CmpIt = CmpI, NextIt = std::next(CmpIt);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001164 for (instr_iterator I = NextIt, E = BB->instr_end(); I != E; ++I) {
1165 MachineInstr *In = &*I;
1166 for (unsigned i = 0, n = In->getNumOperands(); i < n; ++i) {
1167 MachineOperand &MO = In->getOperand(i);
1168 if (MO.isReg() && MO.isUse()) {
1169 if (MO.getReg() == PredR) // Found an intervening use of PredR.
1170 return false;
1171 }
1172 }
1173
1174 if (In == BumpI) {
1175 instr_iterator After = BumpI;
1176 instr_iterator From = CmpI;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001177 BB->splice(std::next(After), BB, From);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001178 FoundBump = true;
1179 break;
1180 }
1181 }
1182 assert (FoundBump && "Cannot determine instruction order");
1183 return FoundBump;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001184}
1185
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001186
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001187MachineInstr *HexagonHardwareLoops::defWithImmediate(unsigned R) {
1188 MachineInstr *DI = MRI->getVRegDef(R);
1189 unsigned DOpc = DI->getOpcode();
1190 switch (DOpc) {
Colin LeMahieu4af437f2014-12-09 20:23:30 +00001191 case Hexagon::A2_tfrsi:
Colin LeMahieu0f850bd2014-12-19 20:29:29 +00001192 case Hexagon::A2_tfrpi:
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001193 case Hexagon::CONST32_Int_Real:
1194 case Hexagon::CONST64_Int_Real:
1195 return DI;
1196 }
Craig Topper062a2ba2014-04-25 05:30:21 +00001197 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001198}
1199
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001200
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001201int64_t HexagonHardwareLoops::getImmediate(MachineOperand &MO) {
1202 if (MO.isImm())
1203 return MO.getImm();
1204 assert(MO.isReg());
1205 unsigned R = MO.getReg();
1206 MachineInstr *DI = defWithImmediate(R);
1207 assert(DI && "Need an immediate operand");
1208 // All currently supported "define-with-immediate" instructions have the
1209 // actual immediate value in the operand(1).
1210 int64_t v = DI->getOperand(1).getImm();
1211 return v;
1212}
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001213
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001214
1215void HexagonHardwareLoops::setImmediate(MachineOperand &MO, int64_t Val) {
1216 if (MO.isImm()) {
1217 MO.setImm(Val);
1218 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001219 }
1220
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001221 assert(MO.isReg());
1222 unsigned R = MO.getReg();
1223 MachineInstr *DI = defWithImmediate(R);
1224 if (MRI->hasOneNonDBGUse(R)) {
1225 // If R has only one use, then just change its defining instruction to
1226 // the new immediate value.
1227 DI->getOperand(1).setImm(Val);
1228 return;
1229 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001230
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001231 const TargetRegisterClass *RC = MRI->getRegClass(R);
1232 unsigned NewR = MRI->createVirtualRegister(RC);
1233 MachineBasicBlock &B = *DI->getParent();
1234 DebugLoc DL = DI->getDebugLoc();
1235 BuildMI(B, DI, DL, TII->get(DI->getOpcode()), NewR)
1236 .addImm(Val);
1237 MO.setReg(NewR);
1238}
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001239
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001240
1241bool HexagonHardwareLoops::fixupInductionVariable(MachineLoop *L) {
1242 MachineBasicBlock *Header = L->getHeader();
1243 MachineBasicBlock *Preheader = L->getLoopPreheader();
1244 MachineBasicBlock *Latch = L->getLoopLatch();
1245
1246 if (!Header || !Preheader || !Latch)
1247 return false;
1248
1249 // These data structures follow the same concept as the corresponding
1250 // ones in findInductionRegister (where some comments are).
1251 typedef std::pair<unsigned,int64_t> RegisterBump;
1252 typedef std::pair<unsigned,RegisterBump> RegisterInduction;
1253 typedef std::set<RegisterInduction> RegisterInductionSet;
1254
1255 // Register candidates for induction variables, with their associated bumps.
1256 RegisterInductionSet IndRegs;
1257
1258 // Look for induction patterns:
1259 // vreg1 = PHI ..., [ latch, vreg2 ]
1260 // vreg2 = ADD vreg1, imm
1261 typedef MachineBasicBlock::instr_iterator instr_iterator;
1262 for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
1263 I != E && I->isPHI(); ++I) {
1264 MachineInstr *Phi = &*I;
1265
1266 // Have a PHI instruction.
1267 for (unsigned i = 1, n = Phi->getNumOperands(); i < n; i += 2) {
1268 if (Phi->getOperand(i+1).getMBB() != Latch)
1269 continue;
1270
1271 unsigned PhiReg = Phi->getOperand(i).getReg();
1272 MachineInstr *DI = MRI->getVRegDef(PhiReg);
1273 unsigned UpdOpc = DI->getOpcode();
Colin LeMahieuf297dbe2015-02-05 17:49:13 +00001274 bool isAdd = (UpdOpc == Hexagon::A2_addi);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001275
1276 if (isAdd) {
1277 // If the register operand to the add/sub is the PHI we are looking
1278 // at, this meets the induction pattern.
1279 unsigned IndReg = DI->getOperand(1).getReg();
1280 if (MRI->getVRegDef(IndReg) == Phi) {
1281 unsigned UpdReg = DI->getOperand(0).getReg();
1282 int64_t V = DI->getOperand(2).getImm();
1283 IndRegs.insert(std::make_pair(UpdReg, std::make_pair(IndReg, V)));
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001284 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001285 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001286 } // for (i)
1287 } // for (instr)
1288
1289 if (IndRegs.empty())
1290 return false;
1291
Craig Topper062a2ba2014-04-25 05:30:21 +00001292 MachineBasicBlock *TB = nullptr, *FB = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001293 SmallVector<MachineOperand,2> Cond;
1294 // AnalyzeBranch returns true if it fails to analyze branch.
1295 bool NotAnalyzed = TII->AnalyzeBranch(*Latch, TB, FB, Cond, false);
1296 if (NotAnalyzed)
1297 return false;
1298
1299 // Check if the latch branch is unconditional.
1300 if (Cond.empty())
1301 return false;
1302
1303 if (TB != Header && FB != Header)
1304 // The latch does not go back to the header. Not a latch we know and love.
1305 return false;
1306
1307 // Expecting a predicate register as a condition. It won't be a hardware
1308 // predicate register at this point yet, just a vreg.
1309 // HexagonInstrInfo::AnalyzeBranch for negated branches inserts imm(0)
1310 // into Cond, followed by the predicate register. For non-negated branches
1311 // it's just the register.
1312 unsigned CSz = Cond.size();
1313 if (CSz != 1 && CSz != 2)
1314 return false;
1315
1316 unsigned P = Cond[CSz-1].getReg();
1317 MachineInstr *PredDef = MRI->getVRegDef(P);
1318
1319 if (!PredDef->isCompare())
1320 return false;
1321
1322 SmallSet<unsigned,2> CmpRegs;
Craig Topper062a2ba2014-04-25 05:30:21 +00001323 MachineOperand *CmpImmOp = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001324
1325 // Go over all operands to the compare and look for immediate and register
1326 // operands. Assume that if the compare has a single register use and a
1327 // single immediate operand, then the register is being compared with the
1328 // immediate value.
1329 for (unsigned i = 0, n = PredDef->getNumOperands(); i < n; ++i) {
1330 MachineOperand &MO = PredDef->getOperand(i);
1331 if (MO.isReg()) {
1332 // Skip all implicit references. In one case there was:
1333 // %vreg140<def> = FCMPUGT32_rr %vreg138, %vreg139, %USR<imp-use>
1334 if (MO.isImplicit())
1335 continue;
1336 if (MO.isUse()) {
1337 unsigned R = MO.getReg();
1338 if (!defWithImmediate(R)) {
1339 CmpRegs.insert(MO.getReg());
1340 continue;
1341 }
1342 // Consider the register to be the "immediate" operand.
1343 if (CmpImmOp)
1344 return false;
1345 CmpImmOp = &MO;
1346 }
1347 } else if (MO.isImm()) {
1348 if (CmpImmOp) // A second immediate argument? Confusing. Bail out.
1349 return false;
1350 CmpImmOp = &MO;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001351 }
1352 }
1353
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001354 if (CmpRegs.empty())
1355 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001356
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001357 // Check if the compared register follows the order we want. Fix if needed.
1358 for (RegisterInductionSet::iterator I = IndRegs.begin(), E = IndRegs.end();
1359 I != E; ++I) {
1360 // This is a success. If the register used in the comparison is one that
1361 // we have identified as a bumped (updated) induction register, there is
1362 // nothing to do.
1363 if (CmpRegs.count(I->first))
1364 return true;
1365
1366 // Otherwise, if the register being compared comes out of a PHI node,
1367 // and has been recognized as following the induction pattern, and is
1368 // compared against an immediate, we can fix it.
1369 const RegisterBump &RB = I->second;
1370 if (CmpRegs.count(RB.first)) {
1371 if (!CmpImmOp)
1372 return false;
1373
1374 int64_t CmpImm = getImmediate(*CmpImmOp);
1375 int64_t V = RB.second;
1376 if (V > 0 && CmpImm+V < CmpImm) // Overflow (64-bit).
1377 return false;
1378 if (V < 0 && CmpImm+V > CmpImm) // Overflow (64-bit).
1379 return false;
1380 CmpImm += V;
1381 // Some forms of cmp-immediate allow u9 and s10. Assume the worst case
1382 // scenario, i.e. an 8-bit value.
1383 if (CmpImmOp->isImm() && !isInt<8>(CmpImm))
1384 return false;
1385
1386 // Make sure that the compare happens after the bump. Otherwise,
1387 // after the fixup, the compare would use a yet-undefined register.
1388 MachineInstr *BumpI = MRI->getVRegDef(I->first);
1389 bool Order = orderBumpCompare(BumpI, PredDef);
1390 if (!Order)
1391 return false;
1392
1393 // Finally, fix the compare instruction.
1394 setImmediate(*CmpImmOp, CmpImm);
1395 for (unsigned i = 0, n = PredDef->getNumOperands(); i < n; ++i) {
1396 MachineOperand &MO = PredDef->getOperand(i);
1397 if (MO.isReg() && MO.getReg() == RB.first) {
1398 MO.setReg(I->first);
1399 return true;
1400 }
1401 }
1402 }
1403 }
1404
1405 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001406}
1407
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001408
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001409/// \brief Create a preheader for a given loop.
1410MachineBasicBlock *HexagonHardwareLoops::createPreheaderForLoop(
1411 MachineLoop *L) {
1412 if (MachineBasicBlock *TmpPH = L->getLoopPreheader())
1413 return TmpPH;
1414
1415 MachineBasicBlock *Header = L->getHeader();
1416 MachineBasicBlock *Latch = L->getLoopLatch();
1417 MachineFunction *MF = Header->getParent();
1418 DebugLoc DL;
1419
1420 if (!Latch || Header->hasAddressTaken())
Craig Topper062a2ba2014-04-25 05:30:21 +00001421 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001422
1423 typedef MachineBasicBlock::instr_iterator instr_iterator;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001424
1425 // Verify that all existing predecessors have analyzable branches
1426 // (or no branches at all).
1427 typedef std::vector<MachineBasicBlock*> MBBVector;
1428 MBBVector Preds(Header->pred_begin(), Header->pred_end());
1429 SmallVector<MachineOperand,2> Tmp1;
Craig Topper062a2ba2014-04-25 05:30:21 +00001430 MachineBasicBlock *TB = nullptr, *FB = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001431
1432 if (TII->AnalyzeBranch(*Latch, TB, FB, Tmp1, false))
Craig Topper062a2ba2014-04-25 05:30:21 +00001433 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001434
1435 for (MBBVector::iterator I = Preds.begin(), E = Preds.end(); I != E; ++I) {
1436 MachineBasicBlock *PB = *I;
1437 if (PB != Latch) {
1438 bool NotAnalyzed = TII->AnalyzeBranch(*PB, TB, FB, Tmp1, false);
1439 if (NotAnalyzed)
Craig Topper062a2ba2014-04-25 05:30:21 +00001440 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001441 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001442 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001443
1444 MachineBasicBlock *NewPH = MF->CreateMachineBasicBlock();
1445 MF->insert(Header, NewPH);
1446
1447 if (Header->pred_size() > 2) {
1448 // Ensure that the header has only two predecessors: the preheader and
1449 // the loop latch. Any additional predecessors of the header should
1450 // join at the newly created preheader. Inspect all PHI nodes from the
1451 // header and create appropriate corresponding PHI nodes in the preheader.
1452
1453 for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
1454 I != E && I->isPHI(); ++I) {
1455 MachineInstr *PN = &*I;
1456
1457 const MCInstrDesc &PD = TII->get(TargetOpcode::PHI);
1458 MachineInstr *NewPN = MF->CreateMachineInstr(PD, DL);
1459 NewPH->insert(NewPH->end(), NewPN);
1460
1461 unsigned PR = PN->getOperand(0).getReg();
1462 const TargetRegisterClass *RC = MRI->getRegClass(PR);
1463 unsigned NewPR = MRI->createVirtualRegister(RC);
1464 NewPN->addOperand(MachineOperand::CreateReg(NewPR, true));
1465
1466 // Copy all non-latch operands of a header's PHI node to the newly
1467 // created PHI node in the preheader.
1468 for (unsigned i = 1, n = PN->getNumOperands(); i < n; i += 2) {
1469 unsigned PredR = PN->getOperand(i).getReg();
1470 MachineBasicBlock *PredB = PN->getOperand(i+1).getMBB();
1471 if (PredB == Latch)
1472 continue;
1473
1474 NewPN->addOperand(MachineOperand::CreateReg(PredR, false));
1475 NewPN->addOperand(MachineOperand::CreateMBB(PredB));
1476 }
1477
1478 // Remove copied operands from the old PHI node and add the value
1479 // coming from the preheader's PHI.
1480 for (int i = PN->getNumOperands()-2; i > 0; i -= 2) {
1481 MachineBasicBlock *PredB = PN->getOperand(i+1).getMBB();
1482 if (PredB != Latch) {
1483 PN->RemoveOperand(i+1);
1484 PN->RemoveOperand(i);
1485 }
1486 }
1487 PN->addOperand(MachineOperand::CreateReg(NewPR, false));
1488 PN->addOperand(MachineOperand::CreateMBB(NewPH));
1489 }
1490
1491 } else {
1492 assert(Header->pred_size() == 2);
1493
1494 // The header has only two predecessors, but the non-latch predecessor
1495 // is not a preheader (e.g. it has other successors, etc.)
1496 // In such a case we don't need any extra PHI nodes in the new preheader,
1497 // all we need is to adjust existing PHIs in the header to now refer to
1498 // the new preheader.
1499 for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
1500 I != E && I->isPHI(); ++I) {
1501 MachineInstr *PN = &*I;
1502 for (unsigned i = 1, n = PN->getNumOperands(); i < n; i += 2) {
1503 MachineOperand &MO = PN->getOperand(i+1);
1504 if (MO.getMBB() != Latch)
1505 MO.setMBB(NewPH);
1506 }
1507 }
1508 }
1509
1510 // "Reroute" the CFG edges to link in the new preheader.
1511 // If any of the predecessors falls through to the header, insert a branch
1512 // to the new preheader in that place.
1513 SmallVector<MachineOperand,1> Tmp2;
1514 SmallVector<MachineOperand,1> EmptyCond;
1515
Craig Topper062a2ba2014-04-25 05:30:21 +00001516 TB = FB = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001517
1518 for (MBBVector::iterator I = Preds.begin(), E = Preds.end(); I != E; ++I) {
1519 MachineBasicBlock *PB = *I;
1520 if (PB != Latch) {
1521 Tmp2.clear();
1522 bool NotAnalyzed = TII->AnalyzeBranch(*PB, TB, FB, Tmp2, false);
Alp Tokercb402912014-01-24 17:20:08 +00001523 (void)NotAnalyzed; // suppress compiler warning
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001524 assert (!NotAnalyzed && "Should be analyzable!");
1525 if (TB != Header && (Tmp2.empty() || FB != Header))
Craig Topper062a2ba2014-04-25 05:30:21 +00001526 TII->InsertBranch(*PB, NewPH, nullptr, EmptyCond, DL);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001527 PB->ReplaceUsesOfBlockWith(Header, NewPH);
1528 }
1529 }
1530
1531 // It can happen that the latch block will fall through into the header.
1532 // Insert an unconditional branch to the header.
Craig Topper062a2ba2014-04-25 05:30:21 +00001533 TB = FB = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001534 bool LatchNotAnalyzed = TII->AnalyzeBranch(*Latch, TB, FB, Tmp2, false);
Alp Tokercb402912014-01-24 17:20:08 +00001535 (void)LatchNotAnalyzed; // suppress compiler warning
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001536 assert (!LatchNotAnalyzed && "Should be analyzable!");
1537 if (!TB && !FB)
Craig Topper062a2ba2014-04-25 05:30:21 +00001538 TII->InsertBranch(*Latch, Header, nullptr, EmptyCond, DL);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001539
1540 // Finally, the branch from the preheader to the header.
Craig Topper062a2ba2014-04-25 05:30:21 +00001541 TII->InsertBranch(*NewPH, Header, nullptr, EmptyCond, DL);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001542 NewPH->addSuccessor(Header);
1543
1544 return NewPH;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001545}