blob: 22811487bf6b81a8a0228255d810c2a331703a52 [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 Parzyszekb71085b2016-10-21 16:38:29 +000022#include "llvm/CodeGen/LivePhysRegs.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000023#include "llvm/CodeGen/MachineDominators.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000024#include "llvm/CodeGen/MachineFunction.h"
25#include "llvm/CodeGen/MachineFunctionPass.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/CodeGen/MachineInstrBuilder.h"
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +000027#include "llvm/CodeGen/MachineInstrBuilder.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000028#include "llvm/CodeGen/MachineModuleInfo.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000029#include "llvm/CodeGen/MachinePostDominators.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000030#include "llvm/CodeGen/MachineRegisterInfo.h"
31#include "llvm/CodeGen/RegisterScavenging.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Function.h"
33#include "llvm/IR/Type.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Support/CommandLine.h"
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000035#include "llvm/Support/Debug.h"
36#include "llvm/Support/raw_ostream.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000037#include "llvm/Target/TargetInstrInfo.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000038#include "llvm/Target/TargetMachine.h"
39#include "llvm/Target/TargetOptions.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000040
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000041// Hexagon stack frame layout as defined by the ABI:
42//
43// Incoming arguments
44// passed via stack
45// |
46// |
47// SP during function's FP during function's |
48// +-- runtime (top of stack) runtime (bottom) --+ |
49// | | |
50// --++---------------------+------------------+-----------------++-+-------
51// | parameter area for | variable-size | fixed-size |LR| arg
52// | called functions | local objects | local objects |FP|
53// --+----------------------+------------------+-----------------+--+-------
54// <- size known -> <- size unknown -> <- size known ->
55//
56// Low address High address
57//
58// <--- stack growth
59//
60//
61// - In any circumstances, the outgoing function arguments are always accessi-
62// ble using the SP, and the incoming arguments are accessible using the FP.
63// - If the local objects are not aligned, they can always be accessed using
64// the FP.
65// - If there are no variable-sized objects, the local objects can always be
66// accessed using the SP, regardless whether they are aligned or not. (The
67// alignment padding will be at the bottom of the stack (highest address),
68// and so the offset with respect to the SP will be known at the compile-
69// -time.)
70//
71// The only complication occurs if there are both, local aligned objects, and
72// dynamically allocated (variable-sized) objects. The alignment pad will be
73// placed between the FP and the local objects, thus preventing the use of the
74// FP to access the local objects. At the same time, the variable-sized objects
75// will be between the SP and the local objects, thus introducing an unknown
76// distance from the SP to the locals.
77//
78// To avoid this problem, a new register is created that holds the aligned
79// address of the bottom of the stack, referred in the sources as AP (aligned
80// pointer). The AP will be equal to "FP-p", where "p" is the smallest pad
81// that aligns AP to the required boundary (a maximum of the alignments of
82// all stack objects, fixed- and variable-sized). All local objects[1] will
83// then use AP as the base pointer.
84// [1] The exception is with "fixed" stack objects. "Fixed" stack objects get
85// their name from being allocated at fixed locations on the stack, relative
86// to the FP. In the presence of dynamic allocation and local alignment, such
87// objects can only be accessed through the FP.
88//
89// Illustration of the AP:
90// FP --+
91// |
92// ---------------+---------------------+-----+-----------------------++-+--
93// Rest of the | Local stack objects | Pad | Fixed stack objects |LR|
94// stack frame | (aligned) | | (CSR, spills, etc.) |FP|
95// ---------------+---------------------+-----+-----------------+-----+--+--
96// |<-- Multiple of the -->|
97// stack alignment +-- AP
98//
99// The AP is set up at the beginning of the function. Since it is not a dedi-
100// cated (reserved) register, it needs to be kept live throughout the function
101// to be available as the base register for local object accesses.
102// Normally, an address of a stack objects is obtained by a pseudo-instruction
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000103// PS_fi. To access local objects with the AP register present, a different
104// pseudo-instruction needs to be used: PS_fia. The PS_fia takes one extra
105// argument compared to PS_fi: the first input register is the AP register.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000106// This keeps the register live between its definition and its uses.
107
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000108// The AP register is originally set up using pseudo-instruction PS_aligna:
109// AP = PS_aligna A
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000110// where
111// A - required stack alignment
112// The alignment value must be the maximum of all alignments required by
113// any stack object.
114
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000115// The dynamic allocation uses a pseudo-instruction PS_alloca:
116// Rd = PS_alloca Rs, A
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000117// where
118// Rd - address of the allocated space
119// Rs - minimum size (the actual allocated can be larger to accommodate
120// alignment)
121// A - required alignment
122
123
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000124using namespace llvm;
125
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000126static cl::opt<bool> DisableDeallocRet("disable-hexagon-dealloc-ret",
127 cl::Hidden, cl::desc("Disable Dealloc Return for Hexagon target"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000128
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +0000129static cl::opt<unsigned> NumberScavengerSlots("number-scavenger-slots",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000130 cl::Hidden, cl::desc("Set the number of scavenger slots"), cl::init(2),
131 cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000132
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000133static cl::opt<int> SpillFuncThreshold("spill-func-threshold",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000134 cl::Hidden, cl::desc("Specify O2(not Os) spill func threshold"),
135 cl::init(6), cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000136
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000137static cl::opt<int> SpillFuncThresholdOs("spill-func-threshold-Os",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000138 cl::Hidden, cl::desc("Specify Os spill func threshold"),
139 cl::init(1), cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000140
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000141static cl::opt<bool> EnableStackOVFSanitizer("enable-stackovf-sanitizer",
142 cl::Hidden, cl::desc("Enable runtime checks for stack overflow."),
143 cl::init(false), cl::ZeroOrMore);
144
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000145static cl::opt<bool> EnableShrinkWrapping("hexagon-shrink-frame",
146 cl::init(true), cl::Hidden, cl::ZeroOrMore,
147 cl::desc("Enable stack frame shrink wrapping"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000148
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000149static cl::opt<unsigned> ShrinkLimit("shrink-frame-limit", cl::init(UINT_MAX),
150 cl::Hidden, cl::ZeroOrMore, cl::desc("Max count of stack frame "
151 "shrink-wraps"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000152
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000153static cl::opt<bool> EnableSaveRestoreLong("enable-save-restore-long",
154 cl::Hidden, cl::desc("Enable long calls for save-restore stubs."),
155 cl::init(false), cl::ZeroOrMore);
156
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000157static cl::opt<bool> UseAllocframe("use-allocframe", cl::init(true),
158 cl::Hidden, cl::desc("Use allocframe more conservatively"));
159
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +0000160static cl::opt<bool> OptimizeSpillSlots("hexagon-opt-spill", cl::Hidden,
161 cl::init(true), cl::desc("Optimize spill slots"));
162
Krzysztof Parzyszekdc421642016-07-27 20:58:43 +0000163#ifndef NDEBUG
164static cl::opt<unsigned> SpillOptMax("spill-opt-max", cl::Hidden,
165 cl::init(UINT_MAX));
166static unsigned SpillOptCount = 0;
167#endif
168
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000169
170namespace llvm {
171 void initializeHexagonCallFrameInformationPass(PassRegistry&);
172 FunctionPass *createHexagonCallFrameInformation();
173}
174
175namespace {
176 class HexagonCallFrameInformation : public MachineFunctionPass {
177 public:
178 static char ID;
179 HexagonCallFrameInformation() : MachineFunctionPass(ID) {
180 PassRegistry &PR = *PassRegistry::getPassRegistry();
181 initializeHexagonCallFrameInformationPass(PR);
182 }
183 bool runOnMachineFunction(MachineFunction &MF) override;
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000184 MachineFunctionProperties getRequiredProperties() const override {
185 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000186 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000187 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000188 };
189
190 char HexagonCallFrameInformation::ID = 0;
191}
192
193bool HexagonCallFrameInformation::runOnMachineFunction(MachineFunction &MF) {
194 auto &HFI = *MF.getSubtarget<HexagonSubtarget>().getFrameLowering();
195 bool NeedCFI = MF.getMMI().hasDebugInfo() ||
196 MF.getFunction()->needsUnwindTableEntry();
197
198 if (!NeedCFI)
199 return false;
200 HFI.insertCFIInstructions(MF);
201 return true;
202}
203
204INITIALIZE_PASS(HexagonCallFrameInformation, "hexagon-cfi",
205 "Hexagon call frame information", false, false)
206
207FunctionPass *llvm::createHexagonCallFrameInformation() {
208 return new HexagonCallFrameInformation();
209}
210
211
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000212namespace {
213 /// Map a register pair Reg to the subregister that has the greater "number",
214 /// i.e. D3 (aka R7:6) will be mapped to R7, etc.
215 unsigned getMax32BitSubRegister(unsigned Reg, const TargetRegisterInfo &TRI,
216 bool hireg = true) {
217 if (Reg < Hexagon::D0 || Reg > Hexagon::D15)
218 return Reg;
219
220 unsigned RegNo = 0;
221 for (MCSubRegIterator SubRegs(Reg, &TRI); SubRegs.isValid(); ++SubRegs) {
222 if (hireg) {
223 if (*SubRegs > RegNo)
224 RegNo = *SubRegs;
225 } else {
226 if (!RegNo || *SubRegs < RegNo)
227 RegNo = *SubRegs;
228 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000229 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000230 return RegNo;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000231 }
232
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000233 /// Returns the callee saved register with the largest id in the vector.
234 unsigned getMaxCalleeSavedReg(const std::vector<CalleeSavedInfo> &CSI,
235 const TargetRegisterInfo &TRI) {
Benjamin Kramer3e9a5d32016-05-27 11:36:04 +0000236 static_assert(Hexagon::R1 > 0,
237 "Assume physical registers are encoded as positive integers");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000238 if (CSI.empty())
239 return 0;
240
241 unsigned Max = getMax32BitSubRegister(CSI[0].getReg(), TRI);
242 for (unsigned I = 1, E = CSI.size(); I < E; ++I) {
243 unsigned Reg = getMax32BitSubRegister(CSI[I].getReg(), TRI);
244 if (Reg > Max)
245 Max = Reg;
246 }
247 return Max;
248 }
249
250 /// Checks if the basic block contains any instruction that needs a stack
251 /// frame to be already in place.
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000252 bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR,
253 const HexagonRegisterInfo &HRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000254 for (auto &I : MBB) {
255 const MachineInstr *MI = &I;
256 if (MI->isCall())
257 return true;
258 unsigned Opc = MI->getOpcode();
259 switch (Opc) {
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000260 case Hexagon::PS_alloca:
261 case Hexagon::PS_aligna:
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000262 return true;
263 default:
264 break;
265 }
266 // Check individual operands.
Matthias Braune41e1462015-05-29 02:56:46 +0000267 for (const MachineOperand &MO : MI->operands()) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000268 // While the presence of a frame index does not prove that a stack
269 // frame will be required, all frame indexes should be within alloc-
270 // frame/deallocframe. Otherwise, the code that translates a frame
271 // index into an offset would have to be aware of the placement of
272 // the frame creation/destruction instructions.
Matthias Braune41e1462015-05-29 02:56:46 +0000273 if (MO.isFI())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000274 return true;
Matthias Braune41e1462015-05-29 02:56:46 +0000275 if (!MO.isReg())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000276 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000277 unsigned R = MO.getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000278 // Virtual registers will need scavenging, which then may require
279 // a stack slot.
280 if (TargetRegisterInfo::isVirtualRegister(R))
281 return true;
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000282 for (MCSubRegIterator S(R, &HRI, true); S.isValid(); ++S)
283 if (CSR[*S])
284 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000285 }
286 }
287 return false;
288 }
289
290 /// Returns true if MBB has a machine instructions that indicates a tail call
291 /// in the block.
292 bool hasTailCall(const MachineBasicBlock &MBB) {
293 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
294 unsigned RetOpc = I->getOpcode();
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000295 return RetOpc == Hexagon::PS_tailcall_i || RetOpc == Hexagon::PS_tailcall_r;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000296 }
297
298 /// Returns true if MBB contains an instruction that returns.
299 bool hasReturn(const MachineBasicBlock &MBB) {
300 for (auto I = MBB.getFirstTerminator(), E = MBB.end(); I != E; ++I)
301 if (I->isReturn())
302 return true;
303 return false;
304 }
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +0000305
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000306 /// Returns the "return" instruction from this block, or nullptr if there
307 /// isn't any.
308 MachineInstr *getReturn(MachineBasicBlock &MBB) {
309 for (auto &I : MBB)
310 if (I.isReturn())
311 return &I;
312 return nullptr;
313 }
314
315 bool isRestoreCall(unsigned Opc) {
316 switch (Opc) {
317 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4:
318 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC:
Krzysztof Parzyszekfae79862016-07-27 18:47:25 +0000319 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT:
320 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC:
321 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT:
322 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC:
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000323 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4:
324 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC:
325 return true;
326 }
327 return false;
328 }
329
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +0000330 inline bool isOptNone(const MachineFunction &MF) {
331 return MF.getFunction()->hasFnAttribute(Attribute::OptimizeNone) ||
332 MF.getTarget().getOptLevel() == CodeGenOpt::None;
333 }
334
335 inline bool isOptSize(const MachineFunction &MF) {
336 const Function &F = *MF.getFunction();
337 return F.optForSize() && !F.optForMinSize();
338 }
339
340 inline bool isMinSize(const MachineFunction &MF) {
341 return MF.getFunction()->optForMinSize();
342 }
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000343}
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000344
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000345
346/// Implements shrink-wrapping of the stack frame. By default, stack frame
347/// is created in the function entry block, and is cleaned up in every block
348/// that returns. This function finds alternate blocks: one for the frame
349/// setup (prolog) and one for the cleanup (epilog).
350void HexagonFrameLowering::findShrunkPrologEpilog(MachineFunction &MF,
351 MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const {
352 static unsigned ShrinkCounter = 0;
353
354 if (ShrinkLimit.getPosition()) {
355 if (ShrinkCounter >= ShrinkLimit)
356 return;
357 ShrinkCounter++;
358 }
359
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000360 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000361 auto &HRI = *HST.getRegisterInfo();
362
363 MachineDominatorTree MDT;
364 MDT.runOnMachineFunction(MF);
365 MachinePostDominatorTree MPT;
366 MPT.runOnMachineFunction(MF);
367
368 typedef DenseMap<unsigned,unsigned> UnsignedMap;
369 UnsignedMap RPO;
370 typedef ReversePostOrderTraversal<const MachineFunction*> RPOTType;
371 RPOTType RPOT(&MF);
372 unsigned RPON = 0;
373 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I)
374 RPO[(*I)->getNumber()] = RPON++;
375
376 // Don't process functions that have loops, at least for now. Placement
377 // of prolog and epilog must take loop structure into account. For simpli-
378 // city don't do it right now.
379 for (auto &I : MF) {
380 unsigned BN = RPO[I.getNumber()];
381 for (auto SI = I.succ_begin(), SE = I.succ_end(); SI != SE; ++SI) {
382 // If found a back-edge, return.
383 if (RPO[(*SI)->getNumber()] <= BN)
384 return;
385 }
386 }
387
388 // Collect the set of blocks that need a stack frame to execute. Scan
389 // each block for uses/defs of callee-saved registers, calls, etc.
390 SmallVector<MachineBasicBlock*,16> SFBlocks;
391 BitVector CSR(Hexagon::NUM_TARGET_REGS);
392 for (const MCPhysReg *P = HRI.getCalleeSavedRegs(&MF); *P; ++P)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000393 for (MCSubRegIterator S(*P, &HRI, true); S.isValid(); ++S)
394 CSR[*S] = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000395
396 for (auto &I : MF)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000397 if (needsStackFrame(I, CSR, HRI))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000398 SFBlocks.push_back(&I);
399
400 DEBUG({
401 dbgs() << "Blocks needing SF: {";
402 for (auto &B : SFBlocks)
403 dbgs() << " BB#" << B->getNumber();
404 dbgs() << " }\n";
405 });
406 // No frame needed?
407 if (SFBlocks.empty())
408 return;
409
410 // Pick a common dominator and a common post-dominator.
411 MachineBasicBlock *DomB = SFBlocks[0];
412 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
413 DomB = MDT.findNearestCommonDominator(DomB, SFBlocks[i]);
414 if (!DomB)
415 break;
416 }
417 MachineBasicBlock *PDomB = SFBlocks[0];
418 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
419 PDomB = MPT.findNearestCommonDominator(PDomB, SFBlocks[i]);
420 if (!PDomB)
421 break;
422 }
423 DEBUG({
424 dbgs() << "Computed dom block: BB#";
425 if (DomB) dbgs() << DomB->getNumber();
426 else dbgs() << "<null>";
427 dbgs() << ", computed pdom block: BB#";
428 if (PDomB) dbgs() << PDomB->getNumber();
429 else dbgs() << "<null>";
430 dbgs() << "\n";
431 });
432 if (!DomB || !PDomB)
433 return;
434
435 // Make sure that DomB dominates PDomB and PDomB post-dominates DomB.
436 if (!MDT.dominates(DomB, PDomB)) {
437 DEBUG(dbgs() << "Dom block does not dominate pdom block\n");
438 return;
439 }
440 if (!MPT.dominates(PDomB, DomB)) {
441 DEBUG(dbgs() << "PDom block does not post-dominate dom block\n");
442 return;
443 }
444
445 // Finally, everything seems right.
446 PrologB = DomB;
447 EpilogB = PDomB;
448}
449
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000450
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000451/// Perform most of the PEI work here:
452/// - saving/restoring of the callee-saved registers,
453/// - stack frame creation and destruction.
454/// Normally, this work is distributed among various functions, but doing it
455/// in one place allows shrink-wrapping of the stack frame.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000456void HexagonFrameLowering::emitPrologue(MachineFunction &MF,
457 MachineBasicBlock &MBB) const {
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000458 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000459 auto &HRI = *HST.getRegisterInfo();
460
Matthias Braun941a7052016-07-28 18:40:00 +0000461 MachineFrameInfo &MFI = MF.getFrameInfo();
462 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000463
464 MachineBasicBlock *PrologB = &MF.front(), *EpilogB = nullptr;
465 if (EnableShrinkWrapping)
466 findShrunkPrologEpilog(MF, PrologB, EpilogB);
467
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000468 bool PrologueStubs = false;
469 insertCSRSpillsInBlock(*PrologB, CSI, HRI, PrologueStubs);
470 insertPrologueInBlock(*PrologB, PrologueStubs);
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000471 updateEntryPaths(MF, *PrologB);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000472
473 if (EpilogB) {
474 insertCSRRestoresInBlock(*EpilogB, CSI, HRI);
475 insertEpilogueInBlock(*EpilogB);
476 } else {
477 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000478 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000479 insertCSRRestoresInBlock(B, CSI, HRI);
480
481 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000482 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000483 insertEpilogueInBlock(B);
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000484
485 for (auto &B : MF) {
486 if (B.empty())
487 continue;
488 MachineInstr *RetI = getReturn(B);
489 if (!RetI || isRestoreCall(RetI->getOpcode()))
490 continue;
491 for (auto &R : CSI)
492 RetI->addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
493 }
494 }
495
496 if (EpilogB) {
497 // If there is an epilog block, it may not have a return instruction.
498 // In such case, we need to add the callee-saved registers as live-ins
499 // in all blocks on all paths from the epilog to any return block.
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000500 unsigned MaxBN = MF.getNumBlockIDs();
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000501 BitVector DoneT(MaxBN+1), DoneF(MaxBN+1), Path(MaxBN+1);
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000502 updateExitPaths(*EpilogB, *EpilogB, DoneT, DoneF, Path);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000503 }
504}
505
506
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000507void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB,
508 bool PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000509 MachineFunction &MF = *MBB.getParent();
Matthias Braun941a7052016-07-28 18:40:00 +0000510 MachineFrameInfo &MFI = MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000511 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000512 auto &HII = *HST.getInstrInfo();
513 auto &HRI = *HST.getRegisterInfo();
514 DebugLoc dl;
515
Matthias Braun941a7052016-07-28 18:40:00 +0000516 unsigned MaxAlign = std::max(MFI.getMaxAlignment(), getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000517
518 // Calculate the total stack frame size.
519 // Get the number of bytes to allocate from the FrameInfo.
Matthias Braun941a7052016-07-28 18:40:00 +0000520 unsigned FrameSize = MFI.getStackSize();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000521 // Round up the max call frame size to the max alignment on the stack.
Matthias Braun941a7052016-07-28 18:40:00 +0000522 unsigned MaxCFA = alignTo(MFI.getMaxCallFrameSize(), MaxAlign);
523 MFI.setMaxCallFrameSize(MaxCFA);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000524
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000525 FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
Matthias Braun941a7052016-07-28 18:40:00 +0000526 MFI.setStackSize(FrameSize);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000527
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000528 bool AlignStack = (MaxAlign > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000529
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000530 // Get the number of bytes to allocate from the FrameInfo.
Matthias Braun941a7052016-07-28 18:40:00 +0000531 unsigned NumBytes = MFI.getStackSize();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000532 unsigned SP = HRI.getStackRegister();
Matthias Braun941a7052016-07-28 18:40:00 +0000533 unsigned MaxCF = MFI.getMaxCallFrameSize();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000534 MachineBasicBlock::iterator InsertPt = MBB.begin();
535
Krzysztof Parzyszek8849a512016-08-19 18:46:13 +0000536 SmallVector<MachineInstr *, 4> AdjustRegs;
537 for (auto &MBB : MF)
538 for (auto &MI : MBB)
539 if (MI.getOpcode() == Hexagon::PS_alloca)
540 AdjustRegs.push_back(&MI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000541
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000542 for (auto MI : AdjustRegs) {
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000543 assert((MI->getOpcode() == Hexagon::PS_alloca) && "Expected alloca");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000544 expandAlloca(MI, HII, SP, MaxCF);
545 MI->eraseFromParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000546 }
547
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000548 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000549 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000550
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000551 // Check for overflow.
552 // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
553 const unsigned int ALLOCFRAME_MAX = 16384;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000554
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000555 // Create a dummy memory operand to avoid allocframe from being treated as
556 // a volatile memory reference.
557 MachineMemOperand *MMO =
558 MF.getMachineMemOperand(MachinePointerInfo(), MachineMemOperand::MOStore,
559 4, 4);
560
561 if (NumBytes >= ALLOCFRAME_MAX) {
562 // Emit allocframe(#0).
563 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
564 .addImm(0)
565 .addMemOperand(MMO);
566
567 // Subtract offset from frame pointer.
568 // We use a caller-saved non-parameter register for that.
569 unsigned CallerSavedReg = HRI.getFirstCallerSavedNonParamReg();
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +0000570 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CONST32),
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000571 CallerSavedReg).addImm(NumBytes);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000572 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_sub), SP)
573 .addReg(SP)
574 .addReg(CallerSavedReg);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000575 } else {
576 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
577 .addImm(NumBytes)
578 .addMemOperand(MMO);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000579 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000580
581 if (AlignStack) {
582 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
583 .addReg(SP)
584 .addImm(-int64_t(MaxAlign));
585 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000586
587 // If the stack-checking is enabled, and we spilled the callee-saved
588 // registers inline (i.e. did not use a spill function), then call
589 // the stack checker directly.
590 if (EnableStackOVFSanitizer && !PrologueStubs)
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000591 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::PS_call_stk))
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000592 .addExternalSymbol("__runtime_stack_check");
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000593}
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000594
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000595void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
596 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000597 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000598 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000599
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000600 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000601 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000602 auto &HRI = *HST.getRegisterInfo();
603 unsigned SP = HRI.getStackRegister();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000604
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000605 MachineInstr *RetI = getReturn(MBB);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000606 unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
607
608 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
609 DebugLoc DL;
610 if (InsertPt != MBB.end())
611 DL = InsertPt->getDebugLoc();
612 else if (!MBB.empty())
613 DL = std::prev(MBB.end())->getDebugLoc();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000614
615 // Handle EH_RETURN.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000616 if (RetOpc == Hexagon::EH_RETURN_JMPR) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000617 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
618 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::A2_add), SP)
619 .addReg(SP)
620 .addReg(Hexagon::R28);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000621 return;
622 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000623
624 // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
625 // frame instruction if we encounter it.
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000626 if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
Krzysztof Parzyszekfae79862016-07-27 18:47:25 +0000627 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC ||
628 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT ||
629 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000630 MachineBasicBlock::iterator It = RetI;
631 ++It;
632 // Delete all instructions after the RESTORE (except labels).
633 while (It != MBB.end()) {
634 if (!It->isLabel())
635 It = MBB.erase(It);
636 else
637 ++It;
Jyotsna Verma300f0b92013-05-10 20:27:34 +0000638 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000639 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000640 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000641
642 // It is possible that the restoring code is a call to a library function.
643 // All of the restore* functions include "deallocframe", so we need to make
644 // sure that we don't add an extra one.
645 bool NeedsDeallocframe = true;
646 if (!MBB.empty() && InsertPt != MBB.begin()) {
647 MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
648 unsigned COpc = PrevIt->getOpcode();
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000649 if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
Krzysztof Parzyszekfae79862016-07-27 18:47:25 +0000650 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC ||
651 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT ||
652 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC ||
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000653 COpc == Hexagon::PS_call_nr || COpc == Hexagon::PS_callr_nr)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000654 NeedsDeallocframe = false;
655 }
656
657 if (!NeedsDeallocframe)
658 return;
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000659 // If the returning instruction is PS_jmpret, replace it with dealloc_return,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000660 // otherwise just add deallocframe. The function could be returning via a
661 // tail call.
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000662 if (RetOpc != Hexagon::PS_jmpret || DisableDeallocRet) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000663 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
664 return;
665 }
666 unsigned NewOpc = Hexagon::L4_return;
667 MachineInstr *NewI = BuildMI(MBB, RetI, DL, HII.get(NewOpc));
668 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000669 NewI->copyImplicitOps(MF, *RetI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000670 MBB.erase(RetI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000671}
672
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000673void HexagonFrameLowering::updateEntryPaths(MachineFunction &MF,
674 MachineBasicBlock &SaveB) const {
675 SetVector<unsigned> Worklist;
676
677 MachineBasicBlock &EntryB = MF.front();
678 Worklist.insert(EntryB.getNumber());
679
680 unsigned SaveN = SaveB.getNumber();
Matthias Braun941a7052016-07-28 18:40:00 +0000681 auto &CSI = MF.getFrameInfo().getCalleeSavedInfo();
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000682
683 for (unsigned i = 0; i < Worklist.size(); ++i) {
684 unsigned BN = Worklist[i];
685 MachineBasicBlock &MBB = *MF.getBlockNumbered(BN);
686 for (auto &R : CSI)
687 if (!MBB.isLiveIn(R.getReg()))
688 MBB.addLiveIn(R.getReg());
689 if (BN != SaveN)
690 for (auto &SB : MBB.successors())
691 Worklist.insert(SB->getNumber());
692 }
693}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000694
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000695bool HexagonFrameLowering::updateExitPaths(MachineBasicBlock &MBB,
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000696 MachineBasicBlock &RestoreB, BitVector &DoneT, BitVector &DoneF,
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000697 BitVector &Path) const {
698 assert(MBB.getNumber() >= 0);
699 unsigned BN = MBB.getNumber();
700 if (Path[BN] || DoneF[BN])
701 return false;
702 if (DoneT[BN])
703 return true;
704
Matthias Braun941a7052016-07-28 18:40:00 +0000705 auto &CSI = MBB.getParent()->getFrameInfo().getCalleeSavedInfo();
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000706
707 Path[BN] = true;
708 bool ReachedExit = false;
709 for (auto &SB : MBB.successors())
710 ReachedExit |= updateExitPaths(*SB, RestoreB, DoneT, DoneF, Path);
711
712 if (!MBB.empty() && MBB.back().isReturn()) {
713 // Add implicit uses of all callee-saved registers to the reached
714 // return instructions. This is to prevent the anti-dependency breaker
715 // from renaming these registers.
716 MachineInstr &RetI = MBB.back();
717 if (!isRestoreCall(RetI.getOpcode()))
718 for (auto &R : CSI)
719 RetI.addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
720 ReachedExit = true;
721 }
722
723 // We don't want to add unnecessary live-ins to the restore block: since
724 // the callee-saved registers are being defined in it, the entry of the
725 // restore block cannot be on the path from the definitions to any exit.
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000726 if (ReachedExit && &MBB != &RestoreB) {
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000727 for (auto &R : CSI)
728 if (!MBB.isLiveIn(R.getReg()))
729 MBB.addLiveIn(R.getReg());
730 DoneT[BN] = true;
731 }
732 if (!ReachedExit)
733 DoneF[BN] = true;
734
735 Path[BN] = false;
736 return ReachedExit;
737}
738
739
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000740namespace {
Krzysztof Parzyszekc43644d2016-07-28 19:13:46 +0000741 Optional<MachineBasicBlock::iterator> findCFILocation(MachineBasicBlock &B) {
742 // The CFI instructions need to be inserted right after allocframe.
743 // An exception to this is a situation where allocframe is bundled
744 // with a call: then the CFI instructions need to be inserted before
745 // the packet with the allocframe+call (in case the call throws an
746 // exception).
747 auto End = B.instr_end();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000748
Krzysztof Parzyszekc43644d2016-07-28 19:13:46 +0000749 for (MachineInstr &I : B) {
750 MachineBasicBlock::iterator It = I.getIterator();
751 if (!I.isBundle()) {
752 if (I.getOpcode() == Hexagon::S2_allocframe)
753 return std::next(It);
754 continue;
755 }
756 // I is a bundle.
757 bool HasCall = false, HasAllocFrame = false;
758 auto T = It.getInstrIterator();
759 while (++T != End && T->isBundled()) {
760 if (T->getOpcode() == Hexagon::S2_allocframe)
761 HasAllocFrame = true;
762 else if (T->isCall())
763 HasCall = true;
764 }
765 if (HasAllocFrame)
766 return HasCall ? It : std::next(It);
767 }
768 return None;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000769 }
770}
771
772
773void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
774 for (auto &B : MF) {
Krzysztof Parzyszekc43644d2016-07-28 19:13:46 +0000775 auto At = findCFILocation(B);
776 if (At.hasValue())
777 insertCFIInstructionsAt(B, At.getValue());
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000778 }
779}
780
781
782void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
783 MachineBasicBlock::iterator At) const {
784 MachineFunction &MF = *MBB.getParent();
Matthias Braun941a7052016-07-28 18:40:00 +0000785 MachineFrameInfo &MFI = MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000786 MachineModuleInfo &MMI = MF.getMMI();
787 auto &HST = MF.getSubtarget<HexagonSubtarget>();
788 auto &HII = *HST.getInstrInfo();
789 auto &HRI = *HST.getRegisterInfo();
790
791 // If CFI instructions have debug information attached, something goes
792 // wrong with the final assembly generation: the prolog_end is placed
793 // in a wrong location.
794 DebugLoc DL;
795 const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
796
797 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000798 bool HasFP = hasFP(MF);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000799
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000800 if (HasFP) {
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000801 unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
802 unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000803
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000804 // Define CFA via an offset from the value of FP.
805 //
806 // -8 -4 0 (SP)
807 // --+----+----+---------------------
808 // | FP | LR | increasing addresses -->
809 // --+----+----+---------------------
810 // | +-- Old SP (before allocframe)
811 // +-- New FP (after allocframe)
812 //
813 // MCCFIInstruction::createDefCfa subtracts the offset from the register.
814 // MCCFIInstruction::createOffset takes the offset without sign change.
815 auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
816 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000817 .addCFIIndex(MF.addFrameInst(DefCfa));
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000818 // R31 (return addr) = CFA - 4
819 auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
820 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000821 .addCFIIndex(MF.addFrameInst(OffR31));
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000822 // R30 (frame ptr) = CFA - 8
823 auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
824 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000825 .addCFIIndex(MF.addFrameInst(OffR30));
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000826 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000827
828 static unsigned int RegsToMove[] = {
829 Hexagon::R1, Hexagon::R0, Hexagon::R3, Hexagon::R2,
830 Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
831 Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
832 Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
833 Hexagon::D0, Hexagon::D1, Hexagon::D8, Hexagon::D9,
834 Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
835 Hexagon::NoRegister
836 };
837
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000838 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000839
840 for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
841 unsigned Reg = RegsToMove[i];
842 auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
843 return C.getReg() == Reg;
844 };
David Majnemer562e8292016-08-12 00:18:03 +0000845 auto F = find_if(CSI, IfR);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000846 if (F == CSI.end())
847 continue;
848
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000849 int64_t Offset;
850 if (HasFP) {
851 // If the function has a frame pointer (i.e. has an allocframe),
852 // then the CFA has been defined in terms of FP. Any offsets in
853 // the following CFI instructions have to be defined relative
854 // to FP, which points to the bottom of the stack frame.
855 // The function getFrameIndexReference can still choose to use SP
856 // for the offset calculation, so we cannot simply call it here.
857 // Instead, get the offset (relative to the FP) directly.
858 Offset = MFI.getObjectOffset(F->getFrameIdx());
859 } else {
860 unsigned FrameReg;
861 Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg);
862 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000863 // Subtract 8 to make room for R30 and R31, which are added above.
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000864 Offset -= 8;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000865
866 if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
867 unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
868 auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
869 Offset);
870 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000871 .addCFIIndex(MF.addFrameInst(OffReg));
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000872 } else {
873 // Split the double regs into subregs, and generate appropriate
874 // cfi_offsets.
875 // The only reason, we are split double regs is, llvm-mc does not
876 // understand paired registers for cfi_offset.
877 // Eg .cfi_offset r1:0, -64
878
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +0000879 unsigned HiReg = HRI.getSubReg(Reg, Hexagon::isub_hi);
880 unsigned LoReg = HRI.getSubReg(Reg, Hexagon::isub_lo);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000881 unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
882 unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
883 auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
884 Offset+4);
885 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000886 .addCFIIndex(MF.addFrameInst(OffHi));
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000887 auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
888 Offset);
889 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000890 .addCFIIndex(MF.addFrameInst(OffLo));
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000891 }
892 }
893}
894
895
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000896bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000897 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000898 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
899
900 bool HasFixed = MFI.getNumFixedObjects();
901 bool HasPrealloc = const_cast<MachineFrameInfo&>(MFI)
902 .getLocalFrameObjectCount();
903 bool HasExtraAlign = HRI.needsStackRealignment(MF);
904 bool HasAlloca = MFI.hasVarSizedObjects();
905
906 // Insert ALLOCFRAME if we need to or at -O0 for the debugger. Think
907 // that this shouldn't be required, but doing so now because gcc does and
908 // gdb can't break at the start of the function without it. Will remove if
909 // this turns out to be a gdb bug.
910 //
911 if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
912 return true;
913
914 // By default we want to use SP (since it's always there). FP requires
915 // some setup (i.e. ALLOCFRAME).
916 // Fixed and preallocated objects need FP if the distance from them to
917 // the SP is unknown (as is with alloca or aligna).
918 if ((HasFixed || HasPrealloc) && (HasAlloca || HasExtraAlign))
919 return true;
920
921 if (MFI.getStackSize() > 0) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000922 if (EnableStackOVFSanitizer || UseAllocframe)
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000923 return true;
924 }
925
926 if (MFI.hasCalls() ||
927 MF.getInfo<HexagonMachineFunctionInfo>()->hasClobberLR())
928 return true;
929
930 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000931}
932
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000933
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000934enum SpillKind {
935 SK_ToMem,
936 SK_FromMem,
937 SK_FromMemTailcall
938};
939
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000940static const char *getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType,
941 bool Stkchk = false) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000942 const char * V4SpillToMemoryFunctions[] = {
943 "__save_r16_through_r17",
944 "__save_r16_through_r19",
945 "__save_r16_through_r21",
946 "__save_r16_through_r23",
947 "__save_r16_through_r25",
948 "__save_r16_through_r27" };
949
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000950 const char * V4SpillToMemoryStkchkFunctions[] = {
951 "__save_r16_through_r17_stkchk",
952 "__save_r16_through_r19_stkchk",
953 "__save_r16_through_r21_stkchk",
954 "__save_r16_through_r23_stkchk",
955 "__save_r16_through_r25_stkchk",
956 "__save_r16_through_r27_stkchk" };
957
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000958 const char * V4SpillFromMemoryFunctions[] = {
959 "__restore_r16_through_r17_and_deallocframe",
960 "__restore_r16_through_r19_and_deallocframe",
961 "__restore_r16_through_r21_and_deallocframe",
962 "__restore_r16_through_r23_and_deallocframe",
963 "__restore_r16_through_r25_and_deallocframe",
964 "__restore_r16_through_r27_and_deallocframe" };
965
966 const char * V4SpillFromMemoryTailcallFunctions[] = {
967 "__restore_r16_through_r17_and_deallocframe_before_tailcall",
968 "__restore_r16_through_r19_and_deallocframe_before_tailcall",
969 "__restore_r16_through_r21_and_deallocframe_before_tailcall",
970 "__restore_r16_through_r23_and_deallocframe_before_tailcall",
971 "__restore_r16_through_r25_and_deallocframe_before_tailcall",
972 "__restore_r16_through_r27_and_deallocframe_before_tailcall"
973 };
974
975 const char **SpillFunc = nullptr;
976
977 switch(SpillType) {
978 case SK_ToMem:
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000979 SpillFunc = Stkchk ? V4SpillToMemoryStkchkFunctions
980 : V4SpillToMemoryFunctions;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000981 break;
982 case SK_FromMem:
983 SpillFunc = V4SpillFromMemoryFunctions;
984 break;
985 case SK_FromMemTailcall:
986 SpillFunc = V4SpillFromMemoryTailcallFunctions;
987 break;
988 }
989 assert(SpillFunc && "Unknown spill kind");
990
991 // Spill all callee-saved registers up to the highest register used.
992 switch (MaxReg) {
993 case Hexagon::R17:
994 return SpillFunc[0];
995 case Hexagon::R19:
996 return SpillFunc[1];
997 case Hexagon::R21:
998 return SpillFunc[2];
999 case Hexagon::R23:
1000 return SpillFunc[3];
1001 case Hexagon::R25:
1002 return SpillFunc[4];
1003 case Hexagon::R27:
1004 return SpillFunc[5];
1005 default:
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001006 llvm_unreachable("Unhandled maximum callee save register");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001007 }
1008 return 0;
1009}
1010
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001011
James Y Knight5567baf2015-08-15 02:32:35 +00001012int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF,
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001013 int FI, unsigned &FrameReg) const {
Matthias Braun941a7052016-07-28 18:40:00 +00001014 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001015 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001016
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001017 int Offset = MFI.getObjectOffset(FI);
1018 bool HasAlloca = MFI.hasVarSizedObjects();
1019 bool HasExtraAlign = HRI.needsStackRealignment(MF);
1020 bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
James Y Knight5567baf2015-08-15 02:32:35 +00001021
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001022 unsigned SP = HRI.getStackRegister(), FP = HRI.getFrameRegister();
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001023 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1024 unsigned AP = HMFI.getStackAlignBasePhysReg();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001025 unsigned FrameSize = MFI.getStackSize();
1026
1027 bool UseFP = false, UseAP = false; // Default: use SP (except at -O0).
1028 // Use FP at -O0, except when there are objects with extra alignment.
1029 // That additional alignment requirement may cause a pad to be inserted,
1030 // which will make it impossible to use FP to access objects located
1031 // past the pad.
1032 if (NoOpt && !HasExtraAlign)
1033 UseFP = true;
1034 if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
1035 // Fixed and preallocated objects will be located before any padding
1036 // so FP must be used to access them.
1037 UseFP |= (HasAlloca || HasExtraAlign);
1038 } else {
1039 if (HasAlloca) {
1040 if (HasExtraAlign)
1041 UseAP = true;
1042 else
1043 UseFP = true;
1044 }
1045 }
1046
1047 // If FP was picked, then there had better be FP.
1048 bool HasFP = hasFP(MF);
1049 assert((HasFP || !UseFP) && "This function must have frame pointer");
1050
1051 // Having FP implies allocframe. Allocframe will store extra 8 bytes:
1052 // FP/LR. If the base register is used to access an object across these
1053 // 8 bytes, then the offset will need to be adjusted by 8.
1054 //
1055 // After allocframe:
1056 // HexagonISelLowering adds 8 to ---+
1057 // the offsets of all stack-based |
1058 // arguments (*) |
1059 // |
1060 // getObjectOffset < 0 0 8 getObjectOffset >= 8
1061 // ------------------------+-----+------------------------> increasing
1062 // <local objects> |FP/LR| <input arguments> addresses
1063 // -----------------+------+-----+------------------------>
1064 // | |
1065 // SP/AP point --+ +-- FP points here (**)
1066 // somewhere on
1067 // this side of FP/LR
1068 //
1069 // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
1070 // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
1071
1072 // The lowering assumes that FP/LR is present, and so the offsets of
1073 // the formal arguments start at 8. If FP/LR is not there we need to
1074 // reduce the offset by 8.
1075 if (Offset > 0 && !HasFP)
1076 Offset -= 8;
1077
1078 if (UseFP)
1079 FrameReg = FP;
1080 else if (UseAP)
1081 FrameReg = AP;
1082 else
1083 FrameReg = SP;
1084
1085 // Calculate the actual offset in the instruction. If there is no FP
1086 // (in other words, no allocframe), then SP will not be adjusted (i.e.
1087 // there will be no SP -= FrameSize), so the frame size should not be
1088 // added to the calculated offset.
1089 int RealOffset = Offset;
1090 if (!UseFP && !UseAP && HasFP)
1091 RealOffset = FrameSize+Offset;
1092 return RealOffset;
Jakob Stoklund Olesen0b97dbc2012-05-30 22:40:03 +00001093}
1094
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001095
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001096bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001097 const CSIVect &CSI, const HexagonRegisterInfo &HRI,
1098 bool &PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001099 if (CSI.empty())
1100 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001101
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001102 MachineBasicBlock::iterator MI = MBB.begin();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001103 PrologueStubs = false;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001104 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001105 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1106 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001107
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001108 if (useSpillFunction(MF, CSI)) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001109 PrologueStubs = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001110 unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001111 bool StkOvrFlowEnabled = EnableStackOVFSanitizer;
1112 const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem,
1113 StkOvrFlowEnabled);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001114 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
Rafael Espindolab1556c42016-06-28 20:13:36 +00001115 bool IsPIC = HTM.isPositionIndependent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001116 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001117
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001118 // Call spill function.
1119 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001120 unsigned SpillOpc;
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001121 if (StkOvrFlowEnabled) {
1122 if (LongCalls)
1123 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT_PIC
1124 : Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT;
1125 else
1126 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC
1127 : Hexagon::SAVE_REGISTERS_CALL_V4STK;
1128 } else {
1129 if (LongCalls)
1130 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_EXT_PIC
1131 : Hexagon::SAVE_REGISTERS_CALL_V4_EXT;
1132 else
1133 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
1134 : Hexagon::SAVE_REGISTERS_CALL_V4;
1135 }
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001136
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001137 MachineInstr *SaveRegsCall =
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001138 BuildMI(MBB, MI, DL, HII.get(SpillOpc))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001139 .addExternalSymbol(SpillFun);
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001140
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001141 // Add callee-saved registers as use.
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001142 addCalleeSaveRegistersAsImpOperand(SaveRegsCall, CSI, false, true);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001143 // Add live in registers.
1144 for (unsigned I = 0; I < CSI.size(); ++I)
1145 MBB.addLiveIn(CSI[I].getReg());
1146 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001147 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001148
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001149 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001150 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001151 // Add live in registers. We treat eh_return callee saved register r0 - r3
1152 // specially. They are not really callee saved registers as they are not
1153 // supposed to be killed.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001154 bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
1155 int FI = CSI[i].getFrameIdx();
1156 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001157 HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001158 if (IsKill)
1159 MBB.addLiveIn(Reg);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001160 }
1161 return true;
1162}
1163
1164
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001165bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
1166 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
1167 if (CSI.empty())
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001168 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001169
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001170 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1171 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001172 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1173 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001174
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001175 if (useRestoreFunction(MF, CSI)) {
1176 bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
1177 unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
1178 SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
1179 const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001180 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
Rafael Espindolab1556c42016-06-28 20:13:36 +00001181 bool IsPIC = HTM.isPositionIndependent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001182 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001183
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001184 // Call spill function.
1185 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
1186 : MBB.getLastNonDebugInstr()->getDebugLoc();
1187 MachineInstr *DeallocCall = nullptr;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001188
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001189 if (HasTC) {
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001190 unsigned RetOpc;
1191 if (LongCalls)
1192 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC
1193 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT;
1194 else
1195 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
1196 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
1197 DeallocCall = BuildMI(MBB, MI, DL, HII.get(RetOpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001198 .addExternalSymbol(RestoreFn);
1199 } else {
1200 // The block has a return.
1201 MachineBasicBlock::iterator It = MBB.getFirstTerminator();
1202 assert(It->isReturn() && std::next(It) == MBB.end());
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001203 unsigned RetOpc;
1204 if (LongCalls)
1205 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC
1206 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT;
1207 else
1208 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
1209 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
1210 DeallocCall = BuildMI(MBB, It, DL, HII.get(RetOpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001211 .addExternalSymbol(RestoreFn);
1212 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +00001213 DeallocCall->copyImplicitOps(MF, *It);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001214 }
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001215 addCalleeSaveRegistersAsImpOperand(DeallocCall, CSI, true, false);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001216 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001217 }
1218
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001219 for (unsigned i = 0; i < CSI.size(); ++i) {
1220 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001221 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1222 int FI = CSI[i].getFrameIdx();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001223 HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001224 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001225
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001226 return true;
1227}
1228
Hans Wennborge1a2e902016-03-31 18:33:38 +00001229MachineBasicBlock::iterator HexagonFrameLowering::eliminateCallFramePseudoInstr(
1230 MachineFunction &MF, MachineBasicBlock &MBB,
1231 MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00001232 MachineInstr &MI = *I;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001233 unsigned Opc = MI.getOpcode();
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001234 (void)Opc; // Silence compiler warning.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001235 assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1236 "Cannot handle this call frame pseudo instruction");
Hans Wennborge1a2e902016-03-31 18:33:38 +00001237 return MBB.erase(I);
Eli Bendersky8da87162013-02-21 20:05:00 +00001238}
1239
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001240
1241void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1242 MachineFunction &MF, RegScavenger *RS) const {
1243 // If this function has uses aligned stack and also has variable sized stack
1244 // objects, then we need to map all spill slots to fixed positions, so that
1245 // they can be accessed through FP. Otherwise they would have to be accessed
1246 // via AP, which may not be available at the particular place in the program.
Matthias Braun941a7052016-07-28 18:40:00 +00001247 MachineFrameInfo &MFI = MF.getFrameInfo();
1248 bool HasAlloca = MFI.hasVarSizedObjects();
1249 bool NeedsAlign = (MFI.getMaxAlignment() > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001250
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001251 if (!HasAlloca || !NeedsAlign)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001252 return;
1253
Matthias Braun941a7052016-07-28 18:40:00 +00001254 unsigned LFS = MFI.getLocalFrameSize();
1255 for (int i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
1256 if (!MFI.isSpillSlotObjectIndex(i) || MFI.isDeadObjectIndex(i))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001257 continue;
Matthias Braun941a7052016-07-28 18:40:00 +00001258 unsigned S = MFI.getObjectSize(i);
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001259 // Reduce the alignment to at most 8. This will require unaligned vector
1260 // stores if they happen here.
Matthias Braun941a7052016-07-28 18:40:00 +00001261 unsigned A = std::max(MFI.getObjectAlignment(i), 8U);
1262 MFI.setObjectAlignment(i, 8);
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001263 LFS = alignTo(LFS+S, A);
Matthias Braun941a7052016-07-28 18:40:00 +00001264 MFI.mapLocalFrameObject(i, -LFS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001265 }
1266
Matthias Braun941a7052016-07-28 18:40:00 +00001267 MFI.setLocalFrameSize(LFS);
1268 unsigned A = MFI.getLocalFrameMaxAlign();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001269 assert(A <= 8 && "Unexpected local frame alignment");
1270 if (A == 0)
Matthias Braun941a7052016-07-28 18:40:00 +00001271 MFI.setLocalFrameMaxAlign(8);
1272 MFI.setUseLocalStackAllocationBlock(true);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001273
1274 // Set the physical aligned-stack base address register.
1275 unsigned AP = 0;
1276 if (const MachineInstr *AI = getAlignaInstr(MF))
1277 AP = AI->getOperand(0).getReg();
1278 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1279 HMFI.setStackAlignBasePhysReg(AP);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001280}
1281
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001282/// Returns true if there are no caller-saved registers available in class RC.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001283static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001284 const HexagonRegisterInfo &HRI, const TargetRegisterClass *RC) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001285 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001286
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001287 auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1288 for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1289 if (MRI.isPhysRegUsed(*AI))
1290 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001291 return false;
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001292 };
1293
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001294 // Check for an unused caller-saved register. Callee-saved registers
1295 // have become pristine by now.
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001296 for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF, RC); *P; ++P)
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001297 if (!IsUsed(*P))
1298 return false;
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001299
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001300 // All caller-saved registers are used.
1301 return true;
1302}
1303
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001304
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001305#ifndef NDEBUG
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001306static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001307 dbgs() << '{';
1308 for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1309 unsigned R = x;
1310 dbgs() << ' ' << PrintReg(R, &TRI);
1311 }
1312 dbgs() << " }";
1313}
1314#endif
1315
1316
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001317bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1318 const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
Reid Kleckner40d72302016-10-20 00:22:23 +00001319 DEBUG(dbgs() << __func__ << " on "
Krzysztof Parzyszeked75e7a2015-04-23 20:57:39 +00001320 << MF.getFunction()->getName() << '\n');
Matthias Braun941a7052016-07-28 18:40:00 +00001321 MachineFrameInfo &MFI = MF.getFrameInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001322 BitVector SRegs(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001323
1324 // Generate a set of unique, callee-saved registers (SRegs), where each
1325 // register in the set is maximal in terms of sub-/super-register relation,
1326 // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1327
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001328 // (1) For each callee-saved register, add that register and all of its
1329 // sub-registers to SRegs.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001330 DEBUG(dbgs() << "Initial CS registers: {");
1331 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1332 unsigned R = CSI[i].getReg();
1333 DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1334 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1335 SRegs[*SR] = true;
1336 }
1337 DEBUG(dbgs() << " }\n");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001338 DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001339
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001340 // (2) For each reserved register, remove that register and all of its
1341 // sub- and super-registers from SRegs.
1342 BitVector Reserved = TRI->getReservedRegs(MF);
1343 for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1344 unsigned R = x;
1345 for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1346 SRegs[*SR] = false;
1347 }
1348 DEBUG(dbgs() << "Res: "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1349 DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1350
1351 // (3) Collect all registers that have at least one sub-register in SRegs,
1352 // and also have no sub-registers that are reserved. These will be the can-
1353 // didates for saving as a whole instead of their individual sub-registers.
1354 // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1355 BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001356 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1357 unsigned R = x;
1358 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1359 TmpSup[*SR] = true;
1360 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001361 for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1362 unsigned R = x;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001363 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1364 if (!Reserved[*SR])
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001365 continue;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001366 TmpSup[R] = false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001367 break;
1368 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001369 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001370 DEBUG(dbgs() << "TmpSup: "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001371
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001372 // (4) Include all super-registers found in (3) into SRegs.
1373 SRegs |= TmpSup;
1374 DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001375
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001376 // (5) For each register R in SRegs, if any super-register of R is in SRegs,
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001377 // remove R from SRegs.
1378 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1379 unsigned R = x;
1380 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1381 if (!SRegs[*SR])
1382 continue;
1383 SRegs[R] = false;
1384 break;
1385 }
1386 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001387 DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001388
1389 // Now, for each register that has a fixed stack slot, create the stack
1390 // object for it.
1391 CSI.clear();
1392
1393 typedef TargetFrameLowering::SpillSlot SpillSlot;
1394 unsigned NumFixed;
1395 int MinOffset = 0; // CS offsets are negative.
1396 const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1397 for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1398 if (!SRegs[S->Reg])
1399 continue;
1400 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
Matthias Braun941a7052016-07-28 18:40:00 +00001401 int FI = MFI.CreateFixedSpillStackObject(RC->getSize(), S->Offset);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001402 MinOffset = std::min(MinOffset, S->Offset);
1403 CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1404 SRegs[S->Reg] = false;
1405 }
1406
1407 // There can be some registers that don't have fixed slots. For example,
1408 // we need to store R0-R3 in functions with exception handling. For each
1409 // such register, create a non-fixed stack object.
1410 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1411 unsigned R = x;
1412 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
1413 int Off = MinOffset - RC->getSize();
1414 unsigned Align = std::min(RC->getAlignment(), getStackAlignment());
1415 assert(isPowerOf2_32(Align));
1416 Off &= -Align;
Matthias Braun941a7052016-07-28 18:40:00 +00001417 int FI = MFI.CreateFixedSpillStackObject(RC->getSize(), Off);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001418 MinOffset = std::min(MinOffset, Off);
1419 CSI.push_back(CalleeSavedInfo(R, FI));
1420 SRegs[R] = false;
1421 }
1422
1423 DEBUG({
1424 dbgs() << "CS information: {";
1425 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1426 int FI = CSI[i].getFrameIdx();
Matthias Braun941a7052016-07-28 18:40:00 +00001427 int Off = MFI.getObjectOffset(FI);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001428 dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1429 if (Off >= 0)
1430 dbgs() << '+';
1431 dbgs() << Off;
1432 }
1433 dbgs() << " }\n";
1434 });
1435
1436#ifndef NDEBUG
1437 // Verify that all registers were handled.
1438 bool MissedReg = false;
1439 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1440 unsigned R = x;
1441 dbgs() << PrintReg(R, TRI) << ' ';
1442 MissedReg = true;
1443 }
1444 if (MissedReg)
1445 llvm_unreachable("...there are unhandled callee-saved registers!");
1446#endif
1447
1448 return true;
1449}
1450
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001451bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1452 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1453 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1454 MachineInstr *MI = &*It;
1455 DebugLoc DL = MI->getDebugLoc();
1456 unsigned DstR = MI->getOperand(0).getReg();
1457 unsigned SrcR = MI->getOperand(1).getReg();
1458 if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1459 !Hexagon::ModRegsRegClass.contains(SrcR))
1460 return false;
1461
1462 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1463 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR)
1464 .addOperand(MI->getOperand(1));
1465 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1466 .addReg(TmpR, RegState::Kill);
1467
1468 NewRegs.push_back(TmpR);
1469 B.erase(It);
1470 return true;
1471}
1472
1473bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1474 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1475 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1476 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001477 if (!MI->getOperand(0).isFI())
1478 return false;
1479
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001480 DebugLoc DL = MI->getDebugLoc();
1481 unsigned Opc = MI->getOpcode();
1482 unsigned SrcR = MI->getOperand(2).getReg();
1483 bool IsKill = MI->getOperand(2).isKill();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001484 int FI = MI->getOperand(0).getIndex();
1485
1486 // TmpR = C2_tfrpr SrcR if SrcR is a predicate register
1487 // TmpR = A2_tfrcrr SrcR if SrcR is a modifier register
1488 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1489 unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1490 : Hexagon::A2_tfrcrr;
1491 BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1492 .addReg(SrcR, getKillRegState(IsKill));
1493
1494 // S2_storeri_io FI, 0, TmpR
1495 BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1496 .addFrameIndex(FI)
1497 .addImm(0)
1498 .addReg(TmpR, RegState::Kill)
1499 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1500
1501 NewRegs.push_back(TmpR);
1502 B.erase(It);
1503 return true;
1504}
1505
1506bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1507 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1508 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1509 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001510 if (!MI->getOperand(1).isFI())
1511 return false;
1512
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001513 DebugLoc DL = MI->getDebugLoc();
1514 unsigned Opc = MI->getOpcode();
1515 unsigned DstR = MI->getOperand(0).getReg();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001516 int FI = MI->getOperand(1).getIndex();
1517
1518 // TmpR = L2_loadri_io FI, 0
1519 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1520 BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1521 .addFrameIndex(FI)
1522 .addImm(0)
1523 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1524
1525 // DstR = C2_tfrrp TmpR if DstR is a predicate register
1526 // DstR = A2_tfrrcr TmpR if DstR is a modifier register
1527 unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1528 : Hexagon::A2_tfrrcr;
1529 BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1530 .addReg(TmpR, RegState::Kill);
1531
1532 NewRegs.push_back(TmpR);
1533 B.erase(It);
1534 return true;
1535}
1536
1537
1538bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1539 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1540 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1541 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1542 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001543 if (!MI->getOperand(0).isFI())
1544 return false;
1545
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001546 DebugLoc DL = MI->getDebugLoc();
1547 unsigned SrcR = MI->getOperand(2).getReg();
1548 bool IsKill = MI->getOperand(2).isKill();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001549 int FI = MI->getOperand(0).getIndex();
1550
1551 bool Is128B = HST.useHVXDblOps();
1552 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1553 : &Hexagon::VectorRegs128BRegClass;
1554
1555 // Insert transfer to general vector register.
1556 // TmpR0 = A2_tfrsi 0x01010101
1557 // TmpR1 = V6_vandqrt Qx, TmpR0
1558 // store FI, 0, TmpR1
1559 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1560 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1561
1562 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1563 .addImm(0x01010101);
1564
1565 unsigned VandOpc = !Is128B ? Hexagon::V6_vandqrt : Hexagon::V6_vandqrt_128B;
1566 BuildMI(B, It, DL, HII.get(VandOpc), TmpR1)
1567 .addReg(SrcR, getKillRegState(IsKill))
1568 .addReg(TmpR0, RegState::Kill);
1569
1570 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1571 HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1572 expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1573
1574 NewRegs.push_back(TmpR0);
1575 NewRegs.push_back(TmpR1);
1576 B.erase(It);
1577 return true;
1578}
1579
1580bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1581 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1582 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1583 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1584 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001585 if (!MI->getOperand(1).isFI())
1586 return false;
1587
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001588 DebugLoc DL = MI->getDebugLoc();
1589 unsigned DstR = MI->getOperand(0).getReg();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001590 int FI = MI->getOperand(1).getIndex();
1591
1592 bool Is128B = HST.useHVXDblOps();
1593 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1594 : &Hexagon::VectorRegs128BRegClass;
1595
1596 // TmpR0 = A2_tfrsi 0x01010101
1597 // TmpR1 = load FI, 0
1598 // DstR = V6_vandvrt TmpR1, TmpR0
1599 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1600 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1601
1602 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1603 .addImm(0x01010101);
1604 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1605 HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1606 expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1607
1608 unsigned VandOpc = !Is128B ? Hexagon::V6_vandvrt : Hexagon::V6_vandvrt_128B;
1609 BuildMI(B, It, DL, HII.get(VandOpc), DstR)
1610 .addReg(TmpR1, RegState::Kill)
1611 .addReg(TmpR0, RegState::Kill);
1612
1613 NewRegs.push_back(TmpR0);
1614 NewRegs.push_back(TmpR1);
1615 B.erase(It);
1616 return true;
1617}
1618
1619bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1620 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1621 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1622 MachineFunction &MF = *B.getParent();
1623 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Matthias Braun941a7052016-07-28 18:40:00 +00001624 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001625 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1626 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001627 if (!MI->getOperand(0).isFI())
1628 return false;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001629
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001630 // It is possible that the double vector being stored is only partially
1631 // defined. From the point of view of the liveness tracking, it is ok to
1632 // store it as a whole, but if we break it up we may end up storing a
1633 // register that is entirely undefined.
1634 LivePhysRegs LPR(&HRI);
1635 LPR.addLiveIns(B);
1636 SmallVector<std::pair<unsigned, const MachineOperand*>,2> Clobbers;
1637 for (auto R = B.begin(); R != It; ++R)
1638 LPR.stepForward(*R, Clobbers);
1639
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001640 DebugLoc DL = MI->getDebugLoc();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001641 unsigned SrcR = MI->getOperand(2).getReg();
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +00001642 unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::vsub_lo);
1643 unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::vsub_hi);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001644 bool IsKill = MI->getOperand(2).isKill();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001645 int FI = MI->getOperand(0).getIndex();
1646
1647 bool Is128B = HST.useHVXDblOps();
1648 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1649 : &Hexagon::VectorRegs128BRegClass;
1650 unsigned Size = RC->getSize();
1651 unsigned NeedAlign = RC->getAlignment();
1652 unsigned HasAlign = MFI.getObjectAlignment(FI);
1653 unsigned StoreOpc;
1654
1655 // Store low part.
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001656 if (LPR.contains(SrcLo)) {
1657 if (NeedAlign <= HasAlign)
1658 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1659 else
1660 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001661
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001662 BuildMI(B, It, DL, HII.get(StoreOpc))
1663 .addFrameIndex(FI)
1664 .addImm(0)
1665 .addReg(SrcLo, getKillRegState(IsKill))
1666 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1667 }
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001668
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001669 // Store high part.
1670 if (LPR.contains(SrcHi)) {
1671 if (NeedAlign <= MinAlign(HasAlign, Size))
1672 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1673 else
1674 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001675
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001676 BuildMI(B, It, DL, HII.get(StoreOpc))
1677 .addFrameIndex(FI)
1678 .addImm(Size)
1679 .addReg(SrcHi, getKillRegState(IsKill))
1680 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1681 }
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001682
1683 B.erase(It);
1684 return true;
1685}
1686
1687bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1688 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1689 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1690 MachineFunction &MF = *B.getParent();
1691 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Matthias Braun941a7052016-07-28 18:40:00 +00001692 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001693 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1694 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001695 if (!MI->getOperand(1).isFI())
1696 return false;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001697
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001698 DebugLoc DL = MI->getDebugLoc();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001699 unsigned DstR = MI->getOperand(0).getReg();
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +00001700 unsigned DstHi = HRI.getSubReg(DstR, Hexagon::vsub_hi);
1701 unsigned DstLo = HRI.getSubReg(DstR, Hexagon::vsub_lo);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001702 int FI = MI->getOperand(1).getIndex();
1703
1704 bool Is128B = HST.useHVXDblOps();
1705 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1706 : &Hexagon::VectorRegs128BRegClass;
1707 unsigned Size = RC->getSize();
1708 unsigned NeedAlign = RC->getAlignment();
1709 unsigned HasAlign = MFI.getObjectAlignment(FI);
1710 unsigned LoadOpc;
1711
1712 // Load low part.
1713 if (NeedAlign <= HasAlign)
1714 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1715 else
1716 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1717
1718 BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1719 .addFrameIndex(FI)
1720 .addImm(0)
1721 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1722
1723 // Load high part.
1724 if (NeedAlign <= MinAlign(HasAlign, Size))
1725 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1726 else
1727 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1728
1729 BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1730 .addFrameIndex(FI)
1731 .addImm(Size)
1732 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1733
1734 B.erase(It);
1735 return true;
1736}
1737
1738bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1739 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1740 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1741 MachineFunction &MF = *B.getParent();
1742 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Matthias Braun941a7052016-07-28 18:40:00 +00001743 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001744 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001745 if (!MI->getOperand(0).isFI())
1746 return false;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001747
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001748 DebugLoc DL = MI->getDebugLoc();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001749 unsigned SrcR = MI->getOperand(2).getReg();
1750 bool IsKill = MI->getOperand(2).isKill();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001751 int FI = MI->getOperand(0).getIndex();
1752
1753 bool Is128B = HST.useHVXDblOps();
1754 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1755 : &Hexagon::VectorRegs128BRegClass;
1756
1757 unsigned NeedAlign = RC->getAlignment();
1758 unsigned HasAlign = MFI.getObjectAlignment(FI);
1759 unsigned StoreOpc;
1760
1761 if (NeedAlign <= HasAlign)
1762 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1763 else
1764 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1765
1766 BuildMI(B, It, DL, HII.get(StoreOpc))
1767 .addFrameIndex(FI)
1768 .addImm(0)
1769 .addReg(SrcR, getKillRegState(IsKill))
1770 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1771
1772 B.erase(It);
1773 return true;
1774}
1775
1776bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
1777 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1778 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1779 MachineFunction &MF = *B.getParent();
1780 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Matthias Braun941a7052016-07-28 18:40:00 +00001781 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001782 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001783 if (!MI->getOperand(1).isFI())
1784 return false;
1785
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001786 DebugLoc DL = MI->getDebugLoc();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001787 unsigned DstR = MI->getOperand(0).getReg();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001788 int FI = MI->getOperand(1).getIndex();
1789
1790 bool Is128B = HST.useHVXDblOps();
1791 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1792 : &Hexagon::VectorRegs128BRegClass;
1793
1794 unsigned NeedAlign = RC->getAlignment();
1795 unsigned HasAlign = MFI.getObjectAlignment(FI);
1796 unsigned LoadOpc;
1797
1798 if (NeedAlign <= HasAlign)
1799 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1800 else
1801 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1802
1803 BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1804 .addFrameIndex(FI)
1805 .addImm(0)
1806 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1807
1808 B.erase(It);
1809 return true;
1810}
1811
1812
1813bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1814 SmallVectorImpl<unsigned> &NewRegs) const {
1815 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001816 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001817 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001818 bool Changed = false;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001819
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001820 for (auto &B : MF) {
1821 // Traverse the basic block.
1822 MachineBasicBlock::iterator NextI;
1823 for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1824 MachineInstr *MI = &*I;
1825 NextI = std::next(I);
1826 unsigned Opc = MI->getOpcode();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001827
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001828 switch (Opc) {
1829 case TargetOpcode::COPY:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001830 Changed |= expandCopy(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001831 break;
1832 case Hexagon::STriw_pred:
1833 case Hexagon::STriw_mod:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001834 Changed |= expandStoreInt(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001835 break;
1836 case Hexagon::LDriw_pred:
1837 case Hexagon::LDriw_mod:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001838 Changed |= expandLoadInt(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001839 break;
Krzysztof Parzyszek17aa4132016-08-16 15:43:54 +00001840 case Hexagon::PS_vstorerq_ai:
1841 case Hexagon::PS_vstorerq_ai_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001842 Changed |= expandStoreVecPred(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001843 break;
Krzysztof Parzyszek17aa4132016-08-16 15:43:54 +00001844 case Hexagon::PS_vloadrq_ai:
1845 case Hexagon::PS_vloadrq_ai_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001846 Changed |= expandLoadVecPred(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001847 break;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001848 case Hexagon::PS_vloadrw_ai:
1849 case Hexagon::PS_vloadrwu_ai:
1850 case Hexagon::PS_vloadrw_ai_128B:
1851 case Hexagon::PS_vloadrwu_ai_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001852 Changed |= expandLoadVec2(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001853 break;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001854 case Hexagon::PS_vstorerw_ai:
1855 case Hexagon::PS_vstorerwu_ai:
1856 case Hexagon::PS_vstorerw_ai_128B:
1857 case Hexagon::PS_vstorerwu_ai_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001858 Changed |= expandStoreVec2(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001859 break;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001860 }
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001861 }
1862 }
1863
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001864 return Changed;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001865}
1866
1867
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001868void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1869 BitVector &SavedRegs,
1870 RegScavenger *RS) const {
1871 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1872 auto &HRI = *HST.getRegisterInfo();
1873
1874 SavedRegs.resize(HRI.getNumRegs());
1875
1876 // If we have a function containing __builtin_eh_return we want to spill and
1877 // restore all callee saved registers. Pretend that they are used.
1878 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1879 for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1880 SavedRegs.set(*R);
1881
1882 // Replace predicate register pseudo spill code.
1883 SmallVector<unsigned,8> NewRegs;
1884 expandSpillMacros(MF, NewRegs);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001885 if (OptimizeSpillSlots && !isOptNone(MF))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001886 optimizeSpillSlots(MF, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001887
1888 // We need to reserve a a spill slot if scavenging could potentially require
1889 // spilling a scavenged register.
Krzysztof Parzyszekddafa2c2016-08-01 17:15:30 +00001890 if (!NewRegs.empty() || mayOverflowFrameOffset(MF)) {
Matthias Braun941a7052016-07-28 18:40:00 +00001891 MachineFrameInfo &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001892 MachineRegisterInfo &MRI = MF.getRegInfo();
1893 SetVector<const TargetRegisterClass*> SpillRCs;
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001894 // Reserve an int register in any case, because it could be used to hold
1895 // the stack offset in case it does not fit into a spill instruction.
1896 SpillRCs.insert(&Hexagon::IntRegsRegClass);
1897
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001898 for (unsigned VR : NewRegs)
1899 SpillRCs.insert(MRI.getRegClass(VR));
1900
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001901 for (auto *RC : SpillRCs) {
1902 if (!needToReserveScavengingSpillSlots(MF, HRI, RC))
1903 continue;
1904 unsigned Num = RC == &Hexagon::IntRegsRegClass ? NumberScavengerSlots : 1;
1905 unsigned S = RC->getSize(), A = RC->getAlignment();
1906 for (unsigned i = 0; i < Num; i++) {
1907 int NewFI = MFI.CreateSpillStackObject(S, A);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001908 RS->addScavengingFrameIndex(NewFI);
1909 }
1910 }
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001911 }
1912
1913 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1914}
1915
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001916
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001917unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1918 HexagonBlockRanges::IndexRange &FIR,
1919 HexagonBlockRanges::InstrIndexMap &IndexMap,
1920 HexagonBlockRanges::RegToRangeMap &DeadMap,
1921 const TargetRegisterClass *RC) const {
1922 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1923 auto &MRI = MF.getRegInfo();
1924
1925 auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1926 auto F = DeadMap.find({Reg,0});
1927 if (F == DeadMap.end())
1928 return false;
1929 for (auto &DR : F->second)
1930 if (DR.contains(FIR))
1931 return true;
1932 return false;
1933 };
1934
1935 for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
1936 bool Dead = true;
1937 for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
1938 if (isDead(R.Reg))
1939 continue;
1940 Dead = false;
1941 break;
1942 }
1943 if (Dead)
1944 return Reg;
1945 }
1946 return 0;
1947}
1948
1949void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
1950 SmallVectorImpl<unsigned> &VRegs) const {
1951 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1952 auto &HII = *HST.getInstrInfo();
1953 auto &HRI = *HST.getRegisterInfo();
1954 auto &MRI = MF.getRegInfo();
1955 HexagonBlockRanges HBR(MF);
1956
1957 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::InstrIndexMap>
1958 BlockIndexMap;
1959 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::RangeList>
1960 BlockRangeMap;
1961 typedef HexagonBlockRanges::IndexType IndexType;
1962
1963 struct SlotInfo {
1964 BlockRangeMap Map;
NAKAMURA Takumic2cc8702016-02-13 07:29:49 +00001965 unsigned Size;
1966 const TargetRegisterClass *RC;
1967
1968 SlotInfo() : Map(), Size(0), RC(nullptr) {}
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001969 };
1970
1971 BlockIndexMap BlockIndexes;
1972 SmallSet<int,4> BadFIs;
1973 std::map<int,SlotInfo> FIRangeMap;
1974
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001975 // Accumulate register classes: get a common class for a pre-existing
1976 // class HaveRC and a new class NewRC. Return nullptr if a common class
1977 // cannot be found, otherwise return the resulting class. If HaveRC is
1978 // nullptr, assume that it is still unset.
1979 auto getCommonRC = [&HRI] (const TargetRegisterClass *HaveRC,
1980 const TargetRegisterClass *NewRC)
1981 -> const TargetRegisterClass* {
1982 if (HaveRC == nullptr || HaveRC == NewRC)
1983 return NewRC;
1984 // Different classes, both non-null. Pick the more general one.
1985 if (HaveRC->hasSubClassEq(NewRC))
1986 return HaveRC;
1987 if (NewRC->hasSubClassEq(HaveRC))
1988 return NewRC;
1989 return nullptr;
1990 };
1991
1992 // Scan all blocks in the function. Check all occurrences of frame indexes,
1993 // and collect relevant information.
1994 for (auto &B : MF) {
1995 std::map<int,IndexType> LastStore, LastLoad;
Krzysztof Parzyszek280a50e2016-02-13 14:06:01 +00001996 // Emplace appears not to be supported in gcc 4.7.2-4.
1997 //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
Krzysztof Parzyszekde697d42016-02-17 15:02:07 +00001998 auto P = BlockIndexes.insert(
1999 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002000 auto &IndexMap = P.first->second;
2001 DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n"
2002 << IndexMap << '\n');
2003
2004 for (auto &In : B) {
2005 int LFI, SFI;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00002006 bool Load = HII.isLoadFromStackSlot(In, LFI) && !HII.isPredicated(In);
2007 bool Store = HII.isStoreToStackSlot(In, SFI) && !HII.isPredicated(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002008 if (Load && Store) {
2009 // If it's both a load and a store, then we won't handle it.
2010 BadFIs.insert(LFI);
2011 BadFIs.insert(SFI);
2012 continue;
2013 }
2014 // Check for register classes of the register used as the source for
2015 // the store, and the register used as the destination for the load.
2016 // Also, only accept base+imm_offset addressing modes. Other addressing
2017 // modes can have side-effects (post-increments, etc.). For stack
2018 // slots they are very unlikely, so there is not much loss due to
2019 // this restriction.
2020 if (Load || Store) {
2021 int TFI = Load ? LFI : SFI;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002022 unsigned AM = HII.getAddrMode(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002023 SlotInfo &SI = FIRangeMap[TFI];
2024 bool Bad = (AM != HexagonII::BaseImmOffset);
2025 if (!Bad) {
2026 // If the addressing mode is ok, check the register class.
Krzysztof Parzyszek5241b8e2016-07-27 20:50:42 +00002027 unsigned OpNum = Load ? 0 : 2;
2028 auto *RC = HII.getRegClass(In.getDesc(), OpNum, &HRI, MF);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002029 RC = getCommonRC(SI.RC, RC);
2030 if (RC == nullptr)
2031 Bad = true;
2032 else
2033 SI.RC = RC;
2034 }
2035 if (!Bad) {
2036 // Check sizes.
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002037 unsigned S = (1U << (HII.getMemAccessSize(In) - 1));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002038 if (SI.Size != 0 && SI.Size != S)
2039 Bad = true;
2040 else
2041 SI.Size = S;
2042 }
Krzysztof Parzyszek5241b8e2016-07-27 20:50:42 +00002043 if (!Bad) {
2044 for (auto *Mo : In.memoperands()) {
2045 if (!Mo->isVolatile())
2046 continue;
2047 Bad = true;
2048 break;
2049 }
2050 }
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002051 if (Bad)
2052 BadFIs.insert(TFI);
2053 }
2054
2055 // Locate uses of frame indices.
2056 for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
2057 const MachineOperand &Op = In.getOperand(i);
2058 if (!Op.isFI())
2059 continue;
2060 int FI = Op.getIndex();
2061 // Make sure that the following operand is an immediate and that
2062 // it is 0. This is the offset in the stack object.
2063 if (i+1 >= n || !In.getOperand(i+1).isImm() ||
2064 In.getOperand(i+1).getImm() != 0)
2065 BadFIs.insert(FI);
2066 if (BadFIs.count(FI))
2067 continue;
2068
2069 IndexType Index = IndexMap.getIndex(&In);
2070 if (Load) {
2071 if (LastStore[FI] == IndexType::None)
2072 LastStore[FI] = IndexType::Entry;
2073 LastLoad[FI] = Index;
2074 } else if (Store) {
2075 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2076 if (LastStore[FI] != IndexType::None)
2077 RL.add(LastStore[FI], LastLoad[FI], false, false);
2078 else if (LastLoad[FI] != IndexType::None)
2079 RL.add(IndexType::Entry, LastLoad[FI], false, false);
2080 LastLoad[FI] = IndexType::None;
2081 LastStore[FI] = Index;
2082 } else {
2083 BadFIs.insert(FI);
2084 }
2085 }
2086 }
2087
2088 for (auto &I : LastLoad) {
2089 IndexType LL = I.second;
2090 if (LL == IndexType::None)
2091 continue;
2092 auto &RL = FIRangeMap[I.first].Map[&B];
2093 IndexType &LS = LastStore[I.first];
2094 if (LS != IndexType::None)
2095 RL.add(LS, LL, false, false);
2096 else
2097 RL.add(IndexType::Entry, LL, false, false);
2098 LS = IndexType::None;
2099 }
2100 for (auto &I : LastStore) {
2101 IndexType LS = I.second;
2102 if (LS == IndexType::None)
2103 continue;
2104 auto &RL = FIRangeMap[I.first].Map[&B];
2105 RL.add(LS, IndexType::None, false, false);
2106 }
2107 }
2108
2109 DEBUG({
2110 for (auto &P : FIRangeMap) {
2111 dbgs() << "fi#" << P.first;
2112 if (BadFIs.count(P.first))
2113 dbgs() << " (bad)";
2114 dbgs() << " RC: ";
2115 if (P.second.RC != nullptr)
2116 dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
2117 else
2118 dbgs() << "<null>\n";
2119 for (auto &R : P.second.Map)
2120 dbgs() << " BB#" << R.first->getNumber() << " { " << R.second << "}\n";
2121 }
2122 });
2123
2124 // When a slot is loaded from in a block without being stored to in the
2125 // same block, it is live-on-entry to this block. To avoid CFG analysis,
2126 // consider this slot to be live-on-exit from all blocks.
2127 SmallSet<int,4> LoxFIs;
2128
2129 std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
2130
2131 for (auto &P : FIRangeMap) {
2132 // P = pair(FI, map: BB->RangeList)
2133 if (BadFIs.count(P.first))
2134 continue;
2135 for (auto &B : MF) {
2136 auto F = P.second.Map.find(&B);
2137 // F = pair(BB, RangeList)
2138 if (F == P.second.Map.end() || F->second.empty())
2139 continue;
2140 HexagonBlockRanges::IndexRange &IR = F->second.front();
2141 if (IR.start() == IndexType::Entry)
2142 LoxFIs.insert(P.first);
2143 BlockFIMap[&B].push_back(P.first);
2144 }
2145 }
2146
2147 DEBUG({
2148 dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
2149 for (auto &P : BlockFIMap) {
2150 auto &FIs = P.second;
2151 if (FIs.empty())
2152 continue;
2153 dbgs() << " BB#" << P.first->getNumber() << ": {";
2154 for (auto I : FIs) {
2155 dbgs() << " fi#" << I;
2156 if (LoxFIs.count(I))
2157 dbgs() << '*';
2158 }
2159 dbgs() << " }\n";
2160 }
2161 });
2162
Krzysztof Parzyszekdc421642016-07-27 20:58:43 +00002163#ifndef NDEBUG
2164 bool HasOptLimit = SpillOptMax.getPosition();
2165#endif
2166
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002167 // eliminate loads, when all loads eliminated, eliminate all stores.
2168 for (auto &B : MF) {
2169 auto F = BlockIndexes.find(&B);
2170 assert(F != BlockIndexes.end());
2171 HexagonBlockRanges::InstrIndexMap &IM = F->second;
2172 HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
2173 HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
2174 DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n"
2175 << HexagonBlockRanges::PrintRangeMap(DM, HRI));
2176
2177 for (auto FI : BlockFIMap[&B]) {
2178 if (BadFIs.count(FI))
2179 continue;
2180 DEBUG(dbgs() << "Working on fi#" << FI << '\n');
2181 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2182 for (auto &Range : RL) {
2183 DEBUG(dbgs() << "--Examining range:" << RL << '\n');
2184 if (!IndexType::isInstr(Range.start()) ||
2185 !IndexType::isInstr(Range.end()))
2186 continue;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002187 MachineInstr &SI = *IM.getInstr(Range.start());
2188 MachineInstr &EI = *IM.getInstr(Range.end());
2189 assert(SI.mayStore() && "Unexpected start instruction");
2190 assert(EI.mayLoad() && "Unexpected end instruction");
2191 MachineOperand &SrcOp = SI.getOperand(2);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002192
2193 HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
2194 SrcOp.getSubReg() };
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002195 auto *RC = HII.getRegClass(SI.getDesc(), 2, &HRI, MF);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002196 // The this-> is needed to unconfuse MSVC.
2197 unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
2198 DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n');
2199 if (FoundR == 0)
2200 continue;
Krzysztof Parzyszekdc421642016-07-27 20:58:43 +00002201#ifndef NDEBUG
2202 if (HasOptLimit) {
2203 if (SpillOptCount >= SpillOptMax)
2204 return;
2205 SpillOptCount++;
2206 }
2207#endif
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002208
2209 // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002210 MachineBasicBlock::iterator StartIt = SI.getIterator(), NextIt;
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002211 MachineInstr *CopyIn = nullptr;
2212 if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002213 const DebugLoc &DL = SI.getDebugLoc();
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002214 CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
2215 .addOperand(SrcOp);
2216 }
2217
2218 ++StartIt;
2219 // Check if this is a last store and the FI is live-on-exit.
2220 if (LoxFIs.count(FI) && (&Range == &RL.back())) {
2221 // Update store's source register.
2222 if (unsigned SR = SrcOp.getSubReg())
2223 SrcOp.setReg(HRI.getSubReg(FoundR, SR));
2224 else
2225 SrcOp.setReg(FoundR);
2226 SrcOp.setSubReg(0);
2227 // We are keeping this register live.
2228 SrcOp.setIsKill(false);
2229 } else {
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002230 B.erase(&SI);
2231 IM.replaceInstr(&SI, CopyIn);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002232 }
2233
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002234 auto EndIt = std::next(EI.getIterator());
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002235 for (auto It = StartIt; It != EndIt; It = NextIt) {
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002236 MachineInstr &MI = *It;
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002237 NextIt = std::next(It);
2238 int TFI;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002239 if (!HII.isLoadFromStackSlot(MI, TFI) || TFI != FI)
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002240 continue;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002241 unsigned DstR = MI.getOperand(0).getReg();
2242 assert(MI.getOperand(0).getSubReg() == 0);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002243 MachineInstr *CopyOut = nullptr;
2244 if (DstR != FoundR) {
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002245 DebugLoc DL = MI.getDebugLoc();
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002246 unsigned MemSize = (1U << (HII.getMemAccessSize(MI) - 1));
2247 assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2248 unsigned CopyOpc = TargetOpcode::COPY;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002249 if (HII.isSignExtendingLoad(MI))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002250 CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002251 else if (HII.isZeroExtendingLoad(MI))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002252 CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2253 CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002254 .addReg(FoundR, getKillRegState(&MI == &EI));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002255 }
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002256 IM.replaceInstr(&MI, CopyOut);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002257 B.erase(It);
2258 }
2259
2260 // Update the dead map.
2261 HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2262 for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2263 DM[RR].subtract(Range);
2264 } // for Range in range list
2265 }
2266 }
2267}
2268
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002269void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002270 const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002271 MachineBasicBlock &MB = *AI->getParent();
2272 DebugLoc DL = AI->getDebugLoc();
2273 unsigned A = AI->getOperand(2).getImm();
2274
2275 // Have
2276 // Rd = alloca Rs, #A
2277 //
2278 // If Rs and Rd are different registers, use this sequence:
2279 // Rd = sub(r29, Rs)
2280 // r29 = sub(r29, Rs)
2281 // Rd = and(Rd, #-A) ; if necessary
2282 // r29 = and(r29, #-A) ; if necessary
2283 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2284 // otherwise, do
2285 // Rd = sub(r29, Rs)
2286 // Rd = and(Rd, #-A) ; if necessary
2287 // r29 = Rd
2288 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2289
2290 MachineOperand &RdOp = AI->getOperand(0);
2291 MachineOperand &RsOp = AI->getOperand(1);
2292 unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2293
2294 // Rd = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002295 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002296 .addReg(SP)
2297 .addReg(Rs);
2298 if (Rs != Rd) {
2299 // r29 = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002300 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002301 .addReg(SP)
2302 .addReg(Rs);
2303 }
2304 if (A > 8) {
2305 // Rd = and(Rd, #-A)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002306 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002307 .addReg(Rd)
2308 .addImm(-int64_t(A));
2309 if (Rs != Rd)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002310 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002311 .addReg(SP)
2312 .addImm(-int64_t(A));
2313 }
2314 if (Rs == Rd) {
2315 // r29 = Rd
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002316 BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002317 .addReg(Rd);
2318 }
2319 if (CF > 0) {
2320 // Rd = add(Rd, #CF)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002321 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002322 .addReg(Rd)
2323 .addImm(CF);
2324 }
2325}
2326
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002327
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002328bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +00002329 const MachineFrameInfo &MFI = MF.getFrameInfo();
2330 if (!MFI.hasVarSizedObjects())
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002331 return false;
Matthias Braun941a7052016-07-28 18:40:00 +00002332 unsigned MaxA = MFI.getMaxAlignment();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002333 if (MaxA <= getStackAlignment())
2334 return false;
2335 return true;
2336}
2337
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002338
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00002339const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2340 const MachineFunction &MF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002341 for (auto &B : MF)
2342 for (auto &I : B)
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +00002343 if (I.getOpcode() == Hexagon::PS_aligna)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002344 return &I;
2345 return nullptr;
2346}
2347
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002348
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00002349/// Adds all callee-saved registers as implicit uses or defs to the
2350/// instruction.
2351void HexagonFrameLowering::addCalleeSaveRegistersAsImpOperand(MachineInstr *MI,
2352 const CSIVect &CSI, bool IsDef, bool IsKill) const {
2353 // Add the callee-saved registers as implicit uses.
2354 for (auto &R : CSI)
2355 MI->addOperand(MachineOperand::CreateReg(R.getReg(), IsDef, true, IsKill));
2356}
2357
2358
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002359/// Determine whether the callee-saved register saves and restores should
2360/// be generated via inline code. If this function returns "true", inline
2361/// code will be generated. If this function returns "false", additional
2362/// checks are performed, which may still lead to the inline code.
2363bool HexagonFrameLowering::shouldInlineCSR(MachineFunction &MF,
2364 const CSIVect &CSI) const {
2365 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2366 return true;
2367 if (!isOptSize(MF) && !isMinSize(MF))
2368 if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2369 return true;
2370
2371 // Check if CSI only has double registers, and if the registers form
2372 // a contiguous block starting from D8.
2373 BitVector Regs(Hexagon::NUM_TARGET_REGS);
2374 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2375 unsigned R = CSI[i].getReg();
2376 if (!Hexagon::DoubleRegsRegClass.contains(R))
2377 return true;
2378 Regs[R] = true;
2379 }
2380 int F = Regs.find_first();
2381 if (F != Hexagon::D8)
2382 return true;
2383 while (F >= 0) {
2384 int N = Regs.find_next(F);
2385 if (N >= 0 && N != F+1)
2386 return true;
2387 F = N;
2388 }
2389
2390 return false;
2391}
2392
2393
2394bool HexagonFrameLowering::useSpillFunction(MachineFunction &MF,
2395 const CSIVect &CSI) const {
2396 if (shouldInlineCSR(MF, CSI))
2397 return false;
2398 unsigned NumCSI = CSI.size();
2399 if (NumCSI <= 1)
2400 return false;
2401
2402 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2403 : SpillFuncThreshold;
2404 return Threshold < NumCSI;
2405}
2406
2407
2408bool HexagonFrameLowering::useRestoreFunction(MachineFunction &MF,
2409 const CSIVect &CSI) const {
2410 if (shouldInlineCSR(MF, CSI))
2411 return false;
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002412 // The restore functions do a bit more than just restoring registers.
2413 // The non-returning versions will go back directly to the caller's
2414 // caller, others will clean up the stack frame in preparation for
2415 // a tail call. Using them can still save code size even if only one
2416 // register is getting restores. Make the decision based on -Oz:
2417 // using -Os will use inline restore for a single register.
2418 if (isMinSize(MF))
2419 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002420 unsigned NumCSI = CSI.size();
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002421 if (NumCSI <= 1)
2422 return false;
2423
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002424 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2425 : SpillFuncThreshold;
2426 return Threshold < NumCSI;
2427}
Krzysztof Parzyszekddafa2c2016-08-01 17:15:30 +00002428
2429
2430bool HexagonFrameLowering::mayOverflowFrameOffset(MachineFunction &MF) const {
2431 unsigned StackSize = MF.getFrameInfo().estimateStackSize(MF);
2432 auto &HST = MF.getSubtarget<HexagonSubtarget>();
2433 // A fairly simplistic guess as to whether a potential load/store to a
2434 // stack location could require an extra register. It does not account
2435 // for store-immediate instructions.
2436 if (HST.useHVXOps())
2437 return StackSize > 256;
2438 return false;
2439}
2440