blob: acc92405aedf2b8e8267ab47e43720eba68ecc99 [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 Parzyszekc9d4caa2016-03-24 20:20:07 +0000140static cl::opt<bool> EnableStackOVFSanitizer("enable-stackovf-sanitizer",
141 cl::Hidden, cl::desc("Enable runtime checks for stack overflow."),
142 cl::init(false), cl::ZeroOrMore);
143
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000144static cl::opt<bool> EnableShrinkWrapping("hexagon-shrink-frame",
145 cl::init(true), cl::Hidden, cl::ZeroOrMore,
146 cl::desc("Enable stack frame shrink wrapping"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000147
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000148static cl::opt<unsigned> ShrinkLimit("shrink-frame-limit", cl::init(UINT_MAX),
149 cl::Hidden, cl::ZeroOrMore, cl::desc("Max count of stack frame "
150 "shrink-wraps"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000151
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000152static cl::opt<bool> UseAllocframe("use-allocframe", cl::init(true),
153 cl::Hidden, cl::desc("Use allocframe more conservatively"));
154
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +0000155static cl::opt<bool> OptimizeSpillSlots("hexagon-opt-spill", cl::Hidden,
156 cl::init(true), cl::desc("Optimize spill slots"));
157
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000158
159namespace llvm {
160 void initializeHexagonCallFrameInformationPass(PassRegistry&);
161 FunctionPass *createHexagonCallFrameInformation();
162}
163
164namespace {
165 class HexagonCallFrameInformation : public MachineFunctionPass {
166 public:
167 static char ID;
168 HexagonCallFrameInformation() : MachineFunctionPass(ID) {
169 PassRegistry &PR = *PassRegistry::getPassRegistry();
170 initializeHexagonCallFrameInformationPass(PR);
171 }
172 bool runOnMachineFunction(MachineFunction &MF) override;
173 };
174
175 char HexagonCallFrameInformation::ID = 0;
176}
177
178bool HexagonCallFrameInformation::runOnMachineFunction(MachineFunction &MF) {
179 auto &HFI = *MF.getSubtarget<HexagonSubtarget>().getFrameLowering();
180 bool NeedCFI = MF.getMMI().hasDebugInfo() ||
181 MF.getFunction()->needsUnwindTableEntry();
182
183 if (!NeedCFI)
184 return false;
185 HFI.insertCFIInstructions(MF);
186 return true;
187}
188
189INITIALIZE_PASS(HexagonCallFrameInformation, "hexagon-cfi",
190 "Hexagon call frame information", false, false)
191
192FunctionPass *llvm::createHexagonCallFrameInformation() {
193 return new HexagonCallFrameInformation();
194}
195
196
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000197namespace {
198 /// Map a register pair Reg to the subregister that has the greater "number",
199 /// i.e. D3 (aka R7:6) will be mapped to R7, etc.
200 unsigned getMax32BitSubRegister(unsigned Reg, const TargetRegisterInfo &TRI,
201 bool hireg = true) {
202 if (Reg < Hexagon::D0 || Reg > Hexagon::D15)
203 return Reg;
204
205 unsigned RegNo = 0;
206 for (MCSubRegIterator SubRegs(Reg, &TRI); SubRegs.isValid(); ++SubRegs) {
207 if (hireg) {
208 if (*SubRegs > RegNo)
209 RegNo = *SubRegs;
210 } else {
211 if (!RegNo || *SubRegs < RegNo)
212 RegNo = *SubRegs;
213 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000214 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000215 return RegNo;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000216 }
217
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000218 /// Returns the callee saved register with the largest id in the vector.
219 unsigned getMaxCalleeSavedReg(const std::vector<CalleeSavedInfo> &CSI,
220 const TargetRegisterInfo &TRI) {
221 assert(Hexagon::R1 > 0 &&
222 "Assume physical registers are encoded as positive integers");
223 if (CSI.empty())
224 return 0;
225
226 unsigned Max = getMax32BitSubRegister(CSI[0].getReg(), TRI);
227 for (unsigned I = 1, E = CSI.size(); I < E; ++I) {
228 unsigned Reg = getMax32BitSubRegister(CSI[I].getReg(), TRI);
229 if (Reg > Max)
230 Max = Reg;
231 }
232 return Max;
233 }
234
235 /// Checks if the basic block contains any instruction that needs a stack
236 /// frame to be already in place.
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000237 bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR,
238 const HexagonRegisterInfo &HRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000239 for (auto &I : MBB) {
240 const MachineInstr *MI = &I;
241 if (MI->isCall())
242 return true;
243 unsigned Opc = MI->getOpcode();
244 switch (Opc) {
245 case Hexagon::ALLOCA:
246 case Hexagon::ALIGNA:
247 return true;
248 default:
249 break;
250 }
251 // Check individual operands.
Matthias Braune41e1462015-05-29 02:56:46 +0000252 for (const MachineOperand &MO : MI->operands()) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000253 // While the presence of a frame index does not prove that a stack
254 // frame will be required, all frame indexes should be within alloc-
255 // frame/deallocframe. Otherwise, the code that translates a frame
256 // index into an offset would have to be aware of the placement of
257 // the frame creation/destruction instructions.
Matthias Braune41e1462015-05-29 02:56:46 +0000258 if (MO.isFI())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000259 return true;
Matthias Braune41e1462015-05-29 02:56:46 +0000260 if (!MO.isReg())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000261 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000262 unsigned R = MO.getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000263 // Virtual registers will need scavenging, which then may require
264 // a stack slot.
265 if (TargetRegisterInfo::isVirtualRegister(R))
266 return true;
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000267 for (MCSubRegIterator S(R, &HRI, true); S.isValid(); ++S)
268 if (CSR[*S])
269 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000270 }
271 }
272 return false;
273 }
274
275 /// Returns true if MBB has a machine instructions that indicates a tail call
276 /// in the block.
277 bool hasTailCall(const MachineBasicBlock &MBB) {
278 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
279 unsigned RetOpc = I->getOpcode();
280 return RetOpc == Hexagon::TCRETURNi || RetOpc == Hexagon::TCRETURNr;
281 }
282
283 /// Returns true if MBB contains an instruction that returns.
284 bool hasReturn(const MachineBasicBlock &MBB) {
285 for (auto I = MBB.getFirstTerminator(), E = MBB.end(); I != E; ++I)
286 if (I->isReturn())
287 return true;
288 return false;
289 }
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000290}
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000291
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000292
293/// Implements shrink-wrapping of the stack frame. By default, stack frame
294/// is created in the function entry block, and is cleaned up in every block
295/// that returns. This function finds alternate blocks: one for the frame
296/// setup (prolog) and one for the cleanup (epilog).
297void HexagonFrameLowering::findShrunkPrologEpilog(MachineFunction &MF,
298 MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const {
299 static unsigned ShrinkCounter = 0;
300
301 if (ShrinkLimit.getPosition()) {
302 if (ShrinkCounter >= ShrinkLimit)
303 return;
304 ShrinkCounter++;
305 }
306
307 auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
308 auto &HRI = *HST.getRegisterInfo();
309
310 MachineDominatorTree MDT;
311 MDT.runOnMachineFunction(MF);
312 MachinePostDominatorTree MPT;
313 MPT.runOnMachineFunction(MF);
314
315 typedef DenseMap<unsigned,unsigned> UnsignedMap;
316 UnsignedMap RPO;
317 typedef ReversePostOrderTraversal<const MachineFunction*> RPOTType;
318 RPOTType RPOT(&MF);
319 unsigned RPON = 0;
320 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I)
321 RPO[(*I)->getNumber()] = RPON++;
322
323 // Don't process functions that have loops, at least for now. Placement
324 // of prolog and epilog must take loop structure into account. For simpli-
325 // city don't do it right now.
326 for (auto &I : MF) {
327 unsigned BN = RPO[I.getNumber()];
328 for (auto SI = I.succ_begin(), SE = I.succ_end(); SI != SE; ++SI) {
329 // If found a back-edge, return.
330 if (RPO[(*SI)->getNumber()] <= BN)
331 return;
332 }
333 }
334
335 // Collect the set of blocks that need a stack frame to execute. Scan
336 // each block for uses/defs of callee-saved registers, calls, etc.
337 SmallVector<MachineBasicBlock*,16> SFBlocks;
338 BitVector CSR(Hexagon::NUM_TARGET_REGS);
339 for (const MCPhysReg *P = HRI.getCalleeSavedRegs(&MF); *P; ++P)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000340 for (MCSubRegIterator S(*P, &HRI, true); S.isValid(); ++S)
341 CSR[*S] = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000342
343 for (auto &I : MF)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000344 if (needsStackFrame(I, CSR, HRI))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000345 SFBlocks.push_back(&I);
346
347 DEBUG({
348 dbgs() << "Blocks needing SF: {";
349 for (auto &B : SFBlocks)
350 dbgs() << " BB#" << B->getNumber();
351 dbgs() << " }\n";
352 });
353 // No frame needed?
354 if (SFBlocks.empty())
355 return;
356
357 // Pick a common dominator and a common post-dominator.
358 MachineBasicBlock *DomB = SFBlocks[0];
359 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
360 DomB = MDT.findNearestCommonDominator(DomB, SFBlocks[i]);
361 if (!DomB)
362 break;
363 }
364 MachineBasicBlock *PDomB = SFBlocks[0];
365 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
366 PDomB = MPT.findNearestCommonDominator(PDomB, SFBlocks[i]);
367 if (!PDomB)
368 break;
369 }
370 DEBUG({
371 dbgs() << "Computed dom block: BB#";
372 if (DomB) dbgs() << DomB->getNumber();
373 else dbgs() << "<null>";
374 dbgs() << ", computed pdom block: BB#";
375 if (PDomB) dbgs() << PDomB->getNumber();
376 else dbgs() << "<null>";
377 dbgs() << "\n";
378 });
379 if (!DomB || !PDomB)
380 return;
381
382 // Make sure that DomB dominates PDomB and PDomB post-dominates DomB.
383 if (!MDT.dominates(DomB, PDomB)) {
384 DEBUG(dbgs() << "Dom block does not dominate pdom block\n");
385 return;
386 }
387 if (!MPT.dominates(PDomB, DomB)) {
388 DEBUG(dbgs() << "PDom block does not post-dominate dom block\n");
389 return;
390 }
391
392 // Finally, everything seems right.
393 PrologB = DomB;
394 EpilogB = PDomB;
395}
396
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000397
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000398/// Perform most of the PEI work here:
399/// - saving/restoring of the callee-saved registers,
400/// - stack frame creation and destruction.
401/// Normally, this work is distributed among various functions, but doing it
402/// in one place allows shrink-wrapping of the stack frame.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000403void HexagonFrameLowering::emitPrologue(MachineFunction &MF,
404 MachineBasicBlock &MBB) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000405 auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
406 auto &HRI = *HST.getRegisterInfo();
407
408 MachineFrameInfo *MFI = MF.getFrameInfo();
409 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
410
411 MachineBasicBlock *PrologB = &MF.front(), *EpilogB = nullptr;
412 if (EnableShrinkWrapping)
413 findShrunkPrologEpilog(MF, PrologB, EpilogB);
414
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000415 bool PrologueStubs = false;
416 insertCSRSpillsInBlock(*PrologB, CSI, HRI, PrologueStubs);
417 insertPrologueInBlock(*PrologB, PrologueStubs);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000418
419 if (EpilogB) {
420 insertCSRRestoresInBlock(*EpilogB, CSI, HRI);
421 insertEpilogueInBlock(*EpilogB);
422 } else {
423 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000424 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000425 insertCSRRestoresInBlock(B, CSI, HRI);
426
427 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000428 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000429 insertEpilogueInBlock(B);
430 }
431}
432
433
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000434void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB,
435 bool PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000436 MachineFunction &MF = *MBB.getParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000437 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000438 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000439 auto &HII = *HST.getInstrInfo();
440 auto &HRI = *HST.getRegisterInfo();
441 DebugLoc dl;
442
443 unsigned MaxAlign = std::max(MFI->getMaxAlignment(), getStackAlignment());
444
445 // Calculate the total stack frame size.
446 // Get the number of bytes to allocate from the FrameInfo.
447 unsigned FrameSize = MFI->getStackSize();
448 // Round up the max call frame size to the max alignment on the stack.
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000449 unsigned MaxCFA = alignTo(MFI->getMaxCallFrameSize(), MaxAlign);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000450 MFI->setMaxCallFrameSize(MaxCFA);
451
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000452 FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000453 MFI->setStackSize(FrameSize);
454
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000455 bool AlignStack = (MaxAlign > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000456
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000457 // Get the number of bytes to allocate from the FrameInfo.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000458 unsigned NumBytes = MFI->getStackSize();
459 unsigned SP = HRI.getStackRegister();
460 unsigned MaxCF = MFI->getMaxCallFrameSize();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000461 MachineBasicBlock::iterator InsertPt = MBB.begin();
462
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000463 auto *FuncInfo = MF.getInfo<HexagonMachineFunctionInfo>();
464 auto &AdjustRegs = FuncInfo->getAllocaAdjustInsts();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000465
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000466 for (auto MI : AdjustRegs) {
467 assert((MI->getOpcode() == Hexagon::ALLOCA) && "Expected alloca");
468 expandAlloca(MI, HII, SP, MaxCF);
469 MI->eraseFromParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000470 }
471
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000472 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000473 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000474
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000475 // Check for overflow.
476 // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
477 const unsigned int ALLOCFRAME_MAX = 16384;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000478
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000479 // Create a dummy memory operand to avoid allocframe from being treated as
480 // a volatile memory reference.
481 MachineMemOperand *MMO =
482 MF.getMachineMemOperand(MachinePointerInfo(), MachineMemOperand::MOStore,
483 4, 4);
484
485 if (NumBytes >= ALLOCFRAME_MAX) {
486 // Emit allocframe(#0).
487 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
488 .addImm(0)
489 .addMemOperand(MMO);
490
491 // Subtract offset from frame pointer.
492 // We use a caller-saved non-parameter register for that.
493 unsigned CallerSavedReg = HRI.getFirstCallerSavedNonParamReg();
494 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CONST32_Int_Real),
495 CallerSavedReg).addImm(NumBytes);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000496 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_sub), SP)
497 .addReg(SP)
498 .addReg(CallerSavedReg);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000499 } else {
500 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
501 .addImm(NumBytes)
502 .addMemOperand(MMO);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000503 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000504
505 if (AlignStack) {
506 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
507 .addReg(SP)
508 .addImm(-int64_t(MaxAlign));
509 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000510
511 // If the stack-checking is enabled, and we spilled the callee-saved
512 // registers inline (i.e. did not use a spill function), then call
513 // the stack checker directly.
514 if (EnableStackOVFSanitizer && !PrologueStubs)
515 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CALLstk))
516 .addExternalSymbol("__runtime_stack_check");
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000517}
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000518
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000519void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
520 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000521 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000522 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000523
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000524 auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
525 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000526 auto &HRI = *HST.getRegisterInfo();
527 unsigned SP = HRI.getStackRegister();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000528
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000529 MachineInstr *RetI = nullptr;
530 for (auto &I : MBB) {
531 if (!I.isReturn())
532 continue;
533 RetI = &I;
534 break;
535 }
536 unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
537
538 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
539 DebugLoc DL;
540 if (InsertPt != MBB.end())
541 DL = InsertPt->getDebugLoc();
542 else if (!MBB.empty())
543 DL = std::prev(MBB.end())->getDebugLoc();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000544
545 // Handle EH_RETURN.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000546 if (RetOpc == Hexagon::EH_RETURN_JMPR) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000547 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
548 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::A2_add), SP)
549 .addReg(SP)
550 .addReg(Hexagon::R28);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000551 return;
552 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000553
554 // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
555 // frame instruction if we encounter it.
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000556 if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
557 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000558 MachineBasicBlock::iterator It = RetI;
559 ++It;
560 // Delete all instructions after the RESTORE (except labels).
561 while (It != MBB.end()) {
562 if (!It->isLabel())
563 It = MBB.erase(It);
564 else
565 ++It;
Jyotsna Verma300f0b92013-05-10 20:27:34 +0000566 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000567 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000568 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000569
570 // It is possible that the restoring code is a call to a library function.
571 // All of the restore* functions include "deallocframe", so we need to make
572 // sure that we don't add an extra one.
573 bool NeedsDeallocframe = true;
574 if (!MBB.empty() && InsertPt != MBB.begin()) {
575 MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
576 unsigned COpc = PrevIt->getOpcode();
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000577 if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
578 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000579 NeedsDeallocframe = false;
580 }
581
582 if (!NeedsDeallocframe)
583 return;
584 // If the returning instruction is JMPret, replace it with dealloc_return,
585 // otherwise just add deallocframe. The function could be returning via a
586 // tail call.
587 if (RetOpc != Hexagon::JMPret || DisableDeallocRet) {
588 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
589 return;
590 }
591 unsigned NewOpc = Hexagon::L4_return;
592 MachineInstr *NewI = BuildMI(MBB, RetI, DL, HII.get(NewOpc));
593 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000594 NewI->copyImplicitOps(MF, *RetI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000595 MBB.erase(RetI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000596}
597
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000598
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000599namespace {
600 bool IsAllocFrame(MachineBasicBlock::const_iterator It) {
601 if (!It->isBundle())
602 return It->getOpcode() == Hexagon::S2_allocframe;
603 auto End = It->getParent()->instr_end();
Duncan P. N. Exon Smithd84f6002016-02-22 21:30:15 +0000604 MachineBasicBlock::const_instr_iterator I = It.getInstrIterator();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000605 while (++I != End && I->isBundled())
606 if (I->getOpcode() == Hexagon::S2_allocframe)
607 return true;
608 return false;
609 }
610
611 MachineBasicBlock::iterator FindAllocFrame(MachineBasicBlock &B) {
612 for (auto &I : B)
613 if (IsAllocFrame(I))
614 return I;
615 return B.end();
616 }
617}
618
619
620void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
621 for (auto &B : MF) {
622 auto AF = FindAllocFrame(B);
623 if (AF == B.end())
624 continue;
625 insertCFIInstructionsAt(B, ++AF);
626 }
627}
628
629
630void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
631 MachineBasicBlock::iterator At) const {
632 MachineFunction &MF = *MBB.getParent();
633 MachineFrameInfo *MFI = MF.getFrameInfo();
634 MachineModuleInfo &MMI = MF.getMMI();
635 auto &HST = MF.getSubtarget<HexagonSubtarget>();
636 auto &HII = *HST.getInstrInfo();
637 auto &HRI = *HST.getRegisterInfo();
638
639 // If CFI instructions have debug information attached, something goes
640 // wrong with the final assembly generation: the prolog_end is placed
641 // in a wrong location.
642 DebugLoc DL;
643 const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
644
645 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
646
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000647 if (hasFP(MF)) {
648 unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
649 unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000650
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000651 // Define CFA via an offset from the value of FP.
652 //
653 // -8 -4 0 (SP)
654 // --+----+----+---------------------
655 // | FP | LR | increasing addresses -->
656 // --+----+----+---------------------
657 // | +-- Old SP (before allocframe)
658 // +-- New FP (after allocframe)
659 //
660 // MCCFIInstruction::createDefCfa subtracts the offset from the register.
661 // MCCFIInstruction::createOffset takes the offset without sign change.
662 auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
663 BuildMI(MBB, At, DL, CFID)
664 .addCFIIndex(MMI.addFrameInst(DefCfa));
665 // R31 (return addr) = CFA - 4
666 auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
667 BuildMI(MBB, At, DL, CFID)
668 .addCFIIndex(MMI.addFrameInst(OffR31));
669 // R30 (frame ptr) = CFA - 8
670 auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
671 BuildMI(MBB, At, DL, CFID)
672 .addCFIIndex(MMI.addFrameInst(OffR30));
673 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000674
675 static unsigned int RegsToMove[] = {
676 Hexagon::R1, Hexagon::R0, Hexagon::R3, Hexagon::R2,
677 Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
678 Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
679 Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
680 Hexagon::D0, Hexagon::D1, Hexagon::D8, Hexagon::D9,
681 Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
682 Hexagon::NoRegister
683 };
684
685 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
686
687 for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
688 unsigned Reg = RegsToMove[i];
689 auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
690 return C.getReg() == Reg;
691 };
692 auto F = std::find_if(CSI.begin(), CSI.end(), IfR);
693 if (F == CSI.end())
694 continue;
695
696 // Subtract 8 to make room for R30 and R31, which are added above.
697 unsigned FrameReg;
698 int64_t Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg) - 8;
699
700 if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
701 unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
702 auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
703 Offset);
704 BuildMI(MBB, At, DL, CFID)
705 .addCFIIndex(MMI.addFrameInst(OffReg));
706 } else {
707 // Split the double regs into subregs, and generate appropriate
708 // cfi_offsets.
709 // The only reason, we are split double regs is, llvm-mc does not
710 // understand paired registers for cfi_offset.
711 // Eg .cfi_offset r1:0, -64
712
713 unsigned HiReg = HRI.getSubReg(Reg, Hexagon::subreg_hireg);
714 unsigned LoReg = HRI.getSubReg(Reg, Hexagon::subreg_loreg);
715 unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
716 unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
717 auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
718 Offset+4);
719 BuildMI(MBB, At, DL, CFID)
720 .addCFIIndex(MMI.addFrameInst(OffHi));
721 auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
722 Offset);
723 BuildMI(MBB, At, DL, CFID)
724 .addCFIIndex(MMI.addFrameInst(OffLo));
725 }
726 }
727}
728
729
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000730bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000731 auto &MFI = *MF.getFrameInfo();
732 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
733
734 bool HasFixed = MFI.getNumFixedObjects();
735 bool HasPrealloc = const_cast<MachineFrameInfo&>(MFI)
736 .getLocalFrameObjectCount();
737 bool HasExtraAlign = HRI.needsStackRealignment(MF);
738 bool HasAlloca = MFI.hasVarSizedObjects();
739
740 // Insert ALLOCFRAME if we need to or at -O0 for the debugger. Think
741 // that this shouldn't be required, but doing so now because gcc does and
742 // gdb can't break at the start of the function without it. Will remove if
743 // this turns out to be a gdb bug.
744 //
745 if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
746 return true;
747
748 // By default we want to use SP (since it's always there). FP requires
749 // some setup (i.e. ALLOCFRAME).
750 // Fixed and preallocated objects need FP if the distance from them to
751 // the SP is unknown (as is with alloca or aligna).
752 if ((HasFixed || HasPrealloc) && (HasAlloca || HasExtraAlign))
753 return true;
754
755 if (MFI.getStackSize() > 0) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000756 if (EnableStackOVFSanitizer || UseAllocframe)
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000757 return true;
758 }
759
760 if (MFI.hasCalls() ||
761 MF.getInfo<HexagonMachineFunctionInfo>()->hasClobberLR())
762 return true;
763
764 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000765}
766
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000767
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000768enum SpillKind {
769 SK_ToMem,
770 SK_FromMem,
771 SK_FromMemTailcall
772};
773
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000774static const char *getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType,
775 bool Stkchk = false) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000776 const char * V4SpillToMemoryFunctions[] = {
777 "__save_r16_through_r17",
778 "__save_r16_through_r19",
779 "__save_r16_through_r21",
780 "__save_r16_through_r23",
781 "__save_r16_through_r25",
782 "__save_r16_through_r27" };
783
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000784 const char * V4SpillToMemoryStkchkFunctions[] = {
785 "__save_r16_through_r17_stkchk",
786 "__save_r16_through_r19_stkchk",
787 "__save_r16_through_r21_stkchk",
788 "__save_r16_through_r23_stkchk",
789 "__save_r16_through_r25_stkchk",
790 "__save_r16_through_r27_stkchk" };
791
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000792 const char * V4SpillFromMemoryFunctions[] = {
793 "__restore_r16_through_r17_and_deallocframe",
794 "__restore_r16_through_r19_and_deallocframe",
795 "__restore_r16_through_r21_and_deallocframe",
796 "__restore_r16_through_r23_and_deallocframe",
797 "__restore_r16_through_r25_and_deallocframe",
798 "__restore_r16_through_r27_and_deallocframe" };
799
800 const char * V4SpillFromMemoryTailcallFunctions[] = {
801 "__restore_r16_through_r17_and_deallocframe_before_tailcall",
802 "__restore_r16_through_r19_and_deallocframe_before_tailcall",
803 "__restore_r16_through_r21_and_deallocframe_before_tailcall",
804 "__restore_r16_through_r23_and_deallocframe_before_tailcall",
805 "__restore_r16_through_r25_and_deallocframe_before_tailcall",
806 "__restore_r16_through_r27_and_deallocframe_before_tailcall"
807 };
808
809 const char **SpillFunc = nullptr;
810
811 switch(SpillType) {
812 case SK_ToMem:
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000813 SpillFunc = Stkchk ? V4SpillToMemoryStkchkFunctions
814 : V4SpillToMemoryFunctions;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000815 break;
816 case SK_FromMem:
817 SpillFunc = V4SpillFromMemoryFunctions;
818 break;
819 case SK_FromMemTailcall:
820 SpillFunc = V4SpillFromMemoryTailcallFunctions;
821 break;
822 }
823 assert(SpillFunc && "Unknown spill kind");
824
825 // Spill all callee-saved registers up to the highest register used.
826 switch (MaxReg) {
827 case Hexagon::R17:
828 return SpillFunc[0];
829 case Hexagon::R19:
830 return SpillFunc[1];
831 case Hexagon::R21:
832 return SpillFunc[2];
833 case Hexagon::R23:
834 return SpillFunc[3];
835 case Hexagon::R25:
836 return SpillFunc[4];
837 case Hexagon::R27:
838 return SpillFunc[5];
839 default:
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000840 llvm_unreachable("Unhandled maximum callee save register");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000841 }
842 return 0;
843}
844
845/// Adds all callee-saved registers up to MaxReg to the instruction.
846static void addCalleeSaveRegistersAsImpOperand(MachineInstr *Inst,
847 unsigned MaxReg, bool IsDef) {
848 // Add the callee-saved registers as implicit uses.
849 for (unsigned R = Hexagon::R16; R <= MaxReg; ++R) {
850 MachineOperand ImpUse = MachineOperand::CreateReg(R, IsDef, true);
851 Inst->addOperand(ImpUse);
852 }
853}
854
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000855
James Y Knight5567baf2015-08-15 02:32:35 +0000856int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF,
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000857 int FI, unsigned &FrameReg) const {
858 auto &MFI = *MF.getFrameInfo();
859 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000860
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000861 int Offset = MFI.getObjectOffset(FI);
862 bool HasAlloca = MFI.hasVarSizedObjects();
863 bool HasExtraAlign = HRI.needsStackRealignment(MF);
864 bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
James Y Knight5567baf2015-08-15 02:32:35 +0000865
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000866 unsigned SP = HRI.getStackRegister(), FP = HRI.getFrameRegister();
867 unsigned AP = 0;
868 if (const MachineInstr *AI = getAlignaInstr(MF))
869 AP = AI->getOperand(0).getReg();
870 unsigned FrameSize = MFI.getStackSize();
871
872 bool UseFP = false, UseAP = false; // Default: use SP (except at -O0).
873 // Use FP at -O0, except when there are objects with extra alignment.
874 // That additional alignment requirement may cause a pad to be inserted,
875 // which will make it impossible to use FP to access objects located
876 // past the pad.
877 if (NoOpt && !HasExtraAlign)
878 UseFP = true;
879 if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
880 // Fixed and preallocated objects will be located before any padding
881 // so FP must be used to access them.
882 UseFP |= (HasAlloca || HasExtraAlign);
883 } else {
884 if (HasAlloca) {
885 if (HasExtraAlign)
886 UseAP = true;
887 else
888 UseFP = true;
889 }
890 }
891
892 // If FP was picked, then there had better be FP.
893 bool HasFP = hasFP(MF);
894 assert((HasFP || !UseFP) && "This function must have frame pointer");
895
896 // Having FP implies allocframe. Allocframe will store extra 8 bytes:
897 // FP/LR. If the base register is used to access an object across these
898 // 8 bytes, then the offset will need to be adjusted by 8.
899 //
900 // After allocframe:
901 // HexagonISelLowering adds 8 to ---+
902 // the offsets of all stack-based |
903 // arguments (*) |
904 // |
905 // getObjectOffset < 0 0 8 getObjectOffset >= 8
906 // ------------------------+-----+------------------------> increasing
907 // <local objects> |FP/LR| <input arguments> addresses
908 // -----------------+------+-----+------------------------>
909 // | |
910 // SP/AP point --+ +-- FP points here (**)
911 // somewhere on
912 // this side of FP/LR
913 //
914 // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
915 // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
916
917 // The lowering assumes that FP/LR is present, and so the offsets of
918 // the formal arguments start at 8. If FP/LR is not there we need to
919 // reduce the offset by 8.
920 if (Offset > 0 && !HasFP)
921 Offset -= 8;
922
923 if (UseFP)
924 FrameReg = FP;
925 else if (UseAP)
926 FrameReg = AP;
927 else
928 FrameReg = SP;
929
930 // Calculate the actual offset in the instruction. If there is no FP
931 // (in other words, no allocframe), then SP will not be adjusted (i.e.
932 // there will be no SP -= FrameSize), so the frame size should not be
933 // added to the calculated offset.
934 int RealOffset = Offset;
935 if (!UseFP && !UseAP && HasFP)
936 RealOffset = FrameSize+Offset;
937 return RealOffset;
Jakob Stoklund Olesen0b97dbc2012-05-30 22:40:03 +0000938}
939
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000940
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000941bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000942 const CSIVect &CSI, const HexagonRegisterInfo &HRI,
943 bool &PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000944 if (CSI.empty())
945 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000946
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000947 MachineBasicBlock::iterator MI = MBB.begin();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000948 PrologueStubs = false;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000949 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000950 auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000951
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000952 if (useSpillFunction(MF, CSI)) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000953 PrologueStubs = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000954 unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000955 bool StkOvrFlowEnabled = EnableStackOVFSanitizer;
956 const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem,
957 StkOvrFlowEnabled);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000958 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
959 bool IsPIC = HTM.getRelocationModel() == Reloc::PIC_;
960
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000961 // Call spill function.
962 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000963 unsigned SpillOpc;
964 if (StkOvrFlowEnabled)
965 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC
966 : Hexagon::SAVE_REGISTERS_CALL_V4STK;
967 else
968 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
969 : Hexagon::SAVE_REGISTERS_CALL_V4;
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000970
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000971 MachineInstr *SaveRegsCall =
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000972 BuildMI(MBB, MI, DL, HII.get(SpillOpc))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000973 .addExternalSymbol(SpillFun);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000974 // Add callee-saved registers as use.
975 addCalleeSaveRegistersAsImpOperand(SaveRegsCall, MaxReg, false);
976 // Add live in registers.
977 for (unsigned I = 0; I < CSI.size(); ++I)
978 MBB.addLiveIn(CSI[I].getReg());
979 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000980 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000981
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000982 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000983 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000984 // Add live in registers. We treat eh_return callee saved register r0 - r3
985 // specially. They are not really callee saved registers as they are not
986 // supposed to be killed.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000987 bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
988 int FI = CSI[i].getFrameIdx();
989 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000990 HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000991 if (IsKill)
992 MBB.addLiveIn(Reg);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000993 }
994 return true;
995}
996
997
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000998bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
999 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
1000 if (CSI.empty())
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001001 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001002
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001003 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1004 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001005 auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001006
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001007 if (useRestoreFunction(MF, CSI)) {
1008 bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
1009 unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
1010 SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
1011 const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001012 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
1013 bool IsPIC = HTM.getRelocationModel() == Reloc::PIC_;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001014
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001015 // Call spill function.
1016 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
1017 : MBB.getLastNonDebugInstr()->getDebugLoc();
1018 MachineInstr *DeallocCall = nullptr;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001019
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001020 if (HasTC) {
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001021 unsigned ROpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
1022 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001023 DeallocCall = BuildMI(MBB, MI, DL, HII.get(ROpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001024 .addExternalSymbol(RestoreFn);
1025 } else {
1026 // The block has a return.
1027 MachineBasicBlock::iterator It = MBB.getFirstTerminator();
1028 assert(It->isReturn() && std::next(It) == MBB.end());
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001029 unsigned ROpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
1030 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001031 DeallocCall = BuildMI(MBB, It, DL, HII.get(ROpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001032 .addExternalSymbol(RestoreFn);
1033 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +00001034 DeallocCall->copyImplicitOps(MF, *It);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001035 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001036 addCalleeSaveRegistersAsImpOperand(DeallocCall, MaxR, true);
1037 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001038 }
1039
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001040 for (unsigned i = 0; i < CSI.size(); ++i) {
1041 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001042 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1043 int FI = CSI[i].getFrameIdx();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001044 HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001045 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001046
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001047 return true;
1048}
1049
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001050
1051void HexagonFrameLowering::eliminateCallFramePseudoInstr(MachineFunction &MF,
1052 MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00001053 MachineInstr &MI = *I;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001054 unsigned Opc = MI.getOpcode();
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001055 (void)Opc; // Silence compiler warning.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001056 assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1057 "Cannot handle this call frame pseudo instruction");
Eli Bendersky8da87162013-02-21 20:05:00 +00001058 MBB.erase(I);
1059}
1060
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001061
1062void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1063 MachineFunction &MF, RegScavenger *RS) const {
1064 // If this function has uses aligned stack and also has variable sized stack
1065 // objects, then we need to map all spill slots to fixed positions, so that
1066 // they can be accessed through FP. Otherwise they would have to be accessed
1067 // via AP, which may not be available at the particular place in the program.
1068 MachineFrameInfo *MFI = MF.getFrameInfo();
1069 bool HasAlloca = MFI->hasVarSizedObjects();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001070 bool NeedsAlign = (MFI->getMaxAlignment() > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001071
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001072 if (!HasAlloca || !NeedsAlign)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001073 return;
1074
1075 unsigned LFS = MFI->getLocalFrameSize();
1076 int Offset = -LFS;
1077 for (int i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
1078 if (!MFI->isSpillSlotObjectIndex(i) || MFI->isDeadObjectIndex(i))
1079 continue;
1080 int S = MFI->getObjectSize(i);
1081 LFS += S;
1082 Offset -= S;
1083 MFI->mapLocalFrameObject(i, Offset);
1084 }
1085
1086 MFI->setLocalFrameSize(LFS);
1087 unsigned A = MFI->getLocalFrameMaxAlign();
1088 assert(A <= 8 && "Unexpected local frame alignment");
1089 if (A == 0)
1090 MFI->setLocalFrameMaxAlign(8);
1091 MFI->setUseLocalStackAllocationBlock(true);
1092}
1093
1094/// Returns true if there is no caller saved registers available.
1095static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
1096 const HexagonRegisterInfo &HRI) {
1097 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001098 BitVector Reserved = HRI.getReservedRegs(MF);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001099
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001100 auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1101 for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1102 if (MRI.isPhysRegUsed(*AI))
1103 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001104 return false;
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001105 };
1106
1107 // Check for an unused caller-saved register.
1108 for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF); *P; ++P)
1109 if (!IsUsed(*P))
1110 return false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001111 // All caller-saved registers are used.
1112 return true;
1113}
1114
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001115
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001116#ifndef NDEBUG
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001117static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001118 dbgs() << '{';
1119 for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1120 unsigned R = x;
1121 dbgs() << ' ' << PrintReg(R, &TRI);
1122 }
1123 dbgs() << " }";
1124}
1125#endif
1126
1127
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001128bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1129 const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
Krzysztof Parzyszek27ba19a12015-04-23 20:42:20 +00001130 DEBUG(dbgs() << LLVM_FUNCTION_NAME << " on "
Krzysztof Parzyszeked75e7a2015-04-23 20:57:39 +00001131 << MF.getFunction()->getName() << '\n');
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001132 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001133 BitVector SRegs(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001134
1135 // Generate a set of unique, callee-saved registers (SRegs), where each
1136 // register in the set is maximal in terms of sub-/super-register relation,
1137 // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1138
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001139 // (1) For each callee-saved register, add that register and all of its
1140 // sub-registers to SRegs.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001141 DEBUG(dbgs() << "Initial CS registers: {");
1142 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1143 unsigned R = CSI[i].getReg();
1144 DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1145 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1146 SRegs[*SR] = true;
1147 }
1148 DEBUG(dbgs() << " }\n");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001149 DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001150
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001151 // (2) For each reserved register, remove that register and all of its
1152 // sub- and super-registers from SRegs.
1153 BitVector Reserved = TRI->getReservedRegs(MF);
1154 for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1155 unsigned R = x;
1156 for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1157 SRegs[*SR] = false;
1158 }
1159 DEBUG(dbgs() << "Res: "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1160 DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1161
1162 // (3) Collect all registers that have at least one sub-register in SRegs,
1163 // and also have no sub-registers that are reserved. These will be the can-
1164 // didates for saving as a whole instead of their individual sub-registers.
1165 // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1166 BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001167 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1168 unsigned R = x;
1169 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1170 TmpSup[*SR] = true;
1171 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001172 for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1173 unsigned R = x;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001174 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1175 if (!Reserved[*SR])
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001176 continue;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001177 TmpSup[R] = false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001178 break;
1179 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001180 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001181 DEBUG(dbgs() << "TmpSup: "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001182
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001183 // (4) Include all super-registers found in (3) into SRegs.
1184 SRegs |= TmpSup;
1185 DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001186
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001187 // (5) For each register R in SRegs, if any super-register of R is in SRegs,
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001188 // remove R from SRegs.
1189 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1190 unsigned R = x;
1191 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1192 if (!SRegs[*SR])
1193 continue;
1194 SRegs[R] = false;
1195 break;
1196 }
1197 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001198 DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001199
1200 // Now, for each register that has a fixed stack slot, create the stack
1201 // object for it.
1202 CSI.clear();
1203
1204 typedef TargetFrameLowering::SpillSlot SpillSlot;
1205 unsigned NumFixed;
1206 int MinOffset = 0; // CS offsets are negative.
1207 const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1208 for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1209 if (!SRegs[S->Reg])
1210 continue;
1211 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
1212 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), S->Offset);
1213 MinOffset = std::min(MinOffset, S->Offset);
1214 CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1215 SRegs[S->Reg] = false;
1216 }
1217
1218 // There can be some registers that don't have fixed slots. For example,
1219 // we need to store R0-R3 in functions with exception handling. For each
1220 // such register, create a non-fixed stack object.
1221 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1222 unsigned R = x;
1223 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
1224 int Off = MinOffset - RC->getSize();
1225 unsigned Align = std::min(RC->getAlignment(), getStackAlignment());
1226 assert(isPowerOf2_32(Align));
1227 Off &= -Align;
1228 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), Off);
1229 MinOffset = std::min(MinOffset, Off);
1230 CSI.push_back(CalleeSavedInfo(R, FI));
1231 SRegs[R] = false;
1232 }
1233
1234 DEBUG({
1235 dbgs() << "CS information: {";
1236 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1237 int FI = CSI[i].getFrameIdx();
1238 int Off = MFI->getObjectOffset(FI);
1239 dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1240 if (Off >= 0)
1241 dbgs() << '+';
1242 dbgs() << Off;
1243 }
1244 dbgs() << " }\n";
1245 });
1246
1247#ifndef NDEBUG
1248 // Verify that all registers were handled.
1249 bool MissedReg = false;
1250 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1251 unsigned R = x;
1252 dbgs() << PrintReg(R, TRI) << ' ';
1253 MissedReg = true;
1254 }
1255 if (MissedReg)
1256 llvm_unreachable("...there are unhandled callee-saved registers!");
1257#endif
1258
1259 return true;
1260}
1261
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001262
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001263bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1264 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1265 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1266 MachineInstr *MI = &*It;
1267 DebugLoc DL = MI->getDebugLoc();
1268 unsigned DstR = MI->getOperand(0).getReg();
1269 unsigned SrcR = MI->getOperand(1).getReg();
1270 if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1271 !Hexagon::ModRegsRegClass.contains(SrcR))
1272 return false;
1273
1274 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1275 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR)
1276 .addOperand(MI->getOperand(1));
1277 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1278 .addReg(TmpR, RegState::Kill);
1279
1280 NewRegs.push_back(TmpR);
1281 B.erase(It);
1282 return true;
1283}
1284
1285bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1286 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1287 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1288 MachineInstr *MI = &*It;
1289 DebugLoc DL = MI->getDebugLoc();
1290 unsigned Opc = MI->getOpcode();
1291 unsigned SrcR = MI->getOperand(2).getReg();
1292 bool IsKill = MI->getOperand(2).isKill();
1293
1294 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1295 int FI = MI->getOperand(0).getIndex();
1296
1297 // TmpR = C2_tfrpr SrcR if SrcR is a predicate register
1298 // TmpR = A2_tfrcrr SrcR if SrcR is a modifier register
1299 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1300 unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1301 : Hexagon::A2_tfrcrr;
1302 BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1303 .addReg(SrcR, getKillRegState(IsKill));
1304
1305 // S2_storeri_io FI, 0, TmpR
1306 BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1307 .addFrameIndex(FI)
1308 .addImm(0)
1309 .addReg(TmpR, RegState::Kill)
1310 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1311
1312 NewRegs.push_back(TmpR);
1313 B.erase(It);
1314 return true;
1315}
1316
1317bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1318 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1319 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1320 MachineInstr *MI = &*It;
1321 DebugLoc DL = MI->getDebugLoc();
1322 unsigned Opc = MI->getOpcode();
1323 unsigned DstR = MI->getOperand(0).getReg();
1324
1325 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1326 int FI = MI->getOperand(1).getIndex();
1327
1328 // TmpR = L2_loadri_io FI, 0
1329 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1330 BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1331 .addFrameIndex(FI)
1332 .addImm(0)
1333 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1334
1335 // DstR = C2_tfrrp TmpR if DstR is a predicate register
1336 // DstR = A2_tfrrcr TmpR if DstR is a modifier register
1337 unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1338 : Hexagon::A2_tfrrcr;
1339 BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1340 .addReg(TmpR, RegState::Kill);
1341
1342 NewRegs.push_back(TmpR);
1343 B.erase(It);
1344 return true;
1345}
1346
1347
1348bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1349 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1350 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1351 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1352 MachineInstr *MI = &*It;
1353 DebugLoc DL = MI->getDebugLoc();
1354 unsigned SrcR = MI->getOperand(2).getReg();
1355 bool IsKill = MI->getOperand(2).isKill();
1356
1357 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1358 int FI = MI->getOperand(0).getIndex();
1359
1360 bool Is128B = HST.useHVXDblOps();
1361 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1362 : &Hexagon::VectorRegs128BRegClass;
1363
1364 // Insert transfer to general vector register.
1365 // TmpR0 = A2_tfrsi 0x01010101
1366 // TmpR1 = V6_vandqrt Qx, TmpR0
1367 // store FI, 0, TmpR1
1368 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1369 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1370
1371 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1372 .addImm(0x01010101);
1373
1374 unsigned VandOpc = !Is128B ? Hexagon::V6_vandqrt : Hexagon::V6_vandqrt_128B;
1375 BuildMI(B, It, DL, HII.get(VandOpc), TmpR1)
1376 .addReg(SrcR, getKillRegState(IsKill))
1377 .addReg(TmpR0, RegState::Kill);
1378
1379 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1380 HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1381 expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1382
1383 NewRegs.push_back(TmpR0);
1384 NewRegs.push_back(TmpR1);
1385 B.erase(It);
1386 return true;
1387}
1388
1389bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1390 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1391 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1392 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1393 MachineInstr *MI = &*It;
1394 DebugLoc DL = MI->getDebugLoc();
1395 unsigned DstR = MI->getOperand(0).getReg();
1396
1397 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1398 int FI = MI->getOperand(1).getIndex();
1399
1400 bool Is128B = HST.useHVXDblOps();
1401 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1402 : &Hexagon::VectorRegs128BRegClass;
1403
1404 // TmpR0 = A2_tfrsi 0x01010101
1405 // TmpR1 = load FI, 0
1406 // DstR = V6_vandvrt TmpR1, TmpR0
1407 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1408 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1409
1410 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1411 .addImm(0x01010101);
1412 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1413 HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1414 expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1415
1416 unsigned VandOpc = !Is128B ? Hexagon::V6_vandvrt : Hexagon::V6_vandvrt_128B;
1417 BuildMI(B, It, DL, HII.get(VandOpc), DstR)
1418 .addReg(TmpR1, RegState::Kill)
1419 .addReg(TmpR0, RegState::Kill);
1420
1421 NewRegs.push_back(TmpR0);
1422 NewRegs.push_back(TmpR1);
1423 B.erase(It);
1424 return true;
1425}
1426
1427bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1428 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1429 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1430 MachineFunction &MF = *B.getParent();
1431 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1432 auto &MFI = *MF.getFrameInfo();
1433 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1434 MachineInstr *MI = &*It;
1435 DebugLoc DL = MI->getDebugLoc();
1436
1437 unsigned SrcR = MI->getOperand(2).getReg();
1438 unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::subreg_loreg);
1439 unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::subreg_hireg);
1440 bool IsKill = MI->getOperand(2).isKill();
1441
1442 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1443 int FI = MI->getOperand(0).getIndex();
1444
1445 bool Is128B = HST.useHVXDblOps();
1446 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1447 : &Hexagon::VectorRegs128BRegClass;
1448 unsigned Size = RC->getSize();
1449 unsigned NeedAlign = RC->getAlignment();
1450 unsigned HasAlign = MFI.getObjectAlignment(FI);
1451 unsigned StoreOpc;
1452
1453 // Store low part.
1454 if (NeedAlign <= HasAlign)
1455 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1456 else
1457 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1458
1459 BuildMI(B, It, DL, HII.get(StoreOpc))
1460 .addFrameIndex(FI)
1461 .addImm(0)
1462 .addReg(SrcLo, getKillRegState(IsKill))
1463 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1464
1465 // Load high part.
1466 if (NeedAlign <= MinAlign(HasAlign, Size))
1467 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1468 else
1469 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1470
1471 BuildMI(B, It, DL, HII.get(StoreOpc))
1472 .addFrameIndex(FI)
1473 .addImm(Size)
1474 .addReg(SrcHi, getKillRegState(IsKill))
1475 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1476
1477 B.erase(It);
1478 return true;
1479}
1480
1481bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1482 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1483 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1484 MachineFunction &MF = *B.getParent();
1485 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1486 auto &MFI = *MF.getFrameInfo();
1487 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1488 MachineInstr *MI = &*It;
1489 DebugLoc DL = MI->getDebugLoc();
1490
1491 unsigned DstR = MI->getOperand(0).getReg();
1492 unsigned DstHi = HRI.getSubReg(DstR, Hexagon::subreg_hireg);
1493 unsigned DstLo = HRI.getSubReg(DstR, Hexagon::subreg_loreg);
1494
1495 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1496 int FI = MI->getOperand(1).getIndex();
1497
1498 bool Is128B = HST.useHVXDblOps();
1499 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1500 : &Hexagon::VectorRegs128BRegClass;
1501 unsigned Size = RC->getSize();
1502 unsigned NeedAlign = RC->getAlignment();
1503 unsigned HasAlign = MFI.getObjectAlignment(FI);
1504 unsigned LoadOpc;
1505
1506 // Load low part.
1507 if (NeedAlign <= HasAlign)
1508 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1509 else
1510 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1511
1512 BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1513 .addFrameIndex(FI)
1514 .addImm(0)
1515 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1516
1517 // Load high part.
1518 if (NeedAlign <= MinAlign(HasAlign, Size))
1519 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1520 else
1521 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1522
1523 BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1524 .addFrameIndex(FI)
1525 .addImm(Size)
1526 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1527
1528 B.erase(It);
1529 return true;
1530}
1531
1532bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1533 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1534 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1535 MachineFunction &MF = *B.getParent();
1536 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1537 auto &MFI = *MF.getFrameInfo();
1538 MachineInstr *MI = &*It;
1539 DebugLoc DL = MI->getDebugLoc();
1540
1541 unsigned SrcR = MI->getOperand(2).getReg();
1542 bool IsKill = MI->getOperand(2).isKill();
1543
1544 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1545 int FI = MI->getOperand(0).getIndex();
1546
1547 bool Is128B = HST.useHVXDblOps();
1548 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1549 : &Hexagon::VectorRegs128BRegClass;
1550
1551 unsigned NeedAlign = RC->getAlignment();
1552 unsigned HasAlign = MFI.getObjectAlignment(FI);
1553 unsigned StoreOpc;
1554
1555 if (NeedAlign <= HasAlign)
1556 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1557 else
1558 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1559
1560 BuildMI(B, It, DL, HII.get(StoreOpc))
1561 .addFrameIndex(FI)
1562 .addImm(0)
1563 .addReg(SrcR, getKillRegState(IsKill))
1564 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1565
1566 B.erase(It);
1567 return true;
1568}
1569
1570bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
1571 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1572 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1573 MachineFunction &MF = *B.getParent();
1574 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1575 auto &MFI = *MF.getFrameInfo();
1576 MachineInstr *MI = &*It;
1577 DebugLoc DL = MI->getDebugLoc();
1578
1579 unsigned DstR = MI->getOperand(0).getReg();
1580
1581 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1582 int FI = MI->getOperand(1).getIndex();
1583
1584 bool Is128B = HST.useHVXDblOps();
1585 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1586 : &Hexagon::VectorRegs128BRegClass;
1587
1588 unsigned NeedAlign = RC->getAlignment();
1589 unsigned HasAlign = MFI.getObjectAlignment(FI);
1590 unsigned LoadOpc;
1591
1592 if (NeedAlign <= HasAlign)
1593 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1594 else
1595 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1596
1597 BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1598 .addFrameIndex(FI)
1599 .addImm(0)
1600 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1601
1602 B.erase(It);
1603 return true;
1604}
1605
1606
1607bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1608 SmallVectorImpl<unsigned> &NewRegs) const {
1609 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001610 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001611 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001612 bool Changed = false;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001613
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001614 for (auto &B : MF) {
1615 // Traverse the basic block.
1616 MachineBasicBlock::iterator NextI;
1617 for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1618 MachineInstr *MI = &*I;
1619 NextI = std::next(I);
1620 unsigned Opc = MI->getOpcode();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001621
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001622 switch (Opc) {
1623 case TargetOpcode::COPY:
1624 Changed = expandCopy(B, I, MRI, HII, NewRegs);
1625 break;
1626 case Hexagon::STriw_pred:
1627 case Hexagon::STriw_mod:
1628 Changed = expandStoreInt(B, I, MRI, HII, NewRegs);
1629 break;
1630 case Hexagon::LDriw_pred:
1631 case Hexagon::LDriw_mod:
1632 Changed = expandLoadInt(B, I, MRI, HII, NewRegs);
1633 break;
1634 case Hexagon::STriq_pred_V6:
1635 case Hexagon::STriq_pred_V6_128B:
1636 Changed = expandStoreVecPred(B, I, MRI, HII, NewRegs);
1637 break;
1638 case Hexagon::LDriq_pred_V6:
1639 case Hexagon::LDriq_pred_V6_128B:
1640 Changed = expandLoadVecPred(B, I, MRI, HII, NewRegs);
1641 break;
1642 case Hexagon::LDrivv_pseudo_V6:
1643 case Hexagon::LDrivv_pseudo_V6_128B:
1644 Changed = expandLoadVec2(B, I, MRI, HII, NewRegs);
1645 break;
1646 case Hexagon::STrivv_pseudo_V6:
1647 case Hexagon::STrivv_pseudo_V6_128B:
1648 Changed = expandStoreVec2(B, I, MRI, HII, NewRegs);
1649 break;
1650 case Hexagon::STriv_pseudo_V6:
1651 case Hexagon::STriv_pseudo_V6_128B:
1652 Changed = expandStoreVec(B, I, MRI, HII, NewRegs);
1653 break;
1654 case Hexagon::LDriv_pseudo_V6:
1655 case Hexagon::LDriv_pseudo_V6_128B:
1656 Changed = expandLoadVec(B, I, MRI, HII, NewRegs);
1657 break;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001658 }
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001659 }
1660 }
1661
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001662 return Changed;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001663}
1664
1665
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001666void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1667 BitVector &SavedRegs,
1668 RegScavenger *RS) const {
1669 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1670 auto &HRI = *HST.getRegisterInfo();
1671
1672 SavedRegs.resize(HRI.getNumRegs());
1673
1674 // If we have a function containing __builtin_eh_return we want to spill and
1675 // restore all callee saved registers. Pretend that they are used.
1676 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1677 for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1678 SavedRegs.set(*R);
1679
1680 // Replace predicate register pseudo spill code.
1681 SmallVector<unsigned,8> NewRegs;
1682 expandSpillMacros(MF, NewRegs);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001683 if (OptimizeSpillSlots)
1684 optimizeSpillSlots(MF, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001685
1686 // We need to reserve a a spill slot if scavenging could potentially require
1687 // spilling a scavenged register.
1688 if (!NewRegs.empty() && needToReserveScavengingSpillSlots(MF, HRI)) {
1689 MachineRegisterInfo &MRI = MF.getRegInfo();
1690 SetVector<const TargetRegisterClass*> SpillRCs;
1691 for (unsigned VR : NewRegs)
1692 SpillRCs.insert(MRI.getRegClass(VR));
1693
1694 MachineFrameInfo &MFI = *MF.getFrameInfo();
1695 const TargetRegisterClass &IntRC = Hexagon::IntRegsRegClass;
1696 if (SpillRCs.count(&IntRC)) {
1697 for (int i = 0; i < NumberScavengerSlots; i++) {
1698 int NewFI = MFI.CreateSpillStackObject(IntRC.getSize(),
1699 IntRC.getAlignment());
1700 RS->addScavengingFrameIndex(NewFI);
1701 }
1702 }
1703 for (auto *RC : SpillRCs) {
1704 if (RC == &IntRC)
1705 continue;
1706 int NewFI = MFI.CreateSpillStackObject(RC->getSize(), RC->getAlignment());
1707 RS->addScavengingFrameIndex(NewFI);
1708 }
1709 }
1710
1711 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1712}
1713
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001714
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001715unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1716 HexagonBlockRanges::IndexRange &FIR,
1717 HexagonBlockRanges::InstrIndexMap &IndexMap,
1718 HexagonBlockRanges::RegToRangeMap &DeadMap,
1719 const TargetRegisterClass *RC) const {
1720 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1721 auto &MRI = MF.getRegInfo();
1722
1723 auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1724 auto F = DeadMap.find({Reg,0});
1725 if (F == DeadMap.end())
1726 return false;
1727 for (auto &DR : F->second)
1728 if (DR.contains(FIR))
1729 return true;
1730 return false;
1731 };
1732
1733 for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
1734 bool Dead = true;
1735 for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
1736 if (isDead(R.Reg))
1737 continue;
1738 Dead = false;
1739 break;
1740 }
1741 if (Dead)
1742 return Reg;
1743 }
1744 return 0;
1745}
1746
1747void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
1748 SmallVectorImpl<unsigned> &VRegs) const {
1749 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1750 auto &HII = *HST.getInstrInfo();
1751 auto &HRI = *HST.getRegisterInfo();
1752 auto &MRI = MF.getRegInfo();
1753 HexagonBlockRanges HBR(MF);
1754
1755 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::InstrIndexMap>
1756 BlockIndexMap;
1757 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::RangeList>
1758 BlockRangeMap;
1759 typedef HexagonBlockRanges::IndexType IndexType;
1760
1761 struct SlotInfo {
1762 BlockRangeMap Map;
NAKAMURA Takumic2cc8702016-02-13 07:29:49 +00001763 unsigned Size;
1764 const TargetRegisterClass *RC;
1765
1766 SlotInfo() : Map(), Size(0), RC(nullptr) {}
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001767 };
1768
1769 BlockIndexMap BlockIndexes;
1770 SmallSet<int,4> BadFIs;
1771 std::map<int,SlotInfo> FIRangeMap;
1772
1773 auto getRegClass = [&MRI,&HRI] (HexagonBlockRanges::RegisterRef R)
1774 -> const TargetRegisterClass* {
1775 if (TargetRegisterInfo::isPhysicalRegister(R.Reg))
1776 assert(R.Sub == 0);
1777 if (TargetRegisterInfo::isVirtualRegister(R.Reg)) {
1778 auto *RCR = MRI.getRegClass(R.Reg);
1779 if (R.Sub == 0)
1780 return RCR;
1781 unsigned PR = *RCR->begin();
1782 R.Reg = HRI.getSubReg(PR, R.Sub);
1783 }
1784 return HRI.getMinimalPhysRegClass(R.Reg);
1785 };
1786 // Accumulate register classes: get a common class for a pre-existing
1787 // class HaveRC and a new class NewRC. Return nullptr if a common class
1788 // cannot be found, otherwise return the resulting class. If HaveRC is
1789 // nullptr, assume that it is still unset.
1790 auto getCommonRC = [&HRI] (const TargetRegisterClass *HaveRC,
1791 const TargetRegisterClass *NewRC)
1792 -> const TargetRegisterClass* {
1793 if (HaveRC == nullptr || HaveRC == NewRC)
1794 return NewRC;
1795 // Different classes, both non-null. Pick the more general one.
1796 if (HaveRC->hasSubClassEq(NewRC))
1797 return HaveRC;
1798 if (NewRC->hasSubClassEq(HaveRC))
1799 return NewRC;
1800 return nullptr;
1801 };
1802
1803 // Scan all blocks in the function. Check all occurrences of frame indexes,
1804 // and collect relevant information.
1805 for (auto &B : MF) {
1806 std::map<int,IndexType> LastStore, LastLoad;
Krzysztof Parzyszek280a50e2016-02-13 14:06:01 +00001807 // Emplace appears not to be supported in gcc 4.7.2-4.
1808 //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
Krzysztof Parzyszekde697d42016-02-17 15:02:07 +00001809 auto P = BlockIndexes.insert(
1810 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001811 auto &IndexMap = P.first->second;
1812 DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n"
1813 << IndexMap << '\n');
1814
1815 for (auto &In : B) {
1816 int LFI, SFI;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001817 bool Load = HII.isLoadFromStackSlot(&In, LFI) && !HII.isPredicated(In);
1818 bool Store = HII.isStoreToStackSlot(&In, SFI) && !HII.isPredicated(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001819 if (Load && Store) {
1820 // If it's both a load and a store, then we won't handle it.
1821 BadFIs.insert(LFI);
1822 BadFIs.insert(SFI);
1823 continue;
1824 }
1825 // Check for register classes of the register used as the source for
1826 // the store, and the register used as the destination for the load.
1827 // Also, only accept base+imm_offset addressing modes. Other addressing
1828 // modes can have side-effects (post-increments, etc.). For stack
1829 // slots they are very unlikely, so there is not much loss due to
1830 // this restriction.
1831 if (Load || Store) {
1832 int TFI = Load ? LFI : SFI;
1833 unsigned AM = HII.getAddrMode(&In);
1834 SlotInfo &SI = FIRangeMap[TFI];
1835 bool Bad = (AM != HexagonII::BaseImmOffset);
1836 if (!Bad) {
1837 // If the addressing mode is ok, check the register class.
1838 const TargetRegisterClass *RC = nullptr;
1839 if (Load) {
1840 MachineOperand &DataOp = In.getOperand(0);
1841 RC = getRegClass({DataOp.getReg(), DataOp.getSubReg()});
1842 } else {
1843 MachineOperand &DataOp = In.getOperand(2);
1844 RC = getRegClass({DataOp.getReg(), DataOp.getSubReg()});
1845 }
1846 RC = getCommonRC(SI.RC, RC);
1847 if (RC == nullptr)
1848 Bad = true;
1849 else
1850 SI.RC = RC;
1851 }
1852 if (!Bad) {
1853 // Check sizes.
1854 unsigned S = (1U << (HII.getMemAccessSize(&In) - 1));
1855 if (SI.Size != 0 && SI.Size != S)
1856 Bad = true;
1857 else
1858 SI.Size = S;
1859 }
1860 if (Bad)
1861 BadFIs.insert(TFI);
1862 }
1863
1864 // Locate uses of frame indices.
1865 for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
1866 const MachineOperand &Op = In.getOperand(i);
1867 if (!Op.isFI())
1868 continue;
1869 int FI = Op.getIndex();
1870 // Make sure that the following operand is an immediate and that
1871 // it is 0. This is the offset in the stack object.
1872 if (i+1 >= n || !In.getOperand(i+1).isImm() ||
1873 In.getOperand(i+1).getImm() != 0)
1874 BadFIs.insert(FI);
1875 if (BadFIs.count(FI))
1876 continue;
1877
1878 IndexType Index = IndexMap.getIndex(&In);
1879 if (Load) {
1880 if (LastStore[FI] == IndexType::None)
1881 LastStore[FI] = IndexType::Entry;
1882 LastLoad[FI] = Index;
1883 } else if (Store) {
1884 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
1885 if (LastStore[FI] != IndexType::None)
1886 RL.add(LastStore[FI], LastLoad[FI], false, false);
1887 else if (LastLoad[FI] != IndexType::None)
1888 RL.add(IndexType::Entry, LastLoad[FI], false, false);
1889 LastLoad[FI] = IndexType::None;
1890 LastStore[FI] = Index;
1891 } else {
1892 BadFIs.insert(FI);
1893 }
1894 }
1895 }
1896
1897 for (auto &I : LastLoad) {
1898 IndexType LL = I.second;
1899 if (LL == IndexType::None)
1900 continue;
1901 auto &RL = FIRangeMap[I.first].Map[&B];
1902 IndexType &LS = LastStore[I.first];
1903 if (LS != IndexType::None)
1904 RL.add(LS, LL, false, false);
1905 else
1906 RL.add(IndexType::Entry, LL, false, false);
1907 LS = IndexType::None;
1908 }
1909 for (auto &I : LastStore) {
1910 IndexType LS = I.second;
1911 if (LS == IndexType::None)
1912 continue;
1913 auto &RL = FIRangeMap[I.first].Map[&B];
1914 RL.add(LS, IndexType::None, false, false);
1915 }
1916 }
1917
1918 DEBUG({
1919 for (auto &P : FIRangeMap) {
1920 dbgs() << "fi#" << P.first;
1921 if (BadFIs.count(P.first))
1922 dbgs() << " (bad)";
1923 dbgs() << " RC: ";
1924 if (P.second.RC != nullptr)
1925 dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
1926 else
1927 dbgs() << "<null>\n";
1928 for (auto &R : P.second.Map)
1929 dbgs() << " BB#" << R.first->getNumber() << " { " << R.second << "}\n";
1930 }
1931 });
1932
1933 // When a slot is loaded from in a block without being stored to in the
1934 // same block, it is live-on-entry to this block. To avoid CFG analysis,
1935 // consider this slot to be live-on-exit from all blocks.
1936 SmallSet<int,4> LoxFIs;
1937
1938 std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
1939
1940 for (auto &P : FIRangeMap) {
1941 // P = pair(FI, map: BB->RangeList)
1942 if (BadFIs.count(P.first))
1943 continue;
1944 for (auto &B : MF) {
1945 auto F = P.second.Map.find(&B);
1946 // F = pair(BB, RangeList)
1947 if (F == P.second.Map.end() || F->second.empty())
1948 continue;
1949 HexagonBlockRanges::IndexRange &IR = F->second.front();
1950 if (IR.start() == IndexType::Entry)
1951 LoxFIs.insert(P.first);
1952 BlockFIMap[&B].push_back(P.first);
1953 }
1954 }
1955
1956 DEBUG({
1957 dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
1958 for (auto &P : BlockFIMap) {
1959 auto &FIs = P.second;
1960 if (FIs.empty())
1961 continue;
1962 dbgs() << " BB#" << P.first->getNumber() << ": {";
1963 for (auto I : FIs) {
1964 dbgs() << " fi#" << I;
1965 if (LoxFIs.count(I))
1966 dbgs() << '*';
1967 }
1968 dbgs() << " }\n";
1969 }
1970 });
1971
1972 // eliminate loads, when all loads eliminated, eliminate all stores.
1973 for (auto &B : MF) {
1974 auto F = BlockIndexes.find(&B);
1975 assert(F != BlockIndexes.end());
1976 HexagonBlockRanges::InstrIndexMap &IM = F->second;
1977 HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
1978 HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
1979 DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n"
1980 << HexagonBlockRanges::PrintRangeMap(DM, HRI));
1981
1982 for (auto FI : BlockFIMap[&B]) {
1983 if (BadFIs.count(FI))
1984 continue;
1985 DEBUG(dbgs() << "Working on fi#" << FI << '\n');
1986 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
1987 for (auto &Range : RL) {
1988 DEBUG(dbgs() << "--Examining range:" << RL << '\n');
1989 if (!IndexType::isInstr(Range.start()) ||
1990 !IndexType::isInstr(Range.end()))
1991 continue;
1992 MachineInstr *SI = IM.getInstr(Range.start());
1993 MachineInstr *EI = IM.getInstr(Range.end());
1994 assert(SI->mayStore() && "Unexpected start instruction");
1995 assert(EI->mayLoad() && "Unexpected end instruction");
1996 MachineOperand &SrcOp = SI->getOperand(2);
1997
1998 HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
1999 SrcOp.getSubReg() };
2000 auto *RC = getRegClass({SrcOp.getReg(), SrcOp.getSubReg()});
2001 // The this-> is needed to unconfuse MSVC.
2002 unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
2003 DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n');
2004 if (FoundR == 0)
2005 continue;
2006
2007 // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
2008 MachineBasicBlock::iterator StartIt = SI, NextIt;
2009 MachineInstr *CopyIn = nullptr;
2010 if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
2011 DebugLoc DL = SI->getDebugLoc();
2012 CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
2013 .addOperand(SrcOp);
2014 }
2015
2016 ++StartIt;
2017 // Check if this is a last store and the FI is live-on-exit.
2018 if (LoxFIs.count(FI) && (&Range == &RL.back())) {
2019 // Update store's source register.
2020 if (unsigned SR = SrcOp.getSubReg())
2021 SrcOp.setReg(HRI.getSubReg(FoundR, SR));
2022 else
2023 SrcOp.setReg(FoundR);
2024 SrcOp.setSubReg(0);
2025 // We are keeping this register live.
2026 SrcOp.setIsKill(false);
2027 } else {
2028 B.erase(SI);
2029 IM.replaceInstr(SI, CopyIn);
2030 }
2031
2032 auto EndIt = std::next(MachineBasicBlock::iterator(EI));
2033 for (auto It = StartIt; It != EndIt; It = NextIt) {
2034 MachineInstr *MI = &*It;
2035 NextIt = std::next(It);
2036 int TFI;
2037 if (!HII.isLoadFromStackSlot(MI, TFI) || TFI != FI)
2038 continue;
2039 unsigned DstR = MI->getOperand(0).getReg();
2040 assert(MI->getOperand(0).getSubReg() == 0);
2041 MachineInstr *CopyOut = nullptr;
2042 if (DstR != FoundR) {
2043 DebugLoc DL = MI->getDebugLoc();
2044 unsigned MemSize = (1U << (HII.getMemAccessSize(MI) - 1));
2045 assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2046 unsigned CopyOpc = TargetOpcode::COPY;
2047 if (HII.isSignExtendingLoad(MI))
2048 CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
2049 else if (HII.isZeroExtendingLoad(MI))
2050 CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2051 CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
2052 .addReg(FoundR, getKillRegState(MI == EI));
2053 }
2054 IM.replaceInstr(MI, CopyOut);
2055 B.erase(It);
2056 }
2057
2058 // Update the dead map.
2059 HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2060 for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2061 DM[RR].subtract(Range);
2062 } // for Range in range list
2063 }
2064 }
2065}
2066
2067
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002068void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002069 const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002070 MachineBasicBlock &MB = *AI->getParent();
2071 DebugLoc DL = AI->getDebugLoc();
2072 unsigned A = AI->getOperand(2).getImm();
2073
2074 // Have
2075 // Rd = alloca Rs, #A
2076 //
2077 // If Rs and Rd are different registers, use this sequence:
2078 // Rd = sub(r29, Rs)
2079 // r29 = sub(r29, Rs)
2080 // Rd = and(Rd, #-A) ; if necessary
2081 // r29 = and(r29, #-A) ; if necessary
2082 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2083 // otherwise, do
2084 // Rd = sub(r29, Rs)
2085 // Rd = and(Rd, #-A) ; if necessary
2086 // r29 = Rd
2087 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2088
2089 MachineOperand &RdOp = AI->getOperand(0);
2090 MachineOperand &RsOp = AI->getOperand(1);
2091 unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2092
2093 // Rd = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002094 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002095 .addReg(SP)
2096 .addReg(Rs);
2097 if (Rs != Rd) {
2098 // r29 = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002099 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002100 .addReg(SP)
2101 .addReg(Rs);
2102 }
2103 if (A > 8) {
2104 // Rd = and(Rd, #-A)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002105 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002106 .addReg(Rd)
2107 .addImm(-int64_t(A));
2108 if (Rs != Rd)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002109 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002110 .addReg(SP)
2111 .addImm(-int64_t(A));
2112 }
2113 if (Rs == Rd) {
2114 // r29 = Rd
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002115 BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002116 .addReg(Rd);
2117 }
2118 if (CF > 0) {
2119 // Rd = add(Rd, #CF)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002120 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002121 .addReg(Rd)
2122 .addImm(CF);
2123 }
2124}
2125
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002126
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002127bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
2128 const MachineFrameInfo *MFI = MF.getFrameInfo();
2129 if (!MFI->hasVarSizedObjects())
2130 return false;
2131 unsigned MaxA = MFI->getMaxAlignment();
2132 if (MaxA <= getStackAlignment())
2133 return false;
2134 return true;
2135}
2136
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002137
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00002138const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2139 const MachineFunction &MF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002140 for (auto &B : MF)
2141 for (auto &I : B)
2142 if (I.getOpcode() == Hexagon::ALIGNA)
2143 return &I;
2144 return nullptr;
2145}
2146
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002147
Sanjay Patel924879a2015-08-04 15:49:57 +00002148// FIXME: Use Function::optForSize().
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002149inline static bool isOptSize(const MachineFunction &MF) {
2150 AttributeSet AF = MF.getFunction()->getAttributes();
2151 return AF.hasAttribute(AttributeSet::FunctionIndex,
2152 Attribute::OptimizeForSize);
2153}
2154
2155inline static bool isMinSize(const MachineFunction &MF) {
Sanjay Patel924879a2015-08-04 15:49:57 +00002156 return MF.getFunction()->optForMinSize();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002157}
2158
2159
2160/// Determine whether the callee-saved register saves and restores should
2161/// be generated via inline code. If this function returns "true", inline
2162/// code will be generated. If this function returns "false", additional
2163/// checks are performed, which may still lead to the inline code.
2164bool HexagonFrameLowering::shouldInlineCSR(MachineFunction &MF,
2165 const CSIVect &CSI) const {
2166 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2167 return true;
2168 if (!isOptSize(MF) && !isMinSize(MF))
2169 if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2170 return true;
2171
2172 // Check if CSI only has double registers, and if the registers form
2173 // a contiguous block starting from D8.
2174 BitVector Regs(Hexagon::NUM_TARGET_REGS);
2175 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2176 unsigned R = CSI[i].getReg();
2177 if (!Hexagon::DoubleRegsRegClass.contains(R))
2178 return true;
2179 Regs[R] = true;
2180 }
2181 int F = Regs.find_first();
2182 if (F != Hexagon::D8)
2183 return true;
2184 while (F >= 0) {
2185 int N = Regs.find_next(F);
2186 if (N >= 0 && N != F+1)
2187 return true;
2188 F = N;
2189 }
2190
2191 return false;
2192}
2193
2194
2195bool HexagonFrameLowering::useSpillFunction(MachineFunction &MF,
2196 const CSIVect &CSI) const {
2197 if (shouldInlineCSR(MF, CSI))
2198 return false;
2199 unsigned NumCSI = CSI.size();
2200 if (NumCSI <= 1)
2201 return false;
2202
2203 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2204 : SpillFuncThreshold;
2205 return Threshold < NumCSI;
2206}
2207
2208
2209bool HexagonFrameLowering::useRestoreFunction(MachineFunction &MF,
2210 const CSIVect &CSI) const {
2211 if (shouldInlineCSR(MF, CSI))
2212 return false;
2213 unsigned NumCSI = CSI.size();
2214 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2215 : SpillFuncThreshold;
2216 return Threshold < NumCSI;
2217}