blob: d01e0106365d929390220b90c313ac7708731e5b [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 Parzyszeka5bd29542016-05-16 18:02:28 +0000128static cl::opt<unsigned> 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 Parzyszek080bebd2016-07-25 14:42:11 +0000152static cl::opt<bool> EnableSaveRestoreLong("enable-save-restore-long",
153 cl::Hidden, cl::desc("Enable long calls for save-restore stubs."),
154 cl::init(false), cl::ZeroOrMore);
155
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000156static cl::opt<bool> UseAllocframe("use-allocframe", cl::init(true),
157 cl::Hidden, cl::desc("Use allocframe more conservatively"));
158
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +0000159static cl::opt<bool> OptimizeSpillSlots("hexagon-opt-spill", cl::Hidden,
160 cl::init(true), cl::desc("Optimize spill slots"));
161
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000162
163namespace llvm {
164 void initializeHexagonCallFrameInformationPass(PassRegistry&);
165 FunctionPass *createHexagonCallFrameInformation();
166}
167
168namespace {
169 class HexagonCallFrameInformation : public MachineFunctionPass {
170 public:
171 static char ID;
172 HexagonCallFrameInformation() : MachineFunctionPass(ID) {
173 PassRegistry &PR = *PassRegistry::getPassRegistry();
174 initializeHexagonCallFrameInformationPass(PR);
175 }
176 bool runOnMachineFunction(MachineFunction &MF) override;
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000177 MachineFunctionProperties getRequiredProperties() const override {
178 return MachineFunctionProperties().set(
179 MachineFunctionProperties::Property::AllVRegsAllocated);
180 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000181 };
182
183 char HexagonCallFrameInformation::ID = 0;
184}
185
186bool HexagonCallFrameInformation::runOnMachineFunction(MachineFunction &MF) {
187 auto &HFI = *MF.getSubtarget<HexagonSubtarget>().getFrameLowering();
188 bool NeedCFI = MF.getMMI().hasDebugInfo() ||
189 MF.getFunction()->needsUnwindTableEntry();
190
191 if (!NeedCFI)
192 return false;
193 HFI.insertCFIInstructions(MF);
194 return true;
195}
196
197INITIALIZE_PASS(HexagonCallFrameInformation, "hexagon-cfi",
198 "Hexagon call frame information", false, false)
199
200FunctionPass *llvm::createHexagonCallFrameInformation() {
201 return new HexagonCallFrameInformation();
202}
203
204
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000205namespace {
206 /// Map a register pair Reg to the subregister that has the greater "number",
207 /// i.e. D3 (aka R7:6) will be mapped to R7, etc.
208 unsigned getMax32BitSubRegister(unsigned Reg, const TargetRegisterInfo &TRI,
209 bool hireg = true) {
210 if (Reg < Hexagon::D0 || Reg > Hexagon::D15)
211 return Reg;
212
213 unsigned RegNo = 0;
214 for (MCSubRegIterator SubRegs(Reg, &TRI); SubRegs.isValid(); ++SubRegs) {
215 if (hireg) {
216 if (*SubRegs > RegNo)
217 RegNo = *SubRegs;
218 } else {
219 if (!RegNo || *SubRegs < RegNo)
220 RegNo = *SubRegs;
221 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000222 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000223 return RegNo;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000224 }
225
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000226 /// Returns the callee saved register with the largest id in the vector.
227 unsigned getMaxCalleeSavedReg(const std::vector<CalleeSavedInfo> &CSI,
228 const TargetRegisterInfo &TRI) {
Benjamin Kramer3e9a5d32016-05-27 11:36:04 +0000229 static_assert(Hexagon::R1 > 0,
230 "Assume physical registers are encoded as positive integers");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000231 if (CSI.empty())
232 return 0;
233
234 unsigned Max = getMax32BitSubRegister(CSI[0].getReg(), TRI);
235 for (unsigned I = 1, E = CSI.size(); I < E; ++I) {
236 unsigned Reg = getMax32BitSubRegister(CSI[I].getReg(), TRI);
237 if (Reg > Max)
238 Max = Reg;
239 }
240 return Max;
241 }
242
243 /// Checks if the basic block contains any instruction that needs a stack
244 /// frame to be already in place.
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000245 bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR,
246 const HexagonRegisterInfo &HRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000247 for (auto &I : MBB) {
248 const MachineInstr *MI = &I;
249 if (MI->isCall())
250 return true;
251 unsigned Opc = MI->getOpcode();
252 switch (Opc) {
253 case Hexagon::ALLOCA:
254 case Hexagon::ALIGNA:
255 return true;
256 default:
257 break;
258 }
259 // Check individual operands.
Matthias Braune41e1462015-05-29 02:56:46 +0000260 for (const MachineOperand &MO : MI->operands()) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000261 // While the presence of a frame index does not prove that a stack
262 // frame will be required, all frame indexes should be within alloc-
263 // frame/deallocframe. Otherwise, the code that translates a frame
264 // index into an offset would have to be aware of the placement of
265 // the frame creation/destruction instructions.
Matthias Braune41e1462015-05-29 02:56:46 +0000266 if (MO.isFI())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000267 return true;
Matthias Braune41e1462015-05-29 02:56:46 +0000268 if (!MO.isReg())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000269 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000270 unsigned R = MO.getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000271 // Virtual registers will need scavenging, which then may require
272 // a stack slot.
273 if (TargetRegisterInfo::isVirtualRegister(R))
274 return true;
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000275 for (MCSubRegIterator S(R, &HRI, true); S.isValid(); ++S)
276 if (CSR[*S])
277 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000278 }
279 }
280 return false;
281 }
282
283 /// Returns true if MBB has a machine instructions that indicates a tail call
284 /// in the block.
285 bool hasTailCall(const MachineBasicBlock &MBB) {
286 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
287 unsigned RetOpc = I->getOpcode();
288 return RetOpc == Hexagon::TCRETURNi || RetOpc == Hexagon::TCRETURNr;
289 }
290
291 /// Returns true if MBB contains an instruction that returns.
292 bool hasReturn(const MachineBasicBlock &MBB) {
293 for (auto I = MBB.getFirstTerminator(), E = MBB.end(); I != E; ++I)
294 if (I->isReturn())
295 return true;
296 return false;
297 }
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +0000298
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000299 /// Returns the "return" instruction from this block, or nullptr if there
300 /// isn't any.
301 MachineInstr *getReturn(MachineBasicBlock &MBB) {
302 for (auto &I : MBB)
303 if (I.isReturn())
304 return &I;
305 return nullptr;
306 }
307
308 bool isRestoreCall(unsigned Opc) {
309 switch (Opc) {
310 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4:
311 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC:
312 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4:
313 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC:
314 return true;
315 }
316 return false;
317 }
318
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +0000319 inline bool isOptNone(const MachineFunction &MF) {
320 return MF.getFunction()->hasFnAttribute(Attribute::OptimizeNone) ||
321 MF.getTarget().getOptLevel() == CodeGenOpt::None;
322 }
323
324 inline bool isOptSize(const MachineFunction &MF) {
325 const Function &F = *MF.getFunction();
326 return F.optForSize() && !F.optForMinSize();
327 }
328
329 inline bool isMinSize(const MachineFunction &MF) {
330 return MF.getFunction()->optForMinSize();
331 }
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000332}
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000333
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000334
335/// Implements shrink-wrapping of the stack frame. By default, stack frame
336/// is created in the function entry block, and is cleaned up in every block
337/// that returns. This function finds alternate blocks: one for the frame
338/// setup (prolog) and one for the cleanup (epilog).
339void HexagonFrameLowering::findShrunkPrologEpilog(MachineFunction &MF,
340 MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const {
341 static unsigned ShrinkCounter = 0;
342
343 if (ShrinkLimit.getPosition()) {
344 if (ShrinkCounter >= ShrinkLimit)
345 return;
346 ShrinkCounter++;
347 }
348
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000349 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000350 auto &HRI = *HST.getRegisterInfo();
351
352 MachineDominatorTree MDT;
353 MDT.runOnMachineFunction(MF);
354 MachinePostDominatorTree MPT;
355 MPT.runOnMachineFunction(MF);
356
357 typedef DenseMap<unsigned,unsigned> UnsignedMap;
358 UnsignedMap RPO;
359 typedef ReversePostOrderTraversal<const MachineFunction*> RPOTType;
360 RPOTType RPOT(&MF);
361 unsigned RPON = 0;
362 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I)
363 RPO[(*I)->getNumber()] = RPON++;
364
365 // Don't process functions that have loops, at least for now. Placement
366 // of prolog and epilog must take loop structure into account. For simpli-
367 // city don't do it right now.
368 for (auto &I : MF) {
369 unsigned BN = RPO[I.getNumber()];
370 for (auto SI = I.succ_begin(), SE = I.succ_end(); SI != SE; ++SI) {
371 // If found a back-edge, return.
372 if (RPO[(*SI)->getNumber()] <= BN)
373 return;
374 }
375 }
376
377 // Collect the set of blocks that need a stack frame to execute. Scan
378 // each block for uses/defs of callee-saved registers, calls, etc.
379 SmallVector<MachineBasicBlock*,16> SFBlocks;
380 BitVector CSR(Hexagon::NUM_TARGET_REGS);
381 for (const MCPhysReg *P = HRI.getCalleeSavedRegs(&MF); *P; ++P)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000382 for (MCSubRegIterator S(*P, &HRI, true); S.isValid(); ++S)
383 CSR[*S] = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000384
385 for (auto &I : MF)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000386 if (needsStackFrame(I, CSR, HRI))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000387 SFBlocks.push_back(&I);
388
389 DEBUG({
390 dbgs() << "Blocks needing SF: {";
391 for (auto &B : SFBlocks)
392 dbgs() << " BB#" << B->getNumber();
393 dbgs() << " }\n";
394 });
395 // No frame needed?
396 if (SFBlocks.empty())
397 return;
398
399 // Pick a common dominator and a common post-dominator.
400 MachineBasicBlock *DomB = SFBlocks[0];
401 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
402 DomB = MDT.findNearestCommonDominator(DomB, SFBlocks[i]);
403 if (!DomB)
404 break;
405 }
406 MachineBasicBlock *PDomB = SFBlocks[0];
407 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
408 PDomB = MPT.findNearestCommonDominator(PDomB, SFBlocks[i]);
409 if (!PDomB)
410 break;
411 }
412 DEBUG({
413 dbgs() << "Computed dom block: BB#";
414 if (DomB) dbgs() << DomB->getNumber();
415 else dbgs() << "<null>";
416 dbgs() << ", computed pdom block: BB#";
417 if (PDomB) dbgs() << PDomB->getNumber();
418 else dbgs() << "<null>";
419 dbgs() << "\n";
420 });
421 if (!DomB || !PDomB)
422 return;
423
424 // Make sure that DomB dominates PDomB and PDomB post-dominates DomB.
425 if (!MDT.dominates(DomB, PDomB)) {
426 DEBUG(dbgs() << "Dom block does not dominate pdom block\n");
427 return;
428 }
429 if (!MPT.dominates(PDomB, DomB)) {
430 DEBUG(dbgs() << "PDom block does not post-dominate dom block\n");
431 return;
432 }
433
434 // Finally, everything seems right.
435 PrologB = DomB;
436 EpilogB = PDomB;
437}
438
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000439
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000440/// Perform most of the PEI work here:
441/// - saving/restoring of the callee-saved registers,
442/// - stack frame creation and destruction.
443/// Normally, this work is distributed among various functions, but doing it
444/// in one place allows shrink-wrapping of the stack frame.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000445void HexagonFrameLowering::emitPrologue(MachineFunction &MF,
446 MachineBasicBlock &MBB) const {
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000447 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000448 auto &HRI = *HST.getRegisterInfo();
449
450 MachineFrameInfo *MFI = MF.getFrameInfo();
451 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
452
453 MachineBasicBlock *PrologB = &MF.front(), *EpilogB = nullptr;
454 if (EnableShrinkWrapping)
455 findShrunkPrologEpilog(MF, PrologB, EpilogB);
456
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000457 bool PrologueStubs = false;
458 insertCSRSpillsInBlock(*PrologB, CSI, HRI, PrologueStubs);
459 insertPrologueInBlock(*PrologB, PrologueStubs);
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000460 updateEntryPaths(MF, *PrologB);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000461
462 if (EpilogB) {
463 insertCSRRestoresInBlock(*EpilogB, CSI, HRI);
464 insertEpilogueInBlock(*EpilogB);
465 } else {
466 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000467 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000468 insertCSRRestoresInBlock(B, CSI, HRI);
469
470 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000471 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000472 insertEpilogueInBlock(B);
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000473
474 for (auto &B : MF) {
475 if (B.empty())
476 continue;
477 MachineInstr *RetI = getReturn(B);
478 if (!RetI || isRestoreCall(RetI->getOpcode()))
479 continue;
480 for (auto &R : CSI)
481 RetI->addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
482 }
483 }
484
485 if (EpilogB) {
486 // If there is an epilog block, it may not have a return instruction.
487 // In such case, we need to add the callee-saved registers as live-ins
488 // in all blocks on all paths from the epilog to any return block.
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000489 unsigned MaxBN = MF.getNumBlockIDs();
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000490 BitVector DoneT(MaxBN+1), DoneF(MaxBN+1), Path(MaxBN+1);
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000491 updateExitPaths(*EpilogB, *EpilogB, DoneT, DoneF, Path);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000492 }
493}
494
495
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000496void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB,
497 bool PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000498 MachineFunction &MF = *MBB.getParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000499 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000500 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000501 auto &HII = *HST.getInstrInfo();
502 auto &HRI = *HST.getRegisterInfo();
503 DebugLoc dl;
504
505 unsigned MaxAlign = std::max(MFI->getMaxAlignment(), getStackAlignment());
506
507 // Calculate the total stack frame size.
508 // Get the number of bytes to allocate from the FrameInfo.
509 unsigned FrameSize = MFI->getStackSize();
510 // Round up the max call frame size to the max alignment on the stack.
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000511 unsigned MaxCFA = alignTo(MFI->getMaxCallFrameSize(), MaxAlign);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000512 MFI->setMaxCallFrameSize(MaxCFA);
513
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000514 FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000515 MFI->setStackSize(FrameSize);
516
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000517 bool AlignStack = (MaxAlign > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000518
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000519 // Get the number of bytes to allocate from the FrameInfo.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000520 unsigned NumBytes = MFI->getStackSize();
521 unsigned SP = HRI.getStackRegister();
522 unsigned MaxCF = MFI->getMaxCallFrameSize();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000523 MachineBasicBlock::iterator InsertPt = MBB.begin();
524
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000525 auto *FuncInfo = MF.getInfo<HexagonMachineFunctionInfo>();
526 auto &AdjustRegs = FuncInfo->getAllocaAdjustInsts();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000527
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000528 for (auto MI : AdjustRegs) {
529 assert((MI->getOpcode() == Hexagon::ALLOCA) && "Expected alloca");
530 expandAlloca(MI, HII, SP, MaxCF);
531 MI->eraseFromParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000532 }
533
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000534 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000535 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000536
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000537 // Check for overflow.
538 // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
539 const unsigned int ALLOCFRAME_MAX = 16384;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000540
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000541 // Create a dummy memory operand to avoid allocframe from being treated as
542 // a volatile memory reference.
543 MachineMemOperand *MMO =
544 MF.getMachineMemOperand(MachinePointerInfo(), MachineMemOperand::MOStore,
545 4, 4);
546
547 if (NumBytes >= ALLOCFRAME_MAX) {
548 // Emit allocframe(#0).
549 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
550 .addImm(0)
551 .addMemOperand(MMO);
552
553 // Subtract offset from frame pointer.
554 // We use a caller-saved non-parameter register for that.
555 unsigned CallerSavedReg = HRI.getFirstCallerSavedNonParamReg();
556 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CONST32_Int_Real),
557 CallerSavedReg).addImm(NumBytes);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000558 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_sub), SP)
559 .addReg(SP)
560 .addReg(CallerSavedReg);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000561 } else {
562 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
563 .addImm(NumBytes)
564 .addMemOperand(MMO);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000565 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000566
567 if (AlignStack) {
568 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
569 .addReg(SP)
570 .addImm(-int64_t(MaxAlign));
571 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000572
573 // If the stack-checking is enabled, and we spilled the callee-saved
574 // registers inline (i.e. did not use a spill function), then call
575 // the stack checker directly.
576 if (EnableStackOVFSanitizer && !PrologueStubs)
577 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CALLstk))
578 .addExternalSymbol("__runtime_stack_check");
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000579}
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000580
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000581void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
582 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000583 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000584 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000585
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000586 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000587 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000588 auto &HRI = *HST.getRegisterInfo();
589 unsigned SP = HRI.getStackRegister();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000590
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000591 MachineInstr *RetI = getReturn(MBB);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000592 unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
593
594 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
595 DebugLoc DL;
596 if (InsertPt != MBB.end())
597 DL = InsertPt->getDebugLoc();
598 else if (!MBB.empty())
599 DL = std::prev(MBB.end())->getDebugLoc();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000600
601 // Handle EH_RETURN.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000602 if (RetOpc == Hexagon::EH_RETURN_JMPR) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000603 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
604 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::A2_add), SP)
605 .addReg(SP)
606 .addReg(Hexagon::R28);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000607 return;
608 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000609
610 // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
611 // frame instruction if we encounter it.
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000612 if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
613 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000614 MachineBasicBlock::iterator It = RetI;
615 ++It;
616 // Delete all instructions after the RESTORE (except labels).
617 while (It != MBB.end()) {
618 if (!It->isLabel())
619 It = MBB.erase(It);
620 else
621 ++It;
Jyotsna Verma300f0b92013-05-10 20:27:34 +0000622 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000623 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000624 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000625
626 // It is possible that the restoring code is a call to a library function.
627 // All of the restore* functions include "deallocframe", so we need to make
628 // sure that we don't add an extra one.
629 bool NeedsDeallocframe = true;
630 if (!MBB.empty() && InsertPt != MBB.begin()) {
631 MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
632 unsigned COpc = PrevIt->getOpcode();
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000633 if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
634 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000635 NeedsDeallocframe = false;
636 }
637
638 if (!NeedsDeallocframe)
639 return;
640 // If the returning instruction is JMPret, replace it with dealloc_return,
641 // otherwise just add deallocframe. The function could be returning via a
642 // tail call.
643 if (RetOpc != Hexagon::JMPret || DisableDeallocRet) {
644 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
645 return;
646 }
647 unsigned NewOpc = Hexagon::L4_return;
648 MachineInstr *NewI = BuildMI(MBB, RetI, DL, HII.get(NewOpc));
649 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000650 NewI->copyImplicitOps(MF, *RetI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000651 MBB.erase(RetI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000652}
653
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000654void HexagonFrameLowering::updateEntryPaths(MachineFunction &MF,
655 MachineBasicBlock &SaveB) const {
656 SetVector<unsigned> Worklist;
657
658 MachineBasicBlock &EntryB = MF.front();
659 Worklist.insert(EntryB.getNumber());
660
661 unsigned SaveN = SaveB.getNumber();
662 auto &CSI = MF.getFrameInfo()->getCalleeSavedInfo();
663
664 for (unsigned i = 0; i < Worklist.size(); ++i) {
665 unsigned BN = Worklist[i];
666 MachineBasicBlock &MBB = *MF.getBlockNumbered(BN);
667 for (auto &R : CSI)
668 if (!MBB.isLiveIn(R.getReg()))
669 MBB.addLiveIn(R.getReg());
670 if (BN != SaveN)
671 for (auto &SB : MBB.successors())
672 Worklist.insert(SB->getNumber());
673 }
674}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000675
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000676bool HexagonFrameLowering::updateExitPaths(MachineBasicBlock &MBB,
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000677 MachineBasicBlock &RestoreB, BitVector &DoneT, BitVector &DoneF,
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000678 BitVector &Path) const {
679 assert(MBB.getNumber() >= 0);
680 unsigned BN = MBB.getNumber();
681 if (Path[BN] || DoneF[BN])
682 return false;
683 if (DoneT[BN])
684 return true;
685
686 auto &CSI = MBB.getParent()->getFrameInfo()->getCalleeSavedInfo();
687
688 Path[BN] = true;
689 bool ReachedExit = false;
690 for (auto &SB : MBB.successors())
691 ReachedExit |= updateExitPaths(*SB, RestoreB, DoneT, DoneF, Path);
692
693 if (!MBB.empty() && MBB.back().isReturn()) {
694 // Add implicit uses of all callee-saved registers to the reached
695 // return instructions. This is to prevent the anti-dependency breaker
696 // from renaming these registers.
697 MachineInstr &RetI = MBB.back();
698 if (!isRestoreCall(RetI.getOpcode()))
699 for (auto &R : CSI)
700 RetI.addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
701 ReachedExit = true;
702 }
703
704 // We don't want to add unnecessary live-ins to the restore block: since
705 // the callee-saved registers are being defined in it, the entry of the
706 // restore block cannot be on the path from the definitions to any exit.
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000707 if (ReachedExit && &MBB != &RestoreB) {
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000708 for (auto &R : CSI)
709 if (!MBB.isLiveIn(R.getReg()))
710 MBB.addLiveIn(R.getReg());
711 DoneT[BN] = true;
712 }
713 if (!ReachedExit)
714 DoneF[BN] = true;
715
716 Path[BN] = false;
717 return ReachedExit;
718}
719
720
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000721namespace {
722 bool IsAllocFrame(MachineBasicBlock::const_iterator It) {
723 if (!It->isBundle())
724 return It->getOpcode() == Hexagon::S2_allocframe;
725 auto End = It->getParent()->instr_end();
Duncan P. N. Exon Smithd84f6002016-02-22 21:30:15 +0000726 MachineBasicBlock::const_instr_iterator I = It.getInstrIterator();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000727 while (++I != End && I->isBundled())
728 if (I->getOpcode() == Hexagon::S2_allocframe)
729 return true;
730 return false;
731 }
732
733 MachineBasicBlock::iterator FindAllocFrame(MachineBasicBlock &B) {
734 for (auto &I : B)
735 if (IsAllocFrame(I))
736 return I;
737 return B.end();
738 }
739}
740
741
742void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
743 for (auto &B : MF) {
744 auto AF = FindAllocFrame(B);
745 if (AF == B.end())
746 continue;
747 insertCFIInstructionsAt(B, ++AF);
748 }
749}
750
751
752void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
753 MachineBasicBlock::iterator At) const {
754 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000755 MachineFrameInfo &MFI = *MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000756 MachineModuleInfo &MMI = MF.getMMI();
757 auto &HST = MF.getSubtarget<HexagonSubtarget>();
758 auto &HII = *HST.getInstrInfo();
759 auto &HRI = *HST.getRegisterInfo();
760
761 // If CFI instructions have debug information attached, something goes
762 // wrong with the final assembly generation: the prolog_end is placed
763 // in a wrong location.
764 DebugLoc DL;
765 const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
766
767 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000768 bool HasFP = hasFP(MF);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000769
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000770 if (HasFP) {
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000771 unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
772 unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000773
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000774 // Define CFA via an offset from the value of FP.
775 //
776 // -8 -4 0 (SP)
777 // --+----+----+---------------------
778 // | FP | LR | increasing addresses -->
779 // --+----+----+---------------------
780 // | +-- Old SP (before allocframe)
781 // +-- New FP (after allocframe)
782 //
783 // MCCFIInstruction::createDefCfa subtracts the offset from the register.
784 // MCCFIInstruction::createOffset takes the offset without sign change.
785 auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
786 BuildMI(MBB, At, DL, CFID)
787 .addCFIIndex(MMI.addFrameInst(DefCfa));
788 // R31 (return addr) = CFA - 4
789 auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
790 BuildMI(MBB, At, DL, CFID)
791 .addCFIIndex(MMI.addFrameInst(OffR31));
792 // R30 (frame ptr) = CFA - 8
793 auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
794 BuildMI(MBB, At, DL, CFID)
795 .addCFIIndex(MMI.addFrameInst(OffR30));
796 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000797
798 static unsigned int RegsToMove[] = {
799 Hexagon::R1, Hexagon::R0, Hexagon::R3, Hexagon::R2,
800 Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
801 Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
802 Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
803 Hexagon::D0, Hexagon::D1, Hexagon::D8, Hexagon::D9,
804 Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
805 Hexagon::NoRegister
806 };
807
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000808 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000809
810 for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
811 unsigned Reg = RegsToMove[i];
812 auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
813 return C.getReg() == Reg;
814 };
815 auto F = std::find_if(CSI.begin(), CSI.end(), IfR);
816 if (F == CSI.end())
817 continue;
818
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000819 int64_t Offset;
820 if (HasFP) {
821 // If the function has a frame pointer (i.e. has an allocframe),
822 // then the CFA has been defined in terms of FP. Any offsets in
823 // the following CFI instructions have to be defined relative
824 // to FP, which points to the bottom of the stack frame.
825 // The function getFrameIndexReference can still choose to use SP
826 // for the offset calculation, so we cannot simply call it here.
827 // Instead, get the offset (relative to the FP) directly.
828 Offset = MFI.getObjectOffset(F->getFrameIdx());
829 } else {
830 unsigned FrameReg;
831 Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg);
832 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000833 // Subtract 8 to make room for R30 and R31, which are added above.
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000834 Offset -= 8;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000835
836 if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
837 unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
838 auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
839 Offset);
840 BuildMI(MBB, At, DL, CFID)
841 .addCFIIndex(MMI.addFrameInst(OffReg));
842 } else {
843 // Split the double regs into subregs, and generate appropriate
844 // cfi_offsets.
845 // The only reason, we are split double regs is, llvm-mc does not
846 // understand paired registers for cfi_offset.
847 // Eg .cfi_offset r1:0, -64
848
849 unsigned HiReg = HRI.getSubReg(Reg, Hexagon::subreg_hireg);
850 unsigned LoReg = HRI.getSubReg(Reg, Hexagon::subreg_loreg);
851 unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
852 unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
853 auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
854 Offset+4);
855 BuildMI(MBB, At, DL, CFID)
856 .addCFIIndex(MMI.addFrameInst(OffHi));
857 auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
858 Offset);
859 BuildMI(MBB, At, DL, CFID)
860 .addCFIIndex(MMI.addFrameInst(OffLo));
861 }
862 }
863}
864
865
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000866bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000867 auto &MFI = *MF.getFrameInfo();
868 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
869
870 bool HasFixed = MFI.getNumFixedObjects();
871 bool HasPrealloc = const_cast<MachineFrameInfo&>(MFI)
872 .getLocalFrameObjectCount();
873 bool HasExtraAlign = HRI.needsStackRealignment(MF);
874 bool HasAlloca = MFI.hasVarSizedObjects();
875
876 // Insert ALLOCFRAME if we need to or at -O0 for the debugger. Think
877 // that this shouldn't be required, but doing so now because gcc does and
878 // gdb can't break at the start of the function without it. Will remove if
879 // this turns out to be a gdb bug.
880 //
881 if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
882 return true;
883
884 // By default we want to use SP (since it's always there). FP requires
885 // some setup (i.e. ALLOCFRAME).
886 // Fixed and preallocated objects need FP if the distance from them to
887 // the SP is unknown (as is with alloca or aligna).
888 if ((HasFixed || HasPrealloc) && (HasAlloca || HasExtraAlign))
889 return true;
890
891 if (MFI.getStackSize() > 0) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000892 if (EnableStackOVFSanitizer || UseAllocframe)
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000893 return true;
894 }
895
896 if (MFI.hasCalls() ||
897 MF.getInfo<HexagonMachineFunctionInfo>()->hasClobberLR())
898 return true;
899
900 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000901}
902
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000903
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000904enum SpillKind {
905 SK_ToMem,
906 SK_FromMem,
907 SK_FromMemTailcall
908};
909
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000910static const char *getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType,
911 bool Stkchk = false) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000912 const char * V4SpillToMemoryFunctions[] = {
913 "__save_r16_through_r17",
914 "__save_r16_through_r19",
915 "__save_r16_through_r21",
916 "__save_r16_through_r23",
917 "__save_r16_through_r25",
918 "__save_r16_through_r27" };
919
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000920 const char * V4SpillToMemoryStkchkFunctions[] = {
921 "__save_r16_through_r17_stkchk",
922 "__save_r16_through_r19_stkchk",
923 "__save_r16_through_r21_stkchk",
924 "__save_r16_through_r23_stkchk",
925 "__save_r16_through_r25_stkchk",
926 "__save_r16_through_r27_stkchk" };
927
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000928 const char * V4SpillFromMemoryFunctions[] = {
929 "__restore_r16_through_r17_and_deallocframe",
930 "__restore_r16_through_r19_and_deallocframe",
931 "__restore_r16_through_r21_and_deallocframe",
932 "__restore_r16_through_r23_and_deallocframe",
933 "__restore_r16_through_r25_and_deallocframe",
934 "__restore_r16_through_r27_and_deallocframe" };
935
936 const char * V4SpillFromMemoryTailcallFunctions[] = {
937 "__restore_r16_through_r17_and_deallocframe_before_tailcall",
938 "__restore_r16_through_r19_and_deallocframe_before_tailcall",
939 "__restore_r16_through_r21_and_deallocframe_before_tailcall",
940 "__restore_r16_through_r23_and_deallocframe_before_tailcall",
941 "__restore_r16_through_r25_and_deallocframe_before_tailcall",
942 "__restore_r16_through_r27_and_deallocframe_before_tailcall"
943 };
944
945 const char **SpillFunc = nullptr;
946
947 switch(SpillType) {
948 case SK_ToMem:
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000949 SpillFunc = Stkchk ? V4SpillToMemoryStkchkFunctions
950 : V4SpillToMemoryFunctions;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000951 break;
952 case SK_FromMem:
953 SpillFunc = V4SpillFromMemoryFunctions;
954 break;
955 case SK_FromMemTailcall:
956 SpillFunc = V4SpillFromMemoryTailcallFunctions;
957 break;
958 }
959 assert(SpillFunc && "Unknown spill kind");
960
961 // Spill all callee-saved registers up to the highest register used.
962 switch (MaxReg) {
963 case Hexagon::R17:
964 return SpillFunc[0];
965 case Hexagon::R19:
966 return SpillFunc[1];
967 case Hexagon::R21:
968 return SpillFunc[2];
969 case Hexagon::R23:
970 return SpillFunc[3];
971 case Hexagon::R25:
972 return SpillFunc[4];
973 case Hexagon::R27:
974 return SpillFunc[5];
975 default:
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000976 llvm_unreachable("Unhandled maximum callee save register");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000977 }
978 return 0;
979}
980
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000981
James Y Knight5567baf2015-08-15 02:32:35 +0000982int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF,
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000983 int FI, unsigned &FrameReg) const {
984 auto &MFI = *MF.getFrameInfo();
985 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000986
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000987 int Offset = MFI.getObjectOffset(FI);
988 bool HasAlloca = MFI.hasVarSizedObjects();
989 bool HasExtraAlign = HRI.needsStackRealignment(MF);
990 bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
James Y Knight5567baf2015-08-15 02:32:35 +0000991
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000992 unsigned SP = HRI.getStackRegister(), FP = HRI.getFrameRegister();
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +0000993 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
994 unsigned AP = HMFI.getStackAlignBasePhysReg();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000995 unsigned FrameSize = MFI.getStackSize();
996
997 bool UseFP = false, UseAP = false; // Default: use SP (except at -O0).
998 // Use FP at -O0, except when there are objects with extra alignment.
999 // That additional alignment requirement may cause a pad to be inserted,
1000 // which will make it impossible to use FP to access objects located
1001 // past the pad.
1002 if (NoOpt && !HasExtraAlign)
1003 UseFP = true;
1004 if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
1005 // Fixed and preallocated objects will be located before any padding
1006 // so FP must be used to access them.
1007 UseFP |= (HasAlloca || HasExtraAlign);
1008 } else {
1009 if (HasAlloca) {
1010 if (HasExtraAlign)
1011 UseAP = true;
1012 else
1013 UseFP = true;
1014 }
1015 }
1016
1017 // If FP was picked, then there had better be FP.
1018 bool HasFP = hasFP(MF);
1019 assert((HasFP || !UseFP) && "This function must have frame pointer");
1020
1021 // Having FP implies allocframe. Allocframe will store extra 8 bytes:
1022 // FP/LR. If the base register is used to access an object across these
1023 // 8 bytes, then the offset will need to be adjusted by 8.
1024 //
1025 // After allocframe:
1026 // HexagonISelLowering adds 8 to ---+
1027 // the offsets of all stack-based |
1028 // arguments (*) |
1029 // |
1030 // getObjectOffset < 0 0 8 getObjectOffset >= 8
1031 // ------------------------+-----+------------------------> increasing
1032 // <local objects> |FP/LR| <input arguments> addresses
1033 // -----------------+------+-----+------------------------>
1034 // | |
1035 // SP/AP point --+ +-- FP points here (**)
1036 // somewhere on
1037 // this side of FP/LR
1038 //
1039 // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
1040 // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
1041
1042 // The lowering assumes that FP/LR is present, and so the offsets of
1043 // the formal arguments start at 8. If FP/LR is not there we need to
1044 // reduce the offset by 8.
1045 if (Offset > 0 && !HasFP)
1046 Offset -= 8;
1047
1048 if (UseFP)
1049 FrameReg = FP;
1050 else if (UseAP)
1051 FrameReg = AP;
1052 else
1053 FrameReg = SP;
1054
1055 // Calculate the actual offset in the instruction. If there is no FP
1056 // (in other words, no allocframe), then SP will not be adjusted (i.e.
1057 // there will be no SP -= FrameSize), so the frame size should not be
1058 // added to the calculated offset.
1059 int RealOffset = Offset;
1060 if (!UseFP && !UseAP && HasFP)
1061 RealOffset = FrameSize+Offset;
1062 return RealOffset;
Jakob Stoklund Olesen0b97dbc2012-05-30 22:40:03 +00001063}
1064
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001065
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001066bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001067 const CSIVect &CSI, const HexagonRegisterInfo &HRI,
1068 bool &PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001069 if (CSI.empty())
1070 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001071
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001072 MachineBasicBlock::iterator MI = MBB.begin();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001073 PrologueStubs = false;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001074 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001075 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1076 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001077
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001078 if (useSpillFunction(MF, CSI)) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001079 PrologueStubs = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001080 unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001081 bool StkOvrFlowEnabled = EnableStackOVFSanitizer;
1082 const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem,
1083 StkOvrFlowEnabled);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001084 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
Rafael Espindolab1556c42016-06-28 20:13:36 +00001085 bool IsPIC = HTM.isPositionIndependent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001086 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001087
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001088 // Call spill function.
1089 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001090 unsigned SpillOpc;
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001091 if (StkOvrFlowEnabled) {
1092 if (LongCalls)
1093 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT_PIC
1094 : Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT;
1095 else
1096 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC
1097 : Hexagon::SAVE_REGISTERS_CALL_V4STK;
1098 } else {
1099 if (LongCalls)
1100 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_EXT_PIC
1101 : Hexagon::SAVE_REGISTERS_CALL_V4_EXT;
1102 else
1103 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
1104 : Hexagon::SAVE_REGISTERS_CALL_V4;
1105 }
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001106
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001107 MachineInstr *SaveRegsCall =
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001108 BuildMI(MBB, MI, DL, HII.get(SpillOpc))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001109 .addExternalSymbol(SpillFun);
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001110
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001111 // Add callee-saved registers as use.
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001112 addCalleeSaveRegistersAsImpOperand(SaveRegsCall, CSI, false, true);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001113 // Add live in registers.
1114 for (unsigned I = 0; I < CSI.size(); ++I)
1115 MBB.addLiveIn(CSI[I].getReg());
1116 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001117 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001118
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001119 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001120 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001121 // Add live in registers. We treat eh_return callee saved register r0 - r3
1122 // specially. They are not really callee saved registers as they are not
1123 // supposed to be killed.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001124 bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
1125 int FI = CSI[i].getFrameIdx();
1126 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001127 HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001128 if (IsKill)
1129 MBB.addLiveIn(Reg);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001130 }
1131 return true;
1132}
1133
1134
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001135bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
1136 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
1137 if (CSI.empty())
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001138 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001139
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001140 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1141 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001142 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1143 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001144
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001145 if (useRestoreFunction(MF, CSI)) {
1146 bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
1147 unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
1148 SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
1149 const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001150 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
Rafael Espindolab1556c42016-06-28 20:13:36 +00001151 bool IsPIC = HTM.isPositionIndependent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001152 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001153
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001154 // Call spill function.
1155 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
1156 : MBB.getLastNonDebugInstr()->getDebugLoc();
1157 MachineInstr *DeallocCall = nullptr;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001158
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001159 if (HasTC) {
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001160 unsigned RetOpc;
1161 if (LongCalls)
1162 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC
1163 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT;
1164 else
1165 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
1166 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
1167 DeallocCall = BuildMI(MBB, MI, DL, HII.get(RetOpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001168 .addExternalSymbol(RestoreFn);
1169 } else {
1170 // The block has a return.
1171 MachineBasicBlock::iterator It = MBB.getFirstTerminator();
1172 assert(It->isReturn() && std::next(It) == MBB.end());
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001173 unsigned RetOpc;
1174 if (LongCalls)
1175 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC
1176 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT;
1177 else
1178 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
1179 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
1180 DeallocCall = BuildMI(MBB, It, DL, HII.get(RetOpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001181 .addExternalSymbol(RestoreFn);
1182 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +00001183 DeallocCall->copyImplicitOps(MF, *It);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001184 }
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001185 addCalleeSaveRegistersAsImpOperand(DeallocCall, CSI, true, false);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001186 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001187 }
1188
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001189 for (unsigned i = 0; i < CSI.size(); ++i) {
1190 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001191 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1192 int FI = CSI[i].getFrameIdx();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001193 HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001194 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001195
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001196 return true;
1197}
1198
Hans Wennborge1a2e902016-03-31 18:33:38 +00001199MachineBasicBlock::iterator HexagonFrameLowering::eliminateCallFramePseudoInstr(
1200 MachineFunction &MF, MachineBasicBlock &MBB,
1201 MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00001202 MachineInstr &MI = *I;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001203 unsigned Opc = MI.getOpcode();
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001204 (void)Opc; // Silence compiler warning.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001205 assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1206 "Cannot handle this call frame pseudo instruction");
Hans Wennborge1a2e902016-03-31 18:33:38 +00001207 return MBB.erase(I);
Eli Bendersky8da87162013-02-21 20:05:00 +00001208}
1209
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001210
1211void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1212 MachineFunction &MF, RegScavenger *RS) const {
1213 // If this function has uses aligned stack and also has variable sized stack
1214 // objects, then we need to map all spill slots to fixed positions, so that
1215 // they can be accessed through FP. Otherwise they would have to be accessed
1216 // via AP, which may not be available at the particular place in the program.
1217 MachineFrameInfo *MFI = MF.getFrameInfo();
1218 bool HasAlloca = MFI->hasVarSizedObjects();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001219 bool NeedsAlign = (MFI->getMaxAlignment() > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001220
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001221 if (!HasAlloca || !NeedsAlign)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001222 return;
1223
1224 unsigned LFS = MFI->getLocalFrameSize();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001225 for (int i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
1226 if (!MFI->isSpillSlotObjectIndex(i) || MFI->isDeadObjectIndex(i))
1227 continue;
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001228 unsigned S = MFI->getObjectSize(i);
1229 // Reduce the alignment to at most 8. This will require unaligned vector
1230 // stores if they happen here.
1231 unsigned A = std::max(MFI->getObjectAlignment(i), 8U);
1232 MFI->setObjectAlignment(i, 8);
1233 LFS = alignTo(LFS+S, A);
1234 MFI->mapLocalFrameObject(i, -LFS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001235 }
1236
1237 MFI->setLocalFrameSize(LFS);
1238 unsigned A = MFI->getLocalFrameMaxAlign();
1239 assert(A <= 8 && "Unexpected local frame alignment");
1240 if (A == 0)
1241 MFI->setLocalFrameMaxAlign(8);
1242 MFI->setUseLocalStackAllocationBlock(true);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001243
1244 // Set the physical aligned-stack base address register.
1245 unsigned AP = 0;
1246 if (const MachineInstr *AI = getAlignaInstr(MF))
1247 AP = AI->getOperand(0).getReg();
1248 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1249 HMFI.setStackAlignBasePhysReg(AP);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001250}
1251
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001252/// Returns true if there are no caller-saved registers available in class RC.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001253static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001254 const HexagonRegisterInfo &HRI, const TargetRegisterClass *RC) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001255 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001256
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001257 auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1258 for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1259 if (MRI.isPhysRegUsed(*AI))
1260 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001261 return false;
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001262 };
1263
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001264 // Check for an unused caller-saved register. Callee-saved registers
1265 // have become pristine by now.
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001266 for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF, RC); *P; ++P)
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001267 if (!IsUsed(*P))
1268 return false;
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001269
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001270 // All caller-saved registers are used.
1271 return true;
1272}
1273
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001274
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001275#ifndef NDEBUG
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001276static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001277 dbgs() << '{';
1278 for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1279 unsigned R = x;
1280 dbgs() << ' ' << PrintReg(R, &TRI);
1281 }
1282 dbgs() << " }";
1283}
1284#endif
1285
1286
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001287bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1288 const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
Krzysztof Parzyszek27ba19a12015-04-23 20:42:20 +00001289 DEBUG(dbgs() << LLVM_FUNCTION_NAME << " on "
Krzysztof Parzyszeked75e7a2015-04-23 20:57:39 +00001290 << MF.getFunction()->getName() << '\n');
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001291 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001292 BitVector SRegs(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001293
1294 // Generate a set of unique, callee-saved registers (SRegs), where each
1295 // register in the set is maximal in terms of sub-/super-register relation,
1296 // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1297
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001298 // (1) For each callee-saved register, add that register and all of its
1299 // sub-registers to SRegs.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001300 DEBUG(dbgs() << "Initial CS registers: {");
1301 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1302 unsigned R = CSI[i].getReg();
1303 DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1304 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1305 SRegs[*SR] = true;
1306 }
1307 DEBUG(dbgs() << " }\n");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001308 DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001309
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001310 // (2) For each reserved register, remove that register and all of its
1311 // sub- and super-registers from SRegs.
1312 BitVector Reserved = TRI->getReservedRegs(MF);
1313 for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1314 unsigned R = x;
1315 for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1316 SRegs[*SR] = false;
1317 }
1318 DEBUG(dbgs() << "Res: "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1319 DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1320
1321 // (3) Collect all registers that have at least one sub-register in SRegs,
1322 // and also have no sub-registers that are reserved. These will be the can-
1323 // didates for saving as a whole instead of their individual sub-registers.
1324 // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1325 BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001326 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1327 unsigned R = x;
1328 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1329 TmpSup[*SR] = true;
1330 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001331 for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1332 unsigned R = x;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001333 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1334 if (!Reserved[*SR])
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001335 continue;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001336 TmpSup[R] = false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001337 break;
1338 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001339 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001340 DEBUG(dbgs() << "TmpSup: "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001341
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001342 // (4) Include all super-registers found in (3) into SRegs.
1343 SRegs |= TmpSup;
1344 DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001345
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001346 // (5) For each register R in SRegs, if any super-register of R is in SRegs,
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001347 // remove R from SRegs.
1348 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1349 unsigned R = x;
1350 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1351 if (!SRegs[*SR])
1352 continue;
1353 SRegs[R] = false;
1354 break;
1355 }
1356 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001357 DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001358
1359 // Now, for each register that has a fixed stack slot, create the stack
1360 // object for it.
1361 CSI.clear();
1362
1363 typedef TargetFrameLowering::SpillSlot SpillSlot;
1364 unsigned NumFixed;
1365 int MinOffset = 0; // CS offsets are negative.
1366 const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1367 for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1368 if (!SRegs[S->Reg])
1369 continue;
1370 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
1371 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), S->Offset);
1372 MinOffset = std::min(MinOffset, S->Offset);
1373 CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1374 SRegs[S->Reg] = false;
1375 }
1376
1377 // There can be some registers that don't have fixed slots. For example,
1378 // we need to store R0-R3 in functions with exception handling. For each
1379 // such register, create a non-fixed stack object.
1380 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1381 unsigned R = x;
1382 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
1383 int Off = MinOffset - RC->getSize();
1384 unsigned Align = std::min(RC->getAlignment(), getStackAlignment());
1385 assert(isPowerOf2_32(Align));
1386 Off &= -Align;
1387 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), Off);
1388 MinOffset = std::min(MinOffset, Off);
1389 CSI.push_back(CalleeSavedInfo(R, FI));
1390 SRegs[R] = false;
1391 }
1392
1393 DEBUG({
1394 dbgs() << "CS information: {";
1395 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1396 int FI = CSI[i].getFrameIdx();
1397 int Off = MFI->getObjectOffset(FI);
1398 dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1399 if (Off >= 0)
1400 dbgs() << '+';
1401 dbgs() << Off;
1402 }
1403 dbgs() << " }\n";
1404 });
1405
1406#ifndef NDEBUG
1407 // Verify that all registers were handled.
1408 bool MissedReg = false;
1409 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1410 unsigned R = x;
1411 dbgs() << PrintReg(R, TRI) << ' ';
1412 MissedReg = true;
1413 }
1414 if (MissedReg)
1415 llvm_unreachable("...there are unhandled callee-saved registers!");
1416#endif
1417
1418 return true;
1419}
1420
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001421
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001422bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1423 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1424 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1425 MachineInstr *MI = &*It;
1426 DebugLoc DL = MI->getDebugLoc();
1427 unsigned DstR = MI->getOperand(0).getReg();
1428 unsigned SrcR = MI->getOperand(1).getReg();
1429 if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1430 !Hexagon::ModRegsRegClass.contains(SrcR))
1431 return false;
1432
1433 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1434 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR)
1435 .addOperand(MI->getOperand(1));
1436 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1437 .addReg(TmpR, RegState::Kill);
1438
1439 NewRegs.push_back(TmpR);
1440 B.erase(It);
1441 return true;
1442}
1443
1444bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1445 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1446 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1447 MachineInstr *MI = &*It;
1448 DebugLoc DL = MI->getDebugLoc();
1449 unsigned Opc = MI->getOpcode();
1450 unsigned SrcR = MI->getOperand(2).getReg();
1451 bool IsKill = MI->getOperand(2).isKill();
1452
1453 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1454 int FI = MI->getOperand(0).getIndex();
1455
1456 // TmpR = C2_tfrpr SrcR if SrcR is a predicate register
1457 // TmpR = A2_tfrcrr SrcR if SrcR is a modifier register
1458 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1459 unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1460 : Hexagon::A2_tfrcrr;
1461 BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1462 .addReg(SrcR, getKillRegState(IsKill));
1463
1464 // S2_storeri_io FI, 0, TmpR
1465 BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1466 .addFrameIndex(FI)
1467 .addImm(0)
1468 .addReg(TmpR, RegState::Kill)
1469 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1470
1471 NewRegs.push_back(TmpR);
1472 B.erase(It);
1473 return true;
1474}
1475
1476bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1477 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1478 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1479 MachineInstr *MI = &*It;
1480 DebugLoc DL = MI->getDebugLoc();
1481 unsigned Opc = MI->getOpcode();
1482 unsigned DstR = MI->getOperand(0).getReg();
1483
1484 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1485 int FI = MI->getOperand(1).getIndex();
1486
1487 // TmpR = L2_loadri_io FI, 0
1488 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1489 BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1490 .addFrameIndex(FI)
1491 .addImm(0)
1492 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1493
1494 // DstR = C2_tfrrp TmpR if DstR is a predicate register
1495 // DstR = A2_tfrrcr TmpR if DstR is a modifier register
1496 unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1497 : Hexagon::A2_tfrrcr;
1498 BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1499 .addReg(TmpR, RegState::Kill);
1500
1501 NewRegs.push_back(TmpR);
1502 B.erase(It);
1503 return true;
1504}
1505
1506
1507bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1508 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1509 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1510 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1511 MachineInstr *MI = &*It;
1512 DebugLoc DL = MI->getDebugLoc();
1513 unsigned SrcR = MI->getOperand(2).getReg();
1514 bool IsKill = MI->getOperand(2).isKill();
1515
1516 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1517 int FI = MI->getOperand(0).getIndex();
1518
1519 bool Is128B = HST.useHVXDblOps();
1520 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1521 : &Hexagon::VectorRegs128BRegClass;
1522
1523 // Insert transfer to general vector register.
1524 // TmpR0 = A2_tfrsi 0x01010101
1525 // TmpR1 = V6_vandqrt Qx, TmpR0
1526 // store FI, 0, TmpR1
1527 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1528 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1529
1530 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1531 .addImm(0x01010101);
1532
1533 unsigned VandOpc = !Is128B ? Hexagon::V6_vandqrt : Hexagon::V6_vandqrt_128B;
1534 BuildMI(B, It, DL, HII.get(VandOpc), TmpR1)
1535 .addReg(SrcR, getKillRegState(IsKill))
1536 .addReg(TmpR0, RegState::Kill);
1537
1538 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1539 HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1540 expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1541
1542 NewRegs.push_back(TmpR0);
1543 NewRegs.push_back(TmpR1);
1544 B.erase(It);
1545 return true;
1546}
1547
1548bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1549 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1550 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1551 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1552 MachineInstr *MI = &*It;
1553 DebugLoc DL = MI->getDebugLoc();
1554 unsigned DstR = MI->getOperand(0).getReg();
1555
1556 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1557 int FI = MI->getOperand(1).getIndex();
1558
1559 bool Is128B = HST.useHVXDblOps();
1560 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1561 : &Hexagon::VectorRegs128BRegClass;
1562
1563 // TmpR0 = A2_tfrsi 0x01010101
1564 // TmpR1 = load FI, 0
1565 // DstR = V6_vandvrt TmpR1, TmpR0
1566 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1567 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1568
1569 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1570 .addImm(0x01010101);
1571 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1572 HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1573 expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1574
1575 unsigned VandOpc = !Is128B ? Hexagon::V6_vandvrt : Hexagon::V6_vandvrt_128B;
1576 BuildMI(B, It, DL, HII.get(VandOpc), DstR)
1577 .addReg(TmpR1, RegState::Kill)
1578 .addReg(TmpR0, RegState::Kill);
1579
1580 NewRegs.push_back(TmpR0);
1581 NewRegs.push_back(TmpR1);
1582 B.erase(It);
1583 return true;
1584}
1585
1586bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1587 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1588 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1589 MachineFunction &MF = *B.getParent();
1590 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1591 auto &MFI = *MF.getFrameInfo();
1592 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1593 MachineInstr *MI = &*It;
1594 DebugLoc DL = MI->getDebugLoc();
1595
1596 unsigned SrcR = MI->getOperand(2).getReg();
1597 unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::subreg_loreg);
1598 unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::subreg_hireg);
1599 bool IsKill = MI->getOperand(2).isKill();
1600
1601 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1602 int FI = MI->getOperand(0).getIndex();
1603
1604 bool Is128B = HST.useHVXDblOps();
1605 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1606 : &Hexagon::VectorRegs128BRegClass;
1607 unsigned Size = RC->getSize();
1608 unsigned NeedAlign = RC->getAlignment();
1609 unsigned HasAlign = MFI.getObjectAlignment(FI);
1610 unsigned StoreOpc;
1611
1612 // Store low part.
1613 if (NeedAlign <= HasAlign)
1614 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1615 else
1616 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1617
1618 BuildMI(B, It, DL, HII.get(StoreOpc))
1619 .addFrameIndex(FI)
1620 .addImm(0)
1621 .addReg(SrcLo, getKillRegState(IsKill))
1622 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1623
1624 // Load high part.
1625 if (NeedAlign <= MinAlign(HasAlign, Size))
1626 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1627 else
1628 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1629
1630 BuildMI(B, It, DL, HII.get(StoreOpc))
1631 .addFrameIndex(FI)
1632 .addImm(Size)
1633 .addReg(SrcHi, getKillRegState(IsKill))
1634 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1635
1636 B.erase(It);
1637 return true;
1638}
1639
1640bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1641 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1642 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1643 MachineFunction &MF = *B.getParent();
1644 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1645 auto &MFI = *MF.getFrameInfo();
1646 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1647 MachineInstr *MI = &*It;
1648 DebugLoc DL = MI->getDebugLoc();
1649
1650 unsigned DstR = MI->getOperand(0).getReg();
1651 unsigned DstHi = HRI.getSubReg(DstR, Hexagon::subreg_hireg);
1652 unsigned DstLo = HRI.getSubReg(DstR, Hexagon::subreg_loreg);
1653
1654 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1655 int FI = MI->getOperand(1).getIndex();
1656
1657 bool Is128B = HST.useHVXDblOps();
1658 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1659 : &Hexagon::VectorRegs128BRegClass;
1660 unsigned Size = RC->getSize();
1661 unsigned NeedAlign = RC->getAlignment();
1662 unsigned HasAlign = MFI.getObjectAlignment(FI);
1663 unsigned LoadOpc;
1664
1665 // Load low part.
1666 if (NeedAlign <= HasAlign)
1667 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1668 else
1669 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1670
1671 BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1672 .addFrameIndex(FI)
1673 .addImm(0)
1674 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1675
1676 // Load high part.
1677 if (NeedAlign <= MinAlign(HasAlign, Size))
1678 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1679 else
1680 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1681
1682 BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1683 .addFrameIndex(FI)
1684 .addImm(Size)
1685 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1686
1687 B.erase(It);
1688 return true;
1689}
1690
1691bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1692 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1693 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1694 MachineFunction &MF = *B.getParent();
1695 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1696 auto &MFI = *MF.getFrameInfo();
1697 MachineInstr *MI = &*It;
1698 DebugLoc DL = MI->getDebugLoc();
1699
1700 unsigned SrcR = MI->getOperand(2).getReg();
1701 bool IsKill = MI->getOperand(2).isKill();
1702
1703 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1704 int FI = MI->getOperand(0).getIndex();
1705
1706 bool Is128B = HST.useHVXDblOps();
1707 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1708 : &Hexagon::VectorRegs128BRegClass;
1709
1710 unsigned NeedAlign = RC->getAlignment();
1711 unsigned HasAlign = MFI.getObjectAlignment(FI);
1712 unsigned StoreOpc;
1713
1714 if (NeedAlign <= HasAlign)
1715 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1716 else
1717 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1718
1719 BuildMI(B, It, DL, HII.get(StoreOpc))
1720 .addFrameIndex(FI)
1721 .addImm(0)
1722 .addReg(SrcR, getKillRegState(IsKill))
1723 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1724
1725 B.erase(It);
1726 return true;
1727}
1728
1729bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
1730 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1731 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1732 MachineFunction &MF = *B.getParent();
1733 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1734 auto &MFI = *MF.getFrameInfo();
1735 MachineInstr *MI = &*It;
1736 DebugLoc DL = MI->getDebugLoc();
1737
1738 unsigned DstR = MI->getOperand(0).getReg();
1739
1740 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1741 int FI = MI->getOperand(1).getIndex();
1742
1743 bool Is128B = HST.useHVXDblOps();
1744 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1745 : &Hexagon::VectorRegs128BRegClass;
1746
1747 unsigned NeedAlign = RC->getAlignment();
1748 unsigned HasAlign = MFI.getObjectAlignment(FI);
1749 unsigned LoadOpc;
1750
1751 if (NeedAlign <= HasAlign)
1752 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1753 else
1754 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1755
1756 BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1757 .addFrameIndex(FI)
1758 .addImm(0)
1759 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1760
1761 B.erase(It);
1762 return true;
1763}
1764
1765
1766bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1767 SmallVectorImpl<unsigned> &NewRegs) const {
1768 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001769 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001770 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001771 bool Changed = false;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001772
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001773 for (auto &B : MF) {
1774 // Traverse the basic block.
1775 MachineBasicBlock::iterator NextI;
1776 for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1777 MachineInstr *MI = &*I;
1778 NextI = std::next(I);
1779 unsigned Opc = MI->getOpcode();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001780
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001781 switch (Opc) {
1782 case TargetOpcode::COPY:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001783 Changed |= expandCopy(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001784 break;
1785 case Hexagon::STriw_pred:
1786 case Hexagon::STriw_mod:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001787 Changed |= expandStoreInt(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001788 break;
1789 case Hexagon::LDriw_pred:
1790 case Hexagon::LDriw_mod:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001791 Changed |= expandLoadInt(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001792 break;
1793 case Hexagon::STriq_pred_V6:
1794 case Hexagon::STriq_pred_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001795 Changed |= expandStoreVecPred(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001796 break;
1797 case Hexagon::LDriq_pred_V6:
1798 case Hexagon::LDriq_pred_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001799 Changed |= expandLoadVecPred(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001800 break;
1801 case Hexagon::LDrivv_pseudo_V6:
1802 case Hexagon::LDrivv_pseudo_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001803 Changed |= expandLoadVec2(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001804 break;
1805 case Hexagon::STrivv_pseudo_V6:
1806 case Hexagon::STrivv_pseudo_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001807 Changed |= expandStoreVec2(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001808 break;
1809 case Hexagon::STriv_pseudo_V6:
1810 case Hexagon::STriv_pseudo_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001811 Changed |= expandStoreVec(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001812 break;
1813 case Hexagon::LDriv_pseudo_V6:
1814 case Hexagon::LDriv_pseudo_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001815 Changed |= expandLoadVec(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001816 break;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001817 }
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001818 }
1819 }
1820
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001821 return Changed;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001822}
1823
1824
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001825void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1826 BitVector &SavedRegs,
1827 RegScavenger *RS) const {
1828 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1829 auto &HRI = *HST.getRegisterInfo();
1830
1831 SavedRegs.resize(HRI.getNumRegs());
1832
1833 // If we have a function containing __builtin_eh_return we want to spill and
1834 // restore all callee saved registers. Pretend that they are used.
1835 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1836 for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1837 SavedRegs.set(*R);
1838
1839 // Replace predicate register pseudo spill code.
1840 SmallVector<unsigned,8> NewRegs;
1841 expandSpillMacros(MF, NewRegs);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001842 if (OptimizeSpillSlots && !isOptNone(MF))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001843 optimizeSpillSlots(MF, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001844
1845 // We need to reserve a a spill slot if scavenging could potentially require
1846 // spilling a scavenged register.
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001847 if (!NewRegs.empty()) {
1848 MachineFrameInfo &MFI = *MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001849 MachineRegisterInfo &MRI = MF.getRegInfo();
1850 SetVector<const TargetRegisterClass*> SpillRCs;
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001851 // Reserve an int register in any case, because it could be used to hold
1852 // the stack offset in case it does not fit into a spill instruction.
1853 SpillRCs.insert(&Hexagon::IntRegsRegClass);
1854
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001855 for (unsigned VR : NewRegs)
1856 SpillRCs.insert(MRI.getRegClass(VR));
1857
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001858 for (auto *RC : SpillRCs) {
1859 if (!needToReserveScavengingSpillSlots(MF, HRI, RC))
1860 continue;
1861 unsigned Num = RC == &Hexagon::IntRegsRegClass ? NumberScavengerSlots : 1;
1862 unsigned S = RC->getSize(), A = RC->getAlignment();
1863 for (unsigned i = 0; i < Num; i++) {
1864 int NewFI = MFI.CreateSpillStackObject(S, A);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001865 RS->addScavengingFrameIndex(NewFI);
1866 }
1867 }
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001868 }
1869
1870 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1871}
1872
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001873
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001874unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1875 HexagonBlockRanges::IndexRange &FIR,
1876 HexagonBlockRanges::InstrIndexMap &IndexMap,
1877 HexagonBlockRanges::RegToRangeMap &DeadMap,
1878 const TargetRegisterClass *RC) const {
1879 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1880 auto &MRI = MF.getRegInfo();
1881
1882 auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1883 auto F = DeadMap.find({Reg,0});
1884 if (F == DeadMap.end())
1885 return false;
1886 for (auto &DR : F->second)
1887 if (DR.contains(FIR))
1888 return true;
1889 return false;
1890 };
1891
1892 for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
1893 bool Dead = true;
1894 for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
1895 if (isDead(R.Reg))
1896 continue;
1897 Dead = false;
1898 break;
1899 }
1900 if (Dead)
1901 return Reg;
1902 }
1903 return 0;
1904}
1905
1906void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
1907 SmallVectorImpl<unsigned> &VRegs) const {
1908 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1909 auto &HII = *HST.getInstrInfo();
1910 auto &HRI = *HST.getRegisterInfo();
1911 auto &MRI = MF.getRegInfo();
1912 HexagonBlockRanges HBR(MF);
1913
1914 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::InstrIndexMap>
1915 BlockIndexMap;
1916 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::RangeList>
1917 BlockRangeMap;
1918 typedef HexagonBlockRanges::IndexType IndexType;
1919
1920 struct SlotInfo {
1921 BlockRangeMap Map;
NAKAMURA Takumic2cc8702016-02-13 07:29:49 +00001922 unsigned Size;
1923 const TargetRegisterClass *RC;
1924
1925 SlotInfo() : Map(), Size(0), RC(nullptr) {}
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001926 };
1927
1928 BlockIndexMap BlockIndexes;
1929 SmallSet<int,4> BadFIs;
1930 std::map<int,SlotInfo> FIRangeMap;
1931
1932 auto getRegClass = [&MRI,&HRI] (HexagonBlockRanges::RegisterRef R)
1933 -> const TargetRegisterClass* {
1934 if (TargetRegisterInfo::isPhysicalRegister(R.Reg))
1935 assert(R.Sub == 0);
1936 if (TargetRegisterInfo::isVirtualRegister(R.Reg)) {
1937 auto *RCR = MRI.getRegClass(R.Reg);
1938 if (R.Sub == 0)
1939 return RCR;
1940 unsigned PR = *RCR->begin();
1941 R.Reg = HRI.getSubReg(PR, R.Sub);
1942 }
1943 return HRI.getMinimalPhysRegClass(R.Reg);
1944 };
1945 // Accumulate register classes: get a common class for a pre-existing
1946 // class HaveRC and a new class NewRC. Return nullptr if a common class
1947 // cannot be found, otherwise return the resulting class. If HaveRC is
1948 // nullptr, assume that it is still unset.
1949 auto getCommonRC = [&HRI] (const TargetRegisterClass *HaveRC,
1950 const TargetRegisterClass *NewRC)
1951 -> const TargetRegisterClass* {
1952 if (HaveRC == nullptr || HaveRC == NewRC)
1953 return NewRC;
1954 // Different classes, both non-null. Pick the more general one.
1955 if (HaveRC->hasSubClassEq(NewRC))
1956 return HaveRC;
1957 if (NewRC->hasSubClassEq(HaveRC))
1958 return NewRC;
1959 return nullptr;
1960 };
1961
1962 // Scan all blocks in the function. Check all occurrences of frame indexes,
1963 // and collect relevant information.
1964 for (auto &B : MF) {
1965 std::map<int,IndexType> LastStore, LastLoad;
Krzysztof Parzyszek280a50e2016-02-13 14:06:01 +00001966 // Emplace appears not to be supported in gcc 4.7.2-4.
1967 //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
Krzysztof Parzyszekde697d42016-02-17 15:02:07 +00001968 auto P = BlockIndexes.insert(
1969 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001970 auto &IndexMap = P.first->second;
1971 DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n"
1972 << IndexMap << '\n');
1973
1974 for (auto &In : B) {
1975 int LFI, SFI;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001976 bool Load = HII.isLoadFromStackSlot(In, LFI) && !HII.isPredicated(In);
1977 bool Store = HII.isStoreToStackSlot(In, SFI) && !HII.isPredicated(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001978 if (Load && Store) {
1979 // If it's both a load and a store, then we won't handle it.
1980 BadFIs.insert(LFI);
1981 BadFIs.insert(SFI);
1982 continue;
1983 }
1984 // Check for register classes of the register used as the source for
1985 // the store, and the register used as the destination for the load.
1986 // Also, only accept base+imm_offset addressing modes. Other addressing
1987 // modes can have side-effects (post-increments, etc.). For stack
1988 // slots they are very unlikely, so there is not much loss due to
1989 // this restriction.
1990 if (Load || Store) {
1991 int TFI = Load ? LFI : SFI;
1992 unsigned AM = HII.getAddrMode(&In);
1993 SlotInfo &SI = FIRangeMap[TFI];
1994 bool Bad = (AM != HexagonII::BaseImmOffset);
1995 if (!Bad) {
1996 // If the addressing mode is ok, check the register class.
1997 const TargetRegisterClass *RC = nullptr;
1998 if (Load) {
1999 MachineOperand &DataOp = In.getOperand(0);
2000 RC = getRegClass({DataOp.getReg(), DataOp.getSubReg()});
2001 } else {
2002 MachineOperand &DataOp = In.getOperand(2);
2003 RC = getRegClass({DataOp.getReg(), DataOp.getSubReg()});
2004 }
2005 RC = getCommonRC(SI.RC, RC);
2006 if (RC == nullptr)
2007 Bad = true;
2008 else
2009 SI.RC = RC;
2010 }
2011 if (!Bad) {
2012 // Check sizes.
2013 unsigned S = (1U << (HII.getMemAccessSize(&In) - 1));
2014 if (SI.Size != 0 && SI.Size != S)
2015 Bad = true;
2016 else
2017 SI.Size = S;
2018 }
2019 if (Bad)
2020 BadFIs.insert(TFI);
2021 }
2022
2023 // Locate uses of frame indices.
2024 for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
2025 const MachineOperand &Op = In.getOperand(i);
2026 if (!Op.isFI())
2027 continue;
2028 int FI = Op.getIndex();
2029 // Make sure that the following operand is an immediate and that
2030 // it is 0. This is the offset in the stack object.
2031 if (i+1 >= n || !In.getOperand(i+1).isImm() ||
2032 In.getOperand(i+1).getImm() != 0)
2033 BadFIs.insert(FI);
2034 if (BadFIs.count(FI))
2035 continue;
2036
2037 IndexType Index = IndexMap.getIndex(&In);
2038 if (Load) {
2039 if (LastStore[FI] == IndexType::None)
2040 LastStore[FI] = IndexType::Entry;
2041 LastLoad[FI] = Index;
2042 } else if (Store) {
2043 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2044 if (LastStore[FI] != IndexType::None)
2045 RL.add(LastStore[FI], LastLoad[FI], false, false);
2046 else if (LastLoad[FI] != IndexType::None)
2047 RL.add(IndexType::Entry, LastLoad[FI], false, false);
2048 LastLoad[FI] = IndexType::None;
2049 LastStore[FI] = Index;
2050 } else {
2051 BadFIs.insert(FI);
2052 }
2053 }
2054 }
2055
2056 for (auto &I : LastLoad) {
2057 IndexType LL = I.second;
2058 if (LL == IndexType::None)
2059 continue;
2060 auto &RL = FIRangeMap[I.first].Map[&B];
2061 IndexType &LS = LastStore[I.first];
2062 if (LS != IndexType::None)
2063 RL.add(LS, LL, false, false);
2064 else
2065 RL.add(IndexType::Entry, LL, false, false);
2066 LS = IndexType::None;
2067 }
2068 for (auto &I : LastStore) {
2069 IndexType LS = I.second;
2070 if (LS == IndexType::None)
2071 continue;
2072 auto &RL = FIRangeMap[I.first].Map[&B];
2073 RL.add(LS, IndexType::None, false, false);
2074 }
2075 }
2076
2077 DEBUG({
2078 for (auto &P : FIRangeMap) {
2079 dbgs() << "fi#" << P.first;
2080 if (BadFIs.count(P.first))
2081 dbgs() << " (bad)";
2082 dbgs() << " RC: ";
2083 if (P.second.RC != nullptr)
2084 dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
2085 else
2086 dbgs() << "<null>\n";
2087 for (auto &R : P.second.Map)
2088 dbgs() << " BB#" << R.first->getNumber() << " { " << R.second << "}\n";
2089 }
2090 });
2091
2092 // When a slot is loaded from in a block without being stored to in the
2093 // same block, it is live-on-entry to this block. To avoid CFG analysis,
2094 // consider this slot to be live-on-exit from all blocks.
2095 SmallSet<int,4> LoxFIs;
2096
2097 std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
2098
2099 for (auto &P : FIRangeMap) {
2100 // P = pair(FI, map: BB->RangeList)
2101 if (BadFIs.count(P.first))
2102 continue;
2103 for (auto &B : MF) {
2104 auto F = P.second.Map.find(&B);
2105 // F = pair(BB, RangeList)
2106 if (F == P.second.Map.end() || F->second.empty())
2107 continue;
2108 HexagonBlockRanges::IndexRange &IR = F->second.front();
2109 if (IR.start() == IndexType::Entry)
2110 LoxFIs.insert(P.first);
2111 BlockFIMap[&B].push_back(P.first);
2112 }
2113 }
2114
2115 DEBUG({
2116 dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
2117 for (auto &P : BlockFIMap) {
2118 auto &FIs = P.second;
2119 if (FIs.empty())
2120 continue;
2121 dbgs() << " BB#" << P.first->getNumber() << ": {";
2122 for (auto I : FIs) {
2123 dbgs() << " fi#" << I;
2124 if (LoxFIs.count(I))
2125 dbgs() << '*';
2126 }
2127 dbgs() << " }\n";
2128 }
2129 });
2130
2131 // eliminate loads, when all loads eliminated, eliminate all stores.
2132 for (auto &B : MF) {
2133 auto F = BlockIndexes.find(&B);
2134 assert(F != BlockIndexes.end());
2135 HexagonBlockRanges::InstrIndexMap &IM = F->second;
2136 HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
2137 HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
2138 DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n"
2139 << HexagonBlockRanges::PrintRangeMap(DM, HRI));
2140
2141 for (auto FI : BlockFIMap[&B]) {
2142 if (BadFIs.count(FI))
2143 continue;
2144 DEBUG(dbgs() << "Working on fi#" << FI << '\n');
2145 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2146 for (auto &Range : RL) {
2147 DEBUG(dbgs() << "--Examining range:" << RL << '\n');
2148 if (!IndexType::isInstr(Range.start()) ||
2149 !IndexType::isInstr(Range.end()))
2150 continue;
2151 MachineInstr *SI = IM.getInstr(Range.start());
2152 MachineInstr *EI = IM.getInstr(Range.end());
2153 assert(SI->mayStore() && "Unexpected start instruction");
2154 assert(EI->mayLoad() && "Unexpected end instruction");
2155 MachineOperand &SrcOp = SI->getOperand(2);
2156
2157 HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
2158 SrcOp.getSubReg() };
2159 auto *RC = getRegClass({SrcOp.getReg(), SrcOp.getSubReg()});
2160 // The this-> is needed to unconfuse MSVC.
2161 unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
2162 DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n');
2163 if (FoundR == 0)
2164 continue;
2165
2166 // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
2167 MachineBasicBlock::iterator StartIt = SI, NextIt;
2168 MachineInstr *CopyIn = nullptr;
2169 if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
Benjamin Kramer4ca41fd2016-06-12 17:30:47 +00002170 const DebugLoc &DL = SI->getDebugLoc();
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002171 CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
2172 .addOperand(SrcOp);
2173 }
2174
2175 ++StartIt;
2176 // Check if this is a last store and the FI is live-on-exit.
2177 if (LoxFIs.count(FI) && (&Range == &RL.back())) {
2178 // Update store's source register.
2179 if (unsigned SR = SrcOp.getSubReg())
2180 SrcOp.setReg(HRI.getSubReg(FoundR, SR));
2181 else
2182 SrcOp.setReg(FoundR);
2183 SrcOp.setSubReg(0);
2184 // We are keeping this register live.
2185 SrcOp.setIsKill(false);
2186 } else {
2187 B.erase(SI);
2188 IM.replaceInstr(SI, CopyIn);
2189 }
2190
2191 auto EndIt = std::next(MachineBasicBlock::iterator(EI));
2192 for (auto It = StartIt; It != EndIt; It = NextIt) {
2193 MachineInstr *MI = &*It;
2194 NextIt = std::next(It);
2195 int TFI;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00002196 if (!HII.isLoadFromStackSlot(*MI, TFI) || TFI != FI)
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002197 continue;
2198 unsigned DstR = MI->getOperand(0).getReg();
2199 assert(MI->getOperand(0).getSubReg() == 0);
2200 MachineInstr *CopyOut = nullptr;
2201 if (DstR != FoundR) {
2202 DebugLoc DL = MI->getDebugLoc();
2203 unsigned MemSize = (1U << (HII.getMemAccessSize(MI) - 1));
2204 assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2205 unsigned CopyOpc = TargetOpcode::COPY;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00002206 if (HII.isSignExtendingLoad(*MI))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002207 CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00002208 else if (HII.isZeroExtendingLoad(*MI))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002209 CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2210 CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
2211 .addReg(FoundR, getKillRegState(MI == EI));
2212 }
2213 IM.replaceInstr(MI, CopyOut);
2214 B.erase(It);
2215 }
2216
2217 // Update the dead map.
2218 HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2219 for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2220 DM[RR].subtract(Range);
2221 } // for Range in range list
2222 }
2223 }
2224}
2225
2226
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002227void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002228 const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002229 MachineBasicBlock &MB = *AI->getParent();
2230 DebugLoc DL = AI->getDebugLoc();
2231 unsigned A = AI->getOperand(2).getImm();
2232
2233 // Have
2234 // Rd = alloca Rs, #A
2235 //
2236 // If Rs and Rd are different registers, use this sequence:
2237 // Rd = sub(r29, Rs)
2238 // r29 = sub(r29, Rs)
2239 // Rd = and(Rd, #-A) ; if necessary
2240 // r29 = and(r29, #-A) ; if necessary
2241 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2242 // otherwise, do
2243 // Rd = sub(r29, Rs)
2244 // Rd = and(Rd, #-A) ; if necessary
2245 // r29 = Rd
2246 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2247
2248 MachineOperand &RdOp = AI->getOperand(0);
2249 MachineOperand &RsOp = AI->getOperand(1);
2250 unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2251
2252 // Rd = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002253 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002254 .addReg(SP)
2255 .addReg(Rs);
2256 if (Rs != Rd) {
2257 // r29 = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002258 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002259 .addReg(SP)
2260 .addReg(Rs);
2261 }
2262 if (A > 8) {
2263 // Rd = and(Rd, #-A)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002264 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002265 .addReg(Rd)
2266 .addImm(-int64_t(A));
2267 if (Rs != Rd)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002268 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002269 .addReg(SP)
2270 .addImm(-int64_t(A));
2271 }
2272 if (Rs == Rd) {
2273 // r29 = Rd
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002274 BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002275 .addReg(Rd);
2276 }
2277 if (CF > 0) {
2278 // Rd = add(Rd, #CF)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002279 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002280 .addReg(Rd)
2281 .addImm(CF);
2282 }
2283}
2284
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002285
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002286bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
2287 const MachineFrameInfo *MFI = MF.getFrameInfo();
2288 if (!MFI->hasVarSizedObjects())
2289 return false;
2290 unsigned MaxA = MFI->getMaxAlignment();
2291 if (MaxA <= getStackAlignment())
2292 return false;
2293 return true;
2294}
2295
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002296
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00002297const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2298 const MachineFunction &MF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002299 for (auto &B : MF)
2300 for (auto &I : B)
2301 if (I.getOpcode() == Hexagon::ALIGNA)
2302 return &I;
2303 return nullptr;
2304}
2305
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002306
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00002307/// Adds all callee-saved registers as implicit uses or defs to the
2308/// instruction.
2309void HexagonFrameLowering::addCalleeSaveRegistersAsImpOperand(MachineInstr *MI,
2310 const CSIVect &CSI, bool IsDef, bool IsKill) const {
2311 // Add the callee-saved registers as implicit uses.
2312 for (auto &R : CSI)
2313 MI->addOperand(MachineOperand::CreateReg(R.getReg(), IsDef, true, IsKill));
2314}
2315
2316
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002317/// Determine whether the callee-saved register saves and restores should
2318/// be generated via inline code. If this function returns "true", inline
2319/// code will be generated. If this function returns "false", additional
2320/// checks are performed, which may still lead to the inline code.
2321bool HexagonFrameLowering::shouldInlineCSR(MachineFunction &MF,
2322 const CSIVect &CSI) const {
2323 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2324 return true;
2325 if (!isOptSize(MF) && !isMinSize(MF))
2326 if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2327 return true;
2328
2329 // Check if CSI only has double registers, and if the registers form
2330 // a contiguous block starting from D8.
2331 BitVector Regs(Hexagon::NUM_TARGET_REGS);
2332 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2333 unsigned R = CSI[i].getReg();
2334 if (!Hexagon::DoubleRegsRegClass.contains(R))
2335 return true;
2336 Regs[R] = true;
2337 }
2338 int F = Regs.find_first();
2339 if (F != Hexagon::D8)
2340 return true;
2341 while (F >= 0) {
2342 int N = Regs.find_next(F);
2343 if (N >= 0 && N != F+1)
2344 return true;
2345 F = N;
2346 }
2347
2348 return false;
2349}
2350
2351
2352bool HexagonFrameLowering::useSpillFunction(MachineFunction &MF,
2353 const CSIVect &CSI) const {
2354 if (shouldInlineCSR(MF, CSI))
2355 return false;
2356 unsigned NumCSI = CSI.size();
2357 if (NumCSI <= 1)
2358 return false;
2359
2360 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2361 : SpillFuncThreshold;
2362 return Threshold < NumCSI;
2363}
2364
2365
2366bool HexagonFrameLowering::useRestoreFunction(MachineFunction &MF,
2367 const CSIVect &CSI) const {
2368 if (shouldInlineCSR(MF, CSI))
2369 return false;
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002370 // The restore functions do a bit more than just restoring registers.
2371 // The non-returning versions will go back directly to the caller's
2372 // caller, others will clean up the stack frame in preparation for
2373 // a tail call. Using them can still save code size even if only one
2374 // register is getting restores. Make the decision based on -Oz:
2375 // using -Os will use inline restore for a single register.
2376 if (isMinSize(MF))
2377 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002378 unsigned NumCSI = CSI.size();
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002379 if (NumCSI <= 1)
2380 return false;
2381
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002382 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2383 : SpillFuncThreshold;
2384 return Threshold < NumCSI;
2385}