WinException.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317
  1. //===-- CodeGen/AsmPrinter/WinException.cpp - Dwarf Exception Impl ------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains support for writing Win64 exception info into asm files.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "WinException.h"
  13. #include "llvm/ADT/Twine.h"
  14. #include "llvm/BinaryFormat/COFF.h"
  15. #include "llvm/BinaryFormat/Dwarf.h"
  16. #include "llvm/CodeGen/AsmPrinter.h"
  17. #include "llvm/CodeGen/MachineFrameInfo.h"
  18. #include "llvm/CodeGen/MachineFunction.h"
  19. #include "llvm/CodeGen/MachineModuleInfo.h"
  20. #include "llvm/CodeGen/TargetFrameLowering.h"
  21. #include "llvm/CodeGen/TargetLowering.h"
  22. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  23. #include "llvm/CodeGen/WinEHFuncInfo.h"
  24. #include "llvm/IR/DataLayout.h"
  25. #include "llvm/IR/Mangler.h"
  26. #include "llvm/IR/Module.h"
  27. #include "llvm/MC/MCAsmInfo.h"
  28. #include "llvm/MC/MCContext.h"
  29. #include "llvm/MC/MCExpr.h"
  30. #include "llvm/MC/MCSection.h"
  31. #include "llvm/MC/MCStreamer.h"
  32. #include "llvm/MC/MCSymbol.h"
  33. #include "llvm/Support/ErrorHandling.h"
  34. #include "llvm/Support/FormattedStream.h"
  35. #include "llvm/Target/TargetLoweringObjectFile.h"
  36. #include "llvm/Target/TargetOptions.h"
  37. using namespace llvm;
  38. WinException::WinException(AsmPrinter *A) : EHStreamer(A) {
  39. // MSVC's EH tables are always composed of 32-bit words. All known 64-bit
  40. // platforms use an imagerel32 relocation to refer to symbols.
  41. useImageRel32 = (A->getDataLayout().getPointerSizeInBits() == 64);
  42. isAArch64 = Asm->TM.getTargetTriple().isAArch64();
  43. }
  44. WinException::~WinException() {}
  45. /// endModule - Emit all exception information that should come after the
  46. /// content.
  47. void WinException::endModule() {
  48. auto &OS = *Asm->OutStreamer;
  49. const Module *M = MMI->getModule();
  50. for (const Function &F : *M)
  51. if (F.hasFnAttribute("safeseh"))
  52. OS.EmitCOFFSafeSEH(Asm->getSymbol(&F));
  53. }
  54. void WinException::beginFunction(const MachineFunction *MF) {
  55. shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
  56. // If any landing pads survive, we need an EH table.
  57. bool hasLandingPads = !MF->getLandingPads().empty();
  58. bool hasEHFunclets = MF->hasEHFunclets();
  59. const Function &F = MF->getFunction();
  60. shouldEmitMoves = Asm->needsSEHMoves() && MF->hasWinCFI();
  61. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  62. unsigned PerEncoding = TLOF.getPersonalityEncoding();
  63. EHPersonality Per = EHPersonality::Unknown;
  64. const Function *PerFn = nullptr;
  65. if (F.hasPersonalityFn()) {
  66. PerFn = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
  67. Per = classifyEHPersonality(PerFn);
  68. }
  69. bool forceEmitPersonality = F.hasPersonalityFn() &&
  70. !isNoOpWithoutInvoke(Per) &&
  71. F.needsUnwindTableEntry();
  72. shouldEmitPersonality =
  73. forceEmitPersonality || ((hasLandingPads || hasEHFunclets) &&
  74. PerEncoding != dwarf::DW_EH_PE_omit && PerFn);
  75. unsigned LSDAEncoding = TLOF.getLSDAEncoding();
  76. shouldEmitLSDA = shouldEmitPersonality &&
  77. LSDAEncoding != dwarf::DW_EH_PE_omit;
  78. // If we're not using CFI, we don't want the CFI or the personality, but we
  79. // might want EH tables if we had EH pads.
  80. if (!Asm->MAI->usesWindowsCFI()) {
  81. if (Per == EHPersonality::MSVC_X86SEH && !hasEHFunclets) {
  82. // If this is 32-bit SEH and we don't have any funclets (really invokes),
  83. // make sure we emit the parent offset label. Some unreferenced filter
  84. // functions may still refer to it.
  85. const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
  86. StringRef FLinkageName =
  87. GlobalValue::dropLLVMManglingEscape(MF->getFunction().getName());
  88. emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
  89. }
  90. shouldEmitLSDA = hasEHFunclets;
  91. shouldEmitPersonality = false;
  92. return;
  93. }
  94. beginFunclet(MF->front(), Asm->CurrentFnSym);
  95. }
  96. void WinException::markFunctionEnd() {
  97. if (isAArch64 && CurrentFuncletEntry &&
  98. (shouldEmitMoves || shouldEmitPersonality))
  99. Asm->OutStreamer->EmitWinCFIFuncletOrFuncEnd();
  100. }
  101. /// endFunction - Gather and emit post-function exception information.
  102. ///
  103. void WinException::endFunction(const MachineFunction *MF) {
  104. if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
  105. return;
  106. const Function &F = MF->getFunction();
  107. EHPersonality Per = EHPersonality::Unknown;
  108. if (F.hasPersonalityFn())
  109. Per = classifyEHPersonality(F.getPersonalityFn()->stripPointerCasts());
  110. // Get rid of any dead landing pads if we're not using funclets. In funclet
  111. // schemes, the landing pad is not actually reachable. It only exists so
  112. // that we can emit the right table data.
  113. if (!isFuncletEHPersonality(Per)) {
  114. MachineFunction *NonConstMF = const_cast<MachineFunction*>(MF);
  115. NonConstMF->tidyLandingPads();
  116. }
  117. endFuncletImpl();
  118. // endFunclet will emit the necessary .xdata tables for x64 SEH.
  119. if (Per == EHPersonality::MSVC_Win64SEH && MF->hasEHFunclets())
  120. return;
  121. if (shouldEmitPersonality || shouldEmitLSDA) {
  122. Asm->OutStreamer->PushSection();
  123. // Just switch sections to the right xdata section.
  124. MCSection *XData = Asm->OutStreamer->getAssociatedXDataSection(
  125. Asm->OutStreamer->getCurrentSectionOnly());
  126. Asm->OutStreamer->SwitchSection(XData);
  127. // Emit the tables appropriate to the personality function in use. If we
  128. // don't recognize the personality, assume it uses an Itanium-style LSDA.
  129. if (Per == EHPersonality::MSVC_Win64SEH)
  130. emitCSpecificHandlerTable(MF);
  131. else if (Per == EHPersonality::MSVC_X86SEH)
  132. emitExceptHandlerTable(MF);
  133. else if (Per == EHPersonality::MSVC_CXX)
  134. emitCXXFrameHandler3Table(MF);
  135. else if (Per == EHPersonality::CoreCLR)
  136. emitCLRExceptionTable(MF);
  137. else
  138. emitExceptionTable();
  139. Asm->OutStreamer->PopSection();
  140. }
  141. }
  142. /// Retrieve the MCSymbol for a GlobalValue or MachineBasicBlock.
  143. static MCSymbol *getMCSymbolForMBB(AsmPrinter *Asm,
  144. const MachineBasicBlock *MBB) {
  145. if (!MBB)
  146. return nullptr;
  147. assert(MBB->isEHFuncletEntry());
  148. // Give catches and cleanups a name based off of their parent function and
  149. // their funclet entry block's number.
  150. const MachineFunction *MF = MBB->getParent();
  151. const Function &F = MF->getFunction();
  152. StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
  153. MCContext &Ctx = MF->getContext();
  154. StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch";
  155. return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" +
  156. Twine(MBB->getNumber()) + "@?0?" +
  157. FuncLinkageName + "@4HA");
  158. }
  159. void WinException::beginFunclet(const MachineBasicBlock &MBB,
  160. MCSymbol *Sym) {
  161. CurrentFuncletEntry = &MBB;
  162. const Function &F = Asm->MF->getFunction();
  163. // If a symbol was not provided for the funclet, invent one.
  164. if (!Sym) {
  165. Sym = getMCSymbolForMBB(Asm, &MBB);
  166. // Describe our funclet symbol as a function with internal linkage.
  167. Asm->OutStreamer->BeginCOFFSymbolDef(Sym);
  168. Asm->OutStreamer->EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
  169. Asm->OutStreamer->EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
  170. << COFF::SCT_COMPLEX_TYPE_SHIFT);
  171. Asm->OutStreamer->EndCOFFSymbolDef();
  172. // We want our funclet's entry point to be aligned such that no nops will be
  173. // present after the label.
  174. Asm->EmitAlignment(
  175. std::max(Asm->MF->getLogAlignment(), MBB.getLogAlignment()), &F);
  176. // Now that we've emitted the alignment directive, point at our funclet.
  177. Asm->OutStreamer->EmitLabel(Sym);
  178. }
  179. // Mark 'Sym' as starting our funclet.
  180. if (shouldEmitMoves || shouldEmitPersonality) {
  181. CurrentFuncletTextSection = Asm->OutStreamer->getCurrentSectionOnly();
  182. Asm->OutStreamer->EmitWinCFIStartProc(Sym);
  183. }
  184. if (shouldEmitPersonality) {
  185. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  186. const Function *PerFn = nullptr;
  187. // Determine which personality routine we are using for this funclet.
  188. if (F.hasPersonalityFn())
  189. PerFn = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
  190. const MCSymbol *PersHandlerSym =
  191. TLOF.getCFIPersonalitySymbol(PerFn, Asm->TM, MMI);
  192. // Do not emit a .seh_handler directives for cleanup funclets.
  193. // FIXME: This means cleanup funclets cannot handle exceptions. Given that
  194. // Clang doesn't produce EH constructs inside cleanup funclets and LLVM's
  195. // inliner doesn't allow inlining them, this isn't a major problem in
  196. // practice.
  197. if (!CurrentFuncletEntry->isCleanupFuncletEntry())
  198. Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
  199. }
  200. }
  201. void WinException::endFunclet() {
  202. if (isAArch64 && CurrentFuncletEntry &&
  203. (shouldEmitMoves || shouldEmitPersonality)) {
  204. Asm->OutStreamer->SwitchSection(CurrentFuncletTextSection);
  205. Asm->OutStreamer->EmitWinCFIFuncletOrFuncEnd();
  206. }
  207. endFuncletImpl();
  208. }
  209. void WinException::endFuncletImpl() {
  210. // No funclet to process? Great, we have nothing to do.
  211. if (!CurrentFuncletEntry)
  212. return;
  213. const MachineFunction *MF = Asm->MF;
  214. if (shouldEmitMoves || shouldEmitPersonality) {
  215. const Function &F = MF->getFunction();
  216. EHPersonality Per = EHPersonality::Unknown;
  217. if (F.hasPersonalityFn())
  218. Per = classifyEHPersonality(F.getPersonalityFn()->stripPointerCasts());
  219. // On funclet exit, we emit a fake "function" end marker, so that the call
  220. // to EmitWinEHHandlerData below can calculate the size of the funclet or
  221. // function.
  222. if (isAArch64) {
  223. MCSection *XData = Asm->OutStreamer->getAssociatedXDataSection(
  224. Asm->OutStreamer->getCurrentSectionOnly());
  225. Asm->OutStreamer->SwitchSection(XData);
  226. }
  227. // Emit an UNWIND_INFO struct describing the prologue.
  228. Asm->OutStreamer->EmitWinEHHandlerData();
  229. if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
  230. !CurrentFuncletEntry->isCleanupFuncletEntry()) {
  231. // If this is a C++ catch funclet (or the parent function),
  232. // emit a reference to the LSDA for the parent function.
  233. StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
  234. MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
  235. Twine("$cppxdata$", FuncLinkageName));
  236. Asm->OutStreamer->EmitValue(create32bitRef(FuncInfoXData), 4);
  237. } else if (Per == EHPersonality::MSVC_Win64SEH && MF->hasEHFunclets() &&
  238. !CurrentFuncletEntry->isEHFuncletEntry()) {
  239. // If this is the parent function in Win64 SEH, emit the LSDA immediately
  240. // following .seh_handlerdata.
  241. emitCSpecificHandlerTable(MF);
  242. }
  243. // Switch back to the funclet start .text section now that we are done
  244. // writing to .xdata, and emit an .seh_endproc directive to mark the end of
  245. // the function.
  246. Asm->OutStreamer->SwitchSection(CurrentFuncletTextSection);
  247. Asm->OutStreamer->EmitWinCFIEndProc();
  248. }
  249. // Let's make sure we don't try to end the same funclet twice.
  250. CurrentFuncletEntry = nullptr;
  251. }
  252. const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
  253. if (!Value)
  254. return MCConstantExpr::create(0, Asm->OutContext);
  255. return MCSymbolRefExpr::create(Value, useImageRel32
  256. ? MCSymbolRefExpr::VK_COFF_IMGREL32
  257. : MCSymbolRefExpr::VK_None,
  258. Asm->OutContext);
  259. }
  260. const MCExpr *WinException::create32bitRef(const GlobalValue *GV) {
  261. if (!GV)
  262. return MCConstantExpr::create(0, Asm->OutContext);
  263. return create32bitRef(Asm->getSymbol(GV));
  264. }
  265. const MCExpr *WinException::getLabel(const MCSymbol *Label) {
  266. if (isAArch64)
  267. return MCSymbolRefExpr::create(Label, MCSymbolRefExpr::VK_COFF_IMGREL32,
  268. Asm->OutContext);
  269. return MCBinaryExpr::createAdd(create32bitRef(Label),
  270. MCConstantExpr::create(1, Asm->OutContext),
  271. Asm->OutContext);
  272. }
  273. const MCExpr *WinException::getOffset(const MCSymbol *OffsetOf,
  274. const MCSymbol *OffsetFrom) {
  275. return MCBinaryExpr::createSub(
  276. MCSymbolRefExpr::create(OffsetOf, Asm->OutContext),
  277. MCSymbolRefExpr::create(OffsetFrom, Asm->OutContext), Asm->OutContext);
  278. }
  279. const MCExpr *WinException::getOffsetPlusOne(const MCSymbol *OffsetOf,
  280. const MCSymbol *OffsetFrom) {
  281. return MCBinaryExpr::createAdd(getOffset(OffsetOf, OffsetFrom),
  282. MCConstantExpr::create(1, Asm->OutContext),
  283. Asm->OutContext);
  284. }
  285. int WinException::getFrameIndexOffset(int FrameIndex,
  286. const WinEHFuncInfo &FuncInfo) {
  287. const TargetFrameLowering &TFI = *Asm->MF->getSubtarget().getFrameLowering();
  288. unsigned UnusedReg;
  289. if (Asm->MAI->usesWindowsCFI()) {
  290. int Offset =
  291. TFI.getFrameIndexReferencePreferSP(*Asm->MF, FrameIndex, UnusedReg,
  292. /*IgnoreSPUpdates*/ true);
  293. assert(UnusedReg ==
  294. Asm->MF->getSubtarget()
  295. .getTargetLowering()
  296. ->getStackPointerRegisterToSaveRestore());
  297. return Offset;
  298. }
  299. // For 32-bit, offsets should be relative to the end of the EH registration
  300. // node. For 64-bit, it's relative to SP at the end of the prologue.
  301. assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
  302. int Offset = TFI.getFrameIndexReference(*Asm->MF, FrameIndex, UnusedReg);
  303. Offset += FuncInfo.EHRegNodeEndOffset;
  304. return Offset;
  305. }
  306. namespace {
  307. /// Top-level state used to represent unwind to caller
  308. const int NullState = -1;
  309. struct InvokeStateChange {
  310. /// EH Label immediately after the last invoke in the previous state, or
  311. /// nullptr if the previous state was the null state.
  312. const MCSymbol *PreviousEndLabel;
  313. /// EH label immediately before the first invoke in the new state, or nullptr
  314. /// if the new state is the null state.
  315. const MCSymbol *NewStartLabel;
  316. /// State of the invoke following NewStartLabel, or NullState to indicate
  317. /// the presence of calls which may unwind to caller.
  318. int NewState;
  319. };
  320. /// Iterator that reports all the invoke state changes in a range of machine
  321. /// basic blocks. Changes to the null state are reported whenever a call that
  322. /// may unwind to caller is encountered. The MBB range is expected to be an
  323. /// entire function or funclet, and the start and end of the range are treated
  324. /// as being in the NullState even if there's not an unwind-to-caller call
  325. /// before the first invoke or after the last one (i.e., the first state change
  326. /// reported is the first change to something other than NullState, and a
  327. /// change back to NullState is always reported at the end of iteration).
  328. class InvokeStateChangeIterator {
  329. InvokeStateChangeIterator(const WinEHFuncInfo &EHInfo,
  330. MachineFunction::const_iterator MFI,
  331. MachineFunction::const_iterator MFE,
  332. MachineBasicBlock::const_iterator MBBI,
  333. int BaseState)
  334. : EHInfo(EHInfo), MFI(MFI), MFE(MFE), MBBI(MBBI), BaseState(BaseState) {
  335. LastStateChange.PreviousEndLabel = nullptr;
  336. LastStateChange.NewStartLabel = nullptr;
  337. LastStateChange.NewState = BaseState;
  338. scan();
  339. }
  340. public:
  341. static iterator_range<InvokeStateChangeIterator>
  342. range(const WinEHFuncInfo &EHInfo, MachineFunction::const_iterator Begin,
  343. MachineFunction::const_iterator End, int BaseState = NullState) {
  344. // Reject empty ranges to simplify bookkeeping by ensuring that we can get
  345. // the end of the last block.
  346. assert(Begin != End);
  347. auto BlockBegin = Begin->begin();
  348. auto BlockEnd = std::prev(End)->end();
  349. return make_range(
  350. InvokeStateChangeIterator(EHInfo, Begin, End, BlockBegin, BaseState),
  351. InvokeStateChangeIterator(EHInfo, End, End, BlockEnd, BaseState));
  352. }
  353. // Iterator methods.
  354. bool operator==(const InvokeStateChangeIterator &O) const {
  355. assert(BaseState == O.BaseState);
  356. // Must be visiting same block.
  357. if (MFI != O.MFI)
  358. return false;
  359. // Must be visiting same isntr.
  360. if (MBBI != O.MBBI)
  361. return false;
  362. // At end of block/instr iteration, we can still have two distinct states:
  363. // one to report the final EndLabel, and another indicating the end of the
  364. // state change iteration. Check for CurrentEndLabel equality to
  365. // distinguish these.
  366. return CurrentEndLabel == O.CurrentEndLabel;
  367. }
  368. bool operator!=(const InvokeStateChangeIterator &O) const {
  369. return !operator==(O);
  370. }
  371. InvokeStateChange &operator*() { return LastStateChange; }
  372. InvokeStateChange *operator->() { return &LastStateChange; }
  373. InvokeStateChangeIterator &operator++() { return scan(); }
  374. private:
  375. InvokeStateChangeIterator &scan();
  376. const WinEHFuncInfo &EHInfo;
  377. const MCSymbol *CurrentEndLabel = nullptr;
  378. MachineFunction::const_iterator MFI;
  379. MachineFunction::const_iterator MFE;
  380. MachineBasicBlock::const_iterator MBBI;
  381. InvokeStateChange LastStateChange;
  382. bool VisitingInvoke = false;
  383. int BaseState;
  384. };
  385. } // end anonymous namespace
  386. InvokeStateChangeIterator &InvokeStateChangeIterator::scan() {
  387. bool IsNewBlock = false;
  388. for (; MFI != MFE; ++MFI, IsNewBlock = true) {
  389. if (IsNewBlock)
  390. MBBI = MFI->begin();
  391. for (auto MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
  392. const MachineInstr &MI = *MBBI;
  393. if (!VisitingInvoke && LastStateChange.NewState != BaseState &&
  394. MI.isCall() && !EHStreamer::callToNoUnwindFunction(&MI)) {
  395. // Indicate a change of state to the null state. We don't have
  396. // start/end EH labels handy but the caller won't expect them for
  397. // null state regions.
  398. LastStateChange.PreviousEndLabel = CurrentEndLabel;
  399. LastStateChange.NewStartLabel = nullptr;
  400. LastStateChange.NewState = BaseState;
  401. CurrentEndLabel = nullptr;
  402. // Don't re-visit this instr on the next scan
  403. ++MBBI;
  404. return *this;
  405. }
  406. // All other state changes are at EH labels before/after invokes.
  407. if (!MI.isEHLabel())
  408. continue;
  409. MCSymbol *Label = MI.getOperand(0).getMCSymbol();
  410. if (Label == CurrentEndLabel) {
  411. VisitingInvoke = false;
  412. continue;
  413. }
  414. auto InvokeMapIter = EHInfo.LabelToStateMap.find(Label);
  415. // Ignore EH labels that aren't the ones inserted before an invoke
  416. if (InvokeMapIter == EHInfo.LabelToStateMap.end())
  417. continue;
  418. auto &StateAndEnd = InvokeMapIter->second;
  419. int NewState = StateAndEnd.first;
  420. // Keep track of the fact that we're between EH start/end labels so
  421. // we know not to treat the inoke we'll see as unwinding to caller.
  422. VisitingInvoke = true;
  423. if (NewState == LastStateChange.NewState) {
  424. // The state isn't actually changing here. Record the new end and
  425. // keep going.
  426. CurrentEndLabel = StateAndEnd.second;
  427. continue;
  428. }
  429. // Found a state change to report
  430. LastStateChange.PreviousEndLabel = CurrentEndLabel;
  431. LastStateChange.NewStartLabel = Label;
  432. LastStateChange.NewState = NewState;
  433. // Start keeping track of the new current end
  434. CurrentEndLabel = StateAndEnd.second;
  435. // Don't re-visit this instr on the next scan
  436. ++MBBI;
  437. return *this;
  438. }
  439. }
  440. // Iteration hit the end of the block range.
  441. if (LastStateChange.NewState != BaseState) {
  442. // Report the end of the last new state
  443. LastStateChange.PreviousEndLabel = CurrentEndLabel;
  444. LastStateChange.NewStartLabel = nullptr;
  445. LastStateChange.NewState = BaseState;
  446. // Leave CurrentEndLabel non-null to distinguish this state from end.
  447. assert(CurrentEndLabel != nullptr);
  448. return *this;
  449. }
  450. // We've reported all state changes and hit the end state.
  451. CurrentEndLabel = nullptr;
  452. return *this;
  453. }
  454. /// Emit the language-specific data that __C_specific_handler expects. This
  455. /// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
  456. /// up after faults with __try, __except, and __finally. The typeinfo values
  457. /// are not really RTTI data, but pointers to filter functions that return an
  458. /// integer (1, 0, or -1) indicating how to handle the exception. For __finally
  459. /// blocks and other cleanups, the landing pad label is zero, and the filter
  460. /// function is actually a cleanup handler with the same prototype. A catch-all
  461. /// entry is modeled with a null filter function field and a non-zero landing
  462. /// pad label.
  463. ///
  464. /// Possible filter function return values:
  465. /// EXCEPTION_EXECUTE_HANDLER (1):
  466. /// Jump to the landing pad label after cleanups.
  467. /// EXCEPTION_CONTINUE_SEARCH (0):
  468. /// Continue searching this table or continue unwinding.
  469. /// EXCEPTION_CONTINUE_EXECUTION (-1):
  470. /// Resume execution at the trapping PC.
  471. ///
  472. /// Inferred table structure:
  473. /// struct Table {
  474. /// int NumEntries;
  475. /// struct Entry {
  476. /// imagerel32 LabelStart;
  477. /// imagerel32 LabelEnd;
  478. /// imagerel32 FilterOrFinally; // One means catch-all.
  479. /// imagerel32 LabelLPad; // Zero means __finally.
  480. /// } Entries[NumEntries];
  481. /// };
  482. void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
  483. auto &OS = *Asm->OutStreamer;
  484. MCContext &Ctx = Asm->OutContext;
  485. const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
  486. bool VerboseAsm = OS.isVerboseAsm();
  487. auto AddComment = [&](const Twine &Comment) {
  488. if (VerboseAsm)
  489. OS.AddComment(Comment);
  490. };
  491. if (!isAArch64) {
  492. // Emit a label assignment with the SEH frame offset so we can use it for
  493. // llvm.eh.recoverfp.
  494. StringRef FLinkageName =
  495. GlobalValue::dropLLVMManglingEscape(MF->getFunction().getName());
  496. MCSymbol *ParentFrameOffset =
  497. Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
  498. const MCExpr *MCOffset =
  499. MCConstantExpr::create(FuncInfo.SEHSetFrameOffset, Ctx);
  500. Asm->OutStreamer->EmitAssignment(ParentFrameOffset, MCOffset);
  501. }
  502. // Use the assembler to compute the number of table entries through label
  503. // difference and division.
  504. MCSymbol *TableBegin =
  505. Ctx.createTempSymbol("lsda_begin", /*AlwaysAddSuffix=*/true);
  506. MCSymbol *TableEnd =
  507. Ctx.createTempSymbol("lsda_end", /*AlwaysAddSuffix=*/true);
  508. const MCExpr *LabelDiff = getOffset(TableEnd, TableBegin);
  509. const MCExpr *EntrySize = MCConstantExpr::create(16, Ctx);
  510. const MCExpr *EntryCount = MCBinaryExpr::createDiv(LabelDiff, EntrySize, Ctx);
  511. AddComment("Number of call sites");
  512. OS.EmitValue(EntryCount, 4);
  513. OS.EmitLabel(TableBegin);
  514. // Iterate over all the invoke try ranges. Unlike MSVC, LLVM currently only
  515. // models exceptions from invokes. LLVM also allows arbitrary reordering of
  516. // the code, so our tables end up looking a bit different. Rather than
  517. // trying to match MSVC's tables exactly, we emit a denormalized table. For
  518. // each range of invokes in the same state, we emit table entries for all
  519. // the actions that would be taken in that state. This means our tables are
  520. // slightly bigger, which is OK.
  521. const MCSymbol *LastStartLabel = nullptr;
  522. int LastEHState = -1;
  523. // Break out before we enter into a finally funclet.
  524. // FIXME: We need to emit separate EH tables for cleanups.
  525. MachineFunction::const_iterator End = MF->end();
  526. MachineFunction::const_iterator Stop = std::next(MF->begin());
  527. while (Stop != End && !Stop->isEHFuncletEntry())
  528. ++Stop;
  529. for (const auto &StateChange :
  530. InvokeStateChangeIterator::range(FuncInfo, MF->begin(), Stop)) {
  531. // Emit all the actions for the state we just transitioned out of
  532. // if it was not the null state
  533. if (LastEHState != -1)
  534. emitSEHActionsForRange(FuncInfo, LastStartLabel,
  535. StateChange.PreviousEndLabel, LastEHState);
  536. LastStartLabel = StateChange.NewStartLabel;
  537. LastEHState = StateChange.NewState;
  538. }
  539. OS.EmitLabel(TableEnd);
  540. }
  541. void WinException::emitSEHActionsForRange(const WinEHFuncInfo &FuncInfo,
  542. const MCSymbol *BeginLabel,
  543. const MCSymbol *EndLabel, int State) {
  544. auto &OS = *Asm->OutStreamer;
  545. MCContext &Ctx = Asm->OutContext;
  546. bool VerboseAsm = OS.isVerboseAsm();
  547. auto AddComment = [&](const Twine &Comment) {
  548. if (VerboseAsm)
  549. OS.AddComment(Comment);
  550. };
  551. assert(BeginLabel && EndLabel);
  552. while (State != -1) {
  553. const SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
  554. const MCExpr *FilterOrFinally;
  555. const MCExpr *ExceptOrNull;
  556. auto *Handler = UME.Handler.get<MachineBasicBlock *>();
  557. if (UME.IsFinally) {
  558. FilterOrFinally = create32bitRef(getMCSymbolForMBB(Asm, Handler));
  559. ExceptOrNull = MCConstantExpr::create(0, Ctx);
  560. } else {
  561. // For an except, the filter can be 1 (catch-all) or a function
  562. // label.
  563. FilterOrFinally = UME.Filter ? create32bitRef(UME.Filter)
  564. : MCConstantExpr::create(1, Ctx);
  565. ExceptOrNull = create32bitRef(Handler->getSymbol());
  566. }
  567. AddComment("LabelStart");
  568. OS.EmitValue(getLabel(BeginLabel), 4);
  569. AddComment("LabelEnd");
  570. OS.EmitValue(getLabel(EndLabel), 4);
  571. AddComment(UME.IsFinally ? "FinallyFunclet" : UME.Filter ? "FilterFunction"
  572. : "CatchAll");
  573. OS.EmitValue(FilterOrFinally, 4);
  574. AddComment(UME.IsFinally ? "Null" : "ExceptionHandler");
  575. OS.EmitValue(ExceptOrNull, 4);
  576. assert(UME.ToState < State && "states should decrease");
  577. State = UME.ToState;
  578. }
  579. }
  580. void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
  581. const Function &F = MF->getFunction();
  582. auto &OS = *Asm->OutStreamer;
  583. const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
  584. StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
  585. SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
  586. MCSymbol *FuncInfoXData = nullptr;
  587. if (shouldEmitPersonality) {
  588. // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
  589. // IPs to state numbers.
  590. FuncInfoXData =
  591. Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
  592. computeIP2StateTable(MF, FuncInfo, IPToStateTable);
  593. } else {
  594. FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
  595. }
  596. int UnwindHelpOffset = 0;
  597. if (Asm->MAI->usesWindowsCFI())
  598. UnwindHelpOffset =
  599. getFrameIndexOffset(FuncInfo.UnwindHelpFrameIdx, FuncInfo);
  600. MCSymbol *UnwindMapXData = nullptr;
  601. MCSymbol *TryBlockMapXData = nullptr;
  602. MCSymbol *IPToStateXData = nullptr;
  603. if (!FuncInfo.CxxUnwindMap.empty())
  604. UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
  605. Twine("$stateUnwindMap$", FuncLinkageName));
  606. if (!FuncInfo.TryBlockMap.empty())
  607. TryBlockMapXData =
  608. Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
  609. if (!IPToStateTable.empty())
  610. IPToStateXData =
  611. Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
  612. bool VerboseAsm = OS.isVerboseAsm();
  613. auto AddComment = [&](const Twine &Comment) {
  614. if (VerboseAsm)
  615. OS.AddComment(Comment);
  616. };
  617. // FuncInfo {
  618. // uint32_t MagicNumber
  619. // int32_t MaxState;
  620. // UnwindMapEntry *UnwindMap;
  621. // uint32_t NumTryBlocks;
  622. // TryBlockMapEntry *TryBlockMap;
  623. // uint32_t IPMapEntries; // always 0 for x86
  624. // IPToStateMapEntry *IPToStateMap; // always 0 for x86
  625. // uint32_t UnwindHelp; // non-x86 only
  626. // ESTypeList *ESTypeList;
  627. // int32_t EHFlags;
  628. // }
  629. // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
  630. // EHFlags & 2 -> ???
  631. // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
  632. OS.EmitValueToAlignment(4);
  633. OS.EmitLabel(FuncInfoXData);
  634. AddComment("MagicNumber");
  635. OS.EmitIntValue(0x19930522, 4);
  636. AddComment("MaxState");
  637. OS.EmitIntValue(FuncInfo.CxxUnwindMap.size(), 4);
  638. AddComment("UnwindMap");
  639. OS.EmitValue(create32bitRef(UnwindMapXData), 4);
  640. AddComment("NumTryBlocks");
  641. OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4);
  642. AddComment("TryBlockMap");
  643. OS.EmitValue(create32bitRef(TryBlockMapXData), 4);
  644. AddComment("IPMapEntries");
  645. OS.EmitIntValue(IPToStateTable.size(), 4);
  646. AddComment("IPToStateXData");
  647. OS.EmitValue(create32bitRef(IPToStateXData), 4);
  648. if (Asm->MAI->usesWindowsCFI()) {
  649. AddComment("UnwindHelp");
  650. OS.EmitIntValue(UnwindHelpOffset, 4);
  651. }
  652. AddComment("ESTypeList");
  653. OS.EmitIntValue(0, 4);
  654. AddComment("EHFlags");
  655. OS.EmitIntValue(1, 4);
  656. // UnwindMapEntry {
  657. // int32_t ToState;
  658. // void (*Action)();
  659. // };
  660. if (UnwindMapXData) {
  661. OS.EmitLabel(UnwindMapXData);
  662. for (const CxxUnwindMapEntry &UME : FuncInfo.CxxUnwindMap) {
  663. MCSymbol *CleanupSym =
  664. getMCSymbolForMBB(Asm, UME.Cleanup.dyn_cast<MachineBasicBlock *>());
  665. AddComment("ToState");
  666. OS.EmitIntValue(UME.ToState, 4);
  667. AddComment("Action");
  668. OS.EmitValue(create32bitRef(CleanupSym), 4);
  669. }
  670. }
  671. // TryBlockMap {
  672. // int32_t TryLow;
  673. // int32_t TryHigh;
  674. // int32_t CatchHigh;
  675. // int32_t NumCatches;
  676. // HandlerType *HandlerArray;
  677. // };
  678. if (TryBlockMapXData) {
  679. OS.EmitLabel(TryBlockMapXData);
  680. SmallVector<MCSymbol *, 1> HandlerMaps;
  681. for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
  682. const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
  683. MCSymbol *HandlerMapXData = nullptr;
  684. if (!TBME.HandlerArray.empty())
  685. HandlerMapXData =
  686. Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
  687. .concat(Twine(I))
  688. .concat("$")
  689. .concat(FuncLinkageName));
  690. HandlerMaps.push_back(HandlerMapXData);
  691. // TBMEs should form intervals.
  692. assert(0 <= TBME.TryLow && "bad trymap interval");
  693. assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
  694. assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
  695. assert(TBME.CatchHigh < int(FuncInfo.CxxUnwindMap.size()) &&
  696. "bad trymap interval");
  697. AddComment("TryLow");
  698. OS.EmitIntValue(TBME.TryLow, 4);
  699. AddComment("TryHigh");
  700. OS.EmitIntValue(TBME.TryHigh, 4);
  701. AddComment("CatchHigh");
  702. OS.EmitIntValue(TBME.CatchHigh, 4);
  703. AddComment("NumCatches");
  704. OS.EmitIntValue(TBME.HandlerArray.size(), 4);
  705. AddComment("HandlerArray");
  706. OS.EmitValue(create32bitRef(HandlerMapXData), 4);
  707. }
  708. // All funclets use the same parent frame offset currently.
  709. unsigned ParentFrameOffset = 0;
  710. if (shouldEmitPersonality) {
  711. const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
  712. ParentFrameOffset = TFI->getWinEHParentFrameOffset(*MF);
  713. }
  714. for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
  715. const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
  716. MCSymbol *HandlerMapXData = HandlerMaps[I];
  717. if (!HandlerMapXData)
  718. continue;
  719. // HandlerType {
  720. // int32_t Adjectives;
  721. // TypeDescriptor *Type;
  722. // int32_t CatchObjOffset;
  723. // void (*Handler)();
  724. // int32_t ParentFrameOffset; // x64 and AArch64 only
  725. // };
  726. OS.EmitLabel(HandlerMapXData);
  727. for (const WinEHHandlerType &HT : TBME.HandlerArray) {
  728. // Get the frame escape label with the offset of the catch object. If
  729. // the index is INT_MAX, then there is no catch object, and we should
  730. // emit an offset of zero, indicating that no copy will occur.
  731. const MCExpr *FrameAllocOffsetRef = nullptr;
  732. if (HT.CatchObj.FrameIndex != INT_MAX) {
  733. int Offset = getFrameIndexOffset(HT.CatchObj.FrameIndex, FuncInfo);
  734. assert(Offset != 0 && "Illegal offset for catch object!");
  735. FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
  736. } else {
  737. FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
  738. }
  739. MCSymbol *HandlerSym =
  740. getMCSymbolForMBB(Asm, HT.Handler.dyn_cast<MachineBasicBlock *>());
  741. AddComment("Adjectives");
  742. OS.EmitIntValue(HT.Adjectives, 4);
  743. AddComment("Type");
  744. OS.EmitValue(create32bitRef(HT.TypeDescriptor), 4);
  745. AddComment("CatchObjOffset");
  746. OS.EmitValue(FrameAllocOffsetRef, 4);
  747. AddComment("Handler");
  748. OS.EmitValue(create32bitRef(HandlerSym), 4);
  749. if (shouldEmitPersonality) {
  750. AddComment("ParentFrameOffset");
  751. OS.EmitIntValue(ParentFrameOffset, 4);
  752. }
  753. }
  754. }
  755. }
  756. // IPToStateMapEntry {
  757. // void *IP;
  758. // int32_t State;
  759. // };
  760. if (IPToStateXData) {
  761. OS.EmitLabel(IPToStateXData);
  762. for (auto &IPStatePair : IPToStateTable) {
  763. AddComment("IP");
  764. OS.EmitValue(IPStatePair.first, 4);
  765. AddComment("ToState");
  766. OS.EmitIntValue(IPStatePair.second, 4);
  767. }
  768. }
  769. }
  770. void WinException::computeIP2StateTable(
  771. const MachineFunction *MF, const WinEHFuncInfo &FuncInfo,
  772. SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
  773. for (MachineFunction::const_iterator FuncletStart = MF->begin(),
  774. FuncletEnd = MF->begin(),
  775. End = MF->end();
  776. FuncletStart != End; FuncletStart = FuncletEnd) {
  777. // Find the end of the funclet
  778. while (++FuncletEnd != End) {
  779. if (FuncletEnd->isEHFuncletEntry()) {
  780. break;
  781. }
  782. }
  783. // Don't emit ip2state entries for cleanup funclets. Any interesting
  784. // exceptional actions in cleanups must be handled in a separate IR
  785. // function.
  786. if (FuncletStart->isCleanupFuncletEntry())
  787. continue;
  788. MCSymbol *StartLabel;
  789. int BaseState;
  790. if (FuncletStart == MF->begin()) {
  791. BaseState = NullState;
  792. StartLabel = Asm->getFunctionBegin();
  793. } else {
  794. auto *FuncletPad =
  795. cast<FuncletPadInst>(FuncletStart->getBasicBlock()->getFirstNonPHI());
  796. assert(FuncInfo.FuncletBaseStateMap.count(FuncletPad) != 0);
  797. BaseState = FuncInfo.FuncletBaseStateMap.find(FuncletPad)->second;
  798. StartLabel = getMCSymbolForMBB(Asm, &*FuncletStart);
  799. }
  800. assert(StartLabel && "need local function start label");
  801. IPToStateTable.push_back(
  802. std::make_pair(create32bitRef(StartLabel), BaseState));
  803. for (const auto &StateChange : InvokeStateChangeIterator::range(
  804. FuncInfo, FuncletStart, FuncletEnd, BaseState)) {
  805. // Compute the label to report as the start of this entry; use the EH
  806. // start label for the invoke if we have one, otherwise (this is a call
  807. // which may unwind to our caller and does not have an EH start label, so)
  808. // use the previous end label.
  809. const MCSymbol *ChangeLabel = StateChange.NewStartLabel;
  810. if (!ChangeLabel)
  811. ChangeLabel = StateChange.PreviousEndLabel;
  812. // Emit an entry indicating that PCs after 'Label' have this EH state.
  813. IPToStateTable.push_back(
  814. std::make_pair(getLabel(ChangeLabel), StateChange.NewState));
  815. // FIXME: assert that NewState is between CatchLow and CatchHigh.
  816. }
  817. }
  818. }
  819. void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
  820. StringRef FLinkageName) {
  821. // Outlined helpers called by the EH runtime need to know the offset of the EH
  822. // registration in order to recover the parent frame pointer. Now that we know
  823. // we've code generated the parent, we can emit the label assignment that
  824. // those helpers use to get the offset of the registration node.
  825. // Compute the parent frame offset. The EHRegNodeFrameIndex will be invalid if
  826. // after optimization all the invokes were eliminated. We still need to emit
  827. // the parent frame offset label, but it should be garbage and should never be
  828. // used.
  829. int64_t Offset = 0;
  830. int FI = FuncInfo.EHRegNodeFrameIndex;
  831. if (FI != INT_MAX) {
  832. const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
  833. Offset = TFI->getNonLocalFrameIndexReference(*Asm->MF, FI);
  834. }
  835. MCContext &Ctx = Asm->OutContext;
  836. MCSymbol *ParentFrameOffset =
  837. Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
  838. Asm->OutStreamer->EmitAssignment(ParentFrameOffset,
  839. MCConstantExpr::create(Offset, Ctx));
  840. }
  841. /// Emit the language-specific data that _except_handler3 and 4 expect. This is
  842. /// functionally equivalent to the __C_specific_handler table, except it is
  843. /// indexed by state number instead of IP.
  844. void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
  845. MCStreamer &OS = *Asm->OutStreamer;
  846. const Function &F = MF->getFunction();
  847. StringRef FLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
  848. bool VerboseAsm = OS.isVerboseAsm();
  849. auto AddComment = [&](const Twine &Comment) {
  850. if (VerboseAsm)
  851. OS.AddComment(Comment);
  852. };
  853. const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
  854. emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
  855. // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
  856. MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
  857. OS.EmitValueToAlignment(4);
  858. OS.EmitLabel(LSDALabel);
  859. const Function *Per =
  860. dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
  861. StringRef PerName = Per->getName();
  862. int BaseState = -1;
  863. if (PerName == "_except_handler4") {
  864. // The LSDA for _except_handler4 starts with this struct, followed by the
  865. // scope table:
  866. //
  867. // struct EH4ScopeTable {
  868. // int32_t GSCookieOffset;
  869. // int32_t GSCookieXOROffset;
  870. // int32_t EHCookieOffset;
  871. // int32_t EHCookieXOROffset;
  872. // ScopeTableEntry ScopeRecord[];
  873. // };
  874. //
  875. // Offsets are %ebp relative.
  876. //
  877. // The GS cookie is present only if the function needs stack protection.
  878. // GSCookieOffset = -2 means that GS cookie is not used.
  879. //
  880. // The EH cookie is always present.
  881. //
  882. // Check is done the following way:
  883. // (ebp+CookieXOROffset) ^ [ebp+CookieOffset] == _security_cookie
  884. // Retrieve the Guard Stack slot.
  885. int GSCookieOffset = -2;
  886. const MachineFrameInfo &MFI = MF->getFrameInfo();
  887. if (MFI.hasStackProtectorIndex()) {
  888. unsigned UnusedReg;
  889. const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
  890. int SSPIdx = MFI.getStackProtectorIndex();
  891. GSCookieOffset = TFI->getFrameIndexReference(*MF, SSPIdx, UnusedReg);
  892. }
  893. // Retrieve the EH Guard slot.
  894. // TODO(etienneb): Get rid of this value and change it for and assertion.
  895. int EHCookieOffset = 9999;
  896. if (FuncInfo.EHGuardFrameIndex != INT_MAX) {
  897. unsigned UnusedReg;
  898. const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
  899. int EHGuardIdx = FuncInfo.EHGuardFrameIndex;
  900. EHCookieOffset = TFI->getFrameIndexReference(*MF, EHGuardIdx, UnusedReg);
  901. }
  902. AddComment("GSCookieOffset");
  903. OS.EmitIntValue(GSCookieOffset, 4);
  904. AddComment("GSCookieXOROffset");
  905. OS.EmitIntValue(0, 4);
  906. AddComment("EHCookieOffset");
  907. OS.EmitIntValue(EHCookieOffset, 4);
  908. AddComment("EHCookieXOROffset");
  909. OS.EmitIntValue(0, 4);
  910. BaseState = -2;
  911. }
  912. assert(!FuncInfo.SEHUnwindMap.empty());
  913. for (const SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
  914. auto *Handler = UME.Handler.get<MachineBasicBlock *>();
  915. const MCSymbol *ExceptOrFinally =
  916. UME.IsFinally ? getMCSymbolForMBB(Asm, Handler) : Handler->getSymbol();
  917. // -1 is usually the base state for "unwind to caller", but for
  918. // _except_handler4 it's -2. Do that replacement here if necessary.
  919. int ToState = UME.ToState == -1 ? BaseState : UME.ToState;
  920. AddComment("ToState");
  921. OS.EmitIntValue(ToState, 4);
  922. AddComment(UME.IsFinally ? "Null" : "FilterFunction");
  923. OS.EmitValue(create32bitRef(UME.Filter), 4);
  924. AddComment(UME.IsFinally ? "FinallyFunclet" : "ExceptionHandler");
  925. OS.EmitValue(create32bitRef(ExceptOrFinally), 4);
  926. }
  927. }
  928. static int getTryRank(const WinEHFuncInfo &FuncInfo, int State) {
  929. int Rank = 0;
  930. while (State != -1) {
  931. ++Rank;
  932. State = FuncInfo.ClrEHUnwindMap[State].TryParentState;
  933. }
  934. return Rank;
  935. }
  936. static int getTryAncestor(const WinEHFuncInfo &FuncInfo, int Left, int Right) {
  937. int LeftRank = getTryRank(FuncInfo, Left);
  938. int RightRank = getTryRank(FuncInfo, Right);
  939. while (LeftRank < RightRank) {
  940. Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
  941. --RightRank;
  942. }
  943. while (RightRank < LeftRank) {
  944. Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
  945. --LeftRank;
  946. }
  947. while (Left != Right) {
  948. Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
  949. Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
  950. }
  951. return Left;
  952. }
  953. void WinException::emitCLRExceptionTable(const MachineFunction *MF) {
  954. // CLR EH "states" are really just IDs that identify handlers/funclets;
  955. // states, handlers, and funclets all have 1:1 mappings between them, and a
  956. // handler/funclet's "state" is its index in the ClrEHUnwindMap.
  957. MCStreamer &OS = *Asm->OutStreamer;
  958. const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
  959. MCSymbol *FuncBeginSym = Asm->getFunctionBegin();
  960. MCSymbol *FuncEndSym = Asm->getFunctionEnd();
  961. // A ClrClause describes a protected region.
  962. struct ClrClause {
  963. const MCSymbol *StartLabel; // Start of protected region
  964. const MCSymbol *EndLabel; // End of protected region
  965. int State; // Index of handler protecting the protected region
  966. int EnclosingState; // Index of funclet enclosing the protected region
  967. };
  968. SmallVector<ClrClause, 8> Clauses;
  969. // Build a map from handler MBBs to their corresponding states (i.e. their
  970. // indices in the ClrEHUnwindMap).
  971. int NumStates = FuncInfo.ClrEHUnwindMap.size();
  972. assert(NumStates > 0 && "Don't need exception table!");
  973. DenseMap<const MachineBasicBlock *, int> HandlerStates;
  974. for (int State = 0; State < NumStates; ++State) {
  975. MachineBasicBlock *HandlerBlock =
  976. FuncInfo.ClrEHUnwindMap[State].Handler.get<MachineBasicBlock *>();
  977. HandlerStates[HandlerBlock] = State;
  978. // Use this loop through all handlers to verify our assumption (used in
  979. // the MinEnclosingState computation) that enclosing funclets have lower
  980. // state numbers than their enclosed funclets.
  981. assert(FuncInfo.ClrEHUnwindMap[State].HandlerParentState < State &&
  982. "ill-formed state numbering");
  983. }
  984. // Map the main function to the NullState.
  985. HandlerStates[&MF->front()] = NullState;
  986. // Write out a sentinel indicating the end of the standard (Windows) xdata
  987. // and the start of the additional (CLR) info.
  988. OS.EmitIntValue(0xffffffff, 4);
  989. // Write out the number of funclets
  990. OS.EmitIntValue(NumStates, 4);
  991. // Walk the machine blocks/instrs, computing and emitting a few things:
  992. // 1. Emit a list of the offsets to each handler entry, in lexical order.
  993. // 2. Compute a map (EndSymbolMap) from each funclet to the symbol at its end.
  994. // 3. Compute the list of ClrClauses, in the required order (inner before
  995. // outer, earlier before later; the order by which a forward scan with
  996. // early termination will find the innermost enclosing clause covering
  997. // a given address).
  998. // 4. A map (MinClauseMap) from each handler index to the index of the
  999. // outermost funclet/function which contains a try clause targeting the
  1000. // key handler. This will be used to determine IsDuplicate-ness when
  1001. // emitting ClrClauses. The NullState value is used to indicate that the
  1002. // top-level function contains a try clause targeting the key handler.
  1003. // HandlerStack is a stack of (PendingStartLabel, PendingState) pairs for
  1004. // try regions we entered before entering the PendingState try but which
  1005. // we haven't yet exited.
  1006. SmallVector<std::pair<const MCSymbol *, int>, 4> HandlerStack;
  1007. // EndSymbolMap and MinClauseMap are maps described above.
  1008. std::unique_ptr<MCSymbol *[]> EndSymbolMap(new MCSymbol *[NumStates]);
  1009. SmallVector<int, 4> MinClauseMap((size_t)NumStates, NumStates);
  1010. // Visit the root function and each funclet.
  1011. for (MachineFunction::const_iterator FuncletStart = MF->begin(),
  1012. FuncletEnd = MF->begin(),
  1013. End = MF->end();
  1014. FuncletStart != End; FuncletStart = FuncletEnd) {
  1015. int FuncletState = HandlerStates[&*FuncletStart];
  1016. // Find the end of the funclet
  1017. MCSymbol *EndSymbol = FuncEndSym;
  1018. while (++FuncletEnd != End) {
  1019. if (FuncletEnd->isEHFuncletEntry()) {
  1020. EndSymbol = getMCSymbolForMBB(Asm, &*FuncletEnd);
  1021. break;
  1022. }
  1023. }
  1024. // Emit the function/funclet end and, if this is a funclet (and not the
  1025. // root function), record it in the EndSymbolMap.
  1026. OS.EmitValue(getOffset(EndSymbol, FuncBeginSym), 4);
  1027. if (FuncletState != NullState) {
  1028. // Record the end of the handler.
  1029. EndSymbolMap[FuncletState] = EndSymbol;
  1030. }
  1031. // Walk the state changes in this function/funclet and compute its clauses.
  1032. // Funclets always start in the null state.
  1033. const MCSymbol *CurrentStartLabel = nullptr;
  1034. int CurrentState = NullState;
  1035. assert(HandlerStack.empty());
  1036. for (const auto &StateChange :
  1037. InvokeStateChangeIterator::range(FuncInfo, FuncletStart, FuncletEnd)) {
  1038. // Close any try regions we're not still under
  1039. int StillPendingState =
  1040. getTryAncestor(FuncInfo, CurrentState, StateChange.NewState);
  1041. while (CurrentState != StillPendingState) {
  1042. assert(CurrentState != NullState &&
  1043. "Failed to find still-pending state!");
  1044. // Close the pending clause
  1045. Clauses.push_back({CurrentStartLabel, StateChange.PreviousEndLabel,
  1046. CurrentState, FuncletState});
  1047. // Now the next-outer try region is current
  1048. CurrentState = FuncInfo.ClrEHUnwindMap[CurrentState].TryParentState;
  1049. // Pop the new start label from the handler stack if we've exited all
  1050. // inner try regions of the corresponding try region.
  1051. if (HandlerStack.back().second == CurrentState)
  1052. CurrentStartLabel = HandlerStack.pop_back_val().first;
  1053. }
  1054. if (StateChange.NewState != CurrentState) {
  1055. // For each clause we're starting, update the MinClauseMap so we can
  1056. // know which is the topmost funclet containing a clause targeting
  1057. // it.
  1058. for (int EnteredState = StateChange.NewState;
  1059. EnteredState != CurrentState;
  1060. EnteredState =
  1061. FuncInfo.ClrEHUnwindMap[EnteredState].TryParentState) {
  1062. int &MinEnclosingState = MinClauseMap[EnteredState];
  1063. if (FuncletState < MinEnclosingState)
  1064. MinEnclosingState = FuncletState;
  1065. }
  1066. // Save the previous current start/label on the stack and update to
  1067. // the newly-current start/state.
  1068. HandlerStack.emplace_back(CurrentStartLabel, CurrentState);
  1069. CurrentStartLabel = StateChange.NewStartLabel;
  1070. CurrentState = StateChange.NewState;
  1071. }
  1072. }
  1073. assert(HandlerStack.empty());
  1074. }
  1075. // Now emit the clause info, starting with the number of clauses.
  1076. OS.EmitIntValue(Clauses.size(), 4);
  1077. for (ClrClause &Clause : Clauses) {
  1078. // Emit a CORINFO_EH_CLAUSE :
  1079. /*
  1080. struct CORINFO_EH_CLAUSE
  1081. {
  1082. CORINFO_EH_CLAUSE_FLAGS Flags; // actually a CorExceptionFlag
  1083. DWORD TryOffset;
  1084. DWORD TryLength; // actually TryEndOffset
  1085. DWORD HandlerOffset;
  1086. DWORD HandlerLength; // actually HandlerEndOffset
  1087. union
  1088. {
  1089. DWORD ClassToken; // use for catch clauses
  1090. DWORD FilterOffset; // use for filter clauses
  1091. };
  1092. };
  1093. enum CORINFO_EH_CLAUSE_FLAGS
  1094. {
  1095. CORINFO_EH_CLAUSE_NONE = 0,
  1096. CORINFO_EH_CLAUSE_FILTER = 0x0001, // This clause is for a filter
  1097. CORINFO_EH_CLAUSE_FINALLY = 0x0002, // This clause is a finally clause
  1098. CORINFO_EH_CLAUSE_FAULT = 0x0004, // This clause is a fault clause
  1099. };
  1100. typedef enum CorExceptionFlag
  1101. {
  1102. COR_ILEXCEPTION_CLAUSE_NONE,
  1103. COR_ILEXCEPTION_CLAUSE_FILTER = 0x0001, // This is a filter clause
  1104. COR_ILEXCEPTION_CLAUSE_FINALLY = 0x0002, // This is a finally clause
  1105. COR_ILEXCEPTION_CLAUSE_FAULT = 0x0004, // This is a fault clause
  1106. COR_ILEXCEPTION_CLAUSE_DUPLICATED = 0x0008, // duplicated clause. This
  1107. // clause was duplicated
  1108. // to a funclet which was
  1109. // pulled out of line
  1110. } CorExceptionFlag;
  1111. */
  1112. // Add 1 to the start/end of the EH clause; the IP associated with a
  1113. // call when the runtime does its scan is the IP of the next instruction
  1114. // (the one to which control will return after the call), so we need
  1115. // to add 1 to the end of the clause to cover that offset. We also add
  1116. // 1 to the start of the clause to make sure that the ranges reported
  1117. // for all clauses are disjoint. Note that we'll need some additional
  1118. // logic when machine traps are supported, since in that case the IP
  1119. // that the runtime uses is the offset of the faulting instruction
  1120. // itself; if such an instruction immediately follows a call but the
  1121. // two belong to different clauses, we'll need to insert a nop between
  1122. // them so the runtime can distinguish the point to which the call will
  1123. // return from the point at which the fault occurs.
  1124. const MCExpr *ClauseBegin =
  1125. getOffsetPlusOne(Clause.StartLabel, FuncBeginSym);
  1126. const MCExpr *ClauseEnd = getOffsetPlusOne(Clause.EndLabel, FuncBeginSym);
  1127. const ClrEHUnwindMapEntry &Entry = FuncInfo.ClrEHUnwindMap[Clause.State];
  1128. MachineBasicBlock *HandlerBlock = Entry.Handler.get<MachineBasicBlock *>();
  1129. MCSymbol *BeginSym = getMCSymbolForMBB(Asm, HandlerBlock);
  1130. const MCExpr *HandlerBegin = getOffset(BeginSym, FuncBeginSym);
  1131. MCSymbol *EndSym = EndSymbolMap[Clause.State];
  1132. const MCExpr *HandlerEnd = getOffset(EndSym, FuncBeginSym);
  1133. uint32_t Flags = 0;
  1134. switch (Entry.HandlerType) {
  1135. case ClrHandlerType::Catch:
  1136. // Leaving bits 0-2 clear indicates catch.
  1137. break;
  1138. case ClrHandlerType::Filter:
  1139. Flags |= 1;
  1140. break;
  1141. case ClrHandlerType::Finally:
  1142. Flags |= 2;
  1143. break;
  1144. case ClrHandlerType::Fault:
  1145. Flags |= 4;
  1146. break;
  1147. }
  1148. if (Clause.EnclosingState != MinClauseMap[Clause.State]) {
  1149. // This is a "duplicate" clause; the handler needs to be entered from a
  1150. // frame above the one holding the invoke.
  1151. assert(Clause.EnclosingState > MinClauseMap[Clause.State]);
  1152. Flags |= 8;
  1153. }
  1154. OS.EmitIntValue(Flags, 4);
  1155. // Write the clause start/end
  1156. OS.EmitValue(ClauseBegin, 4);
  1157. OS.EmitValue(ClauseEnd, 4);
  1158. // Write out the handler start/end
  1159. OS.EmitValue(HandlerBegin, 4);
  1160. OS.EmitValue(HandlerEnd, 4);
  1161. // Write out the type token or filter offset
  1162. assert(Entry.HandlerType != ClrHandlerType::Filter && "NYI: filters");
  1163. OS.EmitIntValue(Entry.TypeToken, 4);
  1164. }
  1165. }