10#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
11#include "mlir/IR/Builders.h"
12#include "mlir/IR/Dominance.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/IR/Attributes.h"
21#include "llvm/Support/MathExtras.h"
28using namespace mlir::abi;
71cir::PointerType getPtrTyInAddrSpace(mlir::Type pointee,
unsigned addrSpace) {
72 mlir::ptr::MemorySpaceAttrInterface asAttr;
74 asAttr = cir::TargetAddressSpaceAttr::get(pointee.getContext(), addrSpace);
75 return cir::PointerType::get(pointee, asAttr);
80cir::PointerType getIndirectPtrTy(mlir::Type pointee,
81 const ArgClassification &ac) {
83 (ac.kind == ArgKind::Indirect || ac.kind == ArgKind::IndirectAliased) &&
84 "expected an indirect classification");
85 return getPtrTyInAddrSpace(pointee, ac.indirectAddrSpace);
90cir::StructType getUnionFlattenType(cir::UnionType unionTy,
91 const mlir::DataLayout &dl) {
93 if (mlir::Type storage = unionTy.getUnionStorageType(dl))
94 fields.push_back(storage);
95 if (mlir::Type padding = unionTy.getPadding())
96 fields.push_back(padding);
97 return cir::StructType::get(unionTy.getContext(), fields, unionTy.getPacked(),
114 const mlir::DataLayout &dl) {
115 if (ac.kind != ArgKind::Direct || !ac.coercedType || !ac.canFlatten)
117 auto recTy = dyn_cast<cir::RecordType>(ac.coercedType);
118 if (
auto unionTy = dyn_cast_if_present<cir::UnionType>(recTy))
119 recTy = getUnionFlattenType(unionTy, dl);
120 if (!recTy || !recTy.isStruct() || recTy.getMembers().empty())
128bool isRecordExtend(
const ArgClassification &ac, mlir::Type origTy) {
129 if (ac.kind != ArgKind::Extend || !mlir::isa<cir::RecordType>(origTy))
131 assert(ac.coercedType &&
"an Extend of a record names its first member type");
141mlir::LogicalResult buildNewArgTypes(
143 SmallVectorImpl<mlir::Type> &newArgTypes,
const mlir::DataLayout &dl,
144 function_ref<mlir::InFlightDiagnostic()> emitError) {
145 assert(newArgTypes.empty() &&
"expected an empty output vector");
146 newArgTypes.reserve(oldArgTypes.size());
147 for (
auto [idx, ac] : llvm::enumerate(fc.argInfos)) {
148 mlir::Type origTy = oldArgTypes[idx];
150 case ArgKind::Direct:
154 llvm::append_range(newArgTypes, flatTy.getMembers());
159 newArgTypes.push_back(ac.coercedType ? ac.coercedType : origTy);
162 case ArgKind::Ignore:
164 case ArgKind::Expand: {
168 auto recTy = cast<cir::RecordType>(origTy);
169 assert(recTy.isStruct() &&
170 "Expand classification requires a struct type, not a union");
171 assert(!recTy.getMembers().empty() &&
172 "Expand classification requires at least one struct field");
173 llvm::append_range(newArgTypes, recTy.getMembers());
176 case ArgKind::Extend:
184 newArgTypes.push_back(isRecordExtend(ac, origTy) ? ac.coercedType
187 case ArgKind::Indirect:
188 case ArgKind::IndirectAliased:
189 newArgTypes.push_back(getIndirectPtrTy(origTy, ac));
193 return mlir::success();
201computeNewReturnType(mlir::Type origRetTy,
const ArgClassification &retInfo,
202 mlir::MLIRContext *ctx,
203 function_ref<mlir::InFlightDiagnostic()> emitError) {
204 switch (retInfo.kind) {
205 case ArgKind::Direct:
208 return retInfo.coercedType ? retInfo.coercedType : origRetTy;
209 case ArgKind::Ignore:
210 return cir::VoidType::get(ctx);
211 case ArgKind::Expand:
212 emitError() <<
"Expand return is not allowed (classic codegen rejects "
213 <<
"it in EmitFunctionEpilog)";
215 case ArgKind::IndirectAliased:
216 emitError() <<
"IndirectAliased return is not supported";
218 case ArgKind::Extend:
223 case ArgKind::Indirect:
228 return cir::VoidType::get(ctx);
230 llvm_unreachable(
"all ArgKind cases handled");
238mlir::Value createIgnoredValue(mlir::OpBuilder &builder, mlir::Location loc,
240 return cir::ConstantOp::create(builder, loc, ty, cir::PoisonAttr::get(ty));
248static bool isCoercionWiderThanMemory(mlir::Type origTy, mlir::Type coercedTy,
249 const mlir::DataLayout &dl) {
250 uint64_t memoryBits = dl.getTypeSizeInBits(origTy).getFixedValue();
251 if (
auto vecTy = mlir::dyn_cast<cir::VectorType>(origTy);
252 vecTy && mlir::isa<cir::BoolType>(vecTy.getElementType()))
253 memoryBits = vecTy.getBoolStorageWidth();
254 return dl.getTypeSizeInBits(coercedTy).getFixedValue() > memoryBits;
263static bool needsArgAttrUpdate(
const FunctionClassification &fc) {
264 return llvm::any_of(fc.argInfos, [](
const ArgClassification &ac) {
265 return ac.kind == ArgKind::Ignore || ac.kind == ArgKind::Extend ||
266 ac.kind == ArgKind::Indirect ||
267 ac.kind == ArgKind::IndirectAliased || ac.kind == ArgKind::Expand ||
268 (ac.kind == ArgKind::Direct && (ac.coercedType || ac.directAlign));
282mlir::ArrayAttr updateArgAttrs(mlir::MLIRContext *ctx, mlir::ModuleOp module,
284 mlir::ArrayAttr existingArgAttrs,
285 const FunctionClassification &fc,
286 const mlir::DataLayout &dl,
287 bool enableNoundefAttrs) {
288 mlir::Builder builder(ctx);
290 newArgAttrs.reserve(fc.argInfos.size());
291 for (
auto [oldIdx, ac] : llvm::enumerate(fc.argInfos)) {
292 if (ac.kind == ArgKind::Ignore)
294 mlir::DictionaryAttr existing = builder.getDictionaryAttr({});
295 if (existingArgAttrs && oldIdx < existingArgAttrs.size())
296 existing = mlir::cast<mlir::DictionaryAttr>(existingArgAttrs[oldIdx]);
297 if (ac.kind == ArgKind::Direct && ac.coercedType &&
298 isCoercionWiderThanMemory(origArgTypes[oldIdx], ac.coercedType, dl)) {
299 mlir::NamedAttrList attrs(existing);
300 attrs.erase(mlir::LLVM::LLVMDialect::getNoUndefAttrName());
301 existing = attrs.getDictionary(ctx);
303 if (ac.kind == ArgKind::Direct && ac.directAlign) {
304 mlir::NamedAttrList attrs(existing);
305 attrs.set(mlir::LLVM::LLVMDialect::getStackAlignmentAttrName(),
306 builder.getI64IntegerAttr(ac.directAlign->value()));
307 existing = attrs.getDictionary(ctx);
312 newArgAttrs.append(flatTy.getNumElements(), existing);
313 }
else if (ac.kind == ArgKind::Expand) {
316 auto recTy = cast<cir::RecordType>(origArgTypes[oldIdx]);
317 newArgAttrs.append(recTy.getNumElements(), builder.getDictionaryAttr({}));
318 }
else if (ac.kind == ArgKind::Extend) {
322 StringRef attrName = ac.signExtend
323 ? mlir::LLVM::LLVMDialect::getSExtAttrName()
324 :
mlir::LLVM::LLVMDialect::getZExtAttrName();
325 mlir::NamedAttrList attrs(existing);
326 attrs.set(attrName, builder.getUnitAttr());
327 if (enableNoundefAttrs)
328 attrs.set(mlir::LLVM::LLVMDialect::getNoUndefAttrName(),
329 builder.getUnitAttr());
330 newArgAttrs.push_back(attrs.getDictionary(ctx));
331 }
else if (ac.kind == ArgKind::Indirect) {
339 mlir::Type pointeeTy = origArgTypes[oldIdx];
340 mlir::NamedAttrList attrs(existing);
341 attrs.erase(mlir::LLVM::LLVMDialect::getNoFPClassAttrName());
342 attrs.set(mlir::LLVM::LLVMDialect::getAlignAttrName(),
343 builder.getI64IntegerAttr(ac.indirectAlign.value()));
344 if (enableNoundefAttrs)
345 attrs.set(mlir::LLVM::LLVMDialect::getNoUndefAttrName(),
346 builder.getUnitAttr());
352 attrs.set(mlir::LLVM::LLVMDialect::getByValAttrName(),
353 mlir::TypeAttr::get(pointeeTy));
357 attrs.set(mlir::LLVM::LLVMDialect::getNoFreeObjAttrName(),
358 builder.getUnitAttr());
362 auto recTy = mlir::dyn_cast<cir::RecordType>(pointeeTy);
363 cir::RecordLayoutAttr layout =
365 :
cir::RecordLayoutAttr();
366 if (!layout || layout.getHasTrivialDtor())
367 attrs.set(mlir::LLVM::LLVMDialect::getDeadOnReturnAttrName(),
368 builder.getI64IntegerAttr(
static_cast<int64_t>(
369 llvm::DeadOnReturnInfo().toIntValue())));
370 attrs.set(mlir::LLVM::LLVMDialect::getDereferenceableAttrName(),
371 builder.getI64IntegerAttr(
372 dl.getTypeAllocSize(pointeeTy).getFixedValue()));
374 newArgAttrs.push_back(attrs.getDictionary(ctx));
375 }
else if (ac.kind == ArgKind::IndirectAliased) {
378 mlir::NamedAttrList attrs(existing);
379 attrs.erase(mlir::LLVM::LLVMDialect::getNoFPClassAttrName());
380 attrs.set(mlir::LLVM::LLVMDialect::getAlignAttrName(),
381 builder.getI64IntegerAttr(ac.indirectAlign.value()));
382 if (enableNoundefAttrs)
383 attrs.set(mlir::LLVM::LLVMDialect::getNoUndefAttrName(),
384 builder.getUnitAttr());
385 attrs.set(mlir::LLVM::LLVMDialect::getByRefAttrName(),
386 mlir::TypeAttr::get(origArgTypes[oldIdx]));
387 newArgAttrs.push_back(attrs.getDictionary(ctx));
389 newArgAttrs.push_back(existing);
392 return builder.getArrayAttr(newArgAttrs);
401mlir::ArrayAttr updateResAttrs(mlir::MLIRContext *ctx,
402 mlir::ArrayAttr existingResAttrs,
403 const ArgClassification &retInfo,
404 mlir::Type origRetTy,
405 const mlir::DataLayout &dl) {
406 bool needsNoUndefDrop =
407 retInfo.kind == ArgKind::Direct && retInfo.coercedType &&
408 isCoercionWiderThanMemory(origRetTy, retInfo.coercedType, dl);
409 if (retInfo.kind != ArgKind::Extend && !needsNoUndefDrop)
410 return existingResAttrs;
412 mlir::NamedAttrList attrs;
413 if (existingResAttrs && !existingResAttrs.empty())
415 mlir::cast<mlir::DictionaryAttr>(existingResAttrs[0]).getValue());
416 if (retInfo.kind == ArgKind::Extend)
417 attrs.set(retInfo.signExtend ?
"llvm.signext" :
"llvm.zeroext",
418 mlir::UnitAttr::get(ctx));
419 if (needsNoUndefDrop)
420 attrs.erase(mlir::LLVM::LLVMDialect::getNoUndefAttrName());
421 return mlir::ArrayAttr::get(ctx, {attrs.getDictionary(ctx)});
434static uint64_t coercionByteSize(mlir::Type ty,
const mlir::DataLayout &dl) {
435 if (
auto intTy = mlir::dyn_cast<cir::IntType>(ty))
436 return llvm::divideCeil(intTy.getWidth(), 8);
437 return dl.getTypeSize(ty);
446emitViewAtOffset(mlir::OpBuilder &builder, mlir::Location loc,
447 mlir::Type wantTy, mlir::Value base,
448 SmallPtrSetImpl<mlir::Operation *> &createdOps,
450 auto basePtrTy = mlir::cast<cir::PointerType>(base.getType());
451 if (wantTy == basePtrTy.getPointee()) {
452 assert(offset == 0 &&
"a view of the storage's own type has no offset");
455 mlir::ptr::MemorySpaceAttrInterface addrSpace = basePtrTy.getAddrSpace();
456 mlir::Value view = base;
458 auto u8Ty = cir::IntType::get(builder.getContext(), 8,
false);
459 auto u8PtrTy = cir::PointerType::get(u8Ty, addrSpace);
460 auto u8Base = cir::CastOp::create(builder, loc, u8PtrTy,
461 cir::CastKind::bitcast, base);
462 createdOps.insert(u8Base);
464 cir::IntType::get(builder.getContext(), 64,
true);
465 auto strideVal = cir::ConstantOp::create(
466 builder, loc, cir::IntAttr::get(strideTy, offset));
467 createdOps.insert(strideVal);
468 view = cir::PtrStrideOp::create(builder, loc, u8PtrTy, u8Base, strideVal);
469 createdOps.insert(view.getDefiningOp());
471 auto typedView = cir::CastOp::create(builder, loc,
472 cir::PointerType::get(wantTy, addrSpace),
473 cir::CastKind::bitcast, view);
474 createdOps.insert(typedView);
480static cir::PointerType getAllocaPtrTy(mlir::Type pointee,
481 const mlir::DataLayout &dl) {
482 mlir::ptr::MemorySpaceAttrInterface addrSpace;
483 if (
auto asAttr = mlir::dyn_cast_if_present<mlir::IntegerAttr>(
484 dl.getAllocaMemorySpace()))
485 addrSpace = cir::TargetAddressSpaceAttr::get(pointee.getContext(),
487 return cir::PointerType::get(pointee, addrSpace);
495static cir::AllocaOp createCoercionSlot(
496 mlir::OpBuilder &builder, mlir::Location loc, mlir::Type srcTy,
497 mlir::Type dstTy, mlir::Block *slotBlock,
const mlir::DataLayout &dl,
498 SmallPtrSetImpl<mlir::Operation *> &createdOps,
unsigned offset) {
499 assert(srcTy != dstTy &&
"callers must pre-check that the types differ");
501 uint64_t srcAlign = dl.getTypeABIAlignment(srcTy);
502 uint64_t dstAlign = dl.getTypeABIAlignment(dstTy);
503 uint64_t allocaAlign = std::max(srcAlign, dstAlign);
504 mlir::Type slotTy = coercionByteSize(srcTy, dl) >= coercionByteSize(dstTy, dl)
511 [[maybe_unused]] mlir::Type coercedTy = ((slotTy == srcTy) ? dstTy : srcTy);
512 assert((offset == 0 ||
513 coercionByteSize(coercedTy, dl) < coercionByteSize(slotTy, dl)) &&
514 "a direct offset must land on the coerced side, the smaller one");
515 assert((offset == 0 ||
516 offset + dl.getTypeSize(coercedTy) <= dl.getTypeSize(slotTy)) &&
517 "coerce slot too small for offset access");
518 assert((offset == 0 || offset % dl.getTypeABIAlignment(coercedTy) == 0) &&
519 "a direct offset must be aligned for the coerced access");
521 mlir::OpBuilder::InsertionGuard guard(builder);
522 builder.setInsertionPointToStart(slotBlock);
523 auto alloca = cir::AllocaOp::create(builder, loc, getAllocaPtrTy(slotTy, dl),
524 builder.getStringAttr(
"coerce"),
525 builder.getI64IntegerAttr(allocaAlign));
526 createdOps.insert(alloca);
560mlir::Value emitCoercionToMemory(mlir::OpBuilder &builder, mlir::Location loc,
561 mlir::Type dstTy, mlir::Value src,
562 mlir::Block *slotBlock,
563 const mlir::DataLayout &dl,
564 SmallPtrSetImpl<mlir::Operation *> &createdOps,
566 mlir::Type srcTy = src.getType();
567 cir::AllocaOp alloca = createCoercionSlot(builder, loc, srcTy, dstTy,
568 slotBlock, dl, createdOps, offset);
569 mlir::Type slotTy = alloca.getAllocaType();
572 mlir::Value srcSlot = emitViewAtOffset(
573 builder, loc, srcTy, alloca, createdOps, srcTy == slotTy ? 0 : offset);
574 auto store = cir::StoreOp::create(builder, loc, src, srcSlot);
575 createdOps.insert(store);
578 return emitViewAtOffset(builder, loc, dstTy, alloca, createdOps,
579 dstTy == slotTy ? 0 : offset);
585emitAddrSpaceCoercion(mlir::OpBuilder &builder, mlir::Location loc,
586 mlir::Type dstTy, mlir::Value src,
587 SmallPtrSetImpl<mlir::Operation *> &createdOps,
589 auto srcPtrTy = dyn_cast<cir::PointerType>(src.getType());
590 auto dstPtrTy = dyn_cast<cir::PointerType>(dstTy);
591 if (offset || !srcPtrTy || !dstPtrTy ||
592 srcPtrTy.getPointee() != dstPtrTy.getPointee())
594 assert(srcPtrTy.getAddrSpace() != dstPtrTy.getAddrSpace() &&
595 "pointers to the same pointee must differ in address space");
596 auto cast = cir::CastOp::create(builder, loc, dstTy,
597 cir::CastKind::address_space, src);
598 createdOps.insert(cast);
606mlir::Value emitCoercion(mlir::OpBuilder &builder, mlir::Location loc,
607 mlir::Type dstTy, mlir::Value src,
608 mlir::Block *slotBlock,
const mlir::DataLayout &dl,
609 SmallPtrSetImpl<mlir::Operation *> &createdOps,
611 if (mlir::Value cast =
612 emitAddrSpaceCoercion(builder, loc, dstTy, src, createdOps, offset))
615 mlir::Value dstSlot = emitCoercionToMemory(builder, loc, dstTy, src,
616 slotBlock, dl, createdOps, offset);
617 auto load = cir::LoadOp::create(builder, loc, dstSlot);
618 createdOps.insert(load);
624mlir::Value emitCoercion(mlir::OpBuilder &builder, mlir::Location loc,
625 mlir::Type dstTy, mlir::Value src,
626 mlir::Block *slotBlock,
const mlir::DataLayout &dl,
628 SmallPtrSet<mlir::Operation *, 4> ignored;
629 return emitCoercion(builder, loc, dstTy, src, slotBlock, dl, ignored, offset);
641mlir::Block *coercionSlotBlock(mlir::Operation *op) {
642 if (
auto funcOp = op->getParentOfType<mlir::FunctionOpInterface>())
643 return &funcOp->getRegion(0).front();
644 mlir::Region *region = op->getParentRegion();
645 while (mlir::Region *outer = region->getParentRegion()) {
646 if (mlir::isa<mlir::ModuleOp>(outer->getParentOp()))
650 assert(!region->empty() &&
"coercion slot needs a block to hold the alloca");
651 return ®ion->front();
658static cir::LoadOp maybeGetSimpleLoad(mlir::Value val) {
659 cir::LoadOp load = val.getDefiningOp<cir::LoadOp>();
660 if (!load || load.getIsVolatile() || load.getMemOrder())
668static cir::LoadOp maybeGetCopyableRecordLoad(mlir::Value val) {
669 cir::LoadOp load = val.getDefiningOp<cir::LoadOp>();
670 if (!load || load.getMemOrder() ||
671 !mlir::isa<cir::RecordType>(load.getType()))
679static mlir::LogicalResult rejectAtomicRecordLoad(mlir::Operation *user,
681 auto load = val.getDefiningOp<cir::LoadOp>();
682 if (!load || !load.getMemOrder() ||
683 !mlir::isa<cir::RecordType>(load.getType()))
684 return mlir::success();
685 return user->emitOpError()
686 <<
"atomic load of a record operand not yet implemented in "
694static bool canReadInPlace(cir::LoadOp load, mlir::Type coercedTy,
708static mlir::Value emitInPlaceCoercedLoad(mlir::OpBuilder &builder,
709 mlir::Location loc, cir::LoadOp load,
710 mlir::Type coercedTy,
713 assert(src &&
"the record load must read an alloca");
714 mlir::OpBuilder::InsertionGuard guard(builder);
715 builder.setInsertionPoint(load);
716 SmallPtrSet<mlir::Operation *, 4> ignored;
717 mlir::Value view = emitViewAtOffset(builder, loc, coercedTy, load.getAddr(),
719 auto coerced = cir::LoadOp::create(builder, loc, view);
720 coerced.setAlignment(llvm::MinAlign(src.getAlignment(), offset));
730emitCopiedCoercionSlot(mlir::OpBuilder &builder, mlir::Location loc,
731 cir::LoadOp load, mlir::Type coercedTy,
732 mlir::Block *slotBlock,
const mlir::DataLayout &dl,
734 auto recTy = cast<cir::RecordType>(load.getType());
737 srcAlign = src.getAlignment();
739 srcAlign = load.getAlignment().value_or(dl.getTypeABIAlignment(recTy));
740 SmallPtrSet<mlir::Operation *, 4> ignored;
741 cir::AllocaOp slot = createCoercionSlot(builder, loc, recTy, coercedTy,
742 slotBlock, dl, ignored, offset);
743 slot.setAlignment(std::max(slot.getAlignment(), srcAlign));
744 assert((offset == 0 || slot.getAllocaType() == recTy) &&
745 "a direct offset must leave the record as the slot's type");
746 mlir::OpBuilder::InsertionGuard guard(builder);
747 builder.setInsertionPoint(load);
748 mlir::Value recView =
749 emitViewAtOffset(builder, loc, recTy, slot, ignored, 0);
751 cir::CopyOp::create(builder, loc, recView, load.getAddr(),
752 builder.getI64IntegerAttr(slot.getAlignment()),
753 builder.getI64IntegerAttr(srcAlign));
754 copy.setIsVolatile(load.getIsVolatile());
761static mlir::Value emitCopiedCoercedLoad(mlir::OpBuilder &builder,
762 mlir::Location loc, cir::LoadOp load,
763 mlir::Type coercedTy,
764 mlir::Block *slotBlock,
765 const mlir::DataLayout &dl,
767 cir::AllocaOp slot = emitCopiedCoercionSlot(builder, loc, load, coercedTy,
768 slotBlock, dl, offset);
769 mlir::OpBuilder::InsertionGuard guard(builder);
770 builder.setInsertionPoint(load);
771 SmallPtrSet<mlir::Operation *, 4> ignored;
772 mlir::Value coercedView =
773 emitViewAtOffset(builder, loc, coercedTy, slot, ignored, offset);
774 auto coerced = cir::LoadOp::create(builder, loc, coercedView);
775 coerced.setAlignment(llvm::MinAlign(slot.getAlignment(), offset));
786static mlir::Value emitCoercedRecordLoad(
787 mlir::OpBuilder &builder, mlir::Location loc, cir::LoadOp load,
788 mlir::Type coercedTy, mlir::Block *slotBlock,
const mlir::DataLayout &dl,
790 if (!load.getIsVolatile() &&
791 canReadInPlace(load, coercedTy, cirDataLayout, offset))
792 return emitInPlaceCoercedLoad(builder, loc, load, coercedTy, offset);
793 return emitCopiedCoercedLoad(builder, loc, load, coercedTy, slotBlock, dl,
807static bool shouldSkipTailPadding(mlir::Value dst, mlir::Type ty) {
808 auto structTy = mlir::dyn_cast<cir::StructType>(ty);
813 for (
auto [member,
kind] : llvm::reverse(llvm::zip_equal(members, kinds)))
815 return kind == cir::RecordMemberKind::Pad;
837static mlir::LogicalResult
838rewireRecordUses(mlir::OpBuilder &builder, mlir::Location loc, mlir::Value val,
839 mlir::Value addr,
uint64_t addrAlign,
840 const mlir::DataLayout &dl,
841 const SmallPtrSetImpl<mlir::Operation *> &exceptions) {
842 mlir::Type recTy = mlir::cast<cir::PointerType>(addr.getType()).getPointee();
843 assert(mlir::isa<cir::RecordType>(recTy) &&
"only a record is rewired");
846 for (mlir::OpOperand &use : val.getUses()) {
847 mlir::Operation *user = use.getOwner();
848 if (exceptions.contains(user))
850 if (
auto store = mlir::dyn_cast<cir::StoreOp>(user)) {
851 if (store.getMemOrder())
852 return store.emitOpError()
853 <<
"atomic store of a record argument or result not yet "
854 "implemented in CallConvLowering";
855 stores.push_back(store);
858 auto member = mlir::dyn_cast<cir::ExtractMemberOp>(user);
859 bool isFieldRead =
member && !mlir::isa<cir::RecordType>(
member.getType());
861 !mlir::isa<cir::CIRCallOpInterface, cir::ReturnOp>(user))
862 return user->emitOpError()
863 <<
"use of a record argument or result other than by a store, "
864 "call, return or member read not yet implemented in "
866 otherUses.push_back(&use);
869 mlir::IntegerAttr srcAlign = builder.getI64IntegerAttr(addrAlign);
870 for (cir::StoreOp store : stores) {
871 mlir::OpBuilder::InsertionGuard guard(builder);
872 builder.setInsertionPoint(store);
874 store.getAlignment().value_or(dl.getTypeABIAlignment(recTy));
876 cir::CopyOp::create(builder, store.getLoc(), store.getAddr(), addr,
877 builder.getI64IntegerAttr(dstAlign), srcAlign);
878 copy.setIsVolatile(store.getIsVolatile());
879 copy.setSkipTailPadding(shouldSkipTailPadding(store.getAddr(), recTy));
883 if (otherUses.empty())
884 return mlir::success();
885 auto load = cir::LoadOp::create(builder, loc, addr);
886 load.setAlignment(addrAlign);
887 for (mlir::OpOperand *use : otherUses)
889 return mlir::success();
896static mlir::LogicalResult
897replaceUsesFromSlot(mlir::OpBuilder &builder, mlir::Location loc,
898 mlir::Value val, mlir::Value view,
899 const mlir::DataLayout &dl,
900 const SmallPtrSetImpl<mlir::Operation *> &exceptions) {
901 if (!mlir::isa<cir::RecordType>(
902 mlir::cast<cir::PointerType>(view.getType()).getPointee())) {
903 auto load = cir::LoadOp::create(builder, loc, view);
904 val.replaceAllUsesExcept(load, exceptions);
905 return mlir::success();
908 assert(slot &&
"the view must start at the coercion slot");
909 return rewireRecordUses(builder, loc, val, view, slot.getAlignment(), dl,
920static mlir::LogicalResult
921emitCoercionAndReplaceUses(mlir::OpBuilder &builder, mlir::Location loc,
922 mlir::Type origTy, mlir::Value src, mlir::Value val,
923 mlir::Block *slotBlock,
const mlir::DataLayout &dl,
924 SmallPtrSetImpl<mlir::Operation *> &createdOps,
926 if (mlir::Value cast = emitAddrSpaceCoercion(builder, loc, origTy, src,
927 createdOps, offset)) {
928 val.replaceAllUsesExcept(cast, createdOps);
929 return mlir::success();
931 mlir::Value view = emitCoercionToMemory(builder, loc, origTy, src, slotBlock,
932 dl, createdOps, offset);
933 return replaceUsesFromSlot(builder, loc, val, view, dl, createdOps);
946insertReturnCoercion(mlir::FunctionOpInterface funcOp, mlir::Type origRetTy,
947 mlir::Type coercedRetTy, mlir::OpBuilder &builder,
948 const mlir::DataLayout &dl,
951 funcOp.walk([&](cir::ReturnOp r) { returns.push_back(r); });
952 for (cir::ReturnOp r : returns) {
953 if (r.getInput().empty())
955 mlir::Value origVal = r.getInput()[0];
956 if (origVal.getType() == coercedRetTy)
959 if (failed(rejectAtomicRecordLoad(r, origVal)))
960 return mlir::failure();
961 if (cir::LoadOp recLoad = maybeGetCopyableRecordLoad(origVal)) {
962 mlir::Value coerced = emitCoercedRecordLoad(
963 builder, r.getLoc(), recLoad, coercedRetTy,
964 &funcOp->getRegion(0).front(), dl, cirDataLayout, offset);
965 r->setOperand(0, coerced);
966 if (recLoad->use_empty())
971 builder.setInsertionPoint(r);
972 mlir::Value coerced =
973 emitCoercion(builder, r.getLoc(), coercedRetTy, origVal,
974 &funcOp->getRegion(0).front(), dl, offset);
975 r->setOperand(0, coerced);
977 return mlir::success();
982static cir::LoadOp getWholeRecordLoad(mlir::Value recordVal) {
983 cir::LoadOp load = maybeGetSimpleLoad(recordVal);
1010static mlir::Value forwardableIndirectAddr(cir::LoadOp load,
1011 cir::PointerType paramTy,
1015 mlir::Value addr = load.getAddr();
1017 if (
auto view = addr.getDefiningOp<cir::CastOp>();
1018 view && view.getKind() == cir::CastKind::address_space &&
1019 view.getSrc().getType() == paramTy)
1020 addr = view.getSrc();
1021 if (addr.getType() != paramTy)
1024 return slot && slot.getAlignment() >= minAlign ? addr : mlir::Value();
1037static bool storageUnwrittenBetween(cir::LoadOp load, mlir::Operation *call,
1038 mlir::AliasAnalysis &aliasAnalysis) {
1039 if (load->getBlock() != call->getBlock())
1041 for (mlir::Operation *op = load->getNextNode(); op != call;
1042 op = op->getNextNode()) {
1043 assert(op &&
"the load must precede the call in the block they share");
1044 if (op->getNumRegions() != 0 ||
1045 aliasAnalysis.getModRef(op, load.getAddr()).isMod())
1055static mlir::IntegerAttr loadSourceAlignment(cir::LoadOp load,
1056 mlir::OpBuilder &builder) {
1057 if (mlir::IntegerAttr stated = load.getAlignmentAttr())
1060 return builder.getI64IntegerAttr(slot.getAlignment());
1061 return builder.getI64IntegerAttr(1);
1075static void emitStructFieldArgs(mlir::OpBuilder &builder, mlir::Location loc,
1077 SmallVectorImpl<mlir::Value> &newArgs,
1078 SmallVectorImpl<cir::LoadOp> &deadRecordLoads) {
1079 cir::LoadOp srcLoad = getWholeRecordLoad(structVal);
1082 mlir::OpBuilder::InsertionGuard guard(builder);
1083 builder.setInsertionPoint(srcLoad);
1084 cir::PointerType baseTy = srcLoad.getAddr().getType();
1085 for (
auto [f, fieldTy] : llvm::enumerate(recTy.
getMembers())) {
1086 mlir::Type fieldPtrTy =
1087 cir::PointerType::get(fieldTy, baseTy.getAddrSpace());
1088 mlir::Value fieldPtr = cir::GetMemberOp::create(
1089 builder, loc, fieldPtrTy, srcLoad.getAddr(),
"",
1091 newArgs.push_back(cir::LoadOp::create(builder, loc, fieldPtr));
1093 deadRecordLoads.push_back(srcLoad);
1097 cir::ExtractMemberOp::create(builder, loc, structVal, f));
1108 for (mlir::Operation *load : uniqueLoads)
1109 if (load->use_empty())
1115static cir::StoreOp maybeFindParamSpill(mlir::BlockArgument blockArg) {
1116 if (!blockArg.hasOneUse())
1118 auto store = dyn_cast<cir::StoreOp>(*blockArg.user_begin());
1119 if (!store || store.getValue() != blockArg)
1126static cir::AllocaOp getSpillSlot(mlir::Value addr) {
1127 if (
auto view = addr.getDefiningOp<cir::CastOp>();
1128 view && view.getKind() == cir::CastKind::address_space)
1129 addr = view.getSrc();
1130 return addr.getDefiningOp<cir::AllocaOp>();
1139static std::pair<cir::StoreOp, cir::AllocaOp>
1140findParamSpill(mlir::BlockArgument blockArg) {
1141 if (blockArg.use_empty())
1143 cir::StoreOp store = maybeFindParamSpill(blockArg);
1144 assert(store &&
"non-byval arg's only use must be its CIRGen param spill");
1145 cir::AllocaOp slot = getSpillSlot(store.getAddr());
1146 assert(slot &&
"non-byval arg's spill must store to an alloca");
1147 return {store, slot};
1172insertArgCoercion(mlir::FunctionOpInterface funcOp,
1173 const FunctionClassification &fc, mlir::OpBuilder &builder,
1174 const mlir::DataLayout &dl,
bool hasSRetArg,
1175 SmallVectorImpl<std::pair<cir::AllocaOp, mlir::BlockArgument>>
1176 &pendingParamSlots) {
1177 mlir::Region &body = funcOp->getRegion(0);
1179 return mlir::success();
1180 mlir::Block &entry = body.front();
1186 unsigned blockArgIdx = hasSRetArg ? 1 : 0;
1188 for (
const ArgClassification &ac : fc.argInfos) {
1189 assert(blockArgIdx < entry.getNumArguments() &&
1190 "classification count must not exceed entry block arguments");
1192 if (ac.kind == ArgKind::Expand) {
1196 mlir::BlockArgument origArg = entry.getArgument(blockArgIdx);
1197 auto recTy = cast<cir::RecordType>(origArg.getType());
1199 "Expand classification requires a struct type, not a union");
1201 assert(numFields > 0 &&
1202 "Expand classification requires at least one struct field");
1203 mlir::Location loc = funcOp.getLoc();
1213 cir::StoreOp paramStore;
1214 cir::AllocaOp destAlloca;
1215 if (!origArg.use_empty()) {
1216 assert(origArg.hasOneUse() &&
1217 "Expand arg must have exactly one use (the CIRGen param spill)");
1218 paramStore = cast<cir::StoreOp>(*origArg.user_begin());
1219 assert(paramStore.getValue() == origArg &&
1220 "Expand arg's use must be the value operand of its store");
1221 destAlloca = cast<cir::AllocaOp>(paramStore.getAddr().getDefiningOp());
1228 mlir::Operation *fieldStoreInsertPt =
nullptr;
1230 fieldStoreInsertPt = paramStore->getNextNode();
1231 assert(fieldStoreInsertPt &&
1232 "param spill must be followed by a block terminator");
1233 paramStore->erase();
1244 builder.setInsertionPoint(fieldStoreInsertPt);
1245 for (
auto [f, fieldTy] : llvm::enumerate(recTy.
getMembers())) {
1247 origArg.setType(fieldTy);
1249 entry.insertArgument(blockArgIdx + f, fieldTy, loc);
1252 mlir::Type fieldPtrTy = cir::PointerType::get(
1254 mlir::cast<cir::PointerType>(destAlloca.getType()).getAddrSpace());
1255 auto fieldPtr = cir::GetMemberOp::create(builder, loc, fieldPtrTy,
1258 cir::StoreOp::create(builder, loc, entry.getArgument(blockArgIdx + f),
1262 blockArgIdx += numFields;
1266 mlir::BlockArgument blockArg = entry.getArgument(blockArgIdx);
1274 unsigned numFields = flatTy.getNumElements();
1275 Type origTy = blockArg.getType();
1276 Location loc = funcOp.getLoc();
1279 blockArg.setType(flatTy.getElementType(0));
1280 for (
unsigned f = 1; f < numFields; ++f)
1281 entry.insertArgument(blockArgIdx + f, flatTy.getElementType(f), loc);
1284 builder.setInsertionPointToStart(&entry);
1285 assert(!ac.directOffset &&
1286 "the coerced struct starts at slot offset 0 here, so a flattened "
1287 "coercion cannot honor a direct offset");
1288 SmallPtrSet<Operation *, 8> flattenOps;
1290 if (origTy == flatTy) {
1291 slot = cir::AllocaOp::create(
1292 builder, loc, getAllocaPtrTy(flatTy, dl),
1293 builder.getStringAttr(
"coerce"),
1294 builder.getI64IntegerAttr(dl.getTypeABIAlignment(flatTy)));
1295 flattenOps.insert(slot);
1297 slot = createCoercionSlot(builder, loc, flatTy, origTy, &entry, dl,
1300 Value flatView = emitViewAtOffset(builder, loc, flatTy, slot, flattenOps,
1302 auto flatPtrTy = cast<cir::PointerType>(flatView.getType());
1303 for (
auto [f, fieldTy] : llvm::enumerate(flatTy.getMembers())) {
1305 cir::PointerType::get(fieldTy, flatPtrTy.getAddrSpace());
1306 auto fieldPtr = cir::GetMemberOp::create(builder, loc, fieldPtrTy,
1309 flattenOps.insert(fieldPtr);
1310 auto storeOp = cir::StoreOp::create(
1311 builder, loc, entry.getArgument(blockArgIdx + f), fieldPtr);
1314 llvm::MinAlign(slot.getAlignment(), flatTy.getElementOffset(dl, f));
1315 if (fieldAlign < dl.getTypeABIAlignment(fieldTy))
1316 storeOp.setAlignment(fieldAlign);
1317 flattenOps.insert(storeOp);
1322 Value origView = emitViewAtOffset(builder, loc, origTy, slot, flattenOps,
1324 if (failed(replaceUsesFromSlot(builder, loc, blockArg, origView, dl,
1326 return mlir::failure();
1328 blockArgIdx += numFields;
1332 if ((ac.kind == ArgKind::Direct && ac.coercedType) ||
1333 isRecordExtend(ac, blockArg.getType())) {
1334 mlir::Type oldArgTy = blockArg.getType();
1335 mlir::Type newArgTy = ac.coercedType;
1336 if (oldArgTy == newArgTy) {
1340 blockArg.setType(newArgTy);
1344 builder.setInsertionPointToStart(&entry);
1345 SmallPtrSet<mlir::Operation *, 4> coercionOps;
1346 if (failed(emitCoercionAndReplaceUses(builder, funcOp.getLoc(), oldArgTy,
1347 blockArg, blockArg, &entry, dl,
1348 coercionOps, ac.directOffset)))
1349 return mlir::failure();
1350 }
else if (ac.kind == ArgKind::Indirect ||
1351 ac.kind == ArgKind::IndirectAliased) {
1359 bool byRef = ac.kind == ArgKind::IndirectAliased;
1360 cir::PointerType ptrTy = getIndirectPtrTy(blockArg.getType(), ac);
1362 if (!byRef && !ac.byVal) {
1368 auto [paramStore, destAlloca] = findParamSpill(blockArg);
1371 paramStore->erase();
1374 blockArg.setType(ptrTy);
1383 pendingParamSlots.emplace_back(destAlloca, blockArg);
1390 cir::StoreOp paramStore;
1391 if (mlir::isa<cir::RecordType>(blockArg.getType()))
1392 paramStore = maybeFindParamSpill(blockArg);
1396 mlir::Value destAddr;
1397 mlir::IntegerAttr destAlign;
1398 mlir::Operation *spillPos =
nullptr;
1399 bool spillIsVolatile =
false;
1401 if (paramStore.getMemOrder())
1402 return paramStore.emitOpError()
1403 <<
"atomic store of a record argument or result not yet "
1404 "implemented in CallConvLowering";
1405 spillIsVolatile = paramStore.getIsVolatile();
1406 destAddr = paramStore.getAddr();
1408 destAlign = paramStore.getAlignmentAttr();
1409 if (!destAlign && destAlloca)
1410 destAlign = destAlloca.getAlignmentAttr();
1411 spillPos = paramStore->getNextNode();
1412 assert(spillPos &&
"param spill must be followed by a block "
1414 paramStore->erase();
1417 blockArg.setType(ptrTy);
1420 mlir::OpBuilder::InsertionGuard guard(builder);
1421 builder.setInsertionPoint(spillPos);
1422 auto copy = cir::CopyOp::create(
1423 builder, funcOp.getLoc(), destAddr, blockArg, destAlign,
1424 builder.getI64IntegerAttr(ac.indirectAlign.value()));
1425 copy.setIsVolatile(spillIsVolatile);
1426 copy.setSkipTailPadding(
1427 shouldSkipTailPadding(destAddr, ptrTy.getPointee()));
1428 }
else if (!blockArg.use_empty()) {
1429 builder.setInsertionPointToStart(&entry);
1430 if (mlir::isa<cir::RecordType>(ptrTy.getPointee())) {
1431 SmallPtrSet<mlir::Operation *, 1> noExceptions;
1432 if (failed(rewireRecordUses(builder, funcOp.getLoc(), blockArg,
1433 blockArg, ac.indirectAlign.value(), dl,
1435 return mlir::failure();
1438 cir::LoadOp::create(builder, funcOp.getLoc(), blockArg);
1439 SmallPtrSet<mlir::Operation *, 1> loadOps = {loadOp};
1440 blockArg.replaceAllUsesExcept(loadOp.getResult(), loadOps);
1449 return mlir::success();
1454void replaceAddrSpaceViews(cir::AllocaOp slot, mlir::Value ptr) {
1455 for (mlir::Operation *user : llvm::make_early_inc_range(slot->getUsers())) {
1456 auto view = mlir::dyn_cast<cir::CastOp>(user);
1457 if (view && view.getKind() == cir::CastKind::address_space &&
1458 view.getType() == ptr.getType()) {
1459 view.getResult().replaceAllUsesWith(ptr);
1496void insertSRetStores(mlir::FunctionOpInterface funcOp, mlir::Type origRetTy,
1497 mlir::OpBuilder &builder) {
1498 mlir::Value sretPtr = funcOp.getArguments()[0];
1501 funcOp->walk([&](cir::ReturnOp retOp) { returnOps.push_back(retOp); });
1503 cir::AllocaOp retAlloca =
nullptr;
1504 for (cir::ReturnOp retOp : returnOps) {
1507 assert(!retOp.getInput().empty() &&
1508 "cir.return in sret function must have an operand");
1510 cir::LoadOp retLoad =
1511 mlir::cast<cir::LoadOp>(retOp.getInput()[0].getDefiningOp());
1518 retAlloca = mlir::cast<cir::AllocaOp>(retLoad.getAddr().getDefiningOp());
1519 if (retAlloca.getType() == sretPtr.getType())
1520 retAlloca.getResult().replaceAllUsesWith(sretPtr);
1522 replaceAddrSpaceViews(retAlloca, sretPtr);
1527 builder.setInsertionPoint(retOp);
1528 cir::ReturnOp::create(builder, retOp.getLoc());
1530 if (retLoad.use_empty())
1535 assert(retAlloca->use_empty() &&
1536 "__retval used other than by its returns and address_space views");
1555 builder.getNamedAttr(
"llvm.sret", mlir::TypeAttr::get(retTy)));
1557 builder.getNamedAttr(
"llvm.align", builder.getI64IntegerAttr(align)));
1560 builder.getNamedAttr(
"llvm.noalias", builder.getUnitAttr()));
1561 attrs.push_back(builder.getNamedAttr(
"llvm.writable", builder.getUnitAttr()));
1563 builder.getNamedAttr(
"llvm.dead_on_unwind", builder.getUnitAttr()));
1573void applySretSlotAttrs(cir::CallOp newCall, mlir::ArrayAttr argAttrs,
1575 mlir::OpBuilder &builder) {
1576 mlir::MLIRContext *ctx = newCall->getContext();
1578 buildSretSlotAttrs(builder, retTy, align,
false);
1581 newArgAttrs.reserve(newCall.getArgOperands().size());
1582 newArgAttrs.push_back(mlir::DictionaryAttr::get(ctx, sretAttrs));
1584 llvm::append_range(newArgAttrs, argAttrs);
1585 assert(newArgAttrs.size() <= newCall.getArgOperands().size() &&
1586 "arg_attrs wider than the rewritten call's operand list");
1587 newArgAttrs.resize(newCall.getArgOperands().size(),
1588 mlir::DictionaryAttr::get(ctx));
1589 newCall->setAttr(
"arg_attrs", mlir::ArrayAttr::get(ctx, newArgAttrs));
1596static void copyCallAttributes(cir::CallOp source, cir::CallOp target) {
1597 source->getName().walkInherentAttrs(source, [&](llvm::StringRef name,
1598 mlir::Attribute &attr) {
1599 if (name != cir::CIRDialect::getCalleeAttrName())
1600 target->setInherentAttr(mlir::StringAttr::get(source->getContext(), name),
1603 for (mlir::NamedAttribute attr : source->getDiscardableAttrs())
1604 if (!target->hasDiscardableAttr(
attr.getName()))
1605 target->setDiscardableAttr(
attr.getName(),
attr.getValue());
1616static void prependIndirectCallee(cir::CallOp call,
1617 SmallVectorImpl<mlir::Value> &args,
1618 mlir::Type retTy,
unsigned numEllipsisArgs,
1619 mlir::OpBuilder &builder) {
1620 if (!call.isIndirect())
1622 assert(numEllipsisArgs <= args.size() &&
1623 "more ellipsis arguments than arguments");
1624 mlir::Value calleePtr = call.getIndirectCall();
1626 paramTypes.reserve(args.size() - numEllipsisArgs);
1627 llvm::transform(
ArrayRef(args).drop_back(numEllipsisArgs),
1628 std::back_inserter(paramTypes),
1629 [](mlir::Value v) {
return v.getType(); });
1639 assert((calleeFnTy.isVarArg() || numEllipsisArgs == 0) &&
1640 "only a variadic callee takes arguments through an ellipsis");
1641 auto newPtrTy = cir::PointerType::get(
1642 cir::FuncType::get(paramTypes, retTy, calleeFnTy.isVarArg()));
1643 if (calleePtr.getType() != newPtrTy)
1644 calleePtr = cir::CastOp::create(builder, call.getLoc(), newPtrTy,
1645 cir::CastKind::bitcast, calleePtr);
1646 args.insert(args.begin(), calleePtr);
1660rewriteIndirectReturnCall(cir::CallOp call,
const FunctionClassification &fc,
1662 unsigned numEllipsisArgs, mlir::Type origRetTy,
1664 mlir::OpBuilder &builder,
const mlir::DataLayout &dl,
1665 bool enableNoundefAttrs) {
1666 mlir::MLIRContext *ctx = call->getContext();
1667 cir::PointerType ptrTy = getIndirectPtrTy(origRetTy, fc.returnInfo);
1668 builder.setInsertionPoint(call);
1669 uint64_t sretAlign = fc.returnInfo.indirectAlign.value();
1683 mlir::Value sretSlot =
nullptr;
1684 cir::StoreOp reuseStore =
nullptr;
1685 if (call.getResult().hasOneUse()) {
1686 mlir::Operation *user = *call.getResult().getUsers().begin();
1687 auto store = mlir::dyn_cast<cir::StoreOp>(user);
1688 if (store && store.getValue() == call.getResult()) {
1689 mlir::Value dest = store.getAddr();
1690 if (
auto view = dest.getDefiningOp<cir::CastOp>();
1691 view && view.getKind() == cir::CastKind::address_space &&
1692 view.getSrc().getType() == ptrTy)
1693 dest = view.getSrc();
1694 if (dest.getType() == ptrTy &&
1695 mlir::DominanceInfo().properlyDominates(dest, call)) {
1702 cir::PointerType allocaPtrTy = getAllocaPtrTy(origRetTy, dl);
1703 sretSlot = cir::AllocaOp::create(
1704 builder, call.getLoc(), allocaPtrTy,
1705 builder.getStringAttr(
"sret"),
1706 builder.getI64IntegerAttr(sretAlign));
1708 if (allocaPtrTy != ptrTy)
1709 sretSlot = cir::CastOp::create(builder, call.getLoc(), ptrTy,
1710 cir::CastKind::address_space, sretSlot);
1714 sretArgs.push_back(sretSlot);
1715 sretArgs.append(newArgs.begin(), newArgs.end());
1719 mlir::Type sretVoidTy = cir::VoidType::get(ctx);
1720 prependIndirectCallee(call, sretArgs, sretVoidTy, numEllipsisArgs, builder);
1721 auto newCall = cir::CallOp::create(
1722 builder, call.getLoc(), call.getCalleeAttr(), sretVoidTy, sretArgs);
1723 copyCallAttributes(call, newCall);
1724 newCall->removeAttr(
"res_attrs");
1729 mlir::ArrayAttr argAttrs = call->getAttrOfType<mlir::ArrayAttr>(
"arg_attrs");
1730 if (needsArgAttrUpdate(fc))
1732 updateArgAttrs(ctx, call->getParentOfType<mlir::ModuleOp>(),
1733 origCallArgTypes, argAttrs, fc, dl, enableNoundefAttrs);
1734 applySretSlotAttrs(newCall, argAttrs, origRetTy, sretAlign, builder);
1740 reuseStore->erase();
1741 }
else if (mlir::isa<cir::RecordType>(origRetTy)) {
1742 builder.setInsertionPointAfter(newCall);
1743 SmallPtrSet<mlir::Operation *, 1> noExceptions;
1744 if (failed(rewireRecordUses(builder, call.getLoc(), call.getResult(),
1745 sretSlot, sretAlign, dl, noExceptions)))
1746 return mlir::failure();
1748 builder.setInsertionPointAfter(newCall);
1749 auto load = cir::LoadOp::create(builder, call.getLoc(), origRetTy, sretSlot,
1753 mlir::IntegerAttr(),
1754 cir::SyncScopeKindAttr(),
1755 cir::MemOrderAttr(),
1757 call.getResult().replaceAllUsesWith(load);
1760 return mlir::success();
1765bool isSSERegisterClass(mlir::Type ty) {
1766 return mlir::isa<cir::VectorType, cir::FPTypeInterface>(ty);
1772 assert(call.isIndirect() &&
"expected an indirect call");
1773 return cast<cir::FuncType>(
1774 cast<cir::PointerType>(call.getIndirectCall().getType()).getPointee());
1783 cir::FuncOp funcOp,
unsigned argNo,
const ArgClassification &ac,
1784 mlir::BlockArgument blockArg, mlir::DominanceInfo &dom,
1785 SmallPtrSetImpl<mlir::Operation *> &claimedSlots) {
1786 cir::PointerType paramPtrTy = getIndirectPtrTy(blockArg.getType(), ac);
1793 cir::StoreOp extraSpill;
1794 mlir::Operation *otherUse =
nullptr;
1796 for (mlir::OpOperand &use : blockArg.getUses()) {
1797 auto store = dyn_cast<cir::StoreOp>(use.getOwner());
1798 if (store && store.getValue() == blockArg) {
1812 auto call = dyn_cast<cir::CIRCallOpInterface>(use.getOwner());
1813 if (call && llvm::is_contained(call.getArgOperands(), blockArg))
1814 callArgs.push_back(&use);
1816 otherUse = use.getOwner();
1820 return extraSpill->emitOpError()
1821 <<
"non-byval parameter " << argNo
1822 <<
" spilled more than once is not yet implemented in "
1826 return otherUse->emitOpError()
1827 <<
"non-byval parameter " << argNo
1828 <<
" consumed other than as a call argument is not yet implemented "
1829 "in CallConvLowering";
1834 if (callArgs.empty())
1835 return mlir::success();
1842 mlir::OpBuilder builder(funcOp.getContext());
1843 builder.setInsertionPointToStart(blockArg.getOwner());
1844 auto synthesized = cir::AllocaOp::create(
1845 builder, funcOp.getLoc(), paramPtrTy,
1846 builder.getStringAttr(
"nonbyval.param"),
1847 builder.getI64IntegerAttr(ac.indirectAlign.value()));
1849 cir::StoreOp::create(builder, funcOp.getLoc(), blockArg, synthesized);
1858 cir::AllocaOp slot = getSpillSlot(spill.getAddr());
1859 if (!slot || slot.getType() != paramPtrTy)
1860 return spill->emitOpError()
1861 <<
"non-byval parameter " << argNo
1862 <<
" spilled to storage that cannot take the incoming pointer is "
1863 "not yet implemented in CallConvLowering";
1869 if (!claimedSlots.insert(slot).second)
1870 return spill->emitOpError()
1871 <<
"non-byval parameter " << argNo
1872 <<
" sharing its spill slot with another parameter is not yet "
1873 "implemented in CallConvLowering";
1878 slot.setAlignment(ac.indirectAlign.value());
1880 if (callArgs.empty())
1881 return mlir::success();
1885 for (mlir::OpOperand *callArg : callArgs)
1886 if (!dom.properlyDominates(spill, callArg->getOwner()))
1887 return callArg->getOwner()->emitOpError()
1888 <<
"non-byval parameter " << argNo
1889 <<
" read before its spill is not yet implemented in "
1902 mlir::OpBuilder builder(spill);
1903 builder.setInsertionPointAfter(spill);
1904 auto reload = cir::LoadOp::create(builder, spill.getLoc(), slot);
1905 reload.setAlignment(ac.indirectAlign.value());
1906 for (mlir::OpOperand *callArg : callArgs)
1907 callArg->set(reload.getResult());
1908 return mlir::success();
1912 cir::FuncOp funcOp,
const FunctionClassification &fc) {
1913 if (!funcOp.isDefinition())
1914 return mlir::success();
1915 mlir::Region &body = funcOp->getRegion(0);
1917 return mlir::success();
1918 mlir::Block &entry = body.front();
1919 mlir::DominanceInfo dom;
1920 SmallPtrSet<mlir::Operation *, 4> claimedSlots;
1926 for (
auto [idx, ac] : llvm::enumerate(fc.argInfos)) {
1927 if (ac.kind != ArgKind::Indirect || ac.byVal)
1929 assert(idx < entry.getNumArguments() &&
1930 "classification count must not exceed entry block arguments");
1932 funcOp, idx, ac, entry.getArgument(idx), dom, claimedSlots)))
1933 return mlir::failure();
1935 return mlir::success();
1939 for (
auto [slot, incoming] : pendingParamSlots) {
1940 slot.getResult().replaceAllUsesWith(incoming);
1943 pendingParamSlots.clear();
1947 mlir::FunctionOpInterface funcOpInterface,
const FunctionClassification &fc,
1948 mlir::OpBuilder &builder) {
1954 cir::FuncOp funcOp = mlir::cast<cir::FuncOp>(funcOpInterface);
1956 if (!fc.needsRewrite())
1957 return mlir::success();
1961 mlir::MLIRContext *ctx = funcOp->getContext();
1966 assert(oldResultTypes.size() <= 1 &&
1967 "CIR functions return zero or one value");
1970 if (mlir::failed(buildNewArgTypes(oldArgTypes, fc, newArgTypes, dl,
1971 [&]() {
return funcOp.emitOpError(); })))
1972 return mlir::failure();
1974 mlir::Type voidTy = cir::VoidType::get(ctx);
1975 mlir::Type origRetTy = oldResultTypes.empty() ? voidTy : oldResultTypes[0];
1976 mlir::Type newRetTy = computeNewReturnType(
1977 origRetTy, fc.returnInfo, ctx, [&]() { return funcOp.emitOpError(); });
1979 return mlir::failure();
1989 fc.returnInfo.kind == ArgKind::Indirect && !oldResultTypes.empty();
1990 cir::PointerType sretPtrTy;
1992 sretPtrTy = getIndirectPtrTy(origRetTy, fc.returnInfo);
1993 newArgTypes.insert(newArgTypes.begin(), sretPtrTy);
1996 if (funcOp.isDefinition()) {
1997 mlir::Region &body = funcOp->getRegion(0);
1998 if (!body.empty()) {
2003 body.front().insertArgument(0u, sretPtrTy, funcOp.getLoc());
2004 insertSRetStores(funcOp, origRetTy, builder);
2013 if (failed(insertArgCoercion(funcOp, fc, builder, dl, hasSRet,
2014 pendingParamSlots)))
2015 return mlir::failure();
2020 if (fc.returnInfo.kind == ArgKind::Direct && fc.returnInfo.coercedType &&
2021 !oldResultTypes.empty() && fc.returnInfo.coercedType != origRetTy &&
2022 failed(insertReturnCoercion(
2023 funcOp, origRetTy, fc.returnInfo.coercedType, builder, dl,
2024 cirDataLayout, fc.returnInfo.directOffset)))
2025 return mlir::failure();
2027 mlir::Block &entry = body.front();
2036 unsigned blockArgIdx = hasSRet ? 1 : 0;
2037 for (
auto [i, ac] : llvm::enumerate(fc.argInfos)) {
2038 if (blockArgIdx >= entry.getNumArguments())
2040 if (ac.kind == ArgKind::Ignore) {
2041 mlir::BlockArgument arg = entry.getArgument(blockArgIdx);
2042 if (!arg.use_empty()) {
2043 builder.setInsertionPointToStart(&entry);
2044 mlir::Value poison =
2045 createIgnoredValue(builder, funcOp.getLoc(), arg.getType());
2046 arg.replaceAllUsesWith(poison);
2048 entry.eraseArgument(blockArgIdx);
2052 blockArgIdx += flatTy.getNumElements();
2053 else if (ac.kind == ArgKind::Expand)
2054 blockArgIdx += cast<cir::RecordType>(oldArgTypes[i]).getNumElements();
2066 if (fc.returnInfo.kind == ArgKind::Ignore && !oldResultTypes.empty()) {
2067 assert(mlir::isa<cir::VoidType>(newRetTy) &&
2068 "Ignore-return path requires the new return type to be void");
2070 funcOp.walk([&](cir::ReturnOp r) { returns.push_back(r); });
2071 for (cir::ReturnOp r : returns) {
2072 if (r.getNumOperands() == 0)
2074 builder.setInsertionPoint(r);
2075 cir::ReturnOp::create(builder, r.getLoc());
2081 mlir::Type newFnTy = funcOp.cloneTypeWith(newArgTypes, newResultTypes);
2082 funcOp.setFunctionTypeAttr(mlir::TypeAttr::get(newFnTy));
2086 if (hasSRet || needsArgAttrUpdate(fc)) {
2087 auto existing = funcOp->getAttrOfType<mlir::ArrayAttr>(
"arg_attrs");
2088 mlir::ArrayAttr updated = updateArgAttrs(ctx, module, oldArgTypes, existing,
2089 fc, dl, enableNoundefAttrs);
2095 builder, origRetTy, fc.returnInfo.indirectAlign.value(),
2096 funcOp.isDefinition());
2098 withSret.push_back(mlir::DictionaryAttr::get(ctx, sretAttrs));
2099 llvm::append_range(withSret, updated);
2100 funcOp->setAttr(
"arg_attrs", mlir::ArrayAttr::get(ctx, withSret));
2102 funcOp->setAttr(
"arg_attrs", updated);
2106 if (mlir::isa<cir::VoidType>(newRetTy)) {
2107 funcOp->removeAttr(
"res_attrs");
2108 }
else if (fc.returnInfo.kind == ArgKind::Extend ||
2109 fc.returnInfo.kind == ArgKind::Direct) {
2110 auto existing = funcOp->getAttrOfType<mlir::ArrayAttr>(
"res_attrs");
2111 if (mlir::ArrayAttr updated =
2112 updateResAttrs(ctx, existing, fc.returnInfo, origRetTy, dl))
2113 funcOp->setAttr(
"res_attrs", updated);
2116 return mlir::success();
2121 const FunctionClassification &fc,
2122 mlir::OpBuilder &builder) {
2134 unsigned numOperands =
2135 mlir::cast<cir::CIRCallOpInterface>(callOp).getNumArgOperands();
2136 if (numOperands > fc.argInfos.size())
2137 return callOp->emitOpError()
2138 <<
"variadic arguments not yet implemented in CallConvLowering";
2139 if (numOperands < fc.argInfos.size())
2140 return callOp->emitOpError()
2141 <<
"call passes fewer arguments than the callee declares, which is "
2142 "not yet implemented in CallConvLowering";
2144 if (!fc.needsRewrite())
2145 return mlir::success();
2147 if (mlir::isa<cir::TryCallOp>(callOp))
2148 return callOp->emitOpError()
2149 <<
"TryCallOp not yet implemented in CallConvLowering";
2151 auto call = mlir::cast<cir::CallOp>(callOp);
2152 mlir::MLIRContext *ctx = callOp->getContext();
2153 mlir::Block *slotBlock = coercionSlotBlock(call);
2155 builder.setInsertionPoint(call);
2158 mlir::ValueRange argOperands = call.getArgOperands();
2159 newArgs.reserve(argOperands.size());
2171 llvm::append_range(origCallArgTypes, argOperands.getTypes());
2177 unsigned numDeclared = fc.argInfos.size();
2178 if (call.isIndirect()) {
2180 assert(numDeclared <= fc.argInfos.size() &&
2181 "the classification covers at least the declared parameters");
2185 std::optional<unsigned> ellipsisStart;
2186 for (
auto [idx, ac] : llvm::enumerate(fc.argInfos)) {
2187 if (idx == numDeclared)
2188 ellipsisStart = newArgs.size();
2189 if (ac.kind == ArgKind::Ignore)
2191 mlir::Value arg = argOperands[idx];
2199 if (arg.getType() != flatTy) {
2200 SmallPtrSet<mlir::Operation *, 4> coercionOps;
2201 assert(!ac.directOffset &&
2202 "the coerced struct starts at slot offset 0 here, so a "
2203 "flattened coercion cannot honor a direct offset");
2204 if (failed(rejectAtomicRecordLoad(call, arg)))
2205 return mlir::failure();
2206 mlir::OpBuilder::InsertionGuard guard(builder);
2207 mlir::Value coercedPtr;
2208 uint64_t baseAlign = 0;
2209 if (cir::LoadOp recLoad = maybeGetCopyableRecordLoad(arg)) {
2210 mlir::Value base = recLoad.getAddr();
2211 if (!recLoad.getIsVolatile() &&
2212 canReadInPlace(recLoad, flatTy, cirDataLayout, 0)) {
2214 assert(baseAlloca &&
"canReadInPlace requires an alloca");
2215 baseAlign = baseAlloca.getAlignment();
2217 base = emitCopiedCoercionSlot(builder, call.getLoc(), recLoad,
2218 flatTy, slotBlock, dl, 0);
2220 builder.setInsertionPoint(recLoad);
2221 coercedPtr = emitViewAtOffset(builder, call.getLoc(), flatTy, base,
2223 deadRecordLoads.push_back(recLoad);
2226 emitCoercionToMemory(builder, call.getLoc(), flatTy, arg,
2227 slotBlock, dl, coercionOps, 0);
2229 auto coercedPtrTy = mlir::cast<cir::PointerType>(coercedPtr.getType());
2230 for (
auto [f, fieldTy] : llvm::enumerate(flatTy.getMembers())) {
2231 mlir::Type fieldPtrTy =
2232 cir::PointerType::get(fieldTy, coercedPtrTy.getAddrSpace());
2234 cir::GetMemberOp::create(builder, call.getLoc(), fieldPtrTy,
2236 auto field = cir::LoadOp::create(builder, call.getLoc(), fieldTy,
2237 fieldPtr.getResult());
2242 llvm::MinAlign(baseAlign, flatTy.getElementOffset(dl, f)));
2243 newArgs.push_back(field);
2246 emitStructFieldArgs(builder, call.getLoc(), arg, flatTy, newArgs,
2249 }
else if (ac.kind == ArgKind::Expand) {
2252 auto recTy = cast<cir::RecordType>(arg.getType());
2254 "Expand classification requires a struct type, not a union");
2255 emitStructFieldArgs(builder, call.getLoc(), arg, recTy, newArgs,
2257 }
else if ((ac.kind == ArgKind::Direct && ac.coercedType &&
2258 arg.getType() != ac.coercedType) ||
2259 isRecordExtend(ac, arg.getType())) {
2260 if (failed(rejectAtomicRecordLoad(call, arg)))
2261 return mlir::failure();
2262 if (cir::LoadOp recLoad = maybeGetCopyableRecordLoad(arg)) {
2263 newArgs.push_back(emitCoercedRecordLoad(
2264 builder, call.getLoc(), recLoad, ac.coercedType, slotBlock, dl,
2265 cirDataLayout, ac.directOffset));
2266 deadRecordLoads.push_back(recLoad);
2268 newArgs.push_back(emitCoercion(builder, call.getLoc(), ac.coercedType,
2269 arg, slotBlock, dl, ac.directOffset));
2271 }
else if (ac.kind == ArgKind::Indirect ||
2272 ac.kind == ArgKind::IndirectAliased) {
2273 uint64_t minAlign = ac.indirectAlign.value();
2276 bool byRef = ac.kind == ArgKind::IndirectAliased;
2277 bool byCopy = byRef || ac.byVal;
2278 cir::PointerType ptrTy = getIndirectPtrTy(arg.getType(), ac);
2286 cir::LoadOp srcLoad;
2287 if (!byCopy || mlir::isa<cir::RecordType>(arg.getType()))
2288 srcLoad = maybeGetSimpleLoad(arg);
2296 mlir::Value fwdAddr = forwardableIndirectAddr(srcLoad, ptrTy, minAlign);
2298 return call->emitOpError()
2299 <<
"non-byval indirect argument that does not name the "
2300 "caller's storage is not yet implemented in "
2302 newArgs.push_back(fwdAddr);
2303 deadRecordLoads.push_back(srcLoad);
2313 if (mlir::Value fwdAddr =
2314 forwardableIndirectAddr(srcLoad, ptrTy, minAlign);
2315 fwdAddr && storageUnwrittenBetween(srcLoad, call.getOperation(),
2317 newArgs.push_back(fwdAddr);
2318 deadRecordLoads.push_back(srcLoad);
2324 if (byRef && ptrTy != getAllocaPtrTy(arg.getType(), dl))
2325 return call->emitOpError()
2326 <<
"byref argument outside the alloca address space that does "
2327 "not name forwardable storage is not yet implemented in "
2332 if (failed(rejectAtomicRecordLoad(call, arg)))
2333 return mlir::failure();
2335 srcLoad = maybeGetCopyableRecordLoad(arg);
2336 mlir::IntegerAttr slotAlign = builder.getI64IntegerAttr(minAlign);
2337 mlir::OpBuilder::InsertionGuard guard(builder);
2339 builder.setInsertionPoint(srcLoad);
2341 auto slot = cir::AllocaOp::create(
2342 builder, call.getLoc(), ptrTy,
2343 builder.getStringAttr(byRef ?
"byref" :
"byval"), slotAlign);
2345 auto copy = cir::CopyOp::create(builder, call.getLoc(), slot,
2346 srcLoad.getAddr(), slotAlign,
2347 loadSourceAlignment(srcLoad, builder));
2348 copy.setIsVolatile(srcLoad.getIsVolatile());
2349 deadRecordLoads.push_back(srcLoad);
2354 cir::StoreOp::create(builder, call.getLoc(), arg, slot);
2356 newArgs.push_back(slot);
2358 newArgs.push_back(arg);
2361 unsigned numEllipsisArgs =
2362 ellipsisStart ? newArgs.size() - *ellipsisStart : 0;
2364 bool hasResult = call.getNumResults() > 0;
2365 mlir::Type origRetTy =
2366 hasResult ? call.getResult().getType() : cir::VoidType::get(ctx);
2372 if (fc.returnInfo.kind == ArgKind::Indirect && hasResult) {
2373 if (failed(rewriteIndirectReturnCall(call, fc, newArgs, numEllipsisArgs,
2374 origRetTy, origCallArgTypes, builder,
2375 dl, enableNoundefAttrs)))
2376 return mlir::failure();
2377 eraseDeadRecordLoads(deadRecordLoads);
2378 return mlir::success();
2381 mlir::Type callRetTy = origRetTy;
2382 if (fc.returnInfo.kind == ArgKind::Ignore && hasResult)
2383 callRetTy = cir::VoidType::get(ctx);
2384 bool returnNeedsCoercion =
2385 hasResult && fc.returnInfo.kind == ArgKind::Direct &&
2386 fc.returnInfo.coercedType && fc.returnInfo.coercedType != origRetTy;
2387 if (returnNeedsCoercion)
2388 callRetTy = fc.returnInfo.coercedType;
2390 builder.setInsertionPoint(call);
2391 prependIndirectCallee(call, newArgs, callRetTy, numEllipsisArgs, builder);
2392 auto newCall = cir::CallOp::create(builder, call.getLoc(),
2393 call.getCalleeAttr(), callRetTy, newArgs);
2394 copyCallAttributes(call, newCall);
2399 if (returnNeedsCoercion) {
2400 builder.setInsertionPointAfter(newCall);
2401 SmallPtrSet<mlir::Operation *, 4> coercionOps;
2402 if (failed(emitCoercionAndReplaceUses(builder, call.getLoc(), origRetTy,
2403 newCall.getResult(), call.getResult(),
2404 slotBlock, dl, coercionOps,
2405 fc.returnInfo.directOffset)))
2406 return mlir::failure();
2409 if (needsArgAttrUpdate(fc)) {
2410 auto existing = call->getAttrOfType<mlir::ArrayAttr>(
"arg_attrs");
2411 newCall->setAttr(
"arg_attrs",
2412 updateArgAttrs(ctx, module, origCallArgTypes, existing, fc,
2413 dl, enableNoundefAttrs));
2417 if (fc.returnInfo.kind == ArgKind::Extend ||
2418 (hasResult && fc.returnInfo.kind == ArgKind::Direct)) {
2419 auto existing = call->getAttrOfType<mlir::ArrayAttr>(
"res_attrs");
2420 if (mlir::ArrayAttr updated =
2421 updateResAttrs(ctx, existing, fc.returnInfo, origRetTy, dl))
2422 newCall->setAttr(
"res_attrs", updated);
2423 }
else if (hasResult && mlir::isa<cir::VoidType>(callRetTy)) {
2424 newCall->removeAttr(
"res_attrs");
2427 if (hasResult && fc.returnInfo.kind == ArgKind::Ignore) {
2432 if (!call.getResult().use_empty()) {
2433 builder.setInsertionPointAfter(newCall);
2434 mlir::Value poison =
2435 createIgnoredValue(builder, call.getLoc(), origRetTy);
2436 call.getResult().replaceAllUsesWith(poison);
2438 }
else if (hasResult && !returnNeedsCoercion) {
2440 call.getResult().replaceAllUsesWith(newCall.getResult());
2444 eraseDeadRecordLoads(deadRecordLoads);
2446 return mlir::success();
2451 mlir::OpBuilder &builder) {
2452 auto oldPtrTy = mlir::cast<cir::PointerType>(addrOp.getAddr().getType());
2453 cir::FuncType newFuncTy = funcOp.getFunctionType();
2456 if (newFuncTy == oldPtrTy.getPointee())
2460 addrOp.getAddr().setType(cir::PointerType::get(newFuncTy));
2461 if (addrOp.getAddr().use_empty())
2466 mlir::OpBuilder::InsertionGuard guard(builder);
2467 builder.setInsertionPointAfter(addrOp);
2468 auto bitcast = cir::CastOp::create(builder, addrOp.getLoc(), oldPtrTy,
2469 cir::CastKind::bitcast, addrOp.getAddr());
2470 addrOp.getAddr().replaceAllUsesExcept(bitcast.getResult(), bitcast);
2479 VAArgFetch(mlir::Location loc, mlir::Value valist,
2481 const ArgClassification &ac,
const mlir::DataLayout &dl,
2482 mlir::ModuleOp module)
2483 : loc(loc), valist(valist), vaFields(vaFields), resultTy(resultTy),
2484 ac(ac), dl(dl), module(module) {
2485 assert(vaFields.size() == 4 &&
2486 "the x86-64 va_list is a four-field cursor, checked by the caller");
2492 mlir::Type resultTy;
2493 const ArgClassification ∾
2494 const mlir::DataLayout &dl;
2495 mlir::ModuleOp module;
2501struct RegisterCursor {
2502 mlir::Value gpOffsetP;
2503 mlir::Value fpOffsetP;
2504 mlir::Value gpOffset;
2505 mlir::Value fpOffset;
2509mlir::LogicalResult reportVAArgNYI(cir::VAArgOp op, llvm::StringRef what) {
2510 op->emitOpError() <<
"va_arg of " << what
2511 <<
" not yet implemented in CallConvLowering";
2512 return mlir::failure();
2519mlir::LogicalResult classifyRegisterPair(cir::VAArgOp op,
2520 const ArgClassification &ac,
2521 std::array<bool, 2> &pairIsSse,
2523 auto pairTy = mlir::dyn_cast<cir::RecordType>(ac.coercedType);
2525 return mlir::success();
2527 if (pairTy.getNumElements() != 2)
2528 return reportVAArgNYI(op,
"a register coercion that is not two eightbytes");
2530 assert(!ac.directOffset &&
2531 "a pair already spans both eightbytes, so it cannot also start "
2532 "partway into the value");
2533 for (
auto [i, memberTy] : llvm::enumerate(pairTy.getMembers()))
2534 pairIsSse[i] = isSSERegisterClass(memberTy);
2536 return mlir::success();
2544uint64_t argumentAreaAlign(mlir::Type ty, mlir::ModuleOp modOp,
2545 const mlir::DataLayout &dl) {
2547 if (
auto recTy = mlir::dyn_cast<cir::RecordType>(ty))
2549 align = std::max<uint64_t>(align, layout.getRecordAlign());
2553mlir::Value roundPointerUpToAlignment(
CIRBaseBuilderTy &b, mlir::Location loc,
2554 mlir::Value bytePtr,
uint64_t align,
2555 const mlir::DataLayout &dl) {
2556 assert(mlir::cast<cir::PointerType>(bytePtr.getType()).getPointee() ==
2558 "the bump strides in bytes, so the pointee must be u8");
2559 assert(llvm::isPowerOf2_64(align) &&
2560 "mask rounding needs a power-of-two alignment");
2561 mlir::Value bumped =
2563 std::optional<uint64_t> indexWidth =
2564 dl.getTypeIndexBitwidth(bytePtr.getType());
2565 assert(indexWidth &&
"a pointer in the argument area has an index width");
2567 static_cast<unsigned>(*indexWidth));
2568 return cir::PtrMaskOp::create(b, loc, bytePtr.getType(), bumped, mask);
2574 const VAArgFetch &f) {
2577 f.loc, b.
getPointerTo(f.vaFields[2]), f.valist,
"overflow_arg_area", 2);
2578 mlir::Value overflow = b.
createLoad(f.loc, overflowP);
2581 uint64_t tyAlign = argumentAreaAlign(f.resultTy, f.module, f.dl);
2583 bytePtr = roundPointerUpToAlignment(b, f.loc, bytePtr, tyAlign, f.dl);
2586 llvm::alignTo(f.dl.getTypeAllocSize(f.resultTy).getFixedValue(), 8);
2587 mlir::Value strideVal = b.
getSignedInt(f.loc, stride, 32);
2598 unsigned neededInt,
unsigned neededSse) {
2599 RegisterCursor cursor;
2602 f.valist,
"gp_offset", 0);
2603 cursor.gpOffset = b.
createLoad(f.loc, cursor.gpOffsetP);
2605 b.
getConstantInt(f.loc, cursor.gpOffset.getType(), 48 - neededInt * 8);
2607 b.
createCompare(f.loc, cir::CmpOpKind::le, cursor.gpOffset, limit);
2611 f.valist,
"fp_offset", 1);
2612 cursor.fpOffset = b.
createLoad(f.loc, cursor.fpOffsetP);
2613 mlir::Value limit = b.
getConstantInt(f.loc, cursor.fpOffset.getType(),
2614 176 - neededSse * 16);
2615 mlir::Value fitsInFp =
2616 b.
createCompare(f.loc, cir::CmpOpKind::le, cursor.fpOffset, limit);
2617 cursor.inRegs = cursor.inRegs
2627 const ArgClassification &ac,
2628 const RegisterCursor &cursor,
2629 const std::array<bool, 2> &pairIsSse,
2630 mlir::Value regSaveArea, mlir::Value regPairTemp) {
2631 auto pairTy = mlir::cast<cir::RecordType>(ac.coercedType);
2635 bool bothSse = pairIsSse[0] && pairIsSse[1];
2638 unsigned seenOfClass[2] = {0, 0};
2639 for (
unsigned i = 0; i < 2; ++i) {
2640 bool isSse = pairIsSse[i];
2641 mlir::Value base = isSse ? cursor.fpOffset : cursor.gpOffset;
2642 unsigned regSize = isSse ? 16 : 8;
2643 unsigned prior = seenOfClass[isSse];
2644 ++seenOfClass[isSse];
2645 mlir::Value off = base;
2651 mlir::Type elemTy = pairTy.getElementType(i);
2662uint64_t registerSlotSize(
unsigned neededInt,
unsigned neededSse) {
2663 assert(!(neededInt && neededSse) &&
2664 "a fetch needing both classes is a pair, reassembled elsewhere");
2665 return neededSse ? neededSse * 16 : neededInt * 8;
2670bool needsTempCopy(
const VAArgFetch &f,
unsigned neededInt,
2671 unsigned neededSse) {
2672 uint64_t tySize = f.dl.getTypeSize(f.resultTy).getFixedValue();
2673 if (f.ac.coercedType &&
2674 (f.ac.directOffset || registerSlotSize(neededInt, neededSse) < tySize))
2678 uint64_t slotAlign = neededSse ? 16 : 8;
2679 return argumentAreaAlign(f.resultTy, f.module, f.dl) > slotAlign;
2685 const VAArgFetch &f, mlir::Value regAddr,
2686 mlir::Value temp,
unsigned neededInt,
2687 unsigned neededSse) {
2689 uint64_t tySize = f.dl.getTypeSize(f.resultTy).getFixedValue();
2691 if (f.ac.coercedType &&
2692 (f.ac.directOffset || registerSlotSize(neededInt, neededSse) < tySize)) {
2699 mlir::Value dst = temp;
2700 if (f.ac.directOffset) {
2702 mlir::Value offset = b.
getSignedInt(loc, f.ac.directOffset, 32);
2710 if (mlir::isa<cir::RecordType>(f.resultTy))
2711 cir::CopyOp::create(
2712 b, loc, temp, regView,
2713 b.getI64IntegerAttr(argumentAreaAlign(f.resultTy, f.module, f.dl)),
2714 b.getI64IntegerAttr(8));
2721 const RegisterCursor &cursor,
unsigned neededInt,
2722 unsigned neededSse) {
2743 const ArgClassification &ac,
2744 mlir::OpBuilder &opBuilder) {
2745 auto op = mlir::cast<cir::VAArgOp>(vaArgOp);
2747 mlir::Location loc = op.getLoc();
2748 mlir::Type resultTy = op.getType();
2749 mlir::Value valist = op.getArgList();
2754 if (ac.kind == ArgKind::Ignore) {
2755 builder.setInsertionPoint(op);
2756 op.getResult().replaceAllUsesWith(
2757 createIgnoredValue(builder, loc, resultTy));
2759 return mlir::success();
2762 if (ac.kind == ArgKind::Indirect && !ac.byVal)
2763 return reportVAArgNYI(op,
"a non-trivially-copyable type");
2764 if (ac.kind == ArgKind::IndirectAliased)
2765 return reportVAArgNYI(op,
"a type passed byref");
2770 unsigned neededInt = ac.neededIntRegs;
2771 unsigned neededSse = ac.neededSseRegs;
2775 std::array<bool, 2> pairIsSse = {
false,
false};
2776 bool isRegPair =
false;
2777 if (ac.kind == ArgKind::Direct && neededInt + neededSse == 2 &&
2779 if (classifyRegisterPair(op, ac, pairIsSse, isRegPair).failed())
2780 return mlir::failure();
2783 auto vaListRecTy = mlir::dyn_cast<cir::RecordType>(
2784 mlir::cast<cir::PointerType>(valist.getType()).getPointee());
2785 if (!vaListRecTy || vaListRecTy.getNumElements() != 4) {
2786 return reportVAArgNYI(op,
2787 "a va_list that is not the four-field gp_offset / "
2788 "fp_offset / overflow_arg_area / reg_save_area "
2792 const VAArgFetch fetch{loc, valist, vaListRecTy.getMembers(), resultTy, ac,
2796 builder.setInsertionPoint(op);
2799 if (neededInt == 0 && neededSse == 0) {
2800 addr = buildOverflowAddrAndAdvance(builder, fetch);
2802 RegisterCursor cursor =
2803 buildRegisterGate(builder, fetch, neededInt, neededSse);
2811 bool pairNeedsReassembly = isRegPair && neededSse != 0;
2814 mlir::Value regPairTemp;
2815 if (pairNeedsReassembly) {
2820 loc, builder.
getPointerTo(ac.coercedType),
"vaarg.reg",
2822 std::max(dl.getTypeABIAlignment(ac.coercedType),
2823 argumentAreaAlign(resultTy, module, dl))));
2826 mlir::Value regTemp;
2827 bool copyThroughTemp =
2828 !pairNeedsReassembly && needsTempCopy(fetch, neededInt, neededSse);
2829 if (copyThroughTemp) {
2833 argumentAreaAlign(resultTy, module, dl)));
2836 addr = cir::TernaryOp::create(
2837 builder, loc, cursor.inRegs,
2839 [&](mlir::OpBuilder &ob, mlir::Location l) {
2840 CIRBaseBuilderTy b(ob);
2841 mlir::Value regSaveArea = b.createLoad(
2842 l, b.createGetMember(l, b.getPointerTo(fetch.vaFields[3]),
2843 valist,
"reg_save_area", 3));
2844 regSaveArea = b.createPtrBitcast(regSaveArea, byteTy);
2846 mlir::Value regAddr;
2847 if (pairNeedsReassembly) {
2848 reassembleRegisterPair(b, l, ac, cursor, pairIsSse,
2849 regSaveArea, regPairTemp);
2850 regAddr = b.createPtrBitcast(regPairTemp, byteTy);
2853 neededSse ? cursor.fpOffset : cursor.gpOffset;
2854 regAddr = b.createPtrStride(l, regSaveArea, off);
2855 if (copyThroughTemp) {
2856 regAddr = copyRegisterToTemp(b, l, fetch, regAddr, regTemp,
2857 neededInt, neededSse);
2861 advanceRegisterCursors(b, l, cursor, neededInt, neededSse);
2862 cir::YieldOp::create(b, l, regAddr);
2865 [&](mlir::OpBuilder &ob, mlir::Location l) {
2867 mlir::Value memAddr = buildOverflowAddrAndAdvance(b, fetch);
2868 cir::YieldOp::create(b, l, memAddr);
2874 mlir::Value resultAddr = builder.createPtrBitcast(addr, resultTy);
2875 uint64_t resultAlign = argumentAreaAlign(resultTy, module, dl);
2876 if (mlir::isa<cir::RecordType>(resultTy)) {
2877 SmallPtrSet<mlir::Operation *, 1> noExceptions;
2878 if (failed(rewireRecordUses(builder, loc, op.getResult(), resultAddr,
2879 resultAlign, dl, noExceptions)))
2880 return mlir::failure();
2882 op.getResult().replaceAllUsesWith(
2883 builder.createAlignedLoad(loc, resultAddr, resultAlign));
2886 return mlir::success();
static mlir::LogicalResult prepareOneNonByvalParameter(cir::FuncOp funcOp, unsigned argNo, const ArgClassification &ac, mlir::BlockArgument blockArg, mlir::DominanceInfo &dom, SmallPtrSetImpl< mlir::Operation * > &claimedSlots)
Bring funcOp's non-byval indirect parameter argNo into the shape the rest of the rewrite assumes.
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
void rewriteFunctionAddress(cir::GetGlobalOp addrOp, cir::FuncOp funcOp, mlir::OpBuilder &builder)
Retype addrOp, which holds the address of funcOp, to the signature funcOp was rewritten to,...
mlir::LogicalResult rewriteFunctionDefinition(mlir::FunctionOpInterface funcOp, const mlir::abi::FunctionClassification &fc, mlir::OpBuilder &builder) override
void finalizeParameterSlots()
Replace each non-byval indirect parameter's spill slot with the incoming pointer, so the body operate...
mlir::LogicalResult prepareNonByvalParameters(cir::FuncOp funcOp, const mlir::abi::FunctionClassification &fc)
Bring each non-byval indirect parameter of funcOp into the shape the rest of the rewrite assumes: the...
mlir::LogicalResult rewriteVAArg(mlir::Operation *vaArgOp, const mlir::abi::ArgClassification &ac, mlir::OpBuilder &builder) override
Expand a cir.va_arg into the x86-64 SysV register-save-area / overflow-area sequence.
mlir::LogicalResult rewriteCallSite(mlir::Operation *callOp, const mlir::abi::FunctionClassification &fc, mlir::OpBuilder &builder) override
mlir::Value createAdd(mlir::Location loc, mlir::Value lhs, mlir::Value rhs, OverflowFlags flags=OverflowFlags::None)
cir::PtrStrideOp createPtrStride(mlir::Location loc, mlir::Value base, mlir::Value stride)
cir::GetMemberOp createGetMember(mlir::Location loc, mlir::Type resultTy, mlir::Value base, llvm::StringRef name, unsigned index)
cir::PointerType getPointerTo(mlir::Type ty)
cir::IntType getUIntNTy(int n)
mlir::Value createPtrBitcast(mlir::Value src, mlir::Type newPointeeTy)
mlir::Value createAlloca(mlir::Location loc, cir::PointerType addrType, llvm::StringRef name, mlir::IntegerAttr alignment, mlir::Value dynAllocSize)
cir::LoadOp createLoad(mlir::Location loc, mlir::Value ptr, bool isVolatile=false, uint64_t alignment=0, bool isNontemporal=false)
mlir::Value getSignedInt(mlir::Location loc, int64_t val, unsigned numBits)
cir::CmpOp createCompare(mlir::Location loc, cir::CmpOpKind kind, mlir::Value lhs, mlir::Value rhs)
cir::ConstantOp getConstantInt(mlir::Location loc, mlir::Type ty, int64_t value)
mlir::Value createAlignedLoad(mlir::Location loc, mlir::Value ptr, uint64_t alignment)
mlir::Value createLogicalAnd(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
cir::StoreOp createStore(mlir::Location loc, mlir::Value val, mlir::Value dst, bool isVolatile=false, bool isNontemporal=false, mlir::IntegerAttr align={}, cir::SyncScopeKindAttr scope={}, cir::MemOrderAttr order={})
llvm::TypeSize getTypeAllocSize(mlir::Type ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
llvm::TypeSize getTypeStoreSize(mlir::Type ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
C++ view class that accepts both !cir.struct and !cir.union types.
llvm::ArrayRef< mlir::Type > getMembers() const
static llvm::SmallVector< RecordMemberKind > getAllDataKinds(llvm::ArrayRef< mlir::Type > members)
One Data kind per member.
mlir::StringAttr getName() const
size_t getNumElements() const
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
RecordLayoutAttr tryGetRecordLayout(mlir::ModuleOp mod, mlir::StringAttr name)
Same lookup as getRecordLayout, but returns a null attribute instead of asserting when the record has...
bool memberOwnsBytes(mlir::Type memberTy)
Whether a record member occupies bytes of its record.
cir::FuncType getIndirectCalleeType(cir::CIRCallOpInterface call)
The signature the indirect call call reaches its callee through.
AllocaOp getUnderlyingAlloca(mlir::Value addr)
The alloca that defines addr, looking through casts that preserve the underlying storage.
const internal::VariadicAllOfMatcher< Attr > attr
constexpr size_t align(size_t Size)
Aligns a size to the pointer alignment.
U cast(CodeGen::Address addr)
__builtin_riscv_nclipru_u32 int64_t
static bool noaliasOnByvalAttr()