blob: c06d9e0a4e619fc4ec8a479474da54d18c58d35c [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
Tony Linthicum1213a7a2011-12-12 21:14:40 +000024// - No function calls in loops.
25//
26//===----------------------------------------------------------------------===//
27
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000028#include "llvm/ADT/SmallSet.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000029#include "Hexagon.h"
Eric Christopher2c44f432015-02-02 19:05:28 +000030#include "HexagonSubtarget.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000031#include "llvm/ADT/Statistic.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000032#include "llvm/CodeGen/MachineDominators.h"
33#include "llvm/CodeGen/MachineFunction.h"
34#include "llvm/CodeGen/MachineFunctionPass.h"
35#include "llvm/CodeGen/MachineInstrBuilder.h"
36#include "llvm/CodeGen/MachineLoopInfo.h"
37#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000038#include "llvm/PassSupport.h"
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000039#include "llvm/Support/CommandLine.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000040#include "llvm/Support/Debug.h"
41#include "llvm/Support/raw_ostream.h"
42#include "llvm/Target/TargetInstrInfo.h"
43#include <algorithm>
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000044#include <vector>
Tony Linthicum1213a7a2011-12-12 21:14:40 +000045
46using namespace llvm;
47
Chandler Carruth84e68b22014-04-22 02:41:26 +000048#define DEBUG_TYPE "hwloops"
49
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000050#ifndef NDEBUG
Brendon Cahoonbece8ed2015-05-08 20:18:21 +000051static cl::opt<int> HWLoopLimit("hexagon-max-hwloop", cl::Hidden, cl::init(-1));
52
53// Option to create preheader only for a specific function.
54static cl::opt<std::string> PHFn("hexagon-hwloop-phfn", cl::Hidden,
55 cl::init(""));
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000056#endif
57
Brendon Cahoonbece8ed2015-05-08 20:18:21 +000058// Option to create a preheader if one doesn't exist.
59static cl::opt<bool> HWCreatePreheader("hexagon-hwloop-preheader",
60 cl::Hidden, cl::init(true),
61 cl::desc("Add a preheader to a hardware loop if one doesn't exist"));
62
Tony Linthicum1213a7a2011-12-12 21:14:40 +000063STATISTIC(NumHWLoops, "Number of loops converted to hardware loops");
64
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000065namespace llvm {
66 void initializeHexagonHardwareLoopsPass(PassRegistry&);
67}
68
Tony Linthicum1213a7a2011-12-12 21:14:40 +000069namespace {
70 class CountValue;
71 struct HexagonHardwareLoops : public MachineFunctionPass {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000072 MachineLoopInfo *MLI;
73 MachineRegisterInfo *MRI;
74 MachineDominatorTree *MDT;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000075 const HexagonInstrInfo *TII;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000076#ifndef NDEBUG
77 static int Counter;
78#endif
Tony Linthicum1213a7a2011-12-12 21:14:40 +000079
80 public:
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000081 static char ID;
Tony Linthicum1213a7a2011-12-12 21:14:40 +000082
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000083 HexagonHardwareLoops() : MachineFunctionPass(ID) {
84 initializeHexagonHardwareLoopsPass(*PassRegistry::getPassRegistry());
85 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +000086
Craig Topper906c2cd2014-04-29 07:58:16 +000087 bool runOnMachineFunction(MachineFunction &MF) override;
Tony Linthicum1213a7a2011-12-12 21:14:40 +000088
Craig Topper906c2cd2014-04-29 07:58:16 +000089 const char *getPassName() const override { return "Hexagon Hardware Loops"; }
Tony Linthicum1213a7a2011-12-12 21:14:40 +000090
Craig Topper906c2cd2014-04-29 07:58:16 +000091 void getAnalysisUsage(AnalysisUsage &AU) const override {
Tony Linthicum1213a7a2011-12-12 21:14:40 +000092 AU.addRequired<MachineDominatorTree>();
Tony Linthicum1213a7a2011-12-12 21:14:40 +000093 AU.addRequired<MachineLoopInfo>();
Tony Linthicum1213a7a2011-12-12 21:14:40 +000094 MachineFunctionPass::getAnalysisUsage(AU);
95 }
96
97 private:
Brendon Cahoon9376e992015-05-14 14:15:08 +000098 typedef std::map<unsigned, MachineInstr *> LoopFeederMap;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +000099
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000100 /// Kinds of comparisons in the compare instructions.
101 struct Comparison {
102 enum Kind {
103 EQ = 0x01,
104 NE = 0x02,
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000105 L = 0x04,
106 G = 0x08,
107 U = 0x40,
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000108 LTs = L,
109 LEs = L | EQ,
110 GTs = G,
111 GEs = G | EQ,
112 LTu = L | U,
113 LEu = L | EQ | U,
114 GTu = G | U,
115 GEu = G | EQ | U
116 };
117
118 static Kind getSwappedComparison(Kind Cmp) {
119 assert ((!((Cmp & L) && (Cmp & G))) && "Malformed comparison operator");
120 if ((Cmp & L) || (Cmp & G))
121 return (Kind)(Cmp ^ (L|G));
122 return Cmp;
123 }
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000124
125 static Kind getNegatedComparison(Kind Cmp) {
126 if ((Cmp & L) || (Cmp & G))
127 return (Kind)((Cmp ^ (L | G)) ^ EQ);
128 if ((Cmp & NE) || (Cmp & EQ))
129 return (Kind)(Cmp ^ (EQ | NE));
130 return (Kind)0;
131 }
132
133 static bool isSigned(Kind Cmp) {
134 return (Cmp & (L | G) && !(Cmp & U));
135 }
136
137 static bool isUnsigned(Kind Cmp) {
138 return (Cmp & U);
139 }
140
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000141 };
142
143 /// \brief Find the register that contains the loop controlling
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000144 /// induction variable.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000145 /// If successful, it will return true and set the \p Reg, \p IVBump
146 /// and \p IVOp arguments. Otherwise it will return false.
147 /// The returned induction register is the register R that follows the
148 /// following induction pattern:
149 /// loop:
150 /// R = phi ..., [ R.next, LatchBlock ]
151 /// R.next = R + #bump
152 /// if (R.next < #N) goto loop
153 /// IVBump is the immediate value added to R, and IVOp is the instruction
154 /// "R.next = R + #bump".
155 bool findInductionRegister(MachineLoop *L, unsigned &Reg,
156 int64_t &IVBump, MachineInstr *&IVOp) const;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000157
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000158 /// \brief Return the comparison kind for the specified opcode.
159 Comparison::Kind getComparisonKind(unsigned CondOpc,
160 MachineOperand *InitialValue,
161 const MachineOperand *Endvalue,
162 int64_t IVBump) const;
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000163
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000164 /// \brief Analyze the statements in a loop to determine if the loop
165 /// has a computable trip count and, if so, return a value that represents
166 /// the trip count expression.
167 CountValue *getLoopTripCount(MachineLoop *L,
Craig Topperb94011f2013-07-14 04:42:23 +0000168 SmallVectorImpl<MachineInstr *> &OldInsts);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000169
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000170 /// \brief Return the expression that represents the number of times
171 /// a loop iterates. The function takes the operands that represent the
172 /// loop start value, loop end value, and induction value. Based upon
173 /// these operands, the function attempts to compute the trip count.
174 /// If the trip count is not directly available (as an immediate value,
175 /// or a register), the function will attempt to insert computation of it
176 /// to the loop's preheader.
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000177 CountValue *computeCount(MachineLoop *Loop, const MachineOperand *Start,
178 const MachineOperand *End, unsigned IVReg,
179 int64_t IVBump, Comparison::Kind Cmp) const;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000180
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000181 /// \brief Return true if the instruction is not valid within a hardware
182 /// loop.
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000183 bool isInvalidLoopOperation(const MachineInstr *MI,
184 bool IsInnerHWLoop) const;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000185
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000186 /// \brief Return true if the loop contains an instruction that inhibits
187 /// using the hardware loop.
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000188 bool containsInvalidInstruction(MachineLoop *L, bool IsInnerHWLoop) const;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000189
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000190 /// \brief Given a loop, check if we can convert it to a hardware loop.
191 /// If so, then perform the conversion and return true.
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000192 bool convertToHardwareLoop(MachineLoop *L, bool &L0used, bool &L1used);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000193
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000194 /// \brief Return true if the instruction is now dead.
195 bool isDead(const MachineInstr *MI,
Craig Topperb94011f2013-07-14 04:42:23 +0000196 SmallVectorImpl<MachineInstr *> &DeadPhis) const;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000197
198 /// \brief Remove the instruction if it is now dead.
199 void removeIfDead(MachineInstr *MI);
200
201 /// \brief Make sure that the "bump" instruction executes before the
202 /// compare. We need that for the IV fixup, so that the compare
203 /// instruction would not use a bumped value that has not yet been
204 /// defined. If the instructions are out of order, try to reorder them.
205 bool orderBumpCompare(MachineInstr *BumpI, MachineInstr *CmpI);
206
Brendon Cahoon9376e992015-05-14 14:15:08 +0000207 /// \brief Return true if MO and MI pair is visited only once. If visited
208 /// more than once, this indicates there is recursion. In such a case,
209 /// return false.
210 bool isLoopFeeder(MachineLoop *L, MachineBasicBlock *A, MachineInstr *MI,
211 const MachineOperand *MO,
212 LoopFeederMap &LoopFeederPhi) const;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000213
Brendon Cahoon9376e992015-05-14 14:15:08 +0000214 /// \brief Return true if the Phi may generate a value that may underflow,
215 /// or may wrap.
216 bool phiMayWrapOrUnderflow(MachineInstr *Phi, const MachineOperand *EndVal,
217 MachineBasicBlock *MBB, MachineLoop *L,
218 LoopFeederMap &LoopFeederPhi) const;
219
220 /// \brief Return true if the induction variable may underflow an unsigned
221 /// value in the first iteration.
222 bool loopCountMayWrapOrUnderFlow(const MachineOperand *InitVal,
223 const MachineOperand *EndVal,
224 MachineBasicBlock *MBB, MachineLoop *L,
225 LoopFeederMap &LoopFeederPhi) const;
226
227 /// \brief Check if the given operand has a compile-time known constant
228 /// value. Return true if yes, and false otherwise. When returning true, set
229 /// Val to the corresponding constant value.
230 bool checkForImmediate(const MachineOperand &MO, int64_t &Val) const;
231
232 /// \brief Check if the operand has a compile-time known constant value.
233 bool isImmediate(const MachineOperand &MO) const {
234 int64_t V;
235 return checkForImmediate(MO, V);
236 }
237
238 /// \brief Return the immediate for the specified operand.
239 int64_t getImmediate(const MachineOperand &MO) const {
240 int64_t V;
241 if (!checkForImmediate(MO, V))
242 llvm_unreachable("Invalid operand");
243 return V;
244 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000245
246 /// \brief Reset the given machine operand to now refer to a new immediate
247 /// value. Assumes that the operand was already referencing an immediate
248 /// value, either directly, or via a register.
249 void setImmediate(MachineOperand &MO, int64_t Val);
250
251 /// \brief Fix the data flow of the induction varible.
252 /// The desired flow is: phi ---> bump -+-> comparison-in-latch.
253 /// |
254 /// +-> back to phi
255 /// where "bump" is the increment of the induction variable:
256 /// iv = iv + #const.
257 /// Due to some prior code transformations, the actual flow may look
258 /// like this:
259 /// phi -+-> bump ---> back to phi
260 /// |
261 /// +-> comparison-in-latch (against upper_bound-bump),
262 /// i.e. the comparison that controls the loop execution may be using
263 /// the value of the induction variable from before the increment.
264 ///
265 /// Return true if the loop's flow is the desired one (i.e. it's
266 /// either been fixed, or no fixing was necessary).
267 /// Otherwise, return false. This can happen if the induction variable
268 /// couldn't be identified, or if the value in the latch's comparison
269 /// cannot be adjusted to reflect the post-bump value.
270 bool fixupInductionVariable(MachineLoop *L);
271
272 /// \brief Given a loop, if it does not have a preheader, create one.
273 /// Return the block that is the preheader.
274 MachineBasicBlock *createPreheaderForLoop(MachineLoop *L);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000275 };
276
277 char HexagonHardwareLoops::ID = 0;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000278#ifndef NDEBUG
279 int HexagonHardwareLoops::Counter = 0;
280#endif
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000281
Sid Manning67a89362014-08-28 14:16:32 +0000282 /// \brief Abstraction for a trip count of a loop. A smaller version
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000283 /// of the MachineOperand class without the concerns of changing the
284 /// operand representation.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000285 class CountValue {
286 public:
287 enum CountValueType {
288 CV_Register,
289 CV_Immediate
290 };
291 private:
292 CountValueType Kind;
293 union Values {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000294 struct {
295 unsigned Reg;
296 unsigned Sub;
297 } R;
298 unsigned ImmVal;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000299 } Contents;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000300
301 public:
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000302 explicit CountValue(CountValueType t, unsigned v, unsigned u = 0) {
303 Kind = t;
304 if (Kind == CV_Register) {
305 Contents.R.Reg = v;
306 Contents.R.Sub = u;
307 } else {
308 Contents.ImmVal = v;
309 }
310 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000311 bool isReg() const { return Kind == CV_Register; }
312 bool isImm() const { return Kind == CV_Immediate; }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000313
314 unsigned getReg() const {
315 assert(isReg() && "Wrong CountValue accessor");
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000316 return Contents.R.Reg;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000317 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000318 unsigned getSubReg() const {
319 assert(isReg() && "Wrong CountValue accessor");
320 return Contents.R.Sub;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000321 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000322 unsigned getImm() const {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000323 assert(isImm() && "Wrong CountValue accessor");
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000324 return Contents.ImmVal;
325 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000326
Eric Christopher2c44f432015-02-02 19:05:28 +0000327 void print(raw_ostream &OS, const TargetRegisterInfo *TRI = nullptr) const {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000328 if (isReg()) { OS << PrintReg(Contents.R.Reg, TRI, Contents.R.Sub); }
329 if (isImm()) { OS << Contents.ImmVal; }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000330 }
331 };
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000332} // end anonymous namespace
333
334
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000335INITIALIZE_PASS_BEGIN(HexagonHardwareLoops, "hwloops",
336 "Hexagon Hardware Loops", false, false)
337INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
338INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
339INITIALIZE_PASS_END(HexagonHardwareLoops, "hwloops",
340 "Hexagon Hardware Loops", false, false)
341
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000342FunctionPass *llvm::createHexagonHardwareLoops() {
343 return new HexagonHardwareLoops();
344}
345
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000346bool HexagonHardwareLoops::runOnMachineFunction(MachineFunction &MF) {
347 DEBUG(dbgs() << "********* Hexagon Hardware Loops *********\n");
348
349 bool Changed = false;
350
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000351 MLI = &getAnalysis<MachineLoopInfo>();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000352 MRI = &MF.getRegInfo();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000353 MDT = &getAnalysis<MachineDominatorTree>();
Eric Christopher2c44f432015-02-02 19:05:28 +0000354 TII = MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000355
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000356 for (auto &L : *MLI)
357 if (!L->getParentLoop()) {
358 bool L0Used = false;
359 bool L1Used = false;
360 Changed |= convertToHardwareLoop(L, L0Used, L1Used);
361 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000362
363 return Changed;
364}
365
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000366/// \brief Return the latch block if it's one of the exiting blocks. Otherwise,
367/// return the exiting block. Return 'null' when multiple exiting blocks are
368/// present.
369static MachineBasicBlock* getExitingBlock(MachineLoop *L) {
370 if (MachineBasicBlock *Latch = L->getLoopLatch()) {
371 if (L->isLoopExiting(Latch))
372 return Latch;
373 else
374 return L->getExitingBlock();
375 }
376 return nullptr;
377}
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000378
379bool HexagonHardwareLoops::findInductionRegister(MachineLoop *L,
380 unsigned &Reg,
381 int64_t &IVBump,
382 MachineInstr *&IVOp
383 ) const {
384 MachineBasicBlock *Header = L->getHeader();
385 MachineBasicBlock *Preheader = L->getLoopPreheader();
386 MachineBasicBlock *Latch = L->getLoopLatch();
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000387 MachineBasicBlock *ExitingBlock = getExitingBlock(L);
388 if (!Header || !Preheader || !Latch || !ExitingBlock)
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000389 return false;
390
391 // This pair represents an induction register together with an immediate
392 // value that will be added to it in each loop iteration.
393 typedef std::pair<unsigned,int64_t> RegisterBump;
394
395 // Mapping: R.next -> (R, bump), where R, R.next and bump are derived
396 // from an induction operation
397 // R.next = R + bump
398 // where bump is an immediate value.
399 typedef std::map<unsigned,RegisterBump> InductionMap;
400
401 InductionMap IndMap;
402
403 typedef MachineBasicBlock::instr_iterator instr_iterator;
404 for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
405 I != E && I->isPHI(); ++I) {
406 MachineInstr *Phi = &*I;
407
408 // Have a PHI instruction. Get the operand that corresponds to the
409 // latch block, and see if is a result of an addition of form "reg+imm",
410 // where the "reg" is defined by the PHI node we are looking at.
411 for (unsigned i = 1, n = Phi->getNumOperands(); i < n; i += 2) {
412 if (Phi->getOperand(i+1).getMBB() != Latch)
413 continue;
414
415 unsigned PhiOpReg = Phi->getOperand(i).getReg();
416 MachineInstr *DI = MRI->getVRegDef(PhiOpReg);
417 unsigned UpdOpc = DI->getOpcode();
Brendon Cahoon9376e992015-05-14 14:15:08 +0000418 bool isAdd = (UpdOpc == Hexagon::A2_addi || UpdOpc == Hexagon::A2_addp);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000419
420 if (isAdd) {
Brendon Cahoon9376e992015-05-14 14:15:08 +0000421 // If the register operand to the add is the PHI we're looking at, this
422 // meets the induction pattern.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000423 unsigned IndReg = DI->getOperand(1).getReg();
Brendon Cahoon9376e992015-05-14 14:15:08 +0000424 MachineOperand &Opnd2 = DI->getOperand(2);
425 int64_t V;
426 if (MRI->getVRegDef(IndReg) == Phi && checkForImmediate(Opnd2, V)) {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000427 unsigned UpdReg = DI->getOperand(0).getReg();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000428 IndMap.insert(std::make_pair(UpdReg, std::make_pair(IndReg, V)));
429 }
430 }
431 } // for (i)
432 } // for (instr)
433
434 SmallVector<MachineOperand,2> Cond;
Craig Topper062a2ba2014-04-25 05:30:21 +0000435 MachineBasicBlock *TB = nullptr, *FB = nullptr;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000436 bool NotAnalyzed = TII->AnalyzeBranch(*ExitingBlock, TB, FB, Cond, false);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000437 if (NotAnalyzed)
438 return false;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000439
Brendon Cahoondf43e682015-05-08 16:16:29 +0000440 unsigned PredR, PredPos, PredRegFlags;
441 if (!TII->getPredReg(Cond, PredR, PredPos, PredRegFlags))
442 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000443
444 MachineInstr *PredI = MRI->getVRegDef(PredR);
445 if (!PredI->isCompare())
446 return false;
447
448 unsigned CmpReg1 = 0, CmpReg2 = 0;
449 int CmpImm = 0, CmpMask = 0;
450 bool CmpAnalyzed = TII->analyzeCompare(PredI, CmpReg1, CmpReg2,
451 CmpMask, CmpImm);
452 // Fail if the compare was not analyzed, or it's not comparing a register
453 // with an immediate value. Not checking the mask here, since we handle
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000454 // the individual compare opcodes (including A4_cmpb*) later on.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000455 if (!CmpAnalyzed)
456 return false;
457
458 // Exactly one of the input registers to the comparison should be among
459 // the induction registers.
460 InductionMap::iterator IndMapEnd = IndMap.end();
461 InductionMap::iterator F = IndMapEnd;
462 if (CmpReg1 != 0) {
463 InductionMap::iterator F1 = IndMap.find(CmpReg1);
464 if (F1 != IndMapEnd)
465 F = F1;
466 }
467 if (CmpReg2 != 0) {
468 InductionMap::iterator F2 = IndMap.find(CmpReg2);
469 if (F2 != IndMapEnd) {
470 if (F != IndMapEnd)
471 return false;
472 F = F2;
473 }
474 }
475 if (F == IndMapEnd)
476 return false;
477
478 Reg = F->second.first;
479 IVBump = F->second.second;
480 IVOp = MRI->getVRegDef(F->first);
481 return true;
482}
483
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000484// Return the comparison kind for the specified opcode.
485HexagonHardwareLoops::Comparison::Kind
486HexagonHardwareLoops::getComparisonKind(unsigned CondOpc,
487 MachineOperand *InitialValue,
488 const MachineOperand *EndValue,
489 int64_t IVBump) const {
490 Comparison::Kind Cmp = (Comparison::Kind)0;
491 switch (CondOpc) {
492 case Hexagon::C2_cmpeqi:
493 case Hexagon::C2_cmpeq:
494 case Hexagon::C2_cmpeqp:
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000495 Cmp = Comparison::EQ;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000496 break;
497 case Hexagon::C4_cmpneq:
498 case Hexagon::C4_cmpneqi:
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000499 Cmp = Comparison::NE;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000500 break;
501 case Hexagon::C4_cmplte:
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000502 Cmp = Comparison::LEs;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000503 break;
504 case Hexagon::C4_cmplteu:
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000505 Cmp = Comparison::LEu;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000506 break;
507 case Hexagon::C2_cmpgtui:
508 case Hexagon::C2_cmpgtu:
509 case Hexagon::C2_cmpgtup:
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000510 Cmp = Comparison::GTu;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000511 break;
512 case Hexagon::C2_cmpgti:
513 case Hexagon::C2_cmpgt:
514 case Hexagon::C2_cmpgtp:
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000515 Cmp = Comparison::GTs;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000516 break;
517 default:
518 return (Comparison::Kind)0;
519 }
520 return Cmp;
521}
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000522
523/// \brief Analyze the statements in a loop to determine if the loop has
524/// a computable trip count and, if so, return a value that represents
525/// the trip count expression.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000526///
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000527/// This function iterates over the phi nodes in the loop to check for
528/// induction variable patterns that are used in the calculation for
529/// the number of time the loop is executed.
530CountValue *HexagonHardwareLoops::getLoopTripCount(MachineLoop *L,
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000531 SmallVectorImpl<MachineInstr *> &OldInsts) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000532 MachineBasicBlock *TopMBB = L->getTopBlock();
533 MachineBasicBlock::pred_iterator PI = TopMBB->pred_begin();
534 assert(PI != TopMBB->pred_end() &&
535 "Loop must have more than one incoming edge!");
536 MachineBasicBlock *Backedge = *PI++;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000537 if (PI == TopMBB->pred_end()) // dead loop?
Craig Topper062a2ba2014-04-25 05:30:21 +0000538 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000539 MachineBasicBlock *Incoming = *PI++;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000540 if (PI != TopMBB->pred_end()) // multiple backedges?
Craig Topper062a2ba2014-04-25 05:30:21 +0000541 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000542
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000543 // Make sure there is one incoming and one backedge and determine which
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000544 // is which.
545 if (L->contains(Incoming)) {
546 if (L->contains(Backedge))
Craig Topper062a2ba2014-04-25 05:30:21 +0000547 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000548 std::swap(Incoming, Backedge);
549 } else if (!L->contains(Backedge))
Craig Topper062a2ba2014-04-25 05:30:21 +0000550 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000551
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000552 // Look for the cmp instruction to determine if we can get a useful trip
553 // count. The trip count can be either a register or an immediate. The
554 // location of the value depends upon the type (reg or imm).
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000555 MachineBasicBlock *ExitingBlock = getExitingBlock(L);
556 if (!ExitingBlock)
Craig Topper062a2ba2014-04-25 05:30:21 +0000557 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000558
559 unsigned IVReg = 0;
560 int64_t IVBump = 0;
561 MachineInstr *IVOp;
562 bool FoundIV = findInductionRegister(L, IVReg, IVBump, IVOp);
563 if (!FoundIV)
Craig Topper062a2ba2014-04-25 05:30:21 +0000564 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000565
566 MachineBasicBlock *Preheader = L->getLoopPreheader();
567
Craig Topper062a2ba2014-04-25 05:30:21 +0000568 MachineOperand *InitialValue = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000569 MachineInstr *IV_Phi = MRI->getVRegDef(IVReg);
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000570 MachineBasicBlock *Latch = L->getLoopLatch();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000571 for (unsigned i = 1, n = IV_Phi->getNumOperands(); i < n; i += 2) {
572 MachineBasicBlock *MBB = IV_Phi->getOperand(i+1).getMBB();
573 if (MBB == Preheader)
574 InitialValue = &IV_Phi->getOperand(i);
575 else if (MBB == Latch)
576 IVReg = IV_Phi->getOperand(i).getReg(); // Want IV reg after bump.
577 }
578 if (!InitialValue)
Craig Topper062a2ba2014-04-25 05:30:21 +0000579 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000580
581 SmallVector<MachineOperand,2> Cond;
Craig Topper062a2ba2014-04-25 05:30:21 +0000582 MachineBasicBlock *TB = nullptr, *FB = nullptr;
Brendon Cahoon254e6562015-05-13 14:54:24 +0000583 bool NotAnalyzed = TII->AnalyzeBranch(*ExitingBlock, TB, FB, Cond, false);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000584 if (NotAnalyzed)
Craig Topper062a2ba2014-04-25 05:30:21 +0000585 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000586
587 MachineBasicBlock *Header = L->getHeader();
588 // TB must be non-null. If FB is also non-null, one of them must be
589 // the header. Otherwise, branch to TB could be exiting the loop, and
590 // the fall through can go to the header.
Brendon Cahoon254e6562015-05-13 14:54:24 +0000591 assert (TB && "Exit block without a branch?");
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000592 if (ExitingBlock != Latch && (TB == Latch || FB == Latch)) {
593 MachineBasicBlock *LTB = 0, *LFB = 0;
594 SmallVector<MachineOperand,2> LCond;
595 bool NotAnalyzed = TII->AnalyzeBranch(*Latch, LTB, LFB, LCond, false);
596 if (NotAnalyzed)
597 return nullptr;
598 if (TB == Latch)
Brendon Cahoon254e6562015-05-13 14:54:24 +0000599 TB = (LTB == Header) ? LTB : LFB;
600 else
601 FB = (LTB == Header) ? LTB: LFB;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000602 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000603 assert ((!FB || TB == Header || FB == Header) && "Branches not to header?");
604 if (!TB || (FB && TB != Header && FB != Header))
Craig Topper062a2ba2014-04-25 05:30:21 +0000605 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000606
607 // Branches of form "if (!P) ..." cause HexagonInstrInfo::AnalyzeBranch
608 // to put imm(0), followed by P in the vector Cond.
609 // If TB is not the header, it means that the "not-taken" path must lead
610 // to the header.
Brendon Cahoondf43e682015-05-08 16:16:29 +0000611 bool Negated = TII->predOpcodeHasNot(Cond) ^ (TB != Header);
612 unsigned PredReg, PredPos, PredRegFlags;
613 if (!TII->getPredReg(Cond, PredReg, PredPos, PredRegFlags))
614 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000615 MachineInstr *CondI = MRI->getVRegDef(PredReg);
616 unsigned CondOpc = CondI->getOpcode();
617
618 unsigned CmpReg1 = 0, CmpReg2 = 0;
619 int Mask = 0, ImmValue = 0;
620 bool AnalyzedCmp = TII->analyzeCompare(CondI, CmpReg1, CmpReg2,
621 Mask, ImmValue);
622 if (!AnalyzedCmp)
Craig Topper062a2ba2014-04-25 05:30:21 +0000623 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000624
625 // The comparison operator type determines how we compute the loop
626 // trip count.
627 OldInsts.push_back(CondI);
628 OldInsts.push_back(IVOp);
629
630 // Sadly, the following code gets information based on the position
631 // of the operands in the compare instruction. This has to be done
632 // this way, because the comparisons check for a specific relationship
633 // between the operands (e.g. is-less-than), rather than to find out
634 // what relationship the operands are in (as on PPC).
635 Comparison::Kind Cmp;
636 bool isSwapped = false;
637 const MachineOperand &Op1 = CondI->getOperand(1);
638 const MachineOperand &Op2 = CondI->getOperand(2);
Craig Topper062a2ba2014-04-25 05:30:21 +0000639 const MachineOperand *EndValue = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000640
641 if (Op1.isReg()) {
642 if (Op2.isImm() || Op1.getReg() == IVReg)
643 EndValue = &Op2;
644 else {
645 EndValue = &Op1;
646 isSwapped = true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000647 }
648 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000649
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000650 if (!EndValue)
Craig Topper062a2ba2014-04-25 05:30:21 +0000651 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000652
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000653 Cmp = getComparisonKind(CondOpc, InitialValue, EndValue, IVBump);
654 if (!Cmp)
655 return nullptr;
656 if (Negated)
657 Cmp = Comparison::getNegatedComparison(Cmp);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000658 if (isSwapped)
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000659 Cmp = Comparison::getSwappedComparison(Cmp);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000660
661 if (InitialValue->isReg()) {
662 unsigned R = InitialValue->getReg();
663 MachineBasicBlock *DefBB = MRI->getVRegDef(R)->getParent();
664 if (!MDT->properlyDominates(DefBB, Header))
Craig Topper062a2ba2014-04-25 05:30:21 +0000665 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000666 OldInsts.push_back(MRI->getVRegDef(R));
667 }
668 if (EndValue->isReg()) {
669 unsigned R = EndValue->getReg();
670 MachineBasicBlock *DefBB = MRI->getVRegDef(R)->getParent();
671 if (!MDT->properlyDominates(DefBB, Header))
Craig Topper062a2ba2014-04-25 05:30:21 +0000672 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000673 }
674
675 return computeCount(L, InitialValue, EndValue, IVReg, IVBump, Cmp);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000676}
677
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000678/// \brief Helper function that returns the expression that represents the
679/// number of times a loop iterates. The function takes the operands that
680/// represent the loop start value, loop end value, and induction value.
681/// Based upon these operands, the function attempts to compute the trip count.
682CountValue *HexagonHardwareLoops::computeCount(MachineLoop *Loop,
683 const MachineOperand *Start,
684 const MachineOperand *End,
685 unsigned IVReg,
686 int64_t IVBump,
687 Comparison::Kind Cmp) const {
688 // Cannot handle comparison EQ, i.e. while (A == B).
689 if (Cmp == Comparison::EQ)
Craig Topper062a2ba2014-04-25 05:30:21 +0000690 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000691
692 // Check if either the start or end values are an assignment of an immediate.
693 // If so, use the immediate value rather than the register.
694 if (Start->isReg()) {
695 const MachineInstr *StartValInstr = MRI->getVRegDef(Start->getReg());
Colin LeMahieu4af437f2014-12-09 20:23:30 +0000696 if (StartValInstr && StartValInstr->getOpcode() == Hexagon::A2_tfrsi)
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000697 Start = &StartValInstr->getOperand(1);
698 }
699 if (End->isReg()) {
700 const MachineInstr *EndValInstr = MRI->getVRegDef(End->getReg());
Colin LeMahieu4af437f2014-12-09 20:23:30 +0000701 if (EndValInstr && EndValInstr->getOpcode() == Hexagon::A2_tfrsi)
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000702 End = &EndValInstr->getOperand(1);
703 }
704
Brendon Cahoon9376e992015-05-14 14:15:08 +0000705 if (!Start->isReg() && !Start->isImm())
706 return nullptr;
707 if (!End->isReg() && !End->isImm())
708 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000709
710 bool CmpLess = Cmp & Comparison::L;
711 bool CmpGreater = Cmp & Comparison::G;
712 bool CmpHasEqual = Cmp & Comparison::EQ;
713
714 // Avoid certain wrap-arounds. This doesn't detect all wrap-arounds.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000715 if (CmpLess && IVBump < 0)
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000716 // Loop going while iv is "less" with the iv value going down. Must wrap.
Craig Topper062a2ba2014-04-25 05:30:21 +0000717 return nullptr;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000718
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000719 if (CmpGreater && IVBump > 0)
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000720 // Loop going while iv is "greater" with the iv value going up. Must wrap.
Craig Topper062a2ba2014-04-25 05:30:21 +0000721 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000722
Brendon Cahoon9376e992015-05-14 14:15:08 +0000723 // Phis that may feed into the loop.
724 LoopFeederMap LoopFeederPhi;
725
726 // Check if the inital value may be zero and can be decremented in the first
727 // iteration. If the value is zero, the endloop instruction will not decrement
728 // the loop counter, so we shoudn't generate a hardware loop in this case.
729 if (loopCountMayWrapOrUnderFlow(Start, End, Loop->getLoopPreheader(), Loop,
730 LoopFeederPhi))
731 return nullptr;
732
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000733 if (Start->isImm() && End->isImm()) {
734 // Both, start and end are immediates.
735 int64_t StartV = Start->getImm();
736 int64_t EndV = End->getImm();
737 int64_t Dist = EndV - StartV;
738 if (Dist == 0)
Craig Topper062a2ba2014-04-25 05:30:21 +0000739 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000740
741 bool Exact = (Dist % IVBump) == 0;
742
743 if (Cmp == Comparison::NE) {
744 if (!Exact)
Craig Topper062a2ba2014-04-25 05:30:21 +0000745 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000746 if ((Dist < 0) ^ (IVBump < 0))
Craig Topper062a2ba2014-04-25 05:30:21 +0000747 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000748 }
749
750 // For comparisons that include the final value (i.e. include equality
751 // with the final value), we need to increase the distance by 1.
752 if (CmpHasEqual)
753 Dist = Dist > 0 ? Dist+1 : Dist-1;
754
Brendon Cahoon9376e992015-05-14 14:15:08 +0000755 // For the loop to iterate, CmpLess should imply Dist > 0. Similarly,
756 // CmpGreater should imply Dist < 0. These conditions could actually
757 // fail, for example, in unreachable code (which may still appear to be
758 // reachable in the CFG).
759 if ((CmpLess && Dist < 0) || (CmpGreater && Dist > 0))
760 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000761
762 // "Normalized" distance, i.e. with the bump set to +-1.
Brendon Cahoon9376e992015-05-14 14:15:08 +0000763 int64_t Dist1 = (IVBump > 0) ? (Dist + (IVBump - 1)) / IVBump
764 : (-Dist + (-IVBump - 1)) / (-IVBump);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000765 assert (Dist1 > 0 && "Fishy thing. Both operands have the same sign.");
766
767 uint64_t Count = Dist1;
768
769 if (Count > 0xFFFFFFFFULL)
Craig Topper062a2ba2014-04-25 05:30:21 +0000770 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000771
772 return new CountValue(CountValue::CV_Immediate, Count);
773 }
774
775 // A general case: Start and End are some values, but the actual
776 // iteration count may not be available. If it is not, insert
777 // a computation of it into the preheader.
778
779 // If the induction variable bump is not a power of 2, quit.
780 // Othwerise we'd need a general integer division.
Benjamin Kramer7bd1f7c2015-03-09 20:20:16 +0000781 if (!isPowerOf2_64(std::abs(IVBump)))
Craig Topper062a2ba2014-04-25 05:30:21 +0000782 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000783
784 MachineBasicBlock *PH = Loop->getLoopPreheader();
785 assert (PH && "Should have a preheader by now");
786 MachineBasicBlock::iterator InsertPos = PH->getFirstTerminator();
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000787 DebugLoc DL;
788 if (InsertPos != PH->end())
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000789 DL = InsertPos->getDebugLoc();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000790
791 // If Start is an immediate and End is a register, the trip count
792 // will be "reg - imm". Hexagon's "subtract immediate" instruction
793 // is actually "reg + -imm".
794
795 // If the loop IV is going downwards, i.e. if the bump is negative,
796 // then the iteration count (computed as End-Start) will need to be
797 // negated. To avoid the negation, just swap Start and End.
798 if (IVBump < 0) {
799 std::swap(Start, End);
800 IVBump = -IVBump;
801 }
802 // Cmp may now have a wrong direction, e.g. LEs may now be GEs.
803 // Signedness, and "including equality" are preserved.
804
805 bool RegToImm = Start->isReg() && End->isImm(); // for (reg..imm)
806 bool RegToReg = Start->isReg() && End->isReg(); // for (reg..reg)
807
808 int64_t StartV = 0, EndV = 0;
809 if (Start->isImm())
810 StartV = Start->getImm();
811 if (End->isImm())
812 EndV = End->getImm();
813
814 int64_t AdjV = 0;
815 // To compute the iteration count, we would need this computation:
816 // Count = (End - Start + (IVBump-1)) / IVBump
817 // or, when CmpHasEqual:
818 // Count = (End - Start + (IVBump-1)+1) / IVBump
819 // The "IVBump-1" part is the adjustment (AdjV). We can avoid
820 // generating an instruction specifically to add it if we can adjust
821 // the immediate values for Start or End.
822
823 if (CmpHasEqual) {
824 // Need to add 1 to the total iteration count.
825 if (Start->isImm())
826 StartV--;
827 else if (End->isImm())
828 EndV++;
829 else
830 AdjV += 1;
831 }
832
833 if (Cmp != Comparison::NE) {
834 if (Start->isImm())
835 StartV -= (IVBump-1);
836 else if (End->isImm())
837 EndV += (IVBump-1);
838 else
839 AdjV += (IVBump-1);
840 }
841
842 unsigned R = 0, SR = 0;
843 if (Start->isReg()) {
844 R = Start->getReg();
845 SR = Start->getSubReg();
846 } else {
847 R = End->getReg();
848 SR = End->getSubReg();
849 }
850 const TargetRegisterClass *RC = MRI->getRegClass(R);
851 // Hardware loops cannot handle 64-bit registers. If it's a double
852 // register, it has to have a subregister.
853 if (!SR && RC == &Hexagon::DoubleRegsRegClass)
Craig Topper062a2ba2014-04-25 05:30:21 +0000854 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000855 const TargetRegisterClass *IntRC = &Hexagon::IntRegsRegClass;
856
857 // Compute DistR (register with the distance between Start and End).
858 unsigned DistR, DistSR;
859
860 // Avoid special case, where the start value is an imm(0).
861 if (Start->isImm() && StartV == 0) {
862 DistR = End->getReg();
863 DistSR = End->getSubReg();
864 } else {
Colin LeMahieue88447d2014-11-21 21:19:18 +0000865 const MCInstrDesc &SubD = RegToReg ? TII->get(Hexagon::A2_sub) :
Colin LeMahieu27d50072015-02-05 18:38:08 +0000866 (RegToImm ? TII->get(Hexagon::A2_subri) :
Colin LeMahieuf297dbe2015-02-05 17:49:13 +0000867 TII->get(Hexagon::A2_addi));
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000868 if (RegToReg || RegToImm) {
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000869 unsigned SubR = MRI->createVirtualRegister(IntRC);
870 MachineInstrBuilder SubIB =
871 BuildMI(*PH, InsertPos, DL, SubD, SubR);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000872
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000873 if (RegToReg)
874 SubIB.addReg(End->getReg(), 0, End->getSubReg())
875 .addReg(Start->getReg(), 0, Start->getSubReg());
876 else
877 SubIB.addImm(EndV)
878 .addReg(Start->getReg(), 0, Start->getSubReg());
879 DistR = SubR;
880 } else {
881 // If the loop has been unrolled, we should use the original loop count
882 // instead of recalculating the value. This will avoid additional
883 // 'Add' instruction.
884 const MachineInstr *EndValInstr = MRI->getVRegDef(End->getReg());
885 if (EndValInstr->getOpcode() == Hexagon::A2_addi &&
886 EndValInstr->getOperand(2).getImm() == StartV) {
887 DistR = EndValInstr->getOperand(1).getReg();
888 } else {
889 unsigned SubR = MRI->createVirtualRegister(IntRC);
890 MachineInstrBuilder SubIB =
891 BuildMI(*PH, InsertPos, DL, SubD, SubR);
892 SubIB.addReg(End->getReg(), 0, End->getSubReg())
893 .addImm(-StartV);
894 DistR = SubR;
895 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000896 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000897 DistSR = 0;
898 }
899
900 // From DistR, compute AdjR (register with the adjusted distance).
901 unsigned AdjR, AdjSR;
902
903 if (AdjV == 0) {
904 AdjR = DistR;
905 AdjSR = DistSR;
906 } else {
907 // Generate CountR = ADD DistR, AdjVal
908 unsigned AddR = MRI->createVirtualRegister(IntRC);
Colin LeMahieuf297dbe2015-02-05 17:49:13 +0000909 MCInstrDesc const &AddD = TII->get(Hexagon::A2_addi);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000910 BuildMI(*PH, InsertPos, DL, AddD, AddR)
911 .addReg(DistR, 0, DistSR)
912 .addImm(AdjV);
913
914 AdjR = AddR;
915 AdjSR = 0;
916 }
917
918 // From AdjR, compute CountR (register with the final count).
919 unsigned CountR, CountSR;
920
921 if (IVBump == 1) {
922 CountR = AdjR;
923 CountSR = AdjSR;
924 } else {
925 // The IV bump is a power of two. Log_2(IV bump) is the shift amount.
926 unsigned Shift = Log2_32(IVBump);
927
928 // Generate NormR = LSR DistR, Shift.
929 unsigned LsrR = MRI->createVirtualRegister(IntRC);
Colin LeMahieuaa1bade2014-12-16 23:36:15 +0000930 const MCInstrDesc &LsrD = TII->get(Hexagon::S2_lsr_i_r);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000931 BuildMI(*PH, InsertPos, DL, LsrD, LsrR)
932 .addReg(AdjR, 0, AdjSR)
933 .addImm(Shift);
934
935 CountR = LsrR;
936 CountSR = 0;
937 }
938
939 return new CountValue(CountValue::CV_Register, CountR, CountSR);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000940}
941
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000942/// \brief Return true if the operation is invalid within hardware loop.
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000943bool HexagonHardwareLoops::isInvalidLoopOperation(const MachineInstr *MI,
944 bool IsInnerHWLoop) const {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000945
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000946 // Call is not allowed because the callee may use a hardware loop except for
947 // the case when the call never returns.
948 if (MI->getDesc().isCall() && MI->getOpcode() != Hexagon::CALLv3nr)
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000949 return true;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000950
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000951 // Check if the instruction defines a hardware loop register.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000952 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
953 const MachineOperand &MO = MI->getOperand(i);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000954 if (!MO.isReg() || !MO.isDef())
955 continue;
956 unsigned R = MO.getReg();
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000957 if (IsInnerHWLoop && (R == Hexagon::LC0 || R == Hexagon::SA0 ||
958 R == Hexagon::LC1 || R == Hexagon::SA1))
959 return true;
960 if (!IsInnerHWLoop && (R == Hexagon::LC1 || R == Hexagon::SA1))
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000961 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000962 }
963 return false;
964}
965
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000966/// \brief Return true if the loop contains an instruction that inhibits
967/// the use of the hardware loop instruction.
968bool HexagonHardwareLoops::containsInvalidInstruction(MachineLoop *L,
969 bool IsInnerHWLoop) const {
Benjamin Kramer7d605262013-09-15 22:04:42 +0000970 const std::vector<MachineBasicBlock *> &Blocks = L->getBlocks();
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000971 DEBUG(dbgs() << "\nhw_loop head, BB#" << Blocks[0]->getNumber(););
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000972 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
973 MachineBasicBlock *MBB = Blocks[i];
974 for (MachineBasicBlock::iterator
975 MII = MBB->begin(), E = MBB->end(); MII != E; ++MII) {
976 const MachineInstr *MI = &*MII;
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000977 if (isInvalidLoopOperation(MI, IsInnerHWLoop)) {
978 DEBUG(dbgs()<< "\nCannot convert to hw_loop due to:"; MI->dump(););
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000979 return true;
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000980 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000981 }
982 }
983 return false;
984}
985
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000986/// \brief Returns true if the instruction is dead. This was essentially
987/// copied from DeadMachineInstructionElim::isDead, but with special cases
988/// for inline asm, physical registers and instructions with side effects
989/// removed.
990bool HexagonHardwareLoops::isDead(const MachineInstr *MI,
Craig Topperb94011f2013-07-14 04:42:23 +0000991 SmallVectorImpl<MachineInstr *> &DeadPhis) const {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000992 // Examine each operand.
993 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
994 const MachineOperand &MO = MI->getOperand(i);
995 if (!MO.isReg() || !MO.isDef())
996 continue;
997
998 unsigned Reg = MO.getReg();
999 if (MRI->use_nodbg_empty(Reg))
1000 continue;
1001
1002 typedef MachineRegisterInfo::use_nodbg_iterator use_nodbg_iterator;
1003
1004 // This instruction has users, but if the only user is the phi node for the
1005 // parent block, and the only use of that phi node is this instruction, then
1006 // this instruction is dead: both it (and the phi node) can be removed.
1007 use_nodbg_iterator I = MRI->use_nodbg_begin(Reg);
1008 use_nodbg_iterator End = MRI->use_nodbg_end();
Owen Anderson16c6bf42014-03-13 23:12:04 +00001009 if (std::next(I) != End || !I->getParent()->isPHI())
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001010 return false;
1011
Owen Anderson16c6bf42014-03-13 23:12:04 +00001012 MachineInstr *OnePhi = I->getParent();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001013 for (unsigned j = 0, f = OnePhi->getNumOperands(); j != f; ++j) {
1014 const MachineOperand &OPO = OnePhi->getOperand(j);
1015 if (!OPO.isReg() || !OPO.isDef())
1016 continue;
1017
1018 unsigned OPReg = OPO.getReg();
1019 use_nodbg_iterator nextJ;
1020 for (use_nodbg_iterator J = MRI->use_nodbg_begin(OPReg);
1021 J != End; J = nextJ) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001022 nextJ = std::next(J);
Owen Anderson16c6bf42014-03-13 23:12:04 +00001023 MachineOperand &Use = *J;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001024 MachineInstr *UseMI = Use.getParent();
1025
Brendon Cahoon9376e992015-05-14 14:15:08 +00001026 // If the phi node has a user that is not MI, bail.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001027 if (MI != UseMI)
1028 return false;
1029 }
1030 }
1031 DeadPhis.push_back(OnePhi);
1032 }
1033
1034 // If there are no defs with uses, the instruction is dead.
1035 return true;
1036}
1037
1038void HexagonHardwareLoops::removeIfDead(MachineInstr *MI) {
1039 // This procedure was essentially copied from DeadMachineInstructionElim.
1040
1041 SmallVector<MachineInstr*, 1> DeadPhis;
1042 if (isDead(MI, DeadPhis)) {
1043 DEBUG(dbgs() << "HW looping will remove: " << *MI);
1044
1045 // It is possible that some DBG_VALUE instructions refer to this
1046 // instruction. Examine each def operand for such references;
1047 // if found, mark the DBG_VALUE as undef (but don't delete it).
1048 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1049 const MachineOperand &MO = MI->getOperand(i);
1050 if (!MO.isReg() || !MO.isDef())
1051 continue;
1052 unsigned Reg = MO.getReg();
1053 MachineRegisterInfo::use_iterator nextI;
1054 for (MachineRegisterInfo::use_iterator I = MRI->use_begin(Reg),
1055 E = MRI->use_end(); I != E; I = nextI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001056 nextI = std::next(I); // I is invalidated by the setReg
Owen Anderson16c6bf42014-03-13 23:12:04 +00001057 MachineOperand &Use = *I;
1058 MachineInstr *UseMI = I->getParent();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001059 if (UseMI == MI)
1060 continue;
1061 if (Use.isDebug())
1062 UseMI->getOperand(0).setReg(0U);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001063 }
1064 }
1065
1066 MI->eraseFromParent();
1067 for (unsigned i = 0; i < DeadPhis.size(); ++i)
1068 DeadPhis[i]->eraseFromParent();
1069 }
1070}
1071
1072/// \brief Check if the loop is a candidate for converting to a hardware
1073/// loop. If so, then perform the transformation.
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001074///
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001075/// This function works on innermost loops first. A loop can be converted
1076/// if it is a counting loop; either a register value or an immediate.
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001077///
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001078/// The code makes several assumptions about the representation of the loop
1079/// in llvm.
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001080bool HexagonHardwareLoops::convertToHardwareLoop(MachineLoop *L,
1081 bool &RecL0used,
1082 bool &RecL1used) {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001083 // This is just for sanity.
1084 assert(L->getHeader() && "Loop without a header?");
1085
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001086 bool Changed = false;
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001087 bool L0Used = false;
1088 bool L1Used = false;
1089
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001090 // Process nested loops first.
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001091 for (MachineLoop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
1092 Changed |= convertToHardwareLoop(*I, RecL0used, RecL1used);
1093 L0Used |= RecL0used;
1094 L1Used |= RecL1used;
1095 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001096
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001097 // If a nested loop has been converted, then we can't convert this loop.
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001098 if (Changed && L0Used && L1Used)
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001099 return Changed;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001100
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001101 unsigned LOOP_i;
1102 unsigned LOOP_r;
1103 unsigned ENDLOOP;
1104
1105 // Flag used to track loopN instruction:
1106 // 1 - Hardware loop is being generated for the inner most loop.
1107 // 0 - Hardware loop is being generated for the outer loop.
1108 unsigned IsInnerHWLoop = 1;
1109
1110 if (L0Used) {
1111 LOOP_i = Hexagon::J2_loop1i;
1112 LOOP_r = Hexagon::J2_loop1r;
1113 ENDLOOP = Hexagon::ENDLOOP1;
1114 IsInnerHWLoop = 0;
1115 } else {
1116 LOOP_i = Hexagon::J2_loop0i;
1117 LOOP_r = Hexagon::J2_loop0r;
1118 ENDLOOP = Hexagon::ENDLOOP0;
1119 }
1120
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001121#ifndef NDEBUG
1122 // Stop trying after reaching the limit (if any).
1123 int Limit = HWLoopLimit;
1124 if (Limit >= 0) {
1125 if (Counter >= HWLoopLimit)
1126 return false;
1127 Counter++;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001128 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001129#endif
1130
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001131 // Does the loop contain any invalid instructions?
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001132 if (containsInvalidInstruction(L, IsInnerHWLoop))
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001133 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001134
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001135 MachineBasicBlock *LastMBB = getExitingBlock(L);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001136 // Don't generate hw loop if the loop has more than one exit.
Craig Topper062a2ba2014-04-25 05:30:21 +00001137 if (!LastMBB)
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001138 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001139
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001140 MachineBasicBlock::iterator LastI = LastMBB->getFirstTerminator();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001141 if (LastI == LastMBB->end())
Matthew Curtis7a938112012-12-07 21:03:15 +00001142 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001143
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001144 // Is the induction variable bump feeding the latch condition?
1145 if (!fixupInductionVariable(L))
1146 return false;
1147
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001148 // Ensure the loop has a preheader: the loop instruction will be
1149 // placed there.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001150 MachineBasicBlock *Preheader = L->getLoopPreheader();
1151 if (!Preheader) {
1152 Preheader = createPreheaderForLoop(L);
1153 if (!Preheader)
1154 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001155 }
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001156
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001157 MachineBasicBlock::iterator InsertPos = Preheader->getFirstTerminator();
1158
1159 SmallVector<MachineInstr*, 2> OldInsts;
1160 // Are we able to determine the trip count for the loop?
1161 CountValue *TripCount = getLoopTripCount(L, OldInsts);
Craig Topper062a2ba2014-04-25 05:30:21 +00001162 if (!TripCount)
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001163 return false;
1164
1165 // Is the trip count available in the preheader?
1166 if (TripCount->isReg()) {
1167 // There will be a use of the register inserted into the preheader,
1168 // so make sure that the register is actually defined at that point.
1169 MachineInstr *TCDef = MRI->getVRegDef(TripCount->getReg());
1170 MachineBasicBlock *BBDef = TCDef->getParent();
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001171 if (!MDT->dominates(BBDef, Preheader))
1172 return false;
Matthew Curtis7a938112012-12-07 21:03:15 +00001173 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001174
1175 // Determine the loop start.
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001176 MachineBasicBlock *TopBlock = L->getTopBlock();
1177 MachineBasicBlock *ExitingBlock = getExitingBlock(L);
1178 MachineBasicBlock *LoopStart = 0;
1179 if (ExitingBlock != L->getLoopLatch()) {
1180 MachineBasicBlock *TB = 0, *FB = 0;
1181 SmallVector<MachineOperand, 2> Cond;
1182
1183 if (TII->AnalyzeBranch(*ExitingBlock, TB, FB, Cond, false))
1184 return false;
1185
1186 if (L->contains(TB))
1187 LoopStart = TB;
1188 else if (L->contains(FB))
1189 LoopStart = FB;
1190 else
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001191 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001192 }
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001193 else
1194 LoopStart = TopBlock;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001195
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001196 // Convert the loop to a hardware loop.
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001197 DEBUG(dbgs() << "Change to hardware loop at "; L->dump());
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001198 DebugLoc DL;
Matthew Curtis7a938112012-12-07 21:03:15 +00001199 if (InsertPos != Preheader->end())
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001200 DL = InsertPos->getDebugLoc();
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001201
1202 if (TripCount->isReg()) {
1203 // Create a copy of the loop count register.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001204 unsigned CountReg = MRI->createVirtualRegister(&Hexagon::IntRegsRegClass);
1205 BuildMI(*Preheader, InsertPos, DL, TII->get(TargetOpcode::COPY), CountReg)
1206 .addReg(TripCount->getReg(), 0, TripCount->getSubReg());
Benjamin Kramerbde91762012-06-02 10:20:22 +00001207 // Add the Loop instruction to the beginning of the loop.
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001208 BuildMI(*Preheader, InsertPos, DL, TII->get(LOOP_r)).addMBB(LoopStart)
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001209 .addReg(CountReg);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001210 } else {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001211 assert(TripCount->isImm() && "Expecting immediate value for trip count");
1212 // Add the Loop immediate instruction to the beginning of the loop,
1213 // if the immediate fits in the instructions. Otherwise, we need to
1214 // create a new virtual register.
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001215 int64_t CountImm = TripCount->getImm();
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001216 if (!TII->isValidOffset(LOOP_i, CountImm)) {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001217 unsigned CountReg = MRI->createVirtualRegister(&Hexagon::IntRegsRegClass);
Colin LeMahieu4af437f2014-12-09 20:23:30 +00001218 BuildMI(*Preheader, InsertPos, DL, TII->get(Hexagon::A2_tfrsi), CountReg)
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001219 .addImm(CountImm);
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001220 BuildMI(*Preheader, InsertPos, DL, TII->get(LOOP_r))
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001221 .addMBB(LoopStart).addReg(CountReg);
1222 } else
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001223 BuildMI(*Preheader, InsertPos, DL, TII->get(LOOP_i))
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001224 .addMBB(LoopStart).addImm(CountImm);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001225 }
1226
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001227 // Make sure the loop start always has a reference in the CFG. We need
1228 // to create a BlockAddress operand to get this mechanism to work both the
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001229 // MachineBasicBlock and BasicBlock objects need the flag set.
1230 LoopStart->setHasAddressTaken();
1231 // This line is needed to set the hasAddressTaken flag on the BasicBlock
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001232 // object.
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001233 BlockAddress::get(const_cast<BasicBlock *>(LoopStart->getBasicBlock()));
1234
1235 // Replace the loop branch with an endloop instruction.
Matthew Curtis7a938112012-12-07 21:03:15 +00001236 DebugLoc LastIDL = LastI->getDebugLoc();
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001237 BuildMI(*LastMBB, LastI, LastIDL, TII->get(ENDLOOP)).addMBB(LoopStart);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001238
1239 // The loop ends with either:
1240 // - a conditional branch followed by an unconditional branch, or
1241 // - a conditional branch to the loop start.
Colin LeMahieudb0b13c2014-12-10 21:24:10 +00001242 if (LastI->getOpcode() == Hexagon::J2_jumpt ||
1243 LastI->getOpcode() == Hexagon::J2_jumpf) {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001244 // Delete one and change/add an uncond. branch to out of the loop.
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001245 MachineBasicBlock *BranchTarget = LastI->getOperand(1).getMBB();
1246 LastI = LastMBB->erase(LastI);
1247 if (!L->contains(BranchTarget)) {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001248 if (LastI != LastMBB->end())
1249 LastI = LastMBB->erase(LastI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001250 SmallVector<MachineOperand, 0> Cond;
Craig Topper062a2ba2014-04-25 05:30:21 +00001251 TII->InsertBranch(*LastMBB, BranchTarget, nullptr, Cond, LastIDL);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001252 }
1253 } else {
1254 // Conditional branch to loop start; just delete it.
1255 LastMBB->erase(LastI);
1256 }
1257 delete TripCount;
1258
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001259 // The induction operation and the comparison may now be
1260 // unneeded. If these are unneeded, then remove them.
1261 for (unsigned i = 0; i < OldInsts.size(); ++i)
1262 removeIfDead(OldInsts[i]);
1263
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001264 ++NumHWLoops;
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001265
1266 // Set RecL1used and RecL0used only after hardware loop has been
1267 // successfully generated. Doing it earlier can cause wrong loop instruction
1268 // to be used.
1269 if (L0Used) // Loop0 was already used. So, the correct loop must be loop1.
1270 RecL1used = true;
1271 else
1272 RecL0used = true;
1273
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001274 return true;
1275}
1276
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001277bool HexagonHardwareLoops::orderBumpCompare(MachineInstr *BumpI,
1278 MachineInstr *CmpI) {
1279 assert (BumpI != CmpI && "Bump and compare in the same instruction?");
1280
1281 MachineBasicBlock *BB = BumpI->getParent();
1282 if (CmpI->getParent() != BB)
1283 return false;
1284
1285 typedef MachineBasicBlock::instr_iterator instr_iterator;
1286 // Check if things are in order to begin with.
1287 for (instr_iterator I = BumpI, E = BB->instr_end(); I != E; ++I)
1288 if (&*I == CmpI)
1289 return true;
1290
1291 // Out of order.
1292 unsigned PredR = CmpI->getOperand(0).getReg();
1293 bool FoundBump = false;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001294 instr_iterator CmpIt = CmpI, NextIt = std::next(CmpIt);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001295 for (instr_iterator I = NextIt, E = BB->instr_end(); I != E; ++I) {
1296 MachineInstr *In = &*I;
1297 for (unsigned i = 0, n = In->getNumOperands(); i < n; ++i) {
1298 MachineOperand &MO = In->getOperand(i);
1299 if (MO.isReg() && MO.isUse()) {
1300 if (MO.getReg() == PredR) // Found an intervening use of PredR.
1301 return false;
1302 }
1303 }
1304
1305 if (In == BumpI) {
1306 instr_iterator After = BumpI;
1307 instr_iterator From = CmpI;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001308 BB->splice(std::next(After), BB, From);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001309 FoundBump = true;
1310 break;
1311 }
1312 }
1313 assert (FoundBump && "Cannot determine instruction order");
1314 return FoundBump;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001315}
1316
Brendon Cahoon9376e992015-05-14 14:15:08 +00001317/// This function is required to break recursion. Visiting phis in a loop may
1318/// result in recursion during compilation. We break the recursion by making
1319/// sure that we visit a MachineOperand and its definition in a
1320/// MachineInstruction only once. If we attempt to visit more than once, then
1321/// there is recursion, and will return false.
1322bool HexagonHardwareLoops::isLoopFeeder(MachineLoop *L, MachineBasicBlock *A,
1323 MachineInstr *MI,
1324 const MachineOperand *MO,
1325 LoopFeederMap &LoopFeederPhi) const {
1326 if (LoopFeederPhi.find(MO->getReg()) == LoopFeederPhi.end()) {
1327 const std::vector<MachineBasicBlock *> &Blocks = L->getBlocks();
1328 DEBUG(dbgs() << "\nhw_loop head, BB#" << Blocks[0]->getNumber(););
1329 // Ignore all BBs that form Loop.
1330 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1331 MachineBasicBlock *MBB = Blocks[i];
1332 if (A == MBB)
1333 return false;
1334 }
1335 MachineInstr *Def = MRI->getVRegDef(MO->getReg());
1336 LoopFeederPhi.insert(std::make_pair(MO->getReg(), Def));
1337 return true;
1338 } else
1339 // Already visited node.
1340 return false;
1341}
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001342
Brendon Cahoon9376e992015-05-14 14:15:08 +00001343/// Return true if a Phi may generate a value that can underflow.
1344/// This function calls loopCountMayWrapOrUnderFlow for each Phi operand.
1345bool HexagonHardwareLoops::phiMayWrapOrUnderflow(
1346 MachineInstr *Phi, const MachineOperand *EndVal, MachineBasicBlock *MBB,
1347 MachineLoop *L, LoopFeederMap &LoopFeederPhi) const {
1348 assert(Phi->isPHI() && "Expecting a Phi.");
1349 // Walk through each Phi, and its used operands. Make sure that
1350 // if there is recursion in Phi, we won't generate hardware loops.
1351 for (int i = 1, n = Phi->getNumOperands(); i < n; i += 2)
1352 if (isLoopFeeder(L, MBB, Phi, &(Phi->getOperand(i)), LoopFeederPhi))
1353 if (loopCountMayWrapOrUnderFlow(&(Phi->getOperand(i)), EndVal,
1354 Phi->getParent(), L, LoopFeederPhi))
1355 return true;
1356 return false;
1357}
1358
1359/// Return true if the induction variable can underflow in the first iteration.
1360/// An example, is an initial unsigned value that is 0 and is decrement in the
1361/// first itertion of a do-while loop. In this case, we cannot generate a
1362/// hardware loop because the endloop instruction does not decrement the loop
1363/// counter if it is <= 1. We only need to perform this analysis if the
1364/// initial value is a register.
1365///
1366/// This function assumes the initial value may underfow unless proven
1367/// otherwise. If the type is signed, then we don't care because signed
1368/// underflow is undefined. We attempt to prove the initial value is not
1369/// zero by perfoming a crude analysis of the loop counter. This function
1370/// checks if the initial value is used in any comparison prior to the loop
1371/// and, if so, assumes the comparison is a range check. This is inexact,
1372/// but will catch the simple cases.
1373bool HexagonHardwareLoops::loopCountMayWrapOrUnderFlow(
1374 const MachineOperand *InitVal, const MachineOperand *EndVal,
1375 MachineBasicBlock *MBB, MachineLoop *L,
1376 LoopFeederMap &LoopFeederPhi) const {
1377 // Only check register values since they are unknown.
1378 if (!InitVal->isReg())
1379 return false;
1380
1381 if (!EndVal->isImm())
1382 return false;
1383
1384 // A register value that is assigned an immediate is a known value, and it
1385 // won't underflow in the first iteration.
1386 int64_t Imm;
1387 if (checkForImmediate(*InitVal, Imm))
1388 return (EndVal->getImm() == Imm);
1389
1390 unsigned Reg = InitVal->getReg();
1391
1392 // We don't know the value of a physical register.
1393 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1394 return true;
1395
1396 MachineInstr *Def = MRI->getVRegDef(Reg);
1397 if (!Def)
1398 return true;
1399
1400 // If the initial value is a Phi or copy and the operands may not underflow,
1401 // then the definition cannot be underflow either.
1402 if (Def->isPHI() && !phiMayWrapOrUnderflow(Def, EndVal, Def->getParent(),
1403 L, LoopFeederPhi))
1404 return false;
1405 if (Def->isCopy() && !loopCountMayWrapOrUnderFlow(&(Def->getOperand(1)),
1406 EndVal, Def->getParent(),
1407 L, LoopFeederPhi))
1408 return false;
1409
1410 // Iterate over the uses of the initial value. If the initial value is used
1411 // in a compare, then we assume this is a range check that ensures the loop
1412 // doesn't underflow. This is not an exact test and should be improved.
1413 for (MachineRegisterInfo::use_instr_nodbg_iterator I = MRI->use_instr_nodbg_begin(Reg),
1414 E = MRI->use_instr_nodbg_end(); I != E; ++I) {
1415 MachineInstr *MI = &*I;
1416 unsigned CmpReg1 = 0, CmpReg2 = 0;
1417 int CmpMask = 0, CmpValue = 0;
1418
1419 if (!TII->analyzeCompare(MI, CmpReg1, CmpReg2, CmpMask, CmpValue))
1420 continue;
1421
1422 MachineBasicBlock *TBB = 0, *FBB = 0;
1423 SmallVector<MachineOperand, 2> Cond;
1424 if (TII->AnalyzeBranch(*MI->getParent(), TBB, FBB, Cond, false))
1425 continue;
1426
1427 Comparison::Kind Cmp = getComparisonKind(MI->getOpcode(), 0, 0, 0);
1428 if (Cmp == 0)
1429 continue;
1430 if (TII->predOpcodeHasNot(Cond) ^ (TBB != MBB))
1431 Cmp = Comparison::getNegatedComparison(Cmp);
1432 if (CmpReg2 != 0 && CmpReg2 == Reg)
1433 Cmp = Comparison::getSwappedComparison(Cmp);
1434
1435 // Signed underflow is undefined.
1436 if (Comparison::isSigned(Cmp))
1437 return false;
1438
1439 // Check if there is a comparison of the inital value. If the initial value
1440 // is greater than or not equal to another value, then assume this is a
1441 // range check.
1442 if ((Cmp & Comparison::G) || Cmp == Comparison::NE)
1443 return false;
1444 }
1445
1446 // OK - this is a hack that needs to be improved. We really need to analyze
1447 // the instructions performed on the initial value. This works on the simplest
1448 // cases only.
1449 if (!Def->isCopy() && !Def->isPHI())
1450 return false;
1451
1452 return true;
1453}
1454
1455bool HexagonHardwareLoops::checkForImmediate(const MachineOperand &MO,
1456 int64_t &Val) const {
1457 if (MO.isImm()) {
1458 Val = MO.getImm();
1459 return true;
1460 }
1461 if (!MO.isReg())
1462 return false;
1463
1464 // MO is a register. Check whether it is defined as an immediate value,
1465 // and if so, get the value of it in TV. That value will then need to be
1466 // processed to handle potential subregisters in MO.
1467 int64_t TV;
1468
1469 unsigned R = MO.getReg();
1470 if (!TargetRegisterInfo::isVirtualRegister(R))
1471 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001472 MachineInstr *DI = MRI->getVRegDef(R);
1473 unsigned DOpc = DI->getOpcode();
1474 switch (DOpc) {
Brendon Cahoon9376e992015-05-14 14:15:08 +00001475 case TargetOpcode::COPY:
Colin LeMahieu4af437f2014-12-09 20:23:30 +00001476 case Hexagon::A2_tfrsi:
Colin LeMahieu0f850bd2014-12-19 20:29:29 +00001477 case Hexagon::A2_tfrpi:
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001478 case Hexagon::CONST32_Int_Real:
Brendon Cahoon9376e992015-05-14 14:15:08 +00001479 case Hexagon::CONST64_Int_Real: {
1480 // Call recursively to avoid an extra check whether operand(1) is
1481 // indeed an immediate (it could be a global address, for example),
1482 // plus we can handle COPY at the same time.
1483 if (!checkForImmediate(DI->getOperand(1), TV))
1484 return false;
1485 break;
1486 }
1487 case Hexagon::A2_combineii:
1488 case Hexagon::A4_combineir:
1489 case Hexagon::A4_combineii:
1490 case Hexagon::A4_combineri:
1491 case Hexagon::A2_combinew: {
1492 const MachineOperand &S1 = DI->getOperand(1);
1493 const MachineOperand &S2 = DI->getOperand(2);
1494 int64_t V1, V2;
1495 if (!checkForImmediate(S1, V1) || !checkForImmediate(S2, V2))
1496 return false;
1497 TV = V2 | (V1 << 32);
1498 break;
1499 }
1500 case TargetOpcode::REG_SEQUENCE: {
1501 const MachineOperand &S1 = DI->getOperand(1);
1502 const MachineOperand &S3 = DI->getOperand(3);
1503 int64_t V1, V3;
1504 if (!checkForImmediate(S1, V1) || !checkForImmediate(S3, V3))
1505 return false;
1506 unsigned Sub2 = DI->getOperand(2).getImm();
1507 unsigned Sub4 = DI->getOperand(4).getImm();
1508 if (Sub2 == Hexagon::subreg_loreg && Sub4 == Hexagon::subreg_hireg)
1509 TV = V1 | (V3 << 32);
1510 else if (Sub2 == Hexagon::subreg_hireg && Sub4 == Hexagon::subreg_loreg)
1511 TV = V3 | (V1 << 32);
1512 else
1513 llvm_unreachable("Unexpected form of REG_SEQUENCE");
1514 break;
1515 }
1516
1517 default:
1518 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001519 }
Brendon Cahoon9376e992015-05-14 14:15:08 +00001520
1521 // By now, we should have successfuly obtained the immediate value defining
1522 // the register referenced in MO. Handle a potential use of a subregister.
1523 switch (MO.getSubReg()) {
1524 case Hexagon::subreg_loreg:
1525 Val = TV & 0xFFFFFFFFULL;
1526 break;
1527 case Hexagon::subreg_hireg:
1528 Val = (TV >> 32) & 0xFFFFFFFFULL;
1529 break;
1530 default:
1531 Val = TV;
1532 break;
1533 }
1534 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001535}
1536
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001537void HexagonHardwareLoops::setImmediate(MachineOperand &MO, int64_t Val) {
1538 if (MO.isImm()) {
1539 MO.setImm(Val);
1540 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001541 }
1542
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001543 assert(MO.isReg());
1544 unsigned R = MO.getReg();
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001545 MachineInstr *DI = MRI->getVRegDef(R);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001546
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001547 const TargetRegisterClass *RC = MRI->getRegClass(R);
1548 unsigned NewR = MRI->createVirtualRegister(RC);
1549 MachineBasicBlock &B = *DI->getParent();
1550 DebugLoc DL = DI->getDebugLoc();
Brendon Cahoon9376e992015-05-14 14:15:08 +00001551 BuildMI(B, DI, DL, TII->get(DI->getOpcode()), NewR).addImm(Val);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001552 MO.setReg(NewR);
1553}
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001554
Brendon Cahoon9376e992015-05-14 14:15:08 +00001555static bool isImmValidForOpcode(unsigned CmpOpc, int64_t Imm) {
1556 // These two instructions are not extendable.
1557 if (CmpOpc == Hexagon::A4_cmpbeqi)
1558 return isUInt<8>(Imm);
1559 if (CmpOpc == Hexagon::A4_cmpbgti)
1560 return isInt<8>(Imm);
1561 // The rest of the comparison-with-immediate instructions are extendable.
1562 return true;
1563}
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001564
1565bool HexagonHardwareLoops::fixupInductionVariable(MachineLoop *L) {
1566 MachineBasicBlock *Header = L->getHeader();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001567 MachineBasicBlock *Latch = L->getLoopLatch();
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001568 MachineBasicBlock *ExitingBlock = getExitingBlock(L);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001569
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001570 if (!(Header && Latch && ExitingBlock))
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001571 return false;
1572
1573 // These data structures follow the same concept as the corresponding
1574 // ones in findInductionRegister (where some comments are).
1575 typedef std::pair<unsigned,int64_t> RegisterBump;
1576 typedef std::pair<unsigned,RegisterBump> RegisterInduction;
1577 typedef std::set<RegisterInduction> RegisterInductionSet;
1578
1579 // Register candidates for induction variables, with their associated bumps.
1580 RegisterInductionSet IndRegs;
1581
1582 // Look for induction patterns:
1583 // vreg1 = PHI ..., [ latch, vreg2 ]
1584 // vreg2 = ADD vreg1, imm
1585 typedef MachineBasicBlock::instr_iterator instr_iterator;
1586 for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
1587 I != E && I->isPHI(); ++I) {
1588 MachineInstr *Phi = &*I;
1589
1590 // Have a PHI instruction.
1591 for (unsigned i = 1, n = Phi->getNumOperands(); i < n; i += 2) {
1592 if (Phi->getOperand(i+1).getMBB() != Latch)
1593 continue;
1594
1595 unsigned PhiReg = Phi->getOperand(i).getReg();
1596 MachineInstr *DI = MRI->getVRegDef(PhiReg);
1597 unsigned UpdOpc = DI->getOpcode();
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001598 bool isAdd = (UpdOpc == Hexagon::A2_addi || UpdOpc == Hexagon::A2_addp);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001599
1600 if (isAdd) {
1601 // If the register operand to the add/sub is the PHI we are looking
1602 // at, this meets the induction pattern.
1603 unsigned IndReg = DI->getOperand(1).getReg();
Brendon Cahoon9376e992015-05-14 14:15:08 +00001604 MachineOperand &Opnd2 = DI->getOperand(2);
1605 int64_t V;
1606 if (MRI->getVRegDef(IndReg) == Phi && checkForImmediate(Opnd2, V)) {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001607 unsigned UpdReg = DI->getOperand(0).getReg();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001608 IndRegs.insert(std::make_pair(UpdReg, std::make_pair(IndReg, V)));
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001609 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001610 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001611 } // for (i)
1612 } // for (instr)
1613
1614 if (IndRegs.empty())
1615 return false;
1616
Craig Topper062a2ba2014-04-25 05:30:21 +00001617 MachineBasicBlock *TB = nullptr, *FB = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001618 SmallVector<MachineOperand,2> Cond;
1619 // AnalyzeBranch returns true if it fails to analyze branch.
Brendon Cahoon254e6562015-05-13 14:54:24 +00001620 bool NotAnalyzed = TII->AnalyzeBranch(*ExitingBlock, TB, FB, Cond, false);
1621 if (NotAnalyzed || Cond.empty())
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001622 return false;
1623
Brendon Cahoon254e6562015-05-13 14:54:24 +00001624 if (ExitingBlock != Latch && (TB == Latch || FB == Latch)) {
1625 MachineBasicBlock *LTB = 0, *LFB = 0;
1626 SmallVector<MachineOperand,2> LCond;
1627 bool NotAnalyzed = TII->AnalyzeBranch(*Latch, LTB, LFB, LCond, false);
1628 if (NotAnalyzed)
1629 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001630
Brendon Cahoon254e6562015-05-13 14:54:24 +00001631 // Since latch is not the exiting block, the latch branch should be an
1632 // unconditional branch to the loop header.
1633 if (TB == Latch)
1634 TB = (LTB == Header) ? LTB : LFB;
1635 else
1636 FB = (LTB == Header) ? LTB : LFB;
1637 }
1638 if (TB != Header) {
1639 if (FB != Header) {
1640 // The latch/exit block does not go back to the header.
1641 return false;
1642 }
1643 // FB is the header (i.e., uncond. jump to branch header)
1644 // In this case, the LoopBody -> TB should not be a back edge otherwise
1645 // it could result in an infinite loop after conversion to hw_loop.
1646 // This case can happen when the Latch has two jumps like this:
1647 // Jmp_c OuterLoopHeader <-- TB
1648 // Jmp InnerLoopHeader <-- FB
1649 if (MDT->dominates(TB, FB))
1650 return false;
1651 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001652
1653 // Expecting a predicate register as a condition. It won't be a hardware
1654 // predicate register at this point yet, just a vreg.
1655 // HexagonInstrInfo::AnalyzeBranch for negated branches inserts imm(0)
1656 // into Cond, followed by the predicate register. For non-negated branches
1657 // it's just the register.
1658 unsigned CSz = Cond.size();
1659 if (CSz != 1 && CSz != 2)
1660 return false;
1661
Brendon Cahoon254e6562015-05-13 14:54:24 +00001662 if (!Cond[CSz-1].isReg())
1663 return false;
1664
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001665 unsigned P = Cond[CSz-1].getReg();
1666 MachineInstr *PredDef = MRI->getVRegDef(P);
1667
1668 if (!PredDef->isCompare())
1669 return false;
1670
1671 SmallSet<unsigned,2> CmpRegs;
Craig Topper062a2ba2014-04-25 05:30:21 +00001672 MachineOperand *CmpImmOp = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001673
1674 // Go over all operands to the compare and look for immediate and register
1675 // operands. Assume that if the compare has a single register use and a
1676 // single immediate operand, then the register is being compared with the
1677 // immediate value.
1678 for (unsigned i = 0, n = PredDef->getNumOperands(); i < n; ++i) {
1679 MachineOperand &MO = PredDef->getOperand(i);
1680 if (MO.isReg()) {
1681 // Skip all implicit references. In one case there was:
1682 // %vreg140<def> = FCMPUGT32_rr %vreg138, %vreg139, %USR<imp-use>
1683 if (MO.isImplicit())
1684 continue;
1685 if (MO.isUse()) {
Brendon Cahoon9376e992015-05-14 14:15:08 +00001686 if (!isImmediate(MO)) {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001687 CmpRegs.insert(MO.getReg());
1688 continue;
1689 }
1690 // Consider the register to be the "immediate" operand.
1691 if (CmpImmOp)
1692 return false;
1693 CmpImmOp = &MO;
1694 }
1695 } else if (MO.isImm()) {
1696 if (CmpImmOp) // A second immediate argument? Confusing. Bail out.
1697 return false;
1698 CmpImmOp = &MO;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001699 }
1700 }
1701
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001702 if (CmpRegs.empty())
1703 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001704
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001705 // Check if the compared register follows the order we want. Fix if needed.
1706 for (RegisterInductionSet::iterator I = IndRegs.begin(), E = IndRegs.end();
1707 I != E; ++I) {
1708 // This is a success. If the register used in the comparison is one that
1709 // we have identified as a bumped (updated) induction register, there is
1710 // nothing to do.
1711 if (CmpRegs.count(I->first))
1712 return true;
1713
1714 // Otherwise, if the register being compared comes out of a PHI node,
1715 // and has been recognized as following the induction pattern, and is
1716 // compared against an immediate, we can fix it.
1717 const RegisterBump &RB = I->second;
1718 if (CmpRegs.count(RB.first)) {
1719 if (!CmpImmOp)
1720 return false;
1721
Brendon Cahoon9376e992015-05-14 14:15:08 +00001722 // If the register is being compared against an immediate, try changing
1723 // the compare instruction to use induction register and adjust the
1724 // immediate operand.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001725 int64_t CmpImm = getImmediate(*CmpImmOp);
1726 int64_t V = RB.second;
Brendon Cahoon9376e992015-05-14 14:15:08 +00001727 // Handle Overflow (64-bit).
1728 if (((V > 0) && (CmpImm > INT64_MAX - V)) ||
1729 ((V < 0) && (CmpImm < INT64_MIN - V)))
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001730 return false;
1731 CmpImm += V;
Brendon Cahoon9376e992015-05-14 14:15:08 +00001732 // Most comparisons of register against an immediate value allow
1733 // the immediate to be constant-extended. There are some exceptions
1734 // though. Make sure the new combination will work.
1735 if (CmpImmOp->isImm())
1736 if (!isImmValidForOpcode(PredDef->getOpcode(), CmpImm))
1737 return false;
1738
1739 // It is not valid to do this transformation on an unsigned comparison
1740 // because it may underflow.
1741 Comparison::Kind Cmp = getComparisonKind(PredDef->getOpcode(), 0, 0, 0);
1742 if (!Cmp || Comparison::isUnsigned(Cmp))
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001743 return false;
1744
1745 // Make sure that the compare happens after the bump. Otherwise,
1746 // after the fixup, the compare would use a yet-undefined register.
1747 MachineInstr *BumpI = MRI->getVRegDef(I->first);
1748 bool Order = orderBumpCompare(BumpI, PredDef);
1749 if (!Order)
1750 return false;
1751
1752 // Finally, fix the compare instruction.
1753 setImmediate(*CmpImmOp, CmpImm);
1754 for (unsigned i = 0, n = PredDef->getNumOperands(); i < n; ++i) {
1755 MachineOperand &MO = PredDef->getOperand(i);
1756 if (MO.isReg() && MO.getReg() == RB.first) {
1757 MO.setReg(I->first);
1758 return true;
1759 }
1760 }
1761 }
1762 }
1763
1764 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001765}
1766
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001767/// \brief Create a preheader for a given loop.
1768MachineBasicBlock *HexagonHardwareLoops::createPreheaderForLoop(
1769 MachineLoop *L) {
1770 if (MachineBasicBlock *TmpPH = L->getLoopPreheader())
1771 return TmpPH;
1772
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001773 if (!HWCreatePreheader)
1774 return nullptr;
1775
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001776 MachineBasicBlock *Header = L->getHeader();
1777 MachineBasicBlock *Latch = L->getLoopLatch();
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001778 MachineBasicBlock *ExitingBlock = getExitingBlock(L);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001779 MachineFunction *MF = Header->getParent();
1780 DebugLoc DL;
1781
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001782#ifndef NDEBUG
1783 if ((PHFn != "") && (PHFn != MF->getName()))
1784 return nullptr;
1785#endif
1786
1787 if (!Latch || !ExitingBlock || Header->hasAddressTaken())
Craig Topper062a2ba2014-04-25 05:30:21 +00001788 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001789
1790 typedef MachineBasicBlock::instr_iterator instr_iterator;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001791
1792 // Verify that all existing predecessors have analyzable branches
1793 // (or no branches at all).
1794 typedef std::vector<MachineBasicBlock*> MBBVector;
1795 MBBVector Preds(Header->pred_begin(), Header->pred_end());
1796 SmallVector<MachineOperand,2> Tmp1;
Craig Topper062a2ba2014-04-25 05:30:21 +00001797 MachineBasicBlock *TB = nullptr, *FB = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001798
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001799 if (TII->AnalyzeBranch(*ExitingBlock, TB, FB, Tmp1, false))
Craig Topper062a2ba2014-04-25 05:30:21 +00001800 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001801
1802 for (MBBVector::iterator I = Preds.begin(), E = Preds.end(); I != E; ++I) {
1803 MachineBasicBlock *PB = *I;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001804 bool NotAnalyzed = TII->AnalyzeBranch(*PB, TB, FB, Tmp1, false);
1805 if (NotAnalyzed)
1806 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001807 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001808
1809 MachineBasicBlock *NewPH = MF->CreateMachineBasicBlock();
1810 MF->insert(Header, NewPH);
1811
1812 if (Header->pred_size() > 2) {
1813 // Ensure that the header has only two predecessors: the preheader and
1814 // the loop latch. Any additional predecessors of the header should
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001815 // join at the newly created preheader. Inspect all PHI nodes from the
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001816 // header and create appropriate corresponding PHI nodes in the preheader.
1817
1818 for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
1819 I != E && I->isPHI(); ++I) {
1820 MachineInstr *PN = &*I;
1821
1822 const MCInstrDesc &PD = TII->get(TargetOpcode::PHI);
1823 MachineInstr *NewPN = MF->CreateMachineInstr(PD, DL);
1824 NewPH->insert(NewPH->end(), NewPN);
1825
1826 unsigned PR = PN->getOperand(0).getReg();
1827 const TargetRegisterClass *RC = MRI->getRegClass(PR);
1828 unsigned NewPR = MRI->createVirtualRegister(RC);
1829 NewPN->addOperand(MachineOperand::CreateReg(NewPR, true));
1830
1831 // Copy all non-latch operands of a header's PHI node to the newly
1832 // created PHI node in the preheader.
1833 for (unsigned i = 1, n = PN->getNumOperands(); i < n; i += 2) {
1834 unsigned PredR = PN->getOperand(i).getReg();
1835 MachineBasicBlock *PredB = PN->getOperand(i+1).getMBB();
1836 if (PredB == Latch)
1837 continue;
1838
1839 NewPN->addOperand(MachineOperand::CreateReg(PredR, false));
1840 NewPN->addOperand(MachineOperand::CreateMBB(PredB));
1841 }
1842
1843 // Remove copied operands from the old PHI node and add the value
1844 // coming from the preheader's PHI.
1845 for (int i = PN->getNumOperands()-2; i > 0; i -= 2) {
1846 MachineBasicBlock *PredB = PN->getOperand(i+1).getMBB();
1847 if (PredB != Latch) {
1848 PN->RemoveOperand(i+1);
1849 PN->RemoveOperand(i);
1850 }
1851 }
1852 PN->addOperand(MachineOperand::CreateReg(NewPR, false));
1853 PN->addOperand(MachineOperand::CreateMBB(NewPH));
1854 }
1855
1856 } else {
1857 assert(Header->pred_size() == 2);
1858
1859 // The header has only two predecessors, but the non-latch predecessor
1860 // is not a preheader (e.g. it has other successors, etc.)
1861 // In such a case we don't need any extra PHI nodes in the new preheader,
1862 // all we need is to adjust existing PHIs in the header to now refer to
1863 // the new preheader.
1864 for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
1865 I != E && I->isPHI(); ++I) {
1866 MachineInstr *PN = &*I;
1867 for (unsigned i = 1, n = PN->getNumOperands(); i < n; i += 2) {
1868 MachineOperand &MO = PN->getOperand(i+1);
1869 if (MO.getMBB() != Latch)
1870 MO.setMBB(NewPH);
1871 }
1872 }
1873 }
1874
1875 // "Reroute" the CFG edges to link in the new preheader.
1876 // If any of the predecessors falls through to the header, insert a branch
1877 // to the new preheader in that place.
1878 SmallVector<MachineOperand,1> Tmp2;
1879 SmallVector<MachineOperand,1> EmptyCond;
1880
Craig Topper062a2ba2014-04-25 05:30:21 +00001881 TB = FB = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001882
1883 for (MBBVector::iterator I = Preds.begin(), E = Preds.end(); I != E; ++I) {
1884 MachineBasicBlock *PB = *I;
1885 if (PB != Latch) {
1886 Tmp2.clear();
1887 bool NotAnalyzed = TII->AnalyzeBranch(*PB, TB, FB, Tmp2, false);
Alp Tokercb402912014-01-24 17:20:08 +00001888 (void)NotAnalyzed; // suppress compiler warning
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001889 assert (!NotAnalyzed && "Should be analyzable!");
1890 if (TB != Header && (Tmp2.empty() || FB != Header))
Craig Topper062a2ba2014-04-25 05:30:21 +00001891 TII->InsertBranch(*PB, NewPH, nullptr, EmptyCond, DL);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001892 PB->ReplaceUsesOfBlockWith(Header, NewPH);
1893 }
1894 }
1895
1896 // It can happen that the latch block will fall through into the header.
1897 // Insert an unconditional branch to the header.
Craig Topper062a2ba2014-04-25 05:30:21 +00001898 TB = FB = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001899 bool LatchNotAnalyzed = TII->AnalyzeBranch(*Latch, TB, FB, Tmp2, false);
Alp Tokercb402912014-01-24 17:20:08 +00001900 (void)LatchNotAnalyzed; // suppress compiler warning
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001901 assert (!LatchNotAnalyzed && "Should be analyzable!");
1902 if (!TB && !FB)
Craig Topper062a2ba2014-04-25 05:30:21 +00001903 TII->InsertBranch(*Latch, Header, nullptr, EmptyCond, DL);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001904
1905 // Finally, the branch from the preheader to the header.
Craig Topper062a2ba2014-04-25 05:30:21 +00001906 TII->InsertBranch(*NewPH, Header, nullptr, EmptyCond, DL);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001907 NewPH->addSuccessor(Header);
1908
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001909 MachineLoop *ParentLoop = L->getParentLoop();
1910 if (ParentLoop)
1911 ParentLoop->addBasicBlockToLoop(NewPH, MLI->getBase());
1912
1913 // Update the dominator information with the new preheader.
1914 if (MDT) {
1915 MachineDomTreeNode *HDom = MDT->getNode(Header);
1916 MDT->addNewBlock(NewPH, HDom->getIDom()->getBlock());
1917 MDT->changeImmediateDominator(Header, NewPH);
1918 }
1919
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001920 return NewPH;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001921}