31#include "mlir/IR/Builders.h"
32#include "mlir/IR/IRMapping.h"
33#include "mlir/IR/PatternMatch.h"
40#include "llvm/ADT/DenseMap.h"
41#include "llvm/ADT/SetVector.h"
42#include "llvm/ADT/SmallVector.h"
43#include "llvm/TargetParser/Triple.h"
49#define GEN_PASS_DEF_CIREHABILOWERING
50#include "clang/CIR/Dialect/Passes.h.inc"
61static cir::FuncOp getOrCreateRuntimeFuncDecl(mlir::ModuleOp mod,
64 cir::FuncType funcTy) {
65 if (
auto existing = mod.lookupSymbol<cir::FuncOp>(
name))
68 mlir::OpBuilder builder(mod.getContext());
69 builder.setInsertionPointToEnd(mod.getBody());
70 auto funcOp = cir::FuncOp::create(builder, loc,
name, funcTy);
71 funcOp.setLinkage(cir::GlobalLinkageKind::ExternalLinkage);
84 explicit EHABILowering(mlir::ModuleOp mod)
85 : mod(mod), ctx(mod.getContext()), builder(ctx) {}
86 virtual ~EHABILowering() =
default;
89 virtual mlir::LogicalResult
run() = 0;
93 mlir::MLIRContext *ctx;
94 mlir::OpBuilder builder;
108class ItaniumEHLowering :
public EHABILowering {
110 using EHABILowering::EHABILowering;
111 mlir::LogicalResult
run()
override;
116 using EhTokenMap = DenseMap<mlir::Value, std::pair<mlir::Value, mlir::Value>>;
118 cir::VoidType voidType;
119 cir::PointerType voidPtrType;
120 cir::PointerType u8PtrType;
121 cir::IntType u32Type;
122 cir::IntType s32Type;
126 cir::FuncOp personalityFunc;
127 cir::FuncOp beginCatchFunc;
128 cir::FuncOp endCatchFunc;
129 cir::FuncOp getExceptionPtrFunc;
130 cir::FuncOp clangCallTerminateFunc;
131 cir::FuncOp cxaThrowFunc;
132 cir::FuncOp cxaRethrowFunc;
133 cir::FuncOp cxaCallUnexpectedFunc;
135 DenseMap<mlir::StringAttr, cir::FuncOp> catchCopyThunks;
137 constexpr const static ::llvm::StringLiteral kGxxPersonality =
138 "__gxx_personality_v0";
140 void ensureRuntimeDecls(mlir::Location loc);
141 void ensureClangCallTerminate(mlir::Location loc);
142 void ensureCxaThrowDecl(mlir::Location loc);
143 void ensureCxaRethrowDecl(mlir::Location loc);
144 void ensureCxaCallUnexpectedDecl(mlir::Location loc);
145 mlir::Block *buildTerminateBlock(cir::FuncOp funcOp, mlir::Location loc);
146 mlir::FailureOr<cir::FuncOp>
147 resolveCatchCopyThunk(cir::ConstructCatchParamOp op);
148 mlir::LogicalResult lowerFunc(cir::FuncOp funcOp);
150 lowerEhInitiate(cir::EhInitiateOp initiateOp,
151 llvm::ArrayRef<cir::EhDispatchOp> reachedDispatches,
152 bool reachesCleanup, EhTokenMap &ehTokenMap);
153 void lowerDispatch(cir::EhDispatchOp dispatch, mlir::Value exnPtr,
155 mlir::LogicalResult lowerConstructCatchParam(cir::ConstructCatchParamOp op,
157 void lowerInitCatchParam(cir::InitCatchParamOp op);
158 mlir::LogicalResult lowerTryThrow(cir::TryThrowOp op);
162mlir::LogicalResult ItaniumEHLowering::run() {
165 voidType = cir::VoidType::get(ctx);
166 voidPtrType = cir::PointerType::get(voidType);
167 auto u8Type = cir::IntType::get(ctx, 8,
false);
168 u8PtrType = cir::PointerType::get(u8Type);
169 u32Type = cir::IntType::get(ctx, 32,
false);
170 s32Type = cir::IntType::get(ctx, 32,
true);
172 for (cir::FuncOp funcOp : mod.getOps<cir::FuncOp>()) {
173 if (mlir::failed(lowerFunc(funcOp)))
174 return mlir::failure();
176 return mlir::success();
181void ItaniumEHLowering::ensureRuntimeDecls(mlir::Location loc) {
184 if (!personalityFunc) {
185 auto personalityFuncTy = cir::FuncType::get({}, s32Type,
true);
186 personalityFunc = getOrCreateRuntimeFuncDecl(mod, loc, kGxxPersonality,
190 if (!beginCatchFunc) {
191 auto beginCatchFuncTy =
192 cir::FuncType::get({voidPtrType}, u8PtrType,
false);
193 beginCatchFunc = getOrCreateRuntimeFuncDecl(mod, loc,
"__cxa_begin_catch",
198 auto endCatchFuncTy = cir::FuncType::get({}, voidType,
false);
200 getOrCreateRuntimeFuncDecl(mod, loc,
"__cxa_end_catch", endCatchFuncTy);
203 if (!getExceptionPtrFunc) {
204 auto getExceptionPtrFuncTy =
205 cir::FuncType::get({voidPtrType}, u8PtrType,
false);
206 getExceptionPtrFunc = getOrCreateRuntimeFuncDecl(
207 mod, loc,
"__cxa_get_exception_ptr", getExceptionPtrFuncTy);
220void ItaniumEHLowering::ensureClangCallTerminate(mlir::Location loc) {
221 if (clangCallTerminateFunc)
224 ensureRuntimeDecls(loc);
226 if (
auto existing = mod.lookupSymbol<cir::FuncOp>(
"__clang_call_terminate")) {
227 clangCallTerminateFunc = existing;
231 auto funcTy = cir::FuncType::get({voidPtrType}, voidType,
false);
232 builder.setInsertionPointToEnd(mod.getBody());
234 cir::FuncOp::create(builder, loc,
"__clang_call_terminate", funcTy);
235 funcOp.setLinkage(cir::GlobalLinkageKind::LinkOnceODRLinkage);
236 funcOp.setGlobalVisibility(cir::VisibilityKind::Hidden);
238 mlir::Block *entryBlock = funcOp.addEntryBlock();
239 builder.setInsertionPointToStart(entryBlock);
240 mlir::Value exnArg = entryBlock->getArgument(0);
242 auto catchCall = cir::CallOp::create(
243 builder, loc, mlir::FlatSymbolRefAttr::get(beginCatchFunc), u8PtrType,
244 mlir::ValueRange{exnArg});
245 catchCall.setNothrowAttr(builder.getUnitAttr());
247 auto terminateFuncDecl = getOrCreateRuntimeFuncDecl(
248 mod, loc,
"_ZSt9terminatev",
249 cir::FuncType::get({}, voidType,
false));
250 terminateFuncDecl->setAttr(cir::CIRDialect::getNoReturnAttrName(),
251 builder.getUnitAttr());
252 auto terminateCall = cir::CallOp::create(
253 builder, loc, mlir::FlatSymbolRefAttr::get(terminateFuncDecl), voidType,
255 terminateCall.setNothrowAttr(builder.getUnitAttr());
256 terminateCall->setAttr(cir::CIRDialect::getNoReturnAttrName(),
257 builder.getUnitAttr());
259 cir::UnreachableOp::create(builder, loc);
261 funcOp->setAttr(cir::CIRDialect::getNoReturnAttrName(),
262 builder.getUnitAttr());
263 clangCallTerminateFunc = funcOp;
269void ItaniumEHLowering::ensureCxaThrowDecl(mlir::Location loc) {
272 auto throwFuncTy = cir::FuncType::get({voidPtrType, voidPtrType, voidPtrType},
275 getOrCreateRuntimeFuncDecl(mod, loc,
"__cxa_throw", throwFuncTy);
281void ItaniumEHLowering::ensureCxaRethrowDecl(mlir::Location loc) {
284 auto rethrowFuncTy = cir::FuncType::get({}, voidType,
false);
286 getOrCreateRuntimeFuncDecl(mod, loc,
"__cxa_rethrow", rethrowFuncTy);
290void ItaniumEHLowering::ensureCxaCallUnexpectedDecl(mlir::Location loc) {
291 if (cxaCallUnexpectedFunc)
293 auto unexpectedFuncTy =
294 cir::FuncType::get({voidPtrType}, voidType,
false);
295 cxaCallUnexpectedFunc = getOrCreateRuntimeFuncDecl(
296 mod, loc,
"__cxa_call_unexpected", unexpectedFuncTy);
300mlir::Block *ItaniumEHLowering::buildTerminateBlock(cir::FuncOp funcOp,
301 mlir::Location loc) {
302 assert(clangCallTerminateFunc &&
303 "ensureClangCallTerminate must run before buildTerminateBlock");
304 mlir::Region &body = funcOp.getRegion();
305 mlir::Block *terminateBlock = builder.createBlock(&body, body.end());
306 auto inflight = cir::EhInflightOp::create(
307 builder, loc,
false,
true,
310 auto terminateCall = cir::CallOp::create(
311 builder, loc, mlir::FlatSymbolRefAttr::get(clangCallTerminateFunc),
312 voidType, mlir::ValueRange{inflight.getExceptionPtr()});
313 terminateCall.setNothrowAttr(builder.getUnitAttr());
314 terminateCall->setAttr(cir::CIRDialect::getNoReturnAttrName(),
315 builder.getUnitAttr());
316 cir::UnreachableOp::create(builder, loc);
317 return terminateBlock;
333static void collectReachableDispatches(
334 mlir::Value rootToken,
335 llvm::SmallSetVector<cir::EhDispatchOp, 4> &dispatches,
336 bool &reachesCleanup) {
337 llvm::SmallVector<mlir::Value> worklist;
338 llvm::SmallPtrSet<mlir::Value, 8> visited;
339 worklist.push_back(rootToken);
343 for (
unsigned i = 0; i < worklist.size(); ++i) {
344 mlir::Value current = worklist[i];
345 if (!visited.insert(current).second)
347 for (mlir::OpOperand &use : current.getUses()) {
348 mlir::Operation *user = use.getOwner();
353 if (mlir::isa<cir::BeginCleanupOp>(user))
354 reachesCleanup =
true;
355 if (
auto dispatch = mlir::dyn_cast<cir::EhDispatchOp>(user))
356 dispatches.insert(dispatch);
358 for (
unsigned s = 0, e = user->getNumSuccessors(); s < e; ++s)
359 for (mlir::BlockArgument arg : user->getSuccessor(s)->getArguments())
360 if (mlir::isa<cir::EhTokenType>(
arg.getType()))
361 worklist.push_back(arg);
367mlir::LogicalResult ItaniumEHLowering::lowerFunc(cir::FuncOp funcOp) {
368 if (funcOp.isDeclaration())
369 return mlir::success();
375 SmallVector<cir::EhInitiateOp> initiateOps;
376 funcOp.walk([&](cir::EhInitiateOp op) { initiateOps.push_back(op); });
377 if (initiateOps.empty())
378 return mlir::success();
380 ensureRuntimeDecls(funcOp.getLoc());
387 if (!funcOp.getPersonality())
388 funcOp.setPersonality(kGxxPersonality);
402 struct InitiateEHInfo {
403 llvm::SmallSetVector<cir::EhDispatchOp, 4> reachedDispatches;
404 bool reachesCleanup =
false;
406 llvm::DenseMap<mlir::Operation *, InitiateEHInfo> initiateInfo;
407 llvm::SmallSetVector<cir::EhDispatchOp, 4> dispatchesToLower;
408 for (cir::EhInitiateOp initiateOp : initiateOps) {
409 InitiateEHInfo &
info = initiateInfo[initiateOp.getOperation()];
410 collectReachableDispatches(initiateOp.getEhToken(),
info.reachedDispatches,
411 info.reachesCleanup);
412 dispatchesToLower.insert(
info.reachedDispatches.begin(),
413 info.reachedDispatches.end());
416 EhTokenMap ehTokenMap;
417 for (cir::EhInitiateOp initiateOp : initiateOps) {
418 const InitiateEHInfo &
info = initiateInfo[initiateOp.getOperation()];
419 if (mlir::failed(lowerEhInitiate(initiateOp,
420 info.reachedDispatches.getArrayRef(),
421 info.reachesCleanup, ehTokenMap)))
422 return mlir::failure();
429 for (cir::EhDispatchOp dispatch : dispatchesToLower) {
430 auto [exnPtr, typeId] = ehTokenMap.lookup(dispatch.getEhToken());
431 assert(exnPtr && typeId &&
432 "dispatch eh_token must be registered in ehTokenMap");
433 lowerDispatch(dispatch, exnPtr, typeId);
438 for (mlir::Block &block : funcOp.getBody()) {
439 for (
int i = block.getNumArguments() - 1; i >= 0; --i) {
440 if (mlir::isa<cir::EhTokenType>(block.getArgument(i).getType()))
441 block.eraseArgument(i);
448 SmallVector<cir::InitCatchParamOp> initCatchOps;
449 funcOp.walk([&](cir::InitCatchParamOp op) { initCatchOps.push_back(op); });
450 for (cir::InitCatchParamOp op : initCatchOps)
451 lowerInitCatchParam(op);
456 SmallVector<cir::TryThrowOp> tryThrowOps;
457 funcOp.walk([&](cir::TryThrowOp op) { tryThrowOps.push_back(op); });
458 for (cir::TryThrowOp op : tryThrowOps)
459 if (mlir::failed(lowerTryThrow(op)))
460 return mlir::failure();
462 return mlir::success();
491mlir::LogicalResult ItaniumEHLowering::lowerEhInitiate(
492 cir::EhInitiateOp initiateOp,
493 llvm::ArrayRef<cir::EhDispatchOp> reachedDispatches,
bool reachesCleanup,
494 EhTokenMap &ehTokenMap) {
495 mlir::Value rootToken = initiateOp.getEhToken();
505 mlir::ArrayAttr catchTypeList;
506 mlir::ArrayAttr filterTypeList;
507 bool catchAll =
false;
508 SmallVector<mlir::Attribute> typeSymbols;
509 for (cir::EhDispatchOp dispatch : reachedDispatches) {
510 if (mlir::ArrayAttr catchTypes = dispatch.getCatchTypesAttr()) {
511 for (mlir::Attribute attr : catchTypes) {
512 if (
auto filter = mlir::dyn_cast<cir::EhFilterAttr>(attr)) {
513 SmallVector<mlir::Attribute> filterSymbols;
516 for (mlir::Attribute typeAttr : filter.getPermittedTypes()) {
517 auto globalView = mlir::cast<cir::GlobalViewAttr>(typeAttr);
518 filterSymbols.push_back(globalView.getSymbol());
520 filterTypeList = builder.getArrayAttr(filterSymbols);
523 typeSymbols.push_back(
524 mlir::cast<cir::GlobalViewAttr>(attr).getSymbol());
527 if (dispatch.getDefaultIsCatchAll() || filterTypeList) {
528 catchAll = dispatch.getDefaultIsCatchAll();
531 assert(dispatch == reachedDispatches.back() &&
532 "catch-all or filter must be the last reachable dispatch");
536 if (!typeSymbols.empty())
537 catchTypeList = builder.getArrayAttr(typeSymbols);
539 builder.setInsertionPoint(initiateOp);
540 auto inflightOp = cir::EhInflightOp::create(
541 builder, initiateOp.getLoc(), initiateOp.getCleanup() || reachesCleanup,
542 catchAll, catchTypeList, filterTypeList);
544 ehTokenMap[rootToken] = {inflightOp.getExceptionPtr(),
545 inflightOp.getTypeId()};
551 SmallVector<mlir::Value> worklist;
552 SmallPtrSet<mlir::Value, 8> visited;
553 worklist.push_back(rootToken);
555 while (!worklist.empty()) {
556 mlir::Value current = worklist.pop_back_val();
557 if (!visited.insert(current).second)
562 SmallVector<mlir::Operation *> users;
563 for (mlir::OpOperand &use : current.getUses())
564 users.push_back(use.getOwner());
568 for (mlir::Operation *user : users) {
574 for (
unsigned s = 0; s < user->getNumSuccessors(); ++s) {
575 mlir::Block *succ = user->getSuccessor(s);
576 for (mlir::BlockArgument arg : succ->getArguments()) {
577 if (!mlir::isa<cir::EhTokenType>(
arg.getType()))
579 if (!ehTokenMap.count(arg)) {
580 mlir::Value ptrArg = succ->addArgument(voidPtrType,
arg.getLoc());
581 mlir::Value u32Arg = succ->addArgument(u32Type,
arg.getLoc());
582 ehTokenMap[
arg] = {ptrArg, u32Arg};
584 worklist.push_back(arg);
588 if (
auto op = mlir::dyn_cast<cir::BeginCleanupOp>(user)) {
591 for (
auto &tokenUsers :
592 llvm::make_early_inc_range(op.getCleanupToken().getUses())) {
594 mlir::dyn_cast<cir::EndCleanupOp>(tokenUsers.getOwner()))
598 }
else if (
auto op = mlir::dyn_cast<cir::BeginCatchOp>(user)) {
601 for (
auto &tokenUsers :
602 llvm::make_early_inc_range(op.getCatchToken().getUses())) {
604 mlir::dyn_cast<cir::EndCatchOp>(tokenUsers.getOwner())) {
605 builder.setInsertionPoint(endOp);
606 cir::CallOp::create(builder, endOp.getLoc(),
607 mlir::FlatSymbolRefAttr::get(endCatchFunc),
608 voidType, mlir::ValueRange{});
613 auto [exnPtr, typeId] = ehTokenMap.lookup(op.getEhToken());
614 builder.setInsertionPoint(op);
615 auto callOp = cir::CallOp::create(
616 builder, op.getLoc(), mlir::FlatSymbolRefAttr::get(beginCatchFunc),
617 u8PtrType, mlir::ValueRange{exnPtr});
618 mlir::Value castResult = callOp.getResult();
619 mlir::Type expectedPtrType = op.getExnPtr().getType();
620 if (castResult.getType() != expectedPtrType)
622 cir::CastOp::create(builder, op.getLoc(), expectedPtrType,
623 cir::CastKind::bitcast, callOp.getResult());
624 op.getExnPtr().replaceAllUsesWith(castResult);
626 }
else if (
auto op = mlir::dyn_cast<cir::ConstructCatchParamOp>(user)) {
627 auto [exnPtr, typeId] = ehTokenMap.lookup(op.getEhToken());
628 if (mlir::failed(lowerConstructCatchParam(op, exnPtr)))
629 return mlir::failure();
630 }
else if (mlir::isa<cir::EhDispatchOp>(user)) {
636 }
else if (
auto op = mlir::dyn_cast<cir::EhTerminateOp>(user)) {
637 auto [exnPtr, typeId] = ehTokenMap.lookup(op.getEhToken());
638 ensureClangCallTerminate(op.getLoc());
639 builder.setInsertionPoint(op);
640 auto call = cir::CallOp::create(
641 builder, op.getLoc(),
642 mlir::FlatSymbolRefAttr::get(clangCallTerminateFunc), voidType,
643 mlir::ValueRange{exnPtr});
644 call.setNothrowAttr(builder.getUnitAttr());
645 call->setAttr(cir::CIRDialect::getNoReturnAttrName(),
646 builder.getUnitAttr());
647 cir::UnreachableOp::create(builder, op.getLoc());
649 }
else if (
auto op = mlir::dyn_cast<cir::EhUnexpectedOp>(user)) {
650 auto [exnPtr, typeId] = ehTokenMap.lookup(op.getEhToken());
651 ensureCxaCallUnexpectedDecl(op.getLoc());
652 builder.setInsertionPoint(op);
653 auto call = cir::CallOp::create(
654 builder, op.getLoc(),
655 mlir::FlatSymbolRefAttr::get(cxaCallUnexpectedFunc), voidType,
656 mlir::ValueRange{exnPtr});
657 call->setAttr(cir::CIRDialect::getNoReturnAttrName(),
658 builder.getUnitAttr());
659 cir::UnreachableOp::create(builder, op.getLoc());
661 }
else if (
auto op = mlir::dyn_cast<cir::ResumeOp>(user)) {
662 auto [exnPtr, typeId] = ehTokenMap.lookup(op.getEhToken());
663 builder.setInsertionPoint(op);
664 cir::ResumeFlatOp::create(builder, op.getLoc(), exnPtr, typeId);
666 }
else if (
auto op = mlir::dyn_cast<cir::BrOp>(user)) {
668 SmallVector<mlir::Value> newOperands;
669 bool changed =
false;
670 for (mlir::Value operand : op.getDestOperands()) {
671 auto it = ehTokenMap.find(operand);
672 if (it != ehTokenMap.end()) {
673 newOperands.push_back(it->second.first);
674 newOperands.push_back(it->second.second);
677 newOperands.push_back(operand);
681 builder.setInsertionPoint(op);
682 cir::BrOp::create(builder, op.getLoc(), op.getDest(), newOperands);
690 return mlir::success();
696void ItaniumEHLowering::lowerDispatch(cir::EhDispatchOp dispatch,
697 mlir::Value exnPtr, mlir::Value typeId) {
698 mlir::Location dispLoc = dispatch.getLoc();
699 mlir::Block *defaultDest = dispatch.getDefaultDestination();
700 mlir::Block *dispatchBlock = dispatch->getBlock();
702 llvm::SmallVector<mlir::Attribute> catchAttrs;
703 llvm::SmallVector<mlir::Block *> catchDests;
704 cir::EhFilterAttr filterAttr;
705 mlir::Block *filterDest =
nullptr;
706 if (mlir::ArrayAttr catchTypes = dispatch.getCatchTypesAttr()) {
707 for (
auto [attr, dest] :
708 llvm::zip(catchTypes, dispatch.getCatchDestinations())) {
709 if (
auto filter = mlir::dyn_cast<cir::EhFilterAttr>(attr)) {
710 assert(!filterAttr &&
"at most one filter handler");
715 catchAttrs.push_back(attr);
716 catchDests.push_back(dest);
723 mlir::Block *
insertBefore = dispatchBlock->getNextNode();
724 mlir::Block *falseDest = defaultDest;
726 assert(filterDest &&
"filter handler requires a destination");
729 if (filterAttr.getPermittedTypes().empty()) {
730 falseDest = filterDest;
735 auto *cmpBlock = builder.createBlock(insertBefore, {voidPtrType, u32Type},
737 mlir::Value cmpExnPtr = cmpBlock->getArgument(0);
738 mlir::Value cmpTypeId = cmpBlock->getArgument(1);
739 mlir::Value signedTypeId = cir::CastOp::create(
740 builder, dispLoc, s32Type, cir::CastKind::integral, cmpTypeId);
741 mlir::Value zero = cir::ConstantOp::create(builder, dispLoc,
742 cir::IntAttr::get(s32Type, 0));
743 auto cmpOp = cir::CmpOp::create(builder, dispLoc, cir::CmpOpKind::lt,
745 cir::BrCondOp::create(builder, dispLoc, cmpOp, filterDest, defaultDest,
746 mlir::ValueRange{cmpExnPtr, cmpTypeId},
747 mlir::ValueRange{cmpExnPtr, cmpTypeId});
749 falseDest = cmpBlock;
753 mlir::Block *firstCmpBlock =
nullptr;
754 if (!catchAttrs.empty()) {
755 unsigned numCatches = catchAttrs.size();
756 for (
int i = numCatches - 1; i >= 0; --i) {
757 auto *cmpBlock = builder.createBlock(insertBefore, {voidPtrType, u32Type},
760 mlir::Value cmpExnPtr = cmpBlock->getArgument(0);
761 mlir::Value cmpTypeId = cmpBlock->getArgument(1);
763 auto globalView = mlir::cast<cir::GlobalViewAttr>(catchAttrs[i]);
765 cir::EhTypeIdOp::create(builder, dispLoc, globalView.getSymbol());
766 auto cmpOp = cir::CmpOp::create(builder, dispLoc, cir::CmpOpKind::eq,
767 cmpTypeId, ehTypeIdOp.getTypeId());
769 cir::BrCondOp::create(builder, dispLoc, cmpOp, catchDests[i], falseDest,
770 mlir::ValueRange{cmpExnPtr, cmpTypeId},
771 mlir::ValueRange{cmpExnPtr, cmpTypeId});
774 falseDest = cmpBlock;
775 firstCmpBlock = cmpBlock;
778 firstCmpBlock = falseDest;
781 builder.setInsertionPoint(dispatch);
782 cir::BrOp::create(builder, dispLoc, firstCmpBlock,
783 mlir::ValueRange{exnPtr, typeId});
790mlir::FailureOr<cir::FuncOp>
791ItaniumEHLowering::resolveCatchCopyThunk(cir::ConstructCatchParamOp op) {
792 mlir::FlatSymbolRefAttr thunkRef = op.getCopyFnAttr();
793 mlir::StringAttr thunkName = thunkRef.getAttr();
794 auto cached = catchCopyThunks.find(thunkName);
795 if (cached != catchCopyThunks.end())
796 return cached->second;
798 cir::FuncOp thunk = mod.lookupSymbol<cir::FuncOp>(thunkRef);
800 return op.emitError(
"could not resolve catch-copy thunk symbol");
801 assert(thunk->hasAttr(cir::CIRDialect::getCatchCopyThunkAttrName()) &&
802 "verifier should have rejected non-thunk catch-copy reference");
803 if (thunk.isDeclaration())
804 return op.emitError(
"catch-copy thunk has no body to inline");
806 mlir::Region &thunkRegion = thunk.getRegion();
807 if (!llvm::hasSingleElement(thunkRegion))
808 return op.emitError(
"multi-block catch-copy thunks are NYI");
810 mlir::Block &thunkEntry = thunkRegion.front();
811 assert(thunkEntry.getNumArguments() == 2 &&
812 "catch-copy thunk must have exactly two parameters");
813 if (!mlir::isa<cir::ReturnOp>(thunkEntry.getTerminator()))
814 return op.emitError(
"catch-copy thunk must end in cir.return");
816 catchCopyThunks[thunkName] = thunk;
824ItaniumEHLowering::lowerConstructCatchParam(cir::ConstructCatchParamOp op,
825 mlir::Value exnPtr) {
826 mlir::Location loc = op.getLoc();
827 mlir::Value paramAddr = op.getParamAddr();
828 cir::PointerType paramAddrType =
829 mlir::cast<cir::PointerType>(paramAddr.getType());
831 if (op.getKind() == cir::InitCatchKind::Reference) {
833 constexpr unsigned headerSize = 32;
835 builder.setInsertionPoint(op);
836 auto index = cir::ConstantOp::create(
837 builder, loc, cir::IntAttr::get(u32Type, headerSize));
838 assert((exnPtr.getType() == voidPtrType || exnPtr.getType() == u8PtrType) &&
839 "lowerConstructCatchParam exn ptr not void* or i8*");
841 cir::PtrStrideOp::create(builder, loc, exnPtr.getType(), exnPtr, index);
843 cir::CastOp::create(builder, loc, paramAddrType.getPointee(),
844 cir::CastKind::bitcast, exnObj);
845 cir::StoreOp::create(builder, loc, casted, paramAddr, {}, {}, {}, {}, {});
850 if (op.getKind() != cir::InitCatchKind::NonTrivialCopy)
852 "ConstructCatchParam: only non_trivial_copy is supported");
854 ensureRuntimeDecls(loc);
855 ensureClangCallTerminate(loc);
858 builder.setInsertionPoint(op);
859 cir::CallOp getExnCall = cir::CallOp::create(
860 builder, loc, mlir::FlatSymbolRefAttr::get(getExceptionPtrFunc),
861 u8PtrType, mlir::ValueRange{exnPtr});
862 getExnCall.setNothrowAttr(builder.getUnitAttr());
863 mlir::Value adjusted =
864 cir::CastOp::create(builder, loc, paramAddrType, cir::CastKind::bitcast,
865 getExnCall.getResult());
868 mlir::FailureOr<cir::FuncOp> thunkOr = resolveCatchCopyThunk(op);
869 if (mlir::failed(thunkOr))
870 return mlir::failure();
871 cir::FuncOp thunk = *thunkOr;
875 assert(llvm::hasSingleElement(thunk.getRegion()) &&
876 "multi-block catch-copy thunks are NYI");
879 mlir::Block &thunkEntry = thunk.getRegion().front();
880 mlir::IRMapping mapping;
881 mapping.map(thunkEntry.getArgument(0), paramAddr);
882 mapping.map(thunkEntry.getArgument(1), adjusted);
883 llvm::SmallVector<cir::CallOp> throwingCalls;
884 for (mlir::Operation &thunkOp : thunkEntry.without_terminator()) {
885 mlir::Operation *cloned = builder.clone(thunkOp, mapping);
886 if (cir::CallOp callOp = mlir::dyn_cast<cir::CallOp>(cloned))
887 if (!callOp.getNothrow())
888 throwingCalls.push_back(callOp);
892 if (throwingCalls.empty())
893 return mlir::success();
897 mlir::IRRewriter rewriter(builder);
898 mlir::Block *terminateBlock =
nullptr;
899 for (cir::CallOp call : throwingCalls) {
901 terminateBlock = buildTerminateBlock(call->getParentOfType<cir::FuncOp>(),
905 return mlir::success();
912mlir::LogicalResult ItaniumEHLowering::lowerTryThrow(cir::TryThrowOp op) {
913 mlir::Location loc = op.getLoc();
914 mlir::Block *normalDest = op.getNormalDest();
915 mlir::Block *unwindDest = op.getUnwindDest();
916 builder.setInsertionPoint(op);
919 ensureCxaRethrowDecl(loc);
920 cir::TryCallOp::create(
921 builder, loc, mlir::FlatSymbolRefAttr::get(cxaRethrowFunc), voidType,
922 normalDest, unwindDest, mlir::ValueRange{});
924 return mlir::success();
927 ensureCxaThrowDecl(loc);
930 mlir::Value exnPtr = op.getExceptionPtr();
931 if (exnPtr.getType() != voidPtrType)
932 exnPtr = cir::CastOp::create(builder, loc, voidPtrType,
933 cir::CastKind::bitcast, exnPtr);
938 mlir::FlatSymbolRefAttr typeInfoAttr = op.getTypeInfoAttr();
939 auto typeInfoGlobal = mod.lookupSymbol<cir::GlobalOp>(typeInfoAttr);
941 return op.emitError(
"type_info symbol not found in module");
942 auto typeInfoPtrTy = cir::PointerType::get(typeInfoGlobal.getSymType());
943 mlir::Value typeInfo = cir::GetGlobalOp::create(builder, loc, typeInfoPtrTy,
944 typeInfoAttr.getValue());
945 if (typeInfo.getType() != voidPtrType)
946 typeInfo = cir::CastOp::create(builder, loc, voidPtrType,
947 cir::CastKind::bitcast, typeInfo);
951 if (mlir::FlatSymbolRefAttr dtorAttr = op.getDtorAttr()) {
952 auto dtorFunc = mod.lookupSymbol<cir::FuncOp>(dtorAttr);
954 return op.emitError(
"dtor symbol not found in module");
955 auto dtorPtrTy = cir::PointerType::get(dtorFunc.getFunctionType());
957 cir::GetGlobalOp::create(builder, loc, dtorPtrTy, dtorAttr.getValue());
958 if (dtor.getType() != voidPtrType)
959 dtor = cir::CastOp::create(builder, loc, voidPtrType,
960 cir::CastKind::bitcast, dtor);
962 dtor = cir::ConstantOp::create(
964 cir::ConstPtrAttr::get(voidPtrType, builder.getI64IntegerAttr(0)));
967 cir::TryCallOp::create(
968 builder, loc, mlir::FlatSymbolRefAttr::get(cxaThrowFunc), voidType,
969 normalDest, unwindDest, mlir::ValueRange{exnPtr, typeInfo, dtor});
971 return mlir::success();
994void ItaniumEHLowering::lowerInitCatchParam(cir::InitCatchParamOp op) {
995 builder.setInsertionPoint(op);
996 mlir::Location loc = op.getLoc();
997 mlir::Value exnPtr = op.getExnPtr();
998 mlir::Value paramAddr = op.getParamAddr();
999 auto paramAddrType = mlir::cast<cir::PointerType>(paramAddr.getType());
1000 mlir::Type elementType = paramAddrType.getPointee();
1001 cir::InitCatchKind
kind = op.getKind();
1004 case InitCatchKind::Reference: {
1008 if (
const auto ref = mlir::dyn_cast<cir::PointerType>(elementType)) {
1011 if (
auto ptr = mlir::dyn_cast<cir::PointerType>(ref.getPointee()))
1012 if (!mlir::isa<cir::RecordType>(ptr.getPointee()))
1018 mlir::Value casted = cir::CastOp::create(builder, loc, elementType,
1019 cir::CastKind::bitcast, exnPtr);
1020 cir::StoreOp::create(builder, loc, casted, paramAddr, {}, {}, {}, {}, {});
1023 case InitCatchKind::TrivialCopy: {
1024 mlir::Value srcPtr = cir::CastOp::create(builder, loc, paramAddrType,
1025 cir::CastKind::bitcast, exnPtr);
1026 cir::CopyOp::create(builder, loc, paramAddr, srcPtr, {}, {});
1029 case InitCatchKind::NonTrivialCopy:
1033 case InitCatchKind::Scalar: {
1037 mlir::Value srcPtr = cir::CastOp::create(builder, loc, paramAddrType,
1038 cir::CastKind::bitcast, exnPtr);
1039 auto loadOp = cir::LoadOp::create(builder, loc, elementType, srcPtr);
1040 cir::StoreOp::create(builder, loc, loadOp.getResult(), paramAddr, {}, {},
1044 case InitCatchKind::Pointer: {
1045 mlir::Value casted = cir::CastOp::create(builder, loc, elementType,
1046 cir::CastKind::bitcast, exnPtr);
1047 cir::StoreOp::create(builder, loc, casted, paramAddr, {}, {}, {}, {}, {});
1050 case InitCatchKind::Objc:
1051 llvm_unreachable(
"InitCatchParam: ObjCLifetime is NYI");
1062struct CIREHABILoweringPass
1063 :
public impl::CIREHABILoweringBase<CIREHABILoweringPass> {
1064 CIREHABILoweringPass() =
default;
1065 void runOnOperation()
override;
1071static void eraseCatchCopyThunks(mlir::ModuleOp mod) {
1072 llvm::StringRef catchHelperAttr =
1073 cir::CIRDialect::getCatchCopyThunkAttrName();
1074 for (cir::FuncOp f : llvm::make_early_inc_range(mod.getOps<cir::FuncOp>())) {
1075 if (!f->hasAttr(catchHelperAttr))
1079 assert(mlir::SymbolTable::symbolKnownUseEmpty(f, mod) &&
1080 "catch-init helper has remaining users");
1085void CIREHABILoweringPass::runOnOperation() {
1086 auto mod = mlir::cast<mlir::ModuleOp>(getOperation());
1091 auto tripleAttr = mlir::dyn_cast_if_present<mlir::StringAttr>(
1092 mod->getAttr(cir::CIRDialect::getTripleAttrName()));
1094 mod.emitError(
"Module has no target triple");
1101 llvm::Triple triple(tripleAttr.getValue());
1102 std::unique_ptr<EHABILowering> lowering;
1103 if (triple.isWindowsMSVCEnvironment()) {
1105 "EH ABI lowering is not yet implemented for the Microsoft ABI");
1106 return signalPassFailure();
1108 lowering = std::make_unique<ItaniumEHLowering>(mod);
1111 if (mlir::failed(lowering->run()))
1112 return signalPassFailure();
1115 eraseCatchCopyThunks(mod);
1121 return std::make_unique<CIREHABILoweringPass>();
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
mlir::Block * replaceCallWithTryCall(cir::CallOp callOp, mlir::Block *unwindDest, mlir::Location loc, mlir::RewriterBase &rewriter)
Replace a cir::CallOp with a cir::TryCallOp whose unwind destination is unwindDest.
void info(bool Verbose, unsigned Level, const char *Fmt, Ts &&...Args)
Prints an indented note to stderr when Verbose is set.
std::unique_ptr< Pass > createCIREHABILoweringPass()
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
static bool sizeOfUnwindException()