blob: c37bd4a63f4a5457c7f6a9b68f887a07913dcc00 [file] [log] [blame]
Jia Liub22310f2012-02-18 12:03:15 +00001//===-- HexagonFrameLowering.cpp - Define frame lowering ------------------===//
Tony Linthicum1213a7a2011-12-12 21:14:40 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//
9//===----------------------------------------------------------------------===//
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000010
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000011#define DEBUG_TYPE "hexagon-pei"
12
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +000013#include "HexagonBlockRanges.h"
Craig Topperb25fda92012-03-17 18:46:09 +000014#include "HexagonFrameLowering.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000015#include "HexagonInstrInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "HexagonMachineFunctionInfo.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000017#include "HexagonRegisterInfo.h"
18#include "HexagonSubtarget.h"
19#include "HexagonTargetMachine.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000020#include "llvm/ADT/BitVector.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000021#include "llvm/ADT/PostOrderIterator.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000022#include "llvm/CodeGen/MachineDominators.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000023#include "llvm/CodeGen/MachineFunction.h"
24#include "llvm/CodeGen/MachineFunctionPass.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/CodeGen/MachineInstrBuilder.h"
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +000026#include "llvm/CodeGen/MachineInstrBuilder.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000027#include "llvm/CodeGen/MachineModuleInfo.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000028#include "llvm/CodeGen/MachinePostDominators.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000029#include "llvm/CodeGen/MachineRegisterInfo.h"
30#include "llvm/CodeGen/RegisterScavenging.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Function.h"
32#include "llvm/IR/Type.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Support/CommandLine.h"
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000034#include "llvm/Support/Debug.h"
35#include "llvm/Support/raw_ostream.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000036#include "llvm/Target/TargetInstrInfo.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000037#include "llvm/Target/TargetMachine.h"
38#include "llvm/Target/TargetOptions.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000039
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000040// Hexagon stack frame layout as defined by the ABI:
41//
42// Incoming arguments
43// passed via stack
44// |
45// |
46// SP during function's FP during function's |
47// +-- runtime (top of stack) runtime (bottom) --+ |
48// | | |
49// --++---------------------+------------------+-----------------++-+-------
50// | parameter area for | variable-size | fixed-size |LR| arg
51// | called functions | local objects | local objects |FP|
52// --+----------------------+------------------+-----------------+--+-------
53// <- size known -> <- size unknown -> <- size known ->
54//
55// Low address High address
56//
57// <--- stack growth
58//
59//
60// - In any circumstances, the outgoing function arguments are always accessi-
61// ble using the SP, and the incoming arguments are accessible using the FP.
62// - If the local objects are not aligned, they can always be accessed using
63// the FP.
64// - If there are no variable-sized objects, the local objects can always be
65// accessed using the SP, regardless whether they are aligned or not. (The
66// alignment padding will be at the bottom of the stack (highest address),
67// and so the offset with respect to the SP will be known at the compile-
68// -time.)
69//
70// The only complication occurs if there are both, local aligned objects, and
71// dynamically allocated (variable-sized) objects. The alignment pad will be
72// placed between the FP and the local objects, thus preventing the use of the
73// FP to access the local objects. At the same time, the variable-sized objects
74// will be between the SP and the local objects, thus introducing an unknown
75// distance from the SP to the locals.
76//
77// To avoid this problem, a new register is created that holds the aligned
78// address of the bottom of the stack, referred in the sources as AP (aligned
79// pointer). The AP will be equal to "FP-p", where "p" is the smallest pad
80// that aligns AP to the required boundary (a maximum of the alignments of
81// all stack objects, fixed- and variable-sized). All local objects[1] will
82// then use AP as the base pointer.
83// [1] The exception is with "fixed" stack objects. "Fixed" stack objects get
84// their name from being allocated at fixed locations on the stack, relative
85// to the FP. In the presence of dynamic allocation and local alignment, such
86// objects can only be accessed through the FP.
87//
88// Illustration of the AP:
89// FP --+
90// |
91// ---------------+---------------------+-----+-----------------------++-+--
92// Rest of the | Local stack objects | Pad | Fixed stack objects |LR|
93// stack frame | (aligned) | | (CSR, spills, etc.) |FP|
94// ---------------+---------------------+-----+-----------------+-----+--+--
95// |<-- Multiple of the -->|
96// stack alignment +-- AP
97//
98// The AP is set up at the beginning of the function. Since it is not a dedi-
99// cated (reserved) register, it needs to be kept live throughout the function
100// to be available as the base register for local object accesses.
101// Normally, an address of a stack objects is obtained by a pseudo-instruction
102// TFR_FI. To access local objects with the AP register present, a different
103// pseudo-instruction needs to be used: TFR_FIA. The TFR_FIA takes one extra
104// argument compared to TFR_FI: the first input register is the AP register.
105// This keeps the register live between its definition and its uses.
106
107// The AP register is originally set up using pseudo-instruction ALIGNA:
108// AP = ALIGNA A
109// where
110// A - required stack alignment
111// The alignment value must be the maximum of all alignments required by
112// any stack object.
113
114// The dynamic allocation uses a pseudo-instruction ALLOCA:
115// Rd = ALLOCA Rs, A
116// where
117// Rd - address of the allocated space
118// Rs - minimum size (the actual allocated can be larger to accommodate
119// alignment)
120// A - required alignment
121
122
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000123using namespace llvm;
124
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000125static cl::opt<bool> DisableDeallocRet("disable-hexagon-dealloc-ret",
126 cl::Hidden, cl::desc("Disable Dealloc Return for Hexagon target"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000127
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +0000128static cl::opt<unsigned> NumberScavengerSlots("number-scavenger-slots",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000129 cl::Hidden, cl::desc("Set the number of scavenger slots"), cl::init(2),
130 cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000131
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000132static cl::opt<int> SpillFuncThreshold("spill-func-threshold",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000133 cl::Hidden, cl::desc("Specify O2(not Os) spill func threshold"),
134 cl::init(6), cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000135
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000136static cl::opt<int> SpillFuncThresholdOs("spill-func-threshold-Os",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000137 cl::Hidden, cl::desc("Specify Os spill func threshold"),
138 cl::init(1), cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000139
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000140static cl::opt<bool> EnableStackOVFSanitizer("enable-stackovf-sanitizer",
141 cl::Hidden, cl::desc("Enable runtime checks for stack overflow."),
142 cl::init(false), cl::ZeroOrMore);
143
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000144static cl::opt<bool> EnableShrinkWrapping("hexagon-shrink-frame",
145 cl::init(true), cl::Hidden, cl::ZeroOrMore,
146 cl::desc("Enable stack frame shrink wrapping"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000147
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000148static cl::opt<unsigned> ShrinkLimit("shrink-frame-limit", cl::init(UINT_MAX),
149 cl::Hidden, cl::ZeroOrMore, cl::desc("Max count of stack frame "
150 "shrink-wraps"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000151
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000152static cl::opt<bool> EnableSaveRestoreLong("enable-save-restore-long",
153 cl::Hidden, cl::desc("Enable long calls for save-restore stubs."),
154 cl::init(false), cl::ZeroOrMore);
155
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000156static cl::opt<bool> UseAllocframe("use-allocframe", cl::init(true),
157 cl::Hidden, cl::desc("Use allocframe more conservatively"));
158
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +0000159static cl::opt<bool> OptimizeSpillSlots("hexagon-opt-spill", cl::Hidden,
160 cl::init(true), cl::desc("Optimize spill slots"));
161
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000162
163namespace llvm {
164 void initializeHexagonCallFrameInformationPass(PassRegistry&);
165 FunctionPass *createHexagonCallFrameInformation();
166}
167
168namespace {
169 class HexagonCallFrameInformation : public MachineFunctionPass {
170 public:
171 static char ID;
172 HexagonCallFrameInformation() : MachineFunctionPass(ID) {
173 PassRegistry &PR = *PassRegistry::getPassRegistry();
174 initializeHexagonCallFrameInformationPass(PR);
175 }
176 bool runOnMachineFunction(MachineFunction &MF) override;
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000177 MachineFunctionProperties getRequiredProperties() const override {
178 return MachineFunctionProperties().set(
179 MachineFunctionProperties::Property::AllVRegsAllocated);
180 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000181 };
182
183 char HexagonCallFrameInformation::ID = 0;
184}
185
186bool HexagonCallFrameInformation::runOnMachineFunction(MachineFunction &MF) {
187 auto &HFI = *MF.getSubtarget<HexagonSubtarget>().getFrameLowering();
188 bool NeedCFI = MF.getMMI().hasDebugInfo() ||
189 MF.getFunction()->needsUnwindTableEntry();
190
191 if (!NeedCFI)
192 return false;
193 HFI.insertCFIInstructions(MF);
194 return true;
195}
196
197INITIALIZE_PASS(HexagonCallFrameInformation, "hexagon-cfi",
198 "Hexagon call frame information", false, false)
199
200FunctionPass *llvm::createHexagonCallFrameInformation() {
201 return new HexagonCallFrameInformation();
202}
203
204
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000205namespace {
206 /// Map a register pair Reg to the subregister that has the greater "number",
207 /// i.e. D3 (aka R7:6) will be mapped to R7, etc.
208 unsigned getMax32BitSubRegister(unsigned Reg, const TargetRegisterInfo &TRI,
209 bool hireg = true) {
210 if (Reg < Hexagon::D0 || Reg > Hexagon::D15)
211 return Reg;
212
213 unsigned RegNo = 0;
214 for (MCSubRegIterator SubRegs(Reg, &TRI); SubRegs.isValid(); ++SubRegs) {
215 if (hireg) {
216 if (*SubRegs > RegNo)
217 RegNo = *SubRegs;
218 } else {
219 if (!RegNo || *SubRegs < RegNo)
220 RegNo = *SubRegs;
221 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000222 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000223 return RegNo;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000224 }
225
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000226 /// Returns the callee saved register with the largest id in the vector.
227 unsigned getMaxCalleeSavedReg(const std::vector<CalleeSavedInfo> &CSI,
228 const TargetRegisterInfo &TRI) {
Benjamin Kramer3e9a5d32016-05-27 11:36:04 +0000229 static_assert(Hexagon::R1 > 0,
230 "Assume physical registers are encoded as positive integers");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000231 if (CSI.empty())
232 return 0;
233
234 unsigned Max = getMax32BitSubRegister(CSI[0].getReg(), TRI);
235 for (unsigned I = 1, E = CSI.size(); I < E; ++I) {
236 unsigned Reg = getMax32BitSubRegister(CSI[I].getReg(), TRI);
237 if (Reg > Max)
238 Max = Reg;
239 }
240 return Max;
241 }
242
243 /// Checks if the basic block contains any instruction that needs a stack
244 /// frame to be already in place.
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000245 bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR,
246 const HexagonRegisterInfo &HRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000247 for (auto &I : MBB) {
248 const MachineInstr *MI = &I;
249 if (MI->isCall())
250 return true;
251 unsigned Opc = MI->getOpcode();
252 switch (Opc) {
253 case Hexagon::ALLOCA:
254 case Hexagon::ALIGNA:
255 return true;
256 default:
257 break;
258 }
259 // Check individual operands.
Matthias Braune41e1462015-05-29 02:56:46 +0000260 for (const MachineOperand &MO : MI->operands()) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000261 // While the presence of a frame index does not prove that a stack
262 // frame will be required, all frame indexes should be within alloc-
263 // frame/deallocframe. Otherwise, the code that translates a frame
264 // index into an offset would have to be aware of the placement of
265 // the frame creation/destruction instructions.
Matthias Braune41e1462015-05-29 02:56:46 +0000266 if (MO.isFI())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000267 return true;
Matthias Braune41e1462015-05-29 02:56:46 +0000268 if (!MO.isReg())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000269 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000270 unsigned R = MO.getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000271 // Virtual registers will need scavenging, which then may require
272 // a stack slot.
273 if (TargetRegisterInfo::isVirtualRegister(R))
274 return true;
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000275 for (MCSubRegIterator S(R, &HRI, true); S.isValid(); ++S)
276 if (CSR[*S])
277 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000278 }
279 }
280 return false;
281 }
282
283 /// Returns true if MBB has a machine instructions that indicates a tail call
284 /// in the block.
285 bool hasTailCall(const MachineBasicBlock &MBB) {
286 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
287 unsigned RetOpc = I->getOpcode();
288 return RetOpc == Hexagon::TCRETURNi || RetOpc == Hexagon::TCRETURNr;
289 }
290
291 /// Returns true if MBB contains an instruction that returns.
292 bool hasReturn(const MachineBasicBlock &MBB) {
293 for (auto I = MBB.getFirstTerminator(), E = MBB.end(); I != E; ++I)
294 if (I->isReturn())
295 return true;
296 return false;
297 }
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +0000298
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000299 /// Returns the "return" instruction from this block, or nullptr if there
300 /// isn't any.
301 MachineInstr *getReturn(MachineBasicBlock &MBB) {
302 for (auto &I : MBB)
303 if (I.isReturn())
304 return &I;
305 return nullptr;
306 }
307
308 bool isRestoreCall(unsigned Opc) {
309 switch (Opc) {
310 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4:
311 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC:
Krzysztof Parzyszekfae79862016-07-27 18:47:25 +0000312 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT:
313 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC:
314 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT:
315 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC:
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000316 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4:
317 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC:
318 return true;
319 }
320 return false;
321 }
322
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +0000323 inline bool isOptNone(const MachineFunction &MF) {
324 return MF.getFunction()->hasFnAttribute(Attribute::OptimizeNone) ||
325 MF.getTarget().getOptLevel() == CodeGenOpt::None;
326 }
327
328 inline bool isOptSize(const MachineFunction &MF) {
329 const Function &F = *MF.getFunction();
330 return F.optForSize() && !F.optForMinSize();
331 }
332
333 inline bool isMinSize(const MachineFunction &MF) {
334 return MF.getFunction()->optForMinSize();
335 }
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000336}
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000337
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000338
339/// Implements shrink-wrapping of the stack frame. By default, stack frame
340/// is created in the function entry block, and is cleaned up in every block
341/// that returns. This function finds alternate blocks: one for the frame
342/// setup (prolog) and one for the cleanup (epilog).
343void HexagonFrameLowering::findShrunkPrologEpilog(MachineFunction &MF,
344 MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const {
345 static unsigned ShrinkCounter = 0;
346
347 if (ShrinkLimit.getPosition()) {
348 if (ShrinkCounter >= ShrinkLimit)
349 return;
350 ShrinkCounter++;
351 }
352
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000353 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000354 auto &HRI = *HST.getRegisterInfo();
355
356 MachineDominatorTree MDT;
357 MDT.runOnMachineFunction(MF);
358 MachinePostDominatorTree MPT;
359 MPT.runOnMachineFunction(MF);
360
361 typedef DenseMap<unsigned,unsigned> UnsignedMap;
362 UnsignedMap RPO;
363 typedef ReversePostOrderTraversal<const MachineFunction*> RPOTType;
364 RPOTType RPOT(&MF);
365 unsigned RPON = 0;
366 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I)
367 RPO[(*I)->getNumber()] = RPON++;
368
369 // Don't process functions that have loops, at least for now. Placement
370 // of prolog and epilog must take loop structure into account. For simpli-
371 // city don't do it right now.
372 for (auto &I : MF) {
373 unsigned BN = RPO[I.getNumber()];
374 for (auto SI = I.succ_begin(), SE = I.succ_end(); SI != SE; ++SI) {
375 // If found a back-edge, return.
376 if (RPO[(*SI)->getNumber()] <= BN)
377 return;
378 }
379 }
380
381 // Collect the set of blocks that need a stack frame to execute. Scan
382 // each block for uses/defs of callee-saved registers, calls, etc.
383 SmallVector<MachineBasicBlock*,16> SFBlocks;
384 BitVector CSR(Hexagon::NUM_TARGET_REGS);
385 for (const MCPhysReg *P = HRI.getCalleeSavedRegs(&MF); *P; ++P)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000386 for (MCSubRegIterator S(*P, &HRI, true); S.isValid(); ++S)
387 CSR[*S] = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000388
389 for (auto &I : MF)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000390 if (needsStackFrame(I, CSR, HRI))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000391 SFBlocks.push_back(&I);
392
393 DEBUG({
394 dbgs() << "Blocks needing SF: {";
395 for (auto &B : SFBlocks)
396 dbgs() << " BB#" << B->getNumber();
397 dbgs() << " }\n";
398 });
399 // No frame needed?
400 if (SFBlocks.empty())
401 return;
402
403 // Pick a common dominator and a common post-dominator.
404 MachineBasicBlock *DomB = SFBlocks[0];
405 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
406 DomB = MDT.findNearestCommonDominator(DomB, SFBlocks[i]);
407 if (!DomB)
408 break;
409 }
410 MachineBasicBlock *PDomB = SFBlocks[0];
411 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
412 PDomB = MPT.findNearestCommonDominator(PDomB, SFBlocks[i]);
413 if (!PDomB)
414 break;
415 }
416 DEBUG({
417 dbgs() << "Computed dom block: BB#";
418 if (DomB) dbgs() << DomB->getNumber();
419 else dbgs() << "<null>";
420 dbgs() << ", computed pdom block: BB#";
421 if (PDomB) dbgs() << PDomB->getNumber();
422 else dbgs() << "<null>";
423 dbgs() << "\n";
424 });
425 if (!DomB || !PDomB)
426 return;
427
428 // Make sure that DomB dominates PDomB and PDomB post-dominates DomB.
429 if (!MDT.dominates(DomB, PDomB)) {
430 DEBUG(dbgs() << "Dom block does not dominate pdom block\n");
431 return;
432 }
433 if (!MPT.dominates(PDomB, DomB)) {
434 DEBUG(dbgs() << "PDom block does not post-dominate dom block\n");
435 return;
436 }
437
438 // Finally, everything seems right.
439 PrologB = DomB;
440 EpilogB = PDomB;
441}
442
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000443
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000444/// Perform most of the PEI work here:
445/// - saving/restoring of the callee-saved registers,
446/// - stack frame creation and destruction.
447/// Normally, this work is distributed among various functions, but doing it
448/// in one place allows shrink-wrapping of the stack frame.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000449void HexagonFrameLowering::emitPrologue(MachineFunction &MF,
450 MachineBasicBlock &MBB) const {
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000451 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000452 auto &HRI = *HST.getRegisterInfo();
453
454 MachineFrameInfo *MFI = MF.getFrameInfo();
455 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
456
457 MachineBasicBlock *PrologB = &MF.front(), *EpilogB = nullptr;
458 if (EnableShrinkWrapping)
459 findShrunkPrologEpilog(MF, PrologB, EpilogB);
460
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000461 bool PrologueStubs = false;
462 insertCSRSpillsInBlock(*PrologB, CSI, HRI, PrologueStubs);
463 insertPrologueInBlock(*PrologB, PrologueStubs);
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000464 updateEntryPaths(MF, *PrologB);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000465
466 if (EpilogB) {
467 insertCSRRestoresInBlock(*EpilogB, CSI, HRI);
468 insertEpilogueInBlock(*EpilogB);
469 } else {
470 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000471 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000472 insertCSRRestoresInBlock(B, CSI, HRI);
473
474 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000475 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000476 insertEpilogueInBlock(B);
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000477
478 for (auto &B : MF) {
479 if (B.empty())
480 continue;
481 MachineInstr *RetI = getReturn(B);
482 if (!RetI || isRestoreCall(RetI->getOpcode()))
483 continue;
484 for (auto &R : CSI)
485 RetI->addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
486 }
487 }
488
489 if (EpilogB) {
490 // If there is an epilog block, it may not have a return instruction.
491 // In such case, we need to add the callee-saved registers as live-ins
492 // in all blocks on all paths from the epilog to any return block.
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000493 unsigned MaxBN = MF.getNumBlockIDs();
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000494 BitVector DoneT(MaxBN+1), DoneF(MaxBN+1), Path(MaxBN+1);
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000495 updateExitPaths(*EpilogB, *EpilogB, DoneT, DoneF, Path);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000496 }
497}
498
499
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000500void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB,
501 bool PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000502 MachineFunction &MF = *MBB.getParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000503 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000504 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000505 auto &HII = *HST.getInstrInfo();
506 auto &HRI = *HST.getRegisterInfo();
507 DebugLoc dl;
508
509 unsigned MaxAlign = std::max(MFI->getMaxAlignment(), getStackAlignment());
510
511 // Calculate the total stack frame size.
512 // Get the number of bytes to allocate from the FrameInfo.
513 unsigned FrameSize = MFI->getStackSize();
514 // Round up the max call frame size to the max alignment on the stack.
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000515 unsigned MaxCFA = alignTo(MFI->getMaxCallFrameSize(), MaxAlign);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000516 MFI->setMaxCallFrameSize(MaxCFA);
517
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000518 FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000519 MFI->setStackSize(FrameSize);
520
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000521 bool AlignStack = (MaxAlign > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000522
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000523 // Get the number of bytes to allocate from the FrameInfo.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000524 unsigned NumBytes = MFI->getStackSize();
525 unsigned SP = HRI.getStackRegister();
526 unsigned MaxCF = MFI->getMaxCallFrameSize();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000527 MachineBasicBlock::iterator InsertPt = MBB.begin();
528
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000529 auto *FuncInfo = MF.getInfo<HexagonMachineFunctionInfo>();
530 auto &AdjustRegs = FuncInfo->getAllocaAdjustInsts();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000531
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000532 for (auto MI : AdjustRegs) {
533 assert((MI->getOpcode() == Hexagon::ALLOCA) && "Expected alloca");
534 expandAlloca(MI, HII, SP, MaxCF);
535 MI->eraseFromParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000536 }
537
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000538 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000539 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000540
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000541 // Check for overflow.
542 // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
543 const unsigned int ALLOCFRAME_MAX = 16384;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000544
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000545 // Create a dummy memory operand to avoid allocframe from being treated as
546 // a volatile memory reference.
547 MachineMemOperand *MMO =
548 MF.getMachineMemOperand(MachinePointerInfo(), MachineMemOperand::MOStore,
549 4, 4);
550
551 if (NumBytes >= ALLOCFRAME_MAX) {
552 // Emit allocframe(#0).
553 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
554 .addImm(0)
555 .addMemOperand(MMO);
556
557 // Subtract offset from frame pointer.
558 // We use a caller-saved non-parameter register for that.
559 unsigned CallerSavedReg = HRI.getFirstCallerSavedNonParamReg();
560 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CONST32_Int_Real),
561 CallerSavedReg).addImm(NumBytes);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000562 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_sub), SP)
563 .addReg(SP)
564 .addReg(CallerSavedReg);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000565 } else {
566 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
567 .addImm(NumBytes)
568 .addMemOperand(MMO);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000569 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000570
571 if (AlignStack) {
572 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
573 .addReg(SP)
574 .addImm(-int64_t(MaxAlign));
575 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000576
577 // If the stack-checking is enabled, and we spilled the callee-saved
578 // registers inline (i.e. did not use a spill function), then call
579 // the stack checker directly.
580 if (EnableStackOVFSanitizer && !PrologueStubs)
581 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CALLstk))
582 .addExternalSymbol("__runtime_stack_check");
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000583}
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000584
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000585void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
586 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000587 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000588 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000589
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000590 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000591 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000592 auto &HRI = *HST.getRegisterInfo();
593 unsigned SP = HRI.getStackRegister();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000594
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000595 MachineInstr *RetI = getReturn(MBB);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000596 unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
597
598 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
599 DebugLoc DL;
600 if (InsertPt != MBB.end())
601 DL = InsertPt->getDebugLoc();
602 else if (!MBB.empty())
603 DL = std::prev(MBB.end())->getDebugLoc();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000604
605 // Handle EH_RETURN.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000606 if (RetOpc == Hexagon::EH_RETURN_JMPR) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000607 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
608 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::A2_add), SP)
609 .addReg(SP)
610 .addReg(Hexagon::R28);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000611 return;
612 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000613
614 // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
615 // frame instruction if we encounter it.
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000616 if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
Krzysztof Parzyszekfae79862016-07-27 18:47:25 +0000617 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC ||
618 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT ||
619 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000620 MachineBasicBlock::iterator It = RetI;
621 ++It;
622 // Delete all instructions after the RESTORE (except labels).
623 while (It != MBB.end()) {
624 if (!It->isLabel())
625 It = MBB.erase(It);
626 else
627 ++It;
Jyotsna Verma300f0b92013-05-10 20:27:34 +0000628 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000629 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000630 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000631
632 // It is possible that the restoring code is a call to a library function.
633 // All of the restore* functions include "deallocframe", so we need to make
634 // sure that we don't add an extra one.
635 bool NeedsDeallocframe = true;
636 if (!MBB.empty() && InsertPt != MBB.begin()) {
637 MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
638 unsigned COpc = PrevIt->getOpcode();
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000639 if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
Krzysztof Parzyszekfae79862016-07-27 18:47:25 +0000640 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC ||
641 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT ||
642 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC ||
643 COpc == Hexagon::CALLv3nr || COpc == Hexagon::CALLRv3nr)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000644 NeedsDeallocframe = false;
645 }
646
647 if (!NeedsDeallocframe)
648 return;
649 // If the returning instruction is JMPret, replace it with dealloc_return,
650 // otherwise just add deallocframe. The function could be returning via a
651 // tail call.
652 if (RetOpc != Hexagon::JMPret || DisableDeallocRet) {
653 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
654 return;
655 }
656 unsigned NewOpc = Hexagon::L4_return;
657 MachineInstr *NewI = BuildMI(MBB, RetI, DL, HII.get(NewOpc));
658 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000659 NewI->copyImplicitOps(MF, *RetI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000660 MBB.erase(RetI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000661}
662
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000663void HexagonFrameLowering::updateEntryPaths(MachineFunction &MF,
664 MachineBasicBlock &SaveB) const {
665 SetVector<unsigned> Worklist;
666
667 MachineBasicBlock &EntryB = MF.front();
668 Worklist.insert(EntryB.getNumber());
669
670 unsigned SaveN = SaveB.getNumber();
671 auto &CSI = MF.getFrameInfo()->getCalleeSavedInfo();
672
673 for (unsigned i = 0; i < Worklist.size(); ++i) {
674 unsigned BN = Worklist[i];
675 MachineBasicBlock &MBB = *MF.getBlockNumbered(BN);
676 for (auto &R : CSI)
677 if (!MBB.isLiveIn(R.getReg()))
678 MBB.addLiveIn(R.getReg());
679 if (BN != SaveN)
680 for (auto &SB : MBB.successors())
681 Worklist.insert(SB->getNumber());
682 }
683}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000684
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000685bool HexagonFrameLowering::updateExitPaths(MachineBasicBlock &MBB,
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000686 MachineBasicBlock &RestoreB, BitVector &DoneT, BitVector &DoneF,
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000687 BitVector &Path) const {
688 assert(MBB.getNumber() >= 0);
689 unsigned BN = MBB.getNumber();
690 if (Path[BN] || DoneF[BN])
691 return false;
692 if (DoneT[BN])
693 return true;
694
695 auto &CSI = MBB.getParent()->getFrameInfo()->getCalleeSavedInfo();
696
697 Path[BN] = true;
698 bool ReachedExit = false;
699 for (auto &SB : MBB.successors())
700 ReachedExit |= updateExitPaths(*SB, RestoreB, DoneT, DoneF, Path);
701
702 if (!MBB.empty() && MBB.back().isReturn()) {
703 // Add implicit uses of all callee-saved registers to the reached
704 // return instructions. This is to prevent the anti-dependency breaker
705 // from renaming these registers.
706 MachineInstr &RetI = MBB.back();
707 if (!isRestoreCall(RetI.getOpcode()))
708 for (auto &R : CSI)
709 RetI.addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
710 ReachedExit = true;
711 }
712
713 // We don't want to add unnecessary live-ins to the restore block: since
714 // the callee-saved registers are being defined in it, the entry of the
715 // restore block cannot be on the path from the definitions to any exit.
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000716 if (ReachedExit && &MBB != &RestoreB) {
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000717 for (auto &R : CSI)
718 if (!MBB.isLiveIn(R.getReg()))
719 MBB.addLiveIn(R.getReg());
720 DoneT[BN] = true;
721 }
722 if (!ReachedExit)
723 DoneF[BN] = true;
724
725 Path[BN] = false;
726 return ReachedExit;
727}
728
729
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000730namespace {
731 bool IsAllocFrame(MachineBasicBlock::const_iterator It) {
732 if (!It->isBundle())
733 return It->getOpcode() == Hexagon::S2_allocframe;
734 auto End = It->getParent()->instr_end();
Duncan P. N. Exon Smithd84f6002016-02-22 21:30:15 +0000735 MachineBasicBlock::const_instr_iterator I = It.getInstrIterator();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000736 while (++I != End && I->isBundled())
737 if (I->getOpcode() == Hexagon::S2_allocframe)
738 return true;
739 return false;
740 }
741
742 MachineBasicBlock::iterator FindAllocFrame(MachineBasicBlock &B) {
743 for (auto &I : B)
744 if (IsAllocFrame(I))
745 return I;
746 return B.end();
747 }
748}
749
750
751void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
752 for (auto &B : MF) {
753 auto AF = FindAllocFrame(B);
754 if (AF == B.end())
755 continue;
756 insertCFIInstructionsAt(B, ++AF);
757 }
758}
759
760
761void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
762 MachineBasicBlock::iterator At) const {
763 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000764 MachineFrameInfo &MFI = *MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000765 MachineModuleInfo &MMI = MF.getMMI();
766 auto &HST = MF.getSubtarget<HexagonSubtarget>();
767 auto &HII = *HST.getInstrInfo();
768 auto &HRI = *HST.getRegisterInfo();
769
770 // If CFI instructions have debug information attached, something goes
771 // wrong with the final assembly generation: the prolog_end is placed
772 // in a wrong location.
773 DebugLoc DL;
774 const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
775
776 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000777 bool HasFP = hasFP(MF);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000778
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000779 if (HasFP) {
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000780 unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
781 unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000782
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000783 // Define CFA via an offset from the value of FP.
784 //
785 // -8 -4 0 (SP)
786 // --+----+----+---------------------
787 // | FP | LR | increasing addresses -->
788 // --+----+----+---------------------
789 // | +-- Old SP (before allocframe)
790 // +-- New FP (after allocframe)
791 //
792 // MCCFIInstruction::createDefCfa subtracts the offset from the register.
793 // MCCFIInstruction::createOffset takes the offset without sign change.
794 auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
795 BuildMI(MBB, At, DL, CFID)
796 .addCFIIndex(MMI.addFrameInst(DefCfa));
797 // R31 (return addr) = CFA - 4
798 auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
799 BuildMI(MBB, At, DL, CFID)
800 .addCFIIndex(MMI.addFrameInst(OffR31));
801 // R30 (frame ptr) = CFA - 8
802 auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
803 BuildMI(MBB, At, DL, CFID)
804 .addCFIIndex(MMI.addFrameInst(OffR30));
805 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000806
807 static unsigned int RegsToMove[] = {
808 Hexagon::R1, Hexagon::R0, Hexagon::R3, Hexagon::R2,
809 Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
810 Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
811 Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
812 Hexagon::D0, Hexagon::D1, Hexagon::D8, Hexagon::D9,
813 Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
814 Hexagon::NoRegister
815 };
816
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000817 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000818
819 for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
820 unsigned Reg = RegsToMove[i];
821 auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
822 return C.getReg() == Reg;
823 };
824 auto F = std::find_if(CSI.begin(), CSI.end(), IfR);
825 if (F == CSI.end())
826 continue;
827
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000828 int64_t Offset;
829 if (HasFP) {
830 // If the function has a frame pointer (i.e. has an allocframe),
831 // then the CFA has been defined in terms of FP. Any offsets in
832 // the following CFI instructions have to be defined relative
833 // to FP, which points to the bottom of the stack frame.
834 // The function getFrameIndexReference can still choose to use SP
835 // for the offset calculation, so we cannot simply call it here.
836 // Instead, get the offset (relative to the FP) directly.
837 Offset = MFI.getObjectOffset(F->getFrameIdx());
838 } else {
839 unsigned FrameReg;
840 Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg);
841 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000842 // Subtract 8 to make room for R30 and R31, which are added above.
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000843 Offset -= 8;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000844
845 if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
846 unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
847 auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
848 Offset);
849 BuildMI(MBB, At, DL, CFID)
850 .addCFIIndex(MMI.addFrameInst(OffReg));
851 } else {
852 // Split the double regs into subregs, and generate appropriate
853 // cfi_offsets.
854 // The only reason, we are split double regs is, llvm-mc does not
855 // understand paired registers for cfi_offset.
856 // Eg .cfi_offset r1:0, -64
857
858 unsigned HiReg = HRI.getSubReg(Reg, Hexagon::subreg_hireg);
859 unsigned LoReg = HRI.getSubReg(Reg, Hexagon::subreg_loreg);
860 unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
861 unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
862 auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
863 Offset+4);
864 BuildMI(MBB, At, DL, CFID)
865 .addCFIIndex(MMI.addFrameInst(OffHi));
866 auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
867 Offset);
868 BuildMI(MBB, At, DL, CFID)
869 .addCFIIndex(MMI.addFrameInst(OffLo));
870 }
871 }
872}
873
874
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000875bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000876 auto &MFI = *MF.getFrameInfo();
877 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
878
879 bool HasFixed = MFI.getNumFixedObjects();
880 bool HasPrealloc = const_cast<MachineFrameInfo&>(MFI)
881 .getLocalFrameObjectCount();
882 bool HasExtraAlign = HRI.needsStackRealignment(MF);
883 bool HasAlloca = MFI.hasVarSizedObjects();
884
885 // Insert ALLOCFRAME if we need to or at -O0 for the debugger. Think
886 // that this shouldn't be required, but doing so now because gcc does and
887 // gdb can't break at the start of the function without it. Will remove if
888 // this turns out to be a gdb bug.
889 //
890 if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
891 return true;
892
893 // By default we want to use SP (since it's always there). FP requires
894 // some setup (i.e. ALLOCFRAME).
895 // Fixed and preallocated objects need FP if the distance from them to
896 // the SP is unknown (as is with alloca or aligna).
897 if ((HasFixed || HasPrealloc) && (HasAlloca || HasExtraAlign))
898 return true;
899
900 if (MFI.getStackSize() > 0) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000901 if (EnableStackOVFSanitizer || UseAllocframe)
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000902 return true;
903 }
904
905 if (MFI.hasCalls() ||
906 MF.getInfo<HexagonMachineFunctionInfo>()->hasClobberLR())
907 return true;
908
909 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000910}
911
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000912
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000913enum SpillKind {
914 SK_ToMem,
915 SK_FromMem,
916 SK_FromMemTailcall
917};
918
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000919static const char *getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType,
920 bool Stkchk = false) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000921 const char * V4SpillToMemoryFunctions[] = {
922 "__save_r16_through_r17",
923 "__save_r16_through_r19",
924 "__save_r16_through_r21",
925 "__save_r16_through_r23",
926 "__save_r16_through_r25",
927 "__save_r16_through_r27" };
928
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000929 const char * V4SpillToMemoryStkchkFunctions[] = {
930 "__save_r16_through_r17_stkchk",
931 "__save_r16_through_r19_stkchk",
932 "__save_r16_through_r21_stkchk",
933 "__save_r16_through_r23_stkchk",
934 "__save_r16_through_r25_stkchk",
935 "__save_r16_through_r27_stkchk" };
936
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000937 const char * V4SpillFromMemoryFunctions[] = {
938 "__restore_r16_through_r17_and_deallocframe",
939 "__restore_r16_through_r19_and_deallocframe",
940 "__restore_r16_through_r21_and_deallocframe",
941 "__restore_r16_through_r23_and_deallocframe",
942 "__restore_r16_through_r25_and_deallocframe",
943 "__restore_r16_through_r27_and_deallocframe" };
944
945 const char * V4SpillFromMemoryTailcallFunctions[] = {
946 "__restore_r16_through_r17_and_deallocframe_before_tailcall",
947 "__restore_r16_through_r19_and_deallocframe_before_tailcall",
948 "__restore_r16_through_r21_and_deallocframe_before_tailcall",
949 "__restore_r16_through_r23_and_deallocframe_before_tailcall",
950 "__restore_r16_through_r25_and_deallocframe_before_tailcall",
951 "__restore_r16_through_r27_and_deallocframe_before_tailcall"
952 };
953
954 const char **SpillFunc = nullptr;
955
956 switch(SpillType) {
957 case SK_ToMem:
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000958 SpillFunc = Stkchk ? V4SpillToMemoryStkchkFunctions
959 : V4SpillToMemoryFunctions;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000960 break;
961 case SK_FromMem:
962 SpillFunc = V4SpillFromMemoryFunctions;
963 break;
964 case SK_FromMemTailcall:
965 SpillFunc = V4SpillFromMemoryTailcallFunctions;
966 break;
967 }
968 assert(SpillFunc && "Unknown spill kind");
969
970 // Spill all callee-saved registers up to the highest register used.
971 switch (MaxReg) {
972 case Hexagon::R17:
973 return SpillFunc[0];
974 case Hexagon::R19:
975 return SpillFunc[1];
976 case Hexagon::R21:
977 return SpillFunc[2];
978 case Hexagon::R23:
979 return SpillFunc[3];
980 case Hexagon::R25:
981 return SpillFunc[4];
982 case Hexagon::R27:
983 return SpillFunc[5];
984 default:
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000985 llvm_unreachable("Unhandled maximum callee save register");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000986 }
987 return 0;
988}
989
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000990
James Y Knight5567baf2015-08-15 02:32:35 +0000991int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF,
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000992 int FI, unsigned &FrameReg) const {
993 auto &MFI = *MF.getFrameInfo();
994 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000995
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000996 int Offset = MFI.getObjectOffset(FI);
997 bool HasAlloca = MFI.hasVarSizedObjects();
998 bool HasExtraAlign = HRI.needsStackRealignment(MF);
999 bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
James Y Knight5567baf2015-08-15 02:32:35 +00001000
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001001 unsigned SP = HRI.getStackRegister(), FP = HRI.getFrameRegister();
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001002 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1003 unsigned AP = HMFI.getStackAlignBasePhysReg();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001004 unsigned FrameSize = MFI.getStackSize();
1005
1006 bool UseFP = false, UseAP = false; // Default: use SP (except at -O0).
1007 // Use FP at -O0, except when there are objects with extra alignment.
1008 // That additional alignment requirement may cause a pad to be inserted,
1009 // which will make it impossible to use FP to access objects located
1010 // past the pad.
1011 if (NoOpt && !HasExtraAlign)
1012 UseFP = true;
1013 if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
1014 // Fixed and preallocated objects will be located before any padding
1015 // so FP must be used to access them.
1016 UseFP |= (HasAlloca || HasExtraAlign);
1017 } else {
1018 if (HasAlloca) {
1019 if (HasExtraAlign)
1020 UseAP = true;
1021 else
1022 UseFP = true;
1023 }
1024 }
1025
1026 // If FP was picked, then there had better be FP.
1027 bool HasFP = hasFP(MF);
1028 assert((HasFP || !UseFP) && "This function must have frame pointer");
1029
1030 // Having FP implies allocframe. Allocframe will store extra 8 bytes:
1031 // FP/LR. If the base register is used to access an object across these
1032 // 8 bytes, then the offset will need to be adjusted by 8.
1033 //
1034 // After allocframe:
1035 // HexagonISelLowering adds 8 to ---+
1036 // the offsets of all stack-based |
1037 // arguments (*) |
1038 // |
1039 // getObjectOffset < 0 0 8 getObjectOffset >= 8
1040 // ------------------------+-----+------------------------> increasing
1041 // <local objects> |FP/LR| <input arguments> addresses
1042 // -----------------+------+-----+------------------------>
1043 // | |
1044 // SP/AP point --+ +-- FP points here (**)
1045 // somewhere on
1046 // this side of FP/LR
1047 //
1048 // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
1049 // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
1050
1051 // The lowering assumes that FP/LR is present, and so the offsets of
1052 // the formal arguments start at 8. If FP/LR is not there we need to
1053 // reduce the offset by 8.
1054 if (Offset > 0 && !HasFP)
1055 Offset -= 8;
1056
1057 if (UseFP)
1058 FrameReg = FP;
1059 else if (UseAP)
1060 FrameReg = AP;
1061 else
1062 FrameReg = SP;
1063
1064 // Calculate the actual offset in the instruction. If there is no FP
1065 // (in other words, no allocframe), then SP will not be adjusted (i.e.
1066 // there will be no SP -= FrameSize), so the frame size should not be
1067 // added to the calculated offset.
1068 int RealOffset = Offset;
1069 if (!UseFP && !UseAP && HasFP)
1070 RealOffset = FrameSize+Offset;
1071 return RealOffset;
Jakob Stoklund Olesen0b97dbc2012-05-30 22:40:03 +00001072}
1073
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001074
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001075bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001076 const CSIVect &CSI, const HexagonRegisterInfo &HRI,
1077 bool &PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001078 if (CSI.empty())
1079 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001080
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001081 MachineBasicBlock::iterator MI = MBB.begin();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001082 PrologueStubs = false;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001083 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001084 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1085 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001086
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001087 if (useSpillFunction(MF, CSI)) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001088 PrologueStubs = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001089 unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001090 bool StkOvrFlowEnabled = EnableStackOVFSanitizer;
1091 const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem,
1092 StkOvrFlowEnabled);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001093 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
Rafael Espindolab1556c42016-06-28 20:13:36 +00001094 bool IsPIC = HTM.isPositionIndependent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001095 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001096
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001097 // Call spill function.
1098 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001099 unsigned SpillOpc;
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001100 if (StkOvrFlowEnabled) {
1101 if (LongCalls)
1102 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT_PIC
1103 : Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT;
1104 else
1105 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC
1106 : Hexagon::SAVE_REGISTERS_CALL_V4STK;
1107 } else {
1108 if (LongCalls)
1109 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_EXT_PIC
1110 : Hexagon::SAVE_REGISTERS_CALL_V4_EXT;
1111 else
1112 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
1113 : Hexagon::SAVE_REGISTERS_CALL_V4;
1114 }
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001115
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001116 MachineInstr *SaveRegsCall =
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001117 BuildMI(MBB, MI, DL, HII.get(SpillOpc))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001118 .addExternalSymbol(SpillFun);
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001119
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001120 // Add callee-saved registers as use.
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001121 addCalleeSaveRegistersAsImpOperand(SaveRegsCall, CSI, false, true);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001122 // Add live in registers.
1123 for (unsigned I = 0; I < CSI.size(); ++I)
1124 MBB.addLiveIn(CSI[I].getReg());
1125 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001126 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001127
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001128 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001129 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001130 // Add live in registers. We treat eh_return callee saved register r0 - r3
1131 // specially. They are not really callee saved registers as they are not
1132 // supposed to be killed.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001133 bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
1134 int FI = CSI[i].getFrameIdx();
1135 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001136 HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001137 if (IsKill)
1138 MBB.addLiveIn(Reg);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001139 }
1140 return true;
1141}
1142
1143
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001144bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
1145 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
1146 if (CSI.empty())
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001147 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001148
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001149 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1150 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001151 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1152 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001153
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001154 if (useRestoreFunction(MF, CSI)) {
1155 bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
1156 unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
1157 SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
1158 const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001159 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
Rafael Espindolab1556c42016-06-28 20:13:36 +00001160 bool IsPIC = HTM.isPositionIndependent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001161 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001162
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001163 // Call spill function.
1164 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
1165 : MBB.getLastNonDebugInstr()->getDebugLoc();
1166 MachineInstr *DeallocCall = nullptr;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001167
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001168 if (HasTC) {
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001169 unsigned RetOpc;
1170 if (LongCalls)
1171 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC
1172 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT;
1173 else
1174 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
1175 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
1176 DeallocCall = BuildMI(MBB, MI, DL, HII.get(RetOpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001177 .addExternalSymbol(RestoreFn);
1178 } else {
1179 // The block has a return.
1180 MachineBasicBlock::iterator It = MBB.getFirstTerminator();
1181 assert(It->isReturn() && std::next(It) == MBB.end());
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001182 unsigned RetOpc;
1183 if (LongCalls)
1184 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC
1185 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT;
1186 else
1187 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
1188 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
1189 DeallocCall = BuildMI(MBB, It, DL, HII.get(RetOpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001190 .addExternalSymbol(RestoreFn);
1191 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +00001192 DeallocCall->copyImplicitOps(MF, *It);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001193 }
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001194 addCalleeSaveRegistersAsImpOperand(DeallocCall, CSI, true, false);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001195 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001196 }
1197
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001198 for (unsigned i = 0; i < CSI.size(); ++i) {
1199 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001200 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1201 int FI = CSI[i].getFrameIdx();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001202 HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001203 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001204
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001205 return true;
1206}
1207
Hans Wennborge1a2e902016-03-31 18:33:38 +00001208MachineBasicBlock::iterator HexagonFrameLowering::eliminateCallFramePseudoInstr(
1209 MachineFunction &MF, MachineBasicBlock &MBB,
1210 MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00001211 MachineInstr &MI = *I;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001212 unsigned Opc = MI.getOpcode();
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001213 (void)Opc; // Silence compiler warning.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001214 assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1215 "Cannot handle this call frame pseudo instruction");
Hans Wennborge1a2e902016-03-31 18:33:38 +00001216 return MBB.erase(I);
Eli Bendersky8da87162013-02-21 20:05:00 +00001217}
1218
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001219
1220void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1221 MachineFunction &MF, RegScavenger *RS) const {
1222 // If this function has uses aligned stack and also has variable sized stack
1223 // objects, then we need to map all spill slots to fixed positions, so that
1224 // they can be accessed through FP. Otherwise they would have to be accessed
1225 // via AP, which may not be available at the particular place in the program.
1226 MachineFrameInfo *MFI = MF.getFrameInfo();
1227 bool HasAlloca = MFI->hasVarSizedObjects();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001228 bool NeedsAlign = (MFI->getMaxAlignment() > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001229
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001230 if (!HasAlloca || !NeedsAlign)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001231 return;
1232
1233 unsigned LFS = MFI->getLocalFrameSize();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001234 for (int i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
1235 if (!MFI->isSpillSlotObjectIndex(i) || MFI->isDeadObjectIndex(i))
1236 continue;
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001237 unsigned S = MFI->getObjectSize(i);
1238 // Reduce the alignment to at most 8. This will require unaligned vector
1239 // stores if they happen here.
1240 unsigned A = std::max(MFI->getObjectAlignment(i), 8U);
1241 MFI->setObjectAlignment(i, 8);
1242 LFS = alignTo(LFS+S, A);
1243 MFI->mapLocalFrameObject(i, -LFS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001244 }
1245
1246 MFI->setLocalFrameSize(LFS);
1247 unsigned A = MFI->getLocalFrameMaxAlign();
1248 assert(A <= 8 && "Unexpected local frame alignment");
1249 if (A == 0)
1250 MFI->setLocalFrameMaxAlign(8);
1251 MFI->setUseLocalStackAllocationBlock(true);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001252
1253 // Set the physical aligned-stack base address register.
1254 unsigned AP = 0;
1255 if (const MachineInstr *AI = getAlignaInstr(MF))
1256 AP = AI->getOperand(0).getReg();
1257 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1258 HMFI.setStackAlignBasePhysReg(AP);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001259}
1260
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001261/// Returns true if there are no caller-saved registers available in class RC.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001262static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001263 const HexagonRegisterInfo &HRI, const TargetRegisterClass *RC) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001264 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001265
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001266 auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1267 for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1268 if (MRI.isPhysRegUsed(*AI))
1269 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001270 return false;
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001271 };
1272
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001273 // Check for an unused caller-saved register. Callee-saved registers
1274 // have become pristine by now.
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001275 for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF, RC); *P; ++P)
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001276 if (!IsUsed(*P))
1277 return false;
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001278
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001279 // All caller-saved registers are used.
1280 return true;
1281}
1282
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001283
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001284#ifndef NDEBUG
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001285static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001286 dbgs() << '{';
1287 for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1288 unsigned R = x;
1289 dbgs() << ' ' << PrintReg(R, &TRI);
1290 }
1291 dbgs() << " }";
1292}
1293#endif
1294
1295
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001296bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1297 const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
Krzysztof Parzyszek27ba19a12015-04-23 20:42:20 +00001298 DEBUG(dbgs() << LLVM_FUNCTION_NAME << " on "
Krzysztof Parzyszeked75e7a2015-04-23 20:57:39 +00001299 << MF.getFunction()->getName() << '\n');
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001300 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001301 BitVector SRegs(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001302
1303 // Generate a set of unique, callee-saved registers (SRegs), where each
1304 // register in the set is maximal in terms of sub-/super-register relation,
1305 // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1306
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001307 // (1) For each callee-saved register, add that register and all of its
1308 // sub-registers to SRegs.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001309 DEBUG(dbgs() << "Initial CS registers: {");
1310 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1311 unsigned R = CSI[i].getReg();
1312 DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1313 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1314 SRegs[*SR] = true;
1315 }
1316 DEBUG(dbgs() << " }\n");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001317 DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001318
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001319 // (2) For each reserved register, remove that register and all of its
1320 // sub- and super-registers from SRegs.
1321 BitVector Reserved = TRI->getReservedRegs(MF);
1322 for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1323 unsigned R = x;
1324 for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1325 SRegs[*SR] = false;
1326 }
1327 DEBUG(dbgs() << "Res: "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1328 DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1329
1330 // (3) Collect all registers that have at least one sub-register in SRegs,
1331 // and also have no sub-registers that are reserved. These will be the can-
1332 // didates for saving as a whole instead of their individual sub-registers.
1333 // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1334 BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001335 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1336 unsigned R = x;
1337 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1338 TmpSup[*SR] = true;
1339 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001340 for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1341 unsigned R = x;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001342 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1343 if (!Reserved[*SR])
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001344 continue;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001345 TmpSup[R] = false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001346 break;
1347 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001348 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001349 DEBUG(dbgs() << "TmpSup: "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001350
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001351 // (4) Include all super-registers found in (3) into SRegs.
1352 SRegs |= TmpSup;
1353 DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001354
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001355 // (5) For each register R in SRegs, if any super-register of R is in SRegs,
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001356 // remove R from SRegs.
1357 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1358 unsigned R = x;
1359 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1360 if (!SRegs[*SR])
1361 continue;
1362 SRegs[R] = false;
1363 break;
1364 }
1365 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001366 DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001367
1368 // Now, for each register that has a fixed stack slot, create the stack
1369 // object for it.
1370 CSI.clear();
1371
1372 typedef TargetFrameLowering::SpillSlot SpillSlot;
1373 unsigned NumFixed;
1374 int MinOffset = 0; // CS offsets are negative.
1375 const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1376 for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1377 if (!SRegs[S->Reg])
1378 continue;
1379 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
1380 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), S->Offset);
1381 MinOffset = std::min(MinOffset, S->Offset);
1382 CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1383 SRegs[S->Reg] = false;
1384 }
1385
1386 // There can be some registers that don't have fixed slots. For example,
1387 // we need to store R0-R3 in functions with exception handling. For each
1388 // such register, create a non-fixed stack object.
1389 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1390 unsigned R = x;
1391 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
1392 int Off = MinOffset - RC->getSize();
1393 unsigned Align = std::min(RC->getAlignment(), getStackAlignment());
1394 assert(isPowerOf2_32(Align));
1395 Off &= -Align;
1396 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), Off);
1397 MinOffset = std::min(MinOffset, Off);
1398 CSI.push_back(CalleeSavedInfo(R, FI));
1399 SRegs[R] = false;
1400 }
1401
1402 DEBUG({
1403 dbgs() << "CS information: {";
1404 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1405 int FI = CSI[i].getFrameIdx();
1406 int Off = MFI->getObjectOffset(FI);
1407 dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1408 if (Off >= 0)
1409 dbgs() << '+';
1410 dbgs() << Off;
1411 }
1412 dbgs() << " }\n";
1413 });
1414
1415#ifndef NDEBUG
1416 // Verify that all registers were handled.
1417 bool MissedReg = false;
1418 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1419 unsigned R = x;
1420 dbgs() << PrintReg(R, TRI) << ' ';
1421 MissedReg = true;
1422 }
1423 if (MissedReg)
1424 llvm_unreachable("...there are unhandled callee-saved registers!");
1425#endif
1426
1427 return true;
1428}
1429
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001430
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001431bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1432 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1433 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1434 MachineInstr *MI = &*It;
1435 DebugLoc DL = MI->getDebugLoc();
1436 unsigned DstR = MI->getOperand(0).getReg();
1437 unsigned SrcR = MI->getOperand(1).getReg();
1438 if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1439 !Hexagon::ModRegsRegClass.contains(SrcR))
1440 return false;
1441
1442 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1443 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR)
1444 .addOperand(MI->getOperand(1));
1445 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1446 .addReg(TmpR, RegState::Kill);
1447
1448 NewRegs.push_back(TmpR);
1449 B.erase(It);
1450 return true;
1451}
1452
1453bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1454 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1455 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1456 MachineInstr *MI = &*It;
1457 DebugLoc DL = MI->getDebugLoc();
1458 unsigned Opc = MI->getOpcode();
1459 unsigned SrcR = MI->getOperand(2).getReg();
1460 bool IsKill = MI->getOperand(2).isKill();
1461
1462 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1463 int FI = MI->getOperand(0).getIndex();
1464
1465 // TmpR = C2_tfrpr SrcR if SrcR is a predicate register
1466 // TmpR = A2_tfrcrr SrcR if SrcR is a modifier register
1467 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1468 unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1469 : Hexagon::A2_tfrcrr;
1470 BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1471 .addReg(SrcR, getKillRegState(IsKill));
1472
1473 // S2_storeri_io FI, 0, TmpR
1474 BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1475 .addFrameIndex(FI)
1476 .addImm(0)
1477 .addReg(TmpR, RegState::Kill)
1478 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1479
1480 NewRegs.push_back(TmpR);
1481 B.erase(It);
1482 return true;
1483}
1484
1485bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1486 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1487 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1488 MachineInstr *MI = &*It;
1489 DebugLoc DL = MI->getDebugLoc();
1490 unsigned Opc = MI->getOpcode();
1491 unsigned DstR = MI->getOperand(0).getReg();
1492
1493 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1494 int FI = MI->getOperand(1).getIndex();
1495
1496 // TmpR = L2_loadri_io FI, 0
1497 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1498 BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1499 .addFrameIndex(FI)
1500 .addImm(0)
1501 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1502
1503 // DstR = C2_tfrrp TmpR if DstR is a predicate register
1504 // DstR = A2_tfrrcr TmpR if DstR is a modifier register
1505 unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1506 : Hexagon::A2_tfrrcr;
1507 BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1508 .addReg(TmpR, RegState::Kill);
1509
1510 NewRegs.push_back(TmpR);
1511 B.erase(It);
1512 return true;
1513}
1514
1515
1516bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1517 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1518 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1519 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1520 MachineInstr *MI = &*It;
1521 DebugLoc DL = MI->getDebugLoc();
1522 unsigned SrcR = MI->getOperand(2).getReg();
1523 bool IsKill = MI->getOperand(2).isKill();
1524
1525 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1526 int FI = MI->getOperand(0).getIndex();
1527
1528 bool Is128B = HST.useHVXDblOps();
1529 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1530 : &Hexagon::VectorRegs128BRegClass;
1531
1532 // Insert transfer to general vector register.
1533 // TmpR0 = A2_tfrsi 0x01010101
1534 // TmpR1 = V6_vandqrt Qx, TmpR0
1535 // store FI, 0, TmpR1
1536 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1537 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1538
1539 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1540 .addImm(0x01010101);
1541
1542 unsigned VandOpc = !Is128B ? Hexagon::V6_vandqrt : Hexagon::V6_vandqrt_128B;
1543 BuildMI(B, It, DL, HII.get(VandOpc), TmpR1)
1544 .addReg(SrcR, getKillRegState(IsKill))
1545 .addReg(TmpR0, RegState::Kill);
1546
1547 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1548 HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1549 expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1550
1551 NewRegs.push_back(TmpR0);
1552 NewRegs.push_back(TmpR1);
1553 B.erase(It);
1554 return true;
1555}
1556
1557bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1558 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1559 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1560 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1561 MachineInstr *MI = &*It;
1562 DebugLoc DL = MI->getDebugLoc();
1563 unsigned DstR = MI->getOperand(0).getReg();
1564
1565 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1566 int FI = MI->getOperand(1).getIndex();
1567
1568 bool Is128B = HST.useHVXDblOps();
1569 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1570 : &Hexagon::VectorRegs128BRegClass;
1571
1572 // TmpR0 = A2_tfrsi 0x01010101
1573 // TmpR1 = load FI, 0
1574 // DstR = V6_vandvrt TmpR1, TmpR0
1575 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1576 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1577
1578 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1579 .addImm(0x01010101);
1580 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1581 HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1582 expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1583
1584 unsigned VandOpc = !Is128B ? Hexagon::V6_vandvrt : Hexagon::V6_vandvrt_128B;
1585 BuildMI(B, It, DL, HII.get(VandOpc), DstR)
1586 .addReg(TmpR1, RegState::Kill)
1587 .addReg(TmpR0, RegState::Kill);
1588
1589 NewRegs.push_back(TmpR0);
1590 NewRegs.push_back(TmpR1);
1591 B.erase(It);
1592 return true;
1593}
1594
1595bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1596 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1597 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1598 MachineFunction &MF = *B.getParent();
1599 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1600 auto &MFI = *MF.getFrameInfo();
1601 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1602 MachineInstr *MI = &*It;
1603 DebugLoc DL = MI->getDebugLoc();
1604
1605 unsigned SrcR = MI->getOperand(2).getReg();
1606 unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::subreg_loreg);
1607 unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::subreg_hireg);
1608 bool IsKill = MI->getOperand(2).isKill();
1609
1610 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1611 int FI = MI->getOperand(0).getIndex();
1612
1613 bool Is128B = HST.useHVXDblOps();
1614 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1615 : &Hexagon::VectorRegs128BRegClass;
1616 unsigned Size = RC->getSize();
1617 unsigned NeedAlign = RC->getAlignment();
1618 unsigned HasAlign = MFI.getObjectAlignment(FI);
1619 unsigned StoreOpc;
1620
1621 // Store low part.
1622 if (NeedAlign <= HasAlign)
1623 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1624 else
1625 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1626
1627 BuildMI(B, It, DL, HII.get(StoreOpc))
1628 .addFrameIndex(FI)
1629 .addImm(0)
1630 .addReg(SrcLo, getKillRegState(IsKill))
1631 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1632
1633 // Load high part.
1634 if (NeedAlign <= MinAlign(HasAlign, Size))
1635 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1636 else
1637 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1638
1639 BuildMI(B, It, DL, HII.get(StoreOpc))
1640 .addFrameIndex(FI)
1641 .addImm(Size)
1642 .addReg(SrcHi, getKillRegState(IsKill))
1643 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1644
1645 B.erase(It);
1646 return true;
1647}
1648
1649bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1650 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1651 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1652 MachineFunction &MF = *B.getParent();
1653 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1654 auto &MFI = *MF.getFrameInfo();
1655 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1656 MachineInstr *MI = &*It;
1657 DebugLoc DL = MI->getDebugLoc();
1658
1659 unsigned DstR = MI->getOperand(0).getReg();
1660 unsigned DstHi = HRI.getSubReg(DstR, Hexagon::subreg_hireg);
1661 unsigned DstLo = HRI.getSubReg(DstR, Hexagon::subreg_loreg);
1662
1663 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1664 int FI = MI->getOperand(1).getIndex();
1665
1666 bool Is128B = HST.useHVXDblOps();
1667 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1668 : &Hexagon::VectorRegs128BRegClass;
1669 unsigned Size = RC->getSize();
1670 unsigned NeedAlign = RC->getAlignment();
1671 unsigned HasAlign = MFI.getObjectAlignment(FI);
1672 unsigned LoadOpc;
1673
1674 // Load low part.
1675 if (NeedAlign <= HasAlign)
1676 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1677 else
1678 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1679
1680 BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1681 .addFrameIndex(FI)
1682 .addImm(0)
1683 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1684
1685 // Load high part.
1686 if (NeedAlign <= MinAlign(HasAlign, Size))
1687 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1688 else
1689 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1690
1691 BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1692 .addFrameIndex(FI)
1693 .addImm(Size)
1694 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1695
1696 B.erase(It);
1697 return true;
1698}
1699
1700bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1701 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1702 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1703 MachineFunction &MF = *B.getParent();
1704 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1705 auto &MFI = *MF.getFrameInfo();
1706 MachineInstr *MI = &*It;
1707 DebugLoc DL = MI->getDebugLoc();
1708
1709 unsigned SrcR = MI->getOperand(2).getReg();
1710 bool IsKill = MI->getOperand(2).isKill();
1711
1712 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1713 int FI = MI->getOperand(0).getIndex();
1714
1715 bool Is128B = HST.useHVXDblOps();
1716 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1717 : &Hexagon::VectorRegs128BRegClass;
1718
1719 unsigned NeedAlign = RC->getAlignment();
1720 unsigned HasAlign = MFI.getObjectAlignment(FI);
1721 unsigned StoreOpc;
1722
1723 if (NeedAlign <= HasAlign)
1724 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1725 else
1726 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1727
1728 BuildMI(B, It, DL, HII.get(StoreOpc))
1729 .addFrameIndex(FI)
1730 .addImm(0)
1731 .addReg(SrcR, getKillRegState(IsKill))
1732 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1733
1734 B.erase(It);
1735 return true;
1736}
1737
1738bool HexagonFrameLowering::expandLoadVec(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>();
1743 auto &MFI = *MF.getFrameInfo();
1744 MachineInstr *MI = &*It;
1745 DebugLoc DL = MI->getDebugLoc();
1746
1747 unsigned DstR = MI->getOperand(0).getReg();
1748
1749 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1750 int FI = MI->getOperand(1).getIndex();
1751
1752 bool Is128B = HST.useHVXDblOps();
1753 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1754 : &Hexagon::VectorRegs128BRegClass;
1755
1756 unsigned NeedAlign = RC->getAlignment();
1757 unsigned HasAlign = MFI.getObjectAlignment(FI);
1758 unsigned LoadOpc;
1759
1760 if (NeedAlign <= HasAlign)
1761 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1762 else
1763 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1764
1765 BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1766 .addFrameIndex(FI)
1767 .addImm(0)
1768 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1769
1770 B.erase(It);
1771 return true;
1772}
1773
1774
1775bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1776 SmallVectorImpl<unsigned> &NewRegs) const {
1777 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001778 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001779 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001780 bool Changed = false;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001781
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001782 for (auto &B : MF) {
1783 // Traverse the basic block.
1784 MachineBasicBlock::iterator NextI;
1785 for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1786 MachineInstr *MI = &*I;
1787 NextI = std::next(I);
1788 unsigned Opc = MI->getOpcode();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001789
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001790 switch (Opc) {
1791 case TargetOpcode::COPY:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001792 Changed |= expandCopy(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001793 break;
1794 case Hexagon::STriw_pred:
1795 case Hexagon::STriw_mod:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001796 Changed |= expandStoreInt(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001797 break;
1798 case Hexagon::LDriw_pred:
1799 case Hexagon::LDriw_mod:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001800 Changed |= expandLoadInt(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001801 break;
1802 case Hexagon::STriq_pred_V6:
1803 case Hexagon::STriq_pred_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001804 Changed |= expandStoreVecPred(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001805 break;
1806 case Hexagon::LDriq_pred_V6:
1807 case Hexagon::LDriq_pred_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001808 Changed |= expandLoadVecPred(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001809 break;
1810 case Hexagon::LDrivv_pseudo_V6:
1811 case Hexagon::LDrivv_pseudo_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001812 Changed |= expandLoadVec2(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001813 break;
1814 case Hexagon::STrivv_pseudo_V6:
1815 case Hexagon::STrivv_pseudo_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001816 Changed |= expandStoreVec2(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001817 break;
1818 case Hexagon::STriv_pseudo_V6:
1819 case Hexagon::STriv_pseudo_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001820 Changed |= expandStoreVec(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001821 break;
1822 case Hexagon::LDriv_pseudo_V6:
1823 case Hexagon::LDriv_pseudo_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001824 Changed |= expandLoadVec(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001825 break;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001826 }
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001827 }
1828 }
1829
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001830 return Changed;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001831}
1832
1833
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001834void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1835 BitVector &SavedRegs,
1836 RegScavenger *RS) const {
1837 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1838 auto &HRI = *HST.getRegisterInfo();
1839
1840 SavedRegs.resize(HRI.getNumRegs());
1841
1842 // If we have a function containing __builtin_eh_return we want to spill and
1843 // restore all callee saved registers. Pretend that they are used.
1844 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1845 for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1846 SavedRegs.set(*R);
1847
1848 // Replace predicate register pseudo spill code.
1849 SmallVector<unsigned,8> NewRegs;
1850 expandSpillMacros(MF, NewRegs);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001851 if (OptimizeSpillSlots && !isOptNone(MF))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001852 optimizeSpillSlots(MF, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001853
1854 // We need to reserve a a spill slot if scavenging could potentially require
1855 // spilling a scavenged register.
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001856 if (!NewRegs.empty()) {
1857 MachineFrameInfo &MFI = *MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001858 MachineRegisterInfo &MRI = MF.getRegInfo();
1859 SetVector<const TargetRegisterClass*> SpillRCs;
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001860 // Reserve an int register in any case, because it could be used to hold
1861 // the stack offset in case it does not fit into a spill instruction.
1862 SpillRCs.insert(&Hexagon::IntRegsRegClass);
1863
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001864 for (unsigned VR : NewRegs)
1865 SpillRCs.insert(MRI.getRegClass(VR));
1866
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001867 for (auto *RC : SpillRCs) {
1868 if (!needToReserveScavengingSpillSlots(MF, HRI, RC))
1869 continue;
1870 unsigned Num = RC == &Hexagon::IntRegsRegClass ? NumberScavengerSlots : 1;
1871 unsigned S = RC->getSize(), A = RC->getAlignment();
1872 for (unsigned i = 0; i < Num; i++) {
1873 int NewFI = MFI.CreateSpillStackObject(S, A);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001874 RS->addScavengingFrameIndex(NewFI);
1875 }
1876 }
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001877 }
1878
1879 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1880}
1881
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001882
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001883unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1884 HexagonBlockRanges::IndexRange &FIR,
1885 HexagonBlockRanges::InstrIndexMap &IndexMap,
1886 HexagonBlockRanges::RegToRangeMap &DeadMap,
1887 const TargetRegisterClass *RC) const {
1888 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1889 auto &MRI = MF.getRegInfo();
1890
1891 auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1892 auto F = DeadMap.find({Reg,0});
1893 if (F == DeadMap.end())
1894 return false;
1895 for (auto &DR : F->second)
1896 if (DR.contains(FIR))
1897 return true;
1898 return false;
1899 };
1900
1901 for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
1902 bool Dead = true;
1903 for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
1904 if (isDead(R.Reg))
1905 continue;
1906 Dead = false;
1907 break;
1908 }
1909 if (Dead)
1910 return Reg;
1911 }
1912 return 0;
1913}
1914
1915void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
1916 SmallVectorImpl<unsigned> &VRegs) const {
1917 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1918 auto &HII = *HST.getInstrInfo();
1919 auto &HRI = *HST.getRegisterInfo();
1920 auto &MRI = MF.getRegInfo();
1921 HexagonBlockRanges HBR(MF);
1922
1923 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::InstrIndexMap>
1924 BlockIndexMap;
1925 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::RangeList>
1926 BlockRangeMap;
1927 typedef HexagonBlockRanges::IndexType IndexType;
1928
1929 struct SlotInfo {
1930 BlockRangeMap Map;
NAKAMURA Takumic2cc8702016-02-13 07:29:49 +00001931 unsigned Size;
1932 const TargetRegisterClass *RC;
1933
1934 SlotInfo() : Map(), Size(0), RC(nullptr) {}
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001935 };
1936
1937 BlockIndexMap BlockIndexes;
1938 SmallSet<int,4> BadFIs;
1939 std::map<int,SlotInfo> FIRangeMap;
1940
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001941 // Accumulate register classes: get a common class for a pre-existing
1942 // class HaveRC and a new class NewRC. Return nullptr if a common class
1943 // cannot be found, otherwise return the resulting class. If HaveRC is
1944 // nullptr, assume that it is still unset.
1945 auto getCommonRC = [&HRI] (const TargetRegisterClass *HaveRC,
1946 const TargetRegisterClass *NewRC)
1947 -> const TargetRegisterClass* {
1948 if (HaveRC == nullptr || HaveRC == NewRC)
1949 return NewRC;
1950 // Different classes, both non-null. Pick the more general one.
1951 if (HaveRC->hasSubClassEq(NewRC))
1952 return HaveRC;
1953 if (NewRC->hasSubClassEq(HaveRC))
1954 return NewRC;
1955 return nullptr;
1956 };
1957
1958 // Scan all blocks in the function. Check all occurrences of frame indexes,
1959 // and collect relevant information.
1960 for (auto &B : MF) {
1961 std::map<int,IndexType> LastStore, LastLoad;
Krzysztof Parzyszek280a50e2016-02-13 14:06:01 +00001962 // Emplace appears not to be supported in gcc 4.7.2-4.
1963 //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
Krzysztof Parzyszekde697d42016-02-17 15:02:07 +00001964 auto P = BlockIndexes.insert(
1965 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001966 auto &IndexMap = P.first->second;
1967 DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n"
1968 << IndexMap << '\n');
1969
1970 for (auto &In : B) {
1971 int LFI, SFI;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001972 bool Load = HII.isLoadFromStackSlot(In, LFI) && !HII.isPredicated(In);
1973 bool Store = HII.isStoreToStackSlot(In, SFI) && !HII.isPredicated(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001974 if (Load && Store) {
1975 // If it's both a load and a store, then we won't handle it.
1976 BadFIs.insert(LFI);
1977 BadFIs.insert(SFI);
1978 continue;
1979 }
1980 // Check for register classes of the register used as the source for
1981 // the store, and the register used as the destination for the load.
1982 // Also, only accept base+imm_offset addressing modes. Other addressing
1983 // modes can have side-effects (post-increments, etc.). For stack
1984 // slots they are very unlikely, so there is not much loss due to
1985 // this restriction.
1986 if (Load || Store) {
1987 int TFI = Load ? LFI : SFI;
1988 unsigned AM = HII.getAddrMode(&In);
1989 SlotInfo &SI = FIRangeMap[TFI];
1990 bool Bad = (AM != HexagonII::BaseImmOffset);
1991 if (!Bad) {
1992 // If the addressing mode is ok, check the register class.
Krzysztof Parzyszek5241b8e2016-07-27 20:50:42 +00001993 unsigned OpNum = Load ? 0 : 2;
1994 auto *RC = HII.getRegClass(In.getDesc(), OpNum, &HRI, MF);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001995 RC = getCommonRC(SI.RC, RC);
1996 if (RC == nullptr)
1997 Bad = true;
1998 else
1999 SI.RC = RC;
2000 }
2001 if (!Bad) {
2002 // Check sizes.
2003 unsigned S = (1U << (HII.getMemAccessSize(&In) - 1));
2004 if (SI.Size != 0 && SI.Size != S)
2005 Bad = true;
2006 else
2007 SI.Size = S;
2008 }
Krzysztof Parzyszek5241b8e2016-07-27 20:50:42 +00002009 if (!Bad) {
2010 for (auto *Mo : In.memoperands()) {
2011 if (!Mo->isVolatile())
2012 continue;
2013 Bad = true;
2014 break;
2015 }
2016 }
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002017 if (Bad)
2018 BadFIs.insert(TFI);
2019 }
2020
2021 // Locate uses of frame indices.
2022 for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
2023 const MachineOperand &Op = In.getOperand(i);
2024 if (!Op.isFI())
2025 continue;
2026 int FI = Op.getIndex();
2027 // Make sure that the following operand is an immediate and that
2028 // it is 0. This is the offset in the stack object.
2029 if (i+1 >= n || !In.getOperand(i+1).isImm() ||
2030 In.getOperand(i+1).getImm() != 0)
2031 BadFIs.insert(FI);
2032 if (BadFIs.count(FI))
2033 continue;
2034
2035 IndexType Index = IndexMap.getIndex(&In);
2036 if (Load) {
2037 if (LastStore[FI] == IndexType::None)
2038 LastStore[FI] = IndexType::Entry;
2039 LastLoad[FI] = Index;
2040 } else if (Store) {
2041 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2042 if (LastStore[FI] != IndexType::None)
2043 RL.add(LastStore[FI], LastLoad[FI], false, false);
2044 else if (LastLoad[FI] != IndexType::None)
2045 RL.add(IndexType::Entry, LastLoad[FI], false, false);
2046 LastLoad[FI] = IndexType::None;
2047 LastStore[FI] = Index;
2048 } else {
2049 BadFIs.insert(FI);
2050 }
2051 }
2052 }
2053
2054 for (auto &I : LastLoad) {
2055 IndexType LL = I.second;
2056 if (LL == IndexType::None)
2057 continue;
2058 auto &RL = FIRangeMap[I.first].Map[&B];
2059 IndexType &LS = LastStore[I.first];
2060 if (LS != IndexType::None)
2061 RL.add(LS, LL, false, false);
2062 else
2063 RL.add(IndexType::Entry, LL, false, false);
2064 LS = IndexType::None;
2065 }
2066 for (auto &I : LastStore) {
2067 IndexType LS = I.second;
2068 if (LS == IndexType::None)
2069 continue;
2070 auto &RL = FIRangeMap[I.first].Map[&B];
2071 RL.add(LS, IndexType::None, false, false);
2072 }
2073 }
2074
2075 DEBUG({
2076 for (auto &P : FIRangeMap) {
2077 dbgs() << "fi#" << P.first;
2078 if (BadFIs.count(P.first))
2079 dbgs() << " (bad)";
2080 dbgs() << " RC: ";
2081 if (P.second.RC != nullptr)
2082 dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
2083 else
2084 dbgs() << "<null>\n";
2085 for (auto &R : P.second.Map)
2086 dbgs() << " BB#" << R.first->getNumber() << " { " << R.second << "}\n";
2087 }
2088 });
2089
2090 // When a slot is loaded from in a block without being stored to in the
2091 // same block, it is live-on-entry to this block. To avoid CFG analysis,
2092 // consider this slot to be live-on-exit from all blocks.
2093 SmallSet<int,4> LoxFIs;
2094
2095 std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
2096
2097 for (auto &P : FIRangeMap) {
2098 // P = pair(FI, map: BB->RangeList)
2099 if (BadFIs.count(P.first))
2100 continue;
2101 for (auto &B : MF) {
2102 auto F = P.second.Map.find(&B);
2103 // F = pair(BB, RangeList)
2104 if (F == P.second.Map.end() || F->second.empty())
2105 continue;
2106 HexagonBlockRanges::IndexRange &IR = F->second.front();
2107 if (IR.start() == IndexType::Entry)
2108 LoxFIs.insert(P.first);
2109 BlockFIMap[&B].push_back(P.first);
2110 }
2111 }
2112
2113 DEBUG({
2114 dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
2115 for (auto &P : BlockFIMap) {
2116 auto &FIs = P.second;
2117 if (FIs.empty())
2118 continue;
2119 dbgs() << " BB#" << P.first->getNumber() << ": {";
2120 for (auto I : FIs) {
2121 dbgs() << " fi#" << I;
2122 if (LoxFIs.count(I))
2123 dbgs() << '*';
2124 }
2125 dbgs() << " }\n";
2126 }
2127 });
2128
2129 // eliminate loads, when all loads eliminated, eliminate all stores.
2130 for (auto &B : MF) {
2131 auto F = BlockIndexes.find(&B);
2132 assert(F != BlockIndexes.end());
2133 HexagonBlockRanges::InstrIndexMap &IM = F->second;
2134 HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
2135 HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
2136 DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n"
2137 << HexagonBlockRanges::PrintRangeMap(DM, HRI));
2138
2139 for (auto FI : BlockFIMap[&B]) {
2140 if (BadFIs.count(FI))
2141 continue;
2142 DEBUG(dbgs() << "Working on fi#" << FI << '\n');
2143 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2144 for (auto &Range : RL) {
2145 DEBUG(dbgs() << "--Examining range:" << RL << '\n');
2146 if (!IndexType::isInstr(Range.start()) ||
2147 !IndexType::isInstr(Range.end()))
2148 continue;
2149 MachineInstr *SI = IM.getInstr(Range.start());
2150 MachineInstr *EI = IM.getInstr(Range.end());
2151 assert(SI->mayStore() && "Unexpected start instruction");
2152 assert(EI->mayLoad() && "Unexpected end instruction");
2153 MachineOperand &SrcOp = SI->getOperand(2);
2154
2155 HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
2156 SrcOp.getSubReg() };
Krzysztof Parzyszek5241b8e2016-07-27 20:50:42 +00002157 auto *RC = HII.getRegClass(SI->getDesc(), 2, &HRI, MF);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002158 // The this-> is needed to unconfuse MSVC.
2159 unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
2160 DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n');
2161 if (FoundR == 0)
2162 continue;
2163
2164 // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
2165 MachineBasicBlock::iterator StartIt = SI, NextIt;
2166 MachineInstr *CopyIn = nullptr;
2167 if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
Benjamin Kramer4ca41fd2016-06-12 17:30:47 +00002168 const DebugLoc &DL = SI->getDebugLoc();
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002169 CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
2170 .addOperand(SrcOp);
2171 }
2172
2173 ++StartIt;
2174 // Check if this is a last store and the FI is live-on-exit.
2175 if (LoxFIs.count(FI) && (&Range == &RL.back())) {
2176 // Update store's source register.
2177 if (unsigned SR = SrcOp.getSubReg())
2178 SrcOp.setReg(HRI.getSubReg(FoundR, SR));
2179 else
2180 SrcOp.setReg(FoundR);
2181 SrcOp.setSubReg(0);
2182 // We are keeping this register live.
2183 SrcOp.setIsKill(false);
2184 } else {
2185 B.erase(SI);
2186 IM.replaceInstr(SI, CopyIn);
2187 }
2188
2189 auto EndIt = std::next(MachineBasicBlock::iterator(EI));
2190 for (auto It = StartIt; It != EndIt; It = NextIt) {
2191 MachineInstr *MI = &*It;
2192 NextIt = std::next(It);
2193 int TFI;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00002194 if (!HII.isLoadFromStackSlot(*MI, TFI) || TFI != FI)
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002195 continue;
2196 unsigned DstR = MI->getOperand(0).getReg();
2197 assert(MI->getOperand(0).getSubReg() == 0);
2198 MachineInstr *CopyOut = nullptr;
2199 if (DstR != FoundR) {
2200 DebugLoc DL = MI->getDebugLoc();
2201 unsigned MemSize = (1U << (HII.getMemAccessSize(MI) - 1));
2202 assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2203 unsigned CopyOpc = TargetOpcode::COPY;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00002204 if (HII.isSignExtendingLoad(*MI))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002205 CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00002206 else if (HII.isZeroExtendingLoad(*MI))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002207 CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2208 CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
2209 .addReg(FoundR, getKillRegState(MI == EI));
2210 }
2211 IM.replaceInstr(MI, CopyOut);
2212 B.erase(It);
2213 }
2214
2215 // Update the dead map.
2216 HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2217 for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2218 DM[RR].subtract(Range);
2219 } // for Range in range list
2220 }
2221 }
2222}
2223
2224
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002225void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002226 const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002227 MachineBasicBlock &MB = *AI->getParent();
2228 DebugLoc DL = AI->getDebugLoc();
2229 unsigned A = AI->getOperand(2).getImm();
2230
2231 // Have
2232 // Rd = alloca Rs, #A
2233 //
2234 // If Rs and Rd are different registers, use this sequence:
2235 // Rd = sub(r29, Rs)
2236 // r29 = sub(r29, Rs)
2237 // Rd = and(Rd, #-A) ; if necessary
2238 // r29 = and(r29, #-A) ; if necessary
2239 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2240 // otherwise, do
2241 // Rd = sub(r29, Rs)
2242 // Rd = and(Rd, #-A) ; if necessary
2243 // r29 = Rd
2244 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2245
2246 MachineOperand &RdOp = AI->getOperand(0);
2247 MachineOperand &RsOp = AI->getOperand(1);
2248 unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2249
2250 // Rd = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002251 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002252 .addReg(SP)
2253 .addReg(Rs);
2254 if (Rs != Rd) {
2255 // r29 = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002256 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002257 .addReg(SP)
2258 .addReg(Rs);
2259 }
2260 if (A > 8) {
2261 // Rd = and(Rd, #-A)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002262 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002263 .addReg(Rd)
2264 .addImm(-int64_t(A));
2265 if (Rs != Rd)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002266 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002267 .addReg(SP)
2268 .addImm(-int64_t(A));
2269 }
2270 if (Rs == Rd) {
2271 // r29 = Rd
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002272 BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002273 .addReg(Rd);
2274 }
2275 if (CF > 0) {
2276 // Rd = add(Rd, #CF)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002277 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002278 .addReg(Rd)
2279 .addImm(CF);
2280 }
2281}
2282
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002283
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002284bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
2285 const MachineFrameInfo *MFI = MF.getFrameInfo();
2286 if (!MFI->hasVarSizedObjects())
2287 return false;
2288 unsigned MaxA = MFI->getMaxAlignment();
2289 if (MaxA <= getStackAlignment())
2290 return false;
2291 return true;
2292}
2293
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002294
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00002295const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2296 const MachineFunction &MF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002297 for (auto &B : MF)
2298 for (auto &I : B)
2299 if (I.getOpcode() == Hexagon::ALIGNA)
2300 return &I;
2301 return nullptr;
2302}
2303
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002304
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00002305/// Adds all callee-saved registers as implicit uses or defs to the
2306/// instruction.
2307void HexagonFrameLowering::addCalleeSaveRegistersAsImpOperand(MachineInstr *MI,
2308 const CSIVect &CSI, bool IsDef, bool IsKill) const {
2309 // Add the callee-saved registers as implicit uses.
2310 for (auto &R : CSI)
2311 MI->addOperand(MachineOperand::CreateReg(R.getReg(), IsDef, true, IsKill));
2312}
2313
2314
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002315/// Determine whether the callee-saved register saves and restores should
2316/// be generated via inline code. If this function returns "true", inline
2317/// code will be generated. If this function returns "false", additional
2318/// checks are performed, which may still lead to the inline code.
2319bool HexagonFrameLowering::shouldInlineCSR(MachineFunction &MF,
2320 const CSIVect &CSI) const {
2321 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2322 return true;
2323 if (!isOptSize(MF) && !isMinSize(MF))
2324 if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2325 return true;
2326
2327 // Check if CSI only has double registers, and if the registers form
2328 // a contiguous block starting from D8.
2329 BitVector Regs(Hexagon::NUM_TARGET_REGS);
2330 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2331 unsigned R = CSI[i].getReg();
2332 if (!Hexagon::DoubleRegsRegClass.contains(R))
2333 return true;
2334 Regs[R] = true;
2335 }
2336 int F = Regs.find_first();
2337 if (F != Hexagon::D8)
2338 return true;
2339 while (F >= 0) {
2340 int N = Regs.find_next(F);
2341 if (N >= 0 && N != F+1)
2342 return true;
2343 F = N;
2344 }
2345
2346 return false;
2347}
2348
2349
2350bool HexagonFrameLowering::useSpillFunction(MachineFunction &MF,
2351 const CSIVect &CSI) const {
2352 if (shouldInlineCSR(MF, CSI))
2353 return false;
2354 unsigned NumCSI = CSI.size();
2355 if (NumCSI <= 1)
2356 return false;
2357
2358 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2359 : SpillFuncThreshold;
2360 return Threshold < NumCSI;
2361}
2362
2363
2364bool HexagonFrameLowering::useRestoreFunction(MachineFunction &MF,
2365 const CSIVect &CSI) const {
2366 if (shouldInlineCSR(MF, CSI))
2367 return false;
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002368 // The restore functions do a bit more than just restoring registers.
2369 // The non-returning versions will go back directly to the caller's
2370 // caller, others will clean up the stack frame in preparation for
2371 // a tail call. Using them can still save code size even if only one
2372 // register is getting restores. Make the decision based on -Oz:
2373 // using -Os will use inline restore for a single register.
2374 if (isMinSize(MF))
2375 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002376 unsigned NumCSI = CSI.size();
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002377 if (NumCSI <= 1)
2378 return false;
2379
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002380 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2381 : SpillFuncThreshold;
2382 return Threshold < NumCSI;
2383}