X86WinEHState.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  1. //===-- X86WinEHState - Insert EH state updates for win32 exceptions ------===//
  2. //
  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
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // All functions using an MSVC EH personality use an explicitly updated state
  10. // number stored in an exception registration stack object. The registration
  11. // object is linked into a thread-local chain of registrations stored at fs:00.
  12. // This pass adds the registration object and EH state updates.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "X86.h"
  16. #include "llvm/ADT/PostOrderIterator.h"
  17. #include "llvm/Analysis/CFG.h"
  18. #include "llvm/Analysis/EHPersonalities.h"
  19. #include "llvm/CodeGen/MachineModuleInfo.h"
  20. #include "llvm/CodeGen/WinEHFuncInfo.h"
  21. #include "llvm/IR/CFG.h"
  22. #include "llvm/IR/Function.h"
  23. #include "llvm/IR/IRBuilder.h"
  24. #include "llvm/IR/Instructions.h"
  25. #include "llvm/IR/Intrinsics.h"
  26. #include "llvm/IR/IntrinsicsX86.h"
  27. #include "llvm/IR/Module.h"
  28. #include "llvm/Pass.h"
  29. #include "llvm/Support/Debug.h"
  30. #include <deque>
  31. using namespace llvm;
  32. #define DEBUG_TYPE "winehstate"
  33. namespace {
  34. const int OverdefinedState = INT_MIN;
  35. class WinEHStatePass : public FunctionPass {
  36. public:
  37. static char ID; // Pass identification, replacement for typeid.
  38. WinEHStatePass() : FunctionPass(ID) { }
  39. bool runOnFunction(Function &Fn) override;
  40. bool doInitialization(Module &M) override;
  41. bool doFinalization(Module &M) override;
  42. void getAnalysisUsage(AnalysisUsage &AU) const override;
  43. StringRef getPassName() const override {
  44. return "Windows 32-bit x86 EH state insertion";
  45. }
  46. private:
  47. void emitExceptionRegistrationRecord(Function *F);
  48. void linkExceptionRegistration(IRBuilder<> &Builder, Function *Handler);
  49. void unlinkExceptionRegistration(IRBuilder<> &Builder);
  50. void addStateStores(Function &F, WinEHFuncInfo &FuncInfo);
  51. void insertStateNumberStore(Instruction *IP, int State);
  52. Value *emitEHLSDA(IRBuilder<> &Builder, Function *F);
  53. Function *generateLSDAInEAXThunk(Function *ParentFunc);
  54. bool isStateStoreNeeded(EHPersonality Personality, CallBase &Call);
  55. void rewriteSetJmpCall(IRBuilder<> &Builder, Function &F, CallBase &Call,
  56. Value *State);
  57. int getBaseStateForBB(DenseMap<BasicBlock *, ColorVector> &BlockColors,
  58. WinEHFuncInfo &FuncInfo, BasicBlock *BB);
  59. int getStateForCall(DenseMap<BasicBlock *, ColorVector> &BlockColors,
  60. WinEHFuncInfo &FuncInfo, CallBase &Call);
  61. // Module-level type getters.
  62. Type *getEHLinkRegistrationType();
  63. Type *getSEHRegistrationType();
  64. Type *getCXXEHRegistrationType();
  65. // Per-module data.
  66. Module *TheModule = nullptr;
  67. StructType *EHLinkRegistrationTy = nullptr;
  68. StructType *CXXEHRegistrationTy = nullptr;
  69. StructType *SEHRegistrationTy = nullptr;
  70. FunctionCallee SetJmp3 = nullptr;
  71. FunctionCallee CxxLongjmpUnwind = nullptr;
  72. // Per-function state
  73. EHPersonality Personality = EHPersonality::Unknown;
  74. Function *PersonalityFn = nullptr;
  75. bool UseStackGuard = false;
  76. int ParentBaseState = 0;
  77. FunctionCallee SehLongjmpUnwind = nullptr;
  78. Constant *Cookie = nullptr;
  79. /// The stack allocation containing all EH data, including the link in the
  80. /// fs:00 chain and the current state.
  81. AllocaInst *RegNode = nullptr;
  82. // The allocation containing the EH security guard.
  83. AllocaInst *EHGuardNode = nullptr;
  84. /// The index of the state field of RegNode.
  85. int StateFieldIndex = ~0U;
  86. /// The linked list node subobject inside of RegNode.
  87. Value *Link = nullptr;
  88. };
  89. } // namespace
  90. FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
  91. char WinEHStatePass::ID = 0;
  92. INITIALIZE_PASS(WinEHStatePass, "x86-winehstate",
  93. "Insert stores for EH state numbers", false, false)
  94. bool WinEHStatePass::doInitialization(Module &M) {
  95. TheModule = &M;
  96. return false;
  97. }
  98. bool WinEHStatePass::doFinalization(Module &M) {
  99. assert(TheModule == &M);
  100. TheModule = nullptr;
  101. EHLinkRegistrationTy = nullptr;
  102. CXXEHRegistrationTy = nullptr;
  103. SEHRegistrationTy = nullptr;
  104. SetJmp3 = nullptr;
  105. CxxLongjmpUnwind = nullptr;
  106. SehLongjmpUnwind = nullptr;
  107. Cookie = nullptr;
  108. return false;
  109. }
  110. void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
  111. // This pass should only insert a stack allocation, memory accesses, and
  112. // localrecovers.
  113. AU.setPreservesCFG();
  114. }
  115. bool WinEHStatePass::runOnFunction(Function &F) {
  116. // Don't insert state stores or exception handler thunks for
  117. // available_externally functions. The handler needs to reference the LSDA,
  118. // which will not be emitted in this case.
  119. if (F.hasAvailableExternallyLinkage())
  120. return false;
  121. // Check the personality. Do nothing if this personality doesn't use funclets.
  122. if (!F.hasPersonalityFn())
  123. return false;
  124. PersonalityFn =
  125. dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
  126. if (!PersonalityFn)
  127. return false;
  128. Personality = classifyEHPersonality(PersonalityFn);
  129. if (!isFuncletEHPersonality(Personality))
  130. return false;
  131. // Skip this function if there are no EH pads and we aren't using IR-level
  132. // outlining.
  133. bool HasPads = false;
  134. for (BasicBlock &BB : F) {
  135. if (BB.isEHPad()) {
  136. HasPads = true;
  137. break;
  138. }
  139. }
  140. if (!HasPads)
  141. return false;
  142. Type *Int8PtrType = Type::getInt8PtrTy(TheModule->getContext());
  143. SetJmp3 = TheModule->getOrInsertFunction(
  144. "_setjmp3", FunctionType::get(
  145. Type::getInt32Ty(TheModule->getContext()),
  146. {Int8PtrType, Type::getInt32Ty(TheModule->getContext())},
  147. /*isVarArg=*/true));
  148. emitExceptionRegistrationRecord(&F);
  149. // The state numbers calculated here in IR must agree with what we calculate
  150. // later on for the MachineFunction. In particular, if an IR pass deletes an
  151. // unreachable EH pad after this point before machine CFG construction, we
  152. // will be in trouble. If this assumption is ever broken, we should turn the
  153. // numbers into an immutable analysis pass.
  154. WinEHFuncInfo FuncInfo;
  155. addStateStores(F, FuncInfo);
  156. // Reset per-function state.
  157. PersonalityFn = nullptr;
  158. Personality = EHPersonality::Unknown;
  159. UseStackGuard = false;
  160. RegNode = nullptr;
  161. EHGuardNode = nullptr;
  162. return true;
  163. }
  164. /// Get the common EH registration subobject:
  165. /// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
  166. /// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
  167. /// struct EHRegistrationNode {
  168. /// EHRegistrationNode *Next;
  169. /// PEXCEPTION_ROUTINE Handler;
  170. /// };
  171. Type *WinEHStatePass::getEHLinkRegistrationType() {
  172. if (EHLinkRegistrationTy)
  173. return EHLinkRegistrationTy;
  174. LLVMContext &Context = TheModule->getContext();
  175. EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
  176. Type *FieldTys[] = {
  177. EHLinkRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
  178. Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
  179. };
  180. EHLinkRegistrationTy->setBody(FieldTys, false);
  181. return EHLinkRegistrationTy;
  182. }
  183. /// The __CxxFrameHandler3 registration node:
  184. /// struct CXXExceptionRegistration {
  185. /// void *SavedESP;
  186. /// EHRegistrationNode SubRecord;
  187. /// int32_t TryLevel;
  188. /// };
  189. Type *WinEHStatePass::getCXXEHRegistrationType() {
  190. if (CXXEHRegistrationTy)
  191. return CXXEHRegistrationTy;
  192. LLVMContext &Context = TheModule->getContext();
  193. Type *FieldTys[] = {
  194. Type::getInt8PtrTy(Context), // void *SavedESP
  195. getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
  196. Type::getInt32Ty(Context) // int32_t TryLevel
  197. };
  198. CXXEHRegistrationTy =
  199. StructType::create(FieldTys, "CXXExceptionRegistration");
  200. return CXXEHRegistrationTy;
  201. }
  202. /// The _except_handler3/4 registration node:
  203. /// struct EH4ExceptionRegistration {
  204. /// void *SavedESP;
  205. /// _EXCEPTION_POINTERS *ExceptionPointers;
  206. /// EHRegistrationNode SubRecord;
  207. /// int32_t EncodedScopeTable;
  208. /// int32_t TryLevel;
  209. /// };
  210. Type *WinEHStatePass::getSEHRegistrationType() {
  211. if (SEHRegistrationTy)
  212. return SEHRegistrationTy;
  213. LLVMContext &Context = TheModule->getContext();
  214. Type *FieldTys[] = {
  215. Type::getInt8PtrTy(Context), // void *SavedESP
  216. Type::getInt8PtrTy(Context), // void *ExceptionPointers
  217. getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
  218. Type::getInt32Ty(Context), // int32_t EncodedScopeTable
  219. Type::getInt32Ty(Context) // int32_t TryLevel
  220. };
  221. SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
  222. return SEHRegistrationTy;
  223. }
  224. // Emit an exception registration record. These are stack allocations with the
  225. // common subobject of two pointers: the previous registration record (the old
  226. // fs:00) and the personality function for the current frame. The data before
  227. // and after that is personality function specific.
  228. void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
  229. assert(Personality == EHPersonality::MSVC_CXX ||
  230. Personality == EHPersonality::MSVC_X86SEH);
  231. // Struct type of RegNode. Used for GEPing.
  232. Type *RegNodeTy;
  233. IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
  234. Type *Int8PtrType = Builder.getInt8PtrTy();
  235. Type *Int32Ty = Builder.getInt32Ty();
  236. Type *VoidTy = Builder.getVoidTy();
  237. if (Personality == EHPersonality::MSVC_CXX) {
  238. RegNodeTy = getCXXEHRegistrationType();
  239. RegNode = Builder.CreateAlloca(RegNodeTy);
  240. // SavedESP = llvm.stacksave()
  241. Value *SP = Builder.CreateCall(
  242. Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
  243. Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
  244. // TryLevel = -1
  245. StateFieldIndex = 2;
  246. ParentBaseState = -1;
  247. insertStateNumberStore(&*Builder.GetInsertPoint(), ParentBaseState);
  248. // Handler = __ehhandler$F
  249. Function *Trampoline = generateLSDAInEAXThunk(F);
  250. Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
  251. linkExceptionRegistration(Builder, Trampoline);
  252. CxxLongjmpUnwind = TheModule->getOrInsertFunction(
  253. "__CxxLongjmpUnwind",
  254. FunctionType::get(VoidTy, Int8PtrType, /*isVarArg=*/false));
  255. cast<Function>(CxxLongjmpUnwind.getCallee()->stripPointerCasts())
  256. ->setCallingConv(CallingConv::X86_StdCall);
  257. } else if (Personality == EHPersonality::MSVC_X86SEH) {
  258. // If _except_handler4 is in use, some additional guard checks and prologue
  259. // stuff is required.
  260. StringRef PersonalityName = PersonalityFn->getName();
  261. UseStackGuard = (PersonalityName == "_except_handler4");
  262. // Allocate local structures.
  263. RegNodeTy = getSEHRegistrationType();
  264. RegNode = Builder.CreateAlloca(RegNodeTy);
  265. if (UseStackGuard)
  266. EHGuardNode = Builder.CreateAlloca(Int32Ty);
  267. // SavedESP = llvm.stacksave()
  268. Value *SP = Builder.CreateCall(
  269. Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
  270. Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
  271. // TryLevel = -2 / -1
  272. StateFieldIndex = 4;
  273. ParentBaseState = UseStackGuard ? -2 : -1;
  274. insertStateNumberStore(&*Builder.GetInsertPoint(), ParentBaseState);
  275. // ScopeTable = llvm.x86.seh.lsda(F)
  276. Value *LSDA = emitEHLSDA(Builder, F);
  277. LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty);
  278. // If using _except_handler4, xor the address of the table with
  279. // __security_cookie.
  280. if (UseStackGuard) {
  281. Cookie = TheModule->getOrInsertGlobal("__security_cookie", Int32Ty);
  282. Value *Val = Builder.CreateLoad(Int32Ty, Cookie, "cookie");
  283. LSDA = Builder.CreateXor(LSDA, Val);
  284. }
  285. Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
  286. // If using _except_handler4, the EHGuard contains: FramePtr xor Cookie.
  287. if (UseStackGuard) {
  288. Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
  289. Value *FrameAddr = Builder.CreateCall(
  290. Intrinsic::getDeclaration(
  291. TheModule, Intrinsic::frameaddress,
  292. Builder.getInt8PtrTy(
  293. TheModule->getDataLayout().getAllocaAddrSpace())),
  294. Builder.getInt32(0), "frameaddr");
  295. Value *FrameAddrI32 = Builder.CreatePtrToInt(FrameAddr, Int32Ty);
  296. FrameAddrI32 = Builder.CreateXor(FrameAddrI32, Val);
  297. Builder.CreateStore(FrameAddrI32, EHGuardNode);
  298. }
  299. // Register the exception handler.
  300. Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
  301. linkExceptionRegistration(Builder, PersonalityFn);
  302. SehLongjmpUnwind = TheModule->getOrInsertFunction(
  303. UseStackGuard ? "_seh_longjmp_unwind4" : "_seh_longjmp_unwind",
  304. FunctionType::get(Type::getVoidTy(TheModule->getContext()), Int8PtrType,
  305. /*isVarArg=*/false));
  306. cast<Function>(SehLongjmpUnwind.getCallee()->stripPointerCasts())
  307. ->setCallingConv(CallingConv::X86_StdCall);
  308. } else {
  309. llvm_unreachable("unexpected personality function");
  310. }
  311. // Insert an unlink before all returns.
  312. for (BasicBlock &BB : *F) {
  313. Instruction *T = BB.getTerminator();
  314. if (!isa<ReturnInst>(T))
  315. continue;
  316. Builder.SetInsertPoint(T);
  317. unlinkExceptionRegistration(Builder);
  318. }
  319. }
  320. Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
  321. Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
  322. return Builder.CreateCall(
  323. Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
  324. }
  325. /// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls
  326. /// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE:
  327. /// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
  328. /// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
  329. /// We essentially want this code:
  330. /// movl $lsda, %eax
  331. /// jmpl ___CxxFrameHandler3
  332. Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
  333. LLVMContext &Context = ParentFunc->getContext();
  334. Type *Int32Ty = Type::getInt32Ty(Context);
  335. Type *Int8PtrType = Type::getInt8PtrTy(Context);
  336. Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
  337. Int8PtrType};
  338. FunctionType *TrampolineTy =
  339. FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
  340. /*isVarArg=*/false);
  341. FunctionType *TargetFuncTy =
  342. FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
  343. /*isVarArg=*/false);
  344. Function *Trampoline =
  345. Function::Create(TrampolineTy, GlobalValue::InternalLinkage,
  346. Twine("__ehhandler$") + GlobalValue::dropLLVMManglingEscape(
  347. ParentFunc->getName()),
  348. TheModule);
  349. if (auto *C = ParentFunc->getComdat())
  350. Trampoline->setComdat(C);
  351. BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
  352. IRBuilder<> Builder(EntryBB);
  353. Value *LSDA = emitEHLSDA(Builder, ParentFunc);
  354. Value *CastPersonality =
  355. Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
  356. auto AI = Trampoline->arg_begin();
  357. Value *Args[5] = {LSDA, &*AI++, &*AI++, &*AI++, &*AI++};
  358. CallInst *Call = Builder.CreateCall(TargetFuncTy, CastPersonality, Args);
  359. // Can't use musttail due to prototype mismatch, but we can use tail.
  360. Call->setTailCall(true);
  361. // Set inreg so we pass it in EAX.
  362. Call->addParamAttr(0, Attribute::InReg);
  363. Builder.CreateRet(Call);
  364. return Trampoline;
  365. }
  366. void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
  367. Function *Handler) {
  368. // Emit the .safeseh directive for this function.
  369. Handler->addFnAttr("safeseh");
  370. Type *LinkTy = getEHLinkRegistrationType();
  371. // Handler = Handler
  372. Value *HandlerI8 = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
  373. Builder.CreateStore(HandlerI8, Builder.CreateStructGEP(LinkTy, Link, 1));
  374. // Next = [fs:00]
  375. Constant *FSZero =
  376. Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
  377. Value *Next = Builder.CreateLoad(LinkTy->getPointerTo(), FSZero);
  378. Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
  379. // [fs:00] = Link
  380. Builder.CreateStore(Link, FSZero);
  381. }
  382. void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
  383. // Clone Link into the current BB for better address mode folding.
  384. if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
  385. GEP = cast<GetElementPtrInst>(GEP->clone());
  386. Builder.Insert(GEP);
  387. Link = GEP;
  388. }
  389. Type *LinkTy = getEHLinkRegistrationType();
  390. // [fs:00] = Link->Next
  391. Value *Next = Builder.CreateLoad(LinkTy->getPointerTo(),
  392. Builder.CreateStructGEP(LinkTy, Link, 0));
  393. Constant *FSZero =
  394. Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
  395. Builder.CreateStore(Next, FSZero);
  396. }
  397. // Calls to setjmp(p) are lowered to _setjmp3(p, 0) by the frontend.
  398. // The idea behind _setjmp3 is that it takes an optional number of personality
  399. // specific parameters to indicate how to restore the personality-specific frame
  400. // state when longjmp is initiated. Typically, the current TryLevel is saved.
  401. void WinEHStatePass::rewriteSetJmpCall(IRBuilder<> &Builder, Function &F,
  402. CallBase &Call, Value *State) {
  403. // Don't rewrite calls with a weird number of arguments.
  404. if (Call.arg_size() != 2)
  405. return;
  406. SmallVector<OperandBundleDef, 1> OpBundles;
  407. Call.getOperandBundlesAsDefs(OpBundles);
  408. SmallVector<Value *, 3> OptionalArgs;
  409. if (Personality == EHPersonality::MSVC_CXX) {
  410. OptionalArgs.push_back(CxxLongjmpUnwind.getCallee());
  411. OptionalArgs.push_back(State);
  412. OptionalArgs.push_back(emitEHLSDA(Builder, &F));
  413. } else if (Personality == EHPersonality::MSVC_X86SEH) {
  414. OptionalArgs.push_back(SehLongjmpUnwind.getCallee());
  415. OptionalArgs.push_back(State);
  416. if (UseStackGuard)
  417. OptionalArgs.push_back(Cookie);
  418. } else {
  419. llvm_unreachable("unhandled personality!");
  420. }
  421. SmallVector<Value *, 5> Args;
  422. Args.push_back(
  423. Builder.CreateBitCast(Call.getArgOperand(0), Builder.getInt8PtrTy()));
  424. Args.push_back(Builder.getInt32(OptionalArgs.size()));
  425. Args.append(OptionalArgs.begin(), OptionalArgs.end());
  426. CallBase *NewCall;
  427. if (auto *CI = dyn_cast<CallInst>(&Call)) {
  428. CallInst *NewCI = Builder.CreateCall(SetJmp3, Args, OpBundles);
  429. NewCI->setTailCallKind(CI->getTailCallKind());
  430. NewCall = NewCI;
  431. } else {
  432. auto *II = cast<InvokeInst>(&Call);
  433. NewCall = Builder.CreateInvoke(
  434. SetJmp3, II->getNormalDest(), II->getUnwindDest(), Args, OpBundles);
  435. }
  436. NewCall->setCallingConv(Call.getCallingConv());
  437. NewCall->setAttributes(Call.getAttributes());
  438. NewCall->setDebugLoc(Call.getDebugLoc());
  439. NewCall->takeName(&Call);
  440. Call.replaceAllUsesWith(NewCall);
  441. Call.eraseFromParent();
  442. }
  443. // Figure out what state we should assign calls in this block.
  444. int WinEHStatePass::getBaseStateForBB(
  445. DenseMap<BasicBlock *, ColorVector> &BlockColors, WinEHFuncInfo &FuncInfo,
  446. BasicBlock *BB) {
  447. int BaseState = ParentBaseState;
  448. auto &BBColors = BlockColors[BB];
  449. assert(BBColors.size() == 1 && "multi-color BB not removed by preparation");
  450. BasicBlock *FuncletEntryBB = BBColors.front();
  451. if (auto *FuncletPad =
  452. dyn_cast<FuncletPadInst>(FuncletEntryBB->getFirstNonPHI())) {
  453. auto BaseStateI = FuncInfo.FuncletBaseStateMap.find(FuncletPad);
  454. if (BaseStateI != FuncInfo.FuncletBaseStateMap.end())
  455. BaseState = BaseStateI->second;
  456. }
  457. return BaseState;
  458. }
  459. // Calculate the state a call-site is in.
  460. int WinEHStatePass::getStateForCall(
  461. DenseMap<BasicBlock *, ColorVector> &BlockColors, WinEHFuncInfo &FuncInfo,
  462. CallBase &Call) {
  463. if (auto *II = dyn_cast<InvokeInst>(&Call)) {
  464. // Look up the state number of the EH pad this unwinds to.
  465. assert(FuncInfo.InvokeStateMap.count(II) && "invoke has no state!");
  466. return FuncInfo.InvokeStateMap[II];
  467. }
  468. // Possibly throwing call instructions have no actions to take after
  469. // an unwind. Ensure they are in the -1 state.
  470. return getBaseStateForBB(BlockColors, FuncInfo, Call.getParent());
  471. }
  472. // Calculate the intersection of all the FinalStates for a BasicBlock's
  473. // predecessors.
  474. static int getPredState(DenseMap<BasicBlock *, int> &FinalStates, Function &F,
  475. int ParentBaseState, BasicBlock *BB) {
  476. // The entry block has no predecessors but we know that the prologue always
  477. // sets us up with a fixed state.
  478. if (&F.getEntryBlock() == BB)
  479. return ParentBaseState;
  480. // This is an EH Pad, conservatively report this basic block as overdefined.
  481. if (BB->isEHPad())
  482. return OverdefinedState;
  483. int CommonState = OverdefinedState;
  484. for (BasicBlock *PredBB : predecessors(BB)) {
  485. // We didn't manage to get a state for one of these predecessors,
  486. // conservatively report this basic block as overdefined.
  487. auto PredEndState = FinalStates.find(PredBB);
  488. if (PredEndState == FinalStates.end())
  489. return OverdefinedState;
  490. // This code is reachable via exceptional control flow,
  491. // conservatively report this basic block as overdefined.
  492. if (isa<CatchReturnInst>(PredBB->getTerminator()))
  493. return OverdefinedState;
  494. int PredState = PredEndState->second;
  495. assert(PredState != OverdefinedState &&
  496. "overdefined BBs shouldn't be in FinalStates");
  497. if (CommonState == OverdefinedState)
  498. CommonState = PredState;
  499. // At least two predecessors have different FinalStates,
  500. // conservatively report this basic block as overdefined.
  501. if (CommonState != PredState)
  502. return OverdefinedState;
  503. }
  504. return CommonState;
  505. }
  506. // Calculate the intersection of all the InitialStates for a BasicBlock's
  507. // successors.
  508. static int getSuccState(DenseMap<BasicBlock *, int> &InitialStates, Function &F,
  509. int ParentBaseState, BasicBlock *BB) {
  510. // This block rejoins normal control flow,
  511. // conservatively report this basic block as overdefined.
  512. if (isa<CatchReturnInst>(BB->getTerminator()))
  513. return OverdefinedState;
  514. int CommonState = OverdefinedState;
  515. for (BasicBlock *SuccBB : successors(BB)) {
  516. // We didn't manage to get a state for one of these predecessors,
  517. // conservatively report this basic block as overdefined.
  518. auto SuccStartState = InitialStates.find(SuccBB);
  519. if (SuccStartState == InitialStates.end())
  520. return OverdefinedState;
  521. // This is an EH Pad, conservatively report this basic block as overdefined.
  522. if (SuccBB->isEHPad())
  523. return OverdefinedState;
  524. int SuccState = SuccStartState->second;
  525. assert(SuccState != OverdefinedState &&
  526. "overdefined BBs shouldn't be in FinalStates");
  527. if (CommonState == OverdefinedState)
  528. CommonState = SuccState;
  529. // At least two successors have different InitialStates,
  530. // conservatively report this basic block as overdefined.
  531. if (CommonState != SuccState)
  532. return OverdefinedState;
  533. }
  534. return CommonState;
  535. }
  536. bool WinEHStatePass::isStateStoreNeeded(EHPersonality Personality,
  537. CallBase &Call) {
  538. // If the function touches memory, it needs a state store.
  539. if (isAsynchronousEHPersonality(Personality))
  540. return !Call.doesNotAccessMemory();
  541. // If the function throws, it needs a state store.
  542. return !Call.doesNotThrow();
  543. }
  544. void WinEHStatePass::addStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
  545. // Mark the registration node. The backend needs to know which alloca it is so
  546. // that it can recover the original frame pointer.
  547. IRBuilder<> Builder(RegNode->getNextNode());
  548. Value *RegNodeI8 = Builder.CreateBitCast(RegNode, Builder.getInt8PtrTy());
  549. Builder.CreateCall(
  550. Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_ehregnode),
  551. {RegNodeI8});
  552. if (EHGuardNode) {
  553. IRBuilder<> Builder(EHGuardNode->getNextNode());
  554. Value *EHGuardNodeI8 =
  555. Builder.CreateBitCast(EHGuardNode, Builder.getInt8PtrTy());
  556. Builder.CreateCall(
  557. Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_ehguard),
  558. {EHGuardNodeI8});
  559. }
  560. // Calculate state numbers.
  561. if (isAsynchronousEHPersonality(Personality))
  562. calculateSEHStateNumbers(&F, FuncInfo);
  563. else
  564. calculateWinCXXEHStateNumbers(&F, FuncInfo);
  565. // Iterate all the instructions and emit state number stores.
  566. DenseMap<BasicBlock *, ColorVector> BlockColors = colorEHFunclets(F);
  567. ReversePostOrderTraversal<Function *> RPOT(&F);
  568. // InitialStates yields the state of the first call-site for a BasicBlock.
  569. DenseMap<BasicBlock *, int> InitialStates;
  570. // FinalStates yields the state of the last call-site for a BasicBlock.
  571. DenseMap<BasicBlock *, int> FinalStates;
  572. // Worklist used to revisit BasicBlocks with indeterminate
  573. // Initial/Final-States.
  574. std::deque<BasicBlock *> Worklist;
  575. // Fill in InitialStates and FinalStates for BasicBlocks with call-sites.
  576. for (BasicBlock *BB : RPOT) {
  577. int InitialState = OverdefinedState;
  578. int FinalState;
  579. if (&F.getEntryBlock() == BB)
  580. InitialState = FinalState = ParentBaseState;
  581. for (Instruction &I : *BB) {
  582. auto *Call = dyn_cast<CallBase>(&I);
  583. if (!Call || !isStateStoreNeeded(Personality, *Call))
  584. continue;
  585. int State = getStateForCall(BlockColors, FuncInfo, *Call);
  586. if (InitialState == OverdefinedState)
  587. InitialState = State;
  588. FinalState = State;
  589. }
  590. // No call-sites in this basic block? That's OK, we will come back to these
  591. // in a later pass.
  592. if (InitialState == OverdefinedState) {
  593. Worklist.push_back(BB);
  594. continue;
  595. }
  596. LLVM_DEBUG(dbgs() << "X86WinEHState: " << BB->getName()
  597. << " InitialState=" << InitialState << '\n');
  598. LLVM_DEBUG(dbgs() << "X86WinEHState: " << BB->getName()
  599. << " FinalState=" << FinalState << '\n');
  600. InitialStates.insert({BB, InitialState});
  601. FinalStates.insert({BB, FinalState});
  602. }
  603. // Try to fill-in InitialStates and FinalStates which have no call-sites.
  604. while (!Worklist.empty()) {
  605. BasicBlock *BB = Worklist.front();
  606. Worklist.pop_front();
  607. // This BasicBlock has already been figured out, nothing more we can do.
  608. if (InitialStates.count(BB) != 0)
  609. continue;
  610. int PredState = getPredState(FinalStates, F, ParentBaseState, BB);
  611. if (PredState == OverdefinedState)
  612. continue;
  613. // We successfully inferred this BasicBlock's state via it's predecessors;
  614. // enqueue it's successors to see if we can infer their states.
  615. InitialStates.insert({BB, PredState});
  616. FinalStates.insert({BB, PredState});
  617. for (BasicBlock *SuccBB : successors(BB))
  618. Worklist.push_back(SuccBB);
  619. }
  620. // Try to hoist stores from successors.
  621. for (BasicBlock *BB : RPOT) {
  622. int SuccState = getSuccState(InitialStates, F, ParentBaseState, BB);
  623. if (SuccState == OverdefinedState)
  624. continue;
  625. // Update our FinalState to reflect the common InitialState of our
  626. // successors.
  627. FinalStates.insert({BB, SuccState});
  628. }
  629. // Finally, insert state stores before call-sites which transition us to a new
  630. // state.
  631. for (BasicBlock *BB : RPOT) {
  632. auto &BBColors = BlockColors[BB];
  633. BasicBlock *FuncletEntryBB = BBColors.front();
  634. if (isa<CleanupPadInst>(FuncletEntryBB->getFirstNonPHI()))
  635. continue;
  636. int PrevState = getPredState(FinalStates, F, ParentBaseState, BB);
  637. LLVM_DEBUG(dbgs() << "X86WinEHState: " << BB->getName()
  638. << " PrevState=" << PrevState << '\n');
  639. for (Instruction &I : *BB) {
  640. auto *Call = dyn_cast<CallBase>(&I);
  641. if (!Call || !isStateStoreNeeded(Personality, *Call))
  642. continue;
  643. int State = getStateForCall(BlockColors, FuncInfo, *Call);
  644. if (State != PrevState)
  645. insertStateNumberStore(&I, State);
  646. PrevState = State;
  647. }
  648. // We might have hoisted a state store into this block, emit it now.
  649. auto EndState = FinalStates.find(BB);
  650. if (EndState != FinalStates.end())
  651. if (EndState->second != PrevState)
  652. insertStateNumberStore(BB->getTerminator(), EndState->second);
  653. }
  654. SmallVector<CallBase *, 1> SetJmp3Calls;
  655. for (BasicBlock *BB : RPOT) {
  656. for (Instruction &I : *BB) {
  657. auto *Call = dyn_cast<CallBase>(&I);
  658. if (!Call)
  659. continue;
  660. if (Call->getCalledOperand()->stripPointerCasts() !=
  661. SetJmp3.getCallee()->stripPointerCasts())
  662. continue;
  663. SetJmp3Calls.push_back(Call);
  664. }
  665. }
  666. for (CallBase *Call : SetJmp3Calls) {
  667. auto &BBColors = BlockColors[Call->getParent()];
  668. BasicBlock *FuncletEntryBB = BBColors.front();
  669. bool InCleanup = isa<CleanupPadInst>(FuncletEntryBB->getFirstNonPHI());
  670. IRBuilder<> Builder(Call);
  671. Value *State;
  672. if (InCleanup) {
  673. Value *StateField = Builder.CreateStructGEP(RegNode->getAllocatedType(),
  674. RegNode, StateFieldIndex);
  675. State = Builder.CreateLoad(Builder.getInt32Ty(), StateField);
  676. } else {
  677. State = Builder.getInt32(getStateForCall(BlockColors, FuncInfo, *Call));
  678. }
  679. rewriteSetJmpCall(Builder, F, *Call, State);
  680. }
  681. }
  682. void WinEHStatePass::insertStateNumberStore(Instruction *IP, int State) {
  683. IRBuilder<> Builder(IP);
  684. Value *StateField = Builder.CreateStructGEP(RegNode->getAllocatedType(),
  685. RegNode, StateFieldIndex);
  686. Builder.CreateStore(Builder.getInt32(State), StateField);
  687. }