Nearly CC
An educational compiler skeleton
storage.h
1 // Copyright (c) 2021-2023, David H. Hovemeyer <david.hovemeyer@gmail.com>
2 //
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the "Software"),
5 // to deal in the Software without restriction, including without limitation
6 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
7 // and/or sell copies of the Software, and to permit persons to whom the
8 // Software is furnished to do so, subject to the following conditions:
9 //
10 // The above copyright notice and this permission notice shall be included
11 // in all copies or substantial portions of the Software.
12 //
13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16 // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
17 // OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
18 // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
19 // OTHER DEALINGS IN THE SOFTWARE.
20 
21 #ifndef STORAGE_H
22 #define STORAGE_H
23 
24 #include "type.h"
25 
26 // Compute storage size and field offsets for
27 // struct and union types. This can *also* be used to
28 // compute offsets and total storage size for local variables.
29 // Laying out fields in a struct and laying out storage for variables
30 // in a stack frame is essentially the same problem.
32 public:
33  enum Mode { STRUCT, UNION };
34 
35 private:
36  Mode m_mode;
37  unsigned m_size;
38  unsigned m_align;
39  bool m_finished;
40 
41 public:
42  // Note that the start_offset parameter is useful if you are
43  // computing storage for local variables in a nested scope.
44  // (You can set it to be the total amount of storage used
45  // by the outer scopes.)
46  StorageCalculator(Mode mode = STRUCT, unsigned start_offset = 0);
48 
49  // Add a field of given type.
50  // Returns the field's storage offset.
51  unsigned add_field(const std::shared_ptr<Type> &type);
52 
53  // Call this after all fields have been added.
54  // Adds padding at end (if necessary).
55  void finish();
56 
57  // Get storage size of overall struct or union
58  unsigned get_size() const;
59 
60  // Get storage alignment of overall struct or union
61  unsigned get_align() const;
62 };
63 
64 #endif // STORAGE_H
Definition: storage.h:31