Debian Codegraph @

flang/lib/Optimizer/HLFIR/Transforms/BufferizeHLFIR.cpp

raw
1 //===- BufferizeHLFIR.cpp - Bufferize HLFIR ------------------------------===//
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 // This file defines a pass that bufferize hlfir.expr. It translates operations
9 // producing or consuming hlfir.expr into operations operating on memory.
10 // An hlfir.expr is translated to a tuple<variable address, cleanupflag>
11 // where cleanupflag is set to true if storage for the expression was allocated
12 // on the heap.
13 //===----------------------------------------------------------------------===//
14
15 #include "flang/Optimizer/Builder/Character.h"
16 #include "flang/Optimizer/Builder/FIRBuilder.h"
17 #include "flang/Optimizer/Builder/HLFIRTools.h"
18 #include "flang/Optimizer/Builder/MutableBox.h"
19 #include "flang/Optimizer/Builder/Runtime/Allocatable.h"
20 #include "flang/Optimizer/Builder/Runtime/Derived.h"
21 #include "flang/Optimizer/Builder/Todo.h"
22 #include "flang/Optimizer/Dialect/FIRDialect.h"
23 #include "flang/Optimizer/Dialect/FIROps.h"
24 #include "flang/Optimizer/Dialect/FIRType.h"
25 #include "flang/Optimizer/Dialect/Support/FIRContext.h"
26 #include "flang/Optimizer/HLFIR/HLFIRDialect.h"
27 #include "flang/Optimizer/HLFIR/HLFIROps.h"
28 #include "flang/Optimizer/HLFIR/Passes.h"
29 #include "mlir/IR/Dominance.h"
30 #include "mlir/IR/PatternMatch.h"
31 #include "mlir/Pass/Pass.h"
32 #include "mlir/Pass/PassManager.h"
33 #include "mlir/Transforms/DialectConversion.h"
34 #include "llvm/ADT/TypeSwitch.h"
35
36 namespace hlfir {
37 #define GEN_PASS_DEF_BUFFERIZEHLFIR
38 #include "flang/Optimizer/HLFIR/Passes.h.inc"
39 } // namespace hlfir
40
41 namespace {
42
43 /// Helper to create tuple from a bufferized expr storage and clean up
44 /// instruction flag. The storage is an HLFIR variable so that it can
45 /// be manipulated as a variable later (all shape and length information
46 /// cam be retrieved from it).
47 static mlir::Value packageBufferizedExpr(mlir::Location loc,
48 fir::FirOpBuilder &builder,
49 hlfir::Entity storage,
50 mlir::Value mustFree) {
51 auto tupleType = mlir::TupleType::get(
52 builder.getContext(),
53 mlir::TypeRange{storage.getType(), mustFree.getType()});
54 auto undef = builder.create<fir::UndefOp>(loc, tupleType);
55 auto insert = builder.create<fir::InsertValueOp>(
56 loc, tupleType, undef, mustFree,
57 builder.getArrayAttr(
58 {builder.getIntegerAttr(builder.getIndexType(), 1)}));
59 return builder.create<fir::InsertValueOp>(
60 loc, tupleType, insert, storage,
61 builder.getArrayAttr(
62 {builder.getIntegerAttr(builder.getIndexType(), 0)}));
63 }
64
65 /// Helper to create tuple from a bufferized expr storage and constant
66 /// boolean clean-up flag.
67 static mlir::Value packageBufferizedExpr(mlir::Location loc,
68 fir::FirOpBuilder &builder,
69 hlfir::Entity storage, bool mustFree) {
70 mlir::Value mustFreeValue = builder.createBool(loc, mustFree);
71 return packageBufferizedExpr(loc, builder, storage, mustFreeValue);
72 }
73
74 /// Helper to extract the storage from a tuple created by packageBufferizedExpr.
75 /// It assumes no tuples are used as HLFIR operation operands, which is
76 /// currently enforced by the verifiers that only accept HLFIR value or
77 /// variable types which do not include tuples.
78 static hlfir::Entity getBufferizedExprStorage(mlir::Value bufferizedExpr) {
79 auto tupleType = mlir::dyn_cast<mlir::TupleType>(bufferizedExpr.getType());
80 if (!tupleType)
81 return hlfir::Entity{bufferizedExpr};
82 assert(tupleType.size() == 2 && "unexpected tuple type");
83 if (auto insert = bufferizedExpr.getDefiningOp<fir::InsertValueOp>())
84 if (insert.getVal().getType() == tupleType.getType(0))
85 return hlfir::Entity{insert.getVal()};
86 TODO(bufferizedExpr.getLoc(), "general extract storage case");
87 }
88
89 /// Helper to extract the clean-up flag from a tuple created by
90 /// packageBufferizedExpr.
91 static mlir::Value getBufferizedExprMustFreeFlag(mlir::Value bufferizedExpr) {
92 auto tupleType = mlir::dyn_cast<mlir::TupleType>(bufferizedExpr.getType());
93 if (!tupleType)
94 return bufferizedExpr;
95 assert(tupleType.size() == 2 && "unexpected tuple type");
96 if (auto insert = bufferizedExpr.getDefiningOp<fir::InsertValueOp>())
97 if (auto insert0 = insert.getAdt().getDefiningOp<fir::InsertValueOp>())
98 if (insert0.getVal().getType() == tupleType.getType(1))
99 return insert0.getVal();
100 TODO(bufferizedExpr.getLoc(), "general extract storage case");
101 }
102
103 static std::pair<hlfir::Entity, mlir::Value>
104 createArrayTemp(mlir::Location loc, fir::FirOpBuilder &builder,
105 mlir::Type exprType, mlir::Value shape,
106 mlir::ValueRange extents, mlir::ValueRange lenParams,
107 std::optional<hlfir::Entity> polymorphicMold) {
108 mlir::Type sequenceType = hlfir::getFortranElementOrSequenceType(exprType);
109 llvm::StringRef tmpName{".tmp.array"};
110
111 if (polymorphicMold) {
112 // Create *allocated* polymorphic temporary using the dynamic type
113 // of the mold and the provided shape/extents. The created temporary
114 // array will be written element per element, that is why it has to be
115 // allocated.
116 mlir::Type boxHeapType = fir::HeapType::get(sequenceType);
117 mlir::Value alloc = fir::factory::genNullBoxStorage(
118 builder, loc, fir::ClassType::get(boxHeapType));
119 mlir::Value isHeapAlloc = builder.createBool(loc, true);
120 fir::FortranVariableFlagsAttr declAttrs =
121 fir::FortranVariableFlagsAttr::get(
122 builder.getContext(), fir::FortranVariableFlagsEnum::allocatable);
123
124 auto declareOp =
125 builder.create<hlfir::DeclareOp>(loc, alloc, tmpName,
126 /*shape=*/nullptr, lenParams,
127 /*dummy_scope=*/nullptr, declAttrs);
128
129 int rank = extents.size();
130 fir::runtime::genAllocatableApplyMold(builder, loc, alloc,
131 polymorphicMold->getFirBase(), rank);
132 if (!extents.empty()) {
133 mlir::Type idxTy = builder.getIndexType();
134 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
135 unsigned dim = 0;
136 for (mlir::Value extent : extents) {
137 mlir::Value dimIndex = builder.createIntegerConstant(loc, idxTy, dim++);
138 fir::runtime::genAllocatableSetBounds(builder, loc, alloc, dimIndex,
139 one, extent);
140 }
141 }
142 if (!lenParams.empty()) {
143 // We should call AllocatableSetDerivedLength() here.
144 // TODO: does the mold provide the length parameters or
145 // the operation itself or should they be in sync?
146 TODO(loc, "polymorphic type with length parameters in HLFIR");
147 }
148 fir::runtime::genAllocatableAllocate(builder, loc, alloc);
149
150 return {hlfir::Entity{declareOp.getBase()}, isHeapAlloc};
151 }
152
153 mlir::Value allocmem = builder.createHeapTemporary(loc, sequenceType, tmpName,
154 extents, lenParams);
155 auto declareOp = builder.create<hlfir::DeclareOp>(
156 loc, allocmem, tmpName, shape, lenParams,
157 /*dummy_scope=*/nullptr, fir::FortranVariableFlagsAttr{});
158 mlir::Value trueVal = builder.createBool(loc, true);
159 return {hlfir::Entity{declareOp.getBase()}, trueVal};
160 }
161
162 /// Copy \p source into a new temporary and package the temporary into a
163 /// <temp,cleanup> tuple. The temporary may be heap or stack allocated.
164 static mlir::Value copyInTempAndPackage(mlir::Location loc,
165 fir::FirOpBuilder &builder,
166 hlfir::Entity source) {
167 auto [temp, cleanup] = hlfir::createTempFromMold(loc, builder, source);
168 builder.create<hlfir::AssignOp>(loc, source, temp, temp.isAllocatable(),
169 /*keep_lhs_length_if_realloc=*/false,
170 /*temporary_lhs=*/true);
171 // Dereference allocatable temporary directly to simplify processing
172 // of its uses.
173 if (temp.isAllocatable())
174 temp = hlfir::derefPointersAndAllocatables(loc, builder, temp);
175 return packageBufferizedExpr(loc, builder, temp, cleanup);
176 }
177
178 struct AsExprOpConversion : public mlir::OpConversionPattern<hlfir::AsExprOp> {
179 using mlir::OpConversionPattern<hlfir::AsExprOp>::OpConversionPattern;
180 explicit AsExprOpConversion(mlir::MLIRContext *ctx)
181 : mlir::OpConversionPattern<hlfir::AsExprOp>{ctx} {}
182 llvm::LogicalResult
183 matchAndRewrite(hlfir::AsExprOp asExpr, OpAdaptor adaptor,
184 mlir::ConversionPatternRewriter &rewriter) const override {
185 mlir::Location loc = asExpr->getLoc();
186 auto module = asExpr->getParentOfType<mlir::ModuleOp>();
187 fir::FirOpBuilder builder(rewriter, module);
188 if (asExpr.isMove()) {
189 // Move variable storage for the hlfir.expr buffer.
190 mlir::Value bufferizedExpr = packageBufferizedExpr(
191 loc, builder, hlfir::Entity{adaptor.getVar()}, adaptor.getMustFree());
192 rewriter.replaceOp(asExpr, bufferizedExpr);
193 return mlir::success();
194 }
195 // Otherwise, create a copy in a new buffer.
196 hlfir::Entity source = hlfir::Entity{adaptor.getVar()};
197 mlir::Value bufferizedExpr = copyInTempAndPackage(loc, builder, source);
198 rewriter.replaceOp(asExpr, bufferizedExpr);
199 return mlir::success();
200 }
201 };
202
203 struct ShapeOfOpConversion
204 : public mlir::OpConversionPattern<hlfir::ShapeOfOp> {
205 using mlir::OpConversionPattern<hlfir::ShapeOfOp>::OpConversionPattern;
206
207 llvm::LogicalResult
208 matchAndRewrite(hlfir::ShapeOfOp shapeOf, OpAdaptor adaptor,
209 mlir::ConversionPatternRewriter &rewriter) const override {
210 mlir::Location loc = shapeOf.getLoc();
211 mlir::ModuleOp mod = shapeOf->getParentOfType<mlir::ModuleOp>();
212 fir::FirOpBuilder builder(rewriter, mod);
213
214 mlir::Value shape;
215 hlfir::Entity bufferizedExpr{getBufferizedExprStorage(adaptor.getExpr())};
216 if (bufferizedExpr.isVariable()) {
217 shape = hlfir::genShape(loc, builder, bufferizedExpr);
218 } else {
219 // everything else failed so try to create a shape from static type info
220 hlfir::ExprType exprTy =
221 mlir::dyn_cast_or_null<hlfir::ExprType>(adaptor.getExpr().getType());
222 if (exprTy)
223 shape = hlfir::genExprShape(builder, loc, exprTy);
224 }
225 // expected to never happen
226 if (!shape)
227 return emitError(loc,
228 "Unresolvable hlfir.shape_of where extents are unknown");
229
230 rewriter.replaceOp(shapeOf, shape);
231 return mlir::success();
232 }
233 };
234
235 struct ApplyOpConversion : public mlir::OpConversionPattern<hlfir::ApplyOp> {
236 using mlir::OpConversionPattern<hlfir::ApplyOp>::OpConversionPattern;
237 explicit ApplyOpConversion(mlir::MLIRContext *ctx)
238 : mlir::OpConversionPattern<hlfir::ApplyOp>{ctx} {}
239 llvm::LogicalResult
240 matchAndRewrite(hlfir::ApplyOp apply, OpAdaptor adaptor,
241 mlir::ConversionPatternRewriter &rewriter) const override {
242 mlir::Location loc = apply->getLoc();
243 hlfir::Entity bufferizedExpr = getBufferizedExprStorage(adaptor.getExpr());
244 mlir::Type resultType = hlfir::getVariableElementType(bufferizedExpr);
245 mlir::Value result = rewriter.create<hlfir::DesignateOp>(
246 loc, resultType, bufferizedExpr, adaptor.getIndices(),
247 adaptor.getTypeparams());
248 if (fir::isa_trivial(apply.getType())) {
249 result = rewriter.create<fir::LoadOp>(loc, result);
250 } else {
251 fir::FirOpBuilder builder(rewriter, apply.getOperation());
252 result =
253 packageBufferizedExpr(loc, builder, hlfir::Entity{result}, false);
254 }
255 rewriter.replaceOp(apply, result);
256 return mlir::success();
257 }
258 };
259
260 struct AssignOpConversion : public mlir::OpConversionPattern<hlfir::AssignOp> {
261 using mlir::OpConversionPattern<hlfir::AssignOp>::OpConversionPattern;
262 explicit AssignOpConversion(mlir::MLIRContext *ctx)
263 : mlir::OpConversionPattern<hlfir::AssignOp>{ctx} {}
264 llvm::LogicalResult
265 matchAndRewrite(hlfir::AssignOp assign, OpAdaptor adaptor,
266 mlir::ConversionPatternRewriter &rewriter) const override {
267 llvm::SmallVector<mlir::Value> newOperands;
268 for (mlir::Value operand : adaptor.getOperands())
269 newOperands.push_back(getBufferizedExprStorage(operand));
270 rewriter.startOpModification(assign);
271 assign->setOperands(newOperands);
272 rewriter.finalizeOpModification(assign);
273 return mlir::success();
274 }
275 };
276
277 struct ConcatOpConversion : public mlir::OpConversionPattern<hlfir::ConcatOp> {
278 using mlir::OpConversionPattern<hlfir::ConcatOp>::OpConversionPattern;
279 explicit ConcatOpConversion(mlir::MLIRContext *ctx)
280 : mlir::OpConversionPattern<hlfir::ConcatOp>{ctx} {}
281 llvm::LogicalResult
282 matchAndRewrite(hlfir::ConcatOp concat, OpAdaptor adaptor,
283 mlir::ConversionPatternRewriter &rewriter) const override {
284 mlir::Location loc = concat->getLoc();
285 fir::FirOpBuilder builder(rewriter, concat.getOperation());
286 assert(adaptor.getStrings().size() >= 2 &&
287 "must have at least two strings operands");
288 if (adaptor.getStrings().size() > 2)
289 TODO(loc, "codegen of optimized chained concatenation of more than two "
290 "strings");
291 hlfir::Entity lhs = getBufferizedExprStorage(adaptor.getStrings()[0]);
292 hlfir::Entity rhs = getBufferizedExprStorage(adaptor.getStrings()[1]);
293 auto [lhsExv, c1] = hlfir::translateToExtendedValue(loc, builder, lhs);
294 auto [rhsExv, c2] = hlfir::translateToExtendedValue(loc, builder, rhs);
295 assert(!c1 && !c2 && "expected variables");
296 fir::ExtendedValue res =
297 fir::factory::CharacterExprHelper{builder, loc}.createConcatenate(
298 *lhsExv.getCharBox(), *rhsExv.getCharBox());
299 // Ensure the memory type is the same as the result type.
300 mlir::Type addrType = fir::ReferenceType::get(
301 hlfir::getFortranElementType(concat.getResult().getType()));
302 mlir::Value cast = builder.createConvert(loc, addrType, fir::getBase(res));
303 res = fir::substBase(res, cast);
304 hlfir::Entity hlfirTempRes =
305 hlfir::Entity{hlfir::genDeclare(loc, builder, res, "tmp",
306 fir::FortranVariableFlagsAttr{})
307 .getBase()};
308 mlir::Value bufferizedExpr =
309 packageBufferizedExpr(loc, builder, hlfirTempRes, false);
310 rewriter.replaceOp(concat, bufferizedExpr);
311 return mlir::success();
312 }
313 };
314
315 struct SetLengthOpConversion
316 : public mlir::OpConversionPattern<hlfir::SetLengthOp> {
317 using mlir::OpConversionPattern<hlfir::SetLengthOp>::OpConversionPattern;
318 explicit SetLengthOpConversion(mlir::MLIRContext *ctx)
319 : mlir::OpConversionPattern<hlfir::SetLengthOp>{ctx} {}
320 llvm::LogicalResult
321 matchAndRewrite(hlfir::SetLengthOp setLength, OpAdaptor adaptor,
322 mlir::ConversionPatternRewriter &rewriter) const override {
323 mlir::Location loc = setLength->getLoc();
324 fir::FirOpBuilder builder(rewriter, setLength.getOperation());
325 // Create a temp with the new length.
326 hlfir::Entity string = getBufferizedExprStorage(adaptor.getString());
327 auto charType = hlfir::getFortranElementType(setLength.getType());
328 llvm::StringRef tmpName{".tmp"};
329 llvm::SmallVector<mlir::Value, 1> lenParams{adaptor.getLength()};
330 auto alloca = builder.createTemporary(loc, charType, tmpName,
331 /*shape=*/std::nullopt, lenParams);
332 auto declareOp = builder.create<hlfir::DeclareOp>(
333 loc, alloca, tmpName, /*shape=*/mlir::Value{}, lenParams,
334 /*dummy_scope=*/nullptr, fir::FortranVariableFlagsAttr{});
335 hlfir::Entity temp{declareOp.getBase()};
336 // Assign string value to the created temp.
337 builder.create<hlfir::AssignOp>(loc, string, temp,
338 /*realloc=*/false,
339 /*keep_lhs_length_if_realloc=*/false,
340 /*temporary_lhs=*/true);
341 mlir::Value bufferizedExpr =
342 packageBufferizedExpr(loc, builder, temp, false);
343 rewriter.replaceOp(setLength, bufferizedExpr);
344 return mlir::success();
345 }
346 };
347
348 struct GetLengthOpConversion
349 : public mlir::OpConversionPattern<hlfir::GetLengthOp> {
350 using mlir::OpConversionPattern<hlfir::GetLengthOp>::OpConversionPattern;
351 explicit GetLengthOpConversion(mlir::MLIRContext *ctx)
352 : mlir::OpConversionPattern<hlfir::GetLengthOp>{ctx} {}
353 llvm::LogicalResult
354 matchAndRewrite(hlfir::GetLengthOp getLength, OpAdaptor adaptor,
355 mlir::ConversionPatternRewriter &rewriter) const override {
356 mlir::Location loc = getLength->getLoc();
357 fir::FirOpBuilder builder(rewriter, getLength.getOperation());
358 hlfir::Entity bufferizedExpr = getBufferizedExprStorage(adaptor.getExpr());
359 mlir::Value length = hlfir::genCharLength(loc, builder, bufferizedExpr);
360 if (!length)
361 return rewriter.notifyMatchFailure(
362 getLength, "could not deduce length from GetLengthOp operand");
363 rewriter.replaceOp(getLength, length);
364 return mlir::success();
365 }
366 };
367
368 /// The current hlfir.associate lowering does not handle multiple uses of a
369 /// non-trivial expression value because it generates the cleanup for the
370 /// expression bufferization at hlfir.end_associate. If there was more than one
371 /// hlfir.end_associate, it would be cleaned up multiple times, perhaps before
372 /// one of the other uses.
373 /// Note that we have to be careful about expressions used by a single
374 /// hlfir.end_associate that may be executed more times than the producer
375 /// of the expression value. This may also cause multiple clean-ups
376 /// for the same memory (e.g. cause double-free errors). For example,
377 /// hlfir.end_associate inside hlfir.elemental may cause such issues
378 /// for expressions produced outside of hlfir.elemental.
379 static bool allOtherUsesAreSafeForAssociate(mlir::Value value,
380 mlir::Operation *currentUse,
381 mlir::Operation *endAssociate) {
382 // If value producer is from a different region than
383 // hlfir.associate/end_associate, then conservatively assume
384 // that the hlfir.end_associate may execute more times than
385 // the value producer.
386 // TODO: this may be improved for operations that cannot
387 // result in multiple executions (e.g. ifOp).
388 if (value.getParentRegion() != currentUse->getParentRegion() ||
389 (endAssociate &&
390 value.getParentRegion() != endAssociate->getParentRegion()))
391 return false;
392
393 for (mlir::Operation *useOp : value.getUsers()) {
394 // Ignore DestroyOp's that do not imply finalization.
395 // If finalization is implied, then we must delegate
396 // the finalization to the correspoding EndAssociateOp,
397 // but we currently do not; so we disable the buffer
398 // reuse in this case.
399 if (auto destroy = mlir::dyn_cast<hlfir::DestroyOp>(useOp)) {
400 if (destroy.mustFinalizeExpr())
401 return false;
402 else
403 continue;
404 }
405
406 if (useOp != currentUse) {
407 // hlfir.shape_of and hlfir.get_length will not disrupt cleanup so it is
408 // safe for hlfir.associate. These operations might read from the box and
409 // so they need to come before the hflir.end_associate (which may
410 // deallocate).
411 if (mlir::isa<hlfir::ShapeOfOp>(useOp) ||
412 mlir::isa<hlfir::GetLengthOp>(useOp)) {
413 if (!endAssociate)
414 continue;
415 // If useOp dominates the endAssociate, then it is definitely safe.
416 if (useOp->getBlock() != endAssociate->getBlock())
417 if (mlir::DominanceInfo{}.dominates(useOp, endAssociate))
418 continue;
419 if (useOp->isBeforeInBlock(endAssociate))
420 continue;
421 }
422 return false;
423 }
424 }
425 return true;
426 }
427
428 static void eraseAllUsesInDestroys(mlir::Value value,
429 mlir::ConversionPatternRewriter &rewriter) {
430 for (mlir::Operation *useOp : value.getUsers())
431 if (auto destroy = mlir::dyn_cast<hlfir::DestroyOp>(useOp)) {
432 assert(!destroy.mustFinalizeExpr() &&
433 "deleting DestroyOp with finalize attribute");
434 rewriter.eraseOp(destroy);
435 }
436 }
437
438 struct AssociateOpConversion
439 : public mlir::OpConversionPattern<hlfir::AssociateOp> {
440 using mlir::OpConversionPattern<hlfir::AssociateOp>::OpConversionPattern;
441 explicit AssociateOpConversion(mlir::MLIRContext *ctx)
442 : mlir::OpConversionPattern<hlfir::AssociateOp>{ctx} {}
443 llvm::LogicalResult
444 matchAndRewrite(hlfir::AssociateOp associate, OpAdaptor adaptor,
445 mlir::ConversionPatternRewriter &rewriter) const override {
446 mlir::Location loc = associate->getLoc();
447 fir::FirOpBuilder builder(rewriter, associate.getOperation());
448 mlir::Value bufferizedExpr = getBufferizedExprStorage(adaptor.getSource());
449 const bool isTrivialValue = fir::isa_trivial(bufferizedExpr.getType());
450
451 auto getEndAssociate =
452 [](hlfir::AssociateOp associate) -> mlir::Operation * {
453 for (mlir::Operation *useOp : associate->getUsers())
454 if (mlir::isa<hlfir::EndAssociateOp>(useOp))
455 return useOp;
456 // happens in some hand coded mlir in tests
457 return nullptr;
458 };
459
460 auto replaceWith = [&](mlir::Value hlfirVar, mlir::Value firVar,
461 mlir::Value flag) {
462 // 0-dim variables may need special handling:
463 // %0 = hlfir.as_expr %x move %true :
464 // (!fir.box<!fir.heap<!fir.type<_T{y:i32}>>>, i1) ->
465 // !hlfir.expr<!fir.type<_T{y:i32}>>
466 // %1:3 = hlfir.associate %0 {adapt.valuebyref} :
467 // (!hlfir.expr<!fir.type<_T{y:i32}>>) ->
468 // (!fir.ref<!fir.type<_T{y:i32}>>,
469 // !fir.ref<!fir.type<_T{y:i32}>>,
470 // i1)
471 //
472 // !fir.box<!fir.heap<!fir.type<_T{y:i32}>>> value must be
473 // propagated as the box address !fir.ref<!fir.type<_T{y:i32}>>.
474 auto adjustVar = [&](mlir::Value sourceVar, mlir::Type assocType) {
475 if (mlir::isa<fir::ReferenceType>(sourceVar.getType()) &&
476 mlir::isa<fir::ClassType>(
477 fir::unwrapRefType(sourceVar.getType()))) {
478 // Association of a polymorphic value.
479 sourceVar = builder.create<fir::LoadOp>(loc, sourceVar);
480 assert(mlir::isa<fir::ClassType>(sourceVar.getType()) &&
481 fir::isAllocatableType(sourceVar.getType()));
482 assert(sourceVar.getType() == assocType);
483 } else if ((mlir::isa<fir::BaseBoxType>(sourceVar.getType()) &&
484 !mlir::isa<fir::BaseBoxType>(assocType)) ||
485 ((mlir::isa<fir::BoxCharType>(sourceVar.getType()) &&
486 !mlir::isa<fir::BoxCharType>(assocType)))) {
487 sourceVar = builder.create<fir::BoxAddrOp>(loc, assocType, sourceVar);
488 } else {
489 sourceVar = builder.createConvert(loc, assocType, sourceVar);
490 }
491 return sourceVar;
492 };
493
494 mlir::Type associateHlfirVarType = associate.getResultTypes()[0];
495 hlfirVar = adjustVar(hlfirVar, associateHlfirVarType);
496 associate.getResult(0).replaceAllUsesWith(hlfirVar);
497
498 mlir::Type associateFirVarType = associate.getResultTypes()[1];
499 firVar = adjustVar(firVar, associateFirVarType);
500 associate.getResult(1).replaceAllUsesWith(firVar);
501 associate.getResult(2).replaceAllUsesWith(flag);
502 // FIXME: note that the AssociateOp that is being erased
503 // here will continue to be a user of the original Source
504 // operand (e.g. a result of hlfir.elemental), because
505 // the erasure is not immediate in the rewriter.
506 // In case there are multiple uses of the Source operand,
507 // the allOtherUsesAreSafeForAssociate() below will always
508 // see them, so there is no way to reuse the buffer.
509 // I think we have to run this analysis before doing
510 // the conversions, so that we can analyze HLFIR in its
511 // original form and decide which of the AssociateOp
512 // users of hlfir.expr can reuse the buffer (if it can).
513 rewriter.eraseOp(associate);
514 };
515
516 // If this is the last use of the expression value and this is an hlfir.expr
517 // that was bufferized, re-use the storage.
518 // Otherwise, create a temp and assign the storage to it.
519 //
520 // WARNING: it is important to use the original Source operand
521 // of the AssociateOp to look for the users, because its replacement
522 // has zero materialized users at this point.
523 // So allOtherUsesAreSafeForAssociate() may incorrectly return
524 // true here.
525 if (!isTrivialValue && allOtherUsesAreSafeForAssociate(
526 associate.getSource(), associate.getOperation(),
527 getEndAssociate(associate))) {
528 // Re-use hlfir.expr buffer if this is the only use of the hlfir.expr
529 // outside of the hlfir.destroy. Take on the cleaning-up responsibility
530 // for the related hlfir.end_associate, and erase the hlfir.destroy (if
531 // any).
532 mlir::Value mustFree = getBufferizedExprMustFreeFlag(adaptor.getSource());
533 mlir::Value firBase = hlfir::Entity{bufferizedExpr}.getFirBase();
534 replaceWith(bufferizedExpr, firBase, mustFree);
535 eraseAllUsesInDestroys(associate.getSource(), rewriter);
536 // Make sure to erase the hlfir.destroy if there is an indirection through
537 // a hlfir.no_reassoc operation.
538 if (auto noReassoc = mlir::dyn_cast_or_null<hlfir::NoReassocOp>(
539 associate.getSource().getDefiningOp()))
540 eraseAllUsesInDestroys(noReassoc.getVal(), rewriter);
541 return mlir::success();
542 }
543 if (isTrivialValue) {
544 llvm::SmallVector<mlir::NamedAttribute, 1> attrs;
545 if (associate->hasAttr(fir::getAdaptToByRefAttrName())) {
546 attrs.push_back(fir::getAdaptToByRefAttr(builder));
547 }
548 llvm::StringRef name = "";
549 if (associate.getUniqName())
550 name = *associate.getUniqName();
551 auto temp =
552 builder.createTemporary(loc, bufferizedExpr.getType(), name, attrs);
553 builder.create<fir::StoreOp>(loc, bufferizedExpr, temp);
554 mlir::Value mustFree = builder.createBool(loc, false);
555 replaceWith(temp, temp, mustFree);
556 return mlir::success();
557 }
558 // non-trivial value with more than one use. We will have to make a copy and
559 // use that
560 hlfir::Entity source = hlfir::Entity{bufferizedExpr};
561 mlir::Value bufferTuple = copyInTempAndPackage(loc, builder, source);
562 bufferizedExpr = getBufferizedExprStorage(bufferTuple);
563 replaceWith(bufferizedExpr, hlfir::Entity{bufferizedExpr}.getFirBase(),
564 getBufferizedExprMustFreeFlag(bufferTuple));
565 return mlir::success();
566 }
567 };
568
569 static void genBufferDestruction(mlir::Location loc, fir::FirOpBuilder &builder,
570 mlir::Value var, mlir::Value mustFree,
571 bool mustFinalize) {
572 auto genFreeOrFinalize = [&](bool doFree, bool deallocComponents,
573 bool doFinalize) {
574 if (!doFree && !deallocComponents && !doFinalize)
575 return;
576
577 mlir::Value addr = var;
578
579 // fir::FreeMemOp operand type must be a fir::HeapType.
580 mlir::Type heapType = fir::HeapType::get(
581 hlfir::getFortranElementOrSequenceType(var.getType()));
582 if (mlir::isa<fir::ReferenceType>(var.getType()) &&
583 mlir::isa<fir::ClassType>(fir::unwrapRefType(var.getType()))) {
584 // A temporary for a polymorphic expression is represented
585 // via an allocatable. Variable type in this case
586 // is !fir.ref<!fir.class<!fir.heap<!fir.type<>>>>.
587 // We need to free the allocatable data, not the box
588 // that is allocated on the stack.
589 var = builder.create<fir::LoadOp>(loc, var);
590 assert(mlir::isa<fir::ClassType>(var.getType()) &&
591 fir::isAllocatableType(var.getType()));
592 addr = builder.create<fir::BoxAddrOp>(loc, heapType, var);
593 // Lowering currently does not produce DestroyOp with 'finalize'
594 // for polymorphic temporaries. It will have to do so, for example,
595 // for MERGE with polymorphic results.
596 if (mustFinalize)
597 TODO(loc, "finalizing polymorphic temporary in HLFIR");
598 } else if (mlir::isa<fir::BaseBoxType, fir::BoxCharType>(var.getType())) {
599 if (mustFinalize && !mlir::isa<fir::BaseBoxType>(var.getType()))
600 fir::emitFatalError(loc, "non-finalizable variable");
601
602 addr = builder.create<fir::BoxAddrOp>(loc, heapType, var);
603 } else {
604 if (!mlir::isa<fir::HeapType>(var.getType()))
605 addr = builder.create<fir::ConvertOp>(loc, heapType, var);
606
607 if (mustFinalize || deallocComponents) {
608 // Embox the raw pointer using proper shape and type params
609 // (note that the shape might be visible via the array finalization
610 // routines).
611 if (!hlfir::isFortranEntity(var))
612 TODO(loc, "need a Fortran entity to create a box");
613
614 hlfir::Entity entity{var};
615 llvm::SmallVector<mlir::Value> lenParams;
616 hlfir::genLengthParameters(loc, builder, entity, lenParams);
617 mlir::Value shape;
618 if (entity.isArray())
619 shape = hlfir::genShape(loc, builder, entity);
620 mlir::Type boxType = fir::BoxType::get(heapType);
621 var = builder.createBox(loc, boxType, addr, shape, /*slice=*/nullptr,
622 lenParams, /*tdesc=*/nullptr);
623 }
624 }
625
626 if (mustFinalize)
627 fir::runtime::genDerivedTypeFinalize(builder, loc, var);
628
629 // If there are allocatable components, they need to be deallocated
630 // (regardless of the mustFree and mustFinalize settings).
631 if (deallocComponents)
632 fir::runtime::genDerivedTypeDestroyWithoutFinalization(builder, loc, var);
633
634 if (doFree)
635 builder.create<fir::FreeMemOp>(loc, addr);
636 };
637 bool deallocComponents = hlfir::mayHaveAllocatableComponent(var.getType());
638
639 auto genFree = [&]() {
640 genFreeOrFinalize(/*doFree=*/true, /*deallocComponents=*/false,
641 /*doFinalize=*/false);
642 };
643 if (auto cstMustFree = fir::getIntIfConstant(mustFree)) {
644 genFreeOrFinalize(*cstMustFree != 0 ? true : false, deallocComponents,
645 mustFinalize);
646 return;
647 }
648
649 // If mustFree is dynamic, first, deallocate any allocatable
650 // components and finalize.
651 genFreeOrFinalize(/*doFree=*/false, deallocComponents,
652 /*doFinalize=*/mustFinalize);
653 // Conditionally free the memory.
654 builder.genIfThen(loc, mustFree).genThen(genFree).end();
655 }
656
657 struct EndAssociateOpConversion
658 : public mlir::OpConversionPattern<hlfir::EndAssociateOp> {
659 using mlir::OpConversionPattern<hlfir::EndAssociateOp>::OpConversionPattern;
660 explicit EndAssociateOpConversion(mlir::MLIRContext *ctx)
661 : mlir::OpConversionPattern<hlfir::EndAssociateOp>{ctx} {}
662 llvm::LogicalResult
663 matchAndRewrite(hlfir::EndAssociateOp endAssociate, OpAdaptor adaptor,
664 mlir::ConversionPatternRewriter &rewriter) const override {
665 mlir::Location loc = endAssociate->getLoc();
666 fir::FirOpBuilder builder(rewriter, endAssociate.getOperation());
667 genBufferDestruction(loc, builder, adaptor.getVar(), adaptor.getMustFree(),
668 /*mustFinalize=*/false);
669 rewriter.eraseOp(endAssociate);
670 return mlir::success();
671 }
672 };
673
674 struct DestroyOpConversion
675 : public mlir::OpConversionPattern<hlfir::DestroyOp> {
676 using mlir::OpConversionPattern<hlfir::DestroyOp>::OpConversionPattern;
677 explicit DestroyOpConversion(mlir::MLIRContext *ctx)
678 : mlir::OpConversionPattern<hlfir::DestroyOp>{ctx} {}
679 llvm::LogicalResult
680 matchAndRewrite(hlfir::DestroyOp destroy, OpAdaptor adaptor,
681 mlir::ConversionPatternRewriter &rewriter) const override {
682 // If expr was bufferized on the heap, now is time to deallocate the buffer.
683 mlir::Location loc = destroy->getLoc();
684 hlfir::Entity bufferizedExpr = getBufferizedExprStorage(adaptor.getExpr());
685 if (!fir::isa_trivial(bufferizedExpr.getType())) {
686 fir::FirOpBuilder builder(rewriter, destroy.getOperation());
687 mlir::Value mustFree = getBufferizedExprMustFreeFlag(adaptor.getExpr());
688 // Passing FIR base might be enough for cases when
689 // component deallocation and finalization are not required.
690 // If extra BoxAddr operations become a performance problem,
691 // we may pass both bases and let genBufferDestruction decide
692 // which one to use.
693 mlir::Value base = bufferizedExpr.getBase();
694 genBufferDestruction(loc, builder, base, mustFree,
695 destroy.mustFinalizeExpr());
696 }
697
698 rewriter.eraseOp(destroy);
699 return mlir::success();
700 }
701 };
702
703 struct NoReassocOpConversion
704 : public mlir::OpConversionPattern<hlfir::NoReassocOp> {
705 using mlir::OpConversionPattern<hlfir::NoReassocOp>::OpConversionPattern;
706 explicit NoReassocOpConversion(mlir::MLIRContext *ctx)
707 : mlir::OpConversionPattern<hlfir::NoReassocOp>{ctx} {}
708 llvm::LogicalResult
709 matchAndRewrite(hlfir::NoReassocOp noreassoc, OpAdaptor adaptor,
710 mlir::ConversionPatternRewriter &rewriter) const override {
711 mlir::Location loc = noreassoc->getLoc();
712 fir::FirOpBuilder builder(rewriter, noreassoc.getOperation());
713 mlir::Value bufferizedExpr = getBufferizedExprStorage(adaptor.getVal());
714 mlir::Value result =
715 builder.create<hlfir::NoReassocOp>(loc, bufferizedExpr);
716
717 if (!fir::isa_trivial(bufferizedExpr.getType())) {
718 // NoReassocOp should not be needed on the mustFree path.
719 mlir::Value mustFree = getBufferizedExprMustFreeFlag(adaptor.getVal());
720 result =
721 packageBufferizedExpr(loc, builder, hlfir::Entity{result}, mustFree);
722 }
723 rewriter.replaceOp(noreassoc, result);
724 return mlir::success();
725 }
726 };
727
728 /// Was \p value created in the mlir block where \p builder is currently set ?
729 static bool wasCreatedInCurrentBlock(mlir::Value value,
730 fir::FirOpBuilder &builder) {
731 if (mlir::Operation *op = value.getDefiningOp())
732 return op->getBlock() == builder.getBlock();
733 return false;
734 }
735
736 /// This Listener allows setting both the builder and the rewriter as
737 /// listeners. This is required when a pattern uses a firBuilder helper that
738 /// may create illegal operations that will need to be translated and requires
739 /// notifying the rewriter.
740 struct HLFIRListener : public mlir::OpBuilder::Listener {
741 HLFIRListener(fir::FirOpBuilder &builder,
742 mlir::ConversionPatternRewriter &rewriter)
743 : builder{builder}, rewriter{rewriter} {}
744 void notifyOperationInserted(mlir::Operation *op,
745 mlir::OpBuilder::InsertPoint previous) override {
746 builder.notifyOperationInserted(op, previous);
747 rewriter.getListener()->notifyOperationInserted(op, previous);
748 }
749 virtual void notifyBlockInserted(mlir::Block *block, mlir::Region *previous,
750 mlir::Region::iterator previousIt) override {
751 builder.notifyBlockInserted(block, previous, previousIt);
752 rewriter.getListener()->notifyBlockInserted(block, previous, previousIt);
753 }
754 fir::FirOpBuilder &builder;
755 mlir::ConversionPatternRewriter &rewriter;
756 };
757
758 struct ElementalOpConversion
759 : public mlir::OpConversionPattern<hlfir::ElementalOp> {
760 using mlir::OpConversionPattern<hlfir::ElementalOp>::OpConversionPattern;
761 explicit ElementalOpConversion(mlir::MLIRContext *ctx)
762 : mlir::OpConversionPattern<hlfir::ElementalOp>{ctx} {
763 // This pattern recursively converts nested ElementalOp's
764 // by cloning and then converting them, so we have to allow
765 // for recursive pattern application. The recursion is bounded
766 // by the nesting level of ElementalOp's.
767 setHasBoundedRewriteRecursion();
768 }
769 llvm::LogicalResult
770 matchAndRewrite(hlfir::ElementalOp elemental, OpAdaptor adaptor,
771 mlir::ConversionPatternRewriter &rewriter) const override {
772 mlir::Location loc = elemental->getLoc();
773 fir::FirOpBuilder builder(rewriter, elemental.getOperation());
774 // The body of the elemental op may contain operation that will require
775 // to be translated. Notify the rewriter about the cloned operations.
776 HLFIRListener listener{builder, rewriter};
777 builder.setListener(&listener);
778
779 mlir::Value shape = adaptor.getShape();
780 std::optional<hlfir::Entity> mold;
781 if (adaptor.getMold())
782 mold = getBufferizedExprStorage(adaptor.getMold());
783 auto extents = hlfir::getIndexExtents(loc, builder, shape);
784 auto [temp, cleanup] =
785 createArrayTemp(loc, builder, elemental.getType(), shape, extents,
786 adaptor.getTypeparams(), mold);
787 // If the box load is needed, we'd better place it outside
788 // of the loop nest.
789 temp = derefPointersAndAllocatables(loc, builder, temp);
790
791 // Generate a loop nest looping around the fir.elemental shape and clone
792 // fir.elemental region inside the inner loop.
793 hlfir::LoopNest loopNest =
794 hlfir::genLoopNest(loc, builder, extents, !elemental.isOrdered());
795 auto insPt = builder.saveInsertionPoint();
796 builder.setInsertionPointToStart(loopNest.innerLoop.getBody());
797 auto yield = hlfir::inlineElementalOp(loc, builder, elemental,
798 loopNest.oneBasedIndices);
799 hlfir::Entity elementValue(yield.getElementValue());
800 // Skip final AsExpr if any. It would create an element temporary,
801 // which is no needed since the element will be assigned right away in
802 // the array temporary. An hlfir.as_expr may have been added if the
803 // elemental is a "view" over a variable (e.g parentheses or transpose).
804 if (auto asExpr = elementValue.getDefiningOp<hlfir::AsExprOp>()) {
805 if (asExpr->hasOneUse() && !asExpr.isMove()) {
806 elementValue = hlfir::Entity{asExpr.getVar()};
807 rewriter.eraseOp(asExpr);
808 }
809 }
810 rewriter.eraseOp(yield);
811 // Assign the element value to the temp element for this iteration.
812 auto tempElement =
813 hlfir::getElementAt(loc, builder, temp, loopNest.oneBasedIndices);
814 // If the elemental result is a temporary of a derived type,
815 // we can avoid the deep copy implied by the AssignOp and just
816 // do the shallow copy with load/store. This helps avoiding the overhead
817 // of deallocating allocatable components of the temporary (if any)
818 // on each iteration of the elemental operation.
819 auto asExpr = elementValue.getDefiningOp<hlfir::AsExprOp>();
820 auto elemType = hlfir::getFortranElementType(elementValue.getType());
821 if (asExpr && asExpr.isMove() && mlir::isa<fir::RecordType>(elemType) &&
822 hlfir::mayHaveAllocatableComponent(elemType) &&
823 wasCreatedInCurrentBlock(elementValue, builder)) {
824 auto load = builder.create<fir::LoadOp>(loc, asExpr.getVar());
825 builder.create<fir::StoreOp>(loc, load, tempElement);
826 } else {
827 builder.create<hlfir::AssignOp>(loc, elementValue, tempElement,
828 /*realloc=*/false,
829 /*keep_lhs_length_if_realloc=*/false,
830 /*temporary_lhs=*/true);
831
832 // hlfir.yield_element implicitly marks the end-of-life its operand if
833 // it is an expression created in the hlfir.elemental (since it is its
834 // last use and an hlfir.destroy could not be created afterwards)
835 // Now that this node has been removed and the expression has been used in
836 // the assign, insert an hlfir.destroy to mark the expression end-of-life.
837 // If the expression creation allocated a buffer on the heap inside the
838 // loop, this will ensure the buffer properly deallocated.
839 if (mlir::isa<hlfir::ExprType>(elementValue.getType()) &&
840 wasCreatedInCurrentBlock(elementValue, builder))
841 builder.create<hlfir::DestroyOp>(loc, elementValue);
842 }
843 builder.restoreInsertionPoint(insPt);
844
845 mlir::Value bufferizedExpr =
846 packageBufferizedExpr(loc, builder, temp, cleanup);
847 // Explicitly delete the body of the elemental to get rid
848 // of any users of hlfir.expr values inside the body as early
849 // as possible.
850 rewriter.startOpModification(elemental);
851 rewriter.eraseBlock(elemental.getBody());
852 rewriter.finalizeOpModification(elemental);
853 rewriter.replaceOp(elemental, bufferizedExpr);
854 return mlir::success();
855 }
856 };
857 struct CharExtremumOpConversion
858 : public mlir::OpConversionPattern<hlfir::CharExtremumOp> {
859 using mlir::OpConversionPattern<hlfir::CharExtremumOp>::OpConversionPattern;
860 explicit CharExtremumOpConversion(mlir::MLIRContext *ctx)
861 : mlir::OpConversionPattern<hlfir::CharExtremumOp>{ctx} {}
862 llvm::LogicalResult
863 matchAndRewrite(hlfir::CharExtremumOp char_extremum, OpAdaptor adaptor,
864 mlir::ConversionPatternRewriter &rewriter) const override {
865 mlir::Location loc = char_extremum->getLoc();
866 auto predicate = char_extremum.getPredicate();
867 bool predIsMin =
868 predicate == hlfir::CharExtremumPredicate::min ? true : false;
869 fir::FirOpBuilder builder(rewriter, char_extremum.getOperation());
870 assert(adaptor.getStrings().size() >= 2 &&
871 "must have at least two strings operands");
872 auto numOperands = adaptor.getStrings().size();
873
874 std::vector<hlfir::Entity> chars;
875 std::vector<
876 std::pair<fir::ExtendedValue, std::optional<hlfir::CleanupFunction>>>
877 pairs;
878 llvm::SmallVector<fir::CharBoxValue> opCBVs;
879 for (size_t i = 0; i < numOperands; ++i) {
880 chars.emplace_back(getBufferizedExprStorage(adaptor.getStrings()[i]));
881 pairs.emplace_back(
882 hlfir::translateToExtendedValue(loc, builder, chars[i]));
883 assert(!pairs[i].second && "expected variables");
884 opCBVs.emplace_back(*pairs[i].first.getCharBox());
885 }
886
887 fir::ExtendedValue res =
888 fir::factory::CharacterExprHelper{builder, loc}.createCharExtremum(
889 predIsMin, opCBVs);
890 mlir::Type addrType = fir::ReferenceType::get(
891 hlfir::getFortranElementType(char_extremum.getResult().getType()));
892 mlir::Value cast = builder.createConvert(loc, addrType, fir::getBase(res));
893 res = fir::substBase(res, cast);
894 hlfir::Entity hlfirTempRes =
895 hlfir::Entity{hlfir::genDeclare(loc, builder, res, ".tmp.char_extremum",
896 fir::FortranVariableFlagsAttr{})
897 .getBase()};
898 mlir::Value bufferizedExpr =
899 packageBufferizedExpr(loc, builder, hlfirTempRes, false);
900 rewriter.replaceOp(char_extremum, bufferizedExpr);
901 return mlir::success();
902 }
903 };
904
905 class BufferizeHLFIR : public hlfir::impl::BufferizeHLFIRBase<BufferizeHLFIR> {
906 public:
907 void runOnOperation() override {
908 // TODO: make this a pass operating on FuncOp. The issue is that
909 // FirOpBuilder helpers may generate new FuncOp because of runtime/llvm
910 // intrinsics calls creation. This may create race conflict if the pass is
911 // scheduled on FuncOp. A solution could be to provide an optional mutex
912 // when building a FirOpBuilder and locking around FuncOp and GlobalOp
913 // creation, but this needs a bit more thinking, so at this point the pass
914 // is scheduled on the moduleOp.
915 auto module = this->getOperation();
916 auto *context = &getContext();
917 mlir::RewritePatternSet patterns(context);
918 patterns.insert<ApplyOpConversion, AsExprOpConversion, AssignOpConversion,
919 AssociateOpConversion, CharExtremumOpConversion,
920 ConcatOpConversion, DestroyOpConversion,
921 ElementalOpConversion, EndAssociateOpConversion,
922 NoReassocOpConversion, SetLengthOpConversion,
923 ShapeOfOpConversion, GetLengthOpConversion>(context);
924 mlir::ConversionTarget target(*context);
925 // Note that YieldElementOp is not marked as an illegal operation.
926 // It must be erased by its parent converter and there is no explicit
927 // conversion pattern to YieldElementOp itself. If any YieldElementOp
928 // survives this pass, the verifier will detect it because it has to be
929 // a child of ElementalOp and ElementalOp's are explicitly illegal.
930 target.addIllegalOp<hlfir::ApplyOp, hlfir::AssociateOp, hlfir::ElementalOp,
931 hlfir::EndAssociateOp, hlfir::SetLengthOp>();
932
933 target.markUnknownOpDynamicallyLegal([](mlir::Operation *op) {
934 return llvm::all_of(op->getResultTypes(),
935 [](mlir::Type ty) {
936 return !mlir::isa<hlfir::ExprType>(ty);
937 }) &&
938 llvm::all_of(op->getOperandTypes(), [](mlir::Type ty) {
939 return !mlir::isa<hlfir::ExprType>(ty);
940 });
941 });
942 if (mlir::failed(
943 mlir::applyFullConversion(module, target, std::move(patterns)))) {
944 mlir::emitError(mlir::UnknownLoc::get(context),
945 "failure in HLFIR bufferization pass");
946 signalPassFailure();
947 }
948 }
949 };
950 } // namespace