blob: 5294266d35fd8ad662848977edd11717f72e1f4f [file] [log] [blame]
Jia Liub22310f2012-02-18 12:03:15 +00001//===-- HexagonFrameLowering.cpp - Define frame lowering ------------------===//
Tony Linthicum1213a7a2011-12-12 21:14:40 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//
9//===----------------------------------------------------------------------===//
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000010
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000011#define DEBUG_TYPE "hexagon-pei"
12
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +000013#include "HexagonBlockRanges.h"
Craig Topperb25fda92012-03-17 18:46:09 +000014#include "HexagonFrameLowering.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000015#include "HexagonInstrInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "HexagonMachineFunctionInfo.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000017#include "HexagonRegisterInfo.h"
18#include "HexagonSubtarget.h"
19#include "HexagonTargetMachine.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000020#include "llvm/ADT/BitVector.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000021#include "llvm/ADT/PostOrderIterator.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000022#include "llvm/CodeGen/MachineDominators.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000023#include "llvm/CodeGen/MachineFunction.h"
24#include "llvm/CodeGen/MachineFunctionPass.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/CodeGen/MachineInstrBuilder.h"
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +000026#include "llvm/CodeGen/MachineInstrBuilder.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000027#include "llvm/CodeGen/MachineModuleInfo.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000028#include "llvm/CodeGen/MachinePostDominators.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000029#include "llvm/CodeGen/MachineRegisterInfo.h"
30#include "llvm/CodeGen/RegisterScavenging.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Function.h"
32#include "llvm/IR/Type.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Support/CommandLine.h"
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000034#include "llvm/Support/Debug.h"
35#include "llvm/Support/raw_ostream.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000036#include "llvm/Target/TargetInstrInfo.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000037#include "llvm/Target/TargetMachine.h"
38#include "llvm/Target/TargetOptions.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000039
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000040// Hexagon stack frame layout as defined by the ABI:
41//
42// Incoming arguments
43// passed via stack
44// |
45// |
46// SP during function's FP during function's |
47// +-- runtime (top of stack) runtime (bottom) --+ |
48// | | |
49// --++---------------------+------------------+-----------------++-+-------
50// | parameter area for | variable-size | fixed-size |LR| arg
51// | called functions | local objects | local objects |FP|
52// --+----------------------+------------------+-----------------+--+-------
53// <- size known -> <- size unknown -> <- size known ->
54//
55// Low address High address
56//
57// <--- stack growth
58//
59//
60// - In any circumstances, the outgoing function arguments are always accessi-
61// ble using the SP, and the incoming arguments are accessible using the FP.
62// - If the local objects are not aligned, they can always be accessed using
63// the FP.
64// - If there are no variable-sized objects, the local objects can always be
65// accessed using the SP, regardless whether they are aligned or not. (The
66// alignment padding will be at the bottom of the stack (highest address),
67// and so the offset with respect to the SP will be known at the compile-
68// -time.)
69//
70// The only complication occurs if there are both, local aligned objects, and
71// dynamically allocated (variable-sized) objects. The alignment pad will be
72// placed between the FP and the local objects, thus preventing the use of the
73// FP to access the local objects. At the same time, the variable-sized objects
74// will be between the SP and the local objects, thus introducing an unknown
75// distance from the SP to the locals.
76//
77// To avoid this problem, a new register is created that holds the aligned
78// address of the bottom of the stack, referred in the sources as AP (aligned
79// pointer). The AP will be equal to "FP-p", where "p" is the smallest pad
80// that aligns AP to the required boundary (a maximum of the alignments of
81// all stack objects, fixed- and variable-sized). All local objects[1] will
82// then use AP as the base pointer.
83// [1] The exception is with "fixed" stack objects. "Fixed" stack objects get
84// their name from being allocated at fixed locations on the stack, relative
85// to the FP. In the presence of dynamic allocation and local alignment, such
86// objects can only be accessed through the FP.
87//
88// Illustration of the AP:
89// FP --+
90// |
91// ---------------+---------------------+-----+-----------------------++-+--
92// Rest of the | Local stack objects | Pad | Fixed stack objects |LR|
93// stack frame | (aligned) | | (CSR, spills, etc.) |FP|
94// ---------------+---------------------+-----+-----------------+-----+--+--
95// |<-- Multiple of the -->|
96// stack alignment +-- AP
97//
98// The AP is set up at the beginning of the function. Since it is not a dedi-
99// cated (reserved) register, it needs to be kept live throughout the function
100// to be available as the base register for local object accesses.
101// Normally, an address of a stack objects is obtained by a pseudo-instruction
102// TFR_FI. To access local objects with the AP register present, a different
103// pseudo-instruction needs to be used: TFR_FIA. The TFR_FIA takes one extra
104// argument compared to TFR_FI: the first input register is the AP register.
105// This keeps the register live between its definition and its uses.
106
107// The AP register is originally set up using pseudo-instruction ALIGNA:
108// AP = ALIGNA A
109// where
110// A - required stack alignment
111// The alignment value must be the maximum of all alignments required by
112// any stack object.
113
114// The dynamic allocation uses a pseudo-instruction ALLOCA:
115// Rd = ALLOCA Rs, A
116// where
117// Rd - address of the allocated space
118// Rs - minimum size (the actual allocated can be larger to accommodate
119// alignment)
120// A - required alignment
121
122
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000123using namespace llvm;
124
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000125static cl::opt<bool> DisableDeallocRet("disable-hexagon-dealloc-ret",
126 cl::Hidden, cl::desc("Disable Dealloc Return for Hexagon target"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000127
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000128static cl::opt<int> NumberScavengerSlots("number-scavenger-slots",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000129 cl::Hidden, cl::desc("Set the number of scavenger slots"), cl::init(2),
130 cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000131
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000132static cl::opt<int> SpillFuncThreshold("spill-func-threshold",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000133 cl::Hidden, cl::desc("Specify O2(not Os) spill func threshold"),
134 cl::init(6), cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000135
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000136static cl::opt<int> SpillFuncThresholdOs("spill-func-threshold-Os",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000137 cl::Hidden, cl::desc("Specify Os spill func threshold"),
138 cl::init(1), cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000139
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000140static cl::opt<bool> EnableShrinkWrapping("hexagon-shrink-frame",
141 cl::init(true), cl::Hidden, cl::ZeroOrMore,
142 cl::desc("Enable stack frame shrink wrapping"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000143
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000144static cl::opt<unsigned> ShrinkLimit("shrink-frame-limit", cl::init(UINT_MAX),
145 cl::Hidden, cl::ZeroOrMore, cl::desc("Max count of stack frame "
146 "shrink-wraps"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000147
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000148static cl::opt<bool> UseAllocframe("use-allocframe", cl::init(true),
149 cl::Hidden, cl::desc("Use allocframe more conservatively"));
150
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +0000151static cl::opt<bool> OptimizeSpillSlots("hexagon-opt-spill", cl::Hidden,
152 cl::init(true), cl::desc("Optimize spill slots"));
153
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000154
155namespace llvm {
156 void initializeHexagonCallFrameInformationPass(PassRegistry&);
157 FunctionPass *createHexagonCallFrameInformation();
158}
159
160namespace {
161 class HexagonCallFrameInformation : public MachineFunctionPass {
162 public:
163 static char ID;
164 HexagonCallFrameInformation() : MachineFunctionPass(ID) {
165 PassRegistry &PR = *PassRegistry::getPassRegistry();
166 initializeHexagonCallFrameInformationPass(PR);
167 }
168 bool runOnMachineFunction(MachineFunction &MF) override;
169 };
170
171 char HexagonCallFrameInformation::ID = 0;
172}
173
174bool HexagonCallFrameInformation::runOnMachineFunction(MachineFunction &MF) {
175 auto &HFI = *MF.getSubtarget<HexagonSubtarget>().getFrameLowering();
176 bool NeedCFI = MF.getMMI().hasDebugInfo() ||
177 MF.getFunction()->needsUnwindTableEntry();
178
179 if (!NeedCFI)
180 return false;
181 HFI.insertCFIInstructions(MF);
182 return true;
183}
184
185INITIALIZE_PASS(HexagonCallFrameInformation, "hexagon-cfi",
186 "Hexagon call frame information", false, false)
187
188FunctionPass *llvm::createHexagonCallFrameInformation() {
189 return new HexagonCallFrameInformation();
190}
191
192
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000193namespace {
194 /// Map a register pair Reg to the subregister that has the greater "number",
195 /// i.e. D3 (aka R7:6) will be mapped to R7, etc.
196 unsigned getMax32BitSubRegister(unsigned Reg, const TargetRegisterInfo &TRI,
197 bool hireg = true) {
198 if (Reg < Hexagon::D0 || Reg > Hexagon::D15)
199 return Reg;
200
201 unsigned RegNo = 0;
202 for (MCSubRegIterator SubRegs(Reg, &TRI); SubRegs.isValid(); ++SubRegs) {
203 if (hireg) {
204 if (*SubRegs > RegNo)
205 RegNo = *SubRegs;
206 } else {
207 if (!RegNo || *SubRegs < RegNo)
208 RegNo = *SubRegs;
209 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000210 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000211 return RegNo;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000212 }
213
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000214 /// Returns the callee saved register with the largest id in the vector.
215 unsigned getMaxCalleeSavedReg(const std::vector<CalleeSavedInfo> &CSI,
216 const TargetRegisterInfo &TRI) {
217 assert(Hexagon::R1 > 0 &&
218 "Assume physical registers are encoded as positive integers");
219 if (CSI.empty())
220 return 0;
221
222 unsigned Max = getMax32BitSubRegister(CSI[0].getReg(), TRI);
223 for (unsigned I = 1, E = CSI.size(); I < E; ++I) {
224 unsigned Reg = getMax32BitSubRegister(CSI[I].getReg(), TRI);
225 if (Reg > Max)
226 Max = Reg;
227 }
228 return Max;
229 }
230
231 /// Checks if the basic block contains any instruction that needs a stack
232 /// frame to be already in place.
233 bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR) {
234 for (auto &I : MBB) {
235 const MachineInstr *MI = &I;
236 if (MI->isCall())
237 return true;
238 unsigned Opc = MI->getOpcode();
239 switch (Opc) {
240 case Hexagon::ALLOCA:
241 case Hexagon::ALIGNA:
242 return true;
243 default:
244 break;
245 }
246 // Check individual operands.
Matthias Braune41e1462015-05-29 02:56:46 +0000247 for (const MachineOperand &MO : MI->operands()) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000248 // While the presence of a frame index does not prove that a stack
249 // frame will be required, all frame indexes should be within alloc-
250 // frame/deallocframe. Otherwise, the code that translates a frame
251 // index into an offset would have to be aware of the placement of
252 // the frame creation/destruction instructions.
Matthias Braune41e1462015-05-29 02:56:46 +0000253 if (MO.isFI())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000254 return true;
Matthias Braune41e1462015-05-29 02:56:46 +0000255 if (!MO.isReg())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000256 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000257 unsigned R = MO.getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000258 // Virtual registers will need scavenging, which then may require
259 // a stack slot.
260 if (TargetRegisterInfo::isVirtualRegister(R))
261 return true;
262 if (CSR[R])
263 return true;
264 }
265 }
266 return false;
267 }
268
269 /// Returns true if MBB has a machine instructions that indicates a tail call
270 /// in the block.
271 bool hasTailCall(const MachineBasicBlock &MBB) {
272 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
273 unsigned RetOpc = I->getOpcode();
274 return RetOpc == Hexagon::TCRETURNi || RetOpc == Hexagon::TCRETURNr;
275 }
276
277 /// Returns true if MBB contains an instruction that returns.
278 bool hasReturn(const MachineBasicBlock &MBB) {
279 for (auto I = MBB.getFirstTerminator(), E = MBB.end(); I != E; ++I)
280 if (I->isReturn())
281 return true;
282 return false;
283 }
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000284}
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000285
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000286
287/// Implements shrink-wrapping of the stack frame. By default, stack frame
288/// is created in the function entry block, and is cleaned up in every block
289/// that returns. This function finds alternate blocks: one for the frame
290/// setup (prolog) and one for the cleanup (epilog).
291void HexagonFrameLowering::findShrunkPrologEpilog(MachineFunction &MF,
292 MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const {
293 static unsigned ShrinkCounter = 0;
294
295 if (ShrinkLimit.getPosition()) {
296 if (ShrinkCounter >= ShrinkLimit)
297 return;
298 ShrinkCounter++;
299 }
300
301 auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
302 auto &HRI = *HST.getRegisterInfo();
303
304 MachineDominatorTree MDT;
305 MDT.runOnMachineFunction(MF);
306 MachinePostDominatorTree MPT;
307 MPT.runOnMachineFunction(MF);
308
309 typedef DenseMap<unsigned,unsigned> UnsignedMap;
310 UnsignedMap RPO;
311 typedef ReversePostOrderTraversal<const MachineFunction*> RPOTType;
312 RPOTType RPOT(&MF);
313 unsigned RPON = 0;
314 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I)
315 RPO[(*I)->getNumber()] = RPON++;
316
317 // Don't process functions that have loops, at least for now. Placement
318 // of prolog and epilog must take loop structure into account. For simpli-
319 // city don't do it right now.
320 for (auto &I : MF) {
321 unsigned BN = RPO[I.getNumber()];
322 for (auto SI = I.succ_begin(), SE = I.succ_end(); SI != SE; ++SI) {
323 // If found a back-edge, return.
324 if (RPO[(*SI)->getNumber()] <= BN)
325 return;
326 }
327 }
328
329 // Collect the set of blocks that need a stack frame to execute. Scan
330 // each block for uses/defs of callee-saved registers, calls, etc.
331 SmallVector<MachineBasicBlock*,16> SFBlocks;
332 BitVector CSR(Hexagon::NUM_TARGET_REGS);
333 for (const MCPhysReg *P = HRI.getCalleeSavedRegs(&MF); *P; ++P)
334 CSR[*P] = true;
335
336 for (auto &I : MF)
337 if (needsStackFrame(I, CSR))
338 SFBlocks.push_back(&I);
339
340 DEBUG({
341 dbgs() << "Blocks needing SF: {";
342 for (auto &B : SFBlocks)
343 dbgs() << " BB#" << B->getNumber();
344 dbgs() << " }\n";
345 });
346 // No frame needed?
347 if (SFBlocks.empty())
348 return;
349
350 // Pick a common dominator and a common post-dominator.
351 MachineBasicBlock *DomB = SFBlocks[0];
352 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
353 DomB = MDT.findNearestCommonDominator(DomB, SFBlocks[i]);
354 if (!DomB)
355 break;
356 }
357 MachineBasicBlock *PDomB = SFBlocks[0];
358 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
359 PDomB = MPT.findNearestCommonDominator(PDomB, SFBlocks[i]);
360 if (!PDomB)
361 break;
362 }
363 DEBUG({
364 dbgs() << "Computed dom block: BB#";
365 if (DomB) dbgs() << DomB->getNumber();
366 else dbgs() << "<null>";
367 dbgs() << ", computed pdom block: BB#";
368 if (PDomB) dbgs() << PDomB->getNumber();
369 else dbgs() << "<null>";
370 dbgs() << "\n";
371 });
372 if (!DomB || !PDomB)
373 return;
374
375 // Make sure that DomB dominates PDomB and PDomB post-dominates DomB.
376 if (!MDT.dominates(DomB, PDomB)) {
377 DEBUG(dbgs() << "Dom block does not dominate pdom block\n");
378 return;
379 }
380 if (!MPT.dominates(PDomB, DomB)) {
381 DEBUG(dbgs() << "PDom block does not post-dominate dom block\n");
382 return;
383 }
384
385 // Finally, everything seems right.
386 PrologB = DomB;
387 EpilogB = PDomB;
388}
389
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000390/// Perform most of the PEI work here:
391/// - saving/restoring of the callee-saved registers,
392/// - stack frame creation and destruction.
393/// Normally, this work is distributed among various functions, but doing it
394/// in one place allows shrink-wrapping of the stack frame.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000395void HexagonFrameLowering::emitPrologue(MachineFunction &MF,
396 MachineBasicBlock &MBB) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000397 auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
398 auto &HRI = *HST.getRegisterInfo();
399
400 MachineFrameInfo *MFI = MF.getFrameInfo();
401 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
402
403 MachineBasicBlock *PrologB = &MF.front(), *EpilogB = nullptr;
404 if (EnableShrinkWrapping)
405 findShrunkPrologEpilog(MF, PrologB, EpilogB);
406
407 insertCSRSpillsInBlock(*PrologB, CSI, HRI);
408 insertPrologueInBlock(*PrologB);
409
410 if (EpilogB) {
411 insertCSRRestoresInBlock(*EpilogB, CSI, HRI);
412 insertEpilogueInBlock(*EpilogB);
413 } else {
414 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000415 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000416 insertCSRRestoresInBlock(B, CSI, HRI);
417
418 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000419 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000420 insertEpilogueInBlock(B);
421 }
422}
423
424
425void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB) const {
426 MachineFunction &MF = *MBB.getParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000427 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000428 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000429 auto &HII = *HST.getInstrInfo();
430 auto &HRI = *HST.getRegisterInfo();
431 DebugLoc dl;
432
433 unsigned MaxAlign = std::max(MFI->getMaxAlignment(), getStackAlignment());
434
435 // Calculate the total stack frame size.
436 // Get the number of bytes to allocate from the FrameInfo.
437 unsigned FrameSize = MFI->getStackSize();
438 // Round up the max call frame size to the max alignment on the stack.
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000439 unsigned MaxCFA = alignTo(MFI->getMaxCallFrameSize(), MaxAlign);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000440 MFI->setMaxCallFrameSize(MaxCFA);
441
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000442 FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000443 MFI->setStackSize(FrameSize);
444
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000445 bool AlignStack = (MaxAlign > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000446
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000447 // Get the number of bytes to allocate from the FrameInfo.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000448 unsigned NumBytes = MFI->getStackSize();
449 unsigned SP = HRI.getStackRegister();
450 unsigned MaxCF = MFI->getMaxCallFrameSize();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000451 MachineBasicBlock::iterator InsertPt = MBB.begin();
452
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000453 auto *FuncInfo = MF.getInfo<HexagonMachineFunctionInfo>();
454 auto &AdjustRegs = FuncInfo->getAllocaAdjustInsts();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000455
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000456 for (auto MI : AdjustRegs) {
457 assert((MI->getOpcode() == Hexagon::ALLOCA) && "Expected alloca");
458 expandAlloca(MI, HII, SP, MaxCF);
459 MI->eraseFromParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000460 }
461
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000462 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000463 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000464
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000465 // Check for overflow.
466 // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
467 const unsigned int ALLOCFRAME_MAX = 16384;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000468
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000469 // Create a dummy memory operand to avoid allocframe from being treated as
470 // a volatile memory reference.
471 MachineMemOperand *MMO =
472 MF.getMachineMemOperand(MachinePointerInfo(), MachineMemOperand::MOStore,
473 4, 4);
474
475 if (NumBytes >= ALLOCFRAME_MAX) {
476 // Emit allocframe(#0).
477 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
478 .addImm(0)
479 .addMemOperand(MMO);
480
481 // Subtract offset from frame pointer.
482 // We use a caller-saved non-parameter register for that.
483 unsigned CallerSavedReg = HRI.getFirstCallerSavedNonParamReg();
484 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CONST32_Int_Real),
485 CallerSavedReg).addImm(NumBytes);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000486 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_sub), SP)
487 .addReg(SP)
488 .addReg(CallerSavedReg);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000489 } else {
490 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
491 .addImm(NumBytes)
492 .addMemOperand(MMO);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000493 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000494
495 if (AlignStack) {
496 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
497 .addReg(SP)
498 .addImm(-int64_t(MaxAlign));
499 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000500}
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000501
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000502void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
503 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000504 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000505 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000506
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000507 auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
508 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000509 auto &HRI = *HST.getRegisterInfo();
510 unsigned SP = HRI.getStackRegister();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000511
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000512 MachineInstr *RetI = nullptr;
513 for (auto &I : MBB) {
514 if (!I.isReturn())
515 continue;
516 RetI = &I;
517 break;
518 }
519 unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
520
521 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
522 DebugLoc DL;
523 if (InsertPt != MBB.end())
524 DL = InsertPt->getDebugLoc();
525 else if (!MBB.empty())
526 DL = std::prev(MBB.end())->getDebugLoc();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000527
528 // Handle EH_RETURN.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000529 if (RetOpc == Hexagon::EH_RETURN_JMPR) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000530 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
531 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::A2_add), SP)
532 .addReg(SP)
533 .addReg(Hexagon::R28);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000534 return;
535 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000536
537 // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
538 // frame instruction if we encounter it.
539 if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4) {
540 MachineBasicBlock::iterator It = RetI;
541 ++It;
542 // Delete all instructions after the RESTORE (except labels).
543 while (It != MBB.end()) {
544 if (!It->isLabel())
545 It = MBB.erase(It);
546 else
547 ++It;
Jyotsna Verma300f0b92013-05-10 20:27:34 +0000548 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000549 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000550 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000551
552 // It is possible that the restoring code is a call to a library function.
553 // All of the restore* functions include "deallocframe", so we need to make
554 // sure that we don't add an extra one.
555 bool NeedsDeallocframe = true;
556 if (!MBB.empty() && InsertPt != MBB.begin()) {
557 MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
558 unsigned COpc = PrevIt->getOpcode();
559 if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4)
560 NeedsDeallocframe = false;
561 }
562
563 if (!NeedsDeallocframe)
564 return;
565 // If the returning instruction is JMPret, replace it with dealloc_return,
566 // otherwise just add deallocframe. The function could be returning via a
567 // tail call.
568 if (RetOpc != Hexagon::JMPret || DisableDeallocRet) {
569 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
570 return;
571 }
572 unsigned NewOpc = Hexagon::L4_return;
573 MachineInstr *NewI = BuildMI(MBB, RetI, DL, HII.get(NewOpc));
574 // Transfer the function live-out registers.
575 NewI->copyImplicitOps(MF, RetI);
576 MBB.erase(RetI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000577}
578
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000579
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000580namespace {
581 bool IsAllocFrame(MachineBasicBlock::const_iterator It) {
582 if (!It->isBundle())
583 return It->getOpcode() == Hexagon::S2_allocframe;
584 auto End = It->getParent()->instr_end();
Duncan P. N. Exon Smithd84f6002016-02-22 21:30:15 +0000585 MachineBasicBlock::const_instr_iterator I = It.getInstrIterator();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000586 while (++I != End && I->isBundled())
587 if (I->getOpcode() == Hexagon::S2_allocframe)
588 return true;
589 return false;
590 }
591
592 MachineBasicBlock::iterator FindAllocFrame(MachineBasicBlock &B) {
593 for (auto &I : B)
594 if (IsAllocFrame(I))
595 return I;
596 return B.end();
597 }
598}
599
600
601void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
602 for (auto &B : MF) {
603 auto AF = FindAllocFrame(B);
604 if (AF == B.end())
605 continue;
606 insertCFIInstructionsAt(B, ++AF);
607 }
608}
609
610
611void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
612 MachineBasicBlock::iterator At) const {
613 MachineFunction &MF = *MBB.getParent();
614 MachineFrameInfo *MFI = MF.getFrameInfo();
615 MachineModuleInfo &MMI = MF.getMMI();
616 auto &HST = MF.getSubtarget<HexagonSubtarget>();
617 auto &HII = *HST.getInstrInfo();
618 auto &HRI = *HST.getRegisterInfo();
619
620 // If CFI instructions have debug information attached, something goes
621 // wrong with the final assembly generation: the prolog_end is placed
622 // in a wrong location.
623 DebugLoc DL;
624 const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
625
626 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
627
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000628 if (hasFP(MF)) {
629 unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
630 unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000631
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000632 // Define CFA via an offset from the value of FP.
633 //
634 // -8 -4 0 (SP)
635 // --+----+----+---------------------
636 // | FP | LR | increasing addresses -->
637 // --+----+----+---------------------
638 // | +-- Old SP (before allocframe)
639 // +-- New FP (after allocframe)
640 //
641 // MCCFIInstruction::createDefCfa subtracts the offset from the register.
642 // MCCFIInstruction::createOffset takes the offset without sign change.
643 auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
644 BuildMI(MBB, At, DL, CFID)
645 .addCFIIndex(MMI.addFrameInst(DefCfa));
646 // R31 (return addr) = CFA - 4
647 auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
648 BuildMI(MBB, At, DL, CFID)
649 .addCFIIndex(MMI.addFrameInst(OffR31));
650 // R30 (frame ptr) = CFA - 8
651 auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
652 BuildMI(MBB, At, DL, CFID)
653 .addCFIIndex(MMI.addFrameInst(OffR30));
654 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000655
656 static unsigned int RegsToMove[] = {
657 Hexagon::R1, Hexagon::R0, Hexagon::R3, Hexagon::R2,
658 Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
659 Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
660 Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
661 Hexagon::D0, Hexagon::D1, Hexagon::D8, Hexagon::D9,
662 Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
663 Hexagon::NoRegister
664 };
665
666 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
667
668 for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
669 unsigned Reg = RegsToMove[i];
670 auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
671 return C.getReg() == Reg;
672 };
673 auto F = std::find_if(CSI.begin(), CSI.end(), IfR);
674 if (F == CSI.end())
675 continue;
676
677 // Subtract 8 to make room for R30 and R31, which are added above.
678 unsigned FrameReg;
679 int64_t Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg) - 8;
680
681 if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
682 unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
683 auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
684 Offset);
685 BuildMI(MBB, At, DL, CFID)
686 .addCFIIndex(MMI.addFrameInst(OffReg));
687 } else {
688 // Split the double regs into subregs, and generate appropriate
689 // cfi_offsets.
690 // The only reason, we are split double regs is, llvm-mc does not
691 // understand paired registers for cfi_offset.
692 // Eg .cfi_offset r1:0, -64
693
694 unsigned HiReg = HRI.getSubReg(Reg, Hexagon::subreg_hireg);
695 unsigned LoReg = HRI.getSubReg(Reg, Hexagon::subreg_loreg);
696 unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
697 unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
698 auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
699 Offset+4);
700 BuildMI(MBB, At, DL, CFID)
701 .addCFIIndex(MMI.addFrameInst(OffHi));
702 auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
703 Offset);
704 BuildMI(MBB, At, DL, CFID)
705 .addCFIIndex(MMI.addFrameInst(OffLo));
706 }
707 }
708}
709
710
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000711bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000712 auto &MFI = *MF.getFrameInfo();
713 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
714
715 bool HasFixed = MFI.getNumFixedObjects();
716 bool HasPrealloc = const_cast<MachineFrameInfo&>(MFI)
717 .getLocalFrameObjectCount();
718 bool HasExtraAlign = HRI.needsStackRealignment(MF);
719 bool HasAlloca = MFI.hasVarSizedObjects();
720
721 // Insert ALLOCFRAME if we need to or at -O0 for the debugger. Think
722 // that this shouldn't be required, but doing so now because gcc does and
723 // gdb can't break at the start of the function without it. Will remove if
724 // this turns out to be a gdb bug.
725 //
726 if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
727 return true;
728
729 // By default we want to use SP (since it's always there). FP requires
730 // some setup (i.e. ALLOCFRAME).
731 // Fixed and preallocated objects need FP if the distance from them to
732 // the SP is unknown (as is with alloca or aligna).
733 if ((HasFixed || HasPrealloc) && (HasAlloca || HasExtraAlign))
734 return true;
735
736 if (MFI.getStackSize() > 0) {
737 if (UseAllocframe)
738 return true;
739 }
740
741 if (MFI.hasCalls() ||
742 MF.getInfo<HexagonMachineFunctionInfo>()->hasClobberLR())
743 return true;
744
745 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000746}
747
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000748
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000749enum SpillKind {
750 SK_ToMem,
751 SK_FromMem,
752 SK_FromMemTailcall
753};
754
755static const char *
756getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType) {
757 const char * V4SpillToMemoryFunctions[] = {
758 "__save_r16_through_r17",
759 "__save_r16_through_r19",
760 "__save_r16_through_r21",
761 "__save_r16_through_r23",
762 "__save_r16_through_r25",
763 "__save_r16_through_r27" };
764
765 const char * V4SpillFromMemoryFunctions[] = {
766 "__restore_r16_through_r17_and_deallocframe",
767 "__restore_r16_through_r19_and_deallocframe",
768 "__restore_r16_through_r21_and_deallocframe",
769 "__restore_r16_through_r23_and_deallocframe",
770 "__restore_r16_through_r25_and_deallocframe",
771 "__restore_r16_through_r27_and_deallocframe" };
772
773 const char * V4SpillFromMemoryTailcallFunctions[] = {
774 "__restore_r16_through_r17_and_deallocframe_before_tailcall",
775 "__restore_r16_through_r19_and_deallocframe_before_tailcall",
776 "__restore_r16_through_r21_and_deallocframe_before_tailcall",
777 "__restore_r16_through_r23_and_deallocframe_before_tailcall",
778 "__restore_r16_through_r25_and_deallocframe_before_tailcall",
779 "__restore_r16_through_r27_and_deallocframe_before_tailcall"
780 };
781
782 const char **SpillFunc = nullptr;
783
784 switch(SpillType) {
785 case SK_ToMem:
786 SpillFunc = V4SpillToMemoryFunctions;
787 break;
788 case SK_FromMem:
789 SpillFunc = V4SpillFromMemoryFunctions;
790 break;
791 case SK_FromMemTailcall:
792 SpillFunc = V4SpillFromMemoryTailcallFunctions;
793 break;
794 }
795 assert(SpillFunc && "Unknown spill kind");
796
797 // Spill all callee-saved registers up to the highest register used.
798 switch (MaxReg) {
799 case Hexagon::R17:
800 return SpillFunc[0];
801 case Hexagon::R19:
802 return SpillFunc[1];
803 case Hexagon::R21:
804 return SpillFunc[2];
805 case Hexagon::R23:
806 return SpillFunc[3];
807 case Hexagon::R25:
808 return SpillFunc[4];
809 case Hexagon::R27:
810 return SpillFunc[5];
811 default:
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000812 llvm_unreachable("Unhandled maximum callee save register");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000813 }
814 return 0;
815}
816
817/// Adds all callee-saved registers up to MaxReg to the instruction.
818static void addCalleeSaveRegistersAsImpOperand(MachineInstr *Inst,
819 unsigned MaxReg, bool IsDef) {
820 // Add the callee-saved registers as implicit uses.
821 for (unsigned R = Hexagon::R16; R <= MaxReg; ++R) {
822 MachineOperand ImpUse = MachineOperand::CreateReg(R, IsDef, true);
823 Inst->addOperand(ImpUse);
824 }
825}
826
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000827
James Y Knight5567baf2015-08-15 02:32:35 +0000828int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF,
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000829 int FI, unsigned &FrameReg) const {
830 auto &MFI = *MF.getFrameInfo();
831 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000832
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000833 int Offset = MFI.getObjectOffset(FI);
834 bool HasAlloca = MFI.hasVarSizedObjects();
835 bool HasExtraAlign = HRI.needsStackRealignment(MF);
836 bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
James Y Knight5567baf2015-08-15 02:32:35 +0000837
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000838 unsigned SP = HRI.getStackRegister(), FP = HRI.getFrameRegister();
839 unsigned AP = 0;
840 if (const MachineInstr *AI = getAlignaInstr(MF))
841 AP = AI->getOperand(0).getReg();
842 unsigned FrameSize = MFI.getStackSize();
843
844 bool UseFP = false, UseAP = false; // Default: use SP (except at -O0).
845 // Use FP at -O0, except when there are objects with extra alignment.
846 // That additional alignment requirement may cause a pad to be inserted,
847 // which will make it impossible to use FP to access objects located
848 // past the pad.
849 if (NoOpt && !HasExtraAlign)
850 UseFP = true;
851 if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
852 // Fixed and preallocated objects will be located before any padding
853 // so FP must be used to access them.
854 UseFP |= (HasAlloca || HasExtraAlign);
855 } else {
856 if (HasAlloca) {
857 if (HasExtraAlign)
858 UseAP = true;
859 else
860 UseFP = true;
861 }
862 }
863
864 // If FP was picked, then there had better be FP.
865 bool HasFP = hasFP(MF);
866 assert((HasFP || !UseFP) && "This function must have frame pointer");
867
868 // Having FP implies allocframe. Allocframe will store extra 8 bytes:
869 // FP/LR. If the base register is used to access an object across these
870 // 8 bytes, then the offset will need to be adjusted by 8.
871 //
872 // After allocframe:
873 // HexagonISelLowering adds 8 to ---+
874 // the offsets of all stack-based |
875 // arguments (*) |
876 // |
877 // getObjectOffset < 0 0 8 getObjectOffset >= 8
878 // ------------------------+-----+------------------------> increasing
879 // <local objects> |FP/LR| <input arguments> addresses
880 // -----------------+------+-----+------------------------>
881 // | |
882 // SP/AP point --+ +-- FP points here (**)
883 // somewhere on
884 // this side of FP/LR
885 //
886 // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
887 // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
888
889 // The lowering assumes that FP/LR is present, and so the offsets of
890 // the formal arguments start at 8. If FP/LR is not there we need to
891 // reduce the offset by 8.
892 if (Offset > 0 && !HasFP)
893 Offset -= 8;
894
895 if (UseFP)
896 FrameReg = FP;
897 else if (UseAP)
898 FrameReg = AP;
899 else
900 FrameReg = SP;
901
902 // Calculate the actual offset in the instruction. If there is no FP
903 // (in other words, no allocframe), then SP will not be adjusted (i.e.
904 // there will be no SP -= FrameSize), so the frame size should not be
905 // added to the calculated offset.
906 int RealOffset = Offset;
907 if (!UseFP && !UseAP && HasFP)
908 RealOffset = FrameSize+Offset;
909 return RealOffset;
Jakob Stoklund Olesen0b97dbc2012-05-30 22:40:03 +0000910}
911
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000912
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000913bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
914 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
915 if (CSI.empty())
916 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000917
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000918 MachineBasicBlock::iterator MI = MBB.begin();
919 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000920 auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000921
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000922 if (useSpillFunction(MF, CSI)) {
923 unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
924 const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem);
925 // Call spill function.
926 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
927 MachineInstr *SaveRegsCall =
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000928 BuildMI(MBB, MI, DL, HII.get(Hexagon::SAVE_REGISTERS_CALL_V4))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000929 .addExternalSymbol(SpillFun);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000930 // Add callee-saved registers as use.
931 addCalleeSaveRegistersAsImpOperand(SaveRegsCall, MaxReg, false);
932 // Add live in registers.
933 for (unsigned I = 0; I < CSI.size(); ++I)
934 MBB.addLiveIn(CSI[I].getReg());
935 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000936 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000937
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000938 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000939 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000940 // Add live in registers. We treat eh_return callee saved register r0 - r3
941 // specially. They are not really callee saved registers as they are not
942 // supposed to be killed.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000943 bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
944 int FI = CSI[i].getFrameIdx();
945 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000946 HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000947 if (IsKill)
948 MBB.addLiveIn(Reg);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000949 }
950 return true;
951}
952
953
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000954bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
955 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
956 if (CSI.empty())
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000957 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000958
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000959 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
960 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000961 auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000962
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000963 if (useRestoreFunction(MF, CSI)) {
964 bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
965 unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
966 SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
967 const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000968
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000969 // Call spill function.
970 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
971 : MBB.getLastNonDebugInstr()->getDebugLoc();
972 MachineInstr *DeallocCall = nullptr;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000973
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000974 if (HasTC) {
975 unsigned ROpc = Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000976 DeallocCall = BuildMI(MBB, MI, DL, HII.get(ROpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000977 .addExternalSymbol(RestoreFn);
978 } else {
979 // The block has a return.
980 MachineBasicBlock::iterator It = MBB.getFirstTerminator();
981 assert(It->isReturn() && std::next(It) == MBB.end());
982 unsigned ROpc = Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000983 DeallocCall = BuildMI(MBB, It, DL, HII.get(ROpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000984 .addExternalSymbol(RestoreFn);
985 // Transfer the function live-out registers.
986 DeallocCall->copyImplicitOps(MF, It);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000987 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000988 addCalleeSaveRegistersAsImpOperand(DeallocCall, MaxR, true);
989 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000990 }
991
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000992 for (unsigned i = 0; i < CSI.size(); ++i) {
993 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000994 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
995 int FI = CSI[i].getFrameIdx();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000996 HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000997 }
998 return true;
999}
1000
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001001
1002void HexagonFrameLowering::eliminateCallFramePseudoInstr(MachineFunction &MF,
1003 MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00001004 MachineInstr &MI = *I;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001005 unsigned Opc = MI.getOpcode();
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001006 (void)Opc; // Silence compiler warning.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001007 assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1008 "Cannot handle this call frame pseudo instruction");
Eli Bendersky8da87162013-02-21 20:05:00 +00001009 MBB.erase(I);
1010}
1011
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001012
1013void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1014 MachineFunction &MF, RegScavenger *RS) const {
1015 // If this function has uses aligned stack and also has variable sized stack
1016 // objects, then we need to map all spill slots to fixed positions, so that
1017 // they can be accessed through FP. Otherwise they would have to be accessed
1018 // via AP, which may not be available at the particular place in the program.
1019 MachineFrameInfo *MFI = MF.getFrameInfo();
1020 bool HasAlloca = MFI->hasVarSizedObjects();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001021 bool NeedsAlign = (MFI->getMaxAlignment() > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001022
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001023 if (!HasAlloca || !NeedsAlign)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001024 return;
1025
1026 unsigned LFS = MFI->getLocalFrameSize();
1027 int Offset = -LFS;
1028 for (int i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
1029 if (!MFI->isSpillSlotObjectIndex(i) || MFI->isDeadObjectIndex(i))
1030 continue;
1031 int S = MFI->getObjectSize(i);
1032 LFS += S;
1033 Offset -= S;
1034 MFI->mapLocalFrameObject(i, Offset);
1035 }
1036
1037 MFI->setLocalFrameSize(LFS);
1038 unsigned A = MFI->getLocalFrameMaxAlign();
1039 assert(A <= 8 && "Unexpected local frame alignment");
1040 if (A == 0)
1041 MFI->setLocalFrameMaxAlign(8);
1042 MFI->setUseLocalStackAllocationBlock(true);
1043}
1044
1045/// Returns true if there is no caller saved registers available.
1046static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
1047 const HexagonRegisterInfo &HRI) {
1048 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001049 const MCPhysReg *CallerSavedRegs = HRI.getCallerSavedRegs(&MF);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001050 // Check for an unused caller-saved register.
1051 for ( ; *CallerSavedRegs; ++CallerSavedRegs) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001052 MCPhysReg FreeReg = *CallerSavedRegs;
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001053 if (MRI.isPhysRegUsed(FreeReg))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001054 continue;
1055
1056 // Check aliased register usage.
1057 bool IsCurrentRegUsed = false;
1058 for (MCRegAliasIterator AI(FreeReg, &HRI, false); AI.isValid(); ++AI)
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001059 if (MRI.isPhysRegUsed(*AI)) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001060 IsCurrentRegUsed = true;
1061 break;
1062 }
1063 if (IsCurrentRegUsed)
1064 continue;
1065
1066 // Neither directly used nor used through an aliased register.
1067 return false;
1068 }
1069 // All caller-saved registers are used.
1070 return true;
1071}
1072
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001073
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001074#ifndef NDEBUG
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001075static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001076 dbgs() << '{';
1077 for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1078 unsigned R = x;
1079 dbgs() << ' ' << PrintReg(R, &TRI);
1080 }
1081 dbgs() << " }";
1082}
1083#endif
1084
1085
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001086bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1087 const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
Krzysztof Parzyszek27ba19a12015-04-23 20:42:20 +00001088 DEBUG(dbgs() << LLVM_FUNCTION_NAME << " on "
Krzysztof Parzyszeked75e7a2015-04-23 20:57:39 +00001089 << MF.getFunction()->getName() << '\n');
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001090 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001091 BitVector SRegs(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001092
1093 // Generate a set of unique, callee-saved registers (SRegs), where each
1094 // register in the set is maximal in terms of sub-/super-register relation,
1095 // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1096
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001097 // (1) For each callee-saved register, add that register and all of its
1098 // sub-registers to SRegs.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001099 DEBUG(dbgs() << "Initial CS registers: {");
1100 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1101 unsigned R = CSI[i].getReg();
1102 DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1103 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1104 SRegs[*SR] = true;
1105 }
1106 DEBUG(dbgs() << " }\n");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001107 DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001108
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001109 // (2) For each reserved register, remove that register and all of its
1110 // sub- and super-registers from SRegs.
1111 BitVector Reserved = TRI->getReservedRegs(MF);
1112 for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1113 unsigned R = x;
1114 for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1115 SRegs[*SR] = false;
1116 }
1117 DEBUG(dbgs() << "Res: "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1118 DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1119
1120 // (3) Collect all registers that have at least one sub-register in SRegs,
1121 // and also have no sub-registers that are reserved. These will be the can-
1122 // didates for saving as a whole instead of their individual sub-registers.
1123 // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1124 BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001125 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1126 unsigned R = x;
1127 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1128 TmpSup[*SR] = true;
1129 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001130 for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1131 unsigned R = x;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001132 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1133 if (!Reserved[*SR])
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001134 continue;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001135 TmpSup[R] = false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001136 break;
1137 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001138 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001139 DEBUG(dbgs() << "TmpSup: "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001140
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001141 // (4) Include all super-registers found in (3) into SRegs.
1142 SRegs |= TmpSup;
1143 DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001144
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001145 // (5) For each register R in SRegs, if any super-register of R is in SRegs,
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001146 // remove R from SRegs.
1147 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1148 unsigned R = x;
1149 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1150 if (!SRegs[*SR])
1151 continue;
1152 SRegs[R] = false;
1153 break;
1154 }
1155 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001156 DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001157
1158 // Now, for each register that has a fixed stack slot, create the stack
1159 // object for it.
1160 CSI.clear();
1161
1162 typedef TargetFrameLowering::SpillSlot SpillSlot;
1163 unsigned NumFixed;
1164 int MinOffset = 0; // CS offsets are negative.
1165 const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1166 for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1167 if (!SRegs[S->Reg])
1168 continue;
1169 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
1170 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), S->Offset);
1171 MinOffset = std::min(MinOffset, S->Offset);
1172 CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1173 SRegs[S->Reg] = false;
1174 }
1175
1176 // There can be some registers that don't have fixed slots. For example,
1177 // we need to store R0-R3 in functions with exception handling. For each
1178 // such register, create a non-fixed stack object.
1179 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1180 unsigned R = x;
1181 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
1182 int Off = MinOffset - RC->getSize();
1183 unsigned Align = std::min(RC->getAlignment(), getStackAlignment());
1184 assert(isPowerOf2_32(Align));
1185 Off &= -Align;
1186 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), Off);
1187 MinOffset = std::min(MinOffset, Off);
1188 CSI.push_back(CalleeSavedInfo(R, FI));
1189 SRegs[R] = false;
1190 }
1191
1192 DEBUG({
1193 dbgs() << "CS information: {";
1194 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1195 int FI = CSI[i].getFrameIdx();
1196 int Off = MFI->getObjectOffset(FI);
1197 dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1198 if (Off >= 0)
1199 dbgs() << '+';
1200 dbgs() << Off;
1201 }
1202 dbgs() << " }\n";
1203 });
1204
1205#ifndef NDEBUG
1206 // Verify that all registers were handled.
1207 bool MissedReg = false;
1208 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1209 unsigned R = x;
1210 dbgs() << PrintReg(R, TRI) << ' ';
1211 MissedReg = true;
1212 }
1213 if (MissedReg)
1214 llvm_unreachable("...there are unhandled callee-saved registers!");
1215#endif
1216
1217 return true;
1218}
1219
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001220
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001221bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1222 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1223 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1224 MachineInstr *MI = &*It;
1225 DebugLoc DL = MI->getDebugLoc();
1226 unsigned DstR = MI->getOperand(0).getReg();
1227 unsigned SrcR = MI->getOperand(1).getReg();
1228 if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1229 !Hexagon::ModRegsRegClass.contains(SrcR))
1230 return false;
1231
1232 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1233 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR)
1234 .addOperand(MI->getOperand(1));
1235 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1236 .addReg(TmpR, RegState::Kill);
1237
1238 NewRegs.push_back(TmpR);
1239 B.erase(It);
1240 return true;
1241}
1242
1243bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1244 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1245 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1246 MachineInstr *MI = &*It;
1247 DebugLoc DL = MI->getDebugLoc();
1248 unsigned Opc = MI->getOpcode();
1249 unsigned SrcR = MI->getOperand(2).getReg();
1250 bool IsKill = MI->getOperand(2).isKill();
1251
1252 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1253 int FI = MI->getOperand(0).getIndex();
1254
1255 // TmpR = C2_tfrpr SrcR if SrcR is a predicate register
1256 // TmpR = A2_tfrcrr SrcR if SrcR is a modifier register
1257 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1258 unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1259 : Hexagon::A2_tfrcrr;
1260 BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1261 .addReg(SrcR, getKillRegState(IsKill));
1262
1263 // S2_storeri_io FI, 0, TmpR
1264 BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1265 .addFrameIndex(FI)
1266 .addImm(0)
1267 .addReg(TmpR, RegState::Kill)
1268 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1269
1270 NewRegs.push_back(TmpR);
1271 B.erase(It);
1272 return true;
1273}
1274
1275bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1276 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1277 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1278 MachineInstr *MI = &*It;
1279 DebugLoc DL = MI->getDebugLoc();
1280 unsigned Opc = MI->getOpcode();
1281 unsigned DstR = MI->getOperand(0).getReg();
1282
1283 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1284 int FI = MI->getOperand(1).getIndex();
1285
1286 // TmpR = L2_loadri_io FI, 0
1287 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1288 BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1289 .addFrameIndex(FI)
1290 .addImm(0)
1291 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1292
1293 // DstR = C2_tfrrp TmpR if DstR is a predicate register
1294 // DstR = A2_tfrrcr TmpR if DstR is a modifier register
1295 unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1296 : Hexagon::A2_tfrrcr;
1297 BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1298 .addReg(TmpR, RegState::Kill);
1299
1300 NewRegs.push_back(TmpR);
1301 B.erase(It);
1302 return true;
1303}
1304
1305
1306bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1307 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1308 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1309 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1310 MachineInstr *MI = &*It;
1311 DebugLoc DL = MI->getDebugLoc();
1312 unsigned SrcR = MI->getOperand(2).getReg();
1313 bool IsKill = MI->getOperand(2).isKill();
1314
1315 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1316 int FI = MI->getOperand(0).getIndex();
1317
1318 bool Is128B = HST.useHVXDblOps();
1319 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1320 : &Hexagon::VectorRegs128BRegClass;
1321
1322 // Insert transfer to general vector register.
1323 // TmpR0 = A2_tfrsi 0x01010101
1324 // TmpR1 = V6_vandqrt Qx, TmpR0
1325 // store FI, 0, TmpR1
1326 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1327 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1328
1329 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1330 .addImm(0x01010101);
1331
1332 unsigned VandOpc = !Is128B ? Hexagon::V6_vandqrt : Hexagon::V6_vandqrt_128B;
1333 BuildMI(B, It, DL, HII.get(VandOpc), TmpR1)
1334 .addReg(SrcR, getKillRegState(IsKill))
1335 .addReg(TmpR0, RegState::Kill);
1336
1337 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1338 HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1339 expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1340
1341 NewRegs.push_back(TmpR0);
1342 NewRegs.push_back(TmpR1);
1343 B.erase(It);
1344 return true;
1345}
1346
1347bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1348 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1349 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1350 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1351 MachineInstr *MI = &*It;
1352 DebugLoc DL = MI->getDebugLoc();
1353 unsigned DstR = MI->getOperand(0).getReg();
1354
1355 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1356 int FI = MI->getOperand(1).getIndex();
1357
1358 bool Is128B = HST.useHVXDblOps();
1359 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1360 : &Hexagon::VectorRegs128BRegClass;
1361
1362 // TmpR0 = A2_tfrsi 0x01010101
1363 // TmpR1 = load FI, 0
1364 // DstR = V6_vandvrt TmpR1, TmpR0
1365 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1366 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1367
1368 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1369 .addImm(0x01010101);
1370 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1371 HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1372 expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1373
1374 unsigned VandOpc = !Is128B ? Hexagon::V6_vandvrt : Hexagon::V6_vandvrt_128B;
1375 BuildMI(B, It, DL, HII.get(VandOpc), DstR)
1376 .addReg(TmpR1, RegState::Kill)
1377 .addReg(TmpR0, RegState::Kill);
1378
1379 NewRegs.push_back(TmpR0);
1380 NewRegs.push_back(TmpR1);
1381 B.erase(It);
1382 return true;
1383}
1384
1385bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1386 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1387 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1388 MachineFunction &MF = *B.getParent();
1389 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1390 auto &MFI = *MF.getFrameInfo();
1391 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1392 MachineInstr *MI = &*It;
1393 DebugLoc DL = MI->getDebugLoc();
1394
1395 unsigned SrcR = MI->getOperand(2).getReg();
1396 unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::subreg_loreg);
1397 unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::subreg_hireg);
1398 bool IsKill = MI->getOperand(2).isKill();
1399
1400 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1401 int FI = MI->getOperand(0).getIndex();
1402
1403 bool Is128B = HST.useHVXDblOps();
1404 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1405 : &Hexagon::VectorRegs128BRegClass;
1406 unsigned Size = RC->getSize();
1407 unsigned NeedAlign = RC->getAlignment();
1408 unsigned HasAlign = MFI.getObjectAlignment(FI);
1409 unsigned StoreOpc;
1410
1411 // Store low part.
1412 if (NeedAlign <= HasAlign)
1413 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1414 else
1415 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1416
1417 BuildMI(B, It, DL, HII.get(StoreOpc))
1418 .addFrameIndex(FI)
1419 .addImm(0)
1420 .addReg(SrcLo, getKillRegState(IsKill))
1421 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1422
1423 // Load high part.
1424 if (NeedAlign <= MinAlign(HasAlign, Size))
1425 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1426 else
1427 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1428
1429 BuildMI(B, It, DL, HII.get(StoreOpc))
1430 .addFrameIndex(FI)
1431 .addImm(Size)
1432 .addReg(SrcHi, getKillRegState(IsKill))
1433 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1434
1435 B.erase(It);
1436 return true;
1437}
1438
1439bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1440 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1441 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1442 MachineFunction &MF = *B.getParent();
1443 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1444 auto &MFI = *MF.getFrameInfo();
1445 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1446 MachineInstr *MI = &*It;
1447 DebugLoc DL = MI->getDebugLoc();
1448
1449 unsigned DstR = MI->getOperand(0).getReg();
1450 unsigned DstHi = HRI.getSubReg(DstR, Hexagon::subreg_hireg);
1451 unsigned DstLo = HRI.getSubReg(DstR, Hexagon::subreg_loreg);
1452
1453 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1454 int FI = MI->getOperand(1).getIndex();
1455
1456 bool Is128B = HST.useHVXDblOps();
1457 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1458 : &Hexagon::VectorRegs128BRegClass;
1459 unsigned Size = RC->getSize();
1460 unsigned NeedAlign = RC->getAlignment();
1461 unsigned HasAlign = MFI.getObjectAlignment(FI);
1462 unsigned LoadOpc;
1463
1464 // Load low part.
1465 if (NeedAlign <= HasAlign)
1466 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1467 else
1468 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1469
1470 BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1471 .addFrameIndex(FI)
1472 .addImm(0)
1473 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1474
1475 // Load high part.
1476 if (NeedAlign <= MinAlign(HasAlign, Size))
1477 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1478 else
1479 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1480
1481 BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1482 .addFrameIndex(FI)
1483 .addImm(Size)
1484 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1485
1486 B.erase(It);
1487 return true;
1488}
1489
1490bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1491 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1492 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1493 MachineFunction &MF = *B.getParent();
1494 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1495 auto &MFI = *MF.getFrameInfo();
1496 MachineInstr *MI = &*It;
1497 DebugLoc DL = MI->getDebugLoc();
1498
1499 unsigned SrcR = MI->getOperand(2).getReg();
1500 bool IsKill = MI->getOperand(2).isKill();
1501
1502 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1503 int FI = MI->getOperand(0).getIndex();
1504
1505 bool Is128B = HST.useHVXDblOps();
1506 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1507 : &Hexagon::VectorRegs128BRegClass;
1508
1509 unsigned NeedAlign = RC->getAlignment();
1510 unsigned HasAlign = MFI.getObjectAlignment(FI);
1511 unsigned StoreOpc;
1512
1513 if (NeedAlign <= HasAlign)
1514 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1515 else
1516 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1517
1518 BuildMI(B, It, DL, HII.get(StoreOpc))
1519 .addFrameIndex(FI)
1520 .addImm(0)
1521 .addReg(SrcR, getKillRegState(IsKill))
1522 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1523
1524 B.erase(It);
1525 return true;
1526}
1527
1528bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
1529 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1530 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1531 MachineFunction &MF = *B.getParent();
1532 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1533 auto &MFI = *MF.getFrameInfo();
1534 MachineInstr *MI = &*It;
1535 DebugLoc DL = MI->getDebugLoc();
1536
1537 unsigned DstR = MI->getOperand(0).getReg();
1538
1539 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1540 int FI = MI->getOperand(1).getIndex();
1541
1542 bool Is128B = HST.useHVXDblOps();
1543 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1544 : &Hexagon::VectorRegs128BRegClass;
1545
1546 unsigned NeedAlign = RC->getAlignment();
1547 unsigned HasAlign = MFI.getObjectAlignment(FI);
1548 unsigned LoadOpc;
1549
1550 if (NeedAlign <= HasAlign)
1551 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1552 else
1553 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1554
1555 BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1556 .addFrameIndex(FI)
1557 .addImm(0)
1558 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1559
1560 B.erase(It);
1561 return true;
1562}
1563
1564
1565bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1566 SmallVectorImpl<unsigned> &NewRegs) const {
1567 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001568 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001569 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001570 bool Changed = false;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001571
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001572 for (auto &B : MF) {
1573 // Traverse the basic block.
1574 MachineBasicBlock::iterator NextI;
1575 for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1576 MachineInstr *MI = &*I;
1577 NextI = std::next(I);
1578 unsigned Opc = MI->getOpcode();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001579
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001580 switch (Opc) {
1581 case TargetOpcode::COPY:
1582 Changed = expandCopy(B, I, MRI, HII, NewRegs);
1583 break;
1584 case Hexagon::STriw_pred:
1585 case Hexagon::STriw_mod:
1586 Changed = expandStoreInt(B, I, MRI, HII, NewRegs);
1587 break;
1588 case Hexagon::LDriw_pred:
1589 case Hexagon::LDriw_mod:
1590 Changed = expandLoadInt(B, I, MRI, HII, NewRegs);
1591 break;
1592 case Hexagon::STriq_pred_V6:
1593 case Hexagon::STriq_pred_V6_128B:
1594 Changed = expandStoreVecPred(B, I, MRI, HII, NewRegs);
1595 break;
1596 case Hexagon::LDriq_pred_V6:
1597 case Hexagon::LDriq_pred_V6_128B:
1598 Changed = expandLoadVecPred(B, I, MRI, HII, NewRegs);
1599 break;
1600 case Hexagon::LDrivv_pseudo_V6:
1601 case Hexagon::LDrivv_pseudo_V6_128B:
1602 Changed = expandLoadVec2(B, I, MRI, HII, NewRegs);
1603 break;
1604 case Hexagon::STrivv_pseudo_V6:
1605 case Hexagon::STrivv_pseudo_V6_128B:
1606 Changed = expandStoreVec2(B, I, MRI, HII, NewRegs);
1607 break;
1608 case Hexagon::STriv_pseudo_V6:
1609 case Hexagon::STriv_pseudo_V6_128B:
1610 Changed = expandStoreVec(B, I, MRI, HII, NewRegs);
1611 break;
1612 case Hexagon::LDriv_pseudo_V6:
1613 case Hexagon::LDriv_pseudo_V6_128B:
1614 Changed = expandLoadVec(B, I, MRI, HII, NewRegs);
1615 break;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001616 }
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001617 }
1618 }
1619
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001620 return Changed;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001621}
1622
1623
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001624void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1625 BitVector &SavedRegs,
1626 RegScavenger *RS) const {
1627 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1628 auto &HRI = *HST.getRegisterInfo();
1629
1630 SavedRegs.resize(HRI.getNumRegs());
1631
1632 // If we have a function containing __builtin_eh_return we want to spill and
1633 // restore all callee saved registers. Pretend that they are used.
1634 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1635 for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1636 SavedRegs.set(*R);
1637
1638 // Replace predicate register pseudo spill code.
1639 SmallVector<unsigned,8> NewRegs;
1640 expandSpillMacros(MF, NewRegs);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001641 if (OptimizeSpillSlots)
1642 optimizeSpillSlots(MF, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001643
1644 // We need to reserve a a spill slot if scavenging could potentially require
1645 // spilling a scavenged register.
1646 if (!NewRegs.empty() && needToReserveScavengingSpillSlots(MF, HRI)) {
1647 MachineRegisterInfo &MRI = MF.getRegInfo();
1648 SetVector<const TargetRegisterClass*> SpillRCs;
1649 for (unsigned VR : NewRegs)
1650 SpillRCs.insert(MRI.getRegClass(VR));
1651
1652 MachineFrameInfo &MFI = *MF.getFrameInfo();
1653 const TargetRegisterClass &IntRC = Hexagon::IntRegsRegClass;
1654 if (SpillRCs.count(&IntRC)) {
1655 for (int i = 0; i < NumberScavengerSlots; i++) {
1656 int NewFI = MFI.CreateSpillStackObject(IntRC.getSize(),
1657 IntRC.getAlignment());
1658 RS->addScavengingFrameIndex(NewFI);
1659 }
1660 }
1661 for (auto *RC : SpillRCs) {
1662 if (RC == &IntRC)
1663 continue;
1664 int NewFI = MFI.CreateSpillStackObject(RC->getSize(), RC->getAlignment());
1665 RS->addScavengingFrameIndex(NewFI);
1666 }
1667 }
1668
1669 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1670}
1671
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001672
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001673unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1674 HexagonBlockRanges::IndexRange &FIR,
1675 HexagonBlockRanges::InstrIndexMap &IndexMap,
1676 HexagonBlockRanges::RegToRangeMap &DeadMap,
1677 const TargetRegisterClass *RC) const {
1678 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1679 auto &MRI = MF.getRegInfo();
1680
1681 auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1682 auto F = DeadMap.find({Reg,0});
1683 if (F == DeadMap.end())
1684 return false;
1685 for (auto &DR : F->second)
1686 if (DR.contains(FIR))
1687 return true;
1688 return false;
1689 };
1690
1691 for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
1692 bool Dead = true;
1693 for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
1694 if (isDead(R.Reg))
1695 continue;
1696 Dead = false;
1697 break;
1698 }
1699 if (Dead)
1700 return Reg;
1701 }
1702 return 0;
1703}
1704
1705void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
1706 SmallVectorImpl<unsigned> &VRegs) const {
1707 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1708 auto &HII = *HST.getInstrInfo();
1709 auto &HRI = *HST.getRegisterInfo();
1710 auto &MRI = MF.getRegInfo();
1711 HexagonBlockRanges HBR(MF);
1712
1713 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::InstrIndexMap>
1714 BlockIndexMap;
1715 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::RangeList>
1716 BlockRangeMap;
1717 typedef HexagonBlockRanges::IndexType IndexType;
1718
1719 struct SlotInfo {
1720 BlockRangeMap Map;
NAKAMURA Takumic2cc8702016-02-13 07:29:49 +00001721 unsigned Size;
1722 const TargetRegisterClass *RC;
1723
1724 SlotInfo() : Map(), Size(0), RC(nullptr) {}
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001725 };
1726
1727 BlockIndexMap BlockIndexes;
1728 SmallSet<int,4> BadFIs;
1729 std::map<int,SlotInfo> FIRangeMap;
1730
1731 auto getRegClass = [&MRI,&HRI] (HexagonBlockRanges::RegisterRef R)
1732 -> const TargetRegisterClass* {
1733 if (TargetRegisterInfo::isPhysicalRegister(R.Reg))
1734 assert(R.Sub == 0);
1735 if (TargetRegisterInfo::isVirtualRegister(R.Reg)) {
1736 auto *RCR = MRI.getRegClass(R.Reg);
1737 if (R.Sub == 0)
1738 return RCR;
1739 unsigned PR = *RCR->begin();
1740 R.Reg = HRI.getSubReg(PR, R.Sub);
1741 }
1742 return HRI.getMinimalPhysRegClass(R.Reg);
1743 };
1744 // Accumulate register classes: get a common class for a pre-existing
1745 // class HaveRC and a new class NewRC. Return nullptr if a common class
1746 // cannot be found, otherwise return the resulting class. If HaveRC is
1747 // nullptr, assume that it is still unset.
1748 auto getCommonRC = [&HRI] (const TargetRegisterClass *HaveRC,
1749 const TargetRegisterClass *NewRC)
1750 -> const TargetRegisterClass* {
1751 if (HaveRC == nullptr || HaveRC == NewRC)
1752 return NewRC;
1753 // Different classes, both non-null. Pick the more general one.
1754 if (HaveRC->hasSubClassEq(NewRC))
1755 return HaveRC;
1756 if (NewRC->hasSubClassEq(HaveRC))
1757 return NewRC;
1758 return nullptr;
1759 };
1760
1761 // Scan all blocks in the function. Check all occurrences of frame indexes,
1762 // and collect relevant information.
1763 for (auto &B : MF) {
1764 std::map<int,IndexType> LastStore, LastLoad;
Krzysztof Parzyszek280a50e2016-02-13 14:06:01 +00001765 // Emplace appears not to be supported in gcc 4.7.2-4.
1766 //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
Krzysztof Parzyszekde697d42016-02-17 15:02:07 +00001767 auto P = BlockIndexes.insert(
1768 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001769 auto &IndexMap = P.first->second;
1770 DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n"
1771 << IndexMap << '\n');
1772
1773 for (auto &In : B) {
1774 int LFI, SFI;
1775 bool Load = HII.isLoadFromStackSlot(&In, LFI) && !HII.isPredicated(&In);
1776 bool Store = HII.isStoreToStackSlot(&In, SFI) && !HII.isPredicated(&In);
1777 if (Load && Store) {
1778 // If it's both a load and a store, then we won't handle it.
1779 BadFIs.insert(LFI);
1780 BadFIs.insert(SFI);
1781 continue;
1782 }
1783 // Check for register classes of the register used as the source for
1784 // the store, and the register used as the destination for the load.
1785 // Also, only accept base+imm_offset addressing modes. Other addressing
1786 // modes can have side-effects (post-increments, etc.). For stack
1787 // slots they are very unlikely, so there is not much loss due to
1788 // this restriction.
1789 if (Load || Store) {
1790 int TFI = Load ? LFI : SFI;
1791 unsigned AM = HII.getAddrMode(&In);
1792 SlotInfo &SI = FIRangeMap[TFI];
1793 bool Bad = (AM != HexagonII::BaseImmOffset);
1794 if (!Bad) {
1795 // If the addressing mode is ok, check the register class.
1796 const TargetRegisterClass *RC = nullptr;
1797 if (Load) {
1798 MachineOperand &DataOp = In.getOperand(0);
1799 RC = getRegClass({DataOp.getReg(), DataOp.getSubReg()});
1800 } else {
1801 MachineOperand &DataOp = In.getOperand(2);
1802 RC = getRegClass({DataOp.getReg(), DataOp.getSubReg()});
1803 }
1804 RC = getCommonRC(SI.RC, RC);
1805 if (RC == nullptr)
1806 Bad = true;
1807 else
1808 SI.RC = RC;
1809 }
1810 if (!Bad) {
1811 // Check sizes.
1812 unsigned S = (1U << (HII.getMemAccessSize(&In) - 1));
1813 if (SI.Size != 0 && SI.Size != S)
1814 Bad = true;
1815 else
1816 SI.Size = S;
1817 }
1818 if (Bad)
1819 BadFIs.insert(TFI);
1820 }
1821
1822 // Locate uses of frame indices.
1823 for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
1824 const MachineOperand &Op = In.getOperand(i);
1825 if (!Op.isFI())
1826 continue;
1827 int FI = Op.getIndex();
1828 // Make sure that the following operand is an immediate and that
1829 // it is 0. This is the offset in the stack object.
1830 if (i+1 >= n || !In.getOperand(i+1).isImm() ||
1831 In.getOperand(i+1).getImm() != 0)
1832 BadFIs.insert(FI);
1833 if (BadFIs.count(FI))
1834 continue;
1835
1836 IndexType Index = IndexMap.getIndex(&In);
1837 if (Load) {
1838 if (LastStore[FI] == IndexType::None)
1839 LastStore[FI] = IndexType::Entry;
1840 LastLoad[FI] = Index;
1841 } else if (Store) {
1842 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
1843 if (LastStore[FI] != IndexType::None)
1844 RL.add(LastStore[FI], LastLoad[FI], false, false);
1845 else if (LastLoad[FI] != IndexType::None)
1846 RL.add(IndexType::Entry, LastLoad[FI], false, false);
1847 LastLoad[FI] = IndexType::None;
1848 LastStore[FI] = Index;
1849 } else {
1850 BadFIs.insert(FI);
1851 }
1852 }
1853 }
1854
1855 for (auto &I : LastLoad) {
1856 IndexType LL = I.second;
1857 if (LL == IndexType::None)
1858 continue;
1859 auto &RL = FIRangeMap[I.first].Map[&B];
1860 IndexType &LS = LastStore[I.first];
1861 if (LS != IndexType::None)
1862 RL.add(LS, LL, false, false);
1863 else
1864 RL.add(IndexType::Entry, LL, false, false);
1865 LS = IndexType::None;
1866 }
1867 for (auto &I : LastStore) {
1868 IndexType LS = I.second;
1869 if (LS == IndexType::None)
1870 continue;
1871 auto &RL = FIRangeMap[I.first].Map[&B];
1872 RL.add(LS, IndexType::None, false, false);
1873 }
1874 }
1875
1876 DEBUG({
1877 for (auto &P : FIRangeMap) {
1878 dbgs() << "fi#" << P.first;
1879 if (BadFIs.count(P.first))
1880 dbgs() << " (bad)";
1881 dbgs() << " RC: ";
1882 if (P.second.RC != nullptr)
1883 dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
1884 else
1885 dbgs() << "<null>\n";
1886 for (auto &R : P.second.Map)
1887 dbgs() << " BB#" << R.first->getNumber() << " { " << R.second << "}\n";
1888 }
1889 });
1890
1891 // When a slot is loaded from in a block without being stored to in the
1892 // same block, it is live-on-entry to this block. To avoid CFG analysis,
1893 // consider this slot to be live-on-exit from all blocks.
1894 SmallSet<int,4> LoxFIs;
1895
1896 std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
1897
1898 for (auto &P : FIRangeMap) {
1899 // P = pair(FI, map: BB->RangeList)
1900 if (BadFIs.count(P.first))
1901 continue;
1902 for (auto &B : MF) {
1903 auto F = P.second.Map.find(&B);
1904 // F = pair(BB, RangeList)
1905 if (F == P.second.Map.end() || F->second.empty())
1906 continue;
1907 HexagonBlockRanges::IndexRange &IR = F->second.front();
1908 if (IR.start() == IndexType::Entry)
1909 LoxFIs.insert(P.first);
1910 BlockFIMap[&B].push_back(P.first);
1911 }
1912 }
1913
1914 DEBUG({
1915 dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
1916 for (auto &P : BlockFIMap) {
1917 auto &FIs = P.second;
1918 if (FIs.empty())
1919 continue;
1920 dbgs() << " BB#" << P.first->getNumber() << ": {";
1921 for (auto I : FIs) {
1922 dbgs() << " fi#" << I;
1923 if (LoxFIs.count(I))
1924 dbgs() << '*';
1925 }
1926 dbgs() << " }\n";
1927 }
1928 });
1929
1930 // eliminate loads, when all loads eliminated, eliminate all stores.
1931 for (auto &B : MF) {
1932 auto F = BlockIndexes.find(&B);
1933 assert(F != BlockIndexes.end());
1934 HexagonBlockRanges::InstrIndexMap &IM = F->second;
1935 HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
1936 HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
1937 DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n"
1938 << HexagonBlockRanges::PrintRangeMap(DM, HRI));
1939
1940 for (auto FI : BlockFIMap[&B]) {
1941 if (BadFIs.count(FI))
1942 continue;
1943 DEBUG(dbgs() << "Working on fi#" << FI << '\n');
1944 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
1945 for (auto &Range : RL) {
1946 DEBUG(dbgs() << "--Examining range:" << RL << '\n');
1947 if (!IndexType::isInstr(Range.start()) ||
1948 !IndexType::isInstr(Range.end()))
1949 continue;
1950 MachineInstr *SI = IM.getInstr(Range.start());
1951 MachineInstr *EI = IM.getInstr(Range.end());
1952 assert(SI->mayStore() && "Unexpected start instruction");
1953 assert(EI->mayLoad() && "Unexpected end instruction");
1954 MachineOperand &SrcOp = SI->getOperand(2);
1955
1956 HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
1957 SrcOp.getSubReg() };
1958 auto *RC = getRegClass({SrcOp.getReg(), SrcOp.getSubReg()});
1959 // The this-> is needed to unconfuse MSVC.
1960 unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
1961 DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n');
1962 if (FoundR == 0)
1963 continue;
1964
1965 // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
1966 MachineBasicBlock::iterator StartIt = SI, NextIt;
1967 MachineInstr *CopyIn = nullptr;
1968 if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
1969 DebugLoc DL = SI->getDebugLoc();
1970 CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
1971 .addOperand(SrcOp);
1972 }
1973
1974 ++StartIt;
1975 // Check if this is a last store and the FI is live-on-exit.
1976 if (LoxFIs.count(FI) && (&Range == &RL.back())) {
1977 // Update store's source register.
1978 if (unsigned SR = SrcOp.getSubReg())
1979 SrcOp.setReg(HRI.getSubReg(FoundR, SR));
1980 else
1981 SrcOp.setReg(FoundR);
1982 SrcOp.setSubReg(0);
1983 // We are keeping this register live.
1984 SrcOp.setIsKill(false);
1985 } else {
1986 B.erase(SI);
1987 IM.replaceInstr(SI, CopyIn);
1988 }
1989
1990 auto EndIt = std::next(MachineBasicBlock::iterator(EI));
1991 for (auto It = StartIt; It != EndIt; It = NextIt) {
1992 MachineInstr *MI = &*It;
1993 NextIt = std::next(It);
1994 int TFI;
1995 if (!HII.isLoadFromStackSlot(MI, TFI) || TFI != FI)
1996 continue;
1997 unsigned DstR = MI->getOperand(0).getReg();
1998 assert(MI->getOperand(0).getSubReg() == 0);
1999 MachineInstr *CopyOut = nullptr;
2000 if (DstR != FoundR) {
2001 DebugLoc DL = MI->getDebugLoc();
2002 unsigned MemSize = (1U << (HII.getMemAccessSize(MI) - 1));
2003 assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2004 unsigned CopyOpc = TargetOpcode::COPY;
2005 if (HII.isSignExtendingLoad(MI))
2006 CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
2007 else if (HII.isZeroExtendingLoad(MI))
2008 CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2009 CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
2010 .addReg(FoundR, getKillRegState(MI == EI));
2011 }
2012 IM.replaceInstr(MI, CopyOut);
2013 B.erase(It);
2014 }
2015
2016 // Update the dead map.
2017 HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2018 for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2019 DM[RR].subtract(Range);
2020 } // for Range in range list
2021 }
2022 }
2023}
2024
2025
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002026void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002027 const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002028 MachineBasicBlock &MB = *AI->getParent();
2029 DebugLoc DL = AI->getDebugLoc();
2030 unsigned A = AI->getOperand(2).getImm();
2031
2032 // Have
2033 // Rd = alloca Rs, #A
2034 //
2035 // If Rs and Rd are different registers, use this sequence:
2036 // Rd = sub(r29, Rs)
2037 // r29 = sub(r29, Rs)
2038 // Rd = and(Rd, #-A) ; if necessary
2039 // r29 = and(r29, #-A) ; if necessary
2040 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2041 // otherwise, do
2042 // Rd = sub(r29, Rs)
2043 // Rd = and(Rd, #-A) ; if necessary
2044 // r29 = Rd
2045 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2046
2047 MachineOperand &RdOp = AI->getOperand(0);
2048 MachineOperand &RsOp = AI->getOperand(1);
2049 unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2050
2051 // Rd = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002052 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002053 .addReg(SP)
2054 .addReg(Rs);
2055 if (Rs != Rd) {
2056 // r29 = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002057 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002058 .addReg(SP)
2059 .addReg(Rs);
2060 }
2061 if (A > 8) {
2062 // Rd = and(Rd, #-A)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002063 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002064 .addReg(Rd)
2065 .addImm(-int64_t(A));
2066 if (Rs != Rd)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002067 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002068 .addReg(SP)
2069 .addImm(-int64_t(A));
2070 }
2071 if (Rs == Rd) {
2072 // r29 = Rd
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002073 BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002074 .addReg(Rd);
2075 }
2076 if (CF > 0) {
2077 // Rd = add(Rd, #CF)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002078 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002079 .addReg(Rd)
2080 .addImm(CF);
2081 }
2082}
2083
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002084
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002085bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
2086 const MachineFrameInfo *MFI = MF.getFrameInfo();
2087 if (!MFI->hasVarSizedObjects())
2088 return false;
2089 unsigned MaxA = MFI->getMaxAlignment();
2090 if (MaxA <= getStackAlignment())
2091 return false;
2092 return true;
2093}
2094
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002095
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00002096const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2097 const MachineFunction &MF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002098 for (auto &B : MF)
2099 for (auto &I : B)
2100 if (I.getOpcode() == Hexagon::ALIGNA)
2101 return &I;
2102 return nullptr;
2103}
2104
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002105
Sanjay Patel924879a2015-08-04 15:49:57 +00002106// FIXME: Use Function::optForSize().
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002107inline static bool isOptSize(const MachineFunction &MF) {
2108 AttributeSet AF = MF.getFunction()->getAttributes();
2109 return AF.hasAttribute(AttributeSet::FunctionIndex,
2110 Attribute::OptimizeForSize);
2111}
2112
2113inline static bool isMinSize(const MachineFunction &MF) {
Sanjay Patel924879a2015-08-04 15:49:57 +00002114 return MF.getFunction()->optForMinSize();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002115}
2116
2117
2118/// Determine whether the callee-saved register saves and restores should
2119/// be generated via inline code. If this function returns "true", inline
2120/// code will be generated. If this function returns "false", additional
2121/// checks are performed, which may still lead to the inline code.
2122bool HexagonFrameLowering::shouldInlineCSR(MachineFunction &MF,
2123 const CSIVect &CSI) const {
2124 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2125 return true;
2126 if (!isOptSize(MF) && !isMinSize(MF))
2127 if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2128 return true;
2129
2130 // Check if CSI only has double registers, and if the registers form
2131 // a contiguous block starting from D8.
2132 BitVector Regs(Hexagon::NUM_TARGET_REGS);
2133 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2134 unsigned R = CSI[i].getReg();
2135 if (!Hexagon::DoubleRegsRegClass.contains(R))
2136 return true;
2137 Regs[R] = true;
2138 }
2139 int F = Regs.find_first();
2140 if (F != Hexagon::D8)
2141 return true;
2142 while (F >= 0) {
2143 int N = Regs.find_next(F);
2144 if (N >= 0 && N != F+1)
2145 return true;
2146 F = N;
2147 }
2148
2149 return false;
2150}
2151
2152
2153bool HexagonFrameLowering::useSpillFunction(MachineFunction &MF,
2154 const CSIVect &CSI) const {
2155 if (shouldInlineCSR(MF, CSI))
2156 return false;
2157 unsigned NumCSI = CSI.size();
2158 if (NumCSI <= 1)
2159 return false;
2160
2161 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2162 : SpillFuncThreshold;
2163 return Threshold < NumCSI;
2164}
2165
2166
2167bool HexagonFrameLowering::useRestoreFunction(MachineFunction &MF,
2168 const CSIVect &CSI) const {
2169 if (shouldInlineCSR(MF, CSI))
2170 return false;
2171 unsigned NumCSI = CSI.size();
2172 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2173 : SpillFuncThreshold;
2174 return Threshold < NumCSI;
2175}