1//===- SafeStackLayout.h - SafeStack frame layout --------------*- C++ -*--===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLVM_LIB_CODEGEN_SAFESTACKLAYOUT_H
10#define LLVM_LIB_CODEGEN_SAFESTACKLAYOUT_H
11
12#include "llvm/ADT/DenseMap.h"
13#include "llvm/ADT/SmallVector.h"
14#include "llvm/Analysis/StackLifetime.h"
15#include "llvm/Support/Alignment.h"
16
17namespace llvm {
18
19struct CodeGenOptions;
20class raw_ostream;
21class Value;
22
23namespace safestack {
24
25/// Compute the layout of an unsafe stack frame.
26class StackLayout {
27 const CodeGenOptions &Opts;
28 Align MaxAlignment;
29
30 struct StackRegion {
31 unsigned Start;
32 unsigned End;
33 StackLifetime::LiveRange Range;
34
35 StackRegion(unsigned Start, unsigned End,
36 const StackLifetime::LiveRange &Range)
37 : Start(Start), End(End), Range(Range) {}
38 };
39
40 /// The list of current stack regions, sorted by StackRegion::Start.
41 SmallVector<StackRegion, 16> Regions;
42
43 struct StackObject {
44 const Value *Handle;
45 unsigned Size;
46 Align Alignment;
47 StackLifetime::LiveRange Range;
48 };
49
50 SmallVector<StackObject, 8> StackObjects;
51
52 DenseMap<const Value *, unsigned> ObjectOffsets;
53 DenseMap<const Value *, Align> ObjectAlignments;
54
55 void layoutObject(StackObject &Obj);
56
57public:
58 StackLayout(const CodeGenOptions &Opts, Align StackAlignment)
59 : Opts(Opts), MaxAlignment(StackAlignment) {}
60
61 /// Add an object to the stack frame. Value pointer is opaque and used as a
62 /// handle to retrieve the object's offset in the frame later.
63 void addObject(const Value *V, unsigned Size, Align Alignment,
64 const StackLifetime::LiveRange &Range);
65
66 /// Run the layout computation for all previously added objects.
67 void computeLayout();
68
69 /// Returns the offset to the object start in the stack frame.
70 unsigned getObjectOffset(const Value *V) { return ObjectOffsets[V]; }
71
72 /// Returns the alignment of the object
73 Align getObjectAlignment(const Value *V) { return ObjectAlignments[V]; }
74
75 /// Returns the size of the entire frame.
76 unsigned getFrameSize() { return Regions.empty() ? 0 : Regions.back().End; }
77
78 /// Returns the alignment of the frame.
79 Align getFrameAlignment() { return MaxAlignment; }
80
81 void print(raw_ostream &OS);
82};
83
84} // end namespace safestack
85
86} // end namespace llvm
87
88#endif // LLVM_LIB_CODEGEN_SAFESTACKLAYOUT_H
89