blob: a6a950ea045cae732e76c0aeecdf88a145727331 [file] [log] [blame]
Eugene Zelenkoe4fc6ee2017-07-26 23:20:35 +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
Craig Topperb25fda92012-03-17 18:46:09 +000011#include "HexagonFrameLowering.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000012#include "HexagonBlockRanges.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000013#include "HexagonInstrInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000014#include "HexagonMachineFunctionInfo.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000015#include "HexagonRegisterInfo.h"
16#include "HexagonSubtarget.h"
17#include "HexagonTargetMachine.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000018#include "MCTargetDesc/HexagonBaseInfo.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000019#include "llvm/ADT/BitVector.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000020#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/None.h"
22#include "llvm/ADT/Optional.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000023#include "llvm/ADT/PostOrderIterator.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000024#include "llvm/ADT/SetVector.h"
25#include "llvm/ADT/SmallSet.h"
26#include "llvm/ADT/SmallVector.h"
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +000027#include "llvm/CodeGen/LivePhysRegs.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000028#include "llvm/CodeGen/MachineBasicBlock.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000029#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000030#include "llvm/CodeGen/MachineFrameInfo.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000031#include "llvm/CodeGen/MachineFunction.h"
32#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000033#include "llvm/CodeGen/MachineInstr.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000035#include "llvm/CodeGen/MachineMemOperand.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000036#include "llvm/CodeGen/MachineModuleInfo.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000037#include "llvm/CodeGen/MachineOperand.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000038#include "llvm/CodeGen/MachinePostDominators.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000039#include "llvm/CodeGen/MachineRegisterInfo.h"
40#include "llvm/CodeGen/RegisterScavenging.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000041#include "llvm/CodeGen/TargetRegisterInfo.h"
Eugene Zelenkoe4fc6ee2017-07-26 23:20:35 +000042#include "llvm/IR/Attributes.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000043#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000044#include "llvm/IR/Function.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000045#include "llvm/MC/MCDwarf.h"
46#include "llvm/MC/MCRegisterInfo.h"
47#include "llvm/Pass.h"
48#include "llvm/Support/CodeGen.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000049#include "llvm/Support/CommandLine.h"
Eugene Zelenkoe4fc6ee2017-07-26 23:20:35 +000050#include "llvm/Support/Compiler.h"
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000051#include "llvm/Support/Debug.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000052#include "llvm/Support/ErrorHandling.h"
53#include "llvm/Support/MathExtras.h"
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000054#include "llvm/Support/raw_ostream.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000055#include "llvm/Target/TargetMachine.h"
Eugene Zelenkoe4fc6ee2017-07-26 23:20:35 +000056#include "llvm/Target/TargetOptions.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000057#include <algorithm>
58#include <cassert>
59#include <cstdint>
60#include <iterator>
61#include <limits>
62#include <map>
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000063#include <utility>
64#include <vector>
Tony Linthicum1213a7a2011-12-12 21:14:40 +000065
Jakub Kuderski34327d22017-07-13 20:26:45 +000066#define DEBUG_TYPE "hexagon-pei"
67
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000068// Hexagon stack frame layout as defined by the ABI:
69//
70// Incoming arguments
71// passed via stack
72// |
73// |
74// SP during function's FP during function's |
75// +-- runtime (top of stack) runtime (bottom) --+ |
76// | | |
77// --++---------------------+------------------+-----------------++-+-------
78// | parameter area for | variable-size | fixed-size |LR| arg
79// | called functions | local objects | local objects |FP|
80// --+----------------------+------------------+-----------------+--+-------
81// <- size known -> <- size unknown -> <- size known ->
82//
83// Low address High address
84//
85// <--- stack growth
86//
87//
88// - In any circumstances, the outgoing function arguments are always accessi-
89// ble using the SP, and the incoming arguments are accessible using the FP.
90// - If the local objects are not aligned, they can always be accessed using
91// the FP.
92// - If there are no variable-sized objects, the local objects can always be
93// accessed using the SP, regardless whether they are aligned or not. (The
94// alignment padding will be at the bottom of the stack (highest address),
95// and so the offset with respect to the SP will be known at the compile-
96// -time.)
97//
98// The only complication occurs if there are both, local aligned objects, and
99// dynamically allocated (variable-sized) objects. The alignment pad will be
100// placed between the FP and the local objects, thus preventing the use of the
101// FP to access the local objects. At the same time, the variable-sized objects
102// will be between the SP and the local objects, thus introducing an unknown
103// distance from the SP to the locals.
104//
105// To avoid this problem, a new register is created that holds the aligned
106// address of the bottom of the stack, referred in the sources as AP (aligned
107// pointer). The AP will be equal to "FP-p", where "p" is the smallest pad
108// that aligns AP to the required boundary (a maximum of the alignments of
109// all stack objects, fixed- and variable-sized). All local objects[1] will
110// then use AP as the base pointer.
111// [1] The exception is with "fixed" stack objects. "Fixed" stack objects get
112// their name from being allocated at fixed locations on the stack, relative
113// to the FP. In the presence of dynamic allocation and local alignment, such
114// objects can only be accessed through the FP.
115//
116// Illustration of the AP:
117// FP --+
118// |
119// ---------------+---------------------+-----+-----------------------++-+--
120// Rest of the | Local stack objects | Pad | Fixed stack objects |LR|
121// stack frame | (aligned) | | (CSR, spills, etc.) |FP|
122// ---------------+---------------------+-----+-----------------+-----+--+--
123// |<-- Multiple of the -->|
124// stack alignment +-- AP
125//
126// The AP is set up at the beginning of the function. Since it is not a dedi-
127// cated (reserved) register, it needs to be kept live throughout the function
128// to be available as the base register for local object accesses.
129// Normally, an address of a stack objects is obtained by a pseudo-instruction
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000130// PS_fi. To access local objects with the AP register present, a different
131// pseudo-instruction needs to be used: PS_fia. The PS_fia takes one extra
132// argument compared to PS_fi: the first input register is the AP register.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000133// This keeps the register live between its definition and its uses.
134
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000135// The AP register is originally set up using pseudo-instruction PS_aligna:
136// AP = PS_aligna A
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000137// where
138// A - required stack alignment
139// The alignment value must be the maximum of all alignments required by
140// any stack object.
141
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000142// The dynamic allocation uses a pseudo-instruction PS_alloca:
143// Rd = PS_alloca Rs, A
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000144// where
145// Rd - address of the allocated space
146// Rs - minimum size (the actual allocated can be larger to accommodate
147// alignment)
148// A - required alignment
149
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000150using namespace llvm;
151
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000152static cl::opt<bool> DisableDeallocRet("disable-hexagon-dealloc-ret",
153 cl::Hidden, cl::desc("Disable Dealloc Return for Hexagon target"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000154
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +0000155static cl::opt<unsigned> NumberScavengerSlots("number-scavenger-slots",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000156 cl::Hidden, cl::desc("Set the number of scavenger slots"), cl::init(2),
157 cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000158
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000159static cl::opt<int> SpillFuncThreshold("spill-func-threshold",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000160 cl::Hidden, cl::desc("Specify O2(not Os) spill func threshold"),
161 cl::init(6), cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000162
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000163static cl::opt<int> SpillFuncThresholdOs("spill-func-threshold-Os",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000164 cl::Hidden, cl::desc("Specify Os spill func threshold"),
165 cl::init(1), cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000166
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000167static cl::opt<bool> EnableStackOVFSanitizer("enable-stackovf-sanitizer",
168 cl::Hidden, cl::desc("Enable runtime checks for stack overflow."),
169 cl::init(false), cl::ZeroOrMore);
170
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000171static cl::opt<bool> EnableShrinkWrapping("hexagon-shrink-frame",
172 cl::init(true), cl::Hidden, cl::ZeroOrMore,
173 cl::desc("Enable stack frame shrink wrapping"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000174
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000175static cl::opt<unsigned> ShrinkLimit("shrink-frame-limit",
176 cl::init(std::numeric_limits<unsigned>::max()), cl::Hidden, cl::ZeroOrMore,
177 cl::desc("Max count of stack frame shrink-wraps"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000178
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000179static cl::opt<bool> EnableSaveRestoreLong("enable-save-restore-long",
180 cl::Hidden, cl::desc("Enable long calls for save-restore stubs."),
181 cl::init(false), cl::ZeroOrMore);
182
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000183static cl::opt<bool> EliminateFramePointer("hexagon-fp-elim", cl::init(true),
184 cl::Hidden, cl::desc("Refrain from using FP whenever possible"));
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000185
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +0000186static cl::opt<bool> OptimizeSpillSlots("hexagon-opt-spill", cl::Hidden,
187 cl::init(true), cl::desc("Optimize spill slots"));
188
Krzysztof Parzyszekdc421642016-07-27 20:58:43 +0000189#ifndef NDEBUG
190static cl::opt<unsigned> SpillOptMax("spill-opt-max", cl::Hidden,
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000191 cl::init(std::numeric_limits<unsigned>::max()));
Krzysztof Parzyszekdc421642016-07-27 20:58:43 +0000192static unsigned SpillOptCount = 0;
193#endif
194
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000195namespace llvm {
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000196
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000197 void initializeHexagonCallFrameInformationPass(PassRegistry&);
198 FunctionPass *createHexagonCallFrameInformation();
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000199
200} // end namespace llvm
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000201
202namespace {
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000203
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000204 class HexagonCallFrameInformation : public MachineFunctionPass {
205 public:
206 static char ID;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000207
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000208 HexagonCallFrameInformation() : MachineFunctionPass(ID) {
209 PassRegistry &PR = *PassRegistry::getPassRegistry();
210 initializeHexagonCallFrameInformationPass(PR);
211 }
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000212
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000213 bool runOnMachineFunction(MachineFunction &MF) override;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000214
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000215 MachineFunctionProperties getRequiredProperties() const override {
216 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000217 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000218 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000219 };
220
221 char HexagonCallFrameInformation::ID = 0;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000222
223} // end anonymous namespace
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000224
225bool HexagonCallFrameInformation::runOnMachineFunction(MachineFunction &MF) {
226 auto &HFI = *MF.getSubtarget<HexagonSubtarget>().getFrameLowering();
227 bool NeedCFI = MF.getMMI().hasDebugInfo() ||
228 MF.getFunction()->needsUnwindTableEntry();
229
230 if (!NeedCFI)
231 return false;
232 HFI.insertCFIInstructions(MF);
233 return true;
234}
235
236INITIALIZE_PASS(HexagonCallFrameInformation, "hexagon-cfi",
237 "Hexagon call frame information", false, false)
238
239FunctionPass *llvm::createHexagonCallFrameInformation() {
240 return new HexagonCallFrameInformation();
241}
242
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000243/// Map a register pair Reg to the subregister that has the greater "number",
244/// i.e. D3 (aka R7:6) will be mapped to R7, etc.
245static unsigned getMax32BitSubRegister(unsigned Reg,
246 const TargetRegisterInfo &TRI,
247 bool hireg = true) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000248 if (Reg < Hexagon::D0 || Reg > Hexagon::D15)
249 return Reg;
250
251 unsigned RegNo = 0;
252 for (MCSubRegIterator SubRegs(Reg, &TRI); SubRegs.isValid(); ++SubRegs) {
253 if (hireg) {
254 if (*SubRegs > RegNo)
255 RegNo = *SubRegs;
256 } else {
257 if (!RegNo || *SubRegs < RegNo)
258 RegNo = *SubRegs;
259 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000260 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000261 return RegNo;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000262}
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000263
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000264/// Returns the callee saved register with the largest id in the vector.
265static unsigned getMaxCalleeSavedReg(const std::vector<CalleeSavedInfo> &CSI,
266 const TargetRegisterInfo &TRI) {
Benjamin Kramer3e9a5d32016-05-27 11:36:04 +0000267 static_assert(Hexagon::R1 > 0,
268 "Assume physical registers are encoded as positive integers");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000269 if (CSI.empty())
270 return 0;
271
272 unsigned Max = getMax32BitSubRegister(CSI[0].getReg(), TRI);
273 for (unsigned I = 1, E = CSI.size(); I < E; ++I) {
274 unsigned Reg = getMax32BitSubRegister(CSI[I].getReg(), TRI);
275 if (Reg > Max)
276 Max = Reg;
277 }
278 return Max;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000279}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000280
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000281/// Checks if the basic block contains any instruction that needs a stack
282/// frame to be already in place.
283static bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR,
284 const HexagonRegisterInfo &HRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000285 for (auto &I : MBB) {
286 const MachineInstr *MI = &I;
287 if (MI->isCall())
288 return true;
289 unsigned Opc = MI->getOpcode();
290 switch (Opc) {
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000291 case Hexagon::PS_alloca:
292 case Hexagon::PS_aligna:
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000293 return true;
294 default:
295 break;
296 }
297 // Check individual operands.
Matthias Braune41e1462015-05-29 02:56:46 +0000298 for (const MachineOperand &MO : MI->operands()) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000299 // While the presence of a frame index does not prove that a stack
300 // frame will be required, all frame indexes should be within alloc-
301 // frame/deallocframe. Otherwise, the code that translates a frame
302 // index into an offset would have to be aware of the placement of
303 // the frame creation/destruction instructions.
Matthias Braune41e1462015-05-29 02:56:46 +0000304 if (MO.isFI())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000305 return true;
Krzysztof Parzyszek1aaf41a2017-02-17 22:14:51 +0000306 if (MO.isReg()) {
307 unsigned R = MO.getReg();
308 // Virtual registers will need scavenging, which then may require
309 // a stack slot.
310 if (TargetRegisterInfo::isVirtualRegister(R))
Rafael Espindola6eab4042017-02-17 02:08:58 +0000311 return true;
Krzysztof Parzyszek1aaf41a2017-02-17 22:14:51 +0000312 for (MCSubRegIterator S(R, &HRI, true); S.isValid(); ++S)
313 if (CSR[*S])
314 return true;
315 continue;
316 }
317 if (MO.isRegMask()) {
318 // A regmask would normally have all callee-saved registers marked
319 // as preserved, so this check would not be needed, but in case of
320 // ever having other regmasks (for other calling conventions),
321 // make sure they would be processed correctly.
322 const uint32_t *BM = MO.getRegMask();
323 for (int x = CSR.find_first(); x >= 0; x = CSR.find_next(x)) {
324 unsigned R = x;
325 // If this regmask does not preserve a CSR, a frame will be needed.
326 if (!(BM[R/32] & (1u << (R%32))))
327 return true;
328 }
329 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000330 }
331 }
332 return false;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000333}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000334
335 /// Returns true if MBB has a machine instructions that indicates a tail call
336 /// in the block.
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000337static bool hasTailCall(const MachineBasicBlock &MBB) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000338 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
339 unsigned RetOpc = I->getOpcode();
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000340 return RetOpc == Hexagon::PS_tailcall_i || RetOpc == Hexagon::PS_tailcall_r;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000341}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000342
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000343/// Returns true if MBB contains an instruction that returns.
344static bool hasReturn(const MachineBasicBlock &MBB) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000345 for (auto I = MBB.getFirstTerminator(), E = MBB.end(); I != E; ++I)
346 if (I->isReturn())
347 return true;
348 return false;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000349}
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +0000350
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000351/// Returns the "return" instruction from this block, or nullptr if there
352/// isn't any.
353static MachineInstr *getReturn(MachineBasicBlock &MBB) {
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000354 for (auto &I : MBB)
355 if (I.isReturn())
356 return &I;
357 return nullptr;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000358}
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000359
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000360static bool isRestoreCall(unsigned Opc) {
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000361 switch (Opc) {
362 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4:
363 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC:
Krzysztof Parzyszekfae79862016-07-27 18:47:25 +0000364 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT:
365 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC:
366 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT:
367 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC:
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000368 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4:
369 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC:
370 return true;
371 }
372 return false;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000373}
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000374
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000375static inline bool isOptNone(const MachineFunction &MF) {
376 return MF.getFunction()->hasFnAttribute(Attribute::OptimizeNone) ||
377 MF.getTarget().getOptLevel() == CodeGenOpt::None;
378}
379
380static inline bool isOptSize(const MachineFunction &MF) {
381 const Function &F = *MF.getFunction();
382 return F.optForSize() && !F.optForMinSize();
383}
384
385static inline bool isMinSize(const MachineFunction &MF) {
386 return MF.getFunction()->optForMinSize();
387}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000388
389/// Implements shrink-wrapping of the stack frame. By default, stack frame
390/// is created in the function entry block, and is cleaned up in every block
391/// that returns. This function finds alternate blocks: one for the frame
392/// setup (prolog) and one for the cleanup (epilog).
393void HexagonFrameLowering::findShrunkPrologEpilog(MachineFunction &MF,
394 MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const {
395 static unsigned ShrinkCounter = 0;
396
397 if (ShrinkLimit.getPosition()) {
398 if (ShrinkCounter >= ShrinkLimit)
399 return;
400 ShrinkCounter++;
401 }
402
Krzysztof Parzyszek55772972017-09-15 15:46:05 +0000403 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000404
405 MachineDominatorTree MDT;
406 MDT.runOnMachineFunction(MF);
407 MachinePostDominatorTree MPT;
408 MPT.runOnMachineFunction(MF);
409
Eugene Zelenkoe4fc6ee2017-07-26 23:20:35 +0000410 using UnsignedMap = DenseMap<unsigned, unsigned>;
411 using RPOTType = ReversePostOrderTraversal<const MachineFunction *>;
412
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000413 UnsignedMap RPO;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000414 RPOTType RPOT(&MF);
415 unsigned RPON = 0;
416 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I)
417 RPO[(*I)->getNumber()] = RPON++;
418
419 // Don't process functions that have loops, at least for now. Placement
420 // of prolog and epilog must take loop structure into account. For simpli-
421 // city don't do it right now.
422 for (auto &I : MF) {
423 unsigned BN = RPO[I.getNumber()];
424 for (auto SI = I.succ_begin(), SE = I.succ_end(); SI != SE; ++SI) {
425 // If found a back-edge, return.
426 if (RPO[(*SI)->getNumber()] <= BN)
427 return;
428 }
429 }
430
431 // Collect the set of blocks that need a stack frame to execute. Scan
432 // each block for uses/defs of callee-saved registers, calls, etc.
433 SmallVector<MachineBasicBlock*,16> SFBlocks;
434 BitVector CSR(Hexagon::NUM_TARGET_REGS);
435 for (const MCPhysReg *P = HRI.getCalleeSavedRegs(&MF); *P; ++P)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000436 for (MCSubRegIterator S(*P, &HRI, true); S.isValid(); ++S)
437 CSR[*S] = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000438
439 for (auto &I : MF)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000440 if (needsStackFrame(I, CSR, HRI))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000441 SFBlocks.push_back(&I);
442
443 DEBUG({
444 dbgs() << "Blocks needing SF: {";
445 for (auto &B : SFBlocks)
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000446 dbgs() << " " << printMBBReference(*B);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000447 dbgs() << " }\n";
448 });
449 // No frame needed?
450 if (SFBlocks.empty())
451 return;
452
453 // Pick a common dominator and a common post-dominator.
454 MachineBasicBlock *DomB = SFBlocks[0];
455 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
456 DomB = MDT.findNearestCommonDominator(DomB, SFBlocks[i]);
457 if (!DomB)
458 break;
459 }
460 MachineBasicBlock *PDomB = SFBlocks[0];
461 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
462 PDomB = MPT.findNearestCommonDominator(PDomB, SFBlocks[i]);
463 if (!PDomB)
464 break;
465 }
466 DEBUG({
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000467 dbgs() << "Computed dom block: ";
468 if (DomB)
469 dbgs() << printMBBReference(*DomB);
470 else
471 dbgs() << "<null>";
472 dbgs() << ", computed pdom block: ";
473 if (PDomB)
474 dbgs() << printMBBReference(*PDomB);
475 else
476 dbgs() << "<null>";
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000477 dbgs() << "\n";
478 });
479 if (!DomB || !PDomB)
480 return;
481
482 // Make sure that DomB dominates PDomB and PDomB post-dominates DomB.
483 if (!MDT.dominates(DomB, PDomB)) {
484 DEBUG(dbgs() << "Dom block does not dominate pdom block\n");
485 return;
486 }
487 if (!MPT.dominates(PDomB, DomB)) {
488 DEBUG(dbgs() << "PDom block does not post-dominate dom block\n");
489 return;
490 }
491
492 // Finally, everything seems right.
493 PrologB = DomB;
494 EpilogB = PDomB;
495}
496
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000497/// Perform most of the PEI work here:
498/// - saving/restoring of the callee-saved registers,
499/// - stack frame creation and destruction.
500/// Normally, this work is distributed among various functions, but doing it
501/// in one place allows shrink-wrapping of the stack frame.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000502void HexagonFrameLowering::emitPrologue(MachineFunction &MF,
503 MachineBasicBlock &MBB) const {
Krzysztof Parzyszek55772972017-09-15 15:46:05 +0000504 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000505
Matthias Braun941a7052016-07-28 18:40:00 +0000506 MachineFrameInfo &MFI = MF.getFrameInfo();
507 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000508
509 MachineBasicBlock *PrologB = &MF.front(), *EpilogB = nullptr;
510 if (EnableShrinkWrapping)
511 findShrunkPrologEpilog(MF, PrologB, EpilogB);
512
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000513 bool PrologueStubs = false;
514 insertCSRSpillsInBlock(*PrologB, CSI, HRI, PrologueStubs);
515 insertPrologueInBlock(*PrologB, PrologueStubs);
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000516 updateEntryPaths(MF, *PrologB);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000517
518 if (EpilogB) {
519 insertCSRRestoresInBlock(*EpilogB, CSI, HRI);
520 insertEpilogueInBlock(*EpilogB);
521 } else {
522 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000523 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000524 insertCSRRestoresInBlock(B, CSI, HRI);
525
526 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000527 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000528 insertEpilogueInBlock(B);
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000529
530 for (auto &B : MF) {
531 if (B.empty())
532 continue;
533 MachineInstr *RetI = getReturn(B);
534 if (!RetI || isRestoreCall(RetI->getOpcode()))
535 continue;
536 for (auto &R : CSI)
537 RetI->addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
538 }
539 }
540
541 if (EpilogB) {
542 // If there is an epilog block, it may not have a return instruction.
543 // In such case, we need to add the callee-saved registers as live-ins
544 // in all blocks on all paths from the epilog to any return block.
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000545 unsigned MaxBN = MF.getNumBlockIDs();
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000546 BitVector DoneT(MaxBN+1), DoneF(MaxBN+1), Path(MaxBN+1);
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000547 updateExitPaths(*EpilogB, *EpilogB, DoneT, DoneF, Path);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000548 }
549}
550
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000551void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB,
552 bool PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000553 MachineFunction &MF = *MBB.getParent();
Matthias Braun941a7052016-07-28 18:40:00 +0000554 MachineFrameInfo &MFI = MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000555 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000556 auto &HII = *HST.getInstrInfo();
557 auto &HRI = *HST.getRegisterInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000558
Krzysztof Parzyszek71702172017-06-23 19:47:04 +0000559 unsigned MaxAlign = std::max(MFI.getMaxAlignment(), getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000560
561 // Calculate the total stack frame size.
562 // Get the number of bytes to allocate from the FrameInfo.
Matthias Braun941a7052016-07-28 18:40:00 +0000563 unsigned FrameSize = MFI.getStackSize();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000564 // Round up the max call frame size to the max alignment on the stack.
Matthias Braun941a7052016-07-28 18:40:00 +0000565 unsigned MaxCFA = alignTo(MFI.getMaxCallFrameSize(), MaxAlign);
566 MFI.setMaxCallFrameSize(MaxCFA);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000567
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000568 FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
Matthias Braun941a7052016-07-28 18:40:00 +0000569 MFI.setStackSize(FrameSize);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000570
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000571 bool AlignStack = (MaxAlign > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000572
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000573 // Get the number of bytes to allocate from the FrameInfo.
Matthias Braun941a7052016-07-28 18:40:00 +0000574 unsigned NumBytes = MFI.getStackSize();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000575 unsigned SP = HRI.getStackRegister();
Matthias Braun941a7052016-07-28 18:40:00 +0000576 unsigned MaxCF = MFI.getMaxCallFrameSize();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000577 MachineBasicBlock::iterator InsertPt = MBB.begin();
578
Krzysztof Parzyszek8849a512016-08-19 18:46:13 +0000579 SmallVector<MachineInstr *, 4> AdjustRegs;
580 for (auto &MBB : MF)
581 for (auto &MI : MBB)
582 if (MI.getOpcode() == Hexagon::PS_alloca)
583 AdjustRegs.push_back(&MI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000584
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000585 for (auto MI : AdjustRegs) {
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000586 assert((MI->getOpcode() == Hexagon::PS_alloca) && "Expected alloca");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000587 expandAlloca(MI, HII, SP, MaxCF);
588 MI->eraseFromParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000589 }
590
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000591 DebugLoc dl = MBB.findDebugLoc(InsertPt);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000592
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000593 if (hasFP(MF)) {
594 insertAllocframe(MBB, InsertPt, NumBytes);
595 if (AlignStack) {
596 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
597 .addReg(SP)
598 .addImm(-int64_t(MaxAlign));
599 }
600 // If the stack-checking is enabled, and we spilled the callee-saved
601 // registers inline (i.e. did not use a spill function), then call
602 // the stack checker directly.
603 if (EnableStackOVFSanitizer && !PrologueStubs)
604 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::PS_call_stk))
605 .addExternalSymbol("__runtime_stack_check");
606 } else if (NumBytes > 0) {
607 assert(alignTo(NumBytes, 8) == NumBytes);
608 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000609 .addReg(SP)
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000610 .addImm(-int(NumBytes));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000611 }
612}
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000613
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000614void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
615 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000616 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000617 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000618 auto &HRI = *HST.getRegisterInfo();
619 unsigned SP = HRI.getStackRegister();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000620
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000621 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
622 DebugLoc dl = MBB.findDebugLoc(InsertPt);
623
624 if (!hasFP(MF)) {
625 MachineFrameInfo &MFI = MF.getFrameInfo();
626 if (unsigned NumBytes = MFI.getStackSize()) {
627 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
628 .addReg(SP)
629 .addImm(NumBytes);
630 }
631 return;
632 }
633
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000634 MachineInstr *RetI = getReturn(MBB);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000635 unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
636
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000637 // Handle EH_RETURN.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000638 if (RetOpc == Hexagon::EH_RETURN_JMPR) {
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000639 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::L2_deallocframe));
640 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_add), SP)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000641 .addReg(SP)
642 .addReg(Hexagon::R28);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000643 return;
644 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000645
646 // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
647 // frame instruction if we encounter it.
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000648 if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
Krzysztof Parzyszekfae79862016-07-27 18:47:25 +0000649 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC ||
650 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT ||
651 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000652 MachineBasicBlock::iterator It = RetI;
653 ++It;
654 // Delete all instructions after the RESTORE (except labels).
655 while (It != MBB.end()) {
656 if (!It->isLabel())
657 It = MBB.erase(It);
658 else
659 ++It;
Jyotsna Verma300f0b92013-05-10 20:27:34 +0000660 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000661 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000662 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000663
664 // It is possible that the restoring code is a call to a library function.
665 // All of the restore* functions include "deallocframe", so we need to make
666 // sure that we don't add an extra one.
667 bool NeedsDeallocframe = true;
668 if (!MBB.empty() && InsertPt != MBB.begin()) {
669 MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
670 unsigned COpc = PrevIt->getOpcode();
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000671 if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
Krzysztof Parzyszekfae79862016-07-27 18:47:25 +0000672 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC ||
673 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT ||
674 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC ||
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000675 COpc == Hexagon::PS_call_nr || COpc == Hexagon::PS_callr_nr)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000676 NeedsDeallocframe = false;
677 }
678
679 if (!NeedsDeallocframe)
680 return;
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000681 // If the returning instruction is PS_jmpret, replace it with dealloc_return,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000682 // otherwise just add deallocframe. The function could be returning via a
683 // tail call.
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000684 if (RetOpc != Hexagon::PS_jmpret || DisableDeallocRet) {
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000685 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::L2_deallocframe));
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000686 return;
687 }
688 unsigned NewOpc = Hexagon::L4_return;
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000689 MachineInstr *NewI = BuildMI(MBB, RetI, dl, HII.get(NewOpc));
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000690 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000691 NewI->copyImplicitOps(MF, *RetI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000692 MBB.erase(RetI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000693}
694
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000695void HexagonFrameLowering::insertAllocframe(MachineBasicBlock &MBB,
696 MachineBasicBlock::iterator InsertPt, unsigned NumBytes) const {
697 MachineFunction &MF = *MBB.getParent();
698 auto &HST = MF.getSubtarget<HexagonSubtarget>();
699 auto &HII = *HST.getInstrInfo();
700 auto &HRI = *HST.getRegisterInfo();
701
702 // Check for overflow.
703 // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
704 const unsigned int ALLOCFRAME_MAX = 16384;
705
706 // Create a dummy memory operand to avoid allocframe from being treated as
707 // a volatile memory reference.
708 auto *MMO = MF.getMachineMemOperand(MachinePointerInfo::getStack(MF, 0),
709 MachineMemOperand::MOStore, 4, 4);
710
711 DebugLoc dl = MBB.findDebugLoc(InsertPt);
712
713 if (NumBytes >= ALLOCFRAME_MAX) {
714 // Emit allocframe(#0).
715 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
716 .addImm(0)
717 .addMemOperand(MMO);
718
719 // Subtract the size from the stack pointer.
720 unsigned SP = HRI.getStackRegister();
721 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
722 .addReg(SP)
723 .addImm(-int(NumBytes));
724 } else {
725 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
726 .addImm(NumBytes)
727 .addMemOperand(MMO);
728 }
729}
730
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000731void HexagonFrameLowering::updateEntryPaths(MachineFunction &MF,
732 MachineBasicBlock &SaveB) const {
733 SetVector<unsigned> Worklist;
734
735 MachineBasicBlock &EntryB = MF.front();
736 Worklist.insert(EntryB.getNumber());
737
738 unsigned SaveN = SaveB.getNumber();
Matthias Braun941a7052016-07-28 18:40:00 +0000739 auto &CSI = MF.getFrameInfo().getCalleeSavedInfo();
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000740
741 for (unsigned i = 0; i < Worklist.size(); ++i) {
742 unsigned BN = Worklist[i];
743 MachineBasicBlock &MBB = *MF.getBlockNumbered(BN);
744 for (auto &R : CSI)
745 if (!MBB.isLiveIn(R.getReg()))
746 MBB.addLiveIn(R.getReg());
747 if (BN != SaveN)
748 for (auto &SB : MBB.successors())
749 Worklist.insert(SB->getNumber());
750 }
751}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000752
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000753bool HexagonFrameLowering::updateExitPaths(MachineBasicBlock &MBB,
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000754 MachineBasicBlock &RestoreB, BitVector &DoneT, BitVector &DoneF,
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000755 BitVector &Path) const {
756 assert(MBB.getNumber() >= 0);
757 unsigned BN = MBB.getNumber();
758 if (Path[BN] || DoneF[BN])
759 return false;
760 if (DoneT[BN])
761 return true;
762
Matthias Braun941a7052016-07-28 18:40:00 +0000763 auto &CSI = MBB.getParent()->getFrameInfo().getCalleeSavedInfo();
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000764
765 Path[BN] = true;
766 bool ReachedExit = false;
767 for (auto &SB : MBB.successors())
768 ReachedExit |= updateExitPaths(*SB, RestoreB, DoneT, DoneF, Path);
769
770 if (!MBB.empty() && MBB.back().isReturn()) {
771 // Add implicit uses of all callee-saved registers to the reached
772 // return instructions. This is to prevent the anti-dependency breaker
773 // from renaming these registers.
774 MachineInstr &RetI = MBB.back();
775 if (!isRestoreCall(RetI.getOpcode()))
776 for (auto &R : CSI)
777 RetI.addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
778 ReachedExit = true;
779 }
780
781 // We don't want to add unnecessary live-ins to the restore block: since
782 // the callee-saved registers are being defined in it, the entry of the
783 // restore block cannot be on the path from the definitions to any exit.
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000784 if (ReachedExit && &MBB != &RestoreB) {
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000785 for (auto &R : CSI)
786 if (!MBB.isLiveIn(R.getReg()))
787 MBB.addLiveIn(R.getReg());
788 DoneT[BN] = true;
789 }
790 if (!ReachedExit)
791 DoneF[BN] = true;
792
793 Path[BN] = false;
794 return ReachedExit;
795}
796
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000797static Optional<MachineBasicBlock::iterator>
798findCFILocation(MachineBasicBlock &B) {
Krzysztof Parzyszekc43644d2016-07-28 19:13:46 +0000799 // The CFI instructions need to be inserted right after allocframe.
800 // An exception to this is a situation where allocframe is bundled
801 // with a call: then the CFI instructions need to be inserted before
802 // the packet with the allocframe+call (in case the call throws an
803 // exception).
804 auto End = B.instr_end();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000805
Krzysztof Parzyszekc43644d2016-07-28 19:13:46 +0000806 for (MachineInstr &I : B) {
807 MachineBasicBlock::iterator It = I.getIterator();
808 if (!I.isBundle()) {
809 if (I.getOpcode() == Hexagon::S2_allocframe)
810 return std::next(It);
811 continue;
812 }
813 // I is a bundle.
814 bool HasCall = false, HasAllocFrame = false;
815 auto T = It.getInstrIterator();
816 while (++T != End && T->isBundled()) {
817 if (T->getOpcode() == Hexagon::S2_allocframe)
818 HasAllocFrame = true;
819 else if (T->isCall())
820 HasCall = true;
821 }
822 if (HasAllocFrame)
823 return HasCall ? It : std::next(It);
824 }
825 return None;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000826}
827
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000828void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
829 for (auto &B : MF) {
Krzysztof Parzyszekc43644d2016-07-28 19:13:46 +0000830 auto At = findCFILocation(B);
831 if (At.hasValue())
832 insertCFIInstructionsAt(B, At.getValue());
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000833 }
834}
835
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000836void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
837 MachineBasicBlock::iterator At) const {
838 MachineFunction &MF = *MBB.getParent();
Matthias Braun941a7052016-07-28 18:40:00 +0000839 MachineFrameInfo &MFI = MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000840 MachineModuleInfo &MMI = MF.getMMI();
841 auto &HST = MF.getSubtarget<HexagonSubtarget>();
842 auto &HII = *HST.getInstrInfo();
843 auto &HRI = *HST.getRegisterInfo();
844
845 // If CFI instructions have debug information attached, something goes
846 // wrong with the final assembly generation: the prolog_end is placed
847 // in a wrong location.
848 DebugLoc DL;
849 const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
850
851 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000852 bool HasFP = hasFP(MF);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000853
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000854 if (HasFP) {
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000855 unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
856 unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000857
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000858 // Define CFA via an offset from the value of FP.
859 //
860 // -8 -4 0 (SP)
861 // --+----+----+---------------------
862 // | FP | LR | increasing addresses -->
863 // --+----+----+---------------------
864 // | +-- Old SP (before allocframe)
865 // +-- New FP (after allocframe)
866 //
867 // MCCFIInstruction::createDefCfa subtracts the offset from the register.
868 // MCCFIInstruction::createOffset takes the offset without sign change.
869 auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
870 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000871 .addCFIIndex(MF.addFrameInst(DefCfa));
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000872 // R31 (return addr) = CFA - 4
873 auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
874 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000875 .addCFIIndex(MF.addFrameInst(OffR31));
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000876 // R30 (frame ptr) = CFA - 8
877 auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
878 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000879 .addCFIIndex(MF.addFrameInst(OffR30));
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000880 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000881
882 static unsigned int RegsToMove[] = {
883 Hexagon::R1, Hexagon::R0, Hexagon::R3, Hexagon::R2,
884 Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
885 Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
886 Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
887 Hexagon::D0, Hexagon::D1, Hexagon::D8, Hexagon::D9,
888 Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
889 Hexagon::NoRegister
890 };
891
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000892 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000893
894 for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
895 unsigned Reg = RegsToMove[i];
896 auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
897 return C.getReg() == Reg;
898 };
David Majnemer562e8292016-08-12 00:18:03 +0000899 auto F = find_if(CSI, IfR);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000900 if (F == CSI.end())
901 continue;
902
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000903 int64_t Offset;
904 if (HasFP) {
905 // If the function has a frame pointer (i.e. has an allocframe),
906 // then the CFA has been defined in terms of FP. Any offsets in
907 // the following CFI instructions have to be defined relative
908 // to FP, which points to the bottom of the stack frame.
909 // The function getFrameIndexReference can still choose to use SP
910 // for the offset calculation, so we cannot simply call it here.
911 // Instead, get the offset (relative to the FP) directly.
912 Offset = MFI.getObjectOffset(F->getFrameIdx());
913 } else {
914 unsigned FrameReg;
915 Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg);
916 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000917 // Subtract 8 to make room for R30 and R31, which are added above.
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000918 Offset -= 8;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000919
920 if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
921 unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
922 auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
923 Offset);
924 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000925 .addCFIIndex(MF.addFrameInst(OffReg));
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000926 } else {
927 // Split the double regs into subregs, and generate appropriate
928 // cfi_offsets.
929 // The only reason, we are split double regs is, llvm-mc does not
930 // understand paired registers for cfi_offset.
931 // Eg .cfi_offset r1:0, -64
932
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +0000933 unsigned HiReg = HRI.getSubReg(Reg, Hexagon::isub_hi);
934 unsigned LoReg = HRI.getSubReg(Reg, Hexagon::isub_lo);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000935 unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
936 unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
937 auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
938 Offset+4);
939 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000940 .addCFIIndex(MF.addFrameInst(OffHi));
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000941 auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
942 Offset);
943 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000944 .addCFIIndex(MF.addFrameInst(OffLo));
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000945 }
946 }
947}
948
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000949bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000950 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
951 return false;
952
Matthias Braun941a7052016-07-28 18:40:00 +0000953 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000954 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000955 bool HasExtraAlign = HRI.needsStackRealignment(MF);
956 bool HasAlloca = MFI.hasVarSizedObjects();
957
958 // Insert ALLOCFRAME if we need to or at -O0 for the debugger. Think
959 // that this shouldn't be required, but doing so now because gcc does and
960 // gdb can't break at the start of the function without it. Will remove if
961 // this turns out to be a gdb bug.
962 //
963 if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
964 return true;
965
966 // By default we want to use SP (since it's always there). FP requires
967 // some setup (i.e. ALLOCFRAME).
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000968 // Both, alloca and stack alignment modify the stack pointer by an
969 // undetermined value, so we need to save it at the entry to the function
970 // (i.e. use allocframe).
971 if (HasAlloca || HasExtraAlign)
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000972 return true;
973
974 if (MFI.getStackSize() > 0) {
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000975 // If FP-elimination is disabled, we have to use FP at this point.
976 const TargetMachine &TM = MF.getTarget();
977 if (TM.Options.DisableFramePointerElim(MF) || !EliminateFramePointer)
978 return true;
979 if (EnableStackOVFSanitizer)
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000980 return true;
981 }
982
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000983 const auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
984 if (MFI.hasCalls() || HMFI.hasClobberLR())
985 return true;
986
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000987 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000988}
989
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000990enum SpillKind {
991 SK_ToMem,
992 SK_FromMem,
993 SK_FromMemTailcall
994};
995
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000996static const char *getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType,
997 bool Stkchk = false) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000998 const char * V4SpillToMemoryFunctions[] = {
999 "__save_r16_through_r17",
1000 "__save_r16_through_r19",
1001 "__save_r16_through_r21",
1002 "__save_r16_through_r23",
1003 "__save_r16_through_r25",
1004 "__save_r16_through_r27" };
1005
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001006 const char * V4SpillToMemoryStkchkFunctions[] = {
1007 "__save_r16_through_r17_stkchk",
1008 "__save_r16_through_r19_stkchk",
1009 "__save_r16_through_r21_stkchk",
1010 "__save_r16_through_r23_stkchk",
1011 "__save_r16_through_r25_stkchk",
1012 "__save_r16_through_r27_stkchk" };
1013
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001014 const char * V4SpillFromMemoryFunctions[] = {
1015 "__restore_r16_through_r17_and_deallocframe",
1016 "__restore_r16_through_r19_and_deallocframe",
1017 "__restore_r16_through_r21_and_deallocframe",
1018 "__restore_r16_through_r23_and_deallocframe",
1019 "__restore_r16_through_r25_and_deallocframe",
1020 "__restore_r16_through_r27_and_deallocframe" };
1021
1022 const char * V4SpillFromMemoryTailcallFunctions[] = {
1023 "__restore_r16_through_r17_and_deallocframe_before_tailcall",
1024 "__restore_r16_through_r19_and_deallocframe_before_tailcall",
1025 "__restore_r16_through_r21_and_deallocframe_before_tailcall",
1026 "__restore_r16_through_r23_and_deallocframe_before_tailcall",
1027 "__restore_r16_through_r25_and_deallocframe_before_tailcall",
1028 "__restore_r16_through_r27_and_deallocframe_before_tailcall"
1029 };
1030
1031 const char **SpillFunc = nullptr;
1032
1033 switch(SpillType) {
1034 case SK_ToMem:
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001035 SpillFunc = Stkchk ? V4SpillToMemoryStkchkFunctions
1036 : V4SpillToMemoryFunctions;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001037 break;
1038 case SK_FromMem:
1039 SpillFunc = V4SpillFromMemoryFunctions;
1040 break;
1041 case SK_FromMemTailcall:
1042 SpillFunc = V4SpillFromMemoryTailcallFunctions;
1043 break;
1044 }
1045 assert(SpillFunc && "Unknown spill kind");
1046
1047 // Spill all callee-saved registers up to the highest register used.
1048 switch (MaxReg) {
1049 case Hexagon::R17:
1050 return SpillFunc[0];
1051 case Hexagon::R19:
1052 return SpillFunc[1];
1053 case Hexagon::R21:
1054 return SpillFunc[2];
1055 case Hexagon::R23:
1056 return SpillFunc[3];
1057 case Hexagon::R25:
1058 return SpillFunc[4];
1059 case Hexagon::R27:
1060 return SpillFunc[5];
1061 default:
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001062 llvm_unreachable("Unhandled maximum callee save register");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001063 }
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +00001064 return nullptr;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001065}
1066
James Y Knight5567baf2015-08-15 02:32:35 +00001067int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF,
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001068 int FI, unsigned &FrameReg) const {
Matthias Braun941a7052016-07-28 18:40:00 +00001069 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001070 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001071
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001072 int Offset = MFI.getObjectOffset(FI);
1073 bool HasAlloca = MFI.hasVarSizedObjects();
1074 bool HasExtraAlign = HRI.needsStackRealignment(MF);
1075 bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
James Y Knight5567baf2015-08-15 02:32:35 +00001076
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001077 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +00001078 unsigned FrameSize = MFI.getStackSize();
1079 unsigned SP = HRI.getStackRegister();
1080 unsigned FP = HRI.getFrameRegister();
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001081 unsigned AP = HMFI.getStackAlignBasePhysReg();
Krzysztof Parzyszek918e6d72017-06-26 14:17:58 +00001082 // It may happen that AP will be absent even HasAlloca && HasExtraAlign
1083 // is true. HasExtraAlign may be set because of vector spills, without
1084 // aligned locals or aligned outgoing function arguments. Since vector
1085 // spills will ultimately be "unaligned", it is safe to use FP as the
1086 // base register.
1087 // In fact, in such a scenario the stack is actually not required to be
1088 // aligned, although it may end up being aligned anyway, since this
1089 // particular case is not easily detectable. The alignment will be
1090 // unnecessary, but not incorrect.
1091 // Unfortunately there is no quick way to verify that the above is
1092 // indeed the case (and that it's not a result of an error), so just
1093 // assume that missing AP will be replaced by FP.
1094 // (A better fix would be to rematerialize AP from FP and always align
1095 // vector spills.)
1096 if (AP == 0)
1097 AP = FP;
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001098
1099 bool UseFP = false, UseAP = false; // Default: use SP (except at -O0).
1100 // Use FP at -O0, except when there are objects with extra alignment.
1101 // That additional alignment requirement may cause a pad to be inserted,
1102 // which will make it impossible to use FP to access objects located
1103 // past the pad.
1104 if (NoOpt && !HasExtraAlign)
1105 UseFP = true;
1106 if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
1107 // Fixed and preallocated objects will be located before any padding
1108 // so FP must be used to access them.
1109 UseFP |= (HasAlloca || HasExtraAlign);
1110 } else {
1111 if (HasAlloca) {
1112 if (HasExtraAlign)
1113 UseAP = true;
1114 else
1115 UseFP = true;
1116 }
1117 }
1118
1119 // If FP was picked, then there had better be FP.
1120 bool HasFP = hasFP(MF);
1121 assert((HasFP || !UseFP) && "This function must have frame pointer");
1122
1123 // Having FP implies allocframe. Allocframe will store extra 8 bytes:
1124 // FP/LR. If the base register is used to access an object across these
1125 // 8 bytes, then the offset will need to be adjusted by 8.
1126 //
1127 // After allocframe:
1128 // HexagonISelLowering adds 8 to ---+
1129 // the offsets of all stack-based |
1130 // arguments (*) |
1131 // |
1132 // getObjectOffset < 0 0 8 getObjectOffset >= 8
1133 // ------------------------+-----+------------------------> increasing
1134 // <local objects> |FP/LR| <input arguments> addresses
1135 // -----------------+------+-----+------------------------>
1136 // | |
1137 // SP/AP point --+ +-- FP points here (**)
1138 // somewhere on
1139 // this side of FP/LR
1140 //
1141 // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
1142 // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
1143
1144 // The lowering assumes that FP/LR is present, and so the offsets of
1145 // the formal arguments start at 8. If FP/LR is not there we need to
1146 // reduce the offset by 8.
1147 if (Offset > 0 && !HasFP)
1148 Offset -= 8;
1149
1150 if (UseFP)
1151 FrameReg = FP;
1152 else if (UseAP)
1153 FrameReg = AP;
1154 else
1155 FrameReg = SP;
1156
1157 // Calculate the actual offset in the instruction. If there is no FP
1158 // (in other words, no allocframe), then SP will not be adjusted (i.e.
1159 // there will be no SP -= FrameSize), so the frame size should not be
1160 // added to the calculated offset.
1161 int RealOffset = Offset;
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +00001162 if (!UseFP && !UseAP)
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001163 RealOffset = FrameSize+Offset;
1164 return RealOffset;
Jakob Stoklund Olesen0b97dbc2012-05-30 22:40:03 +00001165}
1166
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001167bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001168 const CSIVect &CSI, const HexagonRegisterInfo &HRI,
1169 bool &PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001170 if (CSI.empty())
1171 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001172
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001173 MachineBasicBlock::iterator MI = MBB.begin();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001174 PrologueStubs = false;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001175 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001176 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1177 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001178
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001179 if (useSpillFunction(MF, CSI)) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001180 PrologueStubs = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001181 unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001182 bool StkOvrFlowEnabled = EnableStackOVFSanitizer;
1183 const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem,
1184 StkOvrFlowEnabled);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001185 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
Rafael Espindolab1556c42016-06-28 20:13:36 +00001186 bool IsPIC = HTM.isPositionIndependent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001187 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001188
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001189 // Call spill function.
1190 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001191 unsigned SpillOpc;
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001192 if (StkOvrFlowEnabled) {
1193 if (LongCalls)
1194 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT_PIC
1195 : Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT;
1196 else
1197 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC
1198 : Hexagon::SAVE_REGISTERS_CALL_V4STK;
1199 } else {
1200 if (LongCalls)
1201 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_EXT_PIC
1202 : Hexagon::SAVE_REGISTERS_CALL_V4_EXT;
1203 else
1204 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
1205 : Hexagon::SAVE_REGISTERS_CALL_V4;
1206 }
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001207
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001208 MachineInstr *SaveRegsCall =
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001209 BuildMI(MBB, MI, DL, HII.get(SpillOpc))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001210 .addExternalSymbol(SpillFun);
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001211
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001212 // Add callee-saved registers as use.
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001213 addCalleeSaveRegistersAsImpOperand(SaveRegsCall, CSI, false, true);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001214 // Add live in registers.
1215 for (unsigned I = 0; I < CSI.size(); ++I)
1216 MBB.addLiveIn(CSI[I].getReg());
1217 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001218 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001219
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001220 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001221 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001222 // Add live in registers. We treat eh_return callee saved register r0 - r3
1223 // specially. They are not really callee saved registers as they are not
1224 // supposed to be killed.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001225 bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
1226 int FI = CSI[i].getFrameIdx();
1227 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001228 HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001229 if (IsKill)
1230 MBB.addLiveIn(Reg);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001231 }
1232 return true;
1233}
1234
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001235bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
1236 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
1237 if (CSI.empty())
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001238 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001239
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001240 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1241 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001242 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1243 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001244
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001245 if (useRestoreFunction(MF, CSI)) {
1246 bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
1247 unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
1248 SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
1249 const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001250 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
Rafael Espindolab1556c42016-06-28 20:13:36 +00001251 bool IsPIC = HTM.isPositionIndependent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001252 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001253
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001254 // Call spill function.
1255 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
1256 : MBB.getLastNonDebugInstr()->getDebugLoc();
1257 MachineInstr *DeallocCall = nullptr;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001258
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001259 if (HasTC) {
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001260 unsigned RetOpc;
1261 if (LongCalls)
1262 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC
1263 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT;
1264 else
1265 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
1266 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
1267 DeallocCall = BuildMI(MBB, MI, DL, HII.get(RetOpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001268 .addExternalSymbol(RestoreFn);
1269 } else {
1270 // The block has a return.
1271 MachineBasicBlock::iterator It = MBB.getFirstTerminator();
1272 assert(It->isReturn() && std::next(It) == MBB.end());
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001273 unsigned RetOpc;
1274 if (LongCalls)
1275 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC
1276 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT;
1277 else
1278 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
1279 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
1280 DeallocCall = BuildMI(MBB, It, DL, HII.get(RetOpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001281 .addExternalSymbol(RestoreFn);
1282 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +00001283 DeallocCall->copyImplicitOps(MF, *It);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001284 }
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001285 addCalleeSaveRegistersAsImpOperand(DeallocCall, CSI, true, false);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001286 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001287 }
1288
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001289 for (unsigned i = 0; i < CSI.size(); ++i) {
1290 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001291 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1292 int FI = CSI[i].getFrameIdx();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001293 HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001294 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001295
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001296 return true;
1297}
1298
Hans Wennborge1a2e902016-03-31 18:33:38 +00001299MachineBasicBlock::iterator HexagonFrameLowering::eliminateCallFramePseudoInstr(
1300 MachineFunction &MF, MachineBasicBlock &MBB,
1301 MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00001302 MachineInstr &MI = *I;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001303 unsigned Opc = MI.getOpcode();
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001304 (void)Opc; // Silence compiler warning.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001305 assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1306 "Cannot handle this call frame pseudo instruction");
Hans Wennborge1a2e902016-03-31 18:33:38 +00001307 return MBB.erase(I);
Eli Bendersky8da87162013-02-21 20:05:00 +00001308}
1309
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001310void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1311 MachineFunction &MF, RegScavenger *RS) const {
1312 // If this function has uses aligned stack and also has variable sized stack
1313 // objects, then we need to map all spill slots to fixed positions, so that
1314 // they can be accessed through FP. Otherwise they would have to be accessed
1315 // via AP, which may not be available at the particular place in the program.
Matthias Braun941a7052016-07-28 18:40:00 +00001316 MachineFrameInfo &MFI = MF.getFrameInfo();
1317 bool HasAlloca = MFI.hasVarSizedObjects();
1318 bool NeedsAlign = (MFI.getMaxAlignment() > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001319
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001320 if (!HasAlloca || !NeedsAlign)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001321 return;
1322
Matthias Braun941a7052016-07-28 18:40:00 +00001323 unsigned LFS = MFI.getLocalFrameSize();
1324 for (int i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
1325 if (!MFI.isSpillSlotObjectIndex(i) || MFI.isDeadObjectIndex(i))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001326 continue;
Matthias Braun941a7052016-07-28 18:40:00 +00001327 unsigned S = MFI.getObjectSize(i);
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001328 // Reduce the alignment to at most 8. This will require unaligned vector
1329 // stores if they happen here.
Matthias Braun941a7052016-07-28 18:40:00 +00001330 unsigned A = std::max(MFI.getObjectAlignment(i), 8U);
1331 MFI.setObjectAlignment(i, 8);
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001332 LFS = alignTo(LFS+S, A);
Matthias Braun941a7052016-07-28 18:40:00 +00001333 MFI.mapLocalFrameObject(i, -LFS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001334 }
1335
Matthias Braun941a7052016-07-28 18:40:00 +00001336 MFI.setLocalFrameSize(LFS);
1337 unsigned A = MFI.getLocalFrameMaxAlign();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001338 assert(A <= 8 && "Unexpected local frame alignment");
1339 if (A == 0)
Matthias Braun941a7052016-07-28 18:40:00 +00001340 MFI.setLocalFrameMaxAlign(8);
1341 MFI.setUseLocalStackAllocationBlock(true);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001342
1343 // Set the physical aligned-stack base address register.
1344 unsigned AP = 0;
1345 if (const MachineInstr *AI = getAlignaInstr(MF))
1346 AP = AI->getOperand(0).getReg();
1347 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1348 HMFI.setStackAlignBasePhysReg(AP);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001349}
1350
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001351/// Returns true if there are no caller-saved registers available in class RC.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001352static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001353 const HexagonRegisterInfo &HRI, const TargetRegisterClass *RC) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001354 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001355
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001356 auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1357 for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1358 if (MRI.isPhysRegUsed(*AI))
1359 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001360 return false;
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001361 };
1362
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001363 // Check for an unused caller-saved register. Callee-saved registers
1364 // have become pristine by now.
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001365 for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF, RC); *P; ++P)
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001366 if (!IsUsed(*P))
1367 return false;
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001368
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001369 // All caller-saved registers are used.
1370 return true;
1371}
1372
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001373#ifndef NDEBUG
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001374static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001375 dbgs() << '{';
1376 for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1377 unsigned R = x;
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001378 dbgs() << ' ' << printReg(R, &TRI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001379 }
1380 dbgs() << " }";
1381}
1382#endif
1383
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001384bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1385 const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
Reid Kleckner40d72302016-10-20 00:22:23 +00001386 DEBUG(dbgs() << __func__ << " on "
Krzysztof Parzyszeked75e7a2015-04-23 20:57:39 +00001387 << MF.getFunction()->getName() << '\n');
Matthias Braun941a7052016-07-28 18:40:00 +00001388 MachineFrameInfo &MFI = MF.getFrameInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001389 BitVector SRegs(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001390
1391 // Generate a set of unique, callee-saved registers (SRegs), where each
1392 // register in the set is maximal in terms of sub-/super-register relation,
1393 // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1394
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001395 // (1) For each callee-saved register, add that register and all of its
1396 // sub-registers to SRegs.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001397 DEBUG(dbgs() << "Initial CS registers: {");
1398 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1399 unsigned R = CSI[i].getReg();
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001400 DEBUG(dbgs() << ' ' << printReg(R, TRI));
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001401 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1402 SRegs[*SR] = true;
1403 }
1404 DEBUG(dbgs() << " }\n");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001405 DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001406
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001407 // (2) For each reserved register, remove that register and all of its
1408 // sub- and super-registers from SRegs.
1409 BitVector Reserved = TRI->getReservedRegs(MF);
1410 for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1411 unsigned R = x;
1412 for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1413 SRegs[*SR] = false;
1414 }
1415 DEBUG(dbgs() << "Res: "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1416 DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1417
1418 // (3) Collect all registers that have at least one sub-register in SRegs,
1419 // and also have no sub-registers that are reserved. These will be the can-
1420 // didates for saving as a whole instead of their individual sub-registers.
1421 // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1422 BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001423 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1424 unsigned R = x;
1425 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1426 TmpSup[*SR] = true;
1427 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001428 for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1429 unsigned R = x;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001430 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1431 if (!Reserved[*SR])
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001432 continue;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001433 TmpSup[R] = false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001434 break;
1435 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001436 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001437 DEBUG(dbgs() << "TmpSup: "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001438
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001439 // (4) Include all super-registers found in (3) into SRegs.
1440 SRegs |= TmpSup;
1441 DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001442
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001443 // (5) For each register R in SRegs, if any super-register of R is in SRegs,
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001444 // remove R from SRegs.
1445 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1446 unsigned R = x;
1447 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1448 if (!SRegs[*SR])
1449 continue;
1450 SRegs[R] = false;
1451 break;
1452 }
1453 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001454 DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001455
1456 // Now, for each register that has a fixed stack slot, create the stack
1457 // object for it.
1458 CSI.clear();
1459
Eugene Zelenkoe4fc6ee2017-07-26 23:20:35 +00001460 using SpillSlot = TargetFrameLowering::SpillSlot;
1461
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001462 unsigned NumFixed;
1463 int MinOffset = 0; // CS offsets are negative.
1464 const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1465 for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1466 if (!SRegs[S->Reg])
1467 continue;
1468 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001469 int FI = MFI.CreateFixedSpillStackObject(TRI->getSpillSize(*RC), S->Offset);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001470 MinOffset = std::min(MinOffset, S->Offset);
1471 CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1472 SRegs[S->Reg] = false;
1473 }
1474
1475 // There can be some registers that don't have fixed slots. For example,
1476 // we need to store R0-R3 in functions with exception handling. For each
1477 // such register, create a non-fixed stack object.
1478 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1479 unsigned R = x;
1480 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001481 unsigned Size = TRI->getSpillSize(*RC);
1482 int Off = MinOffset - Size;
1483 unsigned Align = std::min(TRI->getSpillAlignment(*RC), getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001484 assert(isPowerOf2_32(Align));
1485 Off &= -Align;
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001486 int FI = MFI.CreateFixedSpillStackObject(Size, Off);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001487 MinOffset = std::min(MinOffset, Off);
1488 CSI.push_back(CalleeSavedInfo(R, FI));
1489 SRegs[R] = false;
1490 }
1491
1492 DEBUG({
1493 dbgs() << "CS information: {";
1494 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1495 int FI = CSI[i].getFrameIdx();
Matthias Braun941a7052016-07-28 18:40:00 +00001496 int Off = MFI.getObjectOffset(FI);
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001497 dbgs() << ' ' << printReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001498 if (Off >= 0)
1499 dbgs() << '+';
1500 dbgs() << Off;
1501 }
1502 dbgs() << " }\n";
1503 });
1504
1505#ifndef NDEBUG
1506 // Verify that all registers were handled.
1507 bool MissedReg = false;
1508 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1509 unsigned R = x;
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001510 dbgs() << printReg(R, TRI) << ' ';
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001511 MissedReg = true;
1512 }
1513 if (MissedReg)
1514 llvm_unreachable("...there are unhandled callee-saved registers!");
1515#endif
1516
1517 return true;
1518}
1519
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001520bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1521 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1522 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1523 MachineInstr *MI = &*It;
1524 DebugLoc DL = MI->getDebugLoc();
1525 unsigned DstR = MI->getOperand(0).getReg();
1526 unsigned SrcR = MI->getOperand(1).getReg();
1527 if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1528 !Hexagon::ModRegsRegClass.contains(SrcR))
1529 return false;
1530
1531 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
Diana Picus116bbab2017-01-13 09:58:52 +00001532 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR).add(MI->getOperand(1));
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001533 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1534 .addReg(TmpR, RegState::Kill);
1535
1536 NewRegs.push_back(TmpR);
1537 B.erase(It);
1538 return true;
1539}
1540
1541bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1542 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1543 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1544 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001545 if (!MI->getOperand(0).isFI())
1546 return false;
1547
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001548 DebugLoc DL = MI->getDebugLoc();
1549 unsigned Opc = MI->getOpcode();
1550 unsigned SrcR = MI->getOperand(2).getReg();
1551 bool IsKill = MI->getOperand(2).isKill();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001552 int FI = MI->getOperand(0).getIndex();
1553
1554 // TmpR = C2_tfrpr SrcR if SrcR is a predicate register
1555 // TmpR = A2_tfrcrr SrcR if SrcR is a modifier register
1556 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1557 unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1558 : Hexagon::A2_tfrcrr;
1559 BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1560 .addReg(SrcR, getKillRegState(IsKill));
1561
1562 // S2_storeri_io FI, 0, TmpR
1563 BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1564 .addFrameIndex(FI)
1565 .addImm(0)
1566 .addReg(TmpR, RegState::Kill)
1567 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1568
1569 NewRegs.push_back(TmpR);
1570 B.erase(It);
1571 return true;
1572}
1573
1574bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1575 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1576 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1577 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001578 if (!MI->getOperand(1).isFI())
1579 return false;
1580
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001581 DebugLoc DL = MI->getDebugLoc();
1582 unsigned Opc = MI->getOpcode();
1583 unsigned DstR = MI->getOperand(0).getReg();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001584 int FI = MI->getOperand(1).getIndex();
1585
1586 // TmpR = L2_loadri_io FI, 0
1587 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1588 BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1589 .addFrameIndex(FI)
1590 .addImm(0)
1591 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1592
1593 // DstR = C2_tfrrp TmpR if DstR is a predicate register
1594 // DstR = A2_tfrrcr TmpR if DstR is a modifier register
1595 unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1596 : Hexagon::A2_tfrrcr;
1597 BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1598 .addReg(TmpR, RegState::Kill);
1599
1600 NewRegs.push_back(TmpR);
1601 B.erase(It);
1602 return true;
1603}
1604
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001605bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1606 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1607 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001608 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001609 if (!MI->getOperand(0).isFI())
1610 return false;
1611
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001612 DebugLoc DL = MI->getDebugLoc();
1613 unsigned SrcR = MI->getOperand(2).getReg();
1614 bool IsKill = MI->getOperand(2).isKill();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001615 int FI = MI->getOperand(0).getIndex();
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001616 auto *RC = &Hexagon::HvxVRRegClass;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001617
1618 // Insert transfer to general vector register.
1619 // TmpR0 = A2_tfrsi 0x01010101
1620 // TmpR1 = V6_vandqrt Qx, TmpR0
1621 // store FI, 0, TmpR1
1622 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1623 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1624
1625 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1626 .addImm(0x01010101);
1627
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001628 BuildMI(B, It, DL, HII.get(Hexagon::V6_vandqrt), TmpR1)
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001629 .addReg(SrcR, getKillRegState(IsKill))
1630 .addReg(TmpR0, RegState::Kill);
1631
1632 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1633 HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1634 expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1635
1636 NewRegs.push_back(TmpR0);
1637 NewRegs.push_back(TmpR1);
1638 B.erase(It);
1639 return true;
1640}
1641
1642bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1643 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1644 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001645 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001646 if (!MI->getOperand(1).isFI())
1647 return false;
1648
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001649 DebugLoc DL = MI->getDebugLoc();
1650 unsigned DstR = MI->getOperand(0).getReg();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001651 int FI = MI->getOperand(1).getIndex();
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001652 auto *RC = &Hexagon::HvxVRRegClass;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001653
1654 // TmpR0 = A2_tfrsi 0x01010101
1655 // TmpR1 = load FI, 0
1656 // DstR = V6_vandvrt TmpR1, TmpR0
1657 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1658 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1659
1660 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1661 .addImm(0x01010101);
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001662 MachineFunction &MF = *B.getParent();
1663 auto *HRI = MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001664 HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1665 expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1666
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001667 BuildMI(B, It, DL, HII.get(Hexagon::V6_vandvrt), DstR)
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001668 .addReg(TmpR1, RegState::Kill)
1669 .addReg(TmpR0, RegState::Kill);
1670
1671 NewRegs.push_back(TmpR0);
1672 NewRegs.push_back(TmpR1);
1673 B.erase(It);
1674 return true;
1675}
1676
1677bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1678 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1679 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1680 MachineFunction &MF = *B.getParent();
Matthias Braun941a7052016-07-28 18:40:00 +00001681 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001682 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1683 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001684 if (!MI->getOperand(0).isFI())
1685 return false;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001686
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001687 // It is possible that the double vector being stored is only partially
1688 // defined. From the point of view of the liveness tracking, it is ok to
1689 // store it as a whole, but if we break it up we may end up storing a
1690 // register that is entirely undefined.
Matthias Braunac4307c2017-05-26 21:51:00 +00001691 LivePhysRegs LPR(HRI);
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001692 LPR.addLiveIns(B);
1693 SmallVector<std::pair<unsigned, const MachineOperand*>,2> Clobbers;
Krzysztof Parzyszek954dd8d2017-01-18 23:11:40 +00001694 for (auto R = B.begin(); R != It; ++R) {
1695 Clobbers.clear();
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001696 LPR.stepForward(*R, Clobbers);
Krzysztof Parzyszek954dd8d2017-01-18 23:11:40 +00001697 // Dead defs are recorded in Clobbers, but are not automatically removed
1698 // from the live set.
1699 for (auto &C : Clobbers)
Krzysztof Parzyszek1aaf41a2017-02-17 22:14:51 +00001700 if (C.second->isReg() && C.second->isDead())
Krzysztof Parzyszek954dd8d2017-01-18 23:11:40 +00001701 LPR.removeReg(C.first);
1702 }
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001703
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001704 DebugLoc DL = MI->getDebugLoc();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001705 unsigned SrcR = MI->getOperand(2).getReg();
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +00001706 unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::vsub_lo);
1707 unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::vsub_hi);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001708 bool IsKill = MI->getOperand(2).isKill();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001709 int FI = MI->getOperand(0).getIndex();
1710
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001711 unsigned Size = HRI.getSpillSize(Hexagon::HvxVRRegClass);
1712 unsigned NeedAlign = HRI.getSpillAlignment(Hexagon::HvxVRRegClass);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001713 unsigned HasAlign = MFI.getObjectAlignment(FI);
1714 unsigned StoreOpc;
1715
1716 // Store low part.
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001717 if (LPR.contains(SrcLo)) {
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001718 StoreOpc = NeedAlign <= HasAlign ? Hexagon::V6_vS32b_ai
1719 : Hexagon::V6_vS32Ub_ai;
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001720 BuildMI(B, It, DL, HII.get(StoreOpc))
1721 .addFrameIndex(FI)
1722 .addImm(0)
1723 .addReg(SrcLo, getKillRegState(IsKill))
1724 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1725 }
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001726
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001727 // Store high part.
1728 if (LPR.contains(SrcHi)) {
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001729 StoreOpc = NeedAlign <= MinAlign(HasAlign, Size) ? Hexagon::V6_vS32b_ai
1730 : Hexagon::V6_vS32Ub_ai;
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001731 BuildMI(B, It, DL, HII.get(StoreOpc))
1732 .addFrameIndex(FI)
1733 .addImm(Size)
1734 .addReg(SrcHi, getKillRegState(IsKill))
1735 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1736 }
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001737
1738 B.erase(It);
1739 return true;
1740}
1741
1742bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1743 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1744 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1745 MachineFunction &MF = *B.getParent();
Matthias Braun941a7052016-07-28 18:40:00 +00001746 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001747 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1748 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001749 if (!MI->getOperand(1).isFI())
1750 return false;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001751
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001752 DebugLoc DL = MI->getDebugLoc();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001753 unsigned DstR = MI->getOperand(0).getReg();
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +00001754 unsigned DstHi = HRI.getSubReg(DstR, Hexagon::vsub_hi);
1755 unsigned DstLo = HRI.getSubReg(DstR, Hexagon::vsub_lo);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001756 int FI = MI->getOperand(1).getIndex();
1757
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001758 unsigned Size = HRI.getSpillSize(Hexagon::HvxVRRegClass);
1759 unsigned NeedAlign = HRI.getSpillAlignment(Hexagon::HvxVRRegClass);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001760 unsigned HasAlign = MFI.getObjectAlignment(FI);
1761 unsigned LoadOpc;
1762
1763 // Load low part.
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001764 LoadOpc = NeedAlign <= HasAlign ? Hexagon::V6_vL32b_ai
1765 : Hexagon::V6_vL32Ub_ai;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001766 BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1767 .addFrameIndex(FI)
1768 .addImm(0)
1769 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1770
1771 // Load high part.
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001772 LoadOpc = NeedAlign <= MinAlign(HasAlign, Size) ? Hexagon::V6_vL32b_ai
1773 : Hexagon::V6_vL32Ub_ai;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001774 BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1775 .addFrameIndex(FI)
1776 .addImm(Size)
1777 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1778
1779 B.erase(It);
1780 return true;
1781}
1782
1783bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1784 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1785 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1786 MachineFunction &MF = *B.getParent();
Matthias Braun941a7052016-07-28 18:40:00 +00001787 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001788 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001789 if (!MI->getOperand(0).isFI())
1790 return false;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001791
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001792 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001793 DebugLoc DL = MI->getDebugLoc();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001794 unsigned SrcR = MI->getOperand(2).getReg();
1795 bool IsKill = MI->getOperand(2).isKill();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001796 int FI = MI->getOperand(0).getIndex();
1797
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001798 unsigned NeedAlign = HRI.getSpillAlignment(Hexagon::HvxVRRegClass);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001799 unsigned HasAlign = MFI.getObjectAlignment(FI);
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001800 unsigned StoreOpc = NeedAlign <= HasAlign ? Hexagon::V6_vS32b_ai
1801 : Hexagon::V6_vS32Ub_ai;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001802 BuildMI(B, It, DL, HII.get(StoreOpc))
1803 .addFrameIndex(FI)
1804 .addImm(0)
1805 .addReg(SrcR, getKillRegState(IsKill))
1806 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1807
1808 B.erase(It);
1809 return true;
1810}
1811
1812bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
1813 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1814 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1815 MachineFunction &MF = *B.getParent();
Matthias Braun941a7052016-07-28 18:40:00 +00001816 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001817 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001818 if (!MI->getOperand(1).isFI())
1819 return false;
1820
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001821 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001822 DebugLoc DL = MI->getDebugLoc();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001823 unsigned DstR = MI->getOperand(0).getReg();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001824 int FI = MI->getOperand(1).getIndex();
1825
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001826 unsigned NeedAlign = HRI.getSpillAlignment(Hexagon::HvxVRRegClass);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001827 unsigned HasAlign = MFI.getObjectAlignment(FI);
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001828 unsigned LoadOpc = NeedAlign <= HasAlign ? Hexagon::V6_vL32b_ai
1829 : Hexagon::V6_vL32Ub_ai;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001830 BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1831 .addFrameIndex(FI)
1832 .addImm(0)
1833 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1834
1835 B.erase(It);
1836 return true;
1837}
1838
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001839bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1840 SmallVectorImpl<unsigned> &NewRegs) const {
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001841 auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001842 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001843 bool Changed = false;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001844
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001845 for (auto &B : MF) {
1846 // Traverse the basic block.
1847 MachineBasicBlock::iterator NextI;
1848 for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1849 MachineInstr *MI = &*I;
1850 NextI = std::next(I);
1851 unsigned Opc = MI->getOpcode();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001852
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001853 switch (Opc) {
1854 case TargetOpcode::COPY:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001855 Changed |= expandCopy(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001856 break;
1857 case Hexagon::STriw_pred:
1858 case Hexagon::STriw_mod:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001859 Changed |= expandStoreInt(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001860 break;
1861 case Hexagon::LDriw_pred:
1862 case Hexagon::LDriw_mod:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001863 Changed |= expandLoadInt(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001864 break;
Krzysztof Parzyszek17aa4132016-08-16 15:43:54 +00001865 case Hexagon::PS_vstorerq_ai:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001866 Changed |= expandStoreVecPred(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001867 break;
Krzysztof Parzyszek17aa4132016-08-16 15:43:54 +00001868 case Hexagon::PS_vloadrq_ai:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001869 Changed |= expandLoadVecPred(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001870 break;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001871 case Hexagon::PS_vloadrw_ai:
1872 case Hexagon::PS_vloadrwu_ai:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001873 Changed |= expandLoadVec2(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001874 break;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001875 case Hexagon::PS_vstorerw_ai:
1876 case Hexagon::PS_vstorerwu_ai:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001877 Changed |= expandStoreVec2(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001878 break;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001879 }
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001880 }
1881 }
1882
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001883 return Changed;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001884}
1885
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001886void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1887 BitVector &SavedRegs,
1888 RegScavenger *RS) const {
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001889 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001890
1891 SavedRegs.resize(HRI.getNumRegs());
1892
1893 // If we have a function containing __builtin_eh_return we want to spill and
1894 // restore all callee saved registers. Pretend that they are used.
1895 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1896 for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1897 SavedRegs.set(*R);
1898
1899 // Replace predicate register pseudo spill code.
1900 SmallVector<unsigned,8> NewRegs;
1901 expandSpillMacros(MF, NewRegs);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001902 if (OptimizeSpillSlots && !isOptNone(MF))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001903 optimizeSpillSlots(MF, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001904
1905 // We need to reserve a a spill slot if scavenging could potentially require
1906 // spilling a scavenged register.
Krzysztof Parzyszekddafa2c2016-08-01 17:15:30 +00001907 if (!NewRegs.empty() || mayOverflowFrameOffset(MF)) {
Matthias Braun941a7052016-07-28 18:40:00 +00001908 MachineFrameInfo &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001909 MachineRegisterInfo &MRI = MF.getRegInfo();
1910 SetVector<const TargetRegisterClass*> SpillRCs;
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001911 // Reserve an int register in any case, because it could be used to hold
1912 // the stack offset in case it does not fit into a spill instruction.
1913 SpillRCs.insert(&Hexagon::IntRegsRegClass);
1914
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001915 for (unsigned VR : NewRegs)
1916 SpillRCs.insert(MRI.getRegClass(VR));
1917
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001918 for (auto *RC : SpillRCs) {
1919 if (!needToReserveScavengingSpillSlots(MF, HRI, RC))
1920 continue;
1921 unsigned Num = RC == &Hexagon::IntRegsRegClass ? NumberScavengerSlots : 1;
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001922 unsigned S = HRI.getSpillSize(*RC), A = HRI.getSpillAlignment(*RC);
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001923 for (unsigned i = 0; i < Num; i++) {
1924 int NewFI = MFI.CreateSpillStackObject(S, A);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001925 RS->addScavengingFrameIndex(NewFI);
1926 }
1927 }
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001928 }
1929
1930 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1931}
1932
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001933unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1934 HexagonBlockRanges::IndexRange &FIR,
1935 HexagonBlockRanges::InstrIndexMap &IndexMap,
1936 HexagonBlockRanges::RegToRangeMap &DeadMap,
1937 const TargetRegisterClass *RC) const {
1938 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1939 auto &MRI = MF.getRegInfo();
1940
1941 auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1942 auto F = DeadMap.find({Reg,0});
1943 if (F == DeadMap.end())
1944 return false;
1945 for (auto &DR : F->second)
1946 if (DR.contains(FIR))
1947 return true;
1948 return false;
1949 };
1950
1951 for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
1952 bool Dead = true;
1953 for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
1954 if (isDead(R.Reg))
1955 continue;
1956 Dead = false;
1957 break;
1958 }
1959 if (Dead)
1960 return Reg;
1961 }
1962 return 0;
1963}
1964
1965void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
1966 SmallVectorImpl<unsigned> &VRegs) const {
1967 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1968 auto &HII = *HST.getInstrInfo();
1969 auto &HRI = *HST.getRegisterInfo();
1970 auto &MRI = MF.getRegInfo();
1971 HexagonBlockRanges HBR(MF);
1972
Eugene Zelenkoe4fc6ee2017-07-26 23:20:35 +00001973 using BlockIndexMap =
1974 std::map<MachineBasicBlock *, HexagonBlockRanges::InstrIndexMap>;
1975 using BlockRangeMap =
1976 std::map<MachineBasicBlock *, HexagonBlockRanges::RangeList>;
1977 using IndexType = HexagonBlockRanges::IndexType;
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001978
1979 struct SlotInfo {
1980 BlockRangeMap Map;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +00001981 unsigned Size = 0;
1982 const TargetRegisterClass *RC = nullptr;
NAKAMURA Takumic2cc8702016-02-13 07:29:49 +00001983
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +00001984 SlotInfo() = default;
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001985 };
1986
1987 BlockIndexMap BlockIndexes;
1988 SmallSet<int,4> BadFIs;
1989 std::map<int,SlotInfo> FIRangeMap;
1990
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001991 // Accumulate register classes: get a common class for a pre-existing
1992 // class HaveRC and a new class NewRC. Return nullptr if a common class
1993 // cannot be found, otherwise return the resulting class. If HaveRC is
1994 // nullptr, assume that it is still unset.
Malcolm Parsons17d266b2017-01-13 17:12:16 +00001995 auto getCommonRC =
1996 [](const TargetRegisterClass *HaveRC,
1997 const TargetRegisterClass *NewRC) -> const TargetRegisterClass * {
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001998 if (HaveRC == nullptr || HaveRC == NewRC)
1999 return NewRC;
2000 // Different classes, both non-null. Pick the more general one.
2001 if (HaveRC->hasSubClassEq(NewRC))
2002 return HaveRC;
2003 if (NewRC->hasSubClassEq(HaveRC))
2004 return NewRC;
2005 return nullptr;
2006 };
2007
2008 // Scan all blocks in the function. Check all occurrences of frame indexes,
2009 // and collect relevant information.
2010 for (auto &B : MF) {
2011 std::map<int,IndexType> LastStore, LastLoad;
Krzysztof Parzyszek280a50e2016-02-13 14:06:01 +00002012 // Emplace appears not to be supported in gcc 4.7.2-4.
2013 //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
Krzysztof Parzyszekde697d42016-02-17 15:02:07 +00002014 auto P = BlockIndexes.insert(
2015 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002016 auto &IndexMap = P.first->second;
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00002017 DEBUG(dbgs() << "Index map for " << printMBBReference(B) << "\n"
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002018 << IndexMap << '\n');
2019
2020 for (auto &In : B) {
2021 int LFI, SFI;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00002022 bool Load = HII.isLoadFromStackSlot(In, LFI) && !HII.isPredicated(In);
2023 bool Store = HII.isStoreToStackSlot(In, SFI) && !HII.isPredicated(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002024 if (Load && Store) {
2025 // If it's both a load and a store, then we won't handle it.
2026 BadFIs.insert(LFI);
2027 BadFIs.insert(SFI);
2028 continue;
2029 }
2030 // Check for register classes of the register used as the source for
2031 // the store, and the register used as the destination for the load.
2032 // Also, only accept base+imm_offset addressing modes. Other addressing
2033 // modes can have side-effects (post-increments, etc.). For stack
2034 // slots they are very unlikely, so there is not much loss due to
2035 // this restriction.
2036 if (Load || Store) {
2037 int TFI = Load ? LFI : SFI;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002038 unsigned AM = HII.getAddrMode(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002039 SlotInfo &SI = FIRangeMap[TFI];
2040 bool Bad = (AM != HexagonII::BaseImmOffset);
2041 if (!Bad) {
2042 // If the addressing mode is ok, check the register class.
Krzysztof Parzyszek5241b8e2016-07-27 20:50:42 +00002043 unsigned OpNum = Load ? 0 : 2;
2044 auto *RC = HII.getRegClass(In.getDesc(), OpNum, &HRI, MF);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002045 RC = getCommonRC(SI.RC, RC);
2046 if (RC == nullptr)
2047 Bad = true;
2048 else
2049 SI.RC = RC;
2050 }
2051 if (!Bad) {
2052 // Check sizes.
Krzysztof Parzyszek473d02d2017-09-14 12:06:40 +00002053 unsigned S = HII.getMemAccessSize(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002054 if (SI.Size != 0 && SI.Size != S)
2055 Bad = true;
2056 else
2057 SI.Size = S;
2058 }
Krzysztof Parzyszek5241b8e2016-07-27 20:50:42 +00002059 if (!Bad) {
2060 for (auto *Mo : In.memoperands()) {
2061 if (!Mo->isVolatile())
2062 continue;
2063 Bad = true;
2064 break;
2065 }
2066 }
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002067 if (Bad)
2068 BadFIs.insert(TFI);
2069 }
2070
2071 // Locate uses of frame indices.
2072 for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
2073 const MachineOperand &Op = In.getOperand(i);
2074 if (!Op.isFI())
2075 continue;
2076 int FI = Op.getIndex();
2077 // Make sure that the following operand is an immediate and that
2078 // it is 0. This is the offset in the stack object.
2079 if (i+1 >= n || !In.getOperand(i+1).isImm() ||
2080 In.getOperand(i+1).getImm() != 0)
2081 BadFIs.insert(FI);
2082 if (BadFIs.count(FI))
2083 continue;
2084
2085 IndexType Index = IndexMap.getIndex(&In);
2086 if (Load) {
2087 if (LastStore[FI] == IndexType::None)
2088 LastStore[FI] = IndexType::Entry;
2089 LastLoad[FI] = Index;
2090 } else if (Store) {
2091 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2092 if (LastStore[FI] != IndexType::None)
2093 RL.add(LastStore[FI], LastLoad[FI], false, false);
2094 else if (LastLoad[FI] != IndexType::None)
2095 RL.add(IndexType::Entry, LastLoad[FI], false, false);
2096 LastLoad[FI] = IndexType::None;
2097 LastStore[FI] = Index;
2098 } else {
2099 BadFIs.insert(FI);
2100 }
2101 }
2102 }
2103
2104 for (auto &I : LastLoad) {
2105 IndexType LL = I.second;
2106 if (LL == IndexType::None)
2107 continue;
2108 auto &RL = FIRangeMap[I.first].Map[&B];
2109 IndexType &LS = LastStore[I.first];
2110 if (LS != IndexType::None)
2111 RL.add(LS, LL, false, false);
2112 else
2113 RL.add(IndexType::Entry, LL, false, false);
2114 LS = IndexType::None;
2115 }
2116 for (auto &I : LastStore) {
2117 IndexType LS = I.second;
2118 if (LS == IndexType::None)
2119 continue;
2120 auto &RL = FIRangeMap[I.first].Map[&B];
2121 RL.add(LS, IndexType::None, false, false);
2122 }
2123 }
2124
2125 DEBUG({
2126 for (auto &P : FIRangeMap) {
2127 dbgs() << "fi#" << P.first;
2128 if (BadFIs.count(P.first))
2129 dbgs() << " (bad)";
2130 dbgs() << " RC: ";
2131 if (P.second.RC != nullptr)
2132 dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
2133 else
2134 dbgs() << "<null>\n";
2135 for (auto &R : P.second.Map)
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00002136 dbgs() << " " << printMBBReference(*R.first) << " { " << R.second
2137 << "}\n";
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002138 }
2139 });
2140
2141 // When a slot is loaded from in a block without being stored to in the
2142 // same block, it is live-on-entry to this block. To avoid CFG analysis,
2143 // consider this slot to be live-on-exit from all blocks.
2144 SmallSet<int,4> LoxFIs;
2145
2146 std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
2147
2148 for (auto &P : FIRangeMap) {
2149 // P = pair(FI, map: BB->RangeList)
2150 if (BadFIs.count(P.first))
2151 continue;
2152 for (auto &B : MF) {
2153 auto F = P.second.Map.find(&B);
2154 // F = pair(BB, RangeList)
2155 if (F == P.second.Map.end() || F->second.empty())
2156 continue;
2157 HexagonBlockRanges::IndexRange &IR = F->second.front();
2158 if (IR.start() == IndexType::Entry)
2159 LoxFIs.insert(P.first);
2160 BlockFIMap[&B].push_back(P.first);
2161 }
2162 }
2163
2164 DEBUG({
2165 dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
2166 for (auto &P : BlockFIMap) {
2167 auto &FIs = P.second;
2168 if (FIs.empty())
2169 continue;
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00002170 dbgs() << " " << printMBBReference(*P.first) << ": {";
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002171 for (auto I : FIs) {
2172 dbgs() << " fi#" << I;
2173 if (LoxFIs.count(I))
2174 dbgs() << '*';
2175 }
2176 dbgs() << " }\n";
2177 }
2178 });
2179
Krzysztof Parzyszekdc421642016-07-27 20:58:43 +00002180#ifndef NDEBUG
2181 bool HasOptLimit = SpillOptMax.getPosition();
2182#endif
2183
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002184 // eliminate loads, when all loads eliminated, eliminate all stores.
2185 for (auto &B : MF) {
2186 auto F = BlockIndexes.find(&B);
2187 assert(F != BlockIndexes.end());
2188 HexagonBlockRanges::InstrIndexMap &IM = F->second;
2189 HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
2190 HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00002191 DEBUG(dbgs() << printMBBReference(B) << " dead map\n"
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002192 << HexagonBlockRanges::PrintRangeMap(DM, HRI));
2193
2194 for (auto FI : BlockFIMap[&B]) {
2195 if (BadFIs.count(FI))
2196 continue;
2197 DEBUG(dbgs() << "Working on fi#" << FI << '\n');
2198 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2199 for (auto &Range : RL) {
2200 DEBUG(dbgs() << "--Examining range:" << RL << '\n');
2201 if (!IndexType::isInstr(Range.start()) ||
2202 !IndexType::isInstr(Range.end()))
2203 continue;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002204 MachineInstr &SI = *IM.getInstr(Range.start());
2205 MachineInstr &EI = *IM.getInstr(Range.end());
2206 assert(SI.mayStore() && "Unexpected start instruction");
2207 assert(EI.mayLoad() && "Unexpected end instruction");
2208 MachineOperand &SrcOp = SI.getOperand(2);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002209
2210 HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
2211 SrcOp.getSubReg() };
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002212 auto *RC = HII.getRegClass(SI.getDesc(), 2, &HRI, MF);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002213 // The this-> is needed to unconfuse MSVC.
2214 unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00002215 DEBUG(dbgs() << "Replacement reg:" << printReg(FoundR, &HRI) << '\n');
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002216 if (FoundR == 0)
2217 continue;
Krzysztof Parzyszekdc421642016-07-27 20:58:43 +00002218#ifndef NDEBUG
2219 if (HasOptLimit) {
2220 if (SpillOptCount >= SpillOptMax)
2221 return;
2222 SpillOptCount++;
2223 }
2224#endif
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002225
2226 // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002227 MachineBasicBlock::iterator StartIt = SI.getIterator(), NextIt;
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002228 MachineInstr *CopyIn = nullptr;
2229 if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002230 const DebugLoc &DL = SI.getDebugLoc();
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002231 CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
Diana Picus116bbab2017-01-13 09:58:52 +00002232 .add(SrcOp);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002233 }
2234
2235 ++StartIt;
2236 // Check if this is a last store and the FI is live-on-exit.
2237 if (LoxFIs.count(FI) && (&Range == &RL.back())) {
2238 // Update store's source register.
2239 if (unsigned SR = SrcOp.getSubReg())
2240 SrcOp.setReg(HRI.getSubReg(FoundR, SR));
2241 else
2242 SrcOp.setReg(FoundR);
2243 SrcOp.setSubReg(0);
2244 // We are keeping this register live.
2245 SrcOp.setIsKill(false);
2246 } else {
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002247 B.erase(&SI);
2248 IM.replaceInstr(&SI, CopyIn);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002249 }
2250
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002251 auto EndIt = std::next(EI.getIterator());
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002252 for (auto It = StartIt; It != EndIt; It = NextIt) {
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002253 MachineInstr &MI = *It;
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002254 NextIt = std::next(It);
2255 int TFI;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002256 if (!HII.isLoadFromStackSlot(MI, TFI) || TFI != FI)
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002257 continue;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002258 unsigned DstR = MI.getOperand(0).getReg();
2259 assert(MI.getOperand(0).getSubReg() == 0);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002260 MachineInstr *CopyOut = nullptr;
2261 if (DstR != FoundR) {
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002262 DebugLoc DL = MI.getDebugLoc();
Krzysztof Parzyszek473d02d2017-09-14 12:06:40 +00002263 unsigned MemSize = HII.getMemAccessSize(MI);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002264 assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2265 unsigned CopyOpc = TargetOpcode::COPY;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002266 if (HII.isSignExtendingLoad(MI))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002267 CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002268 else if (HII.isZeroExtendingLoad(MI))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002269 CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2270 CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002271 .addReg(FoundR, getKillRegState(&MI == &EI));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002272 }
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002273 IM.replaceInstr(&MI, CopyOut);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002274 B.erase(It);
2275 }
2276
2277 // Update the dead map.
2278 HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2279 for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2280 DM[RR].subtract(Range);
2281 } // for Range in range list
2282 }
2283 }
2284}
2285
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002286void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002287 const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002288 MachineBasicBlock &MB = *AI->getParent();
2289 DebugLoc DL = AI->getDebugLoc();
2290 unsigned A = AI->getOperand(2).getImm();
2291
2292 // Have
2293 // Rd = alloca Rs, #A
2294 //
2295 // If Rs and Rd are different registers, use this sequence:
2296 // Rd = sub(r29, Rs)
2297 // r29 = sub(r29, Rs)
2298 // Rd = and(Rd, #-A) ; if necessary
2299 // r29 = and(r29, #-A) ; if necessary
2300 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2301 // otherwise, do
2302 // Rd = sub(r29, Rs)
2303 // Rd = and(Rd, #-A) ; if necessary
2304 // r29 = Rd
2305 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2306
2307 MachineOperand &RdOp = AI->getOperand(0);
2308 MachineOperand &RsOp = AI->getOperand(1);
2309 unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2310
2311 // Rd = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002312 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002313 .addReg(SP)
2314 .addReg(Rs);
2315 if (Rs != Rd) {
2316 // r29 = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002317 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002318 .addReg(SP)
2319 .addReg(Rs);
2320 }
2321 if (A > 8) {
2322 // Rd = and(Rd, #-A)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002323 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002324 .addReg(Rd)
2325 .addImm(-int64_t(A));
2326 if (Rs != Rd)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002327 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002328 .addReg(SP)
2329 .addImm(-int64_t(A));
2330 }
2331 if (Rs == Rd) {
2332 // r29 = Rd
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002333 BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002334 .addReg(Rd);
2335 }
2336 if (CF > 0) {
2337 // Rd = add(Rd, #CF)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002338 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002339 .addReg(Rd)
2340 .addImm(CF);
2341 }
2342}
2343
2344bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +00002345 const MachineFrameInfo &MFI = MF.getFrameInfo();
2346 if (!MFI.hasVarSizedObjects())
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002347 return false;
Krzysztof Parzyszek71702172017-06-23 19:47:04 +00002348 unsigned MaxA = MFI.getMaxAlignment();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002349 if (MaxA <= getStackAlignment())
2350 return false;
2351 return true;
2352}
2353
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00002354const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2355 const MachineFunction &MF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002356 for (auto &B : MF)
2357 for (auto &I : B)
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +00002358 if (I.getOpcode() == Hexagon::PS_aligna)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002359 return &I;
2360 return nullptr;
2361}
2362
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00002363/// Adds all callee-saved registers as implicit uses or defs to the
2364/// instruction.
2365void HexagonFrameLowering::addCalleeSaveRegistersAsImpOperand(MachineInstr *MI,
2366 const CSIVect &CSI, bool IsDef, bool IsKill) const {
2367 // Add the callee-saved registers as implicit uses.
2368 for (auto &R : CSI)
2369 MI->addOperand(MachineOperand::CreateReg(R.getReg(), IsDef, true, IsKill));
2370}
2371
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002372/// Determine whether the callee-saved register saves and restores should
2373/// be generated via inline code. If this function returns "true", inline
2374/// code will be generated. If this function returns "false", additional
2375/// checks are performed, which may still lead to the inline code.
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +00002376bool HexagonFrameLowering::shouldInlineCSR(const MachineFunction &MF,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002377 const CSIVect &CSI) const {
2378 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2379 return true;
Krzysztof Parzyszekf67cd822017-07-11 17:11:54 +00002380 if (!hasFP(MF))
2381 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002382 if (!isOptSize(MF) && !isMinSize(MF))
2383 if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2384 return true;
2385
2386 // Check if CSI only has double registers, and if the registers form
2387 // a contiguous block starting from D8.
2388 BitVector Regs(Hexagon::NUM_TARGET_REGS);
2389 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2390 unsigned R = CSI[i].getReg();
2391 if (!Hexagon::DoubleRegsRegClass.contains(R))
2392 return true;
2393 Regs[R] = true;
2394 }
2395 int F = Regs.find_first();
2396 if (F != Hexagon::D8)
2397 return true;
2398 while (F >= 0) {
2399 int N = Regs.find_next(F);
2400 if (N >= 0 && N != F+1)
2401 return true;
2402 F = N;
2403 }
2404
2405 return false;
2406}
2407
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +00002408bool HexagonFrameLowering::useSpillFunction(const MachineFunction &MF,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002409 const CSIVect &CSI) const {
2410 if (shouldInlineCSR(MF, CSI))
2411 return false;
2412 unsigned NumCSI = CSI.size();
2413 if (NumCSI <= 1)
2414 return false;
2415
2416 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2417 : SpillFuncThreshold;
2418 return Threshold < NumCSI;
2419}
2420
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +00002421bool HexagonFrameLowering::useRestoreFunction(const MachineFunction &MF,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002422 const CSIVect &CSI) const {
2423 if (shouldInlineCSR(MF, CSI))
2424 return false;
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002425 // The restore functions do a bit more than just restoring registers.
2426 // The non-returning versions will go back directly to the caller's
2427 // caller, others will clean up the stack frame in preparation for
2428 // a tail call. Using them can still save code size even if only one
2429 // register is getting restores. Make the decision based on -Oz:
2430 // using -Os will use inline restore for a single register.
2431 if (isMinSize(MF))
2432 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002433 unsigned NumCSI = CSI.size();
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002434 if (NumCSI <= 1)
2435 return false;
2436
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002437 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2438 : SpillFuncThreshold;
2439 return Threshold < NumCSI;
2440}
Krzysztof Parzyszekddafa2c2016-08-01 17:15:30 +00002441
Krzysztof Parzyszekddafa2c2016-08-01 17:15:30 +00002442bool HexagonFrameLowering::mayOverflowFrameOffset(MachineFunction &MF) const {
2443 unsigned StackSize = MF.getFrameInfo().estimateStackSize(MF);
2444 auto &HST = MF.getSubtarget<HexagonSubtarget>();
2445 // A fairly simplistic guess as to whether a potential load/store to a
Krzysztof Parzyszek69ffba42017-06-22 14:11:23 +00002446 // stack location could require an extra register.
2447 if (HST.useHVXOps() && StackSize > 256)
2448 return true;
2449
2450 // Check if the function has store-immediate instructions that access
2451 // the stack. Since the offset field is not extendable, if the stack
2452 // size exceeds the offset limit (6 bits, shifted), the stores will
2453 // require a new base register.
2454 bool HasImmStack = false;
2455 unsigned MinLS = ~0u; // Log_2 of the memory access size.
2456
2457 for (const MachineBasicBlock &B : MF) {
2458 for (const MachineInstr &MI : B) {
2459 unsigned LS = 0;
2460 switch (MI.getOpcode()) {
2461 case Hexagon::S4_storeirit_io:
2462 case Hexagon::S4_storeirif_io:
2463 case Hexagon::S4_storeiri_io:
2464 ++LS;
2465 LLVM_FALLTHROUGH;
2466 case Hexagon::S4_storeirht_io:
2467 case Hexagon::S4_storeirhf_io:
2468 case Hexagon::S4_storeirh_io:
2469 ++LS;
2470 LLVM_FALLTHROUGH;
2471 case Hexagon::S4_storeirbt_io:
2472 case Hexagon::S4_storeirbf_io:
2473 case Hexagon::S4_storeirb_io:
2474 if (MI.getOperand(0).isFI())
2475 HasImmStack = true;
2476 MinLS = std::min(MinLS, LS);
2477 break;
2478 }
2479 }
2480 }
2481
2482 if (HasImmStack)
2483 return !isUInt<6>(StackSize >> MinLS);
2484
Krzysztof Parzyszekddafa2c2016-08-01 17:15:30 +00002485 return false;
2486}