blob: 95b98160194a23ffdf1bc88bc82babcb87b761f4 [file] [log] [blame]
Jia Liub22310f2012-02-18 12:03:15 +00001//===-- HexagonFrameLowering.cpp - Define frame lowering ------------------===//
Tony Linthicum1213a7a2011-12-12 21:14:40 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//
9//===----------------------------------------------------------------------===//
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000010
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000011#define DEBUG_TYPE "hexagon-pei"
12
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +000013#include "HexagonBlockRanges.h"
Craig Topperb25fda92012-03-17 18:46:09 +000014#include "HexagonFrameLowering.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000015#include "HexagonInstrInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "HexagonMachineFunctionInfo.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000017#include "HexagonRegisterInfo.h"
18#include "HexagonSubtarget.h"
19#include "HexagonTargetMachine.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000020#include "llvm/ADT/BitVector.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000021#include "llvm/ADT/PostOrderIterator.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000022#include "llvm/CodeGen/MachineDominators.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000023#include "llvm/CodeGen/MachineFunction.h"
24#include "llvm/CodeGen/MachineFunctionPass.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/CodeGen/MachineInstrBuilder.h"
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +000026#include "llvm/CodeGen/MachineInstrBuilder.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000027#include "llvm/CodeGen/MachineModuleInfo.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000028#include "llvm/CodeGen/MachinePostDominators.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000029#include "llvm/CodeGen/MachineRegisterInfo.h"
30#include "llvm/CodeGen/RegisterScavenging.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Function.h"
32#include "llvm/IR/Type.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Support/CommandLine.h"
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000034#include "llvm/Support/Debug.h"
35#include "llvm/Support/raw_ostream.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000036#include "llvm/Target/TargetInstrInfo.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000037#include "llvm/Target/TargetMachine.h"
38#include "llvm/Target/TargetOptions.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000039
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000040// Hexagon stack frame layout as defined by the ABI:
41//
42// Incoming arguments
43// passed via stack
44// |
45// |
46// SP during function's FP during function's |
47// +-- runtime (top of stack) runtime (bottom) --+ |
48// | | |
49// --++---------------------+------------------+-----------------++-+-------
50// | parameter area for | variable-size | fixed-size |LR| arg
51// | called functions | local objects | local objects |FP|
52// --+----------------------+------------------+-----------------+--+-------
53// <- size known -> <- size unknown -> <- size known ->
54//
55// Low address High address
56//
57// <--- stack growth
58//
59//
60// - In any circumstances, the outgoing function arguments are always accessi-
61// ble using the SP, and the incoming arguments are accessible using the FP.
62// - If the local objects are not aligned, they can always be accessed using
63// the FP.
64// - If there are no variable-sized objects, the local objects can always be
65// accessed using the SP, regardless whether they are aligned or not. (The
66// alignment padding will be at the bottom of the stack (highest address),
67// and so the offset with respect to the SP will be known at the compile-
68// -time.)
69//
70// The only complication occurs if there are both, local aligned objects, and
71// dynamically allocated (variable-sized) objects. The alignment pad will be
72// placed between the FP and the local objects, thus preventing the use of the
73// FP to access the local objects. At the same time, the variable-sized objects
74// will be between the SP and the local objects, thus introducing an unknown
75// distance from the SP to the locals.
76//
77// To avoid this problem, a new register is created that holds the aligned
78// address of the bottom of the stack, referred in the sources as AP (aligned
79// pointer). The AP will be equal to "FP-p", where "p" is the smallest pad
80// that aligns AP to the required boundary (a maximum of the alignments of
81// all stack objects, fixed- and variable-sized). All local objects[1] will
82// then use AP as the base pointer.
83// [1] The exception is with "fixed" stack objects. "Fixed" stack objects get
84// their name from being allocated at fixed locations on the stack, relative
85// to the FP. In the presence of dynamic allocation and local alignment, such
86// objects can only be accessed through the FP.
87//
88// Illustration of the AP:
89// FP --+
90// |
91// ---------------+---------------------+-----+-----------------------++-+--
92// Rest of the | Local stack objects | Pad | Fixed stack objects |LR|
93// stack frame | (aligned) | | (CSR, spills, etc.) |FP|
94// ---------------+---------------------+-----+-----------------+-----+--+--
95// |<-- Multiple of the -->|
96// stack alignment +-- AP
97//
98// The AP is set up at the beginning of the function. Since it is not a dedi-
99// cated (reserved) register, it needs to be kept live throughout the function
100// to be available as the base register for local object accesses.
101// Normally, an address of a stack objects is obtained by a pseudo-instruction
102// TFR_FI. To access local objects with the AP register present, a different
103// pseudo-instruction needs to be used: TFR_FIA. The TFR_FIA takes one extra
104// argument compared to TFR_FI: the first input register is the AP register.
105// This keeps the register live between its definition and its uses.
106
107// The AP register is originally set up using pseudo-instruction ALIGNA:
108// AP = ALIGNA A
109// where
110// A - required stack alignment
111// The alignment value must be the maximum of all alignments required by
112// any stack object.
113
114// The dynamic allocation uses a pseudo-instruction ALLOCA:
115// Rd = ALLOCA Rs, A
116// where
117// Rd - address of the allocated space
118// Rs - minimum size (the actual allocated can be larger to accommodate
119// alignment)
120// A - required alignment
121
122
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000123using namespace llvm;
124
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000125static cl::opt<bool> DisableDeallocRet("disable-hexagon-dealloc-ret",
126 cl::Hidden, cl::desc("Disable Dealloc Return for Hexagon target"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000127
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000128static cl::opt<int> NumberScavengerSlots("number-scavenger-slots",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000129 cl::Hidden, cl::desc("Set the number of scavenger slots"), cl::init(2),
130 cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000131
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000132static cl::opt<int> SpillFuncThreshold("spill-func-threshold",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000133 cl::Hidden, cl::desc("Specify O2(not Os) spill func threshold"),
134 cl::init(6), cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000135
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000136static cl::opt<int> SpillFuncThresholdOs("spill-func-threshold-Os",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000137 cl::Hidden, cl::desc("Specify Os spill func threshold"),
138 cl::init(1), cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000139
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000140static cl::opt<bool> EnableStackOVFSanitizer("enable-stackovf-sanitizer",
141 cl::Hidden, cl::desc("Enable runtime checks for stack overflow."),
142 cl::init(false), cl::ZeroOrMore);
143
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000144static cl::opt<bool> EnableShrinkWrapping("hexagon-shrink-frame",
145 cl::init(true), cl::Hidden, cl::ZeroOrMore,
146 cl::desc("Enable stack frame shrink wrapping"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000147
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000148static cl::opt<unsigned> ShrinkLimit("shrink-frame-limit", cl::init(UINT_MAX),
149 cl::Hidden, cl::ZeroOrMore, cl::desc("Max count of stack frame "
150 "shrink-wraps"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000151
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000152static cl::opt<bool> UseAllocframe("use-allocframe", cl::init(true),
153 cl::Hidden, cl::desc("Use allocframe more conservatively"));
154
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +0000155static cl::opt<bool> OptimizeSpillSlots("hexagon-opt-spill", cl::Hidden,
156 cl::init(true), cl::desc("Optimize spill slots"));
157
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000158
159namespace llvm {
160 void initializeHexagonCallFrameInformationPass(PassRegistry&);
161 FunctionPass *createHexagonCallFrameInformation();
162}
163
164namespace {
165 class HexagonCallFrameInformation : public MachineFunctionPass {
166 public:
167 static char ID;
168 HexagonCallFrameInformation() : MachineFunctionPass(ID) {
169 PassRegistry &PR = *PassRegistry::getPassRegistry();
170 initializeHexagonCallFrameInformationPass(PR);
171 }
172 bool runOnMachineFunction(MachineFunction &MF) override;
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000173 MachineFunctionProperties getRequiredProperties() const override {
174 return MachineFunctionProperties().set(
175 MachineFunctionProperties::Property::AllVRegsAllocated);
176 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000177 };
178
179 char HexagonCallFrameInformation::ID = 0;
180}
181
182bool HexagonCallFrameInformation::runOnMachineFunction(MachineFunction &MF) {
183 auto &HFI = *MF.getSubtarget<HexagonSubtarget>().getFrameLowering();
184 bool NeedCFI = MF.getMMI().hasDebugInfo() ||
185 MF.getFunction()->needsUnwindTableEntry();
186
187 if (!NeedCFI)
188 return false;
189 HFI.insertCFIInstructions(MF);
190 return true;
191}
192
193INITIALIZE_PASS(HexagonCallFrameInformation, "hexagon-cfi",
194 "Hexagon call frame information", false, false)
195
196FunctionPass *llvm::createHexagonCallFrameInformation() {
197 return new HexagonCallFrameInformation();
198}
199
200
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000201namespace {
202 /// Map a register pair Reg to the subregister that has the greater "number",
203 /// i.e. D3 (aka R7:6) will be mapped to R7, etc.
204 unsigned getMax32BitSubRegister(unsigned Reg, const TargetRegisterInfo &TRI,
205 bool hireg = true) {
206 if (Reg < Hexagon::D0 || Reg > Hexagon::D15)
207 return Reg;
208
209 unsigned RegNo = 0;
210 for (MCSubRegIterator SubRegs(Reg, &TRI); SubRegs.isValid(); ++SubRegs) {
211 if (hireg) {
212 if (*SubRegs > RegNo)
213 RegNo = *SubRegs;
214 } else {
215 if (!RegNo || *SubRegs < RegNo)
216 RegNo = *SubRegs;
217 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000218 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000219 return RegNo;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000220 }
221
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000222 /// Returns the callee saved register with the largest id in the vector.
223 unsigned getMaxCalleeSavedReg(const std::vector<CalleeSavedInfo> &CSI,
224 const TargetRegisterInfo &TRI) {
225 assert(Hexagon::R1 > 0 &&
226 "Assume physical registers are encoded as positive integers");
227 if (CSI.empty())
228 return 0;
229
230 unsigned Max = getMax32BitSubRegister(CSI[0].getReg(), TRI);
231 for (unsigned I = 1, E = CSI.size(); I < E; ++I) {
232 unsigned Reg = getMax32BitSubRegister(CSI[I].getReg(), TRI);
233 if (Reg > Max)
234 Max = Reg;
235 }
236 return Max;
237 }
238
239 /// Checks if the basic block contains any instruction that needs a stack
240 /// frame to be already in place.
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000241 bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR,
242 const HexagonRegisterInfo &HRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000243 for (auto &I : MBB) {
244 const MachineInstr *MI = &I;
245 if (MI->isCall())
246 return true;
247 unsigned Opc = MI->getOpcode();
248 switch (Opc) {
249 case Hexagon::ALLOCA:
250 case Hexagon::ALIGNA:
251 return true;
252 default:
253 break;
254 }
255 // Check individual operands.
Matthias Braune41e1462015-05-29 02:56:46 +0000256 for (const MachineOperand &MO : MI->operands()) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000257 // While the presence of a frame index does not prove that a stack
258 // frame will be required, all frame indexes should be within alloc-
259 // frame/deallocframe. Otherwise, the code that translates a frame
260 // index into an offset would have to be aware of the placement of
261 // the frame creation/destruction instructions.
Matthias Braune41e1462015-05-29 02:56:46 +0000262 if (MO.isFI())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000263 return true;
Matthias Braune41e1462015-05-29 02:56:46 +0000264 if (!MO.isReg())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000265 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000266 unsigned R = MO.getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000267 // Virtual registers will need scavenging, which then may require
268 // a stack slot.
269 if (TargetRegisterInfo::isVirtualRegister(R))
270 return true;
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000271 for (MCSubRegIterator S(R, &HRI, true); S.isValid(); ++S)
272 if (CSR[*S])
273 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000274 }
275 }
276 return false;
277 }
278
279 /// Returns true if MBB has a machine instructions that indicates a tail call
280 /// in the block.
281 bool hasTailCall(const MachineBasicBlock &MBB) {
282 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
283 unsigned RetOpc = I->getOpcode();
284 return RetOpc == Hexagon::TCRETURNi || RetOpc == Hexagon::TCRETURNr;
285 }
286
287 /// Returns true if MBB contains an instruction that returns.
288 bool hasReturn(const MachineBasicBlock &MBB) {
289 for (auto I = MBB.getFirstTerminator(), E = MBB.end(); I != E; ++I)
290 if (I->isReturn())
291 return true;
292 return false;
293 }
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +0000294
295 inline bool isOptNone(const MachineFunction &MF) {
296 return MF.getFunction()->hasFnAttribute(Attribute::OptimizeNone) ||
297 MF.getTarget().getOptLevel() == CodeGenOpt::None;
298 }
299
300 inline bool isOptSize(const MachineFunction &MF) {
301 const Function &F = *MF.getFunction();
302 return F.optForSize() && !F.optForMinSize();
303 }
304
305 inline bool isMinSize(const MachineFunction &MF) {
306 return MF.getFunction()->optForMinSize();
307 }
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000308}
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000309
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000310
311/// Implements shrink-wrapping of the stack frame. By default, stack frame
312/// is created in the function entry block, and is cleaned up in every block
313/// that returns. This function finds alternate blocks: one for the frame
314/// setup (prolog) and one for the cleanup (epilog).
315void HexagonFrameLowering::findShrunkPrologEpilog(MachineFunction &MF,
316 MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const {
317 static unsigned ShrinkCounter = 0;
318
319 if (ShrinkLimit.getPosition()) {
320 if (ShrinkCounter >= ShrinkLimit)
321 return;
322 ShrinkCounter++;
323 }
324
325 auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
326 auto &HRI = *HST.getRegisterInfo();
327
328 MachineDominatorTree MDT;
329 MDT.runOnMachineFunction(MF);
330 MachinePostDominatorTree MPT;
331 MPT.runOnMachineFunction(MF);
332
333 typedef DenseMap<unsigned,unsigned> UnsignedMap;
334 UnsignedMap RPO;
335 typedef ReversePostOrderTraversal<const MachineFunction*> RPOTType;
336 RPOTType RPOT(&MF);
337 unsigned RPON = 0;
338 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I)
339 RPO[(*I)->getNumber()] = RPON++;
340
341 // Don't process functions that have loops, at least for now. Placement
342 // of prolog and epilog must take loop structure into account. For simpli-
343 // city don't do it right now.
344 for (auto &I : MF) {
345 unsigned BN = RPO[I.getNumber()];
346 for (auto SI = I.succ_begin(), SE = I.succ_end(); SI != SE; ++SI) {
347 // If found a back-edge, return.
348 if (RPO[(*SI)->getNumber()] <= BN)
349 return;
350 }
351 }
352
353 // Collect the set of blocks that need a stack frame to execute. Scan
354 // each block for uses/defs of callee-saved registers, calls, etc.
355 SmallVector<MachineBasicBlock*,16> SFBlocks;
356 BitVector CSR(Hexagon::NUM_TARGET_REGS);
357 for (const MCPhysReg *P = HRI.getCalleeSavedRegs(&MF); *P; ++P)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000358 for (MCSubRegIterator S(*P, &HRI, true); S.isValid(); ++S)
359 CSR[*S] = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000360
361 for (auto &I : MF)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000362 if (needsStackFrame(I, CSR, HRI))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000363 SFBlocks.push_back(&I);
364
365 DEBUG({
366 dbgs() << "Blocks needing SF: {";
367 for (auto &B : SFBlocks)
368 dbgs() << " BB#" << B->getNumber();
369 dbgs() << " }\n";
370 });
371 // No frame needed?
372 if (SFBlocks.empty())
373 return;
374
375 // Pick a common dominator and a common post-dominator.
376 MachineBasicBlock *DomB = SFBlocks[0];
377 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
378 DomB = MDT.findNearestCommonDominator(DomB, SFBlocks[i]);
379 if (!DomB)
380 break;
381 }
382 MachineBasicBlock *PDomB = SFBlocks[0];
383 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
384 PDomB = MPT.findNearestCommonDominator(PDomB, SFBlocks[i]);
385 if (!PDomB)
386 break;
387 }
388 DEBUG({
389 dbgs() << "Computed dom block: BB#";
390 if (DomB) dbgs() << DomB->getNumber();
391 else dbgs() << "<null>";
392 dbgs() << ", computed pdom block: BB#";
393 if (PDomB) dbgs() << PDomB->getNumber();
394 else dbgs() << "<null>";
395 dbgs() << "\n";
396 });
397 if (!DomB || !PDomB)
398 return;
399
400 // Make sure that DomB dominates PDomB and PDomB post-dominates DomB.
401 if (!MDT.dominates(DomB, PDomB)) {
402 DEBUG(dbgs() << "Dom block does not dominate pdom block\n");
403 return;
404 }
405 if (!MPT.dominates(PDomB, DomB)) {
406 DEBUG(dbgs() << "PDom block does not post-dominate dom block\n");
407 return;
408 }
409
410 // Finally, everything seems right.
411 PrologB = DomB;
412 EpilogB = PDomB;
413}
414
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000415
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000416/// Perform most of the PEI work here:
417/// - saving/restoring of the callee-saved registers,
418/// - stack frame creation and destruction.
419/// Normally, this work is distributed among various functions, but doing it
420/// in one place allows shrink-wrapping of the stack frame.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000421void HexagonFrameLowering::emitPrologue(MachineFunction &MF,
422 MachineBasicBlock &MBB) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000423 auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
424 auto &HRI = *HST.getRegisterInfo();
425
426 MachineFrameInfo *MFI = MF.getFrameInfo();
427 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
428
429 MachineBasicBlock *PrologB = &MF.front(), *EpilogB = nullptr;
430 if (EnableShrinkWrapping)
431 findShrunkPrologEpilog(MF, PrologB, EpilogB);
432
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000433 bool PrologueStubs = false;
434 insertCSRSpillsInBlock(*PrologB, CSI, HRI, PrologueStubs);
435 insertPrologueInBlock(*PrologB, PrologueStubs);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000436
437 if (EpilogB) {
438 insertCSRRestoresInBlock(*EpilogB, CSI, HRI);
439 insertEpilogueInBlock(*EpilogB);
440 } else {
441 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000442 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000443 insertCSRRestoresInBlock(B, CSI, HRI);
444
445 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000446 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000447 insertEpilogueInBlock(B);
448 }
449}
450
451
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000452void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB,
453 bool PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000454 MachineFunction &MF = *MBB.getParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000455 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000456 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000457 auto &HII = *HST.getInstrInfo();
458 auto &HRI = *HST.getRegisterInfo();
459 DebugLoc dl;
460
461 unsigned MaxAlign = std::max(MFI->getMaxAlignment(), getStackAlignment());
462
463 // Calculate the total stack frame size.
464 // Get the number of bytes to allocate from the FrameInfo.
465 unsigned FrameSize = MFI->getStackSize();
466 // Round up the max call frame size to the max alignment on the stack.
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000467 unsigned MaxCFA = alignTo(MFI->getMaxCallFrameSize(), MaxAlign);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000468 MFI->setMaxCallFrameSize(MaxCFA);
469
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000470 FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000471 MFI->setStackSize(FrameSize);
472
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000473 bool AlignStack = (MaxAlign > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000474
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000475 // Get the number of bytes to allocate from the FrameInfo.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000476 unsigned NumBytes = MFI->getStackSize();
477 unsigned SP = HRI.getStackRegister();
478 unsigned MaxCF = MFI->getMaxCallFrameSize();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000479 MachineBasicBlock::iterator InsertPt = MBB.begin();
480
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000481 auto *FuncInfo = MF.getInfo<HexagonMachineFunctionInfo>();
482 auto &AdjustRegs = FuncInfo->getAllocaAdjustInsts();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000483
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000484 for (auto MI : AdjustRegs) {
485 assert((MI->getOpcode() == Hexagon::ALLOCA) && "Expected alloca");
486 expandAlloca(MI, HII, SP, MaxCF);
487 MI->eraseFromParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000488 }
489
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000490 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000491 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000492
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000493 // Check for overflow.
494 // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
495 const unsigned int ALLOCFRAME_MAX = 16384;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000496
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000497 // Create a dummy memory operand to avoid allocframe from being treated as
498 // a volatile memory reference.
499 MachineMemOperand *MMO =
500 MF.getMachineMemOperand(MachinePointerInfo(), MachineMemOperand::MOStore,
501 4, 4);
502
503 if (NumBytes >= ALLOCFRAME_MAX) {
504 // Emit allocframe(#0).
505 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
506 .addImm(0)
507 .addMemOperand(MMO);
508
509 // Subtract offset from frame pointer.
510 // We use a caller-saved non-parameter register for that.
511 unsigned CallerSavedReg = HRI.getFirstCallerSavedNonParamReg();
512 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CONST32_Int_Real),
513 CallerSavedReg).addImm(NumBytes);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000514 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_sub), SP)
515 .addReg(SP)
516 .addReg(CallerSavedReg);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000517 } else {
518 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
519 .addImm(NumBytes)
520 .addMemOperand(MMO);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000521 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000522
523 if (AlignStack) {
524 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
525 .addReg(SP)
526 .addImm(-int64_t(MaxAlign));
527 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000528
529 // If the stack-checking is enabled, and we spilled the callee-saved
530 // registers inline (i.e. did not use a spill function), then call
531 // the stack checker directly.
532 if (EnableStackOVFSanitizer && !PrologueStubs)
533 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CALLstk))
534 .addExternalSymbol("__runtime_stack_check");
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000535}
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000536
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000537void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
538 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000539 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000540 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000541
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000542 auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
543 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000544 auto &HRI = *HST.getRegisterInfo();
545 unsigned SP = HRI.getStackRegister();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000546
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000547 MachineInstr *RetI = nullptr;
548 for (auto &I : MBB) {
549 if (!I.isReturn())
550 continue;
551 RetI = &I;
552 break;
553 }
554 unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
555
556 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
557 DebugLoc DL;
558 if (InsertPt != MBB.end())
559 DL = InsertPt->getDebugLoc();
560 else if (!MBB.empty())
561 DL = std::prev(MBB.end())->getDebugLoc();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000562
563 // Handle EH_RETURN.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000564 if (RetOpc == Hexagon::EH_RETURN_JMPR) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000565 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
566 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::A2_add), SP)
567 .addReg(SP)
568 .addReg(Hexagon::R28);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000569 return;
570 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000571
572 // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
573 // frame instruction if we encounter it.
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000574 if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
575 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000576 MachineBasicBlock::iterator It = RetI;
577 ++It;
578 // Delete all instructions after the RESTORE (except labels).
579 while (It != MBB.end()) {
580 if (!It->isLabel())
581 It = MBB.erase(It);
582 else
583 ++It;
Jyotsna Verma300f0b92013-05-10 20:27:34 +0000584 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000585 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000586 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000587
588 // It is possible that the restoring code is a call to a library function.
589 // All of the restore* functions include "deallocframe", so we need to make
590 // sure that we don't add an extra one.
591 bool NeedsDeallocframe = true;
592 if (!MBB.empty() && InsertPt != MBB.begin()) {
593 MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
594 unsigned COpc = PrevIt->getOpcode();
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000595 if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
596 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000597 NeedsDeallocframe = false;
598 }
599
600 if (!NeedsDeallocframe)
601 return;
602 // If the returning instruction is JMPret, replace it with dealloc_return,
603 // otherwise just add deallocframe. The function could be returning via a
604 // tail call.
605 if (RetOpc != Hexagon::JMPret || DisableDeallocRet) {
606 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
607 return;
608 }
609 unsigned NewOpc = Hexagon::L4_return;
610 MachineInstr *NewI = BuildMI(MBB, RetI, DL, HII.get(NewOpc));
611 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000612 NewI->copyImplicitOps(MF, *RetI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000613 MBB.erase(RetI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000614}
615
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000616
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000617namespace {
618 bool IsAllocFrame(MachineBasicBlock::const_iterator It) {
619 if (!It->isBundle())
620 return It->getOpcode() == Hexagon::S2_allocframe;
621 auto End = It->getParent()->instr_end();
Duncan P. N. Exon Smithd84f6002016-02-22 21:30:15 +0000622 MachineBasicBlock::const_instr_iterator I = It.getInstrIterator();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000623 while (++I != End && I->isBundled())
624 if (I->getOpcode() == Hexagon::S2_allocframe)
625 return true;
626 return false;
627 }
628
629 MachineBasicBlock::iterator FindAllocFrame(MachineBasicBlock &B) {
630 for (auto &I : B)
631 if (IsAllocFrame(I))
632 return I;
633 return B.end();
634 }
635}
636
637
638void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
639 for (auto &B : MF) {
640 auto AF = FindAllocFrame(B);
641 if (AF == B.end())
642 continue;
643 insertCFIInstructionsAt(B, ++AF);
644 }
645}
646
647
648void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
649 MachineBasicBlock::iterator At) const {
650 MachineFunction &MF = *MBB.getParent();
651 MachineFrameInfo *MFI = MF.getFrameInfo();
652 MachineModuleInfo &MMI = MF.getMMI();
653 auto &HST = MF.getSubtarget<HexagonSubtarget>();
654 auto &HII = *HST.getInstrInfo();
655 auto &HRI = *HST.getRegisterInfo();
656
657 // If CFI instructions have debug information attached, something goes
658 // wrong with the final assembly generation: the prolog_end is placed
659 // in a wrong location.
660 DebugLoc DL;
661 const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
662
663 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
664
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000665 if (hasFP(MF)) {
666 unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
667 unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000668
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000669 // Define CFA via an offset from the value of FP.
670 //
671 // -8 -4 0 (SP)
672 // --+----+----+---------------------
673 // | FP | LR | increasing addresses -->
674 // --+----+----+---------------------
675 // | +-- Old SP (before allocframe)
676 // +-- New FP (after allocframe)
677 //
678 // MCCFIInstruction::createDefCfa subtracts the offset from the register.
679 // MCCFIInstruction::createOffset takes the offset without sign change.
680 auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
681 BuildMI(MBB, At, DL, CFID)
682 .addCFIIndex(MMI.addFrameInst(DefCfa));
683 // R31 (return addr) = CFA - 4
684 auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
685 BuildMI(MBB, At, DL, CFID)
686 .addCFIIndex(MMI.addFrameInst(OffR31));
687 // R30 (frame ptr) = CFA - 8
688 auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
689 BuildMI(MBB, At, DL, CFID)
690 .addCFIIndex(MMI.addFrameInst(OffR30));
691 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000692
693 static unsigned int RegsToMove[] = {
694 Hexagon::R1, Hexagon::R0, Hexagon::R3, Hexagon::R2,
695 Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
696 Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
697 Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
698 Hexagon::D0, Hexagon::D1, Hexagon::D8, Hexagon::D9,
699 Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
700 Hexagon::NoRegister
701 };
702
703 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
704
705 for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
706 unsigned Reg = RegsToMove[i];
707 auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
708 return C.getReg() == Reg;
709 };
710 auto F = std::find_if(CSI.begin(), CSI.end(), IfR);
711 if (F == CSI.end())
712 continue;
713
714 // Subtract 8 to make room for R30 and R31, which are added above.
715 unsigned FrameReg;
716 int64_t Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg) - 8;
717
718 if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
719 unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
720 auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
721 Offset);
722 BuildMI(MBB, At, DL, CFID)
723 .addCFIIndex(MMI.addFrameInst(OffReg));
724 } else {
725 // Split the double regs into subregs, and generate appropriate
726 // cfi_offsets.
727 // The only reason, we are split double regs is, llvm-mc does not
728 // understand paired registers for cfi_offset.
729 // Eg .cfi_offset r1:0, -64
730
731 unsigned HiReg = HRI.getSubReg(Reg, Hexagon::subreg_hireg);
732 unsigned LoReg = HRI.getSubReg(Reg, Hexagon::subreg_loreg);
733 unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
734 unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
735 auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
736 Offset+4);
737 BuildMI(MBB, At, DL, CFID)
738 .addCFIIndex(MMI.addFrameInst(OffHi));
739 auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
740 Offset);
741 BuildMI(MBB, At, DL, CFID)
742 .addCFIIndex(MMI.addFrameInst(OffLo));
743 }
744 }
745}
746
747
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000748bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000749 auto &MFI = *MF.getFrameInfo();
750 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
751
752 bool HasFixed = MFI.getNumFixedObjects();
753 bool HasPrealloc = const_cast<MachineFrameInfo&>(MFI)
754 .getLocalFrameObjectCount();
755 bool HasExtraAlign = HRI.needsStackRealignment(MF);
756 bool HasAlloca = MFI.hasVarSizedObjects();
757
758 // Insert ALLOCFRAME if we need to or at -O0 for the debugger. Think
759 // that this shouldn't be required, but doing so now because gcc does and
760 // gdb can't break at the start of the function without it. Will remove if
761 // this turns out to be a gdb bug.
762 //
763 if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
764 return true;
765
766 // By default we want to use SP (since it's always there). FP requires
767 // some setup (i.e. ALLOCFRAME).
768 // Fixed and preallocated objects need FP if the distance from them to
769 // the SP is unknown (as is with alloca or aligna).
770 if ((HasFixed || HasPrealloc) && (HasAlloca || HasExtraAlign))
771 return true;
772
773 if (MFI.getStackSize() > 0) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000774 if (EnableStackOVFSanitizer || UseAllocframe)
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000775 return true;
776 }
777
778 if (MFI.hasCalls() ||
779 MF.getInfo<HexagonMachineFunctionInfo>()->hasClobberLR())
780 return true;
781
782 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000783}
784
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000785
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000786enum SpillKind {
787 SK_ToMem,
788 SK_FromMem,
789 SK_FromMemTailcall
790};
791
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000792static const char *getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType,
793 bool Stkchk = false) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000794 const char * V4SpillToMemoryFunctions[] = {
795 "__save_r16_through_r17",
796 "__save_r16_through_r19",
797 "__save_r16_through_r21",
798 "__save_r16_through_r23",
799 "__save_r16_through_r25",
800 "__save_r16_through_r27" };
801
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000802 const char * V4SpillToMemoryStkchkFunctions[] = {
803 "__save_r16_through_r17_stkchk",
804 "__save_r16_through_r19_stkchk",
805 "__save_r16_through_r21_stkchk",
806 "__save_r16_through_r23_stkchk",
807 "__save_r16_through_r25_stkchk",
808 "__save_r16_through_r27_stkchk" };
809
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000810 const char * V4SpillFromMemoryFunctions[] = {
811 "__restore_r16_through_r17_and_deallocframe",
812 "__restore_r16_through_r19_and_deallocframe",
813 "__restore_r16_through_r21_and_deallocframe",
814 "__restore_r16_through_r23_and_deallocframe",
815 "__restore_r16_through_r25_and_deallocframe",
816 "__restore_r16_through_r27_and_deallocframe" };
817
818 const char * V4SpillFromMemoryTailcallFunctions[] = {
819 "__restore_r16_through_r17_and_deallocframe_before_tailcall",
820 "__restore_r16_through_r19_and_deallocframe_before_tailcall",
821 "__restore_r16_through_r21_and_deallocframe_before_tailcall",
822 "__restore_r16_through_r23_and_deallocframe_before_tailcall",
823 "__restore_r16_through_r25_and_deallocframe_before_tailcall",
824 "__restore_r16_through_r27_and_deallocframe_before_tailcall"
825 };
826
827 const char **SpillFunc = nullptr;
828
829 switch(SpillType) {
830 case SK_ToMem:
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000831 SpillFunc = Stkchk ? V4SpillToMemoryStkchkFunctions
832 : V4SpillToMemoryFunctions;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000833 break;
834 case SK_FromMem:
835 SpillFunc = V4SpillFromMemoryFunctions;
836 break;
837 case SK_FromMemTailcall:
838 SpillFunc = V4SpillFromMemoryTailcallFunctions;
839 break;
840 }
841 assert(SpillFunc && "Unknown spill kind");
842
843 // Spill all callee-saved registers up to the highest register used.
844 switch (MaxReg) {
845 case Hexagon::R17:
846 return SpillFunc[0];
847 case Hexagon::R19:
848 return SpillFunc[1];
849 case Hexagon::R21:
850 return SpillFunc[2];
851 case Hexagon::R23:
852 return SpillFunc[3];
853 case Hexagon::R25:
854 return SpillFunc[4];
855 case Hexagon::R27:
856 return SpillFunc[5];
857 default:
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000858 llvm_unreachable("Unhandled maximum callee save register");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000859 }
860 return 0;
861}
862
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000863
James Y Knight5567baf2015-08-15 02:32:35 +0000864int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF,
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000865 int FI, unsigned &FrameReg) const {
866 auto &MFI = *MF.getFrameInfo();
867 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000868
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000869 int Offset = MFI.getObjectOffset(FI);
870 bool HasAlloca = MFI.hasVarSizedObjects();
871 bool HasExtraAlign = HRI.needsStackRealignment(MF);
872 bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
James Y Knight5567baf2015-08-15 02:32:35 +0000873
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000874 unsigned SP = HRI.getStackRegister(), FP = HRI.getFrameRegister();
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +0000875 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
876 unsigned AP = HMFI.getStackAlignBasePhysReg();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000877 unsigned FrameSize = MFI.getStackSize();
878
879 bool UseFP = false, UseAP = false; // Default: use SP (except at -O0).
880 // Use FP at -O0, except when there are objects with extra alignment.
881 // That additional alignment requirement may cause a pad to be inserted,
882 // which will make it impossible to use FP to access objects located
883 // past the pad.
884 if (NoOpt && !HasExtraAlign)
885 UseFP = true;
886 if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
887 // Fixed and preallocated objects will be located before any padding
888 // so FP must be used to access them.
889 UseFP |= (HasAlloca || HasExtraAlign);
890 } else {
891 if (HasAlloca) {
892 if (HasExtraAlign)
893 UseAP = true;
894 else
895 UseFP = true;
896 }
897 }
898
899 // If FP was picked, then there had better be FP.
900 bool HasFP = hasFP(MF);
901 assert((HasFP || !UseFP) && "This function must have frame pointer");
902
903 // Having FP implies allocframe. Allocframe will store extra 8 bytes:
904 // FP/LR. If the base register is used to access an object across these
905 // 8 bytes, then the offset will need to be adjusted by 8.
906 //
907 // After allocframe:
908 // HexagonISelLowering adds 8 to ---+
909 // the offsets of all stack-based |
910 // arguments (*) |
911 // |
912 // getObjectOffset < 0 0 8 getObjectOffset >= 8
913 // ------------------------+-----+------------------------> increasing
914 // <local objects> |FP/LR| <input arguments> addresses
915 // -----------------+------+-----+------------------------>
916 // | |
917 // SP/AP point --+ +-- FP points here (**)
918 // somewhere on
919 // this side of FP/LR
920 //
921 // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
922 // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
923
924 // The lowering assumes that FP/LR is present, and so the offsets of
925 // the formal arguments start at 8. If FP/LR is not there we need to
926 // reduce the offset by 8.
927 if (Offset > 0 && !HasFP)
928 Offset -= 8;
929
930 if (UseFP)
931 FrameReg = FP;
932 else if (UseAP)
933 FrameReg = AP;
934 else
935 FrameReg = SP;
936
937 // Calculate the actual offset in the instruction. If there is no FP
938 // (in other words, no allocframe), then SP will not be adjusted (i.e.
939 // there will be no SP -= FrameSize), so the frame size should not be
940 // added to the calculated offset.
941 int RealOffset = Offset;
942 if (!UseFP && !UseAP && HasFP)
943 RealOffset = FrameSize+Offset;
944 return RealOffset;
Jakob Stoklund Olesen0b97dbc2012-05-30 22:40:03 +0000945}
946
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000947
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000948bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000949 const CSIVect &CSI, const HexagonRegisterInfo &HRI,
950 bool &PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000951 if (CSI.empty())
952 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000953
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000954 MachineBasicBlock::iterator MI = MBB.begin();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000955 PrologueStubs = false;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000956 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000957 auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000958
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000959 if (useSpillFunction(MF, CSI)) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000960 PrologueStubs = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000961 unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000962 bool StkOvrFlowEnabled = EnableStackOVFSanitizer;
963 const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem,
964 StkOvrFlowEnabled);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000965 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
966 bool IsPIC = HTM.getRelocationModel() == Reloc::PIC_;
967
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000968 // Call spill function.
969 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000970 unsigned SpillOpc;
971 if (StkOvrFlowEnabled)
972 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC
973 : Hexagon::SAVE_REGISTERS_CALL_V4STK;
974 else
975 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
976 : Hexagon::SAVE_REGISTERS_CALL_V4;
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000977
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000978 MachineInstr *SaveRegsCall =
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000979 BuildMI(MBB, MI, DL, HII.get(SpillOpc))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000980 .addExternalSymbol(SpillFun);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000981 // Add callee-saved registers as use.
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +0000982 addCalleeSaveRegistersAsImpOperand(SaveRegsCall, CSI, false, true);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000983 // Add live in registers.
984 for (unsigned I = 0; I < CSI.size(); ++I)
985 MBB.addLiveIn(CSI[I].getReg());
986 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000987 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000988
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000989 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000990 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000991 // Add live in registers. We treat eh_return callee saved register r0 - r3
992 // specially. They are not really callee saved registers as they are not
993 // supposed to be killed.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000994 bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
995 int FI = CSI[i].getFrameIdx();
996 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000997 HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000998 if (IsKill)
999 MBB.addLiveIn(Reg);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001000 }
1001 return true;
1002}
1003
1004
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001005bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
1006 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
1007 if (CSI.empty())
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001008 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001009
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001010 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1011 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001012 auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001013
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001014 if (useRestoreFunction(MF, CSI)) {
1015 bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
1016 unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
1017 SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
1018 const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001019 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
1020 bool IsPIC = HTM.getRelocationModel() == Reloc::PIC_;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001021
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001022 // Call spill function.
1023 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
1024 : MBB.getLastNonDebugInstr()->getDebugLoc();
1025 MachineInstr *DeallocCall = nullptr;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001026
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001027 if (HasTC) {
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001028 unsigned ROpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
1029 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001030 DeallocCall = BuildMI(MBB, MI, DL, HII.get(ROpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001031 .addExternalSymbol(RestoreFn);
1032 } else {
1033 // The block has a return.
1034 MachineBasicBlock::iterator It = MBB.getFirstTerminator();
1035 assert(It->isReturn() && std::next(It) == MBB.end());
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001036 unsigned ROpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
1037 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001038 DeallocCall = BuildMI(MBB, It, DL, HII.get(ROpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001039 .addExternalSymbol(RestoreFn);
1040 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +00001041 DeallocCall->copyImplicitOps(MF, *It);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001042 }
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001043 addCalleeSaveRegistersAsImpOperand(DeallocCall, CSI, true, false);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001044 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001045 }
1046
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001047 for (unsigned i = 0; i < CSI.size(); ++i) {
1048 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001049 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1050 int FI = CSI[i].getFrameIdx();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001051 HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001052 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001053
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001054 return true;
1055}
1056
Hans Wennborge1a2e902016-03-31 18:33:38 +00001057MachineBasicBlock::iterator HexagonFrameLowering::eliminateCallFramePseudoInstr(
1058 MachineFunction &MF, MachineBasicBlock &MBB,
1059 MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00001060 MachineInstr &MI = *I;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001061 unsigned Opc = MI.getOpcode();
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001062 (void)Opc; // Silence compiler warning.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001063 assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1064 "Cannot handle this call frame pseudo instruction");
Hans Wennborge1a2e902016-03-31 18:33:38 +00001065 return MBB.erase(I);
Eli Bendersky8da87162013-02-21 20:05:00 +00001066}
1067
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001068
1069void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1070 MachineFunction &MF, RegScavenger *RS) const {
1071 // If this function has uses aligned stack and also has variable sized stack
1072 // objects, then we need to map all spill slots to fixed positions, so that
1073 // they can be accessed through FP. Otherwise they would have to be accessed
1074 // via AP, which may not be available at the particular place in the program.
1075 MachineFrameInfo *MFI = MF.getFrameInfo();
1076 bool HasAlloca = MFI->hasVarSizedObjects();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001077 bool NeedsAlign = (MFI->getMaxAlignment() > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001078
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001079 if (!HasAlloca || !NeedsAlign)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001080 return;
1081
1082 unsigned LFS = MFI->getLocalFrameSize();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001083 for (int i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
1084 if (!MFI->isSpillSlotObjectIndex(i) || MFI->isDeadObjectIndex(i))
1085 continue;
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001086 unsigned S = MFI->getObjectSize(i);
1087 // Reduce the alignment to at most 8. This will require unaligned vector
1088 // stores if they happen here.
1089 unsigned A = std::max(MFI->getObjectAlignment(i), 8U);
1090 MFI->setObjectAlignment(i, 8);
1091 LFS = alignTo(LFS+S, A);
1092 MFI->mapLocalFrameObject(i, -LFS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001093 }
1094
1095 MFI->setLocalFrameSize(LFS);
1096 unsigned A = MFI->getLocalFrameMaxAlign();
1097 assert(A <= 8 && "Unexpected local frame alignment");
1098 if (A == 0)
1099 MFI->setLocalFrameMaxAlign(8);
1100 MFI->setUseLocalStackAllocationBlock(true);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001101
1102 // Set the physical aligned-stack base address register.
1103 unsigned AP = 0;
1104 if (const MachineInstr *AI = getAlignaInstr(MF))
1105 AP = AI->getOperand(0).getReg();
1106 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1107 HMFI.setStackAlignBasePhysReg(AP);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001108}
1109
1110/// Returns true if there is no caller saved registers available.
1111static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
1112 const HexagonRegisterInfo &HRI) {
1113 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001114 BitVector Reserved = HRI.getReservedRegs(MF);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001115
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001116 auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1117 for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1118 if (MRI.isPhysRegUsed(*AI))
1119 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001120 return false;
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001121 };
1122
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001123 // Check for an unused caller-saved register. Callee-saved registers
1124 // have become pristine by now.
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001125 for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF); *P; ++P)
1126 if (!IsUsed(*P))
1127 return false;
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001128
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001129 // All caller-saved registers are used.
1130 return true;
1131}
1132
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001133
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001134#ifndef NDEBUG
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001135static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001136 dbgs() << '{';
1137 for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1138 unsigned R = x;
1139 dbgs() << ' ' << PrintReg(R, &TRI);
1140 }
1141 dbgs() << " }";
1142}
1143#endif
1144
1145
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001146bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1147 const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
Krzysztof Parzyszek27ba19a12015-04-23 20:42:20 +00001148 DEBUG(dbgs() << LLVM_FUNCTION_NAME << " on "
Krzysztof Parzyszeked75e7a2015-04-23 20:57:39 +00001149 << MF.getFunction()->getName() << '\n');
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001150 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001151 BitVector SRegs(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001152
1153 // Generate a set of unique, callee-saved registers (SRegs), where each
1154 // register in the set is maximal in terms of sub-/super-register relation,
1155 // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1156
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001157 // (1) For each callee-saved register, add that register and all of its
1158 // sub-registers to SRegs.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001159 DEBUG(dbgs() << "Initial CS registers: {");
1160 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1161 unsigned R = CSI[i].getReg();
1162 DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1163 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1164 SRegs[*SR] = true;
1165 }
1166 DEBUG(dbgs() << " }\n");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001167 DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001168
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001169 // (2) For each reserved register, remove that register and all of its
1170 // sub- and super-registers from SRegs.
1171 BitVector Reserved = TRI->getReservedRegs(MF);
1172 for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1173 unsigned R = x;
1174 for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1175 SRegs[*SR] = false;
1176 }
1177 DEBUG(dbgs() << "Res: "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1178 DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1179
1180 // (3) Collect all registers that have at least one sub-register in SRegs,
1181 // and also have no sub-registers that are reserved. These will be the can-
1182 // didates for saving as a whole instead of their individual sub-registers.
1183 // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1184 BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001185 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1186 unsigned R = x;
1187 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1188 TmpSup[*SR] = true;
1189 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001190 for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1191 unsigned R = x;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001192 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1193 if (!Reserved[*SR])
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001194 continue;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001195 TmpSup[R] = false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001196 break;
1197 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001198 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001199 DEBUG(dbgs() << "TmpSup: "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001200
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001201 // (4) Include all super-registers found in (3) into SRegs.
1202 SRegs |= TmpSup;
1203 DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001204
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001205 // (5) For each register R in SRegs, if any super-register of R is in SRegs,
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001206 // remove R from SRegs.
1207 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1208 unsigned R = x;
1209 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1210 if (!SRegs[*SR])
1211 continue;
1212 SRegs[R] = false;
1213 break;
1214 }
1215 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001216 DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001217
1218 // Now, for each register that has a fixed stack slot, create the stack
1219 // object for it.
1220 CSI.clear();
1221
1222 typedef TargetFrameLowering::SpillSlot SpillSlot;
1223 unsigned NumFixed;
1224 int MinOffset = 0; // CS offsets are negative.
1225 const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1226 for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1227 if (!SRegs[S->Reg])
1228 continue;
1229 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
1230 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), S->Offset);
1231 MinOffset = std::min(MinOffset, S->Offset);
1232 CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1233 SRegs[S->Reg] = false;
1234 }
1235
1236 // There can be some registers that don't have fixed slots. For example,
1237 // we need to store R0-R3 in functions with exception handling. For each
1238 // such register, create a non-fixed stack object.
1239 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1240 unsigned R = x;
1241 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
1242 int Off = MinOffset - RC->getSize();
1243 unsigned Align = std::min(RC->getAlignment(), getStackAlignment());
1244 assert(isPowerOf2_32(Align));
1245 Off &= -Align;
1246 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), Off);
1247 MinOffset = std::min(MinOffset, Off);
1248 CSI.push_back(CalleeSavedInfo(R, FI));
1249 SRegs[R] = false;
1250 }
1251
1252 DEBUG({
1253 dbgs() << "CS information: {";
1254 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1255 int FI = CSI[i].getFrameIdx();
1256 int Off = MFI->getObjectOffset(FI);
1257 dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1258 if (Off >= 0)
1259 dbgs() << '+';
1260 dbgs() << Off;
1261 }
1262 dbgs() << " }\n";
1263 });
1264
1265#ifndef NDEBUG
1266 // Verify that all registers were handled.
1267 bool MissedReg = false;
1268 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1269 unsigned R = x;
1270 dbgs() << PrintReg(R, TRI) << ' ';
1271 MissedReg = true;
1272 }
1273 if (MissedReg)
1274 llvm_unreachable("...there are unhandled callee-saved registers!");
1275#endif
1276
1277 return true;
1278}
1279
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001280
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001281bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1282 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1283 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1284 MachineInstr *MI = &*It;
1285 DebugLoc DL = MI->getDebugLoc();
1286 unsigned DstR = MI->getOperand(0).getReg();
1287 unsigned SrcR = MI->getOperand(1).getReg();
1288 if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1289 !Hexagon::ModRegsRegClass.contains(SrcR))
1290 return false;
1291
1292 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1293 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR)
1294 .addOperand(MI->getOperand(1));
1295 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1296 .addReg(TmpR, RegState::Kill);
1297
1298 NewRegs.push_back(TmpR);
1299 B.erase(It);
1300 return true;
1301}
1302
1303bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1304 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1305 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1306 MachineInstr *MI = &*It;
1307 DebugLoc DL = MI->getDebugLoc();
1308 unsigned Opc = MI->getOpcode();
1309 unsigned SrcR = MI->getOperand(2).getReg();
1310 bool IsKill = MI->getOperand(2).isKill();
1311
1312 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1313 int FI = MI->getOperand(0).getIndex();
1314
1315 // TmpR = C2_tfrpr SrcR if SrcR is a predicate register
1316 // TmpR = A2_tfrcrr SrcR if SrcR is a modifier register
1317 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1318 unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1319 : Hexagon::A2_tfrcrr;
1320 BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1321 .addReg(SrcR, getKillRegState(IsKill));
1322
1323 // S2_storeri_io FI, 0, TmpR
1324 BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1325 .addFrameIndex(FI)
1326 .addImm(0)
1327 .addReg(TmpR, RegState::Kill)
1328 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1329
1330 NewRegs.push_back(TmpR);
1331 B.erase(It);
1332 return true;
1333}
1334
1335bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1336 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1337 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1338 MachineInstr *MI = &*It;
1339 DebugLoc DL = MI->getDebugLoc();
1340 unsigned Opc = MI->getOpcode();
1341 unsigned DstR = MI->getOperand(0).getReg();
1342
1343 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1344 int FI = MI->getOperand(1).getIndex();
1345
1346 // TmpR = L2_loadri_io FI, 0
1347 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1348 BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1349 .addFrameIndex(FI)
1350 .addImm(0)
1351 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1352
1353 // DstR = C2_tfrrp TmpR if DstR is a predicate register
1354 // DstR = A2_tfrrcr TmpR if DstR is a modifier register
1355 unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1356 : Hexagon::A2_tfrrcr;
1357 BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1358 .addReg(TmpR, RegState::Kill);
1359
1360 NewRegs.push_back(TmpR);
1361 B.erase(It);
1362 return true;
1363}
1364
1365
1366bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1367 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1368 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1369 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1370 MachineInstr *MI = &*It;
1371 DebugLoc DL = MI->getDebugLoc();
1372 unsigned SrcR = MI->getOperand(2).getReg();
1373 bool IsKill = MI->getOperand(2).isKill();
1374
1375 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1376 int FI = MI->getOperand(0).getIndex();
1377
1378 bool Is128B = HST.useHVXDblOps();
1379 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1380 : &Hexagon::VectorRegs128BRegClass;
1381
1382 // Insert transfer to general vector register.
1383 // TmpR0 = A2_tfrsi 0x01010101
1384 // TmpR1 = V6_vandqrt Qx, TmpR0
1385 // store FI, 0, TmpR1
1386 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1387 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1388
1389 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1390 .addImm(0x01010101);
1391
1392 unsigned VandOpc = !Is128B ? Hexagon::V6_vandqrt : Hexagon::V6_vandqrt_128B;
1393 BuildMI(B, It, DL, HII.get(VandOpc), TmpR1)
1394 .addReg(SrcR, getKillRegState(IsKill))
1395 .addReg(TmpR0, RegState::Kill);
1396
1397 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1398 HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1399 expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1400
1401 NewRegs.push_back(TmpR0);
1402 NewRegs.push_back(TmpR1);
1403 B.erase(It);
1404 return true;
1405}
1406
1407bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1408 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1409 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1410 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1411 MachineInstr *MI = &*It;
1412 DebugLoc DL = MI->getDebugLoc();
1413 unsigned DstR = MI->getOperand(0).getReg();
1414
1415 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1416 int FI = MI->getOperand(1).getIndex();
1417
1418 bool Is128B = HST.useHVXDblOps();
1419 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1420 : &Hexagon::VectorRegs128BRegClass;
1421
1422 // TmpR0 = A2_tfrsi 0x01010101
1423 // TmpR1 = load FI, 0
1424 // DstR = V6_vandvrt TmpR1, TmpR0
1425 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1426 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1427
1428 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1429 .addImm(0x01010101);
1430 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1431 HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1432 expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1433
1434 unsigned VandOpc = !Is128B ? Hexagon::V6_vandvrt : Hexagon::V6_vandvrt_128B;
1435 BuildMI(B, It, DL, HII.get(VandOpc), DstR)
1436 .addReg(TmpR1, RegState::Kill)
1437 .addReg(TmpR0, RegState::Kill);
1438
1439 NewRegs.push_back(TmpR0);
1440 NewRegs.push_back(TmpR1);
1441 B.erase(It);
1442 return true;
1443}
1444
1445bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1446 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1447 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1448 MachineFunction &MF = *B.getParent();
1449 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1450 auto &MFI = *MF.getFrameInfo();
1451 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1452 MachineInstr *MI = &*It;
1453 DebugLoc DL = MI->getDebugLoc();
1454
1455 unsigned SrcR = MI->getOperand(2).getReg();
1456 unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::subreg_loreg);
1457 unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::subreg_hireg);
1458 bool IsKill = MI->getOperand(2).isKill();
1459
1460 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1461 int FI = MI->getOperand(0).getIndex();
1462
1463 bool Is128B = HST.useHVXDblOps();
1464 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1465 : &Hexagon::VectorRegs128BRegClass;
1466 unsigned Size = RC->getSize();
1467 unsigned NeedAlign = RC->getAlignment();
1468 unsigned HasAlign = MFI.getObjectAlignment(FI);
1469 unsigned StoreOpc;
1470
1471 // Store low part.
1472 if (NeedAlign <= HasAlign)
1473 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1474 else
1475 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1476
1477 BuildMI(B, It, DL, HII.get(StoreOpc))
1478 .addFrameIndex(FI)
1479 .addImm(0)
1480 .addReg(SrcLo, getKillRegState(IsKill))
1481 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1482
1483 // Load high part.
1484 if (NeedAlign <= MinAlign(HasAlign, Size))
1485 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1486 else
1487 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1488
1489 BuildMI(B, It, DL, HII.get(StoreOpc))
1490 .addFrameIndex(FI)
1491 .addImm(Size)
1492 .addReg(SrcHi, getKillRegState(IsKill))
1493 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1494
1495 B.erase(It);
1496 return true;
1497}
1498
1499bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1500 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1501 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1502 MachineFunction &MF = *B.getParent();
1503 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1504 auto &MFI = *MF.getFrameInfo();
1505 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1506 MachineInstr *MI = &*It;
1507 DebugLoc DL = MI->getDebugLoc();
1508
1509 unsigned DstR = MI->getOperand(0).getReg();
1510 unsigned DstHi = HRI.getSubReg(DstR, Hexagon::subreg_hireg);
1511 unsigned DstLo = HRI.getSubReg(DstR, Hexagon::subreg_loreg);
1512
1513 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1514 int FI = MI->getOperand(1).getIndex();
1515
1516 bool Is128B = HST.useHVXDblOps();
1517 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1518 : &Hexagon::VectorRegs128BRegClass;
1519 unsigned Size = RC->getSize();
1520 unsigned NeedAlign = RC->getAlignment();
1521 unsigned HasAlign = MFI.getObjectAlignment(FI);
1522 unsigned LoadOpc;
1523
1524 // Load low part.
1525 if (NeedAlign <= HasAlign)
1526 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1527 else
1528 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1529
1530 BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1531 .addFrameIndex(FI)
1532 .addImm(0)
1533 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1534
1535 // Load high part.
1536 if (NeedAlign <= MinAlign(HasAlign, Size))
1537 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1538 else
1539 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1540
1541 BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1542 .addFrameIndex(FI)
1543 .addImm(Size)
1544 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1545
1546 B.erase(It);
1547 return true;
1548}
1549
1550bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1551 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1552 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1553 MachineFunction &MF = *B.getParent();
1554 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1555 auto &MFI = *MF.getFrameInfo();
1556 MachineInstr *MI = &*It;
1557 DebugLoc DL = MI->getDebugLoc();
1558
1559 unsigned SrcR = MI->getOperand(2).getReg();
1560 bool IsKill = MI->getOperand(2).isKill();
1561
1562 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1563 int FI = MI->getOperand(0).getIndex();
1564
1565 bool Is128B = HST.useHVXDblOps();
1566 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1567 : &Hexagon::VectorRegs128BRegClass;
1568
1569 unsigned NeedAlign = RC->getAlignment();
1570 unsigned HasAlign = MFI.getObjectAlignment(FI);
1571 unsigned StoreOpc;
1572
1573 if (NeedAlign <= HasAlign)
1574 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1575 else
1576 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1577
1578 BuildMI(B, It, DL, HII.get(StoreOpc))
1579 .addFrameIndex(FI)
1580 .addImm(0)
1581 .addReg(SrcR, getKillRegState(IsKill))
1582 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1583
1584 B.erase(It);
1585 return true;
1586}
1587
1588bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
1589 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1590 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1591 MachineFunction &MF = *B.getParent();
1592 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1593 auto &MFI = *MF.getFrameInfo();
1594 MachineInstr *MI = &*It;
1595 DebugLoc DL = MI->getDebugLoc();
1596
1597 unsigned DstR = MI->getOperand(0).getReg();
1598
1599 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1600 int FI = MI->getOperand(1).getIndex();
1601
1602 bool Is128B = HST.useHVXDblOps();
1603 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1604 : &Hexagon::VectorRegs128BRegClass;
1605
1606 unsigned NeedAlign = RC->getAlignment();
1607 unsigned HasAlign = MFI.getObjectAlignment(FI);
1608 unsigned LoadOpc;
1609
1610 if (NeedAlign <= HasAlign)
1611 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1612 else
1613 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1614
1615 BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1616 .addFrameIndex(FI)
1617 .addImm(0)
1618 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1619
1620 B.erase(It);
1621 return true;
1622}
1623
1624
1625bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1626 SmallVectorImpl<unsigned> &NewRegs) const {
1627 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001628 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001629 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001630 bool Changed = false;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001631
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001632 for (auto &B : MF) {
1633 // Traverse the basic block.
1634 MachineBasicBlock::iterator NextI;
1635 for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1636 MachineInstr *MI = &*I;
1637 NextI = std::next(I);
1638 unsigned Opc = MI->getOpcode();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001639
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001640 switch (Opc) {
1641 case TargetOpcode::COPY:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001642 Changed |= expandCopy(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001643 break;
1644 case Hexagon::STriw_pred:
1645 case Hexagon::STriw_mod:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001646 Changed |= expandStoreInt(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001647 break;
1648 case Hexagon::LDriw_pred:
1649 case Hexagon::LDriw_mod:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001650 Changed |= expandLoadInt(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001651 break;
1652 case Hexagon::STriq_pred_V6:
1653 case Hexagon::STriq_pred_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001654 Changed |= expandStoreVecPred(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001655 break;
1656 case Hexagon::LDriq_pred_V6:
1657 case Hexagon::LDriq_pred_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001658 Changed |= expandLoadVecPred(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001659 break;
1660 case Hexagon::LDrivv_pseudo_V6:
1661 case Hexagon::LDrivv_pseudo_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001662 Changed |= expandLoadVec2(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001663 break;
1664 case Hexagon::STrivv_pseudo_V6:
1665 case Hexagon::STrivv_pseudo_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001666 Changed |= expandStoreVec2(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001667 break;
1668 case Hexagon::STriv_pseudo_V6:
1669 case Hexagon::STriv_pseudo_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001670 Changed |= expandStoreVec(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001671 break;
1672 case Hexagon::LDriv_pseudo_V6:
1673 case Hexagon::LDriv_pseudo_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001674 Changed |= expandLoadVec(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001675 break;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001676 }
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001677 }
1678 }
1679
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001680 return Changed;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001681}
1682
1683
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001684void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1685 BitVector &SavedRegs,
1686 RegScavenger *RS) const {
1687 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1688 auto &HRI = *HST.getRegisterInfo();
1689
1690 SavedRegs.resize(HRI.getNumRegs());
1691
1692 // If we have a function containing __builtin_eh_return we want to spill and
1693 // restore all callee saved registers. Pretend that they are used.
1694 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1695 for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1696 SavedRegs.set(*R);
1697
1698 // Replace predicate register pseudo spill code.
1699 SmallVector<unsigned,8> NewRegs;
1700 expandSpillMacros(MF, NewRegs);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001701 if (OptimizeSpillSlots && !isOptNone(MF))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001702 optimizeSpillSlots(MF, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001703
1704 // We need to reserve a a spill slot if scavenging could potentially require
1705 // spilling a scavenged register.
1706 if (!NewRegs.empty() && needToReserveScavengingSpillSlots(MF, HRI)) {
1707 MachineRegisterInfo &MRI = MF.getRegInfo();
1708 SetVector<const TargetRegisterClass*> SpillRCs;
1709 for (unsigned VR : NewRegs)
1710 SpillRCs.insert(MRI.getRegClass(VR));
1711
1712 MachineFrameInfo &MFI = *MF.getFrameInfo();
1713 const TargetRegisterClass &IntRC = Hexagon::IntRegsRegClass;
1714 if (SpillRCs.count(&IntRC)) {
1715 for (int i = 0; i < NumberScavengerSlots; i++) {
1716 int NewFI = MFI.CreateSpillStackObject(IntRC.getSize(),
1717 IntRC.getAlignment());
1718 RS->addScavengingFrameIndex(NewFI);
1719 }
1720 }
1721 for (auto *RC : SpillRCs) {
1722 if (RC == &IntRC)
1723 continue;
1724 int NewFI = MFI.CreateSpillStackObject(RC->getSize(), RC->getAlignment());
1725 RS->addScavengingFrameIndex(NewFI);
1726 }
1727 }
1728
1729 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1730}
1731
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001732
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001733unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1734 HexagonBlockRanges::IndexRange &FIR,
1735 HexagonBlockRanges::InstrIndexMap &IndexMap,
1736 HexagonBlockRanges::RegToRangeMap &DeadMap,
1737 const TargetRegisterClass *RC) const {
1738 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1739 auto &MRI = MF.getRegInfo();
1740
1741 auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1742 auto F = DeadMap.find({Reg,0});
1743 if (F == DeadMap.end())
1744 return false;
1745 for (auto &DR : F->second)
1746 if (DR.contains(FIR))
1747 return true;
1748 return false;
1749 };
1750
1751 for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
1752 bool Dead = true;
1753 for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
1754 if (isDead(R.Reg))
1755 continue;
1756 Dead = false;
1757 break;
1758 }
1759 if (Dead)
1760 return Reg;
1761 }
1762 return 0;
1763}
1764
1765void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
1766 SmallVectorImpl<unsigned> &VRegs) const {
1767 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1768 auto &HII = *HST.getInstrInfo();
1769 auto &HRI = *HST.getRegisterInfo();
1770 auto &MRI = MF.getRegInfo();
1771 HexagonBlockRanges HBR(MF);
1772
1773 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::InstrIndexMap>
1774 BlockIndexMap;
1775 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::RangeList>
1776 BlockRangeMap;
1777 typedef HexagonBlockRanges::IndexType IndexType;
1778
1779 struct SlotInfo {
1780 BlockRangeMap Map;
NAKAMURA Takumic2cc8702016-02-13 07:29:49 +00001781 unsigned Size;
1782 const TargetRegisterClass *RC;
1783
1784 SlotInfo() : Map(), Size(0), RC(nullptr) {}
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001785 };
1786
1787 BlockIndexMap BlockIndexes;
1788 SmallSet<int,4> BadFIs;
1789 std::map<int,SlotInfo> FIRangeMap;
1790
1791 auto getRegClass = [&MRI,&HRI] (HexagonBlockRanges::RegisterRef R)
1792 -> const TargetRegisterClass* {
1793 if (TargetRegisterInfo::isPhysicalRegister(R.Reg))
1794 assert(R.Sub == 0);
1795 if (TargetRegisterInfo::isVirtualRegister(R.Reg)) {
1796 auto *RCR = MRI.getRegClass(R.Reg);
1797 if (R.Sub == 0)
1798 return RCR;
1799 unsigned PR = *RCR->begin();
1800 R.Reg = HRI.getSubReg(PR, R.Sub);
1801 }
1802 return HRI.getMinimalPhysRegClass(R.Reg);
1803 };
1804 // Accumulate register classes: get a common class for a pre-existing
1805 // class HaveRC and a new class NewRC. Return nullptr if a common class
1806 // cannot be found, otherwise return the resulting class. If HaveRC is
1807 // nullptr, assume that it is still unset.
1808 auto getCommonRC = [&HRI] (const TargetRegisterClass *HaveRC,
1809 const TargetRegisterClass *NewRC)
1810 -> const TargetRegisterClass* {
1811 if (HaveRC == nullptr || HaveRC == NewRC)
1812 return NewRC;
1813 // Different classes, both non-null. Pick the more general one.
1814 if (HaveRC->hasSubClassEq(NewRC))
1815 return HaveRC;
1816 if (NewRC->hasSubClassEq(HaveRC))
1817 return NewRC;
1818 return nullptr;
1819 };
1820
1821 // Scan all blocks in the function. Check all occurrences of frame indexes,
1822 // and collect relevant information.
1823 for (auto &B : MF) {
1824 std::map<int,IndexType> LastStore, LastLoad;
Krzysztof Parzyszek280a50e2016-02-13 14:06:01 +00001825 // Emplace appears not to be supported in gcc 4.7.2-4.
1826 //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
Krzysztof Parzyszekde697d42016-02-17 15:02:07 +00001827 auto P = BlockIndexes.insert(
1828 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001829 auto &IndexMap = P.first->second;
1830 DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n"
1831 << IndexMap << '\n');
1832
1833 for (auto &In : B) {
1834 int LFI, SFI;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001835 bool Load = HII.isLoadFromStackSlot(&In, LFI) && !HII.isPredicated(In);
1836 bool Store = HII.isStoreToStackSlot(&In, SFI) && !HII.isPredicated(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001837 if (Load && Store) {
1838 // If it's both a load and a store, then we won't handle it.
1839 BadFIs.insert(LFI);
1840 BadFIs.insert(SFI);
1841 continue;
1842 }
1843 // Check for register classes of the register used as the source for
1844 // the store, and the register used as the destination for the load.
1845 // Also, only accept base+imm_offset addressing modes. Other addressing
1846 // modes can have side-effects (post-increments, etc.). For stack
1847 // slots they are very unlikely, so there is not much loss due to
1848 // this restriction.
1849 if (Load || Store) {
1850 int TFI = Load ? LFI : SFI;
1851 unsigned AM = HII.getAddrMode(&In);
1852 SlotInfo &SI = FIRangeMap[TFI];
1853 bool Bad = (AM != HexagonII::BaseImmOffset);
1854 if (!Bad) {
1855 // If the addressing mode is ok, check the register class.
1856 const TargetRegisterClass *RC = nullptr;
1857 if (Load) {
1858 MachineOperand &DataOp = In.getOperand(0);
1859 RC = getRegClass({DataOp.getReg(), DataOp.getSubReg()});
1860 } else {
1861 MachineOperand &DataOp = In.getOperand(2);
1862 RC = getRegClass({DataOp.getReg(), DataOp.getSubReg()});
1863 }
1864 RC = getCommonRC(SI.RC, RC);
1865 if (RC == nullptr)
1866 Bad = true;
1867 else
1868 SI.RC = RC;
1869 }
1870 if (!Bad) {
1871 // Check sizes.
1872 unsigned S = (1U << (HII.getMemAccessSize(&In) - 1));
1873 if (SI.Size != 0 && SI.Size != S)
1874 Bad = true;
1875 else
1876 SI.Size = S;
1877 }
1878 if (Bad)
1879 BadFIs.insert(TFI);
1880 }
1881
1882 // Locate uses of frame indices.
1883 for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
1884 const MachineOperand &Op = In.getOperand(i);
1885 if (!Op.isFI())
1886 continue;
1887 int FI = Op.getIndex();
1888 // Make sure that the following operand is an immediate and that
1889 // it is 0. This is the offset in the stack object.
1890 if (i+1 >= n || !In.getOperand(i+1).isImm() ||
1891 In.getOperand(i+1).getImm() != 0)
1892 BadFIs.insert(FI);
1893 if (BadFIs.count(FI))
1894 continue;
1895
1896 IndexType Index = IndexMap.getIndex(&In);
1897 if (Load) {
1898 if (LastStore[FI] == IndexType::None)
1899 LastStore[FI] = IndexType::Entry;
1900 LastLoad[FI] = Index;
1901 } else if (Store) {
1902 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
1903 if (LastStore[FI] != IndexType::None)
1904 RL.add(LastStore[FI], LastLoad[FI], false, false);
1905 else if (LastLoad[FI] != IndexType::None)
1906 RL.add(IndexType::Entry, LastLoad[FI], false, false);
1907 LastLoad[FI] = IndexType::None;
1908 LastStore[FI] = Index;
1909 } else {
1910 BadFIs.insert(FI);
1911 }
1912 }
1913 }
1914
1915 for (auto &I : LastLoad) {
1916 IndexType LL = I.second;
1917 if (LL == IndexType::None)
1918 continue;
1919 auto &RL = FIRangeMap[I.first].Map[&B];
1920 IndexType &LS = LastStore[I.first];
1921 if (LS != IndexType::None)
1922 RL.add(LS, LL, false, false);
1923 else
1924 RL.add(IndexType::Entry, LL, false, false);
1925 LS = IndexType::None;
1926 }
1927 for (auto &I : LastStore) {
1928 IndexType LS = I.second;
1929 if (LS == IndexType::None)
1930 continue;
1931 auto &RL = FIRangeMap[I.first].Map[&B];
1932 RL.add(LS, IndexType::None, false, false);
1933 }
1934 }
1935
1936 DEBUG({
1937 for (auto &P : FIRangeMap) {
1938 dbgs() << "fi#" << P.first;
1939 if (BadFIs.count(P.first))
1940 dbgs() << " (bad)";
1941 dbgs() << " RC: ";
1942 if (P.second.RC != nullptr)
1943 dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
1944 else
1945 dbgs() << "<null>\n";
1946 for (auto &R : P.second.Map)
1947 dbgs() << " BB#" << R.first->getNumber() << " { " << R.second << "}\n";
1948 }
1949 });
1950
1951 // When a slot is loaded from in a block without being stored to in the
1952 // same block, it is live-on-entry to this block. To avoid CFG analysis,
1953 // consider this slot to be live-on-exit from all blocks.
1954 SmallSet<int,4> LoxFIs;
1955
1956 std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
1957
1958 for (auto &P : FIRangeMap) {
1959 // P = pair(FI, map: BB->RangeList)
1960 if (BadFIs.count(P.first))
1961 continue;
1962 for (auto &B : MF) {
1963 auto F = P.second.Map.find(&B);
1964 // F = pair(BB, RangeList)
1965 if (F == P.second.Map.end() || F->second.empty())
1966 continue;
1967 HexagonBlockRanges::IndexRange &IR = F->second.front();
1968 if (IR.start() == IndexType::Entry)
1969 LoxFIs.insert(P.first);
1970 BlockFIMap[&B].push_back(P.first);
1971 }
1972 }
1973
1974 DEBUG({
1975 dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
1976 for (auto &P : BlockFIMap) {
1977 auto &FIs = P.second;
1978 if (FIs.empty())
1979 continue;
1980 dbgs() << " BB#" << P.first->getNumber() << ": {";
1981 for (auto I : FIs) {
1982 dbgs() << " fi#" << I;
1983 if (LoxFIs.count(I))
1984 dbgs() << '*';
1985 }
1986 dbgs() << " }\n";
1987 }
1988 });
1989
1990 // eliminate loads, when all loads eliminated, eliminate all stores.
1991 for (auto &B : MF) {
1992 auto F = BlockIndexes.find(&B);
1993 assert(F != BlockIndexes.end());
1994 HexagonBlockRanges::InstrIndexMap &IM = F->second;
1995 HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
1996 HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
1997 DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n"
1998 << HexagonBlockRanges::PrintRangeMap(DM, HRI));
1999
2000 for (auto FI : BlockFIMap[&B]) {
2001 if (BadFIs.count(FI))
2002 continue;
2003 DEBUG(dbgs() << "Working on fi#" << FI << '\n');
2004 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2005 for (auto &Range : RL) {
2006 DEBUG(dbgs() << "--Examining range:" << RL << '\n');
2007 if (!IndexType::isInstr(Range.start()) ||
2008 !IndexType::isInstr(Range.end()))
2009 continue;
2010 MachineInstr *SI = IM.getInstr(Range.start());
2011 MachineInstr *EI = IM.getInstr(Range.end());
2012 assert(SI->mayStore() && "Unexpected start instruction");
2013 assert(EI->mayLoad() && "Unexpected end instruction");
2014 MachineOperand &SrcOp = SI->getOperand(2);
2015
2016 HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
2017 SrcOp.getSubReg() };
2018 auto *RC = getRegClass({SrcOp.getReg(), SrcOp.getSubReg()});
2019 // The this-> is needed to unconfuse MSVC.
2020 unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
2021 DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n');
2022 if (FoundR == 0)
2023 continue;
2024
2025 // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
2026 MachineBasicBlock::iterator StartIt = SI, NextIt;
2027 MachineInstr *CopyIn = nullptr;
2028 if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
2029 DebugLoc DL = SI->getDebugLoc();
2030 CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
2031 .addOperand(SrcOp);
2032 }
2033
2034 ++StartIt;
2035 // Check if this is a last store and the FI is live-on-exit.
2036 if (LoxFIs.count(FI) && (&Range == &RL.back())) {
2037 // Update store's source register.
2038 if (unsigned SR = SrcOp.getSubReg())
2039 SrcOp.setReg(HRI.getSubReg(FoundR, SR));
2040 else
2041 SrcOp.setReg(FoundR);
2042 SrcOp.setSubReg(0);
2043 // We are keeping this register live.
2044 SrcOp.setIsKill(false);
2045 } else {
2046 B.erase(SI);
2047 IM.replaceInstr(SI, CopyIn);
2048 }
2049
2050 auto EndIt = std::next(MachineBasicBlock::iterator(EI));
2051 for (auto It = StartIt; It != EndIt; It = NextIt) {
2052 MachineInstr *MI = &*It;
2053 NextIt = std::next(It);
2054 int TFI;
2055 if (!HII.isLoadFromStackSlot(MI, TFI) || TFI != FI)
2056 continue;
2057 unsigned DstR = MI->getOperand(0).getReg();
2058 assert(MI->getOperand(0).getSubReg() == 0);
2059 MachineInstr *CopyOut = nullptr;
2060 if (DstR != FoundR) {
2061 DebugLoc DL = MI->getDebugLoc();
2062 unsigned MemSize = (1U << (HII.getMemAccessSize(MI) - 1));
2063 assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2064 unsigned CopyOpc = TargetOpcode::COPY;
2065 if (HII.isSignExtendingLoad(MI))
2066 CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
2067 else if (HII.isZeroExtendingLoad(MI))
2068 CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2069 CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
2070 .addReg(FoundR, getKillRegState(MI == EI));
2071 }
2072 IM.replaceInstr(MI, CopyOut);
2073 B.erase(It);
2074 }
2075
2076 // Update the dead map.
2077 HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2078 for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2079 DM[RR].subtract(Range);
2080 } // for Range in range list
2081 }
2082 }
2083}
2084
2085
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002086void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002087 const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002088 MachineBasicBlock &MB = *AI->getParent();
2089 DebugLoc DL = AI->getDebugLoc();
2090 unsigned A = AI->getOperand(2).getImm();
2091
2092 // Have
2093 // Rd = alloca Rs, #A
2094 //
2095 // If Rs and Rd are different registers, use this sequence:
2096 // Rd = sub(r29, Rs)
2097 // r29 = sub(r29, Rs)
2098 // Rd = and(Rd, #-A) ; if necessary
2099 // r29 = and(r29, #-A) ; if necessary
2100 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2101 // otherwise, do
2102 // Rd = sub(r29, Rs)
2103 // Rd = and(Rd, #-A) ; if necessary
2104 // r29 = Rd
2105 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2106
2107 MachineOperand &RdOp = AI->getOperand(0);
2108 MachineOperand &RsOp = AI->getOperand(1);
2109 unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2110
2111 // Rd = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002112 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002113 .addReg(SP)
2114 .addReg(Rs);
2115 if (Rs != Rd) {
2116 // r29 = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002117 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002118 .addReg(SP)
2119 .addReg(Rs);
2120 }
2121 if (A > 8) {
2122 // Rd = and(Rd, #-A)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002123 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002124 .addReg(Rd)
2125 .addImm(-int64_t(A));
2126 if (Rs != Rd)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002127 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002128 .addReg(SP)
2129 .addImm(-int64_t(A));
2130 }
2131 if (Rs == Rd) {
2132 // r29 = Rd
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002133 BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002134 .addReg(Rd);
2135 }
2136 if (CF > 0) {
2137 // Rd = add(Rd, #CF)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002138 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002139 .addReg(Rd)
2140 .addImm(CF);
2141 }
2142}
2143
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002144
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002145bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
2146 const MachineFrameInfo *MFI = MF.getFrameInfo();
2147 if (!MFI->hasVarSizedObjects())
2148 return false;
2149 unsigned MaxA = MFI->getMaxAlignment();
2150 if (MaxA <= getStackAlignment())
2151 return false;
2152 return true;
2153}
2154
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002155
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00002156const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2157 const MachineFunction &MF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002158 for (auto &B : MF)
2159 for (auto &I : B)
2160 if (I.getOpcode() == Hexagon::ALIGNA)
2161 return &I;
2162 return nullptr;
2163}
2164
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002165
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00002166/// Adds all callee-saved registers as implicit uses or defs to the
2167/// instruction.
2168void HexagonFrameLowering::addCalleeSaveRegistersAsImpOperand(MachineInstr *MI,
2169 const CSIVect &CSI, bool IsDef, bool IsKill) const {
2170 // Add the callee-saved registers as implicit uses.
2171 for (auto &R : CSI)
2172 MI->addOperand(MachineOperand::CreateReg(R.getReg(), IsDef, true, IsKill));
2173}
2174
2175
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002176/// Determine whether the callee-saved register saves and restores should
2177/// be generated via inline code. If this function returns "true", inline
2178/// code will be generated. If this function returns "false", additional
2179/// checks are performed, which may still lead to the inline code.
2180bool HexagonFrameLowering::shouldInlineCSR(MachineFunction &MF,
2181 const CSIVect &CSI) const {
2182 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2183 return true;
2184 if (!isOptSize(MF) && !isMinSize(MF))
2185 if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2186 return true;
2187
2188 // Check if CSI only has double registers, and if the registers form
2189 // a contiguous block starting from D8.
2190 BitVector Regs(Hexagon::NUM_TARGET_REGS);
2191 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2192 unsigned R = CSI[i].getReg();
2193 if (!Hexagon::DoubleRegsRegClass.contains(R))
2194 return true;
2195 Regs[R] = true;
2196 }
2197 int F = Regs.find_first();
2198 if (F != Hexagon::D8)
2199 return true;
2200 while (F >= 0) {
2201 int N = Regs.find_next(F);
2202 if (N >= 0 && N != F+1)
2203 return true;
2204 F = N;
2205 }
2206
2207 return false;
2208}
2209
2210
2211bool HexagonFrameLowering::useSpillFunction(MachineFunction &MF,
2212 const CSIVect &CSI) const {
2213 if (shouldInlineCSR(MF, CSI))
2214 return false;
2215 unsigned NumCSI = CSI.size();
2216 if (NumCSI <= 1)
2217 return false;
2218
2219 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2220 : SpillFuncThreshold;
2221 return Threshold < NumCSI;
2222}
2223
2224
2225bool HexagonFrameLowering::useRestoreFunction(MachineFunction &MF,
2226 const CSIVect &CSI) const {
2227 if (shouldInlineCSR(MF, CSI))
2228 return false;
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002229 // The restore functions do a bit more than just restoring registers.
2230 // The non-returning versions will go back directly to the caller's
2231 // caller, others will clean up the stack frame in preparation for
2232 // a tail call. Using them can still save code size even if only one
2233 // register is getting restores. Make the decision based on -Oz:
2234 // using -Os will use inline restore for a single register.
2235 if (isMinSize(MF))
2236 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002237 unsigned NumCSI = CSI.size();
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002238 if (NumCSI <= 1)
2239 return false;
2240
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002241 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2242 : SpillFuncThreshold;
2243 return Threshold < NumCSI;
2244}