blob: 81c85c4aa211a0799b4fd5bf38fd2794986acf1b [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 }
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +0000290
291 inline bool isOptNone(const MachineFunction &MF) {
292 return MF.getFunction()->hasFnAttribute(Attribute::OptimizeNone) ||
293 MF.getTarget().getOptLevel() == CodeGenOpt::None;
294 }
295
296 inline bool isOptSize(const MachineFunction &MF) {
297 const Function &F = *MF.getFunction();
298 return F.optForSize() && !F.optForMinSize();
299 }
300
301 inline bool isMinSize(const MachineFunction &MF) {
302 return MF.getFunction()->optForMinSize();
303 }
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000304}
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000305
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000306
307/// Implements shrink-wrapping of the stack frame. By default, stack frame
308/// is created in the function entry block, and is cleaned up in every block
309/// that returns. This function finds alternate blocks: one for the frame
310/// setup (prolog) and one for the cleanup (epilog).
311void HexagonFrameLowering::findShrunkPrologEpilog(MachineFunction &MF,
312 MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const {
313 static unsigned ShrinkCounter = 0;
314
315 if (ShrinkLimit.getPosition()) {
316 if (ShrinkCounter >= ShrinkLimit)
317 return;
318 ShrinkCounter++;
319 }
320
321 auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
322 auto &HRI = *HST.getRegisterInfo();
323
324 MachineDominatorTree MDT;
325 MDT.runOnMachineFunction(MF);
326 MachinePostDominatorTree MPT;
327 MPT.runOnMachineFunction(MF);
328
329 typedef DenseMap<unsigned,unsigned> UnsignedMap;
330 UnsignedMap RPO;
331 typedef ReversePostOrderTraversal<const MachineFunction*> RPOTType;
332 RPOTType RPOT(&MF);
333 unsigned RPON = 0;
334 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I)
335 RPO[(*I)->getNumber()] = RPON++;
336
337 // Don't process functions that have loops, at least for now. Placement
338 // of prolog and epilog must take loop structure into account. For simpli-
339 // city don't do it right now.
340 for (auto &I : MF) {
341 unsigned BN = RPO[I.getNumber()];
342 for (auto SI = I.succ_begin(), SE = I.succ_end(); SI != SE; ++SI) {
343 // If found a back-edge, return.
344 if (RPO[(*SI)->getNumber()] <= BN)
345 return;
346 }
347 }
348
349 // Collect the set of blocks that need a stack frame to execute. Scan
350 // each block for uses/defs of callee-saved registers, calls, etc.
351 SmallVector<MachineBasicBlock*,16> SFBlocks;
352 BitVector CSR(Hexagon::NUM_TARGET_REGS);
353 for (const MCPhysReg *P = HRI.getCalleeSavedRegs(&MF); *P; ++P)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000354 for (MCSubRegIterator S(*P, &HRI, true); S.isValid(); ++S)
355 CSR[*S] = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000356
357 for (auto &I : MF)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000358 if (needsStackFrame(I, CSR, HRI))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000359 SFBlocks.push_back(&I);
360
361 DEBUG({
362 dbgs() << "Blocks needing SF: {";
363 for (auto &B : SFBlocks)
364 dbgs() << " BB#" << B->getNumber();
365 dbgs() << " }\n";
366 });
367 // No frame needed?
368 if (SFBlocks.empty())
369 return;
370
371 // Pick a common dominator and a common post-dominator.
372 MachineBasicBlock *DomB = SFBlocks[0];
373 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
374 DomB = MDT.findNearestCommonDominator(DomB, SFBlocks[i]);
375 if (!DomB)
376 break;
377 }
378 MachineBasicBlock *PDomB = SFBlocks[0];
379 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
380 PDomB = MPT.findNearestCommonDominator(PDomB, SFBlocks[i]);
381 if (!PDomB)
382 break;
383 }
384 DEBUG({
385 dbgs() << "Computed dom block: BB#";
386 if (DomB) dbgs() << DomB->getNumber();
387 else dbgs() << "<null>";
388 dbgs() << ", computed pdom block: BB#";
389 if (PDomB) dbgs() << PDomB->getNumber();
390 else dbgs() << "<null>";
391 dbgs() << "\n";
392 });
393 if (!DomB || !PDomB)
394 return;
395
396 // Make sure that DomB dominates PDomB and PDomB post-dominates DomB.
397 if (!MDT.dominates(DomB, PDomB)) {
398 DEBUG(dbgs() << "Dom block does not dominate pdom block\n");
399 return;
400 }
401 if (!MPT.dominates(PDomB, DomB)) {
402 DEBUG(dbgs() << "PDom block does not post-dominate dom block\n");
403 return;
404 }
405
406 // Finally, everything seems right.
407 PrologB = DomB;
408 EpilogB = PDomB;
409}
410
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000411
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000412/// Perform most of the PEI work here:
413/// - saving/restoring of the callee-saved registers,
414/// - stack frame creation and destruction.
415/// Normally, this work is distributed among various functions, but doing it
416/// in one place allows shrink-wrapping of the stack frame.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000417void HexagonFrameLowering::emitPrologue(MachineFunction &MF,
418 MachineBasicBlock &MBB) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000419 auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
420 auto &HRI = *HST.getRegisterInfo();
421
422 MachineFrameInfo *MFI = MF.getFrameInfo();
423 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
424
425 MachineBasicBlock *PrologB = &MF.front(), *EpilogB = nullptr;
426 if (EnableShrinkWrapping)
427 findShrunkPrologEpilog(MF, PrologB, EpilogB);
428
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000429 bool PrologueStubs = false;
430 insertCSRSpillsInBlock(*PrologB, CSI, HRI, PrologueStubs);
431 insertPrologueInBlock(*PrologB, PrologueStubs);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000432
433 if (EpilogB) {
434 insertCSRRestoresInBlock(*EpilogB, CSI, HRI);
435 insertEpilogueInBlock(*EpilogB);
436 } else {
437 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000438 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000439 insertCSRRestoresInBlock(B, CSI, HRI);
440
441 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000442 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000443 insertEpilogueInBlock(B);
444 }
445}
446
447
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000448void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB,
449 bool PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000450 MachineFunction &MF = *MBB.getParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000451 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000452 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000453 auto &HII = *HST.getInstrInfo();
454 auto &HRI = *HST.getRegisterInfo();
455 DebugLoc dl;
456
457 unsigned MaxAlign = std::max(MFI->getMaxAlignment(), getStackAlignment());
458
459 // Calculate the total stack frame size.
460 // Get the number of bytes to allocate from the FrameInfo.
461 unsigned FrameSize = MFI->getStackSize();
462 // Round up the max call frame size to the max alignment on the stack.
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000463 unsigned MaxCFA = alignTo(MFI->getMaxCallFrameSize(), MaxAlign);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000464 MFI->setMaxCallFrameSize(MaxCFA);
465
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000466 FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000467 MFI->setStackSize(FrameSize);
468
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000469 bool AlignStack = (MaxAlign > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000470
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000471 // Get the number of bytes to allocate from the FrameInfo.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000472 unsigned NumBytes = MFI->getStackSize();
473 unsigned SP = HRI.getStackRegister();
474 unsigned MaxCF = MFI->getMaxCallFrameSize();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000475 MachineBasicBlock::iterator InsertPt = MBB.begin();
476
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000477 auto *FuncInfo = MF.getInfo<HexagonMachineFunctionInfo>();
478 auto &AdjustRegs = FuncInfo->getAllocaAdjustInsts();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000479
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000480 for (auto MI : AdjustRegs) {
481 assert((MI->getOpcode() == Hexagon::ALLOCA) && "Expected alloca");
482 expandAlloca(MI, HII, SP, MaxCF);
483 MI->eraseFromParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000484 }
485
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000486 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000487 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000488
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000489 // Check for overflow.
490 // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
491 const unsigned int ALLOCFRAME_MAX = 16384;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000492
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000493 // Create a dummy memory operand to avoid allocframe from being treated as
494 // a volatile memory reference.
495 MachineMemOperand *MMO =
496 MF.getMachineMemOperand(MachinePointerInfo(), MachineMemOperand::MOStore,
497 4, 4);
498
499 if (NumBytes >= ALLOCFRAME_MAX) {
500 // Emit allocframe(#0).
501 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
502 .addImm(0)
503 .addMemOperand(MMO);
504
505 // Subtract offset from frame pointer.
506 // We use a caller-saved non-parameter register for that.
507 unsigned CallerSavedReg = HRI.getFirstCallerSavedNonParamReg();
508 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CONST32_Int_Real),
509 CallerSavedReg).addImm(NumBytes);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000510 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_sub), SP)
511 .addReg(SP)
512 .addReg(CallerSavedReg);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000513 } else {
514 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
515 .addImm(NumBytes)
516 .addMemOperand(MMO);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000517 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000518
519 if (AlignStack) {
520 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
521 .addReg(SP)
522 .addImm(-int64_t(MaxAlign));
523 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000524
525 // If the stack-checking is enabled, and we spilled the callee-saved
526 // registers inline (i.e. did not use a spill function), then call
527 // the stack checker directly.
528 if (EnableStackOVFSanitizer && !PrologueStubs)
529 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CALLstk))
530 .addExternalSymbol("__runtime_stack_check");
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000531}
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000532
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000533void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
534 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000535 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000536 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000537
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000538 auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
539 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000540 auto &HRI = *HST.getRegisterInfo();
541 unsigned SP = HRI.getStackRegister();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000542
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000543 MachineInstr *RetI = nullptr;
544 for (auto &I : MBB) {
545 if (!I.isReturn())
546 continue;
547 RetI = &I;
548 break;
549 }
550 unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
551
552 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
553 DebugLoc DL;
554 if (InsertPt != MBB.end())
555 DL = InsertPt->getDebugLoc();
556 else if (!MBB.empty())
557 DL = std::prev(MBB.end())->getDebugLoc();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000558
559 // Handle EH_RETURN.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000560 if (RetOpc == Hexagon::EH_RETURN_JMPR) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000561 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
562 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::A2_add), SP)
563 .addReg(SP)
564 .addReg(Hexagon::R28);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000565 return;
566 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000567
568 // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
569 // frame instruction if we encounter it.
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000570 if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
571 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000572 MachineBasicBlock::iterator It = RetI;
573 ++It;
574 // Delete all instructions after the RESTORE (except labels).
575 while (It != MBB.end()) {
576 if (!It->isLabel())
577 It = MBB.erase(It);
578 else
579 ++It;
Jyotsna Verma300f0b92013-05-10 20:27:34 +0000580 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000581 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000582 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000583
584 // It is possible that the restoring code is a call to a library function.
585 // All of the restore* functions include "deallocframe", so we need to make
586 // sure that we don't add an extra one.
587 bool NeedsDeallocframe = true;
588 if (!MBB.empty() && InsertPt != MBB.begin()) {
589 MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
590 unsigned COpc = PrevIt->getOpcode();
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000591 if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
592 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000593 NeedsDeallocframe = false;
594 }
595
596 if (!NeedsDeallocframe)
597 return;
598 // If the returning instruction is JMPret, replace it with dealloc_return,
599 // otherwise just add deallocframe. The function could be returning via a
600 // tail call.
601 if (RetOpc != Hexagon::JMPret || DisableDeallocRet) {
602 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
603 return;
604 }
605 unsigned NewOpc = Hexagon::L4_return;
606 MachineInstr *NewI = BuildMI(MBB, RetI, DL, HII.get(NewOpc));
607 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000608 NewI->copyImplicitOps(MF, *RetI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000609 MBB.erase(RetI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000610}
611
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000612
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000613namespace {
614 bool IsAllocFrame(MachineBasicBlock::const_iterator It) {
615 if (!It->isBundle())
616 return It->getOpcode() == Hexagon::S2_allocframe;
617 auto End = It->getParent()->instr_end();
Duncan P. N. Exon Smithd84f6002016-02-22 21:30:15 +0000618 MachineBasicBlock::const_instr_iterator I = It.getInstrIterator();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000619 while (++I != End && I->isBundled())
620 if (I->getOpcode() == Hexagon::S2_allocframe)
621 return true;
622 return false;
623 }
624
625 MachineBasicBlock::iterator FindAllocFrame(MachineBasicBlock &B) {
626 for (auto &I : B)
627 if (IsAllocFrame(I))
628 return I;
629 return B.end();
630 }
631}
632
633
634void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
635 for (auto &B : MF) {
636 auto AF = FindAllocFrame(B);
637 if (AF == B.end())
638 continue;
639 insertCFIInstructionsAt(B, ++AF);
640 }
641}
642
643
644void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
645 MachineBasicBlock::iterator At) const {
646 MachineFunction &MF = *MBB.getParent();
647 MachineFrameInfo *MFI = MF.getFrameInfo();
648 MachineModuleInfo &MMI = MF.getMMI();
649 auto &HST = MF.getSubtarget<HexagonSubtarget>();
650 auto &HII = *HST.getInstrInfo();
651 auto &HRI = *HST.getRegisterInfo();
652
653 // If CFI instructions have debug information attached, something goes
654 // wrong with the final assembly generation: the prolog_end is placed
655 // in a wrong location.
656 DebugLoc DL;
657 const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
658
659 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
660
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000661 if (hasFP(MF)) {
662 unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
663 unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000664
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000665 // Define CFA via an offset from the value of FP.
666 //
667 // -8 -4 0 (SP)
668 // --+----+----+---------------------
669 // | FP | LR | increasing addresses -->
670 // --+----+----+---------------------
671 // | +-- Old SP (before allocframe)
672 // +-- New FP (after allocframe)
673 //
674 // MCCFIInstruction::createDefCfa subtracts the offset from the register.
675 // MCCFIInstruction::createOffset takes the offset without sign change.
676 auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
677 BuildMI(MBB, At, DL, CFID)
678 .addCFIIndex(MMI.addFrameInst(DefCfa));
679 // R31 (return addr) = CFA - 4
680 auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
681 BuildMI(MBB, At, DL, CFID)
682 .addCFIIndex(MMI.addFrameInst(OffR31));
683 // R30 (frame ptr) = CFA - 8
684 auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
685 BuildMI(MBB, At, DL, CFID)
686 .addCFIIndex(MMI.addFrameInst(OffR30));
687 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000688
689 static unsigned int RegsToMove[] = {
690 Hexagon::R1, Hexagon::R0, Hexagon::R3, Hexagon::R2,
691 Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
692 Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
693 Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
694 Hexagon::D0, Hexagon::D1, Hexagon::D8, Hexagon::D9,
695 Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
696 Hexagon::NoRegister
697 };
698
699 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
700
701 for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
702 unsigned Reg = RegsToMove[i];
703 auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
704 return C.getReg() == Reg;
705 };
706 auto F = std::find_if(CSI.begin(), CSI.end(), IfR);
707 if (F == CSI.end())
708 continue;
709
710 // Subtract 8 to make room for R30 and R31, which are added above.
711 unsigned FrameReg;
712 int64_t Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg) - 8;
713
714 if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
715 unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
716 auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
717 Offset);
718 BuildMI(MBB, At, DL, CFID)
719 .addCFIIndex(MMI.addFrameInst(OffReg));
720 } else {
721 // Split the double regs into subregs, and generate appropriate
722 // cfi_offsets.
723 // The only reason, we are split double regs is, llvm-mc does not
724 // understand paired registers for cfi_offset.
725 // Eg .cfi_offset r1:0, -64
726
727 unsigned HiReg = HRI.getSubReg(Reg, Hexagon::subreg_hireg);
728 unsigned LoReg = HRI.getSubReg(Reg, Hexagon::subreg_loreg);
729 unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
730 unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
731 auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
732 Offset+4);
733 BuildMI(MBB, At, DL, CFID)
734 .addCFIIndex(MMI.addFrameInst(OffHi));
735 auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
736 Offset);
737 BuildMI(MBB, At, DL, CFID)
738 .addCFIIndex(MMI.addFrameInst(OffLo));
739 }
740 }
741}
742
743
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000744bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000745 auto &MFI = *MF.getFrameInfo();
746 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
747
748 bool HasFixed = MFI.getNumFixedObjects();
749 bool HasPrealloc = const_cast<MachineFrameInfo&>(MFI)
750 .getLocalFrameObjectCount();
751 bool HasExtraAlign = HRI.needsStackRealignment(MF);
752 bool HasAlloca = MFI.hasVarSizedObjects();
753
754 // Insert ALLOCFRAME if we need to or at -O0 for the debugger. Think
755 // that this shouldn't be required, but doing so now because gcc does and
756 // gdb can't break at the start of the function without it. Will remove if
757 // this turns out to be a gdb bug.
758 //
759 if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
760 return true;
761
762 // By default we want to use SP (since it's always there). FP requires
763 // some setup (i.e. ALLOCFRAME).
764 // Fixed and preallocated objects need FP if the distance from them to
765 // the SP is unknown (as is with alloca or aligna).
766 if ((HasFixed || HasPrealloc) && (HasAlloca || HasExtraAlign))
767 return true;
768
769 if (MFI.getStackSize() > 0) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000770 if (EnableStackOVFSanitizer || UseAllocframe)
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000771 return true;
772 }
773
774 if (MFI.hasCalls() ||
775 MF.getInfo<HexagonMachineFunctionInfo>()->hasClobberLR())
776 return true;
777
778 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000779}
780
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000781
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000782enum SpillKind {
783 SK_ToMem,
784 SK_FromMem,
785 SK_FromMemTailcall
786};
787
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000788static const char *getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType,
789 bool Stkchk = false) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000790 const char * V4SpillToMemoryFunctions[] = {
791 "__save_r16_through_r17",
792 "__save_r16_through_r19",
793 "__save_r16_through_r21",
794 "__save_r16_through_r23",
795 "__save_r16_through_r25",
796 "__save_r16_through_r27" };
797
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000798 const char * V4SpillToMemoryStkchkFunctions[] = {
799 "__save_r16_through_r17_stkchk",
800 "__save_r16_through_r19_stkchk",
801 "__save_r16_through_r21_stkchk",
802 "__save_r16_through_r23_stkchk",
803 "__save_r16_through_r25_stkchk",
804 "__save_r16_through_r27_stkchk" };
805
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000806 const char * V4SpillFromMemoryFunctions[] = {
807 "__restore_r16_through_r17_and_deallocframe",
808 "__restore_r16_through_r19_and_deallocframe",
809 "__restore_r16_through_r21_and_deallocframe",
810 "__restore_r16_through_r23_and_deallocframe",
811 "__restore_r16_through_r25_and_deallocframe",
812 "__restore_r16_through_r27_and_deallocframe" };
813
814 const char * V4SpillFromMemoryTailcallFunctions[] = {
815 "__restore_r16_through_r17_and_deallocframe_before_tailcall",
816 "__restore_r16_through_r19_and_deallocframe_before_tailcall",
817 "__restore_r16_through_r21_and_deallocframe_before_tailcall",
818 "__restore_r16_through_r23_and_deallocframe_before_tailcall",
819 "__restore_r16_through_r25_and_deallocframe_before_tailcall",
820 "__restore_r16_through_r27_and_deallocframe_before_tailcall"
821 };
822
823 const char **SpillFunc = nullptr;
824
825 switch(SpillType) {
826 case SK_ToMem:
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000827 SpillFunc = Stkchk ? V4SpillToMemoryStkchkFunctions
828 : V4SpillToMemoryFunctions;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000829 break;
830 case SK_FromMem:
831 SpillFunc = V4SpillFromMemoryFunctions;
832 break;
833 case SK_FromMemTailcall:
834 SpillFunc = V4SpillFromMemoryTailcallFunctions;
835 break;
836 }
837 assert(SpillFunc && "Unknown spill kind");
838
839 // Spill all callee-saved registers up to the highest register used.
840 switch (MaxReg) {
841 case Hexagon::R17:
842 return SpillFunc[0];
843 case Hexagon::R19:
844 return SpillFunc[1];
845 case Hexagon::R21:
846 return SpillFunc[2];
847 case Hexagon::R23:
848 return SpillFunc[3];
849 case Hexagon::R25:
850 return SpillFunc[4];
851 case Hexagon::R27:
852 return SpillFunc[5];
853 default:
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000854 llvm_unreachable("Unhandled maximum callee save register");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000855 }
856 return 0;
857}
858
859/// Adds all callee-saved registers up to MaxReg to the instruction.
860static void addCalleeSaveRegistersAsImpOperand(MachineInstr *Inst,
861 unsigned MaxReg, bool IsDef) {
862 // Add the callee-saved registers as implicit uses.
863 for (unsigned R = Hexagon::R16; R <= MaxReg; ++R) {
864 MachineOperand ImpUse = MachineOperand::CreateReg(R, IsDef, true);
865 Inst->addOperand(ImpUse);
866 }
867}
868
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000869
James Y Knight5567baf2015-08-15 02:32:35 +0000870int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF,
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000871 int FI, unsigned &FrameReg) const {
872 auto &MFI = *MF.getFrameInfo();
873 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000874
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000875 int Offset = MFI.getObjectOffset(FI);
876 bool HasAlloca = MFI.hasVarSizedObjects();
877 bool HasExtraAlign = HRI.needsStackRealignment(MF);
878 bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
James Y Knight5567baf2015-08-15 02:32:35 +0000879
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000880 unsigned SP = HRI.getStackRegister(), FP = HRI.getFrameRegister();
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +0000881 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
882 unsigned AP = HMFI.getStackAlignBasePhysReg();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000883 unsigned FrameSize = MFI.getStackSize();
884
885 bool UseFP = false, UseAP = false; // Default: use SP (except at -O0).
886 // Use FP at -O0, except when there are objects with extra alignment.
887 // That additional alignment requirement may cause a pad to be inserted,
888 // which will make it impossible to use FP to access objects located
889 // past the pad.
890 if (NoOpt && !HasExtraAlign)
891 UseFP = true;
892 if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
893 // Fixed and preallocated objects will be located before any padding
894 // so FP must be used to access them.
895 UseFP |= (HasAlloca || HasExtraAlign);
896 } else {
897 if (HasAlloca) {
898 if (HasExtraAlign)
899 UseAP = true;
900 else
901 UseFP = true;
902 }
903 }
904
905 // If FP was picked, then there had better be FP.
906 bool HasFP = hasFP(MF);
907 assert((HasFP || !UseFP) && "This function must have frame pointer");
908
909 // Having FP implies allocframe. Allocframe will store extra 8 bytes:
910 // FP/LR. If the base register is used to access an object across these
911 // 8 bytes, then the offset will need to be adjusted by 8.
912 //
913 // After allocframe:
914 // HexagonISelLowering adds 8 to ---+
915 // the offsets of all stack-based |
916 // arguments (*) |
917 // |
918 // getObjectOffset < 0 0 8 getObjectOffset >= 8
919 // ------------------------+-----+------------------------> increasing
920 // <local objects> |FP/LR| <input arguments> addresses
921 // -----------------+------+-----+------------------------>
922 // | |
923 // SP/AP point --+ +-- FP points here (**)
924 // somewhere on
925 // this side of FP/LR
926 //
927 // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
928 // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
929
930 // The lowering assumes that FP/LR is present, and so the offsets of
931 // the formal arguments start at 8. If FP/LR is not there we need to
932 // reduce the offset by 8.
933 if (Offset > 0 && !HasFP)
934 Offset -= 8;
935
936 if (UseFP)
937 FrameReg = FP;
938 else if (UseAP)
939 FrameReg = AP;
940 else
941 FrameReg = SP;
942
943 // Calculate the actual offset in the instruction. If there is no FP
944 // (in other words, no allocframe), then SP will not be adjusted (i.e.
945 // there will be no SP -= FrameSize), so the frame size should not be
946 // added to the calculated offset.
947 int RealOffset = Offset;
948 if (!UseFP && !UseAP && HasFP)
949 RealOffset = FrameSize+Offset;
950 return RealOffset;
Jakob Stoklund Olesen0b97dbc2012-05-30 22:40:03 +0000951}
952
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000953
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000954bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000955 const CSIVect &CSI, const HexagonRegisterInfo &HRI,
956 bool &PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000957 if (CSI.empty())
958 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000959
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000960 MachineBasicBlock::iterator MI = MBB.begin();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000961 PrologueStubs = false;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000962 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000963 auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000964
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000965 if (useSpillFunction(MF, CSI)) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000966 PrologueStubs = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000967 unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000968 bool StkOvrFlowEnabled = EnableStackOVFSanitizer;
969 const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem,
970 StkOvrFlowEnabled);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000971 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
972 bool IsPIC = HTM.getRelocationModel() == Reloc::PIC_;
973
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000974 // Call spill function.
975 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000976 unsigned SpillOpc;
977 if (StkOvrFlowEnabled)
978 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC
979 : Hexagon::SAVE_REGISTERS_CALL_V4STK;
980 else
981 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
982 : Hexagon::SAVE_REGISTERS_CALL_V4;
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000983
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000984 MachineInstr *SaveRegsCall =
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000985 BuildMI(MBB, MI, DL, HII.get(SpillOpc))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000986 .addExternalSymbol(SpillFun);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000987 // Add callee-saved registers as use.
988 addCalleeSaveRegistersAsImpOperand(SaveRegsCall, MaxReg, false);
989 // Add live in registers.
990 for (unsigned I = 0; I < CSI.size(); ++I)
991 MBB.addLiveIn(CSI[I].getReg());
992 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000993 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000994
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000995 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000996 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000997 // Add live in registers. We treat eh_return callee saved register r0 - r3
998 // specially. They are not really callee saved registers as they are not
999 // supposed to be killed.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001000 bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
1001 int FI = CSI[i].getFrameIdx();
1002 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001003 HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001004 if (IsKill)
1005 MBB.addLiveIn(Reg);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001006 }
1007 return true;
1008}
1009
1010
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001011bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
1012 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
1013 if (CSI.empty())
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001014 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001015
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001016 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1017 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001018 auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001019
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001020 if (useRestoreFunction(MF, CSI)) {
1021 bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
1022 unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
1023 SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
1024 const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001025 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
1026 bool IsPIC = HTM.getRelocationModel() == Reloc::PIC_;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001027
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001028 // Call spill function.
1029 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
1030 : MBB.getLastNonDebugInstr()->getDebugLoc();
1031 MachineInstr *DeallocCall = nullptr;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001032
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001033 if (HasTC) {
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001034 unsigned ROpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
1035 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001036 DeallocCall = BuildMI(MBB, MI, DL, HII.get(ROpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001037 .addExternalSymbol(RestoreFn);
1038 } else {
1039 // The block has a return.
1040 MachineBasicBlock::iterator It = MBB.getFirstTerminator();
1041 assert(It->isReturn() && std::next(It) == MBB.end());
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001042 unsigned ROpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
1043 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001044 DeallocCall = BuildMI(MBB, It, DL, HII.get(ROpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001045 .addExternalSymbol(RestoreFn);
1046 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +00001047 DeallocCall->copyImplicitOps(MF, *It);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001048 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001049 addCalleeSaveRegistersAsImpOperand(DeallocCall, MaxR, true);
1050 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001051 }
1052
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001053 for (unsigned i = 0; i < CSI.size(); ++i) {
1054 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001055 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1056 int FI = CSI[i].getFrameIdx();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001057 HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001058 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001059
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001060 return true;
1061}
1062
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001063
1064void HexagonFrameLowering::eliminateCallFramePseudoInstr(MachineFunction &MF,
1065 MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00001066 MachineInstr &MI = *I;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001067 unsigned Opc = MI.getOpcode();
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001068 (void)Opc; // Silence compiler warning.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001069 assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1070 "Cannot handle this call frame pseudo instruction");
Eli Bendersky8da87162013-02-21 20:05:00 +00001071 MBB.erase(I);
1072}
1073
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001074
1075void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1076 MachineFunction &MF, RegScavenger *RS) const {
1077 // If this function has uses aligned stack and also has variable sized stack
1078 // objects, then we need to map all spill slots to fixed positions, so that
1079 // they can be accessed through FP. Otherwise they would have to be accessed
1080 // via AP, which may not be available at the particular place in the program.
1081 MachineFrameInfo *MFI = MF.getFrameInfo();
1082 bool HasAlloca = MFI->hasVarSizedObjects();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001083 bool NeedsAlign = (MFI->getMaxAlignment() > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001084
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001085 if (!HasAlloca || !NeedsAlign)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001086 return;
1087
1088 unsigned LFS = MFI->getLocalFrameSize();
1089 int Offset = -LFS;
1090 for (int i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
1091 if (!MFI->isSpillSlotObjectIndex(i) || MFI->isDeadObjectIndex(i))
1092 continue;
1093 int S = MFI->getObjectSize(i);
1094 LFS += S;
1095 Offset -= S;
1096 MFI->mapLocalFrameObject(i, Offset);
1097 }
1098
1099 MFI->setLocalFrameSize(LFS);
1100 unsigned A = MFI->getLocalFrameMaxAlign();
1101 assert(A <= 8 && "Unexpected local frame alignment");
1102 if (A == 0)
1103 MFI->setLocalFrameMaxAlign(8);
1104 MFI->setUseLocalStackAllocationBlock(true);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001105
1106 // Set the physical aligned-stack base address register.
1107 unsigned AP = 0;
1108 if (const MachineInstr *AI = getAlignaInstr(MF))
1109 AP = AI->getOperand(0).getReg();
1110 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1111 HMFI.setStackAlignBasePhysReg(AP);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001112}
1113
1114/// Returns true if there is no caller saved registers available.
1115static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
1116 const HexagonRegisterInfo &HRI) {
1117 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001118 BitVector Reserved = HRI.getReservedRegs(MF);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001119
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001120 auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1121 for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1122 if (MRI.isPhysRegUsed(*AI))
1123 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001124 return false;
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001125 };
1126
1127 // Check for an unused caller-saved register.
1128 for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF); *P; ++P)
1129 if (!IsUsed(*P))
1130 return false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001131 // All caller-saved registers are used.
1132 return true;
1133}
1134
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001135
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001136#ifndef NDEBUG
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001137static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001138 dbgs() << '{';
1139 for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1140 unsigned R = x;
1141 dbgs() << ' ' << PrintReg(R, &TRI);
1142 }
1143 dbgs() << " }";
1144}
1145#endif
1146
1147
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001148bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1149 const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
Krzysztof Parzyszek27ba19a12015-04-23 20:42:20 +00001150 DEBUG(dbgs() << LLVM_FUNCTION_NAME << " on "
Krzysztof Parzyszeked75e7a2015-04-23 20:57:39 +00001151 << MF.getFunction()->getName() << '\n');
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001152 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001153 BitVector SRegs(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001154
1155 // Generate a set of unique, callee-saved registers (SRegs), where each
1156 // register in the set is maximal in terms of sub-/super-register relation,
1157 // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1158
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001159 // (1) For each callee-saved register, add that register and all of its
1160 // sub-registers to SRegs.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001161 DEBUG(dbgs() << "Initial CS registers: {");
1162 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1163 unsigned R = CSI[i].getReg();
1164 DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1165 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1166 SRegs[*SR] = true;
1167 }
1168 DEBUG(dbgs() << " }\n");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001169 DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001170
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001171 // (2) For each reserved register, remove that register and all of its
1172 // sub- and super-registers from SRegs.
1173 BitVector Reserved = TRI->getReservedRegs(MF);
1174 for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1175 unsigned R = x;
1176 for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1177 SRegs[*SR] = false;
1178 }
1179 DEBUG(dbgs() << "Res: "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1180 DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1181
1182 // (3) Collect all registers that have at least one sub-register in SRegs,
1183 // and also have no sub-registers that are reserved. These will be the can-
1184 // didates for saving as a whole instead of their individual sub-registers.
1185 // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1186 BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001187 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1188 unsigned R = x;
1189 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1190 TmpSup[*SR] = true;
1191 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001192 for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1193 unsigned R = x;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001194 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1195 if (!Reserved[*SR])
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001196 continue;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001197 TmpSup[R] = false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001198 break;
1199 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001200 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001201 DEBUG(dbgs() << "TmpSup: "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001202
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001203 // (4) Include all super-registers found in (3) into SRegs.
1204 SRegs |= TmpSup;
1205 DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001206
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001207 // (5) For each register R in SRegs, if any super-register of R is in SRegs,
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001208 // remove R from SRegs.
1209 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1210 unsigned R = x;
1211 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1212 if (!SRegs[*SR])
1213 continue;
1214 SRegs[R] = false;
1215 break;
1216 }
1217 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001218 DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001219
1220 // Now, for each register that has a fixed stack slot, create the stack
1221 // object for it.
1222 CSI.clear();
1223
1224 typedef TargetFrameLowering::SpillSlot SpillSlot;
1225 unsigned NumFixed;
1226 int MinOffset = 0; // CS offsets are negative.
1227 const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1228 for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1229 if (!SRegs[S->Reg])
1230 continue;
1231 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
1232 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), S->Offset);
1233 MinOffset = std::min(MinOffset, S->Offset);
1234 CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1235 SRegs[S->Reg] = false;
1236 }
1237
1238 // There can be some registers that don't have fixed slots. For example,
1239 // we need to store R0-R3 in functions with exception handling. For each
1240 // such register, create a non-fixed stack object.
1241 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1242 unsigned R = x;
1243 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
1244 int Off = MinOffset - RC->getSize();
1245 unsigned Align = std::min(RC->getAlignment(), getStackAlignment());
1246 assert(isPowerOf2_32(Align));
1247 Off &= -Align;
1248 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), Off);
1249 MinOffset = std::min(MinOffset, Off);
1250 CSI.push_back(CalleeSavedInfo(R, FI));
1251 SRegs[R] = false;
1252 }
1253
1254 DEBUG({
1255 dbgs() << "CS information: {";
1256 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1257 int FI = CSI[i].getFrameIdx();
1258 int Off = MFI->getObjectOffset(FI);
1259 dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1260 if (Off >= 0)
1261 dbgs() << '+';
1262 dbgs() << Off;
1263 }
1264 dbgs() << " }\n";
1265 });
1266
1267#ifndef NDEBUG
1268 // Verify that all registers were handled.
1269 bool MissedReg = false;
1270 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1271 unsigned R = x;
1272 dbgs() << PrintReg(R, TRI) << ' ';
1273 MissedReg = true;
1274 }
1275 if (MissedReg)
1276 llvm_unreachable("...there are unhandled callee-saved registers!");
1277#endif
1278
1279 return true;
1280}
1281
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001282
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001283bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1284 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1285 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1286 MachineInstr *MI = &*It;
1287 DebugLoc DL = MI->getDebugLoc();
1288 unsigned DstR = MI->getOperand(0).getReg();
1289 unsigned SrcR = MI->getOperand(1).getReg();
1290 if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1291 !Hexagon::ModRegsRegClass.contains(SrcR))
1292 return false;
1293
1294 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1295 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR)
1296 .addOperand(MI->getOperand(1));
1297 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1298 .addReg(TmpR, RegState::Kill);
1299
1300 NewRegs.push_back(TmpR);
1301 B.erase(It);
1302 return true;
1303}
1304
1305bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1306 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1307 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1308 MachineInstr *MI = &*It;
1309 DebugLoc DL = MI->getDebugLoc();
1310 unsigned Opc = MI->getOpcode();
1311 unsigned SrcR = MI->getOperand(2).getReg();
1312 bool IsKill = MI->getOperand(2).isKill();
1313
1314 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1315 int FI = MI->getOperand(0).getIndex();
1316
1317 // TmpR = C2_tfrpr SrcR if SrcR is a predicate register
1318 // TmpR = A2_tfrcrr SrcR if SrcR is a modifier register
1319 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1320 unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1321 : Hexagon::A2_tfrcrr;
1322 BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1323 .addReg(SrcR, getKillRegState(IsKill));
1324
1325 // S2_storeri_io FI, 0, TmpR
1326 BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1327 .addFrameIndex(FI)
1328 .addImm(0)
1329 .addReg(TmpR, RegState::Kill)
1330 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1331
1332 NewRegs.push_back(TmpR);
1333 B.erase(It);
1334 return true;
1335}
1336
1337bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1338 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1339 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1340 MachineInstr *MI = &*It;
1341 DebugLoc DL = MI->getDebugLoc();
1342 unsigned Opc = MI->getOpcode();
1343 unsigned DstR = MI->getOperand(0).getReg();
1344
1345 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1346 int FI = MI->getOperand(1).getIndex();
1347
1348 // TmpR = L2_loadri_io FI, 0
1349 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1350 BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1351 .addFrameIndex(FI)
1352 .addImm(0)
1353 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1354
1355 // DstR = C2_tfrrp TmpR if DstR is a predicate register
1356 // DstR = A2_tfrrcr TmpR if DstR is a modifier register
1357 unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1358 : Hexagon::A2_tfrrcr;
1359 BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1360 .addReg(TmpR, RegState::Kill);
1361
1362 NewRegs.push_back(TmpR);
1363 B.erase(It);
1364 return true;
1365}
1366
1367
1368bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1369 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1370 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1371 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1372 MachineInstr *MI = &*It;
1373 DebugLoc DL = MI->getDebugLoc();
1374 unsigned SrcR = MI->getOperand(2).getReg();
1375 bool IsKill = MI->getOperand(2).isKill();
1376
1377 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1378 int FI = MI->getOperand(0).getIndex();
1379
1380 bool Is128B = HST.useHVXDblOps();
1381 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1382 : &Hexagon::VectorRegs128BRegClass;
1383
1384 // Insert transfer to general vector register.
1385 // TmpR0 = A2_tfrsi 0x01010101
1386 // TmpR1 = V6_vandqrt Qx, TmpR0
1387 // store FI, 0, TmpR1
1388 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1389 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1390
1391 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1392 .addImm(0x01010101);
1393
1394 unsigned VandOpc = !Is128B ? Hexagon::V6_vandqrt : Hexagon::V6_vandqrt_128B;
1395 BuildMI(B, It, DL, HII.get(VandOpc), TmpR1)
1396 .addReg(SrcR, getKillRegState(IsKill))
1397 .addReg(TmpR0, RegState::Kill);
1398
1399 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1400 HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1401 expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1402
1403 NewRegs.push_back(TmpR0);
1404 NewRegs.push_back(TmpR1);
1405 B.erase(It);
1406 return true;
1407}
1408
1409bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1410 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1411 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1412 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1413 MachineInstr *MI = &*It;
1414 DebugLoc DL = MI->getDebugLoc();
1415 unsigned DstR = MI->getOperand(0).getReg();
1416
1417 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1418 int FI = MI->getOperand(1).getIndex();
1419
1420 bool Is128B = HST.useHVXDblOps();
1421 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1422 : &Hexagon::VectorRegs128BRegClass;
1423
1424 // TmpR0 = A2_tfrsi 0x01010101
1425 // TmpR1 = load FI, 0
1426 // DstR = V6_vandvrt TmpR1, TmpR0
1427 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1428 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1429
1430 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1431 .addImm(0x01010101);
1432 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1433 HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1434 expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1435
1436 unsigned VandOpc = !Is128B ? Hexagon::V6_vandvrt : Hexagon::V6_vandvrt_128B;
1437 BuildMI(B, It, DL, HII.get(VandOpc), DstR)
1438 .addReg(TmpR1, RegState::Kill)
1439 .addReg(TmpR0, RegState::Kill);
1440
1441 NewRegs.push_back(TmpR0);
1442 NewRegs.push_back(TmpR1);
1443 B.erase(It);
1444 return true;
1445}
1446
1447bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1448 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1449 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1450 MachineFunction &MF = *B.getParent();
1451 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1452 auto &MFI = *MF.getFrameInfo();
1453 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1454 MachineInstr *MI = &*It;
1455 DebugLoc DL = MI->getDebugLoc();
1456
1457 unsigned SrcR = MI->getOperand(2).getReg();
1458 unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::subreg_loreg);
1459 unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::subreg_hireg);
1460 bool IsKill = MI->getOperand(2).isKill();
1461
1462 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1463 int FI = MI->getOperand(0).getIndex();
1464
1465 bool Is128B = HST.useHVXDblOps();
1466 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1467 : &Hexagon::VectorRegs128BRegClass;
1468 unsigned Size = RC->getSize();
1469 unsigned NeedAlign = RC->getAlignment();
1470 unsigned HasAlign = MFI.getObjectAlignment(FI);
1471 unsigned StoreOpc;
1472
1473 // Store low part.
1474 if (NeedAlign <= HasAlign)
1475 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1476 else
1477 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1478
1479 BuildMI(B, It, DL, HII.get(StoreOpc))
1480 .addFrameIndex(FI)
1481 .addImm(0)
1482 .addReg(SrcLo, getKillRegState(IsKill))
1483 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1484
1485 // Load high part.
1486 if (NeedAlign <= MinAlign(HasAlign, Size))
1487 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1488 else
1489 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1490
1491 BuildMI(B, It, DL, HII.get(StoreOpc))
1492 .addFrameIndex(FI)
1493 .addImm(Size)
1494 .addReg(SrcHi, getKillRegState(IsKill))
1495 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1496
1497 B.erase(It);
1498 return true;
1499}
1500
1501bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1502 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1503 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1504 MachineFunction &MF = *B.getParent();
1505 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1506 auto &MFI = *MF.getFrameInfo();
1507 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1508 MachineInstr *MI = &*It;
1509 DebugLoc DL = MI->getDebugLoc();
1510
1511 unsigned DstR = MI->getOperand(0).getReg();
1512 unsigned DstHi = HRI.getSubReg(DstR, Hexagon::subreg_hireg);
1513 unsigned DstLo = HRI.getSubReg(DstR, Hexagon::subreg_loreg);
1514
1515 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1516 int FI = MI->getOperand(1).getIndex();
1517
1518 bool Is128B = HST.useHVXDblOps();
1519 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1520 : &Hexagon::VectorRegs128BRegClass;
1521 unsigned Size = RC->getSize();
1522 unsigned NeedAlign = RC->getAlignment();
1523 unsigned HasAlign = MFI.getObjectAlignment(FI);
1524 unsigned LoadOpc;
1525
1526 // Load low part.
1527 if (NeedAlign <= HasAlign)
1528 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1529 else
1530 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1531
1532 BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1533 .addFrameIndex(FI)
1534 .addImm(0)
1535 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1536
1537 // Load high part.
1538 if (NeedAlign <= MinAlign(HasAlign, Size))
1539 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1540 else
1541 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1542
1543 BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1544 .addFrameIndex(FI)
1545 .addImm(Size)
1546 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1547
1548 B.erase(It);
1549 return true;
1550}
1551
1552bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1553 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1554 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1555 MachineFunction &MF = *B.getParent();
1556 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1557 auto &MFI = *MF.getFrameInfo();
1558 MachineInstr *MI = &*It;
1559 DebugLoc DL = MI->getDebugLoc();
1560
1561 unsigned SrcR = MI->getOperand(2).getReg();
1562 bool IsKill = MI->getOperand(2).isKill();
1563
1564 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1565 int FI = MI->getOperand(0).getIndex();
1566
1567 bool Is128B = HST.useHVXDblOps();
1568 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1569 : &Hexagon::VectorRegs128BRegClass;
1570
1571 unsigned NeedAlign = RC->getAlignment();
1572 unsigned HasAlign = MFI.getObjectAlignment(FI);
1573 unsigned StoreOpc;
1574
1575 if (NeedAlign <= HasAlign)
1576 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1577 else
1578 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1579
1580 BuildMI(B, It, DL, HII.get(StoreOpc))
1581 .addFrameIndex(FI)
1582 .addImm(0)
1583 .addReg(SrcR, getKillRegState(IsKill))
1584 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1585
1586 B.erase(It);
1587 return true;
1588}
1589
1590bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
1591 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1592 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1593 MachineFunction &MF = *B.getParent();
1594 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1595 auto &MFI = *MF.getFrameInfo();
1596 MachineInstr *MI = &*It;
1597 DebugLoc DL = MI->getDebugLoc();
1598
1599 unsigned DstR = MI->getOperand(0).getReg();
1600
1601 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1602 int FI = MI->getOperand(1).getIndex();
1603
1604 bool Is128B = HST.useHVXDblOps();
1605 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1606 : &Hexagon::VectorRegs128BRegClass;
1607
1608 unsigned NeedAlign = RC->getAlignment();
1609 unsigned HasAlign = MFI.getObjectAlignment(FI);
1610 unsigned LoadOpc;
1611
1612 if (NeedAlign <= HasAlign)
1613 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1614 else
1615 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1616
1617 BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1618 .addFrameIndex(FI)
1619 .addImm(0)
1620 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1621
1622 B.erase(It);
1623 return true;
1624}
1625
1626
1627bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1628 SmallVectorImpl<unsigned> &NewRegs) const {
1629 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001630 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001631 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001632 bool Changed = false;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001633
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001634 for (auto &B : MF) {
1635 // Traverse the basic block.
1636 MachineBasicBlock::iterator NextI;
1637 for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1638 MachineInstr *MI = &*I;
1639 NextI = std::next(I);
1640 unsigned Opc = MI->getOpcode();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001641
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001642 switch (Opc) {
1643 case TargetOpcode::COPY:
1644 Changed = expandCopy(B, I, MRI, HII, NewRegs);
1645 break;
1646 case Hexagon::STriw_pred:
1647 case Hexagon::STriw_mod:
1648 Changed = expandStoreInt(B, I, MRI, HII, NewRegs);
1649 break;
1650 case Hexagon::LDriw_pred:
1651 case Hexagon::LDriw_mod:
1652 Changed = expandLoadInt(B, I, MRI, HII, NewRegs);
1653 break;
1654 case Hexagon::STriq_pred_V6:
1655 case Hexagon::STriq_pred_V6_128B:
1656 Changed = expandStoreVecPred(B, I, MRI, HII, NewRegs);
1657 break;
1658 case Hexagon::LDriq_pred_V6:
1659 case Hexagon::LDriq_pred_V6_128B:
1660 Changed = expandLoadVecPred(B, I, MRI, HII, NewRegs);
1661 break;
1662 case Hexagon::LDrivv_pseudo_V6:
1663 case Hexagon::LDrivv_pseudo_V6_128B:
1664 Changed = expandLoadVec2(B, I, MRI, HII, NewRegs);
1665 break;
1666 case Hexagon::STrivv_pseudo_V6:
1667 case Hexagon::STrivv_pseudo_V6_128B:
1668 Changed = expandStoreVec2(B, I, MRI, HII, NewRegs);
1669 break;
1670 case Hexagon::STriv_pseudo_V6:
1671 case Hexagon::STriv_pseudo_V6_128B:
1672 Changed = expandStoreVec(B, I, MRI, HII, NewRegs);
1673 break;
1674 case Hexagon::LDriv_pseudo_V6:
1675 case Hexagon::LDriv_pseudo_V6_128B:
1676 Changed = expandLoadVec(B, I, MRI, HII, NewRegs);
1677 break;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001678 }
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001679 }
1680 }
1681
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001682 return Changed;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001683}
1684
1685
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001686void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1687 BitVector &SavedRegs,
1688 RegScavenger *RS) const {
1689 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1690 auto &HRI = *HST.getRegisterInfo();
1691
1692 SavedRegs.resize(HRI.getNumRegs());
1693
1694 // If we have a function containing __builtin_eh_return we want to spill and
1695 // restore all callee saved registers. Pretend that they are used.
1696 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1697 for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1698 SavedRegs.set(*R);
1699
1700 // Replace predicate register pseudo spill code.
1701 SmallVector<unsigned,8> NewRegs;
1702 expandSpillMacros(MF, NewRegs);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001703 if (OptimizeSpillSlots && !isOptNone(MF))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001704 optimizeSpillSlots(MF, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001705
1706 // We need to reserve a a spill slot if scavenging could potentially require
1707 // spilling a scavenged register.
1708 if (!NewRegs.empty() && needToReserveScavengingSpillSlots(MF, HRI)) {
1709 MachineRegisterInfo &MRI = MF.getRegInfo();
1710 SetVector<const TargetRegisterClass*> SpillRCs;
1711 for (unsigned VR : NewRegs)
1712 SpillRCs.insert(MRI.getRegClass(VR));
1713
1714 MachineFrameInfo &MFI = *MF.getFrameInfo();
1715 const TargetRegisterClass &IntRC = Hexagon::IntRegsRegClass;
1716 if (SpillRCs.count(&IntRC)) {
1717 for (int i = 0; i < NumberScavengerSlots; i++) {
1718 int NewFI = MFI.CreateSpillStackObject(IntRC.getSize(),
1719 IntRC.getAlignment());
1720 RS->addScavengingFrameIndex(NewFI);
1721 }
1722 }
1723 for (auto *RC : SpillRCs) {
1724 if (RC == &IntRC)
1725 continue;
1726 int NewFI = MFI.CreateSpillStackObject(RC->getSize(), RC->getAlignment());
1727 RS->addScavengingFrameIndex(NewFI);
1728 }
1729 }
1730
1731 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1732}
1733
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001734
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001735unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1736 HexagonBlockRanges::IndexRange &FIR,
1737 HexagonBlockRanges::InstrIndexMap &IndexMap,
1738 HexagonBlockRanges::RegToRangeMap &DeadMap,
1739 const TargetRegisterClass *RC) const {
1740 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1741 auto &MRI = MF.getRegInfo();
1742
1743 auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1744 auto F = DeadMap.find({Reg,0});
1745 if (F == DeadMap.end())
1746 return false;
1747 for (auto &DR : F->second)
1748 if (DR.contains(FIR))
1749 return true;
1750 return false;
1751 };
1752
1753 for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
1754 bool Dead = true;
1755 for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
1756 if (isDead(R.Reg))
1757 continue;
1758 Dead = false;
1759 break;
1760 }
1761 if (Dead)
1762 return Reg;
1763 }
1764 return 0;
1765}
1766
1767void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
1768 SmallVectorImpl<unsigned> &VRegs) const {
1769 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1770 auto &HII = *HST.getInstrInfo();
1771 auto &HRI = *HST.getRegisterInfo();
1772 auto &MRI = MF.getRegInfo();
1773 HexagonBlockRanges HBR(MF);
1774
1775 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::InstrIndexMap>
1776 BlockIndexMap;
1777 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::RangeList>
1778 BlockRangeMap;
1779 typedef HexagonBlockRanges::IndexType IndexType;
1780
1781 struct SlotInfo {
1782 BlockRangeMap Map;
NAKAMURA Takumic2cc8702016-02-13 07:29:49 +00001783 unsigned Size;
1784 const TargetRegisterClass *RC;
1785
1786 SlotInfo() : Map(), Size(0), RC(nullptr) {}
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001787 };
1788
1789 BlockIndexMap BlockIndexes;
1790 SmallSet<int,4> BadFIs;
1791 std::map<int,SlotInfo> FIRangeMap;
1792
1793 auto getRegClass = [&MRI,&HRI] (HexagonBlockRanges::RegisterRef R)
1794 -> const TargetRegisterClass* {
1795 if (TargetRegisterInfo::isPhysicalRegister(R.Reg))
1796 assert(R.Sub == 0);
1797 if (TargetRegisterInfo::isVirtualRegister(R.Reg)) {
1798 auto *RCR = MRI.getRegClass(R.Reg);
1799 if (R.Sub == 0)
1800 return RCR;
1801 unsigned PR = *RCR->begin();
1802 R.Reg = HRI.getSubReg(PR, R.Sub);
1803 }
1804 return HRI.getMinimalPhysRegClass(R.Reg);
1805 };
1806 // Accumulate register classes: get a common class for a pre-existing
1807 // class HaveRC and a new class NewRC. Return nullptr if a common class
1808 // cannot be found, otherwise return the resulting class. If HaveRC is
1809 // nullptr, assume that it is still unset.
1810 auto getCommonRC = [&HRI] (const TargetRegisterClass *HaveRC,
1811 const TargetRegisterClass *NewRC)
1812 -> const TargetRegisterClass* {
1813 if (HaveRC == nullptr || HaveRC == NewRC)
1814 return NewRC;
1815 // Different classes, both non-null. Pick the more general one.
1816 if (HaveRC->hasSubClassEq(NewRC))
1817 return HaveRC;
1818 if (NewRC->hasSubClassEq(HaveRC))
1819 return NewRC;
1820 return nullptr;
1821 };
1822
1823 // Scan all blocks in the function. Check all occurrences of frame indexes,
1824 // and collect relevant information.
1825 for (auto &B : MF) {
1826 std::map<int,IndexType> LastStore, LastLoad;
Krzysztof Parzyszek280a50e2016-02-13 14:06:01 +00001827 // Emplace appears not to be supported in gcc 4.7.2-4.
1828 //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
Krzysztof Parzyszekde697d42016-02-17 15:02:07 +00001829 auto P = BlockIndexes.insert(
1830 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001831 auto &IndexMap = P.first->second;
1832 DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n"
1833 << IndexMap << '\n');
1834
1835 for (auto &In : B) {
1836 int LFI, SFI;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001837 bool Load = HII.isLoadFromStackSlot(&In, LFI) && !HII.isPredicated(In);
1838 bool Store = HII.isStoreToStackSlot(&In, SFI) && !HII.isPredicated(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001839 if (Load && Store) {
1840 // If it's both a load and a store, then we won't handle it.
1841 BadFIs.insert(LFI);
1842 BadFIs.insert(SFI);
1843 continue;
1844 }
1845 // Check for register classes of the register used as the source for
1846 // the store, and the register used as the destination for the load.
1847 // Also, only accept base+imm_offset addressing modes. Other addressing
1848 // modes can have side-effects (post-increments, etc.). For stack
1849 // slots they are very unlikely, so there is not much loss due to
1850 // this restriction.
1851 if (Load || Store) {
1852 int TFI = Load ? LFI : SFI;
1853 unsigned AM = HII.getAddrMode(&In);
1854 SlotInfo &SI = FIRangeMap[TFI];
1855 bool Bad = (AM != HexagonII::BaseImmOffset);
1856 if (!Bad) {
1857 // If the addressing mode is ok, check the register class.
1858 const TargetRegisterClass *RC = nullptr;
1859 if (Load) {
1860 MachineOperand &DataOp = In.getOperand(0);
1861 RC = getRegClass({DataOp.getReg(), DataOp.getSubReg()});
1862 } else {
1863 MachineOperand &DataOp = In.getOperand(2);
1864 RC = getRegClass({DataOp.getReg(), DataOp.getSubReg()});
1865 }
1866 RC = getCommonRC(SI.RC, RC);
1867 if (RC == nullptr)
1868 Bad = true;
1869 else
1870 SI.RC = RC;
1871 }
1872 if (!Bad) {
1873 // Check sizes.
1874 unsigned S = (1U << (HII.getMemAccessSize(&In) - 1));
1875 if (SI.Size != 0 && SI.Size != S)
1876 Bad = true;
1877 else
1878 SI.Size = S;
1879 }
1880 if (Bad)
1881 BadFIs.insert(TFI);
1882 }
1883
1884 // Locate uses of frame indices.
1885 for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
1886 const MachineOperand &Op = In.getOperand(i);
1887 if (!Op.isFI())
1888 continue;
1889 int FI = Op.getIndex();
1890 // Make sure that the following operand is an immediate and that
1891 // it is 0. This is the offset in the stack object.
1892 if (i+1 >= n || !In.getOperand(i+1).isImm() ||
1893 In.getOperand(i+1).getImm() != 0)
1894 BadFIs.insert(FI);
1895 if (BadFIs.count(FI))
1896 continue;
1897
1898 IndexType Index = IndexMap.getIndex(&In);
1899 if (Load) {
1900 if (LastStore[FI] == IndexType::None)
1901 LastStore[FI] = IndexType::Entry;
1902 LastLoad[FI] = Index;
1903 } else if (Store) {
1904 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
1905 if (LastStore[FI] != IndexType::None)
1906 RL.add(LastStore[FI], LastLoad[FI], false, false);
1907 else if (LastLoad[FI] != IndexType::None)
1908 RL.add(IndexType::Entry, LastLoad[FI], false, false);
1909 LastLoad[FI] = IndexType::None;
1910 LastStore[FI] = Index;
1911 } else {
1912 BadFIs.insert(FI);
1913 }
1914 }
1915 }
1916
1917 for (auto &I : LastLoad) {
1918 IndexType LL = I.second;
1919 if (LL == IndexType::None)
1920 continue;
1921 auto &RL = FIRangeMap[I.first].Map[&B];
1922 IndexType &LS = LastStore[I.first];
1923 if (LS != IndexType::None)
1924 RL.add(LS, LL, false, false);
1925 else
1926 RL.add(IndexType::Entry, LL, false, false);
1927 LS = IndexType::None;
1928 }
1929 for (auto &I : LastStore) {
1930 IndexType LS = I.second;
1931 if (LS == IndexType::None)
1932 continue;
1933 auto &RL = FIRangeMap[I.first].Map[&B];
1934 RL.add(LS, IndexType::None, false, false);
1935 }
1936 }
1937
1938 DEBUG({
1939 for (auto &P : FIRangeMap) {
1940 dbgs() << "fi#" << P.first;
1941 if (BadFIs.count(P.first))
1942 dbgs() << " (bad)";
1943 dbgs() << " RC: ";
1944 if (P.second.RC != nullptr)
1945 dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
1946 else
1947 dbgs() << "<null>\n";
1948 for (auto &R : P.second.Map)
1949 dbgs() << " BB#" << R.first->getNumber() << " { " << R.second << "}\n";
1950 }
1951 });
1952
1953 // When a slot is loaded from in a block without being stored to in the
1954 // same block, it is live-on-entry to this block. To avoid CFG analysis,
1955 // consider this slot to be live-on-exit from all blocks.
1956 SmallSet<int,4> LoxFIs;
1957
1958 std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
1959
1960 for (auto &P : FIRangeMap) {
1961 // P = pair(FI, map: BB->RangeList)
1962 if (BadFIs.count(P.first))
1963 continue;
1964 for (auto &B : MF) {
1965 auto F = P.second.Map.find(&B);
1966 // F = pair(BB, RangeList)
1967 if (F == P.second.Map.end() || F->second.empty())
1968 continue;
1969 HexagonBlockRanges::IndexRange &IR = F->second.front();
1970 if (IR.start() == IndexType::Entry)
1971 LoxFIs.insert(P.first);
1972 BlockFIMap[&B].push_back(P.first);
1973 }
1974 }
1975
1976 DEBUG({
1977 dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
1978 for (auto &P : BlockFIMap) {
1979 auto &FIs = P.second;
1980 if (FIs.empty())
1981 continue;
1982 dbgs() << " BB#" << P.first->getNumber() << ": {";
1983 for (auto I : FIs) {
1984 dbgs() << " fi#" << I;
1985 if (LoxFIs.count(I))
1986 dbgs() << '*';
1987 }
1988 dbgs() << " }\n";
1989 }
1990 });
1991
1992 // eliminate loads, when all loads eliminated, eliminate all stores.
1993 for (auto &B : MF) {
1994 auto F = BlockIndexes.find(&B);
1995 assert(F != BlockIndexes.end());
1996 HexagonBlockRanges::InstrIndexMap &IM = F->second;
1997 HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
1998 HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
1999 DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n"
2000 << HexagonBlockRanges::PrintRangeMap(DM, HRI));
2001
2002 for (auto FI : BlockFIMap[&B]) {
2003 if (BadFIs.count(FI))
2004 continue;
2005 DEBUG(dbgs() << "Working on fi#" << FI << '\n');
2006 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2007 for (auto &Range : RL) {
2008 DEBUG(dbgs() << "--Examining range:" << RL << '\n');
2009 if (!IndexType::isInstr(Range.start()) ||
2010 !IndexType::isInstr(Range.end()))
2011 continue;
2012 MachineInstr *SI = IM.getInstr(Range.start());
2013 MachineInstr *EI = IM.getInstr(Range.end());
2014 assert(SI->mayStore() && "Unexpected start instruction");
2015 assert(EI->mayLoad() && "Unexpected end instruction");
2016 MachineOperand &SrcOp = SI->getOperand(2);
2017
2018 HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
2019 SrcOp.getSubReg() };
2020 auto *RC = getRegClass({SrcOp.getReg(), SrcOp.getSubReg()});
2021 // The this-> is needed to unconfuse MSVC.
2022 unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
2023 DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n');
2024 if (FoundR == 0)
2025 continue;
2026
2027 // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
2028 MachineBasicBlock::iterator StartIt = SI, NextIt;
2029 MachineInstr *CopyIn = nullptr;
2030 if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
2031 DebugLoc DL = SI->getDebugLoc();
2032 CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
2033 .addOperand(SrcOp);
2034 }
2035
2036 ++StartIt;
2037 // Check if this is a last store and the FI is live-on-exit.
2038 if (LoxFIs.count(FI) && (&Range == &RL.back())) {
2039 // Update store's source register.
2040 if (unsigned SR = SrcOp.getSubReg())
2041 SrcOp.setReg(HRI.getSubReg(FoundR, SR));
2042 else
2043 SrcOp.setReg(FoundR);
2044 SrcOp.setSubReg(0);
2045 // We are keeping this register live.
2046 SrcOp.setIsKill(false);
2047 } else {
2048 B.erase(SI);
2049 IM.replaceInstr(SI, CopyIn);
2050 }
2051
2052 auto EndIt = std::next(MachineBasicBlock::iterator(EI));
2053 for (auto It = StartIt; It != EndIt; It = NextIt) {
2054 MachineInstr *MI = &*It;
2055 NextIt = std::next(It);
2056 int TFI;
2057 if (!HII.isLoadFromStackSlot(MI, TFI) || TFI != FI)
2058 continue;
2059 unsigned DstR = MI->getOperand(0).getReg();
2060 assert(MI->getOperand(0).getSubReg() == 0);
2061 MachineInstr *CopyOut = nullptr;
2062 if (DstR != FoundR) {
2063 DebugLoc DL = MI->getDebugLoc();
2064 unsigned MemSize = (1U << (HII.getMemAccessSize(MI) - 1));
2065 assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2066 unsigned CopyOpc = TargetOpcode::COPY;
2067 if (HII.isSignExtendingLoad(MI))
2068 CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
2069 else if (HII.isZeroExtendingLoad(MI))
2070 CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2071 CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
2072 .addReg(FoundR, getKillRegState(MI == EI));
2073 }
2074 IM.replaceInstr(MI, CopyOut);
2075 B.erase(It);
2076 }
2077
2078 // Update the dead map.
2079 HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2080 for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2081 DM[RR].subtract(Range);
2082 } // for Range in range list
2083 }
2084 }
2085}
2086
2087
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002088void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002089 const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002090 MachineBasicBlock &MB = *AI->getParent();
2091 DebugLoc DL = AI->getDebugLoc();
2092 unsigned A = AI->getOperand(2).getImm();
2093
2094 // Have
2095 // Rd = alloca Rs, #A
2096 //
2097 // If Rs and Rd are different registers, use this sequence:
2098 // Rd = sub(r29, Rs)
2099 // r29 = sub(r29, Rs)
2100 // Rd = and(Rd, #-A) ; if necessary
2101 // r29 = and(r29, #-A) ; if necessary
2102 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2103 // otherwise, do
2104 // Rd = sub(r29, Rs)
2105 // Rd = and(Rd, #-A) ; if necessary
2106 // r29 = Rd
2107 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2108
2109 MachineOperand &RdOp = AI->getOperand(0);
2110 MachineOperand &RsOp = AI->getOperand(1);
2111 unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2112
2113 // Rd = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002114 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002115 .addReg(SP)
2116 .addReg(Rs);
2117 if (Rs != Rd) {
2118 // r29 = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002119 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002120 .addReg(SP)
2121 .addReg(Rs);
2122 }
2123 if (A > 8) {
2124 // Rd = and(Rd, #-A)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002125 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002126 .addReg(Rd)
2127 .addImm(-int64_t(A));
2128 if (Rs != Rd)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002129 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002130 .addReg(SP)
2131 .addImm(-int64_t(A));
2132 }
2133 if (Rs == Rd) {
2134 // r29 = Rd
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002135 BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002136 .addReg(Rd);
2137 }
2138 if (CF > 0) {
2139 // Rd = add(Rd, #CF)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002140 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002141 .addReg(Rd)
2142 .addImm(CF);
2143 }
2144}
2145
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002146
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002147bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
2148 const MachineFrameInfo *MFI = MF.getFrameInfo();
2149 if (!MFI->hasVarSizedObjects())
2150 return false;
2151 unsigned MaxA = MFI->getMaxAlignment();
2152 if (MaxA <= getStackAlignment())
2153 return false;
2154 return true;
2155}
2156
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002157
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00002158const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2159 const MachineFunction &MF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002160 for (auto &B : MF)
2161 for (auto &I : B)
2162 if (I.getOpcode() == Hexagon::ALIGNA)
2163 return &I;
2164 return nullptr;
2165}
2166
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002167
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002168/// Determine whether the callee-saved register saves and restores should
2169/// be generated via inline code. If this function returns "true", inline
2170/// code will be generated. If this function returns "false", additional
2171/// checks are performed, which may still lead to the inline code.
2172bool HexagonFrameLowering::shouldInlineCSR(MachineFunction &MF,
2173 const CSIVect &CSI) const {
2174 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2175 return true;
2176 if (!isOptSize(MF) && !isMinSize(MF))
2177 if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2178 return true;
2179
2180 // Check if CSI only has double registers, and if the registers form
2181 // a contiguous block starting from D8.
2182 BitVector Regs(Hexagon::NUM_TARGET_REGS);
2183 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2184 unsigned R = CSI[i].getReg();
2185 if (!Hexagon::DoubleRegsRegClass.contains(R))
2186 return true;
2187 Regs[R] = true;
2188 }
2189 int F = Regs.find_first();
2190 if (F != Hexagon::D8)
2191 return true;
2192 while (F >= 0) {
2193 int N = Regs.find_next(F);
2194 if (N >= 0 && N != F+1)
2195 return true;
2196 F = N;
2197 }
2198
2199 return false;
2200}
2201
2202
2203bool HexagonFrameLowering::useSpillFunction(MachineFunction &MF,
2204 const CSIVect &CSI) const {
2205 if (shouldInlineCSR(MF, CSI))
2206 return false;
2207 unsigned NumCSI = CSI.size();
2208 if (NumCSI <= 1)
2209 return false;
2210
2211 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2212 : SpillFuncThreshold;
2213 return Threshold < NumCSI;
2214}
2215
2216
2217bool HexagonFrameLowering::useRestoreFunction(MachineFunction &MF,
2218 const CSIVect &CSI) const {
2219 if (shouldInlineCSR(MF, CSI))
2220 return false;
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002221 // The restore functions do a bit more than just restoring registers.
2222 // The non-returning versions will go back directly to the caller's
2223 // caller, others will clean up the stack frame in preparation for
2224 // a tail call. Using them can still save code size even if only one
2225 // register is getting restores. Make the decision based on -Oz:
2226 // using -Os will use inline restore for a single register.
2227 if (isMinSize(MF))
2228 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002229 unsigned NumCSI = CSI.size();
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002230 if (NumCSI <= 1)
2231 return false;
2232
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002233 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2234 : SpillFuncThreshold;
2235 return Threshold < NumCSI;
2236}