1 //===- LowerGuardIntrinsic.cpp - Lower the guard intrinsic ---------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass lowers the llvm.experimental.guard intrinsic to a conditional call 11 // to @llvm.experimental.deoptimize. Once this happens, the guard can no longer 12 // be widened. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h" 17 #include "llvm/ADT/SmallVector.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" 27 28 using namespace llvm; 29 30 namespace { 31 struct LowerGuardIntrinsicLegacyPass : public FunctionPass { 32 static char ID; 33 LowerGuardIntrinsicLegacyPass() : FunctionPass(ID) { 34 initializeLowerGuardIntrinsicLegacyPassPass( 35 *PassRegistry::getPassRegistry()); 36 } 37 38 bool runOnFunction(Function &F) override; 39 }; 40 } 41 42 static bool lowerGuardIntrinsic(Function &F) { 43 // Check if we can cheaply rule out the possibility of not having any work to 44 // do. 45 auto *GuardDecl = F.getParent()->getFunction( 46 Intrinsic::getName(Intrinsic::experimental_guard)); 47 if (!GuardDecl || GuardDecl->use_empty()) 48 return false; 49 50 SmallVector<CallInst *, 8> ToLower; 51 for (auto &I : instructions(F)) 52 if (auto *CI = dyn_cast<CallInst>(&I)) 53 if (auto *F = CI->getCalledFunction()) 54 if (F->getIntrinsicID() == Intrinsic::experimental_guard) 55 ToLower.push_back(CI); 56 57 if (ToLower.empty()) 58 return false; 59 60 auto *DeoptIntrinsic = Intrinsic::getDeclaration( 61 F.getParent(), Intrinsic::experimental_deoptimize, {F.getReturnType()}); 62 DeoptIntrinsic->setCallingConv(GuardDecl->getCallingConv()); 63 64 for (auto *CI : ToLower) { 65 makeGuardControlFlowExplicit(DeoptIntrinsic, CI); 66 CI->eraseFromParent(); 67 } 68 69 return true; 70 } 71 72 bool LowerGuardIntrinsicLegacyPass::runOnFunction(Function &F) { 73 return lowerGuardIntrinsic(F); 74 } 75 76 char LowerGuardIntrinsicLegacyPass::ID = 0; 77 INITIALIZE_PASS(LowerGuardIntrinsicLegacyPass, "lower-guard-intrinsic", 78 "Lower the guard intrinsic to normal control flow", false, 79 false) 80 81 Pass *llvm::createLowerGuardIntrinsicPass() { 82 return new LowerGuardIntrinsicLegacyPass(); 83 } 84 85 PreservedAnalyses LowerGuardIntrinsicPass::run(Function &F, 86 FunctionAnalysisManager &AM) { 87 if (lowerGuardIntrinsic(F)) 88 return PreservedAnalyses::none(); 89 90 return PreservedAnalyses::all(); 91 } 92