WinEHPrepare.cpp 117 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896
  1. //===-- WinEHPrepare - Prepare exception handling for code generation ---===//
  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 LLVM IR exception handling into something closer to what the
  11. // backend wants for functions using a personality function from a runtime
  12. // provided by MSVC. Functions with other personality functions are left alone
  13. // and may be prepared by other passes. In particular, all supported MSVC
  14. // personality functions require cleanup code to be outlined, and the C++
  15. // personality requires catch handler code to be outlined.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "llvm/CodeGen/Passes.h"
  19. #include "llvm/ADT/MapVector.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/SmallSet.h"
  22. #include "llvm/ADT/SetVector.h"
  23. #include "llvm/ADT/Triple.h"
  24. #include "llvm/ADT/TinyPtrVector.h"
  25. #include "llvm/Analysis/LibCallSemantics.h"
  26. #include "llvm/Analysis/TargetLibraryInfo.h"
  27. #include "llvm/CodeGen/WinEHFuncInfo.h"
  28. #include "llvm/IR/Dominators.h"
  29. #include "llvm/IR/Function.h"
  30. #include "llvm/IR/IRBuilder.h"
  31. #include "llvm/IR/Instructions.h"
  32. #include "llvm/IR/IntrinsicInst.h"
  33. #include "llvm/IR/Module.h"
  34. #include "llvm/IR/PatternMatch.h"
  35. #include "llvm/Pass.h"
  36. #include "llvm/Support/Debug.h"
  37. #include "llvm/Support/raw_ostream.h"
  38. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  39. #include "llvm/Transforms/Utils/Cloning.h"
  40. #include "llvm/Transforms/Utils/Local.h"
  41. #include "llvm/Transforms/Utils/PromoteMemToReg.h"
  42. #include <memory>
  43. using namespace llvm;
  44. using namespace llvm::PatternMatch;
  45. #define DEBUG_TYPE "winehprepare"
  46. namespace {
  47. // This map is used to model frame variable usage during outlining, to
  48. // construct a structure type to hold the frame variables in a frame
  49. // allocation block, and to remap the frame variable allocas (including
  50. // spill locations as needed) to GEPs that get the variable from the
  51. // frame allocation structure.
  52. typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap;
  53. // TinyPtrVector cannot hold nullptr, so we need our own sentinel that isn't
  54. // quite null.
  55. AllocaInst *getCatchObjectSentinel() {
  56. return static_cast<AllocaInst *>(nullptr) + 1;
  57. }
  58. typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
  59. class LandingPadActions;
  60. class LandingPadMap;
  61. typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
  62. typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
  63. class WinEHPrepare : public FunctionPass {
  64. public:
  65. static char ID; // Pass identification, replacement for typeid.
  66. WinEHPrepare(const TargetMachine *TM = nullptr)
  67. : FunctionPass(ID) {
  68. if (TM)
  69. TheTriple = TM->getTargetTriple();
  70. }
  71. bool runOnFunction(Function &Fn) override;
  72. bool doFinalization(Module &M) override;
  73. void getAnalysisUsage(AnalysisUsage &AU) const override;
  74. const char *getPassName() const override {
  75. return "Windows exception handling preparation";
  76. }
  77. private:
  78. bool prepareExceptionHandlers(Function &F,
  79. SmallVectorImpl<LandingPadInst *> &LPads);
  80. void identifyEHBlocks(Function &F, SmallVectorImpl<LandingPadInst *> &LPads);
  81. void promoteLandingPadValues(LandingPadInst *LPad);
  82. void demoteValuesLiveAcrossHandlers(Function &F,
  83. SmallVectorImpl<LandingPadInst *> &LPads);
  84. void findSEHEHReturnPoints(Function &F,
  85. SetVector<BasicBlock *> &EHReturnBlocks);
  86. void findCXXEHReturnPoints(Function &F,
  87. SetVector<BasicBlock *> &EHReturnBlocks);
  88. void getPossibleReturnTargets(Function *ParentF, Function *HandlerF,
  89. SetVector<BasicBlock*> &Targets);
  90. void completeNestedLandingPad(Function *ParentFn,
  91. LandingPadInst *OutlinedLPad,
  92. const LandingPadInst *OriginalLPad,
  93. FrameVarInfoMap &VarInfo);
  94. Function *createHandlerFunc(Function *ParentFn, Type *RetTy,
  95. const Twine &Name, Module *M, Value *&ParentFP);
  96. bool outlineHandler(ActionHandler *Action, Function *SrcFn,
  97. LandingPadInst *LPad, BasicBlock *StartBB,
  98. FrameVarInfoMap &VarInfo);
  99. void addStubInvokeToHandlerIfNeeded(Function *Handler);
  100. void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
  101. CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
  102. VisitedBlockSet &VisitedBlocks);
  103. void findCleanupHandlers(LandingPadActions &Actions, BasicBlock *StartBB,
  104. BasicBlock *EndBB);
  105. void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
  106. Triple TheTriple;
  107. // All fields are reset by runOnFunction.
  108. DominatorTree *DT = nullptr;
  109. const TargetLibraryInfo *LibInfo = nullptr;
  110. EHPersonality Personality = EHPersonality::Unknown;
  111. CatchHandlerMapTy CatchHandlerMap;
  112. CleanupHandlerMapTy CleanupHandlerMap;
  113. DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
  114. SmallPtrSet<BasicBlock *, 4> NormalBlocks;
  115. SmallPtrSet<BasicBlock *, 4> EHBlocks;
  116. SetVector<BasicBlock *> EHReturnBlocks;
  117. // This maps landing pad instructions found in outlined handlers to
  118. // the landing pad instruction in the parent function from which they
  119. // were cloned. The cloned/nested landing pad is used as the key
  120. // because the landing pad may be cloned into multiple handlers.
  121. // This map will be used to add the llvm.eh.actions call to the nested
  122. // landing pads after all handlers have been outlined.
  123. DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP;
  124. // This maps blocks in the parent function which are destinations of
  125. // catch handlers to cloned blocks in (other) outlined handlers. This
  126. // handles the case where a nested landing pads has a catch handler that
  127. // returns to a handler function rather than the parent function.
  128. // The original block is used as the key here because there should only
  129. // ever be one handler function from which the cloned block is not pruned.
  130. // The original block will be pruned from the parent function after all
  131. // handlers have been outlined. This map will be used to adjust the
  132. // return instructions of handlers which return to the block that was
  133. // outlined into a handler. This is done after all handlers have been
  134. // outlined but before the outlined code is pruned from the parent function.
  135. DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks;
  136. // Map from outlined handler to call to parent local address. Only used for
  137. // 32-bit EH.
  138. DenseMap<Function *, Value *> HandlerToParentFP;
  139. AllocaInst *SEHExceptionCodeSlot = nullptr;
  140. };
  141. class WinEHFrameVariableMaterializer : public ValueMaterializer {
  142. public:
  143. WinEHFrameVariableMaterializer(Function *OutlinedFn, Value *ParentFP,
  144. FrameVarInfoMap &FrameVarInfo);
  145. ~WinEHFrameVariableMaterializer() override {}
  146. Value *materializeValueFor(Value *V) override;
  147. void escapeCatchObject(Value *V);
  148. private:
  149. FrameVarInfoMap &FrameVarInfo;
  150. IRBuilder<> Builder;
  151. };
  152. class LandingPadMap {
  153. public:
  154. LandingPadMap() : OriginLPad(nullptr) {}
  155. void mapLandingPad(const LandingPadInst *LPad);
  156. bool isInitialized() { return OriginLPad != nullptr; }
  157. bool isOriginLandingPadBlock(const BasicBlock *BB) const;
  158. bool isLandingPadSpecificInst(const Instruction *Inst) const;
  159. void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
  160. Value *SelectorValue) const;
  161. private:
  162. const LandingPadInst *OriginLPad;
  163. // We will normally only see one of each of these instructions, but
  164. // if more than one occurs for some reason we can handle that.
  165. TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
  166. TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
  167. };
  168. class WinEHCloningDirectorBase : public CloningDirector {
  169. public:
  170. WinEHCloningDirectorBase(Function *HandlerFn, Value *ParentFP,
  171. FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
  172. : Materializer(HandlerFn, ParentFP, VarInfo),
  173. SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
  174. Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
  175. LPadMap(LPadMap), ParentFP(ParentFP) {}
  176. CloningAction handleInstruction(ValueToValueMapTy &VMap,
  177. const Instruction *Inst,
  178. BasicBlock *NewBB) override;
  179. virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
  180. const Instruction *Inst,
  181. BasicBlock *NewBB) = 0;
  182. virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
  183. const Instruction *Inst,
  184. BasicBlock *NewBB) = 0;
  185. virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
  186. const Instruction *Inst,
  187. BasicBlock *NewBB) = 0;
  188. virtual CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
  189. const IndirectBrInst *IBr,
  190. BasicBlock *NewBB) = 0;
  191. virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
  192. const InvokeInst *Invoke,
  193. BasicBlock *NewBB) = 0;
  194. virtual CloningAction handleResume(ValueToValueMapTy &VMap,
  195. const ResumeInst *Resume,
  196. BasicBlock *NewBB) = 0;
  197. virtual CloningAction handleCompare(ValueToValueMapTy &VMap,
  198. const CmpInst *Compare,
  199. BasicBlock *NewBB) = 0;
  200. virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
  201. const LandingPadInst *LPad,
  202. BasicBlock *NewBB) = 0;
  203. ValueMaterializer *getValueMaterializer() override { return &Materializer; }
  204. protected:
  205. WinEHFrameVariableMaterializer Materializer;
  206. Type *SelectorIDType;
  207. Type *Int8PtrType;
  208. LandingPadMap &LPadMap;
  209. /// The value representing the parent frame pointer.
  210. Value *ParentFP;
  211. };
  212. class WinEHCatchDirector : public WinEHCloningDirectorBase {
  213. public:
  214. WinEHCatchDirector(
  215. Function *CatchFn, Value *ParentFP, Value *Selector,
  216. FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap,
  217. DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads,
  218. DominatorTree *DT, SmallPtrSetImpl<BasicBlock *> &EHBlocks)
  219. : WinEHCloningDirectorBase(CatchFn, ParentFP, VarInfo, LPadMap),
  220. CurrentSelector(Selector->stripPointerCasts()),
  221. ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads),
  222. DT(DT), EHBlocks(EHBlocks) {}
  223. CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
  224. const Instruction *Inst,
  225. BasicBlock *NewBB) override;
  226. CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
  227. BasicBlock *NewBB) override;
  228. CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
  229. const Instruction *Inst,
  230. BasicBlock *NewBB) override;
  231. CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
  232. const IndirectBrInst *IBr,
  233. BasicBlock *NewBB) override;
  234. CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
  235. BasicBlock *NewBB) override;
  236. CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
  237. BasicBlock *NewBB) override;
  238. CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
  239. BasicBlock *NewBB) override;
  240. CloningAction handleLandingPad(ValueToValueMapTy &VMap,
  241. const LandingPadInst *LPad,
  242. BasicBlock *NewBB) override;
  243. Value *getExceptionVar() { return ExceptionObjectVar; }
  244. TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
  245. private:
  246. Value *CurrentSelector;
  247. Value *ExceptionObjectVar;
  248. TinyPtrVector<BasicBlock *> ReturnTargets;
  249. // This will be a reference to the field of the same name in the WinEHPrepare
  250. // object which instantiates this WinEHCatchDirector object.
  251. DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
  252. DominatorTree *DT;
  253. SmallPtrSetImpl<BasicBlock *> &EHBlocks;
  254. };
  255. class WinEHCleanupDirector : public WinEHCloningDirectorBase {
  256. public:
  257. WinEHCleanupDirector(Function *CleanupFn, Value *ParentFP,
  258. FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
  259. : WinEHCloningDirectorBase(CleanupFn, ParentFP, VarInfo,
  260. LPadMap) {}
  261. CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
  262. const Instruction *Inst,
  263. BasicBlock *NewBB) override;
  264. CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
  265. BasicBlock *NewBB) override;
  266. CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
  267. const Instruction *Inst,
  268. BasicBlock *NewBB) override;
  269. CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
  270. const IndirectBrInst *IBr,
  271. BasicBlock *NewBB) override;
  272. CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
  273. BasicBlock *NewBB) override;
  274. CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
  275. BasicBlock *NewBB) override;
  276. CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
  277. BasicBlock *NewBB) override;
  278. CloningAction handleLandingPad(ValueToValueMapTy &VMap,
  279. const LandingPadInst *LPad,
  280. BasicBlock *NewBB) override;
  281. };
  282. class LandingPadActions {
  283. public:
  284. LandingPadActions() : HasCleanupHandlers(false) {}
  285. void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
  286. void insertCleanupHandler(CleanupHandler *Action) {
  287. Actions.push_back(Action);
  288. HasCleanupHandlers = true;
  289. }
  290. bool includesCleanup() const { return HasCleanupHandlers; }
  291. SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
  292. SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
  293. SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
  294. private:
  295. // Note that this class does not own the ActionHandler objects in this vector.
  296. // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
  297. // in the WinEHPrepare class.
  298. SmallVector<ActionHandler *, 4> Actions;
  299. bool HasCleanupHandlers;
  300. };
  301. } // end anonymous namespace
  302. char WinEHPrepare::ID = 0;
  303. INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
  304. false, false)
  305. FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
  306. return new WinEHPrepare(TM);
  307. }
  308. bool WinEHPrepare::runOnFunction(Function &Fn) {
  309. // No need to prepare outlined handlers.
  310. if (Fn.hasFnAttribute("wineh-parent"))
  311. return false;
  312. SmallVector<LandingPadInst *, 4> LPads;
  313. SmallVector<ResumeInst *, 4> Resumes;
  314. for (BasicBlock &BB : Fn) {
  315. if (auto *LP = BB.getLandingPadInst())
  316. LPads.push_back(LP);
  317. if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
  318. Resumes.push_back(Resume);
  319. }
  320. // No need to prepare functions that lack landing pads.
  321. if (LPads.empty())
  322. return false;
  323. // Classify the personality to see what kind of preparation we need.
  324. Personality = classifyEHPersonality(Fn.getPersonalityFn());
  325. // Do nothing if this is not an MSVC personality.
  326. if (!isMSVCEHPersonality(Personality))
  327. return false;
  328. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  329. LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  330. // If there were any landing pads, prepareExceptionHandlers will make changes.
  331. prepareExceptionHandlers(Fn, LPads);
  332. return true;
  333. }
  334. bool WinEHPrepare::doFinalization(Module &M) { return false; }
  335. void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
  336. AU.addRequired<DominatorTreeWrapperPass>();
  337. AU.addRequired<TargetLibraryInfoWrapperPass>();
  338. }
  339. static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
  340. Constant *&Selector, BasicBlock *&NextBB);
  341. // Finds blocks reachable from the starting set Worklist. Does not follow unwind
  342. // edges or blocks listed in StopPoints.
  343. static void findReachableBlocks(SmallPtrSetImpl<BasicBlock *> &ReachableBBs,
  344. SetVector<BasicBlock *> &Worklist,
  345. const SetVector<BasicBlock *> *StopPoints) {
  346. while (!Worklist.empty()) {
  347. BasicBlock *BB = Worklist.pop_back_val();
  348. // Don't cross blocks that we should stop at.
  349. if (StopPoints && StopPoints->count(BB))
  350. continue;
  351. if (!ReachableBBs.insert(BB).second)
  352. continue; // Already visited.
  353. // Don't follow unwind edges of invokes.
  354. if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
  355. Worklist.insert(II->getNormalDest());
  356. continue;
  357. }
  358. // Otherwise, follow all successors.
  359. Worklist.insert(succ_begin(BB), succ_end(BB));
  360. }
  361. }
  362. // Attempt to find an instruction where a block can be split before
  363. // a call to llvm.eh.begincatch and its operands. If the block
  364. // begins with the begincatch call or one of its adjacent operands
  365. // the block will not be split.
  366. static Instruction *findBeginCatchSplitPoint(BasicBlock *BB,
  367. IntrinsicInst *II) {
  368. // If the begincatch call is already the first instruction in the block,
  369. // don't split.
  370. Instruction *FirstNonPHI = BB->getFirstNonPHI();
  371. if (II == FirstNonPHI)
  372. return nullptr;
  373. // If either operand is in the same basic block as the instruction and
  374. // isn't used by another instruction before the begincatch call, include it
  375. // in the split block.
  376. auto *Op0 = dyn_cast<Instruction>(II->getOperand(0));
  377. auto *Op1 = dyn_cast<Instruction>(II->getOperand(1));
  378. Instruction *I = II->getPrevNode();
  379. Instruction *LastI = II;
  380. while (I == Op0 || I == Op1) {
  381. // If the block begins with one of the operands and there are no other
  382. // instructions between the operand and the begincatch call, don't split.
  383. if (I == FirstNonPHI)
  384. return nullptr;
  385. LastI = I;
  386. I = I->getPrevNode();
  387. }
  388. // If there is at least one instruction in the block before the begincatch
  389. // call and its operands, split the block at either the begincatch or
  390. // its operand.
  391. return LastI;
  392. }
  393. /// Find all points where exceptional control rejoins normal control flow via
  394. /// llvm.eh.endcatch. Add them to the normal bb reachability worklist.
  395. void WinEHPrepare::findCXXEHReturnPoints(
  396. Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
  397. for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
  398. BasicBlock *BB = BBI;
  399. for (Instruction &I : *BB) {
  400. if (match(&I, m_Intrinsic<Intrinsic::eh_begincatch>())) {
  401. Instruction *SplitPt =
  402. findBeginCatchSplitPoint(BB, cast<IntrinsicInst>(&I));
  403. if (SplitPt) {
  404. // Split the block before the llvm.eh.begincatch call to allow
  405. // cleanup and catch code to be distinguished later.
  406. // Do not update BBI because we still need to process the
  407. // portion of the block that we are splitting off.
  408. SplitBlock(BB, SplitPt, DT);
  409. break;
  410. }
  411. }
  412. if (match(&I, m_Intrinsic<Intrinsic::eh_endcatch>())) {
  413. // Split the block after the call to llvm.eh.endcatch if there is
  414. // anything other than an unconditional branch, or if the successor
  415. // starts with a phi.
  416. auto *Br = dyn_cast<BranchInst>(I.getNextNode());
  417. if (!Br || !Br->isUnconditional() ||
  418. isa<PHINode>(Br->getSuccessor(0)->begin())) {
  419. DEBUG(dbgs() << "splitting block " << BB->getName()
  420. << " with llvm.eh.endcatch\n");
  421. BBI = SplitBlock(BB, I.getNextNode(), DT);
  422. }
  423. // The next BB is normal control flow.
  424. EHReturnBlocks.insert(BB->getTerminator()->getSuccessor(0));
  425. break;
  426. }
  427. }
  428. }
  429. }
  430. static bool isCatchAllLandingPad(const BasicBlock *BB) {
  431. const LandingPadInst *LP = BB->getLandingPadInst();
  432. if (!LP)
  433. return false;
  434. unsigned N = LP->getNumClauses();
  435. return (N > 0 && LP->isCatch(N - 1) &&
  436. isa<ConstantPointerNull>(LP->getClause(N - 1)));
  437. }
  438. /// Find all points where exceptions control rejoins normal control flow via
  439. /// selector dispatch.
  440. void WinEHPrepare::findSEHEHReturnPoints(
  441. Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
  442. for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
  443. BasicBlock *BB = BBI;
  444. // If the landingpad is a catch-all, treat the whole lpad as if it is
  445. // reachable from normal control flow.
  446. // FIXME: This is imprecise. We need a better way of identifying where a
  447. // catch-all starts and cleanups stop. As far as LLVM is concerned, there
  448. // is no difference.
  449. if (isCatchAllLandingPad(BB)) {
  450. EHReturnBlocks.insert(BB);
  451. continue;
  452. }
  453. BasicBlock *CatchHandler;
  454. BasicBlock *NextBB;
  455. Constant *Selector;
  456. if (isSelectorDispatch(BB, CatchHandler, Selector, NextBB)) {
  457. // Split the edge if there are multiple predecessors. This creates a place
  458. // where we can insert EH recovery code.
  459. if (!CatchHandler->getSinglePredecessor()) {
  460. DEBUG(dbgs() << "splitting EH return edge from " << BB->getName()
  461. << " to " << CatchHandler->getName() << '\n');
  462. BBI = CatchHandler = SplitCriticalEdge(
  463. BB, std::find(succ_begin(BB), succ_end(BB), CatchHandler));
  464. }
  465. EHReturnBlocks.insert(CatchHandler);
  466. }
  467. }
  468. }
  469. void WinEHPrepare::identifyEHBlocks(Function &F,
  470. SmallVectorImpl<LandingPadInst *> &LPads) {
  471. DEBUG(dbgs() << "Demoting values live across exception handlers in function "
  472. << F.getName() << '\n');
  473. // Build a set of all non-exceptional blocks and exceptional blocks.
  474. // - Non-exceptional blocks are blocks reachable from the entry block while
  475. // not following invoke unwind edges.
  476. // - Exceptional blocks are blocks reachable from landingpads. Analysis does
  477. // not follow llvm.eh.endcatch blocks, which mark a transition from
  478. // exceptional to normal control.
  479. if (Personality == EHPersonality::MSVC_CXX)
  480. findCXXEHReturnPoints(F, EHReturnBlocks);
  481. else
  482. findSEHEHReturnPoints(F, EHReturnBlocks);
  483. DEBUG({
  484. dbgs() << "identified the following blocks as EH return points:\n";
  485. for (BasicBlock *BB : EHReturnBlocks)
  486. dbgs() << " " << BB->getName() << '\n';
  487. });
  488. // Join points should not have phis at this point, unless they are a
  489. // landingpad, in which case we will demote their phis later.
  490. #ifndef NDEBUG
  491. for (BasicBlock *BB : EHReturnBlocks)
  492. assert((BB->isLandingPad() || !isa<PHINode>(BB->begin())) &&
  493. "non-lpad EH return block has phi");
  494. #endif
  495. // Normal blocks are the blocks reachable from the entry block and all EH
  496. // return points.
  497. SetVector<BasicBlock *> Worklist;
  498. Worklist = EHReturnBlocks;
  499. Worklist.insert(&F.getEntryBlock());
  500. findReachableBlocks(NormalBlocks, Worklist, nullptr);
  501. DEBUG({
  502. dbgs() << "marked the following blocks as normal:\n";
  503. for (BasicBlock *BB : NormalBlocks)
  504. dbgs() << " " << BB->getName() << '\n';
  505. });
  506. // Exceptional blocks are the blocks reachable from landingpads that don't
  507. // cross EH return points.
  508. Worklist.clear();
  509. for (auto *LPI : LPads)
  510. Worklist.insert(LPI->getParent());
  511. findReachableBlocks(EHBlocks, Worklist, &EHReturnBlocks);
  512. DEBUG({
  513. dbgs() << "marked the following blocks as exceptional:\n";
  514. for (BasicBlock *BB : EHBlocks)
  515. dbgs() << " " << BB->getName() << '\n';
  516. });
  517. }
  518. /// Ensure that all values live into and out of exception handlers are stored
  519. /// in memory.
  520. /// FIXME: This falls down when values are defined in one handler and live into
  521. /// another handler. For example, a cleanup defines a value used only by a
  522. /// catch handler.
  523. void WinEHPrepare::demoteValuesLiveAcrossHandlers(
  524. Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
  525. DEBUG(dbgs() << "Demoting values live across exception handlers in function "
  526. << F.getName() << '\n');
  527. // identifyEHBlocks() should have been called before this function.
  528. assert(!NormalBlocks.empty());
  529. // Try to avoid demoting EH pointer and selector values. They get in the way
  530. // of our pattern matching.
  531. SmallPtrSet<Instruction *, 10> EHVals;
  532. for (BasicBlock &BB : F) {
  533. LandingPadInst *LP = BB.getLandingPadInst();
  534. if (!LP)
  535. continue;
  536. EHVals.insert(LP);
  537. for (User *U : LP->users()) {
  538. auto *EI = dyn_cast<ExtractValueInst>(U);
  539. if (!EI)
  540. continue;
  541. EHVals.insert(EI);
  542. for (User *U2 : EI->users()) {
  543. if (auto *PN = dyn_cast<PHINode>(U2))
  544. EHVals.insert(PN);
  545. }
  546. }
  547. }
  548. SetVector<Argument *> ArgsToDemote;
  549. SetVector<Instruction *> InstrsToDemote;
  550. for (BasicBlock &BB : F) {
  551. bool IsNormalBB = NormalBlocks.count(&BB);
  552. bool IsEHBB = EHBlocks.count(&BB);
  553. if (!IsNormalBB && !IsEHBB)
  554. continue; // Blocks that are neither normal nor EH are unreachable.
  555. for (Instruction &I : BB) {
  556. for (Value *Op : I.operands()) {
  557. // Don't demote static allocas, constants, and labels.
  558. if (isa<Constant>(Op) || isa<BasicBlock>(Op) || isa<InlineAsm>(Op))
  559. continue;
  560. auto *AI = dyn_cast<AllocaInst>(Op);
  561. if (AI && AI->isStaticAlloca())
  562. continue;
  563. if (auto *Arg = dyn_cast<Argument>(Op)) {
  564. if (IsEHBB) {
  565. DEBUG(dbgs() << "Demoting argument " << *Arg
  566. << " used by EH instr: " << I << "\n");
  567. ArgsToDemote.insert(Arg);
  568. }
  569. continue;
  570. }
  571. // Don't demote EH values.
  572. auto *OpI = cast<Instruction>(Op);
  573. if (EHVals.count(OpI))
  574. continue;
  575. BasicBlock *OpBB = OpI->getParent();
  576. // If a value is produced and consumed in the same BB, we don't need to
  577. // demote it.
  578. if (OpBB == &BB)
  579. continue;
  580. bool IsOpNormalBB = NormalBlocks.count(OpBB);
  581. bool IsOpEHBB = EHBlocks.count(OpBB);
  582. if (IsNormalBB != IsOpNormalBB || IsEHBB != IsOpEHBB) {
  583. DEBUG({
  584. dbgs() << "Demoting instruction live in-out from EH:\n";
  585. dbgs() << "Instr: " << *OpI << '\n';
  586. dbgs() << "User: " << I << '\n';
  587. });
  588. InstrsToDemote.insert(OpI);
  589. }
  590. }
  591. }
  592. }
  593. // Demote values live into and out of handlers.
  594. // FIXME: This demotion is inefficient. We should insert spills at the point
  595. // of definition, insert one reload in each handler that uses the value, and
  596. // insert reloads in the BB used to rejoin normal control flow.
  597. Instruction *AllocaInsertPt = F.getEntryBlock().getFirstInsertionPt();
  598. for (Instruction *I : InstrsToDemote)
  599. DemoteRegToStack(*I, false, AllocaInsertPt);
  600. // Demote arguments separately, and only for uses in EH blocks.
  601. for (Argument *Arg : ArgsToDemote) {
  602. auto *Slot = new AllocaInst(Arg->getType(), nullptr,
  603. Arg->getName() + ".reg2mem", AllocaInsertPt);
  604. SmallVector<User *, 4> Users(Arg->user_begin(), Arg->user_end());
  605. for (User *U : Users) {
  606. auto *I = dyn_cast<Instruction>(U);
  607. if (I && EHBlocks.count(I->getParent())) {
  608. auto *Reload = new LoadInst(Slot, Arg->getName() + ".reload", false, I);
  609. U->replaceUsesOfWith(Arg, Reload);
  610. }
  611. }
  612. new StoreInst(Arg, Slot, AllocaInsertPt);
  613. }
  614. // Demote landingpad phis, as the landingpad will be removed from the machine
  615. // CFG.
  616. for (LandingPadInst *LPI : LPads) {
  617. BasicBlock *BB = LPI->getParent();
  618. while (auto *Phi = dyn_cast<PHINode>(BB->begin()))
  619. DemotePHIToStack(Phi, AllocaInsertPt);
  620. }
  621. DEBUG(dbgs() << "Demoted " << InstrsToDemote.size() << " instructions and "
  622. << ArgsToDemote.size() << " arguments for WinEHPrepare\n\n");
  623. }
  624. bool WinEHPrepare::prepareExceptionHandlers(
  625. Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
  626. // Don't run on functions that are already prepared.
  627. for (LandingPadInst *LPad : LPads) {
  628. BasicBlock *LPadBB = LPad->getParent();
  629. for (Instruction &Inst : *LPadBB)
  630. if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>()))
  631. return false;
  632. }
  633. identifyEHBlocks(F, LPads);
  634. demoteValuesLiveAcrossHandlers(F, LPads);
  635. // These containers are used to re-map frame variables that are used in
  636. // outlined catch and cleanup handlers. They will be populated as the
  637. // handlers are outlined.
  638. FrameVarInfoMap FrameVarInfo;
  639. bool HandlersOutlined = false;
  640. Module *M = F.getParent();
  641. LLVMContext &Context = M->getContext();
  642. // Create a new function to receive the handler contents.
  643. PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
  644. Type *Int32Type = Type::getInt32Ty(Context);
  645. Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
  646. if (isAsynchronousEHPersonality(Personality)) {
  647. // FIXME: Switch the ehptr type to i32 and then switch this.
  648. SEHExceptionCodeSlot =
  649. new AllocaInst(Int8PtrType, nullptr, "seh_exception_code",
  650. F.getEntryBlock().getFirstInsertionPt());
  651. }
  652. // In order to handle the case where one outlined catch handler returns
  653. // to a block within another outlined catch handler that would otherwise
  654. // be unreachable, we need to outline the nested landing pad before we
  655. // outline the landing pad which encloses it.
  656. if (!isAsynchronousEHPersonality(Personality))
  657. std::sort(LPads.begin(), LPads.end(),
  658. [this](LandingPadInst *const &L, LandingPadInst *const &R) {
  659. return DT->properlyDominates(R->getParent(), L->getParent());
  660. });
  661. // This container stores the llvm.eh.recover and IndirectBr instructions
  662. // that make up the body of each landing pad after it has been outlined.
  663. // We need to defer the population of the target list for the indirectbr
  664. // until all landing pads have been outlined so that we can handle the
  665. // case of blocks in the target that are reached only from nested
  666. // landing pads.
  667. SmallVector<std::pair<CallInst*, IndirectBrInst *>, 4> LPadImpls;
  668. for (LandingPadInst *LPad : LPads) {
  669. // Look for evidence that this landingpad has already been processed.
  670. bool LPadHasActionList = false;
  671. BasicBlock *LPadBB = LPad->getParent();
  672. for (Instruction &Inst : *LPadBB) {
  673. if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) {
  674. LPadHasActionList = true;
  675. break;
  676. }
  677. }
  678. // If we've already outlined the handlers for this landingpad,
  679. // there's nothing more to do here.
  680. if (LPadHasActionList)
  681. continue;
  682. // If either of the values in the aggregate returned by the landing pad is
  683. // extracted and stored to memory, promote the stored value to a register.
  684. promoteLandingPadValues(LPad);
  685. LandingPadActions Actions;
  686. mapLandingPadBlocks(LPad, Actions);
  687. HandlersOutlined |= !Actions.actions().empty();
  688. for (ActionHandler *Action : Actions) {
  689. if (Action->hasBeenProcessed())
  690. continue;
  691. BasicBlock *StartBB = Action->getStartBlock();
  692. // SEH doesn't do any outlining for catches. Instead, pass the handler
  693. // basic block addr to llvm.eh.actions and list the block as a return
  694. // target.
  695. if (isAsynchronousEHPersonality(Personality)) {
  696. if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
  697. processSEHCatchHandler(CatchAction, StartBB);
  698. continue;
  699. }
  700. }
  701. outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo);
  702. }
  703. // Split the block after the landingpad instruction so that it is just a
  704. // call to llvm.eh.actions followed by indirectbr.
  705. assert(!isa<PHINode>(LPadBB->begin()) && "lpad phi not removed");
  706. SplitBlock(LPadBB, LPad->getNextNode(), DT);
  707. // Erase the branch inserted by the split so we can insert indirectbr.
  708. LPadBB->getTerminator()->eraseFromParent();
  709. // Replace all extracted values with undef and ultimately replace the
  710. // landingpad with undef.
  711. SmallVector<Instruction *, 4> SEHCodeUses;
  712. SmallVector<Instruction *, 4> EHUndefs;
  713. for (User *U : LPad->users()) {
  714. auto *E = dyn_cast<ExtractValueInst>(U);
  715. if (!E)
  716. continue;
  717. assert(E->getNumIndices() == 1 &&
  718. "Unexpected operation: extracting both landing pad values");
  719. unsigned Idx = *E->idx_begin();
  720. assert((Idx == 0 || Idx == 1) && "unexpected index");
  721. if (Idx == 0 && isAsynchronousEHPersonality(Personality))
  722. SEHCodeUses.push_back(E);
  723. else
  724. EHUndefs.push_back(E);
  725. }
  726. for (Instruction *E : EHUndefs) {
  727. E->replaceAllUsesWith(UndefValue::get(E->getType()));
  728. E->eraseFromParent();
  729. }
  730. LPad->replaceAllUsesWith(UndefValue::get(LPad->getType()));
  731. // Rewrite uses of the exception pointer to loads of an alloca.
  732. while (!SEHCodeUses.empty()) {
  733. Instruction *E = SEHCodeUses.pop_back_val();
  734. SmallVector<Use *, 4> Uses;
  735. for (Use &U : E->uses())
  736. Uses.push_back(&U);
  737. for (Use *U : Uses) {
  738. auto *I = cast<Instruction>(U->getUser());
  739. if (isa<ResumeInst>(I))
  740. continue;
  741. if (auto *Phi = dyn_cast<PHINode>(I))
  742. SEHCodeUses.push_back(Phi);
  743. else
  744. U->set(new LoadInst(SEHExceptionCodeSlot, "sehcode", false, I));
  745. }
  746. E->replaceAllUsesWith(UndefValue::get(E->getType()));
  747. E->eraseFromParent();
  748. }
  749. // Add a call to describe the actions for this landing pad.
  750. std::vector<Value *> ActionArgs;
  751. for (ActionHandler *Action : Actions) {
  752. // Action codes from docs are: 0 cleanup, 1 catch.
  753. if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
  754. ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
  755. ActionArgs.push_back(CatchAction->getSelector());
  756. // Find the frame escape index of the exception object alloca in the
  757. // parent.
  758. int FrameEscapeIdx = -1;
  759. Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
  760. if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
  761. auto I = FrameVarInfo.find(EHObj);
  762. assert(I != FrameVarInfo.end() &&
  763. "failed to map llvm.eh.begincatch var");
  764. FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
  765. }
  766. ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
  767. } else {
  768. ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
  769. }
  770. ActionArgs.push_back(Action->getHandlerBlockOrFunc());
  771. }
  772. CallInst *Recover =
  773. CallInst::Create(ActionIntrin, ActionArgs, "recover", LPadBB);
  774. SetVector<BasicBlock *> ReturnTargets;
  775. for (ActionHandler *Action : Actions) {
  776. if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
  777. const auto &CatchTargets = CatchAction->getReturnTargets();
  778. ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end());
  779. }
  780. }
  781. IndirectBrInst *Branch =
  782. IndirectBrInst::Create(Recover, ReturnTargets.size(), LPadBB);
  783. for (BasicBlock *Target : ReturnTargets)
  784. Branch->addDestination(Target);
  785. if (!isAsynchronousEHPersonality(Personality)) {
  786. // C++ EH must repopulate the targets later to handle the case of
  787. // targets that are reached indirectly through nested landing pads.
  788. LPadImpls.push_back(std::make_pair(Recover, Branch));
  789. }
  790. } // End for each landingpad
  791. // If nothing got outlined, there is no more processing to be done.
  792. if (!HandlersOutlined)
  793. return false;
  794. // Replace any nested landing pad stubs with the correct action handler.
  795. // This must be done before we remove unreachable blocks because it
  796. // cleans up references to outlined blocks that will be deleted.
  797. for (auto &LPadPair : NestedLPtoOriginalLP)
  798. completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
  799. NestedLPtoOriginalLP.clear();
  800. // Update the indirectbr instructions' target lists if necessary.
  801. SetVector<BasicBlock*> CheckedTargets;
  802. SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
  803. for (auto &LPadImplPair : LPadImpls) {
  804. IntrinsicInst *Recover = cast<IntrinsicInst>(LPadImplPair.first);
  805. IndirectBrInst *Branch = LPadImplPair.second;
  806. // Get a list of handlers called by
  807. parseEHActions(Recover, ActionList);
  808. // Add an indirect branch listing possible successors of the catch handlers.
  809. SetVector<BasicBlock *> ReturnTargets;
  810. for (const auto &Action : ActionList) {
  811. if (auto *CA = dyn_cast<CatchHandler>(Action.get())) {
  812. Function *Handler = cast<Function>(CA->getHandlerBlockOrFunc());
  813. getPossibleReturnTargets(&F, Handler, ReturnTargets);
  814. }
  815. }
  816. ActionList.clear();
  817. // Clear any targets we already knew about.
  818. for (unsigned int I = 0, E = Branch->getNumDestinations(); I < E; ++I) {
  819. BasicBlock *KnownTarget = Branch->getDestination(I);
  820. if (ReturnTargets.count(KnownTarget))
  821. ReturnTargets.remove(KnownTarget);
  822. }
  823. for (BasicBlock *Target : ReturnTargets) {
  824. Branch->addDestination(Target);
  825. // The target may be a block that we excepted to get pruned.
  826. // If it is, it may contain a call to llvm.eh.endcatch.
  827. if (CheckedTargets.insert(Target)) {
  828. // Earlier preparations guarantee that all calls to llvm.eh.endcatch
  829. // will be followed by an unconditional branch.
  830. auto *Br = dyn_cast<BranchInst>(Target->getTerminator());
  831. if (Br && Br->isUnconditional() &&
  832. Br != Target->getFirstNonPHIOrDbgOrLifetime()) {
  833. Instruction *Prev = Br->getPrevNode();
  834. if (match(cast<Value>(Prev), m_Intrinsic<Intrinsic::eh_endcatch>()))
  835. Prev->eraseFromParent();
  836. }
  837. }
  838. }
  839. }
  840. LPadImpls.clear();
  841. F.addFnAttr("wineh-parent", F.getName());
  842. // Delete any blocks that were only used by handlers that were outlined above.
  843. removeUnreachableBlocks(F);
  844. BasicBlock *Entry = &F.getEntryBlock();
  845. IRBuilder<> Builder(F.getParent()->getContext());
  846. Builder.SetInsertPoint(Entry->getFirstInsertionPt());
  847. Function *FrameEscapeFn =
  848. Intrinsic::getDeclaration(M, Intrinsic::localescape);
  849. Function *RecoverFrameFn =
  850. Intrinsic::getDeclaration(M, Intrinsic::localrecover);
  851. SmallVector<Value *, 8> AllocasToEscape;
  852. // Scan the entry block for an existing call to llvm.localescape. We need to
  853. // keep escaping those objects.
  854. for (Instruction &I : F.front()) {
  855. auto *II = dyn_cast<IntrinsicInst>(&I);
  856. if (II && II->getIntrinsicID() == Intrinsic::localescape) {
  857. auto Args = II->arg_operands();
  858. AllocasToEscape.append(Args.begin(), Args.end());
  859. II->eraseFromParent();
  860. break;
  861. }
  862. }
  863. // Finally, replace all of the temporary allocas for frame variables used in
  864. // the outlined handlers with calls to llvm.localrecover.
  865. for (auto &VarInfoEntry : FrameVarInfo) {
  866. Value *ParentVal = VarInfoEntry.first;
  867. TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
  868. AllocaInst *ParentAlloca = cast<AllocaInst>(ParentVal);
  869. // FIXME: We should try to sink unescaped allocas from the parent frame into
  870. // the child frame. If the alloca is escaped, we have to use the lifetime
  871. // markers to ensure that the alloca is only live within the child frame.
  872. // Add this alloca to the list of things to escape.
  873. AllocasToEscape.push_back(ParentAlloca);
  874. // Next replace all outlined allocas that are mapped to it.
  875. for (AllocaInst *TempAlloca : Allocas) {
  876. if (TempAlloca == getCatchObjectSentinel())
  877. continue; // Skip catch parameter sentinels.
  878. Function *HandlerFn = TempAlloca->getParent()->getParent();
  879. llvm::Value *FP = HandlerToParentFP[HandlerFn];
  880. assert(FP);
  881. // FIXME: Sink this localrecover into the blocks where it is used.
  882. Builder.SetInsertPoint(TempAlloca);
  883. Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
  884. Value *RecoverArgs[] = {
  885. Builder.CreateBitCast(&F, Int8PtrType, ""), FP,
  886. llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
  887. Instruction *RecoveredAlloca =
  888. Builder.CreateCall(RecoverFrameFn, RecoverArgs);
  889. // Add a pointer bitcast if the alloca wasn't an i8.
  890. if (RecoveredAlloca->getType() != TempAlloca->getType()) {
  891. RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
  892. RecoveredAlloca = cast<Instruction>(
  893. Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType()));
  894. }
  895. TempAlloca->replaceAllUsesWith(RecoveredAlloca);
  896. TempAlloca->removeFromParent();
  897. RecoveredAlloca->takeName(TempAlloca);
  898. delete TempAlloca;
  899. }
  900. } // End for each FrameVarInfo entry.
  901. // Insert 'call void (...)* @llvm.localescape(...)' at the end of the entry
  902. // block.
  903. Builder.SetInsertPoint(&F.getEntryBlock().back());
  904. Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
  905. if (SEHExceptionCodeSlot) {
  906. if (isAllocaPromotable(SEHExceptionCodeSlot)) {
  907. SmallPtrSet<BasicBlock *, 4> UserBlocks;
  908. for (User *U : SEHExceptionCodeSlot->users()) {
  909. if (auto *Inst = dyn_cast<Instruction>(U))
  910. UserBlocks.insert(Inst->getParent());
  911. }
  912. PromoteMemToReg(SEHExceptionCodeSlot, *DT);
  913. // After the promotion, kill off dead instructions.
  914. for (BasicBlock *BB : UserBlocks)
  915. SimplifyInstructionsInBlock(BB, LibInfo);
  916. }
  917. }
  918. // Clean up the handler action maps we created for this function
  919. DeleteContainerSeconds(CatchHandlerMap);
  920. CatchHandlerMap.clear();
  921. DeleteContainerSeconds(CleanupHandlerMap);
  922. CleanupHandlerMap.clear();
  923. HandlerToParentFP.clear();
  924. DT = nullptr;
  925. LibInfo = nullptr;
  926. SEHExceptionCodeSlot = nullptr;
  927. EHBlocks.clear();
  928. NormalBlocks.clear();
  929. EHReturnBlocks.clear();
  930. return HandlersOutlined;
  931. }
  932. void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
  933. // If the return values of the landing pad instruction are extracted and
  934. // stored to memory, we want to promote the store locations to reg values.
  935. SmallVector<AllocaInst *, 2> EHAllocas;
  936. // The landingpad instruction returns an aggregate value. Typically, its
  937. // value will be passed to a pair of extract value instructions and the
  938. // results of those extracts are often passed to store instructions.
  939. // In unoptimized code the stored value will often be loaded and then stored
  940. // again.
  941. for (auto *U : LPad->users()) {
  942. ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
  943. if (!Extract)
  944. continue;
  945. for (auto *EU : Extract->users()) {
  946. if (auto *Store = dyn_cast<StoreInst>(EU)) {
  947. auto *AV = cast<AllocaInst>(Store->getPointerOperand());
  948. EHAllocas.push_back(AV);
  949. }
  950. }
  951. }
  952. // We can't do this without a dominator tree.
  953. assert(DT);
  954. if (!EHAllocas.empty()) {
  955. PromoteMemToReg(EHAllocas, *DT);
  956. EHAllocas.clear();
  957. }
  958. // After promotion, some extracts may be trivially dead. Remove them.
  959. SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end());
  960. for (auto *U : Users)
  961. RecursivelyDeleteTriviallyDeadInstructions(U);
  962. }
  963. void WinEHPrepare::getPossibleReturnTargets(Function *ParentF,
  964. Function *HandlerF,
  965. SetVector<BasicBlock*> &Targets) {
  966. for (BasicBlock &BB : *HandlerF) {
  967. // If the handler contains landing pads, check for any
  968. // handlers that may return directly to a block in the
  969. // parent function.
  970. if (auto *LPI = BB.getLandingPadInst()) {
  971. IntrinsicInst *Recover = cast<IntrinsicInst>(LPI->getNextNode());
  972. SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
  973. parseEHActions(Recover, ActionList);
  974. for (const auto &Action : ActionList) {
  975. if (auto *CH = dyn_cast<CatchHandler>(Action.get())) {
  976. Function *NestedF = cast<Function>(CH->getHandlerBlockOrFunc());
  977. getPossibleReturnTargets(ParentF, NestedF, Targets);
  978. }
  979. }
  980. }
  981. auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator());
  982. if (!Ret)
  983. continue;
  984. // Handler functions must always return a block address.
  985. BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
  986. // If this is the handler for a nested landing pad, the
  987. // return address may have been remapped to a block in the
  988. // parent handler. We're not interested in those.
  989. if (BA->getFunction() != ParentF)
  990. continue;
  991. Targets.insert(BA->getBasicBlock());
  992. }
  993. }
  994. void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
  995. LandingPadInst *OutlinedLPad,
  996. const LandingPadInst *OriginalLPad,
  997. FrameVarInfoMap &FrameVarInfo) {
  998. // Get the nested block and erase the unreachable instruction that was
  999. // temporarily inserted as its terminator.
  1000. LLVMContext &Context = ParentFn->getContext();
  1001. BasicBlock *OutlinedBB = OutlinedLPad->getParent();
  1002. // If the nested landing pad was outlined before the landing pad that enclosed
  1003. // it, it will already be in outlined form. In that case, we just need to see
  1004. // if the returns and the enclosing branch instruction need to be updated.
  1005. IndirectBrInst *Branch =
  1006. dyn_cast<IndirectBrInst>(OutlinedBB->getTerminator());
  1007. if (!Branch) {
  1008. // If the landing pad wasn't in outlined form, it should be a stub with
  1009. // an unreachable terminator.
  1010. assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
  1011. OutlinedBB->getTerminator()->eraseFromParent();
  1012. // That should leave OutlinedLPad as the last instruction in its block.
  1013. assert(&OutlinedBB->back() == OutlinedLPad);
  1014. }
  1015. // The original landing pad will have already had its action intrinsic
  1016. // built by the outlining loop. We need to clone that into the outlined
  1017. // location. It may also be necessary to add references to the exception
  1018. // variables to the outlined handler in which this landing pad is nested
  1019. // and remap return instructions in the nested handlers that should return
  1020. // to an address in the outlined handler.
  1021. Function *OutlinedHandlerFn = OutlinedBB->getParent();
  1022. BasicBlock::const_iterator II = OriginalLPad;
  1023. ++II;
  1024. // The instruction after the landing pad should now be a call to eh.actions.
  1025. const Instruction *Recover = II;
  1026. const IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover);
  1027. // Remap the return target in the nested handler.
  1028. SmallVector<BlockAddress *, 4> ActionTargets;
  1029. SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
  1030. parseEHActions(EHActions, ActionList);
  1031. for (const auto &Action : ActionList) {
  1032. auto *Catch = dyn_cast<CatchHandler>(Action.get());
  1033. if (!Catch)
  1034. continue;
  1035. // The dyn_cast to function here selects C++ catch handlers and skips
  1036. // SEH catch handlers.
  1037. auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
  1038. if (!Handler)
  1039. continue;
  1040. // Visit all the return instructions, looking for places that return
  1041. // to a location within OutlinedHandlerFn.
  1042. for (BasicBlock &NestedHandlerBB : *Handler) {
  1043. auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
  1044. if (!Ret)
  1045. continue;
  1046. // Handler functions must always return a block address.
  1047. BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
  1048. // The original target will have been in the main parent function,
  1049. // but if it is the address of a block that has been outlined, it
  1050. // should be a block that was outlined into OutlinedHandlerFn.
  1051. assert(BA->getFunction() == ParentFn);
  1052. // Ignore targets that aren't part of an outlined handler function.
  1053. if (!LPadTargetBlocks.count(BA->getBasicBlock()))
  1054. continue;
  1055. // If the return value is the address ofF a block that we
  1056. // previously outlined into the parent handler function, replace
  1057. // the return instruction and add the mapped target to the list
  1058. // of possible return addresses.
  1059. BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
  1060. assert(MappedBB->getParent() == OutlinedHandlerFn);
  1061. BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
  1062. Ret->eraseFromParent();
  1063. ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
  1064. ActionTargets.push_back(NewBA);
  1065. }
  1066. }
  1067. ActionList.clear();
  1068. if (Branch) {
  1069. // If the landing pad was already in outlined form, just update its targets.
  1070. for (unsigned int I = Branch->getNumDestinations(); I > 0; --I)
  1071. Branch->removeDestination(I);
  1072. // Add the previously collected action targets.
  1073. for (auto *Target : ActionTargets)
  1074. Branch->addDestination(Target->getBasicBlock());
  1075. } else {
  1076. // If the landing pad was previously stubbed out, fill in its outlined form.
  1077. IntrinsicInst *NewEHActions = cast<IntrinsicInst>(EHActions->clone());
  1078. OutlinedBB->getInstList().push_back(NewEHActions);
  1079. // Insert an indirect branch into the outlined landing pad BB.
  1080. IndirectBrInst *IBr = IndirectBrInst::Create(NewEHActions, 0, OutlinedBB);
  1081. // Add the previously collected action targets.
  1082. for (auto *Target : ActionTargets)
  1083. IBr->addDestination(Target->getBasicBlock());
  1084. }
  1085. }
  1086. // This function examines a block to determine whether the block ends with a
  1087. // conditional branch to a catch handler based on a selector comparison.
  1088. // This function is used both by the WinEHPrepare::findSelectorComparison() and
  1089. // WinEHCleanupDirector::handleTypeIdFor().
  1090. static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
  1091. Constant *&Selector, BasicBlock *&NextBB) {
  1092. ICmpInst::Predicate Pred;
  1093. BasicBlock *TBB, *FBB;
  1094. Value *LHS, *RHS;
  1095. if (!match(BB->getTerminator(),
  1096. m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
  1097. return false;
  1098. if (!match(LHS,
  1099. m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
  1100. !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
  1101. return false;
  1102. if (Pred == CmpInst::ICMP_EQ) {
  1103. CatchHandler = TBB;
  1104. NextBB = FBB;
  1105. return true;
  1106. }
  1107. if (Pred == CmpInst::ICMP_NE) {
  1108. CatchHandler = FBB;
  1109. NextBB = TBB;
  1110. return true;
  1111. }
  1112. return false;
  1113. }
  1114. static bool isCatchBlock(BasicBlock *BB) {
  1115. for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
  1116. II != IE; ++II) {
  1117. if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_begincatch>()))
  1118. return true;
  1119. }
  1120. return false;
  1121. }
  1122. static BasicBlock *createStubLandingPad(Function *Handler) {
  1123. // FIXME: Finish this!
  1124. LLVMContext &Context = Handler->getContext();
  1125. BasicBlock *StubBB = BasicBlock::Create(Context, "stub");
  1126. Handler->getBasicBlockList().push_back(StubBB);
  1127. IRBuilder<> Builder(StubBB);
  1128. LandingPadInst *LPad = Builder.CreateLandingPad(
  1129. llvm::StructType::get(Type::getInt8PtrTy(Context),
  1130. Type::getInt32Ty(Context), nullptr),
  1131. 0);
  1132. // Insert a call to llvm.eh.actions so that we don't try to outline this lpad.
  1133. Function *ActionIntrin =
  1134. Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::eh_actions);
  1135. Builder.CreateCall(ActionIntrin, {}, "recover");
  1136. LPad->setCleanup(true);
  1137. Builder.CreateUnreachable();
  1138. return StubBB;
  1139. }
  1140. // Cycles through the blocks in an outlined handler function looking for an
  1141. // invoke instruction and inserts an invoke of llvm.donothing with an empty
  1142. // landing pad if none is found. The code that generates the .xdata tables for
  1143. // the handler needs at least one landing pad to identify the parent function's
  1144. // personality.
  1145. void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler) {
  1146. ReturnInst *Ret = nullptr;
  1147. UnreachableInst *Unreached = nullptr;
  1148. for (BasicBlock &BB : *Handler) {
  1149. TerminatorInst *Terminator = BB.getTerminator();
  1150. // If we find an invoke, there is nothing to be done.
  1151. auto *II = dyn_cast<InvokeInst>(Terminator);
  1152. if (II)
  1153. return;
  1154. // If we've already recorded a return instruction, keep looking for invokes.
  1155. if (!Ret)
  1156. Ret = dyn_cast<ReturnInst>(Terminator);
  1157. // If we haven't recorded an unreachable instruction, try this terminator.
  1158. if (!Unreached)
  1159. Unreached = dyn_cast<UnreachableInst>(Terminator);
  1160. }
  1161. // If we got this far, the handler contains no invokes. We should have seen
  1162. // at least one return or unreachable instruction. We'll insert an invoke of
  1163. // llvm.donothing ahead of that instruction.
  1164. assert(Ret || Unreached);
  1165. TerminatorInst *Term;
  1166. if (Ret)
  1167. Term = Ret;
  1168. else
  1169. Term = Unreached;
  1170. BasicBlock *OldRetBB = Term->getParent();
  1171. BasicBlock *NewRetBB = SplitBlock(OldRetBB, Term, DT);
  1172. // SplitBlock adds an unconditional branch instruction at the end of the
  1173. // parent block. We want to replace that with an invoke call, so we can
  1174. // erase it now.
  1175. OldRetBB->getTerminator()->eraseFromParent();
  1176. BasicBlock *StubLandingPad = createStubLandingPad(Handler);
  1177. Function *F =
  1178. Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing);
  1179. InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB);
  1180. }
  1181. // FIXME: Consider sinking this into lib/Target/X86 somehow. TargetLowering
  1182. // usually doesn't build LLVM IR, so that's probably the wrong place.
  1183. Function *WinEHPrepare::createHandlerFunc(Function *ParentFn, Type *RetTy,
  1184. const Twine &Name, Module *M,
  1185. Value *&ParentFP) {
  1186. // x64 uses a two-argument prototype where the parent FP is the second
  1187. // argument. x86 uses no arguments, just the incoming EBP value.
  1188. LLVMContext &Context = M->getContext();
  1189. Type *Int8PtrType = Type::getInt8PtrTy(Context);
  1190. FunctionType *FnType;
  1191. if (TheTriple.getArch() == Triple::x86_64) {
  1192. Type *ArgTys[2] = {Int8PtrType, Int8PtrType};
  1193. FnType = FunctionType::get(RetTy, ArgTys, false);
  1194. } else {
  1195. FnType = FunctionType::get(RetTy, None, false);
  1196. }
  1197. Function *Handler =
  1198. Function::Create(FnType, GlobalVariable::InternalLinkage, Name, M);
  1199. BasicBlock *Entry = BasicBlock::Create(Context, "entry");
  1200. Handler->getBasicBlockList().push_front(Entry);
  1201. if (TheTriple.getArch() == Triple::x86_64) {
  1202. ParentFP = &(Handler->getArgumentList().back());
  1203. } else {
  1204. assert(M);
  1205. Function *FrameAddressFn =
  1206. Intrinsic::getDeclaration(M, Intrinsic::frameaddress);
  1207. Function *RecoverFPFn =
  1208. Intrinsic::getDeclaration(M, Intrinsic::x86_seh_recoverfp);
  1209. IRBuilder<> Builder(&Handler->getEntryBlock());
  1210. Value *EBP =
  1211. Builder.CreateCall(FrameAddressFn, {Builder.getInt32(1)}, "ebp");
  1212. Value *ParentI8Fn = Builder.CreateBitCast(ParentFn, Int8PtrType);
  1213. ParentFP = Builder.CreateCall(RecoverFPFn, {ParentI8Fn, EBP});
  1214. }
  1215. return Handler;
  1216. }
  1217. bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
  1218. LandingPadInst *LPad, BasicBlock *StartBB,
  1219. FrameVarInfoMap &VarInfo) {
  1220. Module *M = SrcFn->getParent();
  1221. LLVMContext &Context = M->getContext();
  1222. Type *Int8PtrType = Type::getInt8PtrTy(Context);
  1223. // Create a new function to receive the handler contents.
  1224. Value *ParentFP;
  1225. Function *Handler;
  1226. if (Action->getType() == Catch) {
  1227. Handler = createHandlerFunc(SrcFn, Int8PtrType, SrcFn->getName() + ".catch", M,
  1228. ParentFP);
  1229. } else {
  1230. Handler = createHandlerFunc(SrcFn, Type::getVoidTy(Context),
  1231. SrcFn->getName() + ".cleanup", M, ParentFP);
  1232. }
  1233. Handler->setPersonalityFn(SrcFn->getPersonalityFn());
  1234. HandlerToParentFP[Handler] = ParentFP;
  1235. Handler->addFnAttr("wineh-parent", SrcFn->getName());
  1236. BasicBlock *Entry = &Handler->getEntryBlock();
  1237. // Generate a standard prolog to setup the frame recovery structure.
  1238. IRBuilder<> Builder(Context);
  1239. Builder.SetInsertPoint(Entry);
  1240. Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
  1241. std::unique_ptr<WinEHCloningDirectorBase> Director;
  1242. ValueToValueMapTy VMap;
  1243. LandingPadMap &LPadMap = LPadMaps[LPad];
  1244. if (!LPadMap.isInitialized())
  1245. LPadMap.mapLandingPad(LPad);
  1246. if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
  1247. Constant *Sel = CatchAction->getSelector();
  1248. Director.reset(new WinEHCatchDirector(Handler, ParentFP, Sel, VarInfo,
  1249. LPadMap, NestedLPtoOriginalLP, DT,
  1250. EHBlocks));
  1251. LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
  1252. ConstantInt::get(Type::getInt32Ty(Context), 1));
  1253. } else {
  1254. Director.reset(
  1255. new WinEHCleanupDirector(Handler, ParentFP, VarInfo, LPadMap));
  1256. LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
  1257. UndefValue::get(Type::getInt32Ty(Context)));
  1258. }
  1259. SmallVector<ReturnInst *, 8> Returns;
  1260. ClonedCodeInfo OutlinedFunctionInfo;
  1261. // If the start block contains PHI nodes, we need to map them.
  1262. BasicBlock::iterator II = StartBB->begin();
  1263. while (auto *PN = dyn_cast<PHINode>(II)) {
  1264. bool Mapped = false;
  1265. // Look for PHI values that we have already mapped (such as the selector).
  1266. for (Value *Val : PN->incoming_values()) {
  1267. if (VMap.count(Val)) {
  1268. VMap[PN] = VMap[Val];
  1269. Mapped = true;
  1270. }
  1271. }
  1272. // If we didn't find a match for this value, map it as an undef.
  1273. if (!Mapped) {
  1274. VMap[PN] = UndefValue::get(PN->getType());
  1275. }
  1276. ++II;
  1277. }
  1278. // The landing pad value may be used by PHI nodes. It will ultimately be
  1279. // eliminated, but we need it in the map for intermediate handling.
  1280. VMap[LPad] = UndefValue::get(LPad->getType());
  1281. // Skip over PHIs and, if applicable, landingpad instructions.
  1282. II = StartBB->getFirstInsertionPt();
  1283. CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
  1284. /*ModuleLevelChanges=*/false, Returns, "",
  1285. &OutlinedFunctionInfo, Director.get());
  1286. // Move all the instructions in the cloned "entry" block into our entry block.
  1287. // Depending on how the parent function was laid out, the block that will
  1288. // correspond to the outlined entry block may not be the first block in the
  1289. // list. We can recognize it, however, as the cloned block which has no
  1290. // predecessors. Any other block wouldn't have been cloned if it didn't
  1291. // have a predecessor which was also cloned.
  1292. Function::iterator ClonedIt = std::next(Function::iterator(Entry));
  1293. while (!pred_empty(ClonedIt))
  1294. ++ClonedIt;
  1295. BasicBlock *ClonedEntryBB = ClonedIt;
  1296. assert(ClonedEntryBB);
  1297. Entry->getInstList().splice(Entry->end(), ClonedEntryBB->getInstList());
  1298. ClonedEntryBB->eraseFromParent();
  1299. // Make sure we can identify the handler's personality later.
  1300. addStubInvokeToHandlerIfNeeded(Handler);
  1301. if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
  1302. WinEHCatchDirector *CatchDirector =
  1303. reinterpret_cast<WinEHCatchDirector *>(Director.get());
  1304. CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
  1305. CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
  1306. // Look for blocks that are not part of the landing pad that we just
  1307. // outlined but terminate with a call to llvm.eh.endcatch and a
  1308. // branch to a block that is in the handler we just outlined.
  1309. // These blocks will be part of a nested landing pad that intends to
  1310. // return to an address in this handler. This case is best handled
  1311. // after both landing pads have been outlined, so for now we'll just
  1312. // save the association of the blocks in LPadTargetBlocks. The
  1313. // return instructions which are created from these branches will be
  1314. // replaced after all landing pads have been outlined.
  1315. for (const auto MapEntry : VMap) {
  1316. // VMap maps all values and blocks that were just cloned, but dead
  1317. // blocks which were pruned will map to nullptr.
  1318. if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
  1319. continue;
  1320. const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
  1321. for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
  1322. auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
  1323. if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
  1324. continue;
  1325. BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
  1326. --II;
  1327. if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
  1328. // This would indicate that a nested landing pad wants to return
  1329. // to a block that is outlined into two different handlers.
  1330. assert(!LPadTargetBlocks.count(MappedBB));
  1331. LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
  1332. }
  1333. }
  1334. }
  1335. } // End if (CatchAction)
  1336. Action->setHandlerBlockOrFunc(Handler);
  1337. return true;
  1338. }
  1339. /// This BB must end in a selector dispatch. All we need to do is pass the
  1340. /// handler block to llvm.eh.actions and list it as a possible indirectbr
  1341. /// target.
  1342. void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
  1343. BasicBlock *StartBB) {
  1344. BasicBlock *HandlerBB;
  1345. BasicBlock *NextBB;
  1346. Constant *Selector;
  1347. bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
  1348. if (Res) {
  1349. // If this was EH dispatch, this must be a conditional branch to the handler
  1350. // block.
  1351. // FIXME: Handle instructions in the dispatch block. Currently we drop them,
  1352. // leading to crashes if some optimization hoists stuff here.
  1353. assert(CatchAction->getSelector() && HandlerBB &&
  1354. "expected catch EH dispatch");
  1355. } else {
  1356. // This must be a catch-all. Split the block after the landingpad.
  1357. assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
  1358. HandlerBB = SplitBlock(StartBB, StartBB->getFirstInsertionPt(), DT);
  1359. }
  1360. IRBuilder<> Builder(HandlerBB->getFirstInsertionPt());
  1361. Function *EHCodeFn = Intrinsic::getDeclaration(
  1362. StartBB->getParent()->getParent(), Intrinsic::eh_exceptioncode);
  1363. Value *Code = Builder.CreateCall(EHCodeFn, {}, "sehcode");
  1364. Code = Builder.CreateIntToPtr(Code, SEHExceptionCodeSlot->getAllocatedType());
  1365. Builder.CreateStore(Code, SEHExceptionCodeSlot);
  1366. CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
  1367. TinyPtrVector<BasicBlock *> Targets(HandlerBB);
  1368. CatchAction->setReturnTargets(Targets);
  1369. }
  1370. void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
  1371. // Each instance of this class should only ever be used to map a single
  1372. // landing pad.
  1373. assert(OriginLPad == nullptr || OriginLPad == LPad);
  1374. // If the landing pad has already been mapped, there's nothing more to do.
  1375. if (OriginLPad == LPad)
  1376. return;
  1377. OriginLPad = LPad;
  1378. // The landingpad instruction returns an aggregate value. Typically, its
  1379. // value will be passed to a pair of extract value instructions and the
  1380. // results of those extracts will have been promoted to reg values before
  1381. // this routine is called.
  1382. for (auto *U : LPad->users()) {
  1383. const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
  1384. if (!Extract)
  1385. continue;
  1386. assert(Extract->getNumIndices() == 1 &&
  1387. "Unexpected operation: extracting both landing pad values");
  1388. unsigned int Idx = *(Extract->idx_begin());
  1389. assert((Idx == 0 || Idx == 1) &&
  1390. "Unexpected operation: extracting an unknown landing pad element");
  1391. if (Idx == 0) {
  1392. ExtractedEHPtrs.push_back(Extract);
  1393. } else if (Idx == 1) {
  1394. ExtractedSelectors.push_back(Extract);
  1395. }
  1396. }
  1397. }
  1398. bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
  1399. return BB->getLandingPadInst() == OriginLPad;
  1400. }
  1401. bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
  1402. if (Inst == OriginLPad)
  1403. return true;
  1404. for (auto *Extract : ExtractedEHPtrs) {
  1405. if (Inst == Extract)
  1406. return true;
  1407. }
  1408. for (auto *Extract : ExtractedSelectors) {
  1409. if (Inst == Extract)
  1410. return true;
  1411. }
  1412. return false;
  1413. }
  1414. void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
  1415. Value *SelectorValue) const {
  1416. // Remap all landing pad extract instructions to the specified values.
  1417. for (auto *Extract : ExtractedEHPtrs)
  1418. VMap[Extract] = EHPtrValue;
  1419. for (auto *Extract : ExtractedSelectors)
  1420. VMap[Extract] = SelectorValue;
  1421. }
  1422. static bool isLocalAddressCall(const Value *V) {
  1423. return match(const_cast<Value *>(V), m_Intrinsic<Intrinsic::localaddress>());
  1424. }
  1425. CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
  1426. ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
  1427. // If this is one of the boilerplate landing pad instructions, skip it.
  1428. // The instruction will have already been remapped in VMap.
  1429. if (LPadMap.isLandingPadSpecificInst(Inst))
  1430. return CloningDirector::SkipInstruction;
  1431. // Nested landing pads that have not already been outlined will be cloned as
  1432. // stubs, with just the landingpad instruction and an unreachable instruction.
  1433. // When all landingpads have been outlined, we'll replace this with the
  1434. // llvm.eh.actions call and indirect branch created when the landing pad was
  1435. // outlined.
  1436. if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
  1437. return handleLandingPad(VMap, LPad, NewBB);
  1438. }
  1439. // Nested landing pads that have already been outlined will be cloned in their
  1440. // outlined form, but we need to intercept the ibr instruction to filter out
  1441. // targets that do not return to the handler we are outlining.
  1442. if (auto *IBr = dyn_cast<IndirectBrInst>(Inst)) {
  1443. return handleIndirectBr(VMap, IBr, NewBB);
  1444. }
  1445. if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
  1446. return handleInvoke(VMap, Invoke, NewBB);
  1447. if (auto *Resume = dyn_cast<ResumeInst>(Inst))
  1448. return handleResume(VMap, Resume, NewBB);
  1449. if (auto *Cmp = dyn_cast<CmpInst>(Inst))
  1450. return handleCompare(VMap, Cmp, NewBB);
  1451. if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
  1452. return handleBeginCatch(VMap, Inst, NewBB);
  1453. if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
  1454. return handleEndCatch(VMap, Inst, NewBB);
  1455. if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
  1456. return handleTypeIdFor(VMap, Inst, NewBB);
  1457. // When outlining llvm.localaddress(), remap that to the second argument,
  1458. // which is the FP of the parent.
  1459. if (isLocalAddressCall(Inst)) {
  1460. VMap[Inst] = ParentFP;
  1461. return CloningDirector::SkipInstruction;
  1462. }
  1463. // Continue with the default cloning behavior.
  1464. return CloningDirector::CloneInstruction;
  1465. }
  1466. CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
  1467. ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
  1468. // If the instruction after the landing pad is a call to llvm.eh.actions
  1469. // the landing pad has already been outlined. In this case, we should
  1470. // clone it because it may return to a block in the handler we are
  1471. // outlining now that would otherwise be unreachable. The landing pads
  1472. // are sorted before outlining begins to enable this case to work
  1473. // properly.
  1474. const Instruction *NextI = LPad->getNextNode();
  1475. if (match(NextI, m_Intrinsic<Intrinsic::eh_actions>()))
  1476. return CloningDirector::CloneInstruction;
  1477. // If the landing pad hasn't been outlined yet, the landing pad we are
  1478. // outlining now does not dominate it and so it cannot return to a block
  1479. // in this handler. In that case, we can just insert a stub landing
  1480. // pad now and patch it up later.
  1481. Instruction *NewInst = LPad->clone();
  1482. if (LPad->hasName())
  1483. NewInst->setName(LPad->getName());
  1484. // Save this correlation for later processing.
  1485. NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
  1486. VMap[LPad] = NewInst;
  1487. BasicBlock::InstListType &InstList = NewBB->getInstList();
  1488. InstList.push_back(NewInst);
  1489. InstList.push_back(new UnreachableInst(NewBB->getContext()));
  1490. return CloningDirector::StopCloningBB;
  1491. }
  1492. CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
  1493. ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
  1494. // The argument to the call is some form of the first element of the
  1495. // landingpad aggregate value, but that doesn't matter. It isn't used
  1496. // here.
  1497. // The second argument is an outparameter where the exception object will be
  1498. // stored. Typically the exception object is a scalar, but it can be an
  1499. // aggregate when catching by value.
  1500. // FIXME: Leave something behind to indicate where the exception object lives
  1501. // for this handler. Should it be part of llvm.eh.actions?
  1502. assert(ExceptionObjectVar == nullptr && "Multiple calls to "
  1503. "llvm.eh.begincatch found while "
  1504. "outlining catch handler.");
  1505. ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
  1506. if (isa<ConstantPointerNull>(ExceptionObjectVar))
  1507. return CloningDirector::SkipInstruction;
  1508. assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
  1509. "catch parameter is not static alloca");
  1510. Materializer.escapeCatchObject(ExceptionObjectVar);
  1511. return CloningDirector::SkipInstruction;
  1512. }
  1513. CloningDirector::CloningAction
  1514. WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
  1515. const Instruction *Inst, BasicBlock *NewBB) {
  1516. auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
  1517. // It might be interesting to track whether or not we are inside a catch
  1518. // function, but that might make the algorithm more brittle than it needs
  1519. // to be.
  1520. // The end catch call can occur in one of two places: either in a
  1521. // landingpad block that is part of the catch handlers exception mechanism,
  1522. // or at the end of the catch block. However, a catch-all handler may call
  1523. // end catch from the original landing pad. If the call occurs in a nested
  1524. // landing pad block, we must skip it and continue so that the landing pad
  1525. // gets cloned.
  1526. auto *ParentBB = IntrinCall->getParent();
  1527. if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
  1528. return CloningDirector::SkipInstruction;
  1529. // If an end catch occurs anywhere else we want to terminate the handler
  1530. // with a return to the code that follows the endcatch call. If the
  1531. // next instruction is not an unconditional branch, we need to split the
  1532. // block to provide a clear target for the return instruction.
  1533. BasicBlock *ContinueBB;
  1534. auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
  1535. const BranchInst *Branch = dyn_cast<BranchInst>(Next);
  1536. if (!Branch || !Branch->isUnconditional()) {
  1537. // We're interrupting the cloning process at this location, so the
  1538. // const_cast we're doing here will not cause a problem.
  1539. ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
  1540. const_cast<Instruction *>(cast<Instruction>(Next)));
  1541. } else {
  1542. ContinueBB = Branch->getSuccessor(0);
  1543. }
  1544. ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
  1545. ReturnTargets.push_back(ContinueBB);
  1546. // We just added a terminator to the cloned block.
  1547. // Tell the caller to stop processing the current basic block so that
  1548. // the branch instruction will be skipped.
  1549. return CloningDirector::StopCloningBB;
  1550. }
  1551. CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
  1552. ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
  1553. auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
  1554. Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
  1555. // This causes a replacement that will collapse the landing pad CFG based
  1556. // on the filter function we intend to match.
  1557. if (Selector == CurrentSelector)
  1558. VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
  1559. else
  1560. VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
  1561. // Tell the caller not to clone this instruction.
  1562. return CloningDirector::SkipInstruction;
  1563. }
  1564. CloningDirector::CloningAction WinEHCatchDirector::handleIndirectBr(
  1565. ValueToValueMapTy &VMap,
  1566. const IndirectBrInst *IBr,
  1567. BasicBlock *NewBB) {
  1568. // If this indirect branch is not part of a landing pad block, just clone it.
  1569. const BasicBlock *ParentBB = IBr->getParent();
  1570. if (!ParentBB->isLandingPad())
  1571. return CloningDirector::CloneInstruction;
  1572. // If it is part of a landing pad, we want to filter out target blocks
  1573. // that are not part of the handler we are outlining.
  1574. const LandingPadInst *LPad = ParentBB->getLandingPadInst();
  1575. // Save this correlation for later processing.
  1576. NestedLPtoOriginalLP[cast<LandingPadInst>(VMap[LPad])] = LPad;
  1577. // We should only get here for landing pads that have already been outlined.
  1578. assert(match(LPad->getNextNode(), m_Intrinsic<Intrinsic::eh_actions>()));
  1579. // Copy the indirectbr, but only include targets that were previously
  1580. // identified as EH blocks and are dominated by the nested landing pad.
  1581. SetVector<const BasicBlock *> ReturnTargets;
  1582. for (int I = 0, E = IBr->getNumDestinations(); I < E; ++I) {
  1583. auto *TargetBB = IBr->getDestination(I);
  1584. if (EHBlocks.count(const_cast<BasicBlock*>(TargetBB)) &&
  1585. DT->dominates(ParentBB, TargetBB)) {
  1586. DEBUG(dbgs() << " Adding destination " << TargetBB->getName() << "\n");
  1587. ReturnTargets.insert(TargetBB);
  1588. }
  1589. }
  1590. IndirectBrInst *NewBranch =
  1591. IndirectBrInst::Create(const_cast<Value *>(IBr->getAddress()),
  1592. ReturnTargets.size(), NewBB);
  1593. for (auto *Target : ReturnTargets)
  1594. NewBranch->addDestination(const_cast<BasicBlock*>(Target));
  1595. // The operands and targets of the branch instruction are remapped later
  1596. // because it is a terminator. Tell the cloning code to clone the
  1597. // blocks we just added to the target list.
  1598. return CloningDirector::CloneSuccessors;
  1599. }
  1600. CloningDirector::CloningAction
  1601. WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
  1602. const InvokeInst *Invoke, BasicBlock *NewBB) {
  1603. return CloningDirector::CloneInstruction;
  1604. }
  1605. CloningDirector::CloningAction
  1606. WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
  1607. const ResumeInst *Resume, BasicBlock *NewBB) {
  1608. // Resume instructions shouldn't be reachable from catch handlers.
  1609. // We still need to handle it, but it will be pruned.
  1610. BasicBlock::InstListType &InstList = NewBB->getInstList();
  1611. InstList.push_back(new UnreachableInst(NewBB->getContext()));
  1612. return CloningDirector::StopCloningBB;
  1613. }
  1614. CloningDirector::CloningAction
  1615. WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap,
  1616. const CmpInst *Compare, BasicBlock *NewBB) {
  1617. const IntrinsicInst *IntrinCall = nullptr;
  1618. if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
  1619. IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0));
  1620. } else if (match(Compare->getOperand(1),
  1621. m_Intrinsic<Intrinsic::eh_typeid_for>())) {
  1622. IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1));
  1623. }
  1624. if (IntrinCall) {
  1625. Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
  1626. // This causes a replacement that will collapse the landing pad CFG based
  1627. // on the filter function we intend to match.
  1628. if (Selector == CurrentSelector->stripPointerCasts()) {
  1629. VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
  1630. } else {
  1631. VMap[Compare] = ConstantInt::get(SelectorIDType, 0);
  1632. }
  1633. return CloningDirector::SkipInstruction;
  1634. }
  1635. return CloningDirector::CloneInstruction;
  1636. }
  1637. CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
  1638. ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
  1639. // The MS runtime will terminate the process if an exception occurs in a
  1640. // cleanup handler, so we shouldn't encounter landing pads in the actual
  1641. // cleanup code, but they may appear in catch blocks. Depending on where
  1642. // we started cloning we may see one, but it will get dropped during dead
  1643. // block pruning.
  1644. Instruction *NewInst = new UnreachableInst(NewBB->getContext());
  1645. VMap[LPad] = NewInst;
  1646. BasicBlock::InstListType &InstList = NewBB->getInstList();
  1647. InstList.push_back(NewInst);
  1648. return CloningDirector::StopCloningBB;
  1649. }
  1650. CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
  1651. ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
  1652. // Cleanup code may flow into catch blocks or the catch block may be part
  1653. // of a branch that will be optimized away. We'll insert a return
  1654. // instruction now, but it may be pruned before the cloning process is
  1655. // complete.
  1656. ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
  1657. return CloningDirector::StopCloningBB;
  1658. }
  1659. CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
  1660. ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
  1661. // Cleanup handlers nested within catch handlers may begin with a call to
  1662. // eh.endcatch. We can just ignore that instruction.
  1663. return CloningDirector::SkipInstruction;
  1664. }
  1665. CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
  1666. ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
  1667. // If we encounter a selector comparison while cloning a cleanup handler,
  1668. // we want to stop cloning immediately. Anything after the dispatch
  1669. // will be outlined into a different handler.
  1670. BasicBlock *CatchHandler;
  1671. Constant *Selector;
  1672. BasicBlock *NextBB;
  1673. if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
  1674. CatchHandler, Selector, NextBB)) {
  1675. ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
  1676. return CloningDirector::StopCloningBB;
  1677. }
  1678. // If eg.typeid.for is called for any other reason, it can be ignored.
  1679. VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
  1680. return CloningDirector::SkipInstruction;
  1681. }
  1682. CloningDirector::CloningAction WinEHCleanupDirector::handleIndirectBr(
  1683. ValueToValueMapTy &VMap,
  1684. const IndirectBrInst *IBr,
  1685. BasicBlock *NewBB) {
  1686. // No special handling is required for cleanup cloning.
  1687. return CloningDirector::CloneInstruction;
  1688. }
  1689. CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
  1690. ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
  1691. // All invokes in cleanup handlers can be replaced with calls.
  1692. SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
  1693. // Insert a normal call instruction...
  1694. CallInst *NewCall =
  1695. CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
  1696. Invoke->getName(), NewBB);
  1697. NewCall->setCallingConv(Invoke->getCallingConv());
  1698. NewCall->setAttributes(Invoke->getAttributes());
  1699. NewCall->setDebugLoc(Invoke->getDebugLoc());
  1700. VMap[Invoke] = NewCall;
  1701. // Remap the operands.
  1702. llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer);
  1703. // Insert an unconditional branch to the normal destination.
  1704. BranchInst::Create(Invoke->getNormalDest(), NewBB);
  1705. // The unwind destination won't be cloned into the new function, so
  1706. // we don't need to clean up its phi nodes.
  1707. // We just added a terminator to the cloned block.
  1708. // Tell the caller to stop processing the current basic block.
  1709. return CloningDirector::CloneSuccessors;
  1710. }
  1711. CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
  1712. ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
  1713. ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
  1714. // We just added a terminator to the cloned block.
  1715. // Tell the caller to stop processing the current basic block so that
  1716. // the branch instruction will be skipped.
  1717. return CloningDirector::StopCloningBB;
  1718. }
  1719. CloningDirector::CloningAction
  1720. WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap,
  1721. const CmpInst *Compare, BasicBlock *NewBB) {
  1722. if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) ||
  1723. match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
  1724. VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
  1725. return CloningDirector::SkipInstruction;
  1726. }
  1727. return CloningDirector::CloneInstruction;
  1728. }
  1729. WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
  1730. Function *OutlinedFn, Value *ParentFP, FrameVarInfoMap &FrameVarInfo)
  1731. : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
  1732. BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
  1733. // New allocas should be inserted in the entry block, but after the parent FP
  1734. // is established if it is an instruction.
  1735. Instruction *InsertPoint = EntryBB->getFirstInsertionPt();
  1736. if (auto *FPInst = dyn_cast<Instruction>(ParentFP))
  1737. InsertPoint = FPInst->getNextNode();
  1738. Builder.SetInsertPoint(EntryBB, InsertPoint);
  1739. }
  1740. Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
  1741. // If we're asked to materialize a static alloca, we temporarily create an
  1742. // alloca in the outlined function and add this to the FrameVarInfo map. When
  1743. // all the outlining is complete, we'll replace these temporary allocas with
  1744. // calls to llvm.localrecover.
  1745. if (auto *AV = dyn_cast<AllocaInst>(V)) {
  1746. assert(AV->isStaticAlloca() &&
  1747. "cannot materialize un-demoted dynamic alloca");
  1748. AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
  1749. Builder.Insert(NewAlloca, AV->getName());
  1750. FrameVarInfo[AV].push_back(NewAlloca);
  1751. return NewAlloca;
  1752. }
  1753. if (isa<Instruction>(V) || isa<Argument>(V)) {
  1754. Function *Parent = isa<Instruction>(V)
  1755. ? cast<Instruction>(V)->getParent()->getParent()
  1756. : cast<Argument>(V)->getParent();
  1757. errs()
  1758. << "Failed to demote instruction used in exception handler of function "
  1759. << GlobalValue::getRealLinkageName(Parent->getName()) << ":\n";
  1760. errs() << " " << *V << '\n';
  1761. report_fatal_error("WinEHPrepare failed to demote instruction");
  1762. }
  1763. // Don't materialize other values.
  1764. return nullptr;
  1765. }
  1766. void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
  1767. // Catch parameter objects have to live in the parent frame. When we see a use
  1768. // of a catch parameter, add a sentinel to the multimap to indicate that it's
  1769. // used from another handler. This will prevent us from trying to sink the
  1770. // alloca into the handler and ensure that the catch parameter is present in
  1771. // the call to llvm.localescape.
  1772. FrameVarInfo[V].push_back(getCatchObjectSentinel());
  1773. }
  1774. // This function maps the catch and cleanup handlers that are reachable from the
  1775. // specified landing pad. The landing pad sequence will have this basic shape:
  1776. //
  1777. // <cleanup handler>
  1778. // <selector comparison>
  1779. // <catch handler>
  1780. // <cleanup handler>
  1781. // <selector comparison>
  1782. // <catch handler>
  1783. // <cleanup handler>
  1784. // ...
  1785. //
  1786. // Any of the cleanup slots may be absent. The cleanup slots may be occupied by
  1787. // any arbitrary control flow, but all paths through the cleanup code must
  1788. // eventually reach the next selector comparison and no path can skip to a
  1789. // different selector comparisons, though some paths may terminate abnormally.
  1790. // Therefore, we will use a depth first search from the start of any given
  1791. // cleanup block and stop searching when we find the next selector comparison.
  1792. //
  1793. // If the landingpad instruction does not have a catch clause, we will assume
  1794. // that any instructions other than selector comparisons and catch handlers can
  1795. // be ignored. In practice, these will only be the boilerplate instructions.
  1796. //
  1797. // The catch handlers may also have any control structure, but we are only
  1798. // interested in the start of the catch handlers, so we don't need to actually
  1799. // follow the flow of the catch handlers. The start of the catch handlers can
  1800. // be located from the compare instructions, but they can be skipped in the
  1801. // flow by following the contrary branch.
  1802. void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
  1803. LandingPadActions &Actions) {
  1804. unsigned int NumClauses = LPad->getNumClauses();
  1805. unsigned int HandlersFound = 0;
  1806. BasicBlock *BB = LPad->getParent();
  1807. DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
  1808. if (NumClauses == 0) {
  1809. findCleanupHandlers(Actions, BB, nullptr);
  1810. return;
  1811. }
  1812. VisitedBlockSet VisitedBlocks;
  1813. while (HandlersFound != NumClauses) {
  1814. BasicBlock *NextBB = nullptr;
  1815. // Skip over filter clauses.
  1816. if (LPad->isFilter(HandlersFound)) {
  1817. ++HandlersFound;
  1818. continue;
  1819. }
  1820. // See if the clause we're looking for is a catch-all.
  1821. // If so, the catch begins immediately.
  1822. Constant *ExpectedSelector =
  1823. LPad->getClause(HandlersFound)->stripPointerCasts();
  1824. if (isa<ConstantPointerNull>(ExpectedSelector)) {
  1825. // The catch all must occur last.
  1826. assert(HandlersFound == NumClauses - 1);
  1827. // There can be additional selector dispatches in the call chain that we
  1828. // need to ignore.
  1829. BasicBlock *CatchBlock = nullptr;
  1830. Constant *Selector;
  1831. while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
  1832. DEBUG(dbgs() << " Found extra catch dispatch in block "
  1833. << CatchBlock->getName() << "\n");
  1834. BB = NextBB;
  1835. }
  1836. // Add the catch handler to the action list.
  1837. CatchHandler *Action = nullptr;
  1838. if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
  1839. // If the CatchHandlerMap already has an entry for this BB, re-use it.
  1840. Action = CatchHandlerMap[BB];
  1841. assert(Action->getSelector() == ExpectedSelector);
  1842. } else {
  1843. // We don't expect a selector dispatch, but there may be a call to
  1844. // llvm.eh.begincatch, which separates catch handling code from
  1845. // cleanup code in the same control flow. This call looks for the
  1846. // begincatch intrinsic.
  1847. Action = findCatchHandler(BB, NextBB, VisitedBlocks);
  1848. if (Action) {
  1849. // For C++ EH, check if there is any interesting cleanup code before
  1850. // we begin the catch. This is important because cleanups cannot
  1851. // rethrow exceptions but code called from catches can. For SEH, it
  1852. // isn't important if some finally code before a catch-all is executed
  1853. // out of line or after recovering from the exception.
  1854. if (Personality == EHPersonality::MSVC_CXX)
  1855. findCleanupHandlers(Actions, BB, BB);
  1856. } else {
  1857. // If an action was not found, it means that the control flows
  1858. // directly into the catch-all handler and there is no cleanup code.
  1859. // That's an expected situation and we must create a catch action.
  1860. // Since this is a catch-all handler, the selector won't actually
  1861. // appear in the code anywhere. ExpectedSelector here is the constant
  1862. // null ptr that we got from the landing pad instruction.
  1863. Action = new CatchHandler(BB, ExpectedSelector, nullptr);
  1864. CatchHandlerMap[BB] = Action;
  1865. }
  1866. }
  1867. Actions.insertCatchHandler(Action);
  1868. DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n");
  1869. ++HandlersFound;
  1870. // Once we reach a catch-all, don't expect to hit a resume instruction.
  1871. BB = nullptr;
  1872. break;
  1873. }
  1874. CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
  1875. assert(CatchAction);
  1876. // See if there is any interesting code executed before the dispatch.
  1877. findCleanupHandlers(Actions, BB, CatchAction->getStartBlock());
  1878. // When the source program contains multiple nested try blocks the catch
  1879. // handlers can get strung together in such a way that we can encounter
  1880. // a dispatch for a selector that we've already had a handler for.
  1881. if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) {
  1882. ++HandlersFound;
  1883. // Add the catch handler to the action list.
  1884. DEBUG(dbgs() << " Found catch dispatch in block "
  1885. << CatchAction->getStartBlock()->getName() << "\n");
  1886. Actions.insertCatchHandler(CatchAction);
  1887. } else {
  1888. // Under some circumstances optimized IR will flow unconditionally into a
  1889. // handler block without checking the selector. This can only happen if
  1890. // the landing pad has a catch-all handler and the handler for the
  1891. // preceeding catch clause is identical to the catch-call handler
  1892. // (typically an empty catch). In this case, the handler must be shared
  1893. // by all remaining clauses.
  1894. if (isa<ConstantPointerNull>(
  1895. CatchAction->getSelector()->stripPointerCasts())) {
  1896. DEBUG(dbgs() << " Applying early catch-all handler in block "
  1897. << CatchAction->getStartBlock()->getName()
  1898. << " to all remaining clauses.\n");
  1899. Actions.insertCatchHandler(CatchAction);
  1900. return;
  1901. }
  1902. DEBUG(dbgs() << " Found extra catch dispatch in block "
  1903. << CatchAction->getStartBlock()->getName() << "\n");
  1904. }
  1905. // Move on to the block after the catch handler.
  1906. BB = NextBB;
  1907. }
  1908. // If we didn't wind up in a catch-all, see if there is any interesting code
  1909. // executed before the resume.
  1910. findCleanupHandlers(Actions, BB, BB);
  1911. // It's possible that some optimization moved code into a landingpad that
  1912. // wasn't
  1913. // previously being used for cleanup. If that happens, we need to execute
  1914. // that
  1915. // extra code from a cleanup handler.
  1916. if (Actions.includesCleanup() && !LPad->isCleanup())
  1917. LPad->setCleanup(true);
  1918. }
  1919. // This function searches starting with the input block for the next
  1920. // block that terminates with a branch whose condition is based on a selector
  1921. // comparison. This may be the input block. See the mapLandingPadBlocks
  1922. // comments for a discussion of control flow assumptions.
  1923. //
  1924. CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
  1925. BasicBlock *&NextBB,
  1926. VisitedBlockSet &VisitedBlocks) {
  1927. // See if we've already found a catch handler use it.
  1928. // Call count() first to avoid creating a null entry for blocks
  1929. // we haven't seen before.
  1930. if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
  1931. CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
  1932. NextBB = Action->getNextBB();
  1933. return Action;
  1934. }
  1935. // VisitedBlocks applies only to the current search. We still
  1936. // need to consider blocks that we've visited while mapping other
  1937. // landing pads.
  1938. VisitedBlocks.insert(BB);
  1939. BasicBlock *CatchBlock = nullptr;
  1940. Constant *Selector = nullptr;
  1941. // If this is the first time we've visited this block from any landing pad
  1942. // look to see if it is a selector dispatch block.
  1943. if (!CatchHandlerMap.count(BB)) {
  1944. if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
  1945. CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
  1946. CatchHandlerMap[BB] = Action;
  1947. return Action;
  1948. }
  1949. // If we encounter a block containing an llvm.eh.begincatch before we
  1950. // find a selector dispatch block, the handler is assumed to be
  1951. // reached unconditionally. This happens for catch-all blocks, but
  1952. // it can also happen for other catch handlers that have been combined
  1953. // with the catch-all handler during optimization.
  1954. if (isCatchBlock(BB)) {
  1955. PointerType *Int8PtrTy = Type::getInt8PtrTy(BB->getContext());
  1956. Constant *NullSelector = ConstantPointerNull::get(Int8PtrTy);
  1957. CatchHandler *Action = new CatchHandler(BB, NullSelector, nullptr);
  1958. CatchHandlerMap[BB] = Action;
  1959. return Action;
  1960. }
  1961. }
  1962. // Visit each successor, looking for the dispatch.
  1963. // FIXME: We expect to find the dispatch quickly, so this will probably
  1964. // work better as a breadth first search.
  1965. for (BasicBlock *Succ : successors(BB)) {
  1966. if (VisitedBlocks.count(Succ))
  1967. continue;
  1968. CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
  1969. if (Action)
  1970. return Action;
  1971. }
  1972. return nullptr;
  1973. }
  1974. // These are helper functions to combine repeated code from findCleanupHandlers.
  1975. static void createCleanupHandler(LandingPadActions &Actions,
  1976. CleanupHandlerMapTy &CleanupHandlerMap,
  1977. BasicBlock *BB) {
  1978. CleanupHandler *Action = new CleanupHandler(BB);
  1979. CleanupHandlerMap[BB] = Action;
  1980. Actions.insertCleanupHandler(Action);
  1981. DEBUG(dbgs() << " Found cleanup code in block "
  1982. << Action->getStartBlock()->getName() << "\n");
  1983. }
  1984. static CallSite matchOutlinedFinallyCall(BasicBlock *BB,
  1985. Instruction *MaybeCall) {
  1986. // Look for finally blocks that Clang has already outlined for us.
  1987. // %fp = call i8* @llvm.localaddress()
  1988. // call void @"fin$parent"(iN 1, i8* %fp)
  1989. if (isLocalAddressCall(MaybeCall) && MaybeCall != BB->getTerminator())
  1990. MaybeCall = MaybeCall->getNextNode();
  1991. CallSite FinallyCall(MaybeCall);
  1992. if (!FinallyCall || FinallyCall.arg_size() != 2)
  1993. return CallSite();
  1994. if (!match(FinallyCall.getArgument(0), m_SpecificInt(1)))
  1995. return CallSite();
  1996. if (!isLocalAddressCall(FinallyCall.getArgument(1)))
  1997. return CallSite();
  1998. return FinallyCall;
  1999. }
  2000. static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) {
  2001. // Skip single ubr blocks.
  2002. while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) {
  2003. auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
  2004. if (Br && Br->isUnconditional())
  2005. BB = Br->getSuccessor(0);
  2006. else
  2007. return BB;
  2008. }
  2009. return BB;
  2010. }
  2011. // This function searches starting with the input block for the next block that
  2012. // contains code that is not part of a catch handler and would not be eliminated
  2013. // during handler outlining.
  2014. //
  2015. void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions,
  2016. BasicBlock *StartBB, BasicBlock *EndBB) {
  2017. // Here we will skip over the following:
  2018. //
  2019. // landing pad prolog:
  2020. //
  2021. // Unconditional branches
  2022. //
  2023. // Selector dispatch
  2024. //
  2025. // Resume pattern
  2026. //
  2027. // Anything else marks the start of an interesting block
  2028. BasicBlock *BB = StartBB;
  2029. // Anything other than an unconditional branch will kick us out of this loop
  2030. // one way or another.
  2031. while (BB) {
  2032. BB = followSingleUnconditionalBranches(BB);
  2033. // If we've already scanned this block, don't scan it again. If it is
  2034. // a cleanup block, there will be an action in the CleanupHandlerMap.
  2035. // If we've scanned it and it is not a cleanup block, there will be a
  2036. // nullptr in the CleanupHandlerMap. If we have not scanned it, there will
  2037. // be no entry in the CleanupHandlerMap. We must call count() first to
  2038. // avoid creating a null entry for blocks we haven't scanned.
  2039. if (CleanupHandlerMap.count(BB)) {
  2040. if (auto *Action = CleanupHandlerMap[BB]) {
  2041. Actions.insertCleanupHandler(Action);
  2042. DEBUG(dbgs() << " Found cleanup code in block "
  2043. << Action->getStartBlock()->getName() << "\n");
  2044. // FIXME: This cleanup might chain into another, and we need to discover
  2045. // that.
  2046. return;
  2047. } else {
  2048. // Here we handle the case where the cleanup handler map contains a
  2049. // value for this block but the value is a nullptr. This means that
  2050. // we have previously analyzed the block and determined that it did
  2051. // not contain any cleanup code. Based on the earlier analysis, we
  2052. // know the block must end in either an unconditional branch, a
  2053. // resume or a conditional branch that is predicated on a comparison
  2054. // with a selector. Either the resume or the selector dispatch
  2055. // would terminate the search for cleanup code, so the unconditional
  2056. // branch is the only case for which we might need to continue
  2057. // searching.
  2058. BasicBlock *SuccBB = followSingleUnconditionalBranches(BB);
  2059. if (SuccBB == BB || SuccBB == EndBB)
  2060. return;
  2061. BB = SuccBB;
  2062. continue;
  2063. }
  2064. }
  2065. // Create an entry in the cleanup handler map for this block. Initially
  2066. // we create an entry that says this isn't a cleanup block. If we find
  2067. // cleanup code, the caller will replace this entry.
  2068. CleanupHandlerMap[BB] = nullptr;
  2069. TerminatorInst *Terminator = BB->getTerminator();
  2070. // Landing pad blocks have extra instructions we need to accept.
  2071. LandingPadMap *LPadMap = nullptr;
  2072. if (BB->isLandingPad()) {
  2073. LandingPadInst *LPad = BB->getLandingPadInst();
  2074. LPadMap = &LPadMaps[LPad];
  2075. if (!LPadMap->isInitialized())
  2076. LPadMap->mapLandingPad(LPad);
  2077. }
  2078. // Look for the bare resume pattern:
  2079. // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
  2080. // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
  2081. // resume { i8*, i32 } %lpad.val2
  2082. if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
  2083. InsertValueInst *Insert1 = nullptr;
  2084. InsertValueInst *Insert2 = nullptr;
  2085. Value *ResumeVal = Resume->getOperand(0);
  2086. // If the resume value isn't a phi or landingpad value, it should be a
  2087. // series of insertions. Identify them so we can avoid them when scanning
  2088. // for cleanups.
  2089. if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) {
  2090. Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
  2091. if (!Insert2)
  2092. return createCleanupHandler(Actions, CleanupHandlerMap, BB);
  2093. Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
  2094. if (!Insert1)
  2095. return createCleanupHandler(Actions, CleanupHandlerMap, BB);
  2096. }
  2097. for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
  2098. II != IE; ++II) {
  2099. Instruction *Inst = II;
  2100. if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
  2101. continue;
  2102. if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
  2103. continue;
  2104. if (!Inst->hasOneUse() ||
  2105. (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
  2106. return createCleanupHandler(Actions, CleanupHandlerMap, BB);
  2107. }
  2108. }
  2109. return;
  2110. }
  2111. BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
  2112. if (Branch && Branch->isConditional()) {
  2113. // Look for the selector dispatch.
  2114. // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
  2115. // %matches = icmp eq i32 %sel, %2
  2116. // br i1 %matches, label %catch14, label %eh.resume
  2117. CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
  2118. if (!Compare || !Compare->isEquality())
  2119. return createCleanupHandler(Actions, CleanupHandlerMap, BB);
  2120. for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
  2121. II != IE; ++II) {
  2122. Instruction *Inst = II;
  2123. if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
  2124. continue;
  2125. if (Inst == Compare || Inst == Branch)
  2126. continue;
  2127. if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
  2128. continue;
  2129. return createCleanupHandler(Actions, CleanupHandlerMap, BB);
  2130. }
  2131. // The selector dispatch block should always terminate our search.
  2132. assert(BB == EndBB);
  2133. return;
  2134. }
  2135. if (isAsynchronousEHPersonality(Personality)) {
  2136. // If this is a landingpad block, split the block at the first non-landing
  2137. // pad instruction.
  2138. Instruction *MaybeCall = BB->getFirstNonPHIOrDbg();
  2139. if (LPadMap) {
  2140. while (MaybeCall != BB->getTerminator() &&
  2141. LPadMap->isLandingPadSpecificInst(MaybeCall))
  2142. MaybeCall = MaybeCall->getNextNode();
  2143. }
  2144. // Look for outlined finally calls on x64, since those happen to match the
  2145. // prototype provided by the runtime.
  2146. if (TheTriple.getArch() == Triple::x86_64) {
  2147. if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) {
  2148. Function *Fin = FinallyCall.getCalledFunction();
  2149. assert(Fin && "outlined finally call should be direct");
  2150. auto *Action = new CleanupHandler(BB);
  2151. Action->setHandlerBlockOrFunc(Fin);
  2152. Actions.insertCleanupHandler(Action);
  2153. CleanupHandlerMap[BB] = Action;
  2154. DEBUG(dbgs() << " Found frontend-outlined finally call to "
  2155. << Fin->getName() << " in block "
  2156. << Action->getStartBlock()->getName() << "\n");
  2157. // Split the block if there were more interesting instructions and
  2158. // look for finally calls in the normal successor block.
  2159. BasicBlock *SuccBB = BB;
  2160. if (FinallyCall.getInstruction() != BB->getTerminator() &&
  2161. FinallyCall.getInstruction()->getNextNode() !=
  2162. BB->getTerminator()) {
  2163. SuccBB =
  2164. SplitBlock(BB, FinallyCall.getInstruction()->getNextNode(), DT);
  2165. } else {
  2166. if (FinallyCall.isInvoke()) {
  2167. SuccBB = cast<InvokeInst>(FinallyCall.getInstruction())
  2168. ->getNormalDest();
  2169. } else {
  2170. SuccBB = BB->getUniqueSuccessor();
  2171. assert(SuccBB &&
  2172. "splitOutlinedFinallyCalls didn't insert a branch");
  2173. }
  2174. }
  2175. BB = SuccBB;
  2176. if (BB == EndBB)
  2177. return;
  2178. continue;
  2179. }
  2180. }
  2181. }
  2182. // Anything else is either a catch block or interesting cleanup code.
  2183. for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
  2184. II != IE; ++II) {
  2185. Instruction *Inst = II;
  2186. if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
  2187. continue;
  2188. // Unconditional branches fall through to this loop.
  2189. if (Inst == Branch)
  2190. continue;
  2191. // If this is a catch block, there is no cleanup code to be found.
  2192. if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
  2193. return;
  2194. // If this a nested landing pad, it may contain an endcatch call.
  2195. if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
  2196. return;
  2197. // Anything else makes this interesting cleanup code.
  2198. return createCleanupHandler(Actions, CleanupHandlerMap, BB);
  2199. }
  2200. // Only unconditional branches in empty blocks should get this far.
  2201. assert(Branch && Branch->isUnconditional());
  2202. if (BB == EndBB)
  2203. return;
  2204. BB = Branch->getSuccessor(0);
  2205. }
  2206. }
  2207. // This is a public function, declared in WinEHFuncInfo.h and is also
  2208. // referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
  2209. void llvm::parseEHActions(
  2210. const IntrinsicInst *II,
  2211. SmallVectorImpl<std::unique_ptr<ActionHandler>> &Actions) {
  2212. assert(II->getIntrinsicID() == Intrinsic::eh_actions &&
  2213. "attempted to parse non eh.actions intrinsic");
  2214. for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
  2215. uint64_t ActionKind =
  2216. cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
  2217. if (ActionKind == /*catch=*/1) {
  2218. auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
  2219. ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
  2220. int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
  2221. Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
  2222. I += 4;
  2223. auto CH = make_unique<CatchHandler>(/*BB=*/nullptr, Selector,
  2224. /*NextBB=*/nullptr);
  2225. CH->setHandlerBlockOrFunc(Handler);
  2226. CH->setExceptionVarIndex(EHObjIndexVal);
  2227. Actions.push_back(std::move(CH));
  2228. } else if (ActionKind == 0) {
  2229. Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
  2230. I += 2;
  2231. auto CH = make_unique<CleanupHandler>(/*BB=*/nullptr);
  2232. CH->setHandlerBlockOrFunc(Handler);
  2233. Actions.push_back(std::move(CH));
  2234. } else {
  2235. llvm_unreachable("Expected either a catch or cleanup handler!");
  2236. }
  2237. }
  2238. std::reverse(Actions.begin(), Actions.end());
  2239. }
  2240. namespace {
  2241. struct WinEHNumbering {
  2242. WinEHNumbering(WinEHFuncInfo &FuncInfo) : FuncInfo(FuncInfo),
  2243. CurrentBaseState(-1), NextState(0) {}
  2244. WinEHFuncInfo &FuncInfo;
  2245. int CurrentBaseState;
  2246. int NextState;
  2247. SmallVector<std::unique_ptr<ActionHandler>, 4> HandlerStack;
  2248. SmallPtrSet<const Function *, 4> VisitedHandlers;
  2249. int currentEHNumber() const {
  2250. return HandlerStack.empty() ? CurrentBaseState : HandlerStack.back()->getEHState();
  2251. }
  2252. void createUnwindMapEntry(int ToState, ActionHandler *AH);
  2253. void createTryBlockMapEntry(int TryLow, int TryHigh,
  2254. ArrayRef<CatchHandler *> Handlers);
  2255. void processCallSite(MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
  2256. ImmutableCallSite CS);
  2257. void popUnmatchedActions(int FirstMismatch);
  2258. void calculateStateNumbers(const Function &F);
  2259. void findActionRootLPads(const Function &F);
  2260. };
  2261. }
  2262. void WinEHNumbering::createUnwindMapEntry(int ToState, ActionHandler *AH) {
  2263. WinEHUnwindMapEntry UME;
  2264. UME.ToState = ToState;
  2265. if (auto *CH = dyn_cast_or_null<CleanupHandler>(AH))
  2266. UME.Cleanup = cast<Function>(CH->getHandlerBlockOrFunc());
  2267. else
  2268. UME.Cleanup = nullptr;
  2269. FuncInfo.UnwindMap.push_back(UME);
  2270. }
  2271. void WinEHNumbering::createTryBlockMapEntry(int TryLow, int TryHigh,
  2272. ArrayRef<CatchHandler *> Handlers) {
  2273. // See if we already have an entry for this set of handlers.
  2274. // This is using iterators rather than a range-based for loop because
  2275. // if we find the entry we're looking for we'll need the iterator to erase it.
  2276. int NumHandlers = Handlers.size();
  2277. auto I = FuncInfo.TryBlockMap.begin();
  2278. auto E = FuncInfo.TryBlockMap.end();
  2279. for ( ; I != E; ++I) {
  2280. auto &Entry = *I;
  2281. if (Entry.HandlerArray.size() != (size_t)NumHandlers)
  2282. continue;
  2283. int N;
  2284. for (N = 0; N < NumHandlers; ++N) {
  2285. if (Entry.HandlerArray[N].Handler != Handlers[N]->getHandlerBlockOrFunc())
  2286. break; // breaks out of inner loop
  2287. }
  2288. // If all the handlers match, this is what we were looking for.
  2289. if (N == NumHandlers) {
  2290. break;
  2291. }
  2292. }
  2293. // If we found an existing entry for this set of handlers, extend the range
  2294. // but move the entry to the end of the map vector. The order of entries
  2295. // in the map is critical to the way that the runtime finds handlers.
  2296. // FIXME: Depending on what has happened with block ordering, this may
  2297. // incorrectly combine entries that should remain separate.
  2298. if (I != E) {
  2299. // Copy the existing entry.
  2300. WinEHTryBlockMapEntry Entry = *I;
  2301. Entry.TryLow = std::min(TryLow, Entry.TryLow);
  2302. Entry.TryHigh = std::max(TryHigh, Entry.TryHigh);
  2303. assert(Entry.TryLow <= Entry.TryHigh);
  2304. // Erase the old entry and add this one to the back.
  2305. FuncInfo.TryBlockMap.erase(I);
  2306. FuncInfo.TryBlockMap.push_back(Entry);
  2307. return;
  2308. }
  2309. // If we didn't find an entry, create a new one.
  2310. WinEHTryBlockMapEntry TBME;
  2311. TBME.TryLow = TryLow;
  2312. TBME.TryHigh = TryHigh;
  2313. assert(TBME.TryLow <= TBME.TryHigh);
  2314. for (CatchHandler *CH : Handlers) {
  2315. WinEHHandlerType HT;
  2316. if (CH->getSelector()->isNullValue()) {
  2317. HT.Adjectives = 0x40;
  2318. HT.TypeDescriptor = nullptr;
  2319. } else {
  2320. auto *GV = cast<GlobalVariable>(CH->getSelector()->stripPointerCasts());
  2321. // Selectors are always pointers to GlobalVariables with 'struct' type.
  2322. // The struct has two fields, adjectives and a type descriptor.
  2323. auto *CS = cast<ConstantStruct>(GV->getInitializer());
  2324. HT.Adjectives =
  2325. cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue();
  2326. HT.TypeDescriptor =
  2327. cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts());
  2328. }
  2329. HT.Handler = cast<Function>(CH->getHandlerBlockOrFunc());
  2330. HT.CatchObjRecoverIdx = CH->getExceptionVarIndex();
  2331. TBME.HandlerArray.push_back(HT);
  2332. }
  2333. FuncInfo.TryBlockMap.push_back(TBME);
  2334. }
  2335. static void print_name(const Value *V) {
  2336. #ifndef NDEBUG
  2337. if (!V) {
  2338. DEBUG(dbgs() << "null");
  2339. return;
  2340. }
  2341. if (const auto *F = dyn_cast<Function>(V))
  2342. DEBUG(dbgs() << F->getName());
  2343. else
  2344. DEBUG(V->dump());
  2345. #endif
  2346. }
  2347. void WinEHNumbering::processCallSite(
  2348. MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
  2349. ImmutableCallSite CS) {
  2350. DEBUG(dbgs() << "processCallSite (EH state = " << currentEHNumber()
  2351. << ") for: ");
  2352. print_name(CS ? CS.getCalledValue() : nullptr);
  2353. DEBUG(dbgs() << '\n');
  2354. DEBUG(dbgs() << "HandlerStack: \n");
  2355. for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
  2356. DEBUG(dbgs() << " ");
  2357. print_name(HandlerStack[I]->getHandlerBlockOrFunc());
  2358. DEBUG(dbgs() << '\n');
  2359. }
  2360. DEBUG(dbgs() << "Actions: \n");
  2361. for (int I = 0, E = Actions.size(); I < E; ++I) {
  2362. DEBUG(dbgs() << " ");
  2363. print_name(Actions[I]->getHandlerBlockOrFunc());
  2364. DEBUG(dbgs() << '\n');
  2365. }
  2366. int FirstMismatch = 0;
  2367. for (int E = std::min(HandlerStack.size(), Actions.size()); FirstMismatch < E;
  2368. ++FirstMismatch) {
  2369. if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() !=
  2370. Actions[FirstMismatch]->getHandlerBlockOrFunc())
  2371. break;
  2372. }
  2373. // Remove unmatched actions from the stack and process their EH states.
  2374. popUnmatchedActions(FirstMismatch);
  2375. DEBUG(dbgs() << "Pushing actions for CallSite: ");
  2376. print_name(CS ? CS.getCalledValue() : nullptr);
  2377. DEBUG(dbgs() << '\n');
  2378. bool LastActionWasCatch = false;
  2379. const LandingPadInst *LastRootLPad = nullptr;
  2380. for (size_t I = FirstMismatch; I != Actions.size(); ++I) {
  2381. // We can reuse eh states when pushing two catches for the same invoke.
  2382. bool CurrActionIsCatch = isa<CatchHandler>(Actions[I].get());
  2383. auto *Handler = cast<Function>(Actions[I]->getHandlerBlockOrFunc());
  2384. // Various conditions can lead to a handler being popped from the
  2385. // stack and re-pushed later. That shouldn't create a new state.
  2386. // FIXME: Can code optimization lead to re-used handlers?
  2387. if (FuncInfo.HandlerEnclosedState.count(Handler)) {
  2388. // If we already assigned the state enclosed by this handler re-use it.
  2389. Actions[I]->setEHState(FuncInfo.HandlerEnclosedState[Handler]);
  2390. continue;
  2391. }
  2392. const LandingPadInst* RootLPad = FuncInfo.RootLPad[Handler];
  2393. if (CurrActionIsCatch && LastActionWasCatch && RootLPad == LastRootLPad) {
  2394. DEBUG(dbgs() << "setEHState for handler to " << currentEHNumber() << "\n");
  2395. Actions[I]->setEHState(currentEHNumber());
  2396. } else {
  2397. DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber() << ", ");
  2398. print_name(Actions[I]->getHandlerBlockOrFunc());
  2399. DEBUG(dbgs() << ") with EH state " << NextState << "\n");
  2400. createUnwindMapEntry(currentEHNumber(), Actions[I].get());
  2401. DEBUG(dbgs() << "setEHState for handler to " << NextState << "\n");
  2402. Actions[I]->setEHState(NextState);
  2403. NextState++;
  2404. }
  2405. HandlerStack.push_back(std::move(Actions[I]));
  2406. LastActionWasCatch = CurrActionIsCatch;
  2407. LastRootLPad = RootLPad;
  2408. }
  2409. // This is used to defer numbering states for a handler until after the
  2410. // last time it appears in an invoke action list.
  2411. if (CS.isInvoke()) {
  2412. for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
  2413. auto *Handler = cast<Function>(HandlerStack[I]->getHandlerBlockOrFunc());
  2414. if (FuncInfo.LastInvoke[Handler] != cast<InvokeInst>(CS.getInstruction()))
  2415. continue;
  2416. FuncInfo.LastInvokeVisited[Handler] = true;
  2417. DEBUG(dbgs() << "Last invoke of ");
  2418. print_name(Handler);
  2419. DEBUG(dbgs() << " has been visited.\n");
  2420. }
  2421. }
  2422. DEBUG(dbgs() << "In EHState " << currentEHNumber() << " for CallSite: ");
  2423. print_name(CS ? CS.getCalledValue() : nullptr);
  2424. DEBUG(dbgs() << '\n');
  2425. }
  2426. void WinEHNumbering::popUnmatchedActions(int FirstMismatch) {
  2427. // Don't recurse while we are looping over the handler stack. Instead, defer
  2428. // the numbering of the catch handlers until we are done popping.
  2429. SmallVector<CatchHandler *, 4> PoppedCatches;
  2430. for (int I = HandlerStack.size() - 1; I >= FirstMismatch; --I) {
  2431. std::unique_ptr<ActionHandler> Handler = HandlerStack.pop_back_val();
  2432. if (isa<CatchHandler>(Handler.get()))
  2433. PoppedCatches.push_back(cast<CatchHandler>(Handler.release()));
  2434. }
  2435. int TryHigh = NextState - 1;
  2436. int LastTryLowIdx = 0;
  2437. for (int I = 0, E = PoppedCatches.size(); I != E; ++I) {
  2438. CatchHandler *CH = PoppedCatches[I];
  2439. DEBUG(dbgs() << "Popped handler with state " << CH->getEHState() << "\n");
  2440. if (I + 1 == E || CH->getEHState() != PoppedCatches[I + 1]->getEHState()) {
  2441. int TryLow = CH->getEHState();
  2442. auto Handlers =
  2443. makeArrayRef(&PoppedCatches[LastTryLowIdx], I - LastTryLowIdx + 1);
  2444. DEBUG(dbgs() << "createTryBlockMapEntry(" << TryLow << ", " << TryHigh);
  2445. for (size_t J = 0; J < Handlers.size(); ++J) {
  2446. DEBUG(dbgs() << ", ");
  2447. print_name(Handlers[J]->getHandlerBlockOrFunc());
  2448. }
  2449. DEBUG(dbgs() << ")\n");
  2450. createTryBlockMapEntry(TryLow, TryHigh, Handlers);
  2451. LastTryLowIdx = I + 1;
  2452. }
  2453. }
  2454. for (CatchHandler *CH : PoppedCatches) {
  2455. if (auto *F = dyn_cast<Function>(CH->getHandlerBlockOrFunc())) {
  2456. if (FuncInfo.LastInvokeVisited[F]) {
  2457. DEBUG(dbgs() << "Assigning base state " << NextState << " to ");
  2458. print_name(F);
  2459. DEBUG(dbgs() << '\n');
  2460. FuncInfo.HandlerBaseState[F] = NextState;
  2461. DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber()
  2462. << ", null)\n");
  2463. createUnwindMapEntry(currentEHNumber(), nullptr);
  2464. ++NextState;
  2465. calculateStateNumbers(*F);
  2466. }
  2467. else {
  2468. DEBUG(dbgs() << "Deferring handling of ");
  2469. print_name(F);
  2470. DEBUG(dbgs() << " until last invoke visited.\n");
  2471. }
  2472. }
  2473. delete CH;
  2474. }
  2475. }
  2476. void WinEHNumbering::calculateStateNumbers(const Function &F) {
  2477. auto I = VisitedHandlers.insert(&F);
  2478. if (!I.second)
  2479. return; // We've already visited this handler, don't renumber it.
  2480. int OldBaseState = CurrentBaseState;
  2481. if (FuncInfo.HandlerBaseState.count(&F)) {
  2482. CurrentBaseState = FuncInfo.HandlerBaseState[&F];
  2483. }
  2484. size_t SavedHandlerStackSize = HandlerStack.size();
  2485. DEBUG(dbgs() << "Calculating state numbers for: " << F.getName() << '\n');
  2486. SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
  2487. for (const BasicBlock &BB : F) {
  2488. for (const Instruction &I : BB) {
  2489. const auto *CI = dyn_cast<CallInst>(&I);
  2490. if (!CI || CI->doesNotThrow())
  2491. continue;
  2492. processCallSite(None, CI);
  2493. }
  2494. const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
  2495. if (!II)
  2496. continue;
  2497. const LandingPadInst *LPI = II->getLandingPadInst();
  2498. auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
  2499. if (!ActionsCall)
  2500. continue;
  2501. parseEHActions(ActionsCall, ActionList);
  2502. if (ActionList.empty())
  2503. continue;
  2504. processCallSite(ActionList, II);
  2505. ActionList.clear();
  2506. FuncInfo.LandingPadStateMap[LPI] = currentEHNumber();
  2507. DEBUG(dbgs() << "Assigning state " << currentEHNumber()
  2508. << " to landing pad at " << LPI->getParent()->getName()
  2509. << '\n');
  2510. }
  2511. // Pop any actions that were pushed on the stack for this function.
  2512. popUnmatchedActions(SavedHandlerStackSize);
  2513. DEBUG(dbgs() << "Assigning max state " << NextState - 1
  2514. << " to " << F.getName() << '\n');
  2515. FuncInfo.CatchHandlerMaxState[&F] = NextState - 1;
  2516. CurrentBaseState = OldBaseState;
  2517. }
  2518. // This function follows the same basic traversal as calculateStateNumbers
  2519. // but it is necessary to identify the root landing pad associated
  2520. // with each action before we start assigning state numbers.
  2521. void WinEHNumbering::findActionRootLPads(const Function &F) {
  2522. auto I = VisitedHandlers.insert(&F);
  2523. if (!I.second)
  2524. return; // We've already visited this handler, don't revisit it.
  2525. SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
  2526. for (const BasicBlock &BB : F) {
  2527. const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
  2528. if (!II)
  2529. continue;
  2530. const LandingPadInst *LPI = II->getLandingPadInst();
  2531. auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
  2532. if (!ActionsCall)
  2533. continue;
  2534. assert(ActionsCall->getIntrinsicID() == Intrinsic::eh_actions);
  2535. parseEHActions(ActionsCall, ActionList);
  2536. if (ActionList.empty())
  2537. continue;
  2538. for (int I = 0, E = ActionList.size(); I < E; ++I) {
  2539. if (auto *Handler
  2540. = dyn_cast<Function>(ActionList[I]->getHandlerBlockOrFunc())) {
  2541. FuncInfo.LastInvoke[Handler] = II;
  2542. // Don't replace the root landing pad if we previously saw this
  2543. // handler in a different function.
  2544. if (FuncInfo.RootLPad.count(Handler) &&
  2545. FuncInfo.RootLPad[Handler]->getParent()->getParent() != &F)
  2546. continue;
  2547. DEBUG(dbgs() << "Setting root lpad for ");
  2548. print_name(Handler);
  2549. DEBUG(dbgs() << " to " << LPI->getParent()->getName() << '\n');
  2550. FuncInfo.RootLPad[Handler] = LPI;
  2551. }
  2552. }
  2553. // Walk the actions again and look for nested handlers. This has to
  2554. // happen after all of the actions have been processed in the current
  2555. // function.
  2556. for (int I = 0, E = ActionList.size(); I < E; ++I)
  2557. if (auto *Handler
  2558. = dyn_cast<Function>(ActionList[I]->getHandlerBlockOrFunc()))
  2559. findActionRootLPads(*Handler);
  2560. ActionList.clear();
  2561. }
  2562. }
  2563. void llvm::calculateWinCXXEHStateNumbers(const Function *ParentFn,
  2564. WinEHFuncInfo &FuncInfo) {
  2565. // Return if it's already been done.
  2566. if (!FuncInfo.LandingPadStateMap.empty())
  2567. return;
  2568. WinEHNumbering Num(FuncInfo);
  2569. Num.findActionRootLPads(*ParentFn);
  2570. // The VisitedHandlers list is used by both findActionRootLPads and
  2571. // calculateStateNumbers, but both functions need to visit all handlers.
  2572. Num.VisitedHandlers.clear();
  2573. Num.calculateStateNumbers(*ParentFn);
  2574. // Pop everything on the handler stack.
  2575. // It may be necessary to call this more than once because a handler can
  2576. // be pushed on the stack as a result of clearing the stack.
  2577. while (!Num.HandlerStack.empty())
  2578. Num.processCallSite(None, ImmutableCallSite());
  2579. }