1 //===-- lib/Semantics/data-to-inits.cpp -----------------------------------===//
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 // DATA statement object/value checking and conversion to static
10 // initializers
11 // - Applies specific checks to each scalar element initialization with a
12 //   constant value or pointer target with class DataInitializationCompiler;
13 // - Collects the elemental initializations for each symbol and converts them
14 //   into a single init() expression with member function
15 //   DataChecker::ConstructInitializer().
16 
17 #include "data-to-inits.h"
18 #include "pointer-assignment.h"
19 #include "flang/Evaluate/fold-designator.h"
20 #include "flang/Semantics/tools.h"
21 
22 namespace Fortran::semantics {
23 
24 // Steps through a list of values in a DATA statement set; implements
25 // repetition.
26 class ValueListIterator {
27 public:
28   explicit ValueListIterator(const parser::DataStmtSet &set)
29       : end_{std::get<std::list<parser::DataStmtValue>>(set.t).end()},
30         at_{std::get<std::list<parser::DataStmtValue>>(set.t).begin()} {
31     SetRepetitionCount();
32   }
33   bool hasFatalError() const { return hasFatalError_; }
34   bool IsAtEnd() const { return at_ == end_; }
35   const SomeExpr *operator*() const { return GetExpr(GetConstant()); }
36   parser::CharBlock LocateSource() const { return GetConstant().source; }
37   ValueListIterator &operator++() {
38     if (repetitionsRemaining_ > 0) {
39       --repetitionsRemaining_;
40     } else if (at_ != end_) {
41       ++at_;
42       SetRepetitionCount();
43     }
44     return *this;
45   }
46 
47 private:
48   using listIterator = std::list<parser::DataStmtValue>::const_iterator;
49   void SetRepetitionCount();
50   const parser::DataStmtConstant &GetConstant() const {
51     return std::get<parser::DataStmtConstant>(at_->t);
52   }
53 
54   listIterator end_;
55   listIterator at_;
56   ConstantSubscript repetitionsRemaining_{0};
57   bool hasFatalError_{false};
58 };
59 
60 void ValueListIterator::SetRepetitionCount() {
61   for (repetitionsRemaining_ = 1; at_ != end_; ++at_) {
62     if (at_->repetitions < 0) {
63       hasFatalError_ = true;
64     }
65     if (at_->repetitions > 0) {
66       repetitionsRemaining_ = at_->repetitions - 1;
67       return;
68     }
69   }
70   repetitionsRemaining_ = 0;
71 }
72 
73 // Collects all of the elemental initializations from DATA statements
74 // into a single image for each symbol that appears in any DATA.
75 // Expands the implied DO loops and array references.
76 // Applies checks that validate each distinct elemental initialization
77 // of the variables in a data-stmt-set, as well as those that apply
78 // to the corresponding values being use to initialize each element.
79 class DataInitializationCompiler {
80 public:
81   DataInitializationCompiler(DataInitializations &inits,
82       evaluate::ExpressionAnalyzer &a, const parser::DataStmtSet &set)
83       : inits_{inits}, exprAnalyzer_{a}, values_{set} {}
84   const DataInitializations &inits() const { return inits_; }
85   bool HasSurplusValues() const { return !values_.IsAtEnd(); }
86   bool Scan(const parser::DataStmtObject &);
87 
88 private:
89   bool Scan(const parser::Variable &);
90   bool Scan(const parser::Designator &);
91   bool Scan(const parser::DataImpliedDo &);
92   bool Scan(const parser::DataIDoObject &);
93 
94   // Initializes all elements of a designator, which can be an array or section.
95   bool InitDesignator(const SomeExpr &);
96   // Initializes a single object.
97   bool InitElement(const evaluate::OffsetSymbol &, const SomeExpr &designator);
98   // If the returned flag is true, emit a warning about CHARACTER misusage.
99   std::optional<std::pair<SomeExpr, bool>> ConvertElement(
100       const SomeExpr &, const evaluate::DynamicType &);
101 
102   DataInitializations &inits_;
103   evaluate::ExpressionAnalyzer &exprAnalyzer_;
104   ValueListIterator values_;
105 };
106 
107 bool DataInitializationCompiler::Scan(const parser::DataStmtObject &object) {
108   return std::visit(
109       common::visitors{
110           [&](const common::Indirection<parser::Variable> &var) {
111             return Scan(var.value());
112           },
113           [&](const parser::DataImpliedDo &ido) { return Scan(ido); },
114       },
115       object.u);
116 }
117 
118 bool DataInitializationCompiler::Scan(const parser::Variable &var) {
119   if (const auto *expr{GetExpr(var)}) {
120     exprAnalyzer_.GetFoldingContext().messages().SetLocation(var.GetSource());
121     if (InitDesignator(*expr)) {
122       return true;
123     }
124   }
125   return false;
126 }
127 
128 bool DataInitializationCompiler::Scan(const parser::Designator &designator) {
129   if (auto expr{exprAnalyzer_.Analyze(designator)}) {
130     exprAnalyzer_.GetFoldingContext().messages().SetLocation(
131         parser::FindSourceLocation(designator));
132     if (InitDesignator(*expr)) {
133       return true;
134     }
135   }
136   return false;
137 }
138 
139 bool DataInitializationCompiler::Scan(const parser::DataImpliedDo &ido) {
140   const auto &bounds{std::get<parser::DataImpliedDo::Bounds>(ido.t)};
141   auto name{bounds.name.thing.thing};
142   const auto *lowerExpr{GetExpr(bounds.lower.thing.thing)};
143   const auto *upperExpr{GetExpr(bounds.upper.thing.thing)};
144   const auto *stepExpr{
145       bounds.step ? GetExpr(bounds.step->thing.thing) : nullptr};
146   if (lowerExpr && upperExpr) {
147     auto lower{ToInt64(*lowerExpr)};
148     auto upper{ToInt64(*upperExpr)};
149     auto step{stepExpr ? ToInt64(*stepExpr) : std::nullopt};
150     auto stepVal{step.value_or(1)};
151     if (stepVal == 0) {
152       exprAnalyzer_.Say(name.source,
153           "DATA statement implied DO loop has a step value of zero"_err_en_US);
154     } else if (lower && upper) {
155       int kind{evaluate::ResultType<evaluate::ImpliedDoIndex>::kind};
156       if (const auto dynamicType{evaluate::DynamicType::From(*name.symbol)}) {
157         if (dynamicType->category() == TypeCategory::Integer) {
158           kind = dynamicType->kind();
159         }
160       }
161       if (exprAnalyzer_.AddImpliedDo(name.source, kind)) {
162         auto &value{exprAnalyzer_.GetFoldingContext().StartImpliedDo(
163             name.source, *lower)};
164         bool result{true};
165         for (auto n{(*upper - value + stepVal) / stepVal}; n > 0;
166              --n, value += stepVal) {
167           for (const auto &object :
168               std::get<std::list<parser::DataIDoObject>>(ido.t)) {
169             if (!Scan(object)) {
170               result = false;
171               break;
172             }
173           }
174         }
175         exprAnalyzer_.GetFoldingContext().EndImpliedDo(name.source);
176         exprAnalyzer_.RemoveImpliedDo(name.source);
177         return result;
178       }
179     }
180   }
181   return false;
182 }
183 
184 bool DataInitializationCompiler::Scan(const parser::DataIDoObject &object) {
185   return std::visit(
186       common::visitors{
187           [&](const parser::Scalar<common::Indirection<parser::Designator>>
188                   &var) { return Scan(var.thing.value()); },
189           [&](const common::Indirection<parser::DataImpliedDo> &ido) {
190             return Scan(ido.value());
191           },
192       },
193       object.u);
194 }
195 
196 bool DataInitializationCompiler::InitDesignator(const SomeExpr &designator) {
197   evaluate::FoldingContext &context{exprAnalyzer_.GetFoldingContext()};
198   evaluate::DesignatorFolder folder{context};
199   while (auto offsetSymbol{folder.FoldDesignator(designator)}) {
200     if (folder.isOutOfRange()) {
201       if (auto bad{evaluate::OffsetToDesignator(context, *offsetSymbol)}) {
202         exprAnalyzer_.context().Say(
203             "DATA statement designator '%s' is out of range"_err_en_US,
204             bad->AsFortran());
205       } else {
206         exprAnalyzer_.context().Say(
207             "DATA statement designator '%s' is out of range"_err_en_US,
208             designator.AsFortran());
209       }
210       return false;
211     } else if (!InitElement(*offsetSymbol, designator)) {
212       return false;
213     } else {
214       ++values_;
215     }
216   }
217   return folder.isEmpty();
218 }
219 
220 std::optional<std::pair<SomeExpr, bool>>
221 DataInitializationCompiler::ConvertElement(
222     const SomeExpr &expr, const evaluate::DynamicType &type) {
223   if (auto converted{evaluate::ConvertToType(type, SomeExpr{expr})}) {
224     return {std::make_pair(std::move(*converted), false)};
225   }
226   if (std::optional<std::string> chValue{evaluate::GetScalarConstantValue<
227           evaluate::Type<TypeCategory::Character, 1>>(expr)}) {
228     // Allow DATA initialization with Hollerith and kind=1 CHARACTER like
229     // (most) other Fortran compilers do.  Pad on the right with spaces
230     // when short, truncate the right if long.
231     // TODO: big-endian targets
232     std::size_t bytes{static_cast<std::size_t>(evaluate::ToInt64(
233         type.MeasureSizeInBytes(&exprAnalyzer_.GetFoldingContext()))
234                                                    .value())};
235     evaluate::BOZLiteralConstant bits{0};
236     for (std::size_t j{0}; j < bytes; ++j) {
237       char ch{j >= chValue->size() ? ' ' : chValue->at(j)};
238       evaluate::BOZLiteralConstant chBOZ{static_cast<unsigned char>(ch)};
239       bits = bits.IOR(chBOZ.SHIFTL(8 * j));
240     }
241     if (auto converted{evaluate::ConvertToType(type, SomeExpr{bits})}) {
242       return {std::make_pair(std::move(*converted), true)};
243     }
244   }
245   return std::nullopt;
246 }
247 
248 bool DataInitializationCompiler::InitElement(
249     const evaluate::OffsetSymbol &offsetSymbol, const SomeExpr &designator) {
250   const Symbol &symbol{offsetSymbol.symbol()};
251   const Symbol *lastSymbol{GetLastSymbol(designator)};
252   bool isPointer{lastSymbol && IsPointer(*lastSymbol)};
253   bool isProcPointer{lastSymbol && IsProcedurePointer(*lastSymbol)};
254   evaluate::FoldingContext &context{exprAnalyzer_.GetFoldingContext()};
255 
256   const auto DescribeElement{[&]() {
257     if (auto badDesignator{
258             evaluate::OffsetToDesignator(context, offsetSymbol)}) {
259       return badDesignator->AsFortran();
260     } else {
261       // Error recovery
262       std::string buf;
263       llvm::raw_string_ostream ss{buf};
264       ss << offsetSymbol.symbol().name() << " offset " << offsetSymbol.offset()
265          << " bytes for " << offsetSymbol.size() << " bytes";
266       return ss.str();
267     }
268   }};
269   const auto GetImage{[&]() -> evaluate::InitialImage & {
270     auto &symbolInit{inits_.emplace(&symbol, symbol.size()).first->second};
271     symbolInit.inits.emplace_back(offsetSymbol.offset(), offsetSymbol.size());
272     return symbolInit.image;
273   }};
274   const auto OutOfRangeError{[&]() {
275     evaluate::AttachDeclaration(
276         exprAnalyzer_.context().Say(
277             "DATA statement designator '%s' is out of range for its variable '%s'"_err_en_US,
278             DescribeElement(), symbol.name()),
279         symbol);
280   }};
281 
282   if (values_.hasFatalError()) {
283     return false;
284   } else if (values_.IsAtEnd()) {
285     exprAnalyzer_.context().Say(
286         "DATA statement set has no value for '%s'"_err_en_US,
287         DescribeElement());
288     return false;
289   } else if (static_cast<std::size_t>(
290                  offsetSymbol.offset() + offsetSymbol.size()) > symbol.size()) {
291     OutOfRangeError();
292     return false;
293   }
294 
295   const SomeExpr *expr{*values_};
296   if (!expr) {
297     CHECK(exprAnalyzer_.context().AnyFatalError());
298   } else if (isPointer) {
299     if (static_cast<std::size_t>(offsetSymbol.offset() + offsetSymbol.size()) >
300         symbol.size()) {
301       OutOfRangeError();
302     } else if (evaluate::IsNullPointer(*expr)) {
303       // nothing to do; rely on zero initialization
304       return true;
305     } else if (evaluate::IsProcedure(*expr)) {
306       if (isProcPointer) {
307         if (CheckPointerAssignment(context, designator, *expr)) {
308           GetImage().AddPointer(offsetSymbol.offset(), *expr);
309           return true;
310         }
311       } else {
312         exprAnalyzer_.Say(values_.LocateSource(),
313             "Procedure '%s' may not be used to initialize '%s', which is not a procedure pointer"_err_en_US,
314             expr->AsFortran(), DescribeElement());
315       }
316     } else if (isProcPointer) {
317       exprAnalyzer_.Say(values_.LocateSource(),
318           "Data object '%s' may not be used to initialize '%s', which is a procedure pointer"_err_en_US,
319           expr->AsFortran(), DescribeElement());
320     } else if (CheckInitialTarget(context, designator, *expr)) {
321       GetImage().AddPointer(offsetSymbol.offset(), *expr);
322       return true;
323     }
324   } else if (evaluate::IsNullPointer(*expr)) {
325     exprAnalyzer_.Say(values_.LocateSource(),
326         "Initializer for '%s' must not be a pointer"_err_en_US,
327         DescribeElement());
328   } else if (evaluate::IsProcedure(*expr)) {
329     exprAnalyzer_.Say(values_.LocateSource(),
330         "Initializer for '%s' must not be a procedure"_err_en_US,
331         DescribeElement());
332   } else if (auto designatorType{designator.GetType()}) {
333     if (auto converted{ConvertElement(*expr, *designatorType)}) {
334       // value non-pointer initialization
335       if (std::holds_alternative<evaluate::BOZLiteralConstant>(expr->u) &&
336           designatorType->category() != TypeCategory::Integer) { // 8.6.7(11)
337         exprAnalyzer_.Say(values_.LocateSource(),
338             "BOZ literal should appear in a DATA statement only as a value for an integer object, but '%s' is '%s'"_en_US,
339             DescribeElement(), designatorType->AsFortran());
340       } else if (converted->second) {
341         exprAnalyzer_.context().Say(
342             "DATA statement value initializes '%s' of type '%s' with CHARACTER"_en_US,
343             DescribeElement(), designatorType->AsFortran());
344       }
345       auto folded{evaluate::Fold(context, std::move(converted->first))};
346       switch (
347           GetImage().Add(offsetSymbol.offset(), offsetSymbol.size(), folded)) {
348       case evaluate::InitialImage::Ok:
349         return true;
350       case evaluate::InitialImage::NotAConstant:
351         exprAnalyzer_.Say(values_.LocateSource(),
352             "DATA statement value '%s' for '%s' is not a constant"_err_en_US,
353             folded.AsFortran(), DescribeElement());
354         break;
355       case evaluate::InitialImage::OutOfRange:
356         OutOfRangeError();
357         break;
358       default:
359         CHECK(exprAnalyzer_.context().AnyFatalError());
360         break;
361       }
362     } else {
363       exprAnalyzer_.context().Say(
364           "DATA statement value could not be converted to the type '%s' of the object '%s'"_err_en_US,
365           designatorType->AsFortran(), DescribeElement());
366     }
367   } else {
368     CHECK(exprAnalyzer_.context().AnyFatalError());
369   }
370   return false;
371 }
372 
373 void AccumulateDataInitializations(DataInitializations &inits,
374     evaluate::ExpressionAnalyzer &exprAnalyzer,
375     const parser::DataStmtSet &set) {
376   DataInitializationCompiler scanner{inits, exprAnalyzer, set};
377   for (const auto &object :
378       std::get<std::list<parser::DataStmtObject>>(set.t)) {
379     if (!scanner.Scan(object)) {
380       return;
381     }
382   }
383   if (scanner.HasSurplusValues()) {
384     exprAnalyzer.context().Say(
385         "DATA statement set has more values than objects"_err_en_US);
386   }
387 }
388 
389 static bool CombineSomeEquivalencedInits(
390     DataInitializations &inits, evaluate::ExpressionAnalyzer &exprAnalyzer) {
391   auto end{inits.end()};
392   for (auto iter{inits.begin()}; iter != end; ++iter) {
393     const Symbol &symbol{*iter->first};
394     Scope &scope{const_cast<Scope &>(symbol.owner())};
395     if (scope.equivalenceSets().empty()) {
396       continue; // no problem to solve here
397     }
398     const auto *commonBlock{FindCommonBlockContaining(symbol)};
399     // Sweep following DATA initializations in search of overlapping
400     // objects, accumulating into a vector; iterate to a fixed point.
401     std::vector<const Symbol *> conflicts;
402     auto minStart{symbol.offset()};
403     auto maxEnd{symbol.offset() + symbol.size()};
404     std::size_t minElementBytes{1};
405     while (true) {
406       auto prevCount{conflicts.size()};
407       conflicts.clear();
408       for (auto scan{iter}; ++scan != end;) {
409         const Symbol &other{*scan->first};
410         const Scope &otherScope{other.owner()};
411         if (&otherScope == &scope &&
412             FindCommonBlockContaining(other) == commonBlock &&
413             maxEnd > other.offset() &&
414             other.offset() + other.size() > minStart) {
415           // "other" conflicts with "symbol" or another conflict
416           conflicts.push_back(&other);
417           minStart = std::min(minStart, other.offset());
418           maxEnd = std::max(maxEnd, other.offset() + other.size());
419         }
420       }
421       if (conflicts.size() == prevCount) {
422         break;
423       }
424     }
425     if (conflicts.empty()) {
426       continue;
427     }
428     // Compute the minimum common granularity
429     if (auto dyType{evaluate::DynamicType::From(symbol)}) {
430       minElementBytes = evaluate::ToInt64(
431           dyType->MeasureSizeInBytes(&exprAnalyzer.GetFoldingContext()))
432                             .value_or(1);
433     }
434     for (const Symbol *s : conflicts) {
435       if (auto dyType{evaluate::DynamicType::From(*s)}) {
436         minElementBytes = std::min(minElementBytes,
437             static_cast<std::size_t>(evaluate::ToInt64(
438                 dyType->MeasureSizeInBytes(&exprAnalyzer.GetFoldingContext()))
439                                          .value_or(1)));
440       } else {
441         minElementBytes = 1;
442       }
443     }
444     CHECK(minElementBytes > 0);
445     CHECK((minElementBytes & (minElementBytes - 1)) == 0);
446     auto bytes{static_cast<common::ConstantSubscript>(maxEnd - minStart)};
447     CHECK(bytes % minElementBytes == 0);
448     const DeclTypeSpec &typeSpec{scope.MakeNumericType(
449         TypeCategory::Integer, KindExpr{minElementBytes})};
450     // Combine "symbol" and "conflicts[]" into a compiler array temp
451     // that overlaps all of them, and merge their initial values into
452     // the temp's initializer.
453     SourceName name{exprAnalyzer.context().GetTempName(scope)};
454     auto emplaced{
455         scope.try_emplace(name, Attrs{Attr::SAVE}, ObjectEntityDetails{})};
456     CHECK(emplaced.second);
457     Symbol &combinedSymbol{*emplaced.first->second};
458     auto &details{combinedSymbol.get<ObjectEntityDetails>()};
459     combinedSymbol.set_offset(minStart);
460     combinedSymbol.set_size(bytes);
461     details.set_type(typeSpec);
462     ArraySpec arraySpec;
463     arraySpec.emplace_back(ShapeSpec::MakeExplicit(Bound{
464         bytes / static_cast<common::ConstantSubscript>(minElementBytes)}));
465     details.set_shape(arraySpec);
466     if (commonBlock) {
467       details.set_commonBlock(*commonBlock);
468     }
469     // Merge these EQUIVALENCE'd DATA initializations, and remove the
470     // original initializations from the map.
471     auto combinedInit{
472         inits.emplace(&combinedSymbol, static_cast<std::size_t>(bytes))};
473     evaluate::InitialImage &combined{combinedInit.first->second.image};
474     combined.Incorporate(symbol.offset() - minStart, iter->second.image);
475     inits.erase(iter);
476     for (const Symbol *s : conflicts) {
477       auto sIter{inits.find(s)};
478       CHECK(sIter != inits.end());
479       combined.Incorporate(s->offset() - minStart, sIter->second.image);
480       inits.erase(sIter);
481     }
482     return true; // got one
483   }
484   return false; // no remaining EQUIVALENCE'd DATA initializations
485 }
486 
487 // Converts the initialization image for all the DATA statement appearances of
488 // a single symbol into an init() expression in the symbol table entry.
489 void ConstructInitializer(const Symbol &symbol,
490     SymbolDataInitialization &initialization,
491     evaluate::ExpressionAnalyzer &exprAnalyzer) {
492   auto &context{exprAnalyzer.GetFoldingContext()};
493   initialization.inits.sort();
494   ConstantSubscript next{0};
495   for (const auto &init : initialization.inits) {
496     if (init.start() < next) {
497       auto badDesignator{evaluate::OffsetToDesignator(
498           context, symbol, init.start(), init.size())};
499       CHECK(badDesignator);
500       exprAnalyzer.Say(symbol.name(),
501           "DATA statement initializations affect '%s' more than once"_err_en_US,
502           badDesignator->AsFortran());
503     }
504     next = init.start() + init.size();
505     CHECK(next <= static_cast<ConstantSubscript>(initialization.image.size()));
506   }
507   if (const auto *proc{symbol.detailsIf<ProcEntityDetails>()}) {
508     CHECK(IsProcedurePointer(symbol));
509     const auto &procDesignator{initialization.image.AsConstantProcPointer()};
510     CHECK(!procDesignator.GetComponent());
511     auto &mutableProc{const_cast<ProcEntityDetails &>(*proc)};
512     mutableProc.set_init(DEREF(procDesignator.GetSymbol()));
513   } else if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {
514     if (auto symbolType{evaluate::DynamicType::From(symbol)}) {
515       auto &mutableObject{const_cast<ObjectEntityDetails &>(*object)};
516       if (IsPointer(symbol)) {
517         mutableObject.set_init(
518             initialization.image.AsConstantDataPointer(*symbolType));
519         mutableObject.set_initWasValidated();
520       } else {
521         if (auto extents{evaluate::GetConstantExtents(context, symbol)}) {
522           mutableObject.set_init(
523               initialization.image.AsConstant(context, *symbolType, *extents));
524           mutableObject.set_initWasValidated();
525         } else {
526           exprAnalyzer.Say(symbol.name(),
527               "internal: unknown shape for '%s' while constructing initializer from DATA"_err_en_US,
528               symbol.name());
529           return;
530         }
531       }
532     } else {
533       exprAnalyzer.Say(symbol.name(),
534           "internal: no type for '%s' while constructing initializer from DATA"_err_en_US,
535           symbol.name());
536       return;
537     }
538     if (!object->init()) {
539       exprAnalyzer.Say(symbol.name(),
540           "internal: could not construct an initializer from DATA statements for '%s'"_err_en_US,
541           symbol.name());
542     }
543   } else {
544     CHECK(exprAnalyzer.context().AnyFatalError());
545   }
546 }
547 
548 void ConvertToInitializers(
549     DataInitializations &inits, evaluate::ExpressionAnalyzer &exprAnalyzer) {
550   while (CombineSomeEquivalencedInits(inits, exprAnalyzer)) {
551   }
552   for (auto &[symbolPtr, initialization] : inits) {
553     ConstructInitializer(*symbolPtr, initialization, exprAnalyzer);
554   }
555 }
556 } // namespace Fortran::semantics
557