1 //===-- lib/Semantics/compute-offsets.cpp -----------------------*- 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 #include "compute-offsets.h"
10 #include "flang/Evaluate/fold-designator.h"
11 #include "flang/Evaluate/fold.h"
12 #include "flang/Evaluate/shape.h"
13 #include "flang/Evaluate/type.h"
14 #include "flang/Runtime/descriptor.h"
15 #include "flang/Semantics/scope.h"
16 #include "flang/Semantics/semantics.h"
17 #include "flang/Semantics/symbol.h"
18 #include "flang/Semantics/tools.h"
19 #include "flang/Semantics/type.h"
20 #include <algorithm>
21 #include <vector>
22 
23 namespace Fortran::semantics {
24 
25 class ComputeOffsetsHelper {
26 public:
27   ComputeOffsetsHelper(SemanticsContext &context) : context_{context} {}
28   void Compute(Scope &);
29 
30 private:
31   struct SizeAndAlignment {
32     SizeAndAlignment() {}
33     SizeAndAlignment(std::size_t bytes) : size{bytes}, alignment{bytes} {}
34     SizeAndAlignment(std::size_t bytes, std::size_t align)
35         : size{bytes}, alignment{align} {}
36     std::size_t size{0};
37     std::size_t alignment{0};
38   };
39   struct SymbolAndOffset {
40     SymbolAndOffset(Symbol &s, std::size_t off, const EquivalenceObject &obj)
41         : symbol{s}, offset{off}, object{&obj} {}
42     SymbolAndOffset(const SymbolAndOffset &) = default;
43     MutableSymbolRef symbol;
44     std::size_t offset;
45     const EquivalenceObject *object;
46   };
47 
48   void DoCommonBlock(Symbol &);
49   void DoEquivalenceBlockBase(Symbol &, SizeAndAlignment &);
50   void DoEquivalenceSet(const EquivalenceSet &);
51   SymbolAndOffset Resolve(const SymbolAndOffset &);
52   std::size_t ComputeOffset(const EquivalenceObject &);
53   void DoSymbol(Symbol &);
54   SizeAndAlignment GetSizeAndAlignment(const Symbol &, bool entire);
55   std::size_t Align(std::size_t, std::size_t);
56 
57   SemanticsContext &context_;
58   std::size_t offset_{0};
59   std::size_t alignment_{1};
60   // symbol -> symbol+offset that determines its location, from EQUIVALENCE
61   std::map<MutableSymbolRef, SymbolAndOffset, SymbolAddressCompare> dependents_;
62   // base symbol -> SizeAndAlignment for each distinct EQUIVALENCE block
63   std::map<MutableSymbolRef, SizeAndAlignment, SymbolAddressCompare>
64       equivalenceBlock_;
65 };
66 
67 void ComputeOffsetsHelper::Compute(Scope &scope) {
68   for (Scope &child : scope.children()) {
69     ComputeOffsets(context_, child);
70   }
71   if (scope.symbol() && scope.IsParameterizedDerivedType()) {
72     return; // only process instantiations of parameterized derived types
73   }
74   if (scope.alignment().has_value()) {
75     return; // prevent infinite recursion in error cases
76   }
77   scope.SetAlignment(0);
78   // Build dependents_ from equivalences: symbol -> symbol+offset
79   for (const EquivalenceSet &set : scope.equivalenceSets()) {
80     DoEquivalenceSet(set);
81   }
82   // Compute a base symbol and overall block size for each
83   // disjoint EQUIVALENCE storage sequence.
84   for (auto &[symbol, dep] : dependents_) {
85     dep = Resolve(dep);
86     CHECK(symbol->size() == 0);
87     auto symInfo{GetSizeAndAlignment(*symbol, true)};
88     symbol->set_size(symInfo.size);
89     Symbol &base{*dep.symbol};
90     auto iter{equivalenceBlock_.find(base)};
91     std::size_t minBlockSize{dep.offset + symInfo.size};
92     if (iter == equivalenceBlock_.end()) {
93       equivalenceBlock_.emplace(
94           base, SizeAndAlignment{minBlockSize, symInfo.alignment});
95     } else {
96       SizeAndAlignment &blockInfo{iter->second};
97       blockInfo.size = std::max(blockInfo.size, minBlockSize);
98       blockInfo.alignment = std::max(blockInfo.alignment, symInfo.alignment);
99     }
100   }
101   // Assign offsets for non-COMMON EQUIVALENCE blocks
102   for (auto &[symbol, blockInfo] : equivalenceBlock_) {
103     if (!InCommonBlock(*symbol)) {
104       DoSymbol(*symbol);
105       DoEquivalenceBlockBase(*symbol, blockInfo);
106       offset_ = std::max(offset_, symbol->offset() + blockInfo.size);
107     }
108   }
109   // Process remaining non-COMMON symbols; this is all of them if there
110   // was no use of EQUIVALENCE in the scope.
111   for (auto &symbol : scope.GetSymbols()) {
112     if (!InCommonBlock(*symbol) &&
113         dependents_.find(symbol) == dependents_.end() &&
114         equivalenceBlock_.find(symbol) == equivalenceBlock_.end()) {
115       DoSymbol(*symbol);
116     }
117   }
118   scope.set_size(offset_);
119   scope.SetAlignment(alignment_);
120   // Assign offsets in COMMON blocks.
121   for (auto &pair : scope.commonBlocks()) {
122     DoCommonBlock(*pair.second);
123   }
124   for (auto &[symbol, dep] : dependents_) {
125     symbol->set_offset(dep.symbol->offset() + dep.offset);
126     if (const auto *block{FindCommonBlockContaining(*dep.symbol)}) {
127       symbol->get<ObjectEntityDetails>().set_commonBlock(*block);
128     }
129   }
130 }
131 
132 auto ComputeOffsetsHelper::Resolve(const SymbolAndOffset &dep)
133     -> SymbolAndOffset {
134   auto it{dependents_.find(*dep.symbol)};
135   if (it == dependents_.end()) {
136     return dep;
137   } else {
138     SymbolAndOffset result{Resolve(it->second)};
139     result.offset += dep.offset;
140     result.object = dep.object;
141     return result;
142   }
143 }
144 
145 void ComputeOffsetsHelper::DoCommonBlock(Symbol &commonBlock) {
146   auto &details{commonBlock.get<CommonBlockDetails>()};
147   offset_ = 0;
148   alignment_ = 0;
149   std::size_t minSize{0};
150   std::size_t minAlignment{0};
151   for (auto &object : details.objects()) {
152     Symbol &symbol{*object};
153     DoSymbol(symbol);
154     auto eqIter{equivalenceBlock_.end()};
155     auto iter{dependents_.find(symbol)};
156     if (iter == dependents_.end()) {
157       eqIter = equivalenceBlock_.find(symbol);
158       if (eqIter != equivalenceBlock_.end()) {
159         DoEquivalenceBlockBase(symbol, eqIter->second);
160       }
161     } else {
162       SymbolAndOffset &dep{iter->second};
163       Symbol &base{*dep.symbol};
164       auto errorSite{
165           commonBlock.name().empty() ? symbol.name() : commonBlock.name()};
166       if (const auto *baseBlock{FindCommonBlockContaining(base)}) {
167         if (baseBlock == &commonBlock) {
168           context_.Say(errorSite,
169               "'%s' is storage associated with '%s' by EQUIVALENCE elsewhere in COMMON block /%s/"_err_en_US,
170               symbol.name(), base.name(), commonBlock.name());
171         } else { // 8.10.3(1)
172           context_.Say(errorSite,
173               "'%s' in COMMON block /%s/ must not be storage associated with '%s' in COMMON block /%s/ by EQUIVALENCE"_err_en_US,
174               symbol.name(), commonBlock.name(), base.name(),
175               baseBlock->name());
176         }
177       } else if (dep.offset > symbol.offset()) { // 8.10.3(3)
178         context_.Say(errorSite,
179             "'%s' cannot backward-extend COMMON block /%s/ via EQUIVALENCE with '%s'"_err_en_US,
180             symbol.name(), commonBlock.name(), base.name());
181       } else {
182         eqIter = equivalenceBlock_.find(base);
183         base.get<ObjectEntityDetails>().set_commonBlock(commonBlock);
184         base.set_offset(symbol.offset() - dep.offset);
185       }
186     }
187     // Get full extent of any EQUIVALENCE block into size of COMMON ( see
188     // 8.10.2.2 point 1 (2))
189     if (eqIter != equivalenceBlock_.end()) {
190       SizeAndAlignment &blockInfo{eqIter->second};
191       minSize = std::max(
192           minSize, std::max(offset_, eqIter->first->offset() + blockInfo.size));
193       minAlignment = std::max(minAlignment, blockInfo.alignment);
194     }
195   }
196   commonBlock.set_size(std::max(minSize, offset_));
197   details.set_alignment(std::max(minAlignment, alignment_));
198 }
199 
200 void ComputeOffsetsHelper::DoEquivalenceBlockBase(
201     Symbol &symbol, SizeAndAlignment &blockInfo) {
202   if (symbol.size() > blockInfo.size) {
203     blockInfo.size = symbol.size();
204   }
205 }
206 
207 void ComputeOffsetsHelper::DoEquivalenceSet(const EquivalenceSet &set) {
208   std::vector<SymbolAndOffset> symbolOffsets;
209   std::optional<std::size_t> representative;
210   for (const EquivalenceObject &object : set) {
211     std::size_t offset{ComputeOffset(object)};
212     SymbolAndOffset resolved{
213         Resolve(SymbolAndOffset{object.symbol, offset, object})};
214     symbolOffsets.push_back(resolved);
215     if (!representative ||
216         resolved.offset >= symbolOffsets[*representative].offset) {
217       // The equivalenced object with the largest offset from its resolved
218       // symbol will be the representative of this set, since the offsets
219       // of the other objects will be positive relative to it.
220       representative = symbolOffsets.size() - 1;
221     }
222   }
223   CHECK(representative);
224   const SymbolAndOffset &base{symbolOffsets[*representative]};
225   for (const auto &[symbol, offset, object] : symbolOffsets) {
226     if (symbol == base.symbol) {
227       if (offset != base.offset) {
228         auto x{evaluate::OffsetToDesignator(
229             context_.foldingContext(), *symbol, base.offset, 1)};
230         auto y{evaluate::OffsetToDesignator(
231             context_.foldingContext(), *symbol, offset, 1)};
232         if (x && y) {
233           context_
234               .Say(base.object->source,
235                   "'%s' and '%s' cannot have the same first storage unit"_err_en_US,
236                   x->AsFortran(), y->AsFortran())
237               .Attach(object->source, "Incompatible reference to '%s'"_en_US,
238                   y->AsFortran());
239         } else { // error recovery
240           context_
241               .Say(base.object->source,
242                   "'%s' (offset %zd bytes and %zd bytes) cannot have the same first storage unit"_err_en_US,
243                   symbol->name(), base.offset, offset)
244               .Attach(object->source,
245                   "Incompatible reference to '%s' offset %zd bytes"_en_US,
246                   symbol->name(), offset);
247         }
248       }
249     } else {
250       dependents_.emplace(*symbol,
251           SymbolAndOffset{*base.symbol, base.offset - offset, *object});
252     }
253   }
254 }
255 
256 // Offset of this equivalence object from the start of its variable.
257 std::size_t ComputeOffsetsHelper::ComputeOffset(
258     const EquivalenceObject &object) {
259   std::size_t offset{0};
260   if (!object.subscripts.empty()) {
261     const ArraySpec &shape{object.symbol.get<ObjectEntityDetails>().shape()};
262     auto lbound{[&](std::size_t i) {
263       return *ToInt64(shape[i].lbound().GetExplicit());
264     }};
265     auto ubound{[&](std::size_t i) {
266       return *ToInt64(shape[i].ubound().GetExplicit());
267     }};
268     for (std::size_t i{object.subscripts.size() - 1};;) {
269       offset += object.subscripts[i] - lbound(i);
270       if (i == 0) {
271         break;
272       }
273       --i;
274       offset *= ubound(i) - lbound(i) + 1;
275     }
276   }
277   auto result{offset * GetSizeAndAlignment(object.symbol, false).size};
278   if (object.substringStart) {
279     int kind{context_.defaultKinds().GetDefaultKind(TypeCategory::Character)};
280     if (const DeclTypeSpec * type{object.symbol.GetType()}) {
281       if (const IntrinsicTypeSpec * intrinsic{type->AsIntrinsic()}) {
282         kind = ToInt64(intrinsic->kind()).value_or(kind);
283       }
284     }
285     result += kind * (*object.substringStart - 1);
286   }
287   return result;
288 }
289 
290 void ComputeOffsetsHelper::DoSymbol(Symbol &symbol) {
291   if (!symbol.has<ObjectEntityDetails>() && !symbol.has<ProcEntityDetails>()) {
292     return;
293   }
294   SizeAndAlignment s{GetSizeAndAlignment(symbol, true)};
295   if (s.size == 0) {
296     return;
297   }
298   offset_ = Align(offset_, s.alignment);
299   symbol.set_size(s.size);
300   symbol.set_offset(offset_);
301   offset_ += s.size;
302   alignment_ = std::max(alignment_, s.alignment);
303 }
304 
305 auto ComputeOffsetsHelper::GetSizeAndAlignment(
306     const Symbol &symbol, bool entire) -> SizeAndAlignment {
307   // TODO: The size of procedure pointers is not yet known
308   // and is independent of rank (and probably also the number
309   // of length type parameters).
310   auto &foldingContext{context_.foldingContext()};
311   if (IsDescriptor(symbol) || IsProcedurePointer(symbol)) {
312     const auto *derived{
313         evaluate::GetDerivedTypeSpec(evaluate::DynamicType::From(symbol))};
314     int lenParams{derived ? CountLenParameters(*derived) : 0};
315     std::size_t size{runtime::Descriptor::SizeInBytes(
316         symbol.Rank(), derived != nullptr, lenParams)};
317     return {size, foldingContext.maxAlignment()};
318   }
319   if (IsProcedure(symbol)) {
320     return {};
321   }
322   if (auto chars{evaluate::characteristics::TypeAndShape::Characterize(
323           symbol, foldingContext)}) {
324     if (entire) {
325       if (auto size{ToInt64(chars->MeasureSizeInBytes(foldingContext))}) {
326         return {static_cast<std::size_t>(*size),
327             chars->type().GetAlignment(foldingContext)};
328       }
329     } else { // element size only
330       if (auto size{ToInt64(chars->MeasureElementSizeInBytes(
331               foldingContext, true /*aligned*/))}) {
332         return {static_cast<std::size_t>(*size),
333             chars->type().GetAlignment(foldingContext)};
334       }
335     }
336   }
337   return {};
338 }
339 
340 // Align a size to its natural alignment, up to maxAlignment.
341 std::size_t ComputeOffsetsHelper::Align(std::size_t x, std::size_t alignment) {
342   alignment = std::min(alignment, context_.foldingContext().maxAlignment());
343   return (x + alignment - 1) & -alignment;
344 }
345 
346 void ComputeOffsets(SemanticsContext &context, Scope &scope) {
347   ComputeOffsetsHelper{context}.Compute(scope);
348 }
349 
350 } // namespace Fortran::semantics
351