1 //===- LowerGuardIntrinsic.cpp - Lower the guard intrinsic ---------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This pass lowers the llvm.experimental.guard intrinsic to a conditional call
10 // to @llvm.experimental.deoptimize. Once this happens, the guard can no longer
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/Analysis/GuardUtils.h"
18 #include "llvm/IR/BasicBlock.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/InstIterator.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/Intrinsics.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Transforms/Scalar.h"
26 #include "llvm/Transforms/Utils/GuardUtils.h"
31 struct LowerGuardIntrinsicLegacyPass
: public FunctionPass
{
33 LowerGuardIntrinsicLegacyPass() : FunctionPass(ID
) {
34 initializeLowerGuardIntrinsicLegacyPassPass(
35 *PassRegistry::getPassRegistry());
38 bool runOnFunction(Function
&F
) override
;
42 static bool lowerGuardIntrinsic(Function
&F
) {
43 // Check if we can cheaply rule out the possibility of not having any work to
45 auto *GuardDecl
= F
.getParent()->getFunction(
46 Intrinsic::getName(Intrinsic::experimental_guard
));
47 if (!GuardDecl
|| GuardDecl
->use_empty())
50 SmallVector
<CallInst
*, 8> ToLower
;
51 for (auto &I
: instructions(F
))
53 ToLower
.push_back(cast
<CallInst
>(&I
));
58 auto *DeoptIntrinsic
= Intrinsic::getDeclaration(
59 F
.getParent(), Intrinsic::experimental_deoptimize
, {F
.getReturnType()});
60 DeoptIntrinsic
->setCallingConv(GuardDecl
->getCallingConv());
62 for (auto *CI
: ToLower
) {
63 makeGuardControlFlowExplicit(DeoptIntrinsic
, CI
);
64 CI
->eraseFromParent();
70 bool LowerGuardIntrinsicLegacyPass::runOnFunction(Function
&F
) {
71 return lowerGuardIntrinsic(F
);
74 char LowerGuardIntrinsicLegacyPass::ID
= 0;
75 INITIALIZE_PASS(LowerGuardIntrinsicLegacyPass
, "lower-guard-intrinsic",
76 "Lower the guard intrinsic to normal control flow", false,
79 Pass
*llvm::createLowerGuardIntrinsicPass() {
80 return new LowerGuardIntrinsicLegacyPass();
83 PreservedAnalyses
LowerGuardIntrinsicPass::run(Function
&F
,
84 FunctionAnalysisManager
&AM
) {
85 if (lowerGuardIntrinsic(F
))
86 return PreservedAnalyses::none();
88 return PreservedAnalyses::all();