1 //===- ConvertArrayConstructor.cpp -- Array Constructor ---------*- 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 "flang/Lower/ConvertArrayConstructor.h" 10 #include "flang/Evaluate/expression.h" 11 #include "flang/Lower/AbstractConverter.h" 12 #include "flang/Lower/ConvertExprToHLFIR.h" 13 #include "flang/Lower/ConvertType.h" 14 #include "flang/Lower/StatementContext.h" 15 #include "flang/Lower/SymbolMap.h" 16 #include "flang/Optimizer/Builder/HLFIRTools.h" 17 #include "flang/Optimizer/Builder/Runtime/ArrayConstructor.h" 18 #include "flang/Optimizer/Builder/Runtime/RTBuilder.h" 19 #include "flang/Optimizer/Builder/TemporaryStorage.h" 20 #include "flang/Optimizer/Builder/Todo.h" 21 #include "flang/Optimizer/HLFIR/HLFIROps.h" 22 23 // Array constructors are lowered with three different strategies. 24 // All strategies are not possible with all array constructors. 25 // 26 // - Strategy 1: runtime approach (RuntimeTempStrategy). 27 // This strategy works will all array constructors, but will create more 28 // complex code that is harder to optimize. An allocatable temp is created, 29 // it may be unallocated if the array constructor length parameters or extent 30 // could not be computed. Then, the runtime is called to push lowered 31 // ac-value (array constructor elements) into the allocatable. The runtime 32 // will allocate or reallocate as needed while values are being pushed. 33 // In the end, the allocatable contain a temporary with all the array 34 // constructor evaluated elements. 35 // 36 // - Strategy 2: inlined temporary approach (InlinedTempStrategyImpl) 37 // This strategy can only be used if the array constructor extent and length 38 // parameters can be pre-computed without evaluating any ac-value, and if all 39 // of the ac-value are scalars (at least for now). 40 // A temporary is allocated inline in one go, and an index pointing at the 41 // current ac-value position in the array constructor element sequence is 42 // maintained and used to store ac-value as they are being lowered. 43 // 44 // - Strategy 3: "function of the indices" approach (AsElementalStrategy) 45 // This strategy can only be used if the array constructor extent and length 46 // parameters can be pre-computed and, if the array constructor is of the 47 // form "[(scalar_expr, ac-implied-do-control)]". In this case, it is lowered 48 // into an hlfir.elemental without creating any temporary in lowering. This 49 // form should maximize the chance of array temporary elision when assigning 50 // the array constructor, potentially reshaped, to an array variable. 51 // 52 // The array constructor lowering looks like: 53 // ``` 54 // strategy = selectArrayCtorLoweringStrategy(array-ctor-expr); 55 // for (ac-value : array-ctor-expr) 56 // if (ac-value is expression) { 57 // strategy.pushValue(ac-value); 58 // } else if (ac-value is implied-do) { 59 // strategy.startImpliedDo(lower, upper, stride); 60 // strategy.startImpliedDoScope(); 61 // // lower nested values 62 // ... 63 // strategy.endImpliedDoScope(); 64 // } 65 // result = strategy.finishArrayCtorLowering(); 66 // ``` 67 68 //===----------------------------------------------------------------------===// 69 // Definition of the lowering strategies. Each lowering strategy is defined 70 // as a class that implements "pushValue", "startImpliedDo" and 71 // "finishArrayCtorLowering". A strategy may optionally override 72 // "startImpliedDoScope" and "endImpliedDoScope" virtual methods 73 // of its base class StrategyBase. 74 //===----------------------------------------------------------------------===// 75 76 namespace { 77 /// Class provides common implementation of scope push/pop methods 78 /// that update StatementContext scopes and SymMap bindings. 79 /// They might be overridden by the lowering strategies, e.g. 80 /// see AsElementalStrategy. 81 class StrategyBase { 82 public: 83 StrategyBase(Fortran::lower::StatementContext &stmtCtx, 84 Fortran::lower::SymMap &symMap) 85 : stmtCtx{stmtCtx}, symMap{symMap} {}; 86 virtual ~StrategyBase() = default; 87 88 virtual void startImpliedDoScope(llvm::StringRef doName, 89 mlir::Value indexValue) { 90 symMap.pushImpliedDoBinding(doName, indexValue); 91 stmtCtx.pushScope(); 92 } 93 94 virtual void endImpliedDoScope() { 95 stmtCtx.finalizeAndPop(); 96 symMap.popImpliedDoBinding(); 97 } 98 99 protected: 100 Fortran::lower::StatementContext &stmtCtx; 101 Fortran::lower::SymMap &symMap; 102 }; 103 104 /// Class that implements the "inlined temp strategy" to lower array 105 /// constructors. It must be provided a boolean to indicate if the array 106 /// constructor has any implied-do-loop. 107 template <bool hasLoops> 108 class InlinedTempStrategyImpl : public StrategyBase, 109 public fir::factory::HomogeneousScalarStack { 110 /// Name that will be given to the temporary allocation and hlfir.declare in 111 /// the IR. 112 static constexpr char tempName[] = ".tmp.arrayctor"; 113 114 public: 115 /// Start lowering an array constructor according to the inline strategy. 116 /// The temporary is created right away. 117 InlinedTempStrategyImpl(mlir::Location loc, fir::FirOpBuilder &builder, 118 Fortran::lower::StatementContext &stmtCtx, 119 Fortran::lower::SymMap &symMap, 120 fir::SequenceType declaredType, mlir::Value extent, 121 llvm::ArrayRef<mlir::Value> lengths) 122 : StrategyBase{stmtCtx, symMap}, 123 fir::factory::HomogeneousScalarStack{ 124 loc, builder, declaredType, 125 extent, lengths, /*allocateOnHeap=*/true, 126 hasLoops, tempName} {} 127 128 /// Push a lowered ac-value into the current insertion point and 129 /// increment the insertion point. 130 using fir::factory::HomogeneousScalarStack::pushValue; 131 132 /// Start a fir.do_loop with the control from an implied-do and return 133 /// the loop induction variable that is the ac-do-variable value. 134 /// Only usable if the counter is able to track the position through loops. 135 mlir::Value startImpliedDo(mlir::Location loc, fir::FirOpBuilder &builder, 136 mlir::Value lower, mlir::Value upper, 137 mlir::Value stride) { 138 if constexpr (!hasLoops) 139 fir::emitFatalError(loc, "array constructor lowering is inconsistent"); 140 auto loop = builder.create<fir::DoLoopOp>(loc, lower, upper, stride, 141 /*unordered=*/false, 142 /*finalCount=*/false); 143 builder.setInsertionPointToStart(loop.getBody()); 144 return loop.getInductionVar(); 145 } 146 147 /// Move the temporary to an hlfir.expr value (array constructors are not 148 /// variables and cannot be further modified). 149 hlfir::Entity finishArrayCtorLowering(mlir::Location loc, 150 fir::FirOpBuilder &builder) { 151 return moveStackAsArrayExpr(loc, builder); 152 } 153 }; 154 155 /// Semantic analysis expression rewrites unroll implied do loop with 156 /// compile time constant bounds (even if huge). So using a minimalistic 157 /// counter greatly reduces the generated IR for simple but big array 158 /// constructors [(i,i=1,constant-expr)] that are expected to be quite 159 /// common. 160 using LooplessInlinedTempStrategy = InlinedTempStrategyImpl</*hasLoops=*/false>; 161 /// A generic memory based counter that can deal with all cases of 162 /// "inlined temp strategy". The counter value is stored in a temp 163 /// from which it is loaded, incremented, and stored every time an 164 /// ac-value is pushed. 165 using InlinedTempStrategy = InlinedTempStrategyImpl</*hasLoops=*/true>; 166 167 /// Class that implements the "as function of the indices" lowering strategy. 168 /// It will lower [(scalar_expr(i), i=l,u,s)] to: 169 /// ``` 170 /// %extent = max((%u-%l+1)/%s, 0) 171 /// %shape = fir.shape %extent 172 /// %elem = hlfir.elemental %shape { 173 /// ^bb0(%pos:index): 174 /// %i = %l+(%i-1)*%s 175 /// %value = scalar_expr(%i) 176 /// hlfir.yield_element %value 177 /// } 178 /// ``` 179 /// That way, no temporary is created in lowering, and if the array constructor 180 /// is part of a more complex elemental expression, or an assignment, it will be 181 /// trivial to "inline" it in the expression or assignment loops if allowed by 182 /// alias analysis. 183 /// This lowering is however only possible for the form of array constructors as 184 /// in the illustration above. It could be extended to deeper independent 185 /// implied-do nest and wrapped in an hlfir.reshape to a rank 1 array. But this 186 /// op does not exist yet, so this is left for the future if it appears 187 /// profitable. 188 class AsElementalStrategy : public StrategyBase { 189 public: 190 /// The constructor only gathers the operands to create the hlfir.elemental. 191 AsElementalStrategy(mlir::Location loc, fir::FirOpBuilder &builder, 192 Fortran::lower::StatementContext &stmtCtx, 193 Fortran::lower::SymMap &symMap, 194 fir::SequenceType declaredType, mlir::Value extent, 195 llvm::ArrayRef<mlir::Value> lengths) 196 : StrategyBase{stmtCtx, symMap}, shape{builder.genShape(loc, {extent})}, 197 lengthParams{lengths.begin(), lengths.end()}, 198 exprType{getExprType(declaredType)} {} 199 200 static hlfir::ExprType getExprType(fir::SequenceType declaredType) { 201 // Note: 7.8 point 4: the dynamic type of an array constructor is its static 202 // type, it is not polymorphic. 203 return hlfir::ExprType::get(declaredType.getContext(), 204 declaredType.getShape(), 205 declaredType.getEleTy(), 206 /*isPolymorphic=*/false); 207 } 208 209 /// Create the hlfir.elemental and compute the ac-implied-do-index value 210 /// given the lower bound and stride (compute "%i" in the illustration above). 211 mlir::Value startImpliedDo(mlir::Location loc, fir::FirOpBuilder &builder, 212 mlir::Value lower, mlir::Value upper, 213 mlir::Value stride) { 214 assert(!elementalOp && "expected only one implied-do"); 215 mlir::Value one = 216 builder.createIntegerConstant(loc, builder.getIndexType(), 1); 217 elementalOp = 218 builder.create<hlfir::ElementalOp>(loc, exprType, shape, lengthParams); 219 builder.setInsertionPointToStart(elementalOp.getBody()); 220 // implied-do-index = lower+((i-1)*stride) 221 mlir::Value diff = builder.create<mlir::arith::SubIOp>( 222 loc, elementalOp.getIndices()[0], one); 223 mlir::Value mul = builder.create<mlir::arith::MulIOp>(loc, diff, stride); 224 mlir::Value add = builder.create<mlir::arith::AddIOp>(loc, lower, mul); 225 return add; 226 } 227 228 /// Create the elemental hlfir.yield_element with the scalar ac-value. 229 void pushValue(mlir::Location loc, fir::FirOpBuilder &builder, 230 hlfir::Entity value) { 231 assert(value.isScalar() && "cannot use hlfir.elemental with array values"); 232 assert(elementalOp && "array constructor must contain an outer implied-do"); 233 mlir::Value elementResult = value; 234 if (fir::isa_trivial(elementResult.getType())) 235 elementResult = 236 builder.createConvert(loc, exprType.getElementType(), elementResult); 237 238 // The clean-ups associated with the implied-do body operations 239 // must be initiated before the YieldElementOp, so we have to pop the scope 240 // right now. 241 stmtCtx.finalizeAndPop(); 242 243 builder.create<hlfir::YieldElementOp>(loc, elementResult); 244 } 245 246 // Override the default, because the context scope must be popped in 247 // pushValue(). 248 virtual void endImpliedDoScope() override { symMap.popImpliedDoBinding(); } 249 250 /// Return the created hlfir.elemental. 251 hlfir::Entity finishArrayCtorLowering(mlir::Location loc, 252 fir::FirOpBuilder &builder) { 253 return hlfir::Entity{elementalOp}; 254 } 255 256 private: 257 mlir::Value shape; 258 llvm::SmallVector<mlir::Value> lengthParams; 259 hlfir::ExprType exprType; 260 hlfir::ElementalOp elementalOp{}; 261 }; 262 263 /// Class that implements the "runtime temp strategy" to lower array 264 /// constructors. 265 class RuntimeTempStrategy : public StrategyBase { 266 /// Name that will be given to the temporary allocation and hlfir.declare in 267 /// the IR. 268 static constexpr char tempName[] = ".tmp.arrayctor"; 269 270 public: 271 /// Start lowering an array constructor according to the runtime strategy. 272 /// The temporary is only created if the extents and length parameters are 273 /// already known. Otherwise, the handling of the allocation (and 274 /// reallocation) is left up to the runtime. 275 /// \p extent is the pre-computed extent of the array constructor, if it could 276 /// be pre-computed. It is std::nullopt otherwise. 277 /// \p lengths are the pre-computed length parameters of the array 278 /// constructor, if they could be precomputed. \p missingLengthParameters is 279 /// set to true if the length parameters could not be precomputed. 280 RuntimeTempStrategy(mlir::Location loc, fir::FirOpBuilder &builder, 281 Fortran::lower::StatementContext &stmtCtx, 282 Fortran::lower::SymMap &symMap, 283 fir::SequenceType declaredType, 284 std::optional<mlir::Value> extent, 285 llvm::ArrayRef<mlir::Value> lengths, 286 bool missingLengthParameters) 287 : StrategyBase{stmtCtx, symMap}, 288 arrayConstructorElementType{declaredType.getEleTy()} { 289 mlir::Type heapType = fir::HeapType::get(declaredType); 290 mlir::Type boxType = fir::BoxType::get(heapType); 291 allocatableTemp = builder.createTemporary(loc, boxType, tempName); 292 mlir::Value initialBoxValue; 293 if (extent && !missingLengthParameters) { 294 llvm::SmallVector<mlir::Value, 1> extents{*extent}; 295 mlir::Value tempStorage = builder.createHeapTemporary( 296 loc, declaredType, tempName, extents, lengths); 297 mlir::Value shape = builder.genShape(loc, extents); 298 declare = builder.create<hlfir::DeclareOp>( 299 loc, tempStorage, tempName, shape, lengths, 300 fir::FortranVariableFlagsAttr{}); 301 initialBoxValue = 302 builder.createBox(loc, boxType, declare->getOriginalBase(), shape, 303 /*slice=*/mlir::Value{}, lengths, /*tdesc=*/{}); 304 } else { 305 // The runtime will have to do the initial allocation. 306 // The declare operation cannot be emitted in this case since the final 307 // array constructor has not yet been allocated. Instead, the resulting 308 // temporary variable will be extracted from the allocatable descriptor 309 // after all the API calls. 310 // Prepare the initial state of the allocatable descriptor with a 311 // deallocated status and all the available knowledge about the extent 312 // and length parameters. 313 llvm::SmallVector<mlir::Value> emboxLengths(lengths.begin(), 314 lengths.end()); 315 if (!extent) 316 extent = builder.createIntegerConstant(loc, builder.getIndexType(), 0); 317 if (missingLengthParameters) { 318 if (declaredType.getEleTy().isa<fir::CharacterType>()) 319 emboxLengths.push_back(builder.createIntegerConstant( 320 loc, builder.getCharacterLengthType(), 0)); 321 else 322 TODO(loc, 323 "parametrized derived type array constructor without type-spec"); 324 } 325 mlir::Value nullAddr = builder.createNullConstant(loc, heapType); 326 mlir::Value shape = builder.genShape(loc, {*extent}); 327 initialBoxValue = builder.createBox(loc, boxType, nullAddr, shape, 328 /*slice=*/mlir::Value{}, emboxLengths, 329 /*tdesc=*/{}); 330 } 331 builder.create<fir::StoreOp>(loc, initialBoxValue, allocatableTemp); 332 arrayConstructorVector = fir::runtime::genInitArrayConstructorVector( 333 loc, builder, allocatableTemp, 334 builder.createBool(loc, missingLengthParameters)); 335 } 336 337 bool useSimplePushRuntime(hlfir::Entity value) { 338 return value.isScalar() && 339 !arrayConstructorElementType.isa<fir::CharacterType>() && 340 !fir::isRecordWithAllocatableMember(arrayConstructorElementType) && 341 !fir::isRecordWithTypeParameters(arrayConstructorElementType); 342 } 343 344 /// Push a lowered ac-value into the array constructor vector using 345 /// the runtime API. 346 void pushValue(mlir::Location loc, fir::FirOpBuilder &builder, 347 hlfir::Entity value) { 348 if (useSimplePushRuntime(value)) { 349 auto [addrExv, cleanUp] = hlfir::convertToAddress( 350 loc, builder, value, arrayConstructorElementType); 351 mlir::Value addr = fir::getBase(addrExv); 352 if (addr.getType().isa<fir::BaseBoxType>()) 353 addr = builder.create<fir::BoxAddrOp>(loc, addr); 354 fir::runtime::genPushArrayConstructorSimpleScalar( 355 loc, builder, arrayConstructorVector, addr); 356 if (cleanUp) 357 (*cleanUp)(); 358 return; 359 } 360 auto [boxExv, cleanUp] = 361 hlfir::convertToBox(loc, builder, value, arrayConstructorElementType); 362 fir::runtime::genPushArrayConstructorValue( 363 loc, builder, arrayConstructorVector, fir::getBase(boxExv)); 364 if (cleanUp) 365 (*cleanUp)(); 366 } 367 368 /// Start a fir.do_loop with the control from an implied-do and return 369 /// the loop induction variable that is the ac-do-variable value. 370 mlir::Value startImpliedDo(mlir::Location loc, fir::FirOpBuilder &builder, 371 mlir::Value lower, mlir::Value upper, 372 mlir::Value stride) { 373 auto loop = builder.create<fir::DoLoopOp>(loc, lower, upper, stride, 374 /*unordered=*/false, 375 /*finalCount=*/false); 376 builder.setInsertionPointToStart(loop.getBody()); 377 return loop.getInductionVar(); 378 } 379 380 /// Move the temporary to an hlfir.expr value (array constructors are not 381 /// variables and cannot be further modified). 382 hlfir::Entity finishArrayCtorLowering(mlir::Location loc, 383 fir::FirOpBuilder &builder) { 384 // Temp is created using createHeapTemporary, or allocated on the heap 385 // by the runtime. 386 mlir::Value mustFree = builder.createBool(loc, true); 387 mlir::Value temp; 388 if (declare) 389 temp = declare->getBase(); 390 else 391 temp = hlfir::derefPointersAndAllocatables( 392 loc, builder, hlfir::Entity{allocatableTemp}); 393 auto hlfirExpr = builder.create<hlfir::AsExprOp>(loc, temp, mustFree); 394 return hlfir::Entity{hlfirExpr}; 395 } 396 397 private: 398 /// Element type of the array constructor being built. 399 mlir::Type arrayConstructorElementType; 400 /// Allocatable descriptor for the storage of the array constructor being 401 /// built. 402 mlir::Value allocatableTemp; 403 /// Structure that allows the runtime API to maintain the status of 404 /// of the array constructor being built between two API calls. 405 mlir::Value arrayConstructorVector; 406 /// DeclareOp for the array constructor storage, if it was possible to 407 /// allocate it before any API calls. 408 std::optional<hlfir::DeclareOp> declare; 409 }; 410 411 /// Wrapper class that dispatch to the selected array constructor lowering 412 /// strategy and does nothing else. 413 class ArrayCtorLoweringStrategy { 414 public: 415 template <typename A> 416 ArrayCtorLoweringStrategy(A &&impl) : implVariant{std::forward<A>(impl)} {} 417 418 void pushValue(mlir::Location loc, fir::FirOpBuilder &builder, 419 hlfir::Entity value) { 420 return std::visit( 421 [&](auto &impl) { return impl.pushValue(loc, builder, value); }, 422 implVariant); 423 } 424 425 mlir::Value startImpliedDo(mlir::Location loc, fir::FirOpBuilder &builder, 426 mlir::Value lower, mlir::Value upper, 427 mlir::Value stride) { 428 return std::visit( 429 [&](auto &impl) { 430 return impl.startImpliedDo(loc, builder, lower, upper, stride); 431 }, 432 implVariant); 433 } 434 435 hlfir::Entity finishArrayCtorLowering(mlir::Location loc, 436 fir::FirOpBuilder &builder) { 437 return std::visit( 438 [&](auto &impl) { return impl.finishArrayCtorLowering(loc, builder); }, 439 implVariant); 440 } 441 442 void startImpliedDoScope(llvm::StringRef doName, mlir::Value indexValue) { 443 std::visit( 444 [&](auto &impl) { 445 return impl.startImpliedDoScope(doName, indexValue); 446 }, 447 implVariant); 448 } 449 450 void endImpliedDoScope() { 451 std::visit([&](auto &impl) { return impl.endImpliedDoScope(); }, 452 implVariant); 453 } 454 455 private: 456 std::variant<InlinedTempStrategy, LooplessInlinedTempStrategy, 457 AsElementalStrategy, RuntimeTempStrategy> 458 implVariant; 459 }; 460 } // namespace 461 462 //===----------------------------------------------------------------------===// 463 // Definition of selectArrayCtorLoweringStrategy and its helpers. 464 // This is the code that analyses the evaluate::ArrayConstructor<T>, 465 // pre-lowers the array constructor extent and length parameters if it can, 466 // and chooses the lowering strategy. 467 //===----------------------------------------------------------------------===// 468 469 /// Helper to lower a scalar extent expression (like implied-do bounds). 470 static mlir::Value lowerExtentExpr(mlir::Location loc, 471 Fortran::lower::AbstractConverter &converter, 472 Fortran::lower::SymMap &symMap, 473 Fortran::lower::StatementContext &stmtCtx, 474 const Fortran::evaluate::ExtentExpr &expr) { 475 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 476 mlir::IndexType idxTy = builder.getIndexType(); 477 hlfir::Entity value = Fortran::lower::convertExprToHLFIR( 478 loc, converter, toEvExpr(expr), symMap, stmtCtx); 479 value = hlfir::loadTrivialScalar(loc, builder, value); 480 return builder.createConvert(loc, idxTy, value); 481 } 482 483 namespace { 484 /// Helper class to lower the array constructor type and its length parameters. 485 /// The length parameters, if any, are only lowered if this does not require 486 /// evaluating an ac-value. 487 template <typename T> 488 struct LengthAndTypeCollector { 489 static mlir::Type collect(mlir::Location, 490 Fortran::lower::AbstractConverter &converter, 491 const Fortran::evaluate::ArrayConstructor<T> &, 492 Fortran::lower::SymMap &, 493 Fortran::lower::StatementContext &, 494 mlir::SmallVectorImpl<mlir::Value> &) { 495 // Numerical and Logical types. 496 return Fortran::lower::getFIRType(&converter.getMLIRContext(), T::category, 497 T::kind, /*lenParams*/ {}); 498 } 499 }; 500 501 template <> 502 struct LengthAndTypeCollector<Fortran::evaluate::SomeDerived> { 503 static mlir::Type collect( 504 mlir::Location loc, Fortran::lower::AbstractConverter &converter, 505 const Fortran::evaluate::ArrayConstructor<Fortran::evaluate::SomeDerived> 506 &arrayCtorExpr, 507 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx, 508 mlir::SmallVectorImpl<mlir::Value> &lengths) { 509 // Array constructors cannot be unlimited polymorphic (C7113), so there must 510 // be a derived type spec available. 511 return Fortran::lower::translateDerivedTypeToFIRType( 512 converter, arrayCtorExpr.result().derivedTypeSpec()); 513 } 514 }; 515 516 template <int Kind> 517 using Character = 518 Fortran::evaluate::Type<Fortran::common::TypeCategory::Character, Kind>; 519 template <int Kind> 520 struct LengthAndTypeCollector<Character<Kind>> { 521 static mlir::Type collect( 522 mlir::Location loc, Fortran::lower::AbstractConverter &converter, 523 const Fortran::evaluate::ArrayConstructor<Character<Kind>> &arrayCtorExpr, 524 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx, 525 mlir::SmallVectorImpl<mlir::Value> &lengths) { 526 llvm::SmallVector<Fortran::lower::LenParameterTy> typeLengths; 527 if (const Fortran::evaluate::ExtentExpr *lenExpr = arrayCtorExpr.LEN()) { 528 lengths.push_back( 529 lowerExtentExpr(loc, converter, symMap, stmtCtx, *lenExpr)); 530 if (std::optional<std::int64_t> cstLen = 531 Fortran::evaluate::ToInt64(*lenExpr)) 532 typeLengths.push_back(*cstLen); 533 } 534 return Fortran::lower::getFIRType(&converter.getMLIRContext(), 535 Fortran::common::TypeCategory::Character, 536 Kind, typeLengths); 537 } 538 }; 539 } // namespace 540 541 /// Does the array constructor have length parameters that 542 /// LengthAndTypeCollector::collect could not lower because this requires 543 /// lowering an ac-value and must be delayed? 544 static bool missingLengthParameters(mlir::Type elementType, 545 llvm::ArrayRef<mlir::Value> lengths) { 546 return (elementType.isa<fir::CharacterType>() || 547 fir::isRecordWithTypeParameters(elementType)) && 548 lengths.empty(); 549 } 550 551 namespace { 552 /// Structure that analyses the ac-value and implied-do of 553 /// evaluate::ArrayConstructor before they are lowered. It does not generate any 554 /// IR. The result of this analysis pass is used to select the lowering 555 /// strategy. 556 struct ArrayCtorAnalysis { 557 template <typename T> 558 ArrayCtorAnalysis( 559 Fortran::evaluate::FoldingContext &, 560 const Fortran::evaluate::ArrayConstructor<T> &arrayCtorExpr); 561 562 // Can the array constructor easily be rewritten into an hlfir.elemental ? 563 bool isSingleImpliedDoWithOneScalarPureExpr() const { 564 return !anyArrayExpr && isPerfectLoopNest && 565 innerNumberOfExprIfPrefectNest == 1 && depthIfPerfectLoopNest == 1 && 566 innerExprIsPureIfPerfectNest; 567 } 568 569 bool anyImpliedDo = false; 570 bool anyArrayExpr = false; 571 bool isPerfectLoopNest = true; 572 bool innerExprIsPureIfPerfectNest = false; 573 std::int64_t innerNumberOfExprIfPrefectNest = 0; 574 std::int64_t depthIfPerfectLoopNest = 0; 575 }; 576 } // namespace 577 578 template <typename T> 579 ArrayCtorAnalysis::ArrayCtorAnalysis( 580 Fortran::evaluate::FoldingContext &foldingContext, 581 const Fortran::evaluate::ArrayConstructor<T> &arrayCtorExpr) { 582 llvm::SmallVector<const Fortran::evaluate::ArrayConstructorValues<T> *> 583 arrayValueListStack{&arrayCtorExpr}; 584 // Loop through the ac-value-list(s) of the array constructor. 585 while (!arrayValueListStack.empty()) { 586 std::int64_t localNumberOfImpliedDo = 0; 587 std::int64_t localNumberOfExpr = 0; 588 // Loop though the ac-value of an ac-value list, and add any nested 589 // ac-value-list of ac-implied-do to the stack. 590 const Fortran::evaluate::ArrayConstructorValues<T> *currentArrayValueList = 591 arrayValueListStack.pop_back_val(); 592 for (const Fortran::evaluate::ArrayConstructorValue<T> &acValue : 593 *currentArrayValueList) 594 std::visit(Fortran::common::visitors{ 595 [&](const Fortran::evaluate::ImpliedDo<T> &impledDo) { 596 arrayValueListStack.push_back(&impledDo.values()); 597 localNumberOfImpliedDo++; 598 }, 599 [&](const Fortran::evaluate::Expr<T> &expr) { 600 localNumberOfExpr++; 601 anyArrayExpr = anyArrayExpr || expr.Rank() > 0; 602 }}, 603 acValue.u); 604 anyImpliedDo = anyImpliedDo || localNumberOfImpliedDo > 0; 605 606 if (localNumberOfImpliedDo == 0) { 607 // Leaf ac-value-list in the array constructor ac-value tree. 608 if (isPerfectLoopNest) { 609 // This this the only leaf of the array-constructor (the array 610 // constructor is a nest of single implied-do with a list of expression 611 // in the last deeper implied do). e.g: "[((i+j, i=1,n)j=1,m)]". 612 innerNumberOfExprIfPrefectNest = localNumberOfExpr; 613 if (localNumberOfExpr == 1) 614 innerExprIsPureIfPerfectNest = !Fortran::evaluate::FindImpureCall( 615 foldingContext, toEvExpr(std::get<Fortran::evaluate::Expr<T>>( 616 currentArrayValueList->begin()->u))); 617 } 618 } else if (localNumberOfImpliedDo == 1 && localNumberOfExpr == 0) { 619 // Perfect implied-do nest new level. 620 ++depthIfPerfectLoopNest; 621 } else { 622 // More than one implied-do, or at least one implied-do and an expr 623 // at that level. This will not form a perfect nest. Examples: 624 // "[a, (i, i=1,n)]" or "[(i, i=1,n), (j, j=1,m)]". 625 isPerfectLoopNest = false; 626 } 627 } 628 } 629 630 /// Does \p expr contain no calls to user function? 631 static bool isCallFreeExpr(const Fortran::evaluate::ExtentExpr &expr) { 632 for (const Fortran::semantics::Symbol &symbol : 633 Fortran::evaluate::CollectSymbols(expr)) 634 if (Fortran::semantics::IsProcedure(symbol)) 635 return false; 636 return true; 637 } 638 639 /// Core function that pre-lowers the extent and length parameters of 640 /// array constructors if it can, runs the ac-value analysis and 641 /// select the lowering strategy accordingly. 642 template <typename T> 643 static ArrayCtorLoweringStrategy selectArrayCtorLoweringStrategy( 644 mlir::Location loc, Fortran::lower::AbstractConverter &converter, 645 const Fortran::evaluate::ArrayConstructor<T> &arrayCtorExpr, 646 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx) { 647 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 648 mlir::Type idxType = builder.getIndexType(); 649 // Try to gather the array constructor extent. 650 mlir::Value extent; 651 fir::SequenceType::Extent typeExtent = fir::SequenceType::getUnknownExtent(); 652 auto shapeExpr = Fortran::evaluate::GetContextFreeShape( 653 converter.getFoldingContext(), arrayCtorExpr); 654 if (shapeExpr && shapeExpr->size() == 1 && (*shapeExpr)[0]) { 655 const Fortran::evaluate::ExtentExpr &extentExpr = *(*shapeExpr)[0]; 656 if (auto constantExtent = Fortran::evaluate::ToInt64(extentExpr)) { 657 typeExtent = *constantExtent; 658 extent = builder.createIntegerConstant(loc, idxType, typeExtent); 659 } else if (isCallFreeExpr(extentExpr)) { 660 // The expression built by expression analysis for the array constructor 661 // extent does not contain procedure symbols. It is side effect free. 662 // This could be relaxed to allow pure procedure, but some care must 663 // be taken to not bring in "unmapped" symbols from callee scopes. 664 extent = lowerExtentExpr(loc, converter, symMap, stmtCtx, extentExpr); 665 } 666 // Otherwise, the temporary will have to be built step by step with 667 // reallocation and the extent will only be known at the end of the array 668 // constructor evaluation. 669 } 670 // Convert the array constructor type and try to gather its length parameter 671 // values, if any. 672 mlir::SmallVector<mlir::Value> lengths; 673 mlir::Type elementType = LengthAndTypeCollector<T>::collect( 674 loc, converter, arrayCtorExpr, symMap, stmtCtx, lengths); 675 // Run an analysis of the array constructor ac-value. 676 ArrayCtorAnalysis analysis(converter.getFoldingContext(), arrayCtorExpr); 677 bool needToEvaluateOneExprToGetLengthParameters = 678 missingLengthParameters(elementType, lengths); 679 auto declaredType = fir::SequenceType::get({typeExtent}, elementType); 680 681 // Based on what was gathered and the result of the analysis, select and 682 // instantiate the right lowering strategy for the array constructor. 683 if (!extent || needToEvaluateOneExprToGetLengthParameters || 684 analysis.anyArrayExpr || declaredType.getEleTy().isa<fir::RecordType>()) 685 return RuntimeTempStrategy( 686 loc, builder, stmtCtx, symMap, declaredType, 687 extent ? std::optional<mlir::Value>(extent) : std::nullopt, lengths, 688 needToEvaluateOneExprToGetLengthParameters); 689 // Note: array constructors containing impure ac-value expr are currently not 690 // rewritten to hlfir.elemental because impure expressions should be evaluated 691 // in order, and hlfir.elemental currently misses a way to indicate that. 692 if (analysis.isSingleImpliedDoWithOneScalarPureExpr()) 693 return AsElementalStrategy(loc, builder, stmtCtx, symMap, declaredType, 694 extent, lengths); 695 696 if (analysis.anyImpliedDo) 697 return InlinedTempStrategy(loc, builder, stmtCtx, symMap, declaredType, 698 extent, lengths); 699 700 return LooplessInlinedTempStrategy(loc, builder, stmtCtx, symMap, 701 declaredType, extent, lengths); 702 } 703 704 /// Lower an ac-value expression \p expr and forward it to the selected 705 /// lowering strategy \p arrayBuilder, 706 template <typename T> 707 static void genAcValue(mlir::Location loc, 708 Fortran::lower::AbstractConverter &converter, 709 const Fortran::evaluate::Expr<T> &expr, 710 Fortran::lower::SymMap &symMap, 711 Fortran::lower::StatementContext &stmtCtx, 712 ArrayCtorLoweringStrategy &arrayBuilder) { 713 // TODO: get rid of the toEvExpr indirection. 714 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 715 hlfir::Entity value = Fortran::lower::convertExprToHLFIR( 716 loc, converter, toEvExpr(expr), symMap, stmtCtx); 717 value = hlfir::loadTrivialScalar(loc, builder, value); 718 arrayBuilder.pushValue(loc, builder, value); 719 } 720 721 /// Lowers an ac-value implied-do \p impledDo according to the selected 722 /// lowering strategy \p arrayBuilder. 723 template <typename T> 724 static void genAcValue(mlir::Location loc, 725 Fortran::lower::AbstractConverter &converter, 726 const Fortran::evaluate::ImpliedDo<T> &impledDo, 727 Fortran::lower::SymMap &symMap, 728 Fortran::lower::StatementContext &stmtCtx, 729 ArrayCtorLoweringStrategy &arrayBuilder) { 730 auto lowerIndex = 731 [&](const Fortran::evaluate::ExtentExpr expr) -> mlir::Value { 732 return lowerExtentExpr(loc, converter, symMap, stmtCtx, expr); 733 }; 734 mlir::Value lower = lowerIndex(impledDo.lower()); 735 mlir::Value upper = lowerIndex(impledDo.upper()); 736 mlir::Value stride = lowerIndex(impledDo.stride()); 737 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 738 mlir::OpBuilder::InsertPoint insertPt = builder.saveInsertionPoint(); 739 mlir::Value impliedDoIndexValue = 740 arrayBuilder.startImpliedDo(loc, builder, lower, upper, stride); 741 arrayBuilder.startImpliedDoScope(toStringRef(impledDo.name()), 742 impliedDoIndexValue); 743 744 for (const auto &acValue : impledDo.values()) 745 std::visit( 746 [&](const auto &x) { 747 genAcValue(loc, converter, x, symMap, stmtCtx, arrayBuilder); 748 }, 749 acValue.u); 750 751 arrayBuilder.endImpliedDoScope(); 752 builder.restoreInsertionPoint(insertPt); 753 } 754 755 /// Entry point for evaluate::ArrayConstructor lowering. 756 template <typename T> 757 hlfir::EntityWithAttributes Fortran::lower::ArrayConstructorBuilder<T>::gen( 758 mlir::Location loc, Fortran::lower::AbstractConverter &converter, 759 const Fortran::evaluate::ArrayConstructor<T> &arrayCtorExpr, 760 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx) { 761 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 762 // Select the lowering strategy given the array constructor. 763 auto arrayBuilder = selectArrayCtorLoweringStrategy( 764 loc, converter, arrayCtorExpr, symMap, stmtCtx); 765 // Run the array lowering strategy through the ac-values. 766 for (const auto &acValue : arrayCtorExpr) 767 std::visit( 768 [&](const auto &x) { 769 genAcValue(loc, converter, x, symMap, stmtCtx, arrayBuilder); 770 }, 771 acValue.u); 772 hlfir::Entity hlfirExpr = arrayBuilder.finishArrayCtorLowering(loc, builder); 773 // Insert the clean-up for the created hlfir.expr. 774 fir::FirOpBuilder *bldr = &builder; 775 stmtCtx.attachCleanup( 776 [=]() { bldr->create<hlfir::DestroyOp>(loc, hlfirExpr); }); 777 return hlfir::EntityWithAttributes{hlfirExpr}; 778 } 779 780 using namespace Fortran::evaluate; 781 using namespace Fortran::common; 782 FOR_EACH_SPECIFIC_TYPE(template class Fortran::lower::ArrayConstructorBuilder, ) 783