34#include "mlir/IR/Builders.h"
35#include "mlir/IR/IRMapping.h"
36#include "mlir/IR/PatternMatch.h"
44#include "llvm/ADT/DenseMap.h"
45#include "llvm/ADT/SetVector.h"
46#include "llvm/ADT/SmallVector.h"
47#include "llvm/TargetParser/Triple.h"
53#define GEN_PASS_DEF_CIREHABILOWERING
54#include "clang/CIR/Dialect/Passes.h.inc"
65static cir::FuncOp getOrCreateRuntimeFuncDecl(mlir::ModuleOp mod,
68 cir::FuncType funcTy) {
69 if (
auto existing = mod.lookupSymbol<cir::FuncOp>(
name))
72 mlir::OpBuilder builder(mod.getContext());
73 builder.setInsertionPointToEnd(mod.getBody());
74 auto funcOp = cir::FuncOp::create(builder, loc,
name, funcTy);
75 funcOp.setLinkage(cir::GlobalLinkageKind::ExternalLinkage);
79 funcOp.setRequiresCallConvLowering(
false);
91 explicit EHABILowering(mlir::ModuleOp mod)
92 : mod(mod), ctx(mod.getContext()), builder(ctx) {}
93 virtual ~EHABILowering() =
default;
96 virtual mlir::LogicalResult
run() = 0;
100 mlir::MLIRContext *ctx;
101 mlir::OpBuilder builder;
115class ItaniumEHLowering :
public EHABILowering {
117 using EHABILowering::EHABILowering;
118 mlir::LogicalResult
run()
override;
123 using EhTokenMap = DenseMap<mlir::Value, std::pair<mlir::Value, mlir::Value>>;
125 cir::VoidType voidType;
126 cir::PointerType voidPtrType;
127 cir::PointerType u8PtrType;
128 cir::IntType u32Type;
129 cir::IntType s32Type;
133 cir::FuncOp personalityFunc;
134 cir::FuncOp beginCatchFunc;
135 cir::FuncOp endCatchFunc;
136 cir::FuncOp getExceptionPtrFunc;
137 cir::FuncOp clangCallTerminateFunc;
138 cir::FuncOp cxaThrowFunc;
139 cir::FuncOp cxaRethrowFunc;
140 cir::FuncOp cxaCallUnexpectedFunc;
142 DenseMap<mlir::StringAttr, cir::FuncOp> catchCopyThunks;
144 llvm::SmallSetVector<mlir::StringAttr, 1> droppedPersonalities;
146 constexpr const static ::llvm::StringLiteral kGxxPersonality =
147 "__gxx_personality_v0";
149 void ensureRuntimeDecls(mlir::Location loc);
150 void ensureClangCallTerminate(mlir::Location loc);
151 void ensureCxaThrowDecl(mlir::Location loc);
152 void ensureCxaRethrowDecl(mlir::Location loc);
153 void ensureCxaCallUnexpectedDecl(mlir::Location loc);
154 mlir::Block *buildTerminateBlock(cir::FuncOp funcOp, mlir::Location loc);
155 mlir::FailureOr<cir::FuncOp>
156 resolveCatchCopyThunk(cir::ConstructCatchParamOp op);
157 mlir::LogicalResult lowerFunc(cir::FuncOp funcOp);
159 lowerEhInitiate(cir::EhInitiateOp initiateOp,
160 llvm::ArrayRef<cir::EhDispatchOp> reachedDispatches,
161 bool reachesCleanup, EhTokenMap &ehTokenMap);
162 void lowerDispatch(cir::EhDispatchOp dispatch, mlir::Value exnPtr,
164 mlir::LogicalResult lowerConstructCatchParam(cir::ConstructCatchParamOp op,
166 void lowerInitCatchParam(cir::InitCatchParamOp op);
167 mlir::LogicalResult lowerTryThrow(cir::TryThrowOp op);
171mlir::LogicalResult ItaniumEHLowering::run() {
174 voidType = cir::VoidType::get(ctx);
175 voidPtrType = cir::PointerType::get(voidType);
176 auto u8Type = cir::IntType::get(ctx, 8,
false);
177 u8PtrType = cir::PointerType::get(u8Type);
178 u32Type = cir::IntType::get(ctx, 32,
false);
179 s32Type = cir::IntType::get(ctx, 32,
true);
181 for (cir::FuncOp funcOp : mod.getOps<cir::FuncOp>()) {
182 if (mlir::failed(lowerFunc(funcOp)))
183 return mlir::failure();
186 for (mlir::StringAttr name : droppedPersonalities) {
187 auto personalityDecl = mod.lookupSymbol<cir::FuncOp>(
name);
188 if (personalityDecl && personalityDecl.isDeclaration() &&
189 mlir::SymbolTable::symbolKnownUseEmpty(personalityDecl, mod))
190 personalityDecl.erase();
192 return mlir::success();
197void ItaniumEHLowering::ensureRuntimeDecls(mlir::Location loc) {
200 if (!personalityFunc) {
201 auto personalityFuncTy = cir::FuncType::get({}, s32Type,
true);
202 personalityFunc = getOrCreateRuntimeFuncDecl(mod, loc, kGxxPersonality,
206 if (!beginCatchFunc) {
207 auto beginCatchFuncTy =
208 cir::FuncType::get({voidPtrType}, u8PtrType,
false);
209 beginCatchFunc = getOrCreateRuntimeFuncDecl(mod, loc,
"__cxa_begin_catch",
214 auto endCatchFuncTy = cir::FuncType::get({}, voidType,
false);
216 getOrCreateRuntimeFuncDecl(mod, loc,
"__cxa_end_catch", endCatchFuncTy);
219 if (!getExceptionPtrFunc) {
220 auto getExceptionPtrFuncTy =
221 cir::FuncType::get({voidPtrType}, u8PtrType,
false);
222 getExceptionPtrFunc = getOrCreateRuntimeFuncDecl(
223 mod, loc,
"__cxa_get_exception_ptr", getExceptionPtrFuncTy);
236void ItaniumEHLowering::ensureClangCallTerminate(mlir::Location loc) {
239 if (clangCallTerminateFunc)
242 ensureRuntimeDecls(loc);
244 if (
auto existing = mod.lookupSymbol<cir::FuncOp>(
"__clang_call_terminate")) {
245 clangCallTerminateFunc = existing;
249 auto funcTy = cir::FuncType::get({voidPtrType}, voidType,
false);
250 builder.setInsertionPointToEnd(mod.getBody());
252 cir::FuncOp::create(builder, loc,
"__clang_call_terminate", funcTy);
253 funcOp.setLinkage(cir::GlobalLinkageKind::LinkOnceODRLinkage);
254 funcOp.setGlobalVisibility(cir::VisibilityKind::Hidden);
257 funcOp.setRequiresCallConvLowering(
false);
259 mlir::Block *entryBlock = funcOp.addEntryBlock();
260 builder.setInsertionPointToStart(entryBlock);
261 mlir::Value exnArg = entryBlock->getArgument(0);
263 auto catchCall = cir::CallOp::create(
264 builder, loc, mlir::FlatSymbolRefAttr::get(beginCatchFunc), u8PtrType,
265 mlir::ValueRange{exnArg});
266 catchCall.setNothrowAttr(builder.getUnitAttr());
268 auto terminateFuncDecl = getOrCreateRuntimeFuncDecl(
269 mod, loc,
"_ZSt9terminatev",
270 cir::FuncType::get({}, voidType,
false));
271 terminateFuncDecl->setAttr(cir::CIRDialect::getNoReturnAttrName(),
272 builder.getUnitAttr());
273 auto terminateCall = cir::CallOp::create(
274 builder, loc, mlir::FlatSymbolRefAttr::get(terminateFuncDecl), voidType,
276 terminateCall.setNothrowAttr(builder.getUnitAttr());
277 terminateCall->setAttr(cir::CIRDialect::getNoReturnAttrName(),
278 builder.getUnitAttr());
280 cir::UnreachableOp::create(builder, loc);
282 funcOp->setAttr(cir::CIRDialect::getNoReturnAttrName(),
283 builder.getUnitAttr());
284 clangCallTerminateFunc = funcOp;
290void ItaniumEHLowering::ensureCxaThrowDecl(mlir::Location loc) {
293 auto throwFuncTy = cir::FuncType::get({voidPtrType, voidPtrType, voidPtrType},
296 getOrCreateRuntimeFuncDecl(mod, loc,
"__cxa_throw", throwFuncTy);
302void ItaniumEHLowering::ensureCxaRethrowDecl(mlir::Location loc) {
305 auto rethrowFuncTy = cir::FuncType::get({}, voidType,
false);
307 getOrCreateRuntimeFuncDecl(mod, loc,
"__cxa_rethrow", rethrowFuncTy);
311void ItaniumEHLowering::ensureCxaCallUnexpectedDecl(mlir::Location loc) {
312 if (cxaCallUnexpectedFunc)
314 auto unexpectedFuncTy =
315 cir::FuncType::get({voidPtrType}, voidType,
false);
316 cxaCallUnexpectedFunc = getOrCreateRuntimeFuncDecl(
317 mod, loc,
"__cxa_call_unexpected", unexpectedFuncTy);
321mlir::Block *ItaniumEHLowering::buildTerminateBlock(cir::FuncOp funcOp,
322 mlir::Location loc) {
325 assert(clangCallTerminateFunc &&
326 "ensureClangCallTerminate must run before buildTerminateBlock");
327 mlir::Region &body = funcOp.getRegion();
328 mlir::Block *terminateBlock = builder.createBlock(&body, body.end());
329 auto inflight = cir::EhInflightOp::create(
330 builder, loc,
false,
true,
333 auto terminateCall = cir::CallOp::create(
334 builder, loc, mlir::FlatSymbolRefAttr::get(clangCallTerminateFunc),
335 voidType, mlir::ValueRange{inflight.getExceptionPtr()});
336 terminateCall.setNothrowAttr(builder.getUnitAttr());
337 terminateCall->setAttr(cir::CIRDialect::getNoReturnAttrName(),
338 builder.getUnitAttr());
339 cir::UnreachableOp::create(builder, loc);
340 return terminateBlock;
356static void collectReachableDispatches(
357 mlir::Value rootToken,
358 llvm::SmallSetVector<cir::EhDispatchOp, 4> &dispatches,
359 bool &reachesCleanup) {
360 llvm::SmallVector<mlir::Value> worklist;
361 llvm::SmallPtrSet<mlir::Value, 8> visited;
362 worklist.push_back(rootToken);
366 for (
unsigned i = 0; i < worklist.size(); ++i) {
367 mlir::Value current = worklist[i];
368 if (!visited.insert(current).second)
370 for (mlir::OpOperand &use : current.getUses()) {
371 mlir::Operation *user = use.getOwner();
376 if (mlir::isa<cir::BeginCleanupOp>(user))
377 reachesCleanup =
true;
378 if (
auto dispatch = mlir::dyn_cast<cir::EhDispatchOp>(user))
379 dispatches.insert(dispatch);
381 for (
unsigned s = 0, e = user->getNumSuccessors(); s < e; ++s)
382 for (mlir::BlockArgument arg : user->getSuccessor(s)->getArguments())
383 if (mlir::isa<cir::EhTokenType>(
arg.getType()))
384 worklist.push_back(arg);
390mlir::LogicalResult ItaniumEHLowering::lowerFunc(cir::FuncOp funcOp) {
391 if (funcOp.isDeclaration())
392 return mlir::success();
398 SmallVector<cir::EhInitiateOp> initiateOps;
399 bool hasLandingPad =
false;
400 funcOp.walk([&](mlir::Operation *op) {
401 if (
auto initiateOp = mlir::dyn_cast<cir::EhInitiateOp>(op))
402 initiateOps.push_back(initiateOp);
403 else if (mlir::isa<cir::EhInflightOp>(op))
404 hasLandingPad =
true;
406 if (initiateOps.empty()) {
408 mlir::FlatSymbolRefAttr personality = funcOp.getPersonalityAttr();
409 if (personality && !hasLandingPad) {
410 droppedPersonalities.insert(personality.getAttr());
411 funcOp.removePersonalityAttr();
413 return mlir::success();
416 ensureRuntimeDecls(funcOp.getLoc());
423 if (!funcOp.getPersonality())
424 funcOp.setPersonality(kGxxPersonality);
438 struct InitiateEHInfo {
439 llvm::SmallSetVector<cir::EhDispatchOp, 4> reachedDispatches;
440 bool reachesCleanup =
false;
442 llvm::DenseMap<mlir::Operation *, InitiateEHInfo> initiateInfo;
443 llvm::SmallSetVector<cir::EhDispatchOp, 4> dispatchesToLower;
444 for (cir::EhInitiateOp initiateOp : initiateOps) {
445 InitiateEHInfo &
info = initiateInfo[initiateOp.getOperation()];
446 collectReachableDispatches(initiateOp.getEhToken(),
info.reachedDispatches,
447 info.reachesCleanup);
448 dispatchesToLower.insert(
info.reachedDispatches.begin(),
449 info.reachedDispatches.end());
452 EhTokenMap ehTokenMap;
453 for (cir::EhInitiateOp initiateOp : initiateOps) {
454 const InitiateEHInfo &
info = initiateInfo[initiateOp.getOperation()];
455 if (mlir::failed(lowerEhInitiate(initiateOp,
456 info.reachedDispatches.getArrayRef(),
457 info.reachesCleanup, ehTokenMap)))
458 return mlir::failure();
465 for (cir::EhDispatchOp dispatch : dispatchesToLower) {
466 auto [exnPtr, typeId] = ehTokenMap.lookup(dispatch.getEhToken());
467 assert(exnPtr && typeId &&
468 "dispatch eh_token must be registered in ehTokenMap");
469 lowerDispatch(dispatch, exnPtr, typeId);
474 for (mlir::Block &block : funcOp.getBody()) {
475 for (
int i = block.getNumArguments() - 1; i >= 0; --i) {
476 if (mlir::isa<cir::EhTokenType>(block.getArgument(i).getType()))
477 block.eraseArgument(i);
484 SmallVector<cir::InitCatchParamOp> initCatchOps;
485 funcOp.walk([&](cir::InitCatchParamOp op) { initCatchOps.push_back(op); });
486 for (cir::InitCatchParamOp op : initCatchOps)
487 lowerInitCatchParam(op);
492 SmallVector<cir::TryThrowOp> tryThrowOps;
493 funcOp.walk([&](cir::TryThrowOp op) { tryThrowOps.push_back(op); });
494 for (cir::TryThrowOp op : tryThrowOps)
495 if (mlir::failed(lowerTryThrow(op)))
496 return mlir::failure();
498 return mlir::success();
527mlir::LogicalResult ItaniumEHLowering::lowerEhInitiate(
528 cir::EhInitiateOp initiateOp,
529 llvm::ArrayRef<cir::EhDispatchOp> reachedDispatches,
bool reachesCleanup,
530 EhTokenMap &ehTokenMap) {
533 mlir::Value rootToken = initiateOp.getEhToken();
543 mlir::ArrayAttr catchTypeList;
544 mlir::ArrayAttr filterTypeList;
545 bool catchAll =
false;
546 SmallVector<mlir::Attribute> typeSymbols;
547 for (cir::EhDispatchOp dispatch : reachedDispatches) {
548 if (mlir::ArrayAttr catchTypes = dispatch.getCatchTypesAttr()) {
549 for (mlir::Attribute attr : catchTypes) {
550 if (
auto filter = mlir::dyn_cast<cir::EhFilterAttr>(attr)) {
551 SmallVector<mlir::Attribute> filterSymbols;
554 for (mlir::Attribute typeAttr : filter.getPermittedTypes()) {
555 auto globalView = mlir::cast<cir::GlobalViewAttr>(typeAttr);
556 filterSymbols.push_back(globalView.getSymbol());
558 filterTypeList = builder.getArrayAttr(filterSymbols);
561 typeSymbols.push_back(
562 mlir::cast<cir::GlobalViewAttr>(attr).getSymbol());
565 if (dispatch.getDefaultIsCatchAll() || filterTypeList) {
566 catchAll = dispatch.getDefaultIsCatchAll();
569 assert(dispatch == reachedDispatches.back() &&
570 "catch-all or filter must be the last reachable dispatch");
574 if (!typeSymbols.empty())
575 catchTypeList = builder.getArrayAttr(typeSymbols);
577 builder.setInsertionPoint(initiateOp);
578 auto inflightOp = cir::EhInflightOp::create(
579 builder, initiateOp.getLoc(), initiateOp.getCleanup() || reachesCleanup,
580 catchAll, catchTypeList, filterTypeList);
582 ehTokenMap[rootToken] = {inflightOp.getExceptionPtr(),
583 inflightOp.getTypeId()};
589 SmallVector<mlir::Value> worklist;
590 SmallPtrSet<mlir::Value, 8> visited;
591 worklist.push_back(rootToken);
593 while (!worklist.empty()) {
594 mlir::Value current = worklist.pop_back_val();
595 if (!visited.insert(current).second)
600 SmallVector<mlir::Operation *> users;
601 for (mlir::OpOperand &use : current.getUses())
602 users.push_back(use.getOwner());
606 for (mlir::Operation *user : users) {
612 for (
unsigned s = 0; s < user->getNumSuccessors(); ++s) {
613 mlir::Block *succ = user->getSuccessor(s);
614 for (mlir::BlockArgument arg : succ->getArguments()) {
615 if (!mlir::isa<cir::EhTokenType>(
arg.getType()))
617 if (!ehTokenMap.count(arg)) {
618 mlir::Value ptrArg = succ->addArgument(voidPtrType,
arg.getLoc());
619 mlir::Value u32Arg = succ->addArgument(u32Type,
arg.getLoc());
620 ehTokenMap[
arg] = {ptrArg, u32Arg};
622 worklist.push_back(arg);
626 if (
auto op = mlir::dyn_cast<cir::BeginCleanupOp>(user)) {
629 for (
auto &tokenUsers :
630 llvm::make_early_inc_range(op.getCleanupToken().getUses())) {
632 mlir::dyn_cast<cir::EndCleanupOp>(tokenUsers.getOwner()))
636 }
else if (
auto op = mlir::dyn_cast<cir::BeginCatchOp>(user)) {
639 for (
auto &tokenUsers :
640 llvm::make_early_inc_range(op.getCatchToken().getUses())) {
642 mlir::dyn_cast<cir::EndCatchOp>(tokenUsers.getOwner())) {
643 builder.setInsertionPoint(endOp);
644 cir::CallOp::create(builder, endOp.getLoc(),
645 mlir::FlatSymbolRefAttr::get(endCatchFunc),
646 voidType, mlir::ValueRange{});
651 auto [exnPtr, typeId] = ehTokenMap.lookup(op.getEhToken());
652 builder.setInsertionPoint(op);
653 auto callOp = cir::CallOp::create(
654 builder, op.getLoc(), mlir::FlatSymbolRefAttr::get(beginCatchFunc),
655 u8PtrType, mlir::ValueRange{exnPtr});
656 mlir::Value castResult = callOp.getResult();
657 mlir::Type expectedPtrType = op.getExnPtr().getType();
658 if (castResult.getType() != expectedPtrType)
660 cir::CastOp::create(builder, op.getLoc(), expectedPtrType,
661 cir::CastKind::bitcast, callOp.getResult());
662 op.getExnPtr().replaceAllUsesWith(castResult);
664 }
else if (
auto op = mlir::dyn_cast<cir::ConstructCatchParamOp>(user)) {
665 auto [exnPtr, typeId] = ehTokenMap.lookup(op.getEhToken());
666 if (mlir::failed(lowerConstructCatchParam(op, exnPtr)))
667 return mlir::failure();
668 }
else if (mlir::isa<cir::EhDispatchOp>(user)) {
674 }
else if (
auto op = mlir::dyn_cast<cir::EhTerminateOp>(user)) {
675 auto [exnPtr, typeId] = ehTokenMap.lookup(op.getEhToken());
676 ensureClangCallTerminate(op.getLoc());
677 builder.setInsertionPoint(op);
678 auto call = cir::CallOp::create(
679 builder, op.getLoc(),
680 mlir::FlatSymbolRefAttr::get(clangCallTerminateFunc), voidType,
681 mlir::ValueRange{exnPtr});
682 call.setNothrowAttr(builder.getUnitAttr());
683 call->setAttr(cir::CIRDialect::getNoReturnAttrName(),
684 builder.getUnitAttr());
685 cir::UnreachableOp::create(builder, op.getLoc());
687 }
else if (
auto op = mlir::dyn_cast<cir::EhUnexpectedOp>(user)) {
688 auto [exnPtr, typeId] = ehTokenMap.lookup(op.getEhToken());
689 ensureCxaCallUnexpectedDecl(op.getLoc());
690 builder.setInsertionPoint(op);
691 auto call = cir::CallOp::create(
692 builder, op.getLoc(),
693 mlir::FlatSymbolRefAttr::get(cxaCallUnexpectedFunc), voidType,
694 mlir::ValueRange{exnPtr});
695 call->setAttr(cir::CIRDialect::getNoReturnAttrName(),
696 builder.getUnitAttr());
697 cir::UnreachableOp::create(builder, op.getLoc());
699 }
else if (
auto op = mlir::dyn_cast<cir::ResumeOp>(user)) {
700 auto [exnPtr, typeId] = ehTokenMap.lookup(op.getEhToken());
701 builder.setInsertionPoint(op);
702 cir::ResumeFlatOp::create(builder, op.getLoc(), exnPtr, typeId);
704 }
else if (
auto op = mlir::dyn_cast<cir::BrOp>(user)) {
706 SmallVector<mlir::Value> newOperands;
707 bool changed =
false;
708 for (mlir::Value operand : op.getDestOperands()) {
709 auto it = ehTokenMap.find(operand);
710 if (it != ehTokenMap.end()) {
711 newOperands.push_back(it->second.first);
712 newOperands.push_back(it->second.second);
715 newOperands.push_back(operand);
719 builder.setInsertionPoint(op);
721 assert(!op.getLoopIdAttr() && !op.getLoopHintsAttr());
722 cir::BrOp::create(builder, op.getLoc(), newOperands,
732 return mlir::success();
738void ItaniumEHLowering::lowerDispatch(cir::EhDispatchOp dispatch,
739 mlir::Value exnPtr, mlir::Value typeId) {
740 mlir::Location dispLoc = dispatch.getLoc();
741 mlir::Block *defaultDest = dispatch.getDefaultDestination();
742 mlir::Block *dispatchBlock = dispatch->getBlock();
744 llvm::SmallVector<mlir::Attribute> catchAttrs;
745 llvm::SmallVector<mlir::Block *> catchDests;
746 cir::EhFilterAttr filterAttr;
747 mlir::Block *filterDest =
nullptr;
748 if (mlir::ArrayAttr catchTypes = dispatch.getCatchTypesAttr()) {
749 for (
auto [attr, dest] :
750 llvm::zip(catchTypes, dispatch.getCatchDestinations())) {
751 if (
auto filter = mlir::dyn_cast<cir::EhFilterAttr>(attr)) {
752 assert(!filterAttr &&
"at most one filter handler");
757 catchAttrs.push_back(attr);
758 catchDests.push_back(dest);
765 mlir::Block *
insertBefore = dispatchBlock->getNextNode();
766 mlir::Block *falseDest = defaultDest;
768 assert(filterDest &&
"filter handler requires a destination");
771 if (filterAttr.getPermittedTypes().empty()) {
772 falseDest = filterDest;
777 auto *cmpBlock = builder.createBlock(insertBefore, {voidPtrType, u32Type},
779 mlir::Value cmpExnPtr = cmpBlock->getArgument(0);
780 mlir::Value cmpTypeId = cmpBlock->getArgument(1);
781 mlir::Value signedTypeId = cir::CastOp::create(
782 builder, dispLoc, s32Type, cir::CastKind::integral, cmpTypeId);
783 mlir::Value zero = cir::ConstantOp::create(builder, dispLoc,
784 cir::IntAttr::get(s32Type, 0));
785 auto cmpOp = cir::CmpOp::create(builder, dispLoc, cir::CmpOpKind::lt,
787 cir::BrCondOp::create(builder, dispLoc, cmpOp, filterDest, defaultDest,
788 mlir::ValueRange{cmpExnPtr, cmpTypeId},
789 mlir::ValueRange{cmpExnPtr, cmpTypeId});
791 falseDest = cmpBlock;
795 mlir::Block *firstCmpBlock =
nullptr;
796 if (!catchAttrs.empty()) {
797 unsigned numCatches = catchAttrs.size();
798 for (
int i = numCatches - 1; i >= 0; --i) {
799 auto *cmpBlock = builder.createBlock(insertBefore, {voidPtrType, u32Type},
802 mlir::Value cmpExnPtr = cmpBlock->getArgument(0);
803 mlir::Value cmpTypeId = cmpBlock->getArgument(1);
805 auto globalView = mlir::cast<cir::GlobalViewAttr>(catchAttrs[i]);
807 cir::EhTypeIdOp::create(builder, dispLoc, globalView.getSymbol());
808 auto cmpOp = cir::CmpOp::create(builder, dispLoc, cir::CmpOpKind::eq,
809 cmpTypeId, ehTypeIdOp.getTypeId());
811 cir::BrCondOp::create(builder, dispLoc, cmpOp, catchDests[i], falseDest,
812 mlir::ValueRange{cmpExnPtr, cmpTypeId},
813 mlir::ValueRange{cmpExnPtr, cmpTypeId});
816 falseDest = cmpBlock;
817 firstCmpBlock = cmpBlock;
820 firstCmpBlock = falseDest;
823 builder.setInsertionPoint(dispatch);
824 cir::BrOp::create(builder, dispLoc, firstCmpBlock,
825 mlir::ValueRange{exnPtr, typeId});
832mlir::FailureOr<cir::FuncOp>
833ItaniumEHLowering::resolveCatchCopyThunk(cir::ConstructCatchParamOp op) {
834 mlir::FlatSymbolRefAttr thunkRef = op.getCopyFnAttr();
835 mlir::StringAttr thunkName = thunkRef.getAttr();
836 auto cached = catchCopyThunks.find(thunkName);
837 if (cached != catchCopyThunks.end())
838 return cached->second;
840 cir::FuncOp thunk = mod.lookupSymbol<cir::FuncOp>(thunkRef);
842 return op.emitError(
"could not resolve catch-copy thunk symbol");
843 assert(thunk->hasAttr(cir::CIRDialect::getCatchCopyThunkAttrName()) &&
844 "verifier should have rejected non-thunk catch-copy reference");
845 if (thunk.isDeclaration())
846 return op.emitError(
"catch-copy thunk has no body to inline");
848 mlir::Region &thunkRegion = thunk.getRegion();
849 if (!llvm::hasSingleElement(thunkRegion))
850 return op.emitError(
"multi-block catch-copy thunks are NYI");
852 mlir::Block &thunkEntry = thunkRegion.front();
853 assert(thunkEntry.getNumArguments() == 2 &&
854 "catch-copy thunk must have exactly two parameters");
855 if (!mlir::isa<cir::ReturnOp>(thunkEntry.getTerminator()))
856 return op.emitError(
"catch-copy thunk must end in cir.return");
858 catchCopyThunks[thunkName] = thunk;
866ItaniumEHLowering::lowerConstructCatchParam(cir::ConstructCatchParamOp op,
867 mlir::Value exnPtr) {
870 mlir::Location loc = op.getLoc();
871 mlir::Value paramAddr = op.getParamAddr();
872 cir::PointerType paramAddrType =
873 mlir::cast<cir::PointerType>(paramAddr.getType());
875 if (op.getKind() == cir::InitCatchKind::ReferenceToPointer) {
877 constexpr unsigned headerSize = 32;
879 builder.setInsertionPoint(op);
880 auto index = cir::ConstantOp::create(
881 builder, loc, cir::IntAttr::get(u32Type, headerSize));
882 assert((exnPtr.getType() == voidPtrType || exnPtr.getType() == u8PtrType) &&
883 "lowerConstructCatchParam exn ptr not void* or i8*");
885 cir::PtrStrideOp::create(builder, loc, exnPtr.getType(), exnPtr, index);
887 cir::CastOp::create(builder, loc, paramAddrType.getPointee(),
888 cir::CastKind::bitcast, exnObj);
889 cir::StoreOp::create(builder, loc, casted, paramAddr, {}, {}, {}, {}, {});
894 if (op.getKind() != cir::InitCatchKind::NonTrivialCopy)
895 return op.emitOpError(
"only reference_to_pointer and non_trivial_copy "
896 "kinds are supported");
898 ensureRuntimeDecls(loc);
899 ensureClangCallTerminate(loc);
902 builder.setInsertionPoint(op);
903 cir::CallOp getExnCall = cir::CallOp::create(
904 builder, loc, mlir::FlatSymbolRefAttr::get(getExceptionPtrFunc),
905 u8PtrType, mlir::ValueRange{exnPtr});
906 getExnCall.setNothrowAttr(builder.getUnitAttr());
907 mlir::Value adjusted =
908 cir::CastOp::create(builder, loc, paramAddrType, cir::CastKind::bitcast,
909 getExnCall.getResult());
912 mlir::FailureOr<cir::FuncOp> thunkOr = resolveCatchCopyThunk(op);
913 if (mlir::failed(thunkOr))
914 return mlir::failure();
915 cir::FuncOp thunk = *thunkOr;
919 assert(llvm::hasSingleElement(thunk.getRegion()) &&
920 "multi-block catch-copy thunks are NYI");
923 mlir::Block &thunkEntry = thunk.getRegion().front();
924 mlir::IRMapping mapping;
925 mapping.map(thunkEntry.getArgument(0), paramAddr);
926 mapping.map(thunkEntry.getArgument(1), adjusted);
927 llvm::SmallVector<cir::CallOp> throwingCalls;
928 for (mlir::Operation &thunkOp : thunkEntry.without_terminator()) {
929 mlir::Operation *cloned = builder.clone(thunkOp, mapping);
930 if (cir::CallOp callOp = mlir::dyn_cast<cir::CallOp>(cloned))
931 if (!callOp.getNothrow())
932 throwingCalls.push_back(callOp);
936 if (throwingCalls.empty())
937 return mlir::success();
941 mlir::IRRewriter rewriter(builder);
942 mlir::Block *terminateBlock =
nullptr;
943 for (cir::CallOp call : throwingCalls) {
945 terminateBlock = buildTerminateBlock(call->getParentOfType<cir::FuncOp>(),
949 return mlir::success();
956mlir::LogicalResult ItaniumEHLowering::lowerTryThrow(cir::TryThrowOp op) {
959 mlir::Location loc = op.getLoc();
960 mlir::Block *normalDest = op.getNormalDest();
961 mlir::Block *unwindDest = op.getUnwindDest();
962 builder.setInsertionPoint(op);
965 ensureCxaRethrowDecl(loc);
966 cir::TryCallOp::create(
967 builder, loc, mlir::FlatSymbolRefAttr::get(cxaRethrowFunc), voidType,
968 normalDest, unwindDest, mlir::ValueRange{});
970 return mlir::success();
973 ensureCxaThrowDecl(loc);
976 mlir::Value exnPtr = op.getExceptionPtr();
977 if (exnPtr.getType() != voidPtrType)
978 exnPtr = cir::CastOp::create(builder, loc, voidPtrType,
979 cir::CastKind::bitcast, exnPtr);
984 mlir::FlatSymbolRefAttr typeInfoAttr = op.getTypeInfoAttr();
985 auto typeInfoGlobal = mod.lookupSymbol<cir::GlobalOp>(typeInfoAttr);
987 return op.emitError(
"type_info symbol not found in module");
988 auto typeInfoPtrTy = cir::PointerType::get(typeInfoGlobal.getSymType());
989 mlir::Value typeInfo = cir::GetGlobalOp::create(builder, loc, typeInfoPtrTy,
990 typeInfoAttr.getValue());
991 if (typeInfo.getType() != voidPtrType)
992 typeInfo = cir::CastOp::create(builder, loc, voidPtrType,
993 cir::CastKind::bitcast, typeInfo);
997 if (mlir::FlatSymbolRefAttr dtorAttr = op.getDtorAttr()) {
998 auto dtorFunc = mod.lookupSymbol<cir::FuncOp>(dtorAttr);
1000 return op.emitError(
"dtor symbol not found in module");
1001 auto dtorPtrTy = cir::PointerType::get(dtorFunc.getFunctionType());
1003 cir::GetGlobalOp::create(builder, loc, dtorPtrTy, dtorAttr.getValue());
1004 if (dtor.getType() != voidPtrType)
1005 dtor = cir::CastOp::create(builder, loc, voidPtrType,
1006 cir::CastKind::bitcast, dtor);
1008 dtor = cir::ConstantOp::create(
1010 cir::ConstPtrAttr::get(voidPtrType, builder.getI64IntegerAttr(0)));
1013 cir::TryCallOp::create(
1014 builder, loc, mlir::FlatSymbolRefAttr::get(cxaThrowFunc), voidType,
1015 normalDest, unwindDest, mlir::ValueRange{exnPtr, typeInfo, dtor});
1017 return mlir::success();
1045void ItaniumEHLowering::lowerInitCatchParam(cir::InitCatchParamOp op) {
1046 builder.setInsertionPoint(op);
1047 mlir::Location loc = op.getLoc();
1048 mlir::Value exnPtr = op.getExnPtr();
1049 mlir::Value paramAddr = op.getParamAddr();
1050 auto paramAddrType = mlir::cast<cir::PointerType>(paramAddr.getType());
1051 mlir::Type elementType = paramAddrType.getPointee();
1052 cir::InitCatchKind
kind = op.getKind();
1055 case InitCatchKind::Reference: {
1056 mlir::Value casted = cir::CastOp::create(builder, loc, elementType,
1057 cir::CastKind::bitcast, exnPtr);
1058 cir::StoreOp::create(builder, loc, casted, paramAddr, {}, {}, {}, {}, {});
1061 case InitCatchKind::ReferenceToPointer:
1065 case InitCatchKind::ReferenceToRecordPointer: {
1071 auto caughtType = mlir::cast<cir::PointerType>(
1072 mlir::cast<cir::PointerType>(elementType).getPointee());
1073 cir::AllocaOp byRefTmp;
1075 mlir::OpBuilder::InsertionGuard guard(builder);
1076 builder.setInsertionPointToStart(
1077 &op->getParentOfType<cir::FuncOp>().getBody().front());
1078 cir::CIRDataLayout dataLayout(mod);
1080 dataLayout.getAlignment(caughtType,
true).value();
1082 cir::AllocaOp::create(builder, loc, elementType,
"exn.byref.tmp",
1083 builder.getI64IntegerAttr(alignment));
1085 mlir::Value casted = cir::CastOp::create(builder, loc, caughtType,
1086 cir::CastKind::bitcast, exnPtr);
1087 cir::StoreOp::create(builder, loc, casted, byRefTmp, {}, {}, {}, {}, {});
1088 cir::StoreOp::create(builder, loc, byRefTmp, paramAddr, {}, {}, {}, {}, {});
1091 case InitCatchKind::TrivialCopy: {
1092 mlir::Value srcPtr = cir::CastOp::create(builder, loc, paramAddrType,
1093 cir::CastKind::bitcast, exnPtr);
1094 cir::CopyOp::create(builder, loc, paramAddr, srcPtr, {}, {});
1097 case InitCatchKind::NonTrivialCopy:
1101 case InitCatchKind::Scalar: {
1105 mlir::Value srcPtr = cir::CastOp::create(builder, loc, paramAddrType,
1106 cir::CastKind::bitcast, exnPtr);
1107 auto loadOp = cir::LoadOp::create(builder, loc, elementType, srcPtr);
1108 cir::StoreOp::create(builder, loc, loadOp.getResult(), paramAddr, {}, {},
1112 case InitCatchKind::Pointer: {
1113 mlir::Value casted = cir::CastOp::create(builder, loc, elementType,
1114 cir::CastKind::bitcast, exnPtr);
1115 cir::StoreOp::create(builder, loc, casted, paramAddr, {}, {}, {}, {}, {});
1118 case InitCatchKind::Objc:
1119 llvm_unreachable(
"InitCatchParam: ObjCLifetime is NYI");
1130struct CIREHABILoweringPass
1131 :
public impl::CIREHABILoweringBase<CIREHABILoweringPass> {
1132 CIREHABILoweringPass() =
default;
1133 void runOnOperation()
override;
1139static void eraseCatchCopyThunks(mlir::ModuleOp mod) {
1140 llvm::StringRef catchHelperAttr =
1141 cir::CIRDialect::getCatchCopyThunkAttrName();
1142 for (cir::FuncOp f : llvm::make_early_inc_range(mod.getOps<cir::FuncOp>())) {
1143 if (!f->hasAttr(catchHelperAttr))
1147 assert(mlir::SymbolTable::symbolKnownUseEmpty(f, mod) &&
1148 "catch-init helper has remaining users");
1153void CIREHABILoweringPass::runOnOperation() {
1154 auto mod = mlir::cast<mlir::ModuleOp>(getOperation());
1159 auto tripleAttr = mlir::dyn_cast_if_present<mlir::StringAttr>(
1160 mod->getAttr(cir::CIRDialect::getTripleAttrName()));
1162 mod.emitError(
"Module has no target triple");
1169 llvm::Triple triple(tripleAttr.getValue());
1170 std::unique_ptr<EHABILowering> lowering;
1171 if (triple.isWindowsMSVCEnvironment()) {
1173 "EH ABI lowering is not yet implemented for the Microsoft ABI");
1174 return signalPassFailure();
1176 lowering = std::make_unique<ItaniumEHLowering>(mod);
1179 if (mlir::failed(lowering->run()))
1180 return signalPassFailure();
1183 eraseCatchCopyThunks(mod);
1189 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 opFuncCallingConv()
static bool sizeOfUnwindException()