CGCleanup.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370
  1. //===--- CGCleanup.cpp - Bookkeeping and code emission for cleanups -------===//
  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 code dealing with the IR generation for cleanups
  10. // and related information.
  11. //
  12. // A "cleanup" is a piece of code which needs to be executed whenever
  13. // control transfers out of a particular scope. This can be
  14. // conditionalized to occur only on exceptional control flow, only on
  15. // normal control flow, or both.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "CGCleanup.h"
  19. #include "CodeGenFunction.h"
  20. #include "llvm/Support/SaveAndRestore.h"
  21. using namespace clang;
  22. using namespace CodeGen;
  23. bool DominatingValue<RValue>::saved_type::needsSaving(RValue rv) {
  24. if (rv.isScalar())
  25. return DominatingLLVMValue::needsSaving(rv.getScalarVal());
  26. if (rv.isAggregate())
  27. return DominatingLLVMValue::needsSaving(rv.getAggregatePointer());
  28. return true;
  29. }
  30. DominatingValue<RValue>::saved_type
  31. DominatingValue<RValue>::saved_type::save(CodeGenFunction &CGF, RValue rv) {
  32. if (rv.isScalar()) {
  33. llvm::Value *V = rv.getScalarVal();
  34. // These automatically dominate and don't need to be saved.
  35. if (!DominatingLLVMValue::needsSaving(V))
  36. return saved_type(V, ScalarLiteral);
  37. // Everything else needs an alloca.
  38. Address addr =
  39. CGF.CreateDefaultAlignTempAlloca(V->getType(), "saved-rvalue");
  40. CGF.Builder.CreateStore(V, addr);
  41. return saved_type(addr.getPointer(), ScalarAddress);
  42. }
  43. if (rv.isComplex()) {
  44. CodeGenFunction::ComplexPairTy V = rv.getComplexVal();
  45. llvm::Type *ComplexTy =
  46. llvm::StructType::get(V.first->getType(), V.second->getType());
  47. Address addr = CGF.CreateDefaultAlignTempAlloca(ComplexTy, "saved-complex");
  48. CGF.Builder.CreateStore(V.first, CGF.Builder.CreateStructGEP(addr, 0));
  49. CGF.Builder.CreateStore(V.second, CGF.Builder.CreateStructGEP(addr, 1));
  50. return saved_type(addr.getPointer(), ComplexAddress);
  51. }
  52. assert(rv.isAggregate());
  53. Address V = rv.getAggregateAddress(); // TODO: volatile?
  54. if (!DominatingLLVMValue::needsSaving(V.getPointer()))
  55. return saved_type(V.getPointer(), AggregateLiteral,
  56. V.getAlignment().getQuantity());
  57. Address addr =
  58. CGF.CreateTempAlloca(V.getType(), CGF.getPointerAlign(), "saved-rvalue");
  59. CGF.Builder.CreateStore(V.getPointer(), addr);
  60. return saved_type(addr.getPointer(), AggregateAddress,
  61. V.getAlignment().getQuantity());
  62. }
  63. /// Given a saved r-value produced by SaveRValue, perform the code
  64. /// necessary to restore it to usability at the current insertion
  65. /// point.
  66. RValue DominatingValue<RValue>::saved_type::restore(CodeGenFunction &CGF) {
  67. auto getSavingAddress = [&](llvm::Value *value) {
  68. auto alignment = cast<llvm::AllocaInst>(value)->getAlignment();
  69. return Address(value, CharUnits::fromQuantity(alignment));
  70. };
  71. switch (K) {
  72. case ScalarLiteral:
  73. return RValue::get(Value);
  74. case ScalarAddress:
  75. return RValue::get(CGF.Builder.CreateLoad(getSavingAddress(Value)));
  76. case AggregateLiteral:
  77. return RValue::getAggregate(Address(Value, CharUnits::fromQuantity(Align)));
  78. case AggregateAddress: {
  79. auto addr = CGF.Builder.CreateLoad(getSavingAddress(Value));
  80. return RValue::getAggregate(Address(addr, CharUnits::fromQuantity(Align)));
  81. }
  82. case ComplexAddress: {
  83. Address address = getSavingAddress(Value);
  84. llvm::Value *real =
  85. CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(address, 0));
  86. llvm::Value *imag =
  87. CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(address, 1));
  88. return RValue::getComplex(real, imag);
  89. }
  90. }
  91. llvm_unreachable("bad saved r-value kind");
  92. }
  93. /// Push an entry of the given size onto this protected-scope stack.
  94. char *EHScopeStack::allocate(size_t Size) {
  95. Size = llvm::alignTo(Size, ScopeStackAlignment);
  96. if (!StartOfBuffer) {
  97. unsigned Capacity = 1024;
  98. while (Capacity < Size) Capacity *= 2;
  99. StartOfBuffer = new char[Capacity];
  100. StartOfData = EndOfBuffer = StartOfBuffer + Capacity;
  101. } else if (static_cast<size_t>(StartOfData - StartOfBuffer) < Size) {
  102. unsigned CurrentCapacity = EndOfBuffer - StartOfBuffer;
  103. unsigned UsedCapacity = CurrentCapacity - (StartOfData - StartOfBuffer);
  104. unsigned NewCapacity = CurrentCapacity;
  105. do {
  106. NewCapacity *= 2;
  107. } while (NewCapacity < UsedCapacity + Size);
  108. char *NewStartOfBuffer = new char[NewCapacity];
  109. char *NewEndOfBuffer = NewStartOfBuffer + NewCapacity;
  110. char *NewStartOfData = NewEndOfBuffer - UsedCapacity;
  111. memcpy(NewStartOfData, StartOfData, UsedCapacity);
  112. delete [] StartOfBuffer;
  113. StartOfBuffer = NewStartOfBuffer;
  114. EndOfBuffer = NewEndOfBuffer;
  115. StartOfData = NewStartOfData;
  116. }
  117. assert(StartOfBuffer + Size <= StartOfData);
  118. StartOfData -= Size;
  119. return StartOfData;
  120. }
  121. void EHScopeStack::deallocate(size_t Size) {
  122. StartOfData += llvm::alignTo(Size, ScopeStackAlignment);
  123. }
  124. bool EHScopeStack::containsOnlyLifetimeMarkers(
  125. EHScopeStack::stable_iterator Old) const {
  126. for (EHScopeStack::iterator it = begin(); stabilize(it) != Old; it++) {
  127. EHCleanupScope *cleanup = dyn_cast<EHCleanupScope>(&*it);
  128. if (!cleanup || !cleanup->isLifetimeMarker())
  129. return false;
  130. }
  131. return true;
  132. }
  133. bool EHScopeStack::requiresLandingPad() const {
  134. for (stable_iterator si = getInnermostEHScope(); si != stable_end(); ) {
  135. // Skip lifetime markers.
  136. if (auto *cleanup = dyn_cast<EHCleanupScope>(&*find(si)))
  137. if (cleanup->isLifetimeMarker()) {
  138. si = cleanup->getEnclosingEHScope();
  139. continue;
  140. }
  141. return true;
  142. }
  143. return false;
  144. }
  145. EHScopeStack::stable_iterator
  146. EHScopeStack::getInnermostActiveNormalCleanup() const {
  147. for (stable_iterator si = getInnermostNormalCleanup(), se = stable_end();
  148. si != se; ) {
  149. EHCleanupScope &cleanup = cast<EHCleanupScope>(*find(si));
  150. if (cleanup.isActive()) return si;
  151. si = cleanup.getEnclosingNormalCleanup();
  152. }
  153. return stable_end();
  154. }
  155. void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {
  156. char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));
  157. bool IsNormalCleanup = Kind & NormalCleanup;
  158. bool IsEHCleanup = Kind & EHCleanup;
  159. bool IsLifetimeMarker = Kind & LifetimeMarker;
  160. EHCleanupScope *Scope =
  161. new (Buffer) EHCleanupScope(IsNormalCleanup,
  162. IsEHCleanup,
  163. Size,
  164. BranchFixups.size(),
  165. InnermostNormalCleanup,
  166. InnermostEHScope);
  167. if (IsNormalCleanup)
  168. InnermostNormalCleanup = stable_begin();
  169. if (IsEHCleanup)
  170. InnermostEHScope = stable_begin();
  171. if (IsLifetimeMarker)
  172. Scope->setLifetimeMarker();
  173. // With Windows -EHa, Invoke llvm.seh.scope.begin() for EHCleanup
  174. if (CGF->getLangOpts().EHAsynch && IsEHCleanup && !IsLifetimeMarker &&
  175. CGF->getTarget().getCXXABI().isMicrosoft())
  176. CGF->EmitSehCppScopeBegin();
  177. return Scope->getCleanupBuffer();
  178. }
  179. void EHScopeStack::popCleanup() {
  180. assert(!empty() && "popping exception stack when not empty");
  181. assert(isa<EHCleanupScope>(*begin()));
  182. EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
  183. InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
  184. InnermostEHScope = Cleanup.getEnclosingEHScope();
  185. deallocate(Cleanup.getAllocatedSize());
  186. // Destroy the cleanup.
  187. Cleanup.Destroy();
  188. // Check whether we can shrink the branch-fixups stack.
  189. if (!BranchFixups.empty()) {
  190. // If we no longer have any normal cleanups, all the fixups are
  191. // complete.
  192. if (!hasNormalCleanups())
  193. BranchFixups.clear();
  194. // Otherwise we can still trim out unnecessary nulls.
  195. else
  196. popNullFixups();
  197. }
  198. }
  199. EHFilterScope *EHScopeStack::pushFilter(unsigned numFilters) {
  200. assert(getInnermostEHScope() == stable_end());
  201. char *buffer = allocate(EHFilterScope::getSizeForNumFilters(numFilters));
  202. EHFilterScope *filter = new (buffer) EHFilterScope(numFilters);
  203. InnermostEHScope = stable_begin();
  204. return filter;
  205. }
  206. void EHScopeStack::popFilter() {
  207. assert(!empty() && "popping exception stack when not empty");
  208. EHFilterScope &filter = cast<EHFilterScope>(*begin());
  209. deallocate(EHFilterScope::getSizeForNumFilters(filter.getNumFilters()));
  210. InnermostEHScope = filter.getEnclosingEHScope();
  211. }
  212. EHCatchScope *EHScopeStack::pushCatch(unsigned numHandlers) {
  213. char *buffer = allocate(EHCatchScope::getSizeForNumHandlers(numHandlers));
  214. EHCatchScope *scope =
  215. new (buffer) EHCatchScope(numHandlers, InnermostEHScope);
  216. InnermostEHScope = stable_begin();
  217. return scope;
  218. }
  219. void EHScopeStack::pushTerminate() {
  220. char *Buffer = allocate(EHTerminateScope::getSize());
  221. new (Buffer) EHTerminateScope(InnermostEHScope);
  222. InnermostEHScope = stable_begin();
  223. }
  224. /// Remove any 'null' fixups on the stack. However, we can't pop more
  225. /// fixups than the fixup depth on the innermost normal cleanup, or
  226. /// else fixups that we try to add to that cleanup will end up in the
  227. /// wrong place. We *could* try to shrink fixup depths, but that's
  228. /// actually a lot of work for little benefit.
  229. void EHScopeStack::popNullFixups() {
  230. // We expect this to only be called when there's still an innermost
  231. // normal cleanup; otherwise there really shouldn't be any fixups.
  232. assert(hasNormalCleanups());
  233. EHScopeStack::iterator it = find(InnermostNormalCleanup);
  234. unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
  235. assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
  236. while (BranchFixups.size() > MinSize &&
  237. BranchFixups.back().Destination == nullptr)
  238. BranchFixups.pop_back();
  239. }
  240. Address CodeGenFunction::createCleanupActiveFlag() {
  241. // Create a variable to decide whether the cleanup needs to be run.
  242. Address active = CreateTempAllocaWithoutCast(
  243. Builder.getInt1Ty(), CharUnits::One(), "cleanup.cond");
  244. // Initialize it to false at a site that's guaranteed to be run
  245. // before each evaluation.
  246. setBeforeOutermostConditional(Builder.getFalse(), active);
  247. // Initialize it to true at the current location.
  248. Builder.CreateStore(Builder.getTrue(), active);
  249. return active;
  250. }
  251. void CodeGenFunction::initFullExprCleanupWithFlag(Address ActiveFlag) {
  252. // Set that as the active flag in the cleanup.
  253. EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
  254. assert(!cleanup.hasActiveFlag() && "cleanup already has active flag?");
  255. cleanup.setActiveFlag(ActiveFlag);
  256. if (cleanup.isNormalCleanup()) cleanup.setTestFlagInNormalCleanup();
  257. if (cleanup.isEHCleanup()) cleanup.setTestFlagInEHCleanup();
  258. }
  259. void EHScopeStack::Cleanup::anchor() {}
  260. static void createStoreInstBefore(llvm::Value *value, Address addr,
  261. llvm::Instruction *beforeInst) {
  262. auto store = new llvm::StoreInst(value, addr.getPointer(), beforeInst);
  263. store->setAlignment(addr.getAlignment().getAsAlign());
  264. }
  265. static llvm::LoadInst *createLoadInstBefore(Address addr, const Twine &name,
  266. llvm::Instruction *beforeInst) {
  267. return new llvm::LoadInst(addr.getElementType(), addr.getPointer(), name,
  268. false, addr.getAlignment().getAsAlign(),
  269. beforeInst);
  270. }
  271. /// All the branch fixups on the EH stack have propagated out past the
  272. /// outermost normal cleanup; resolve them all by adding cases to the
  273. /// given switch instruction.
  274. static void ResolveAllBranchFixups(CodeGenFunction &CGF,
  275. llvm::SwitchInst *Switch,
  276. llvm::BasicBlock *CleanupEntry) {
  277. llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;
  278. for (unsigned I = 0, E = CGF.EHStack.getNumBranchFixups(); I != E; ++I) {
  279. // Skip this fixup if its destination isn't set.
  280. BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
  281. if (Fixup.Destination == nullptr) continue;
  282. // If there isn't an OptimisticBranchBlock, then InitialBranch is
  283. // still pointing directly to its destination; forward it to the
  284. // appropriate cleanup entry. This is required in the specific
  285. // case of
  286. // { std::string s; goto lbl; }
  287. // lbl:
  288. // i.e. where there's an unresolved fixup inside a single cleanup
  289. // entry which we're currently popping.
  290. if (Fixup.OptimisticBranchBlock == nullptr) {
  291. createStoreInstBefore(CGF.Builder.getInt32(Fixup.DestinationIndex),
  292. CGF.getNormalCleanupDestSlot(),
  293. Fixup.InitialBranch);
  294. Fixup.InitialBranch->setSuccessor(0, CleanupEntry);
  295. }
  296. // Don't add this case to the switch statement twice.
  297. if (!CasesAdded.insert(Fixup.Destination).second)
  298. continue;
  299. Switch->addCase(CGF.Builder.getInt32(Fixup.DestinationIndex),
  300. Fixup.Destination);
  301. }
  302. CGF.EHStack.clearFixups();
  303. }
  304. /// Transitions the terminator of the given exit-block of a cleanup to
  305. /// be a cleanup switch.
  306. static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,
  307. llvm::BasicBlock *Block) {
  308. // If it's a branch, turn it into a switch whose default
  309. // destination is its original target.
  310. llvm::Instruction *Term = Block->getTerminator();
  311. assert(Term && "can't transition block without terminator");
  312. if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
  313. assert(Br->isUnconditional());
  314. auto Load = createLoadInstBefore(CGF.getNormalCleanupDestSlot(),
  315. "cleanup.dest", Term);
  316. llvm::SwitchInst *Switch =
  317. llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);
  318. Br->eraseFromParent();
  319. return Switch;
  320. } else {
  321. return cast<llvm::SwitchInst>(Term);
  322. }
  323. }
  324. void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
  325. assert(Block && "resolving a null target block");
  326. if (!EHStack.getNumBranchFixups()) return;
  327. assert(EHStack.hasNormalCleanups() &&
  328. "branch fixups exist with no normal cleanups on stack");
  329. llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;
  330. bool ResolvedAny = false;
  331. for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
  332. // Skip this fixup if its destination doesn't match.
  333. BranchFixup &Fixup = EHStack.getBranchFixup(I);
  334. if (Fixup.Destination != Block) continue;
  335. Fixup.Destination = nullptr;
  336. ResolvedAny = true;
  337. // If it doesn't have an optimistic branch block, LatestBranch is
  338. // already pointing to the right place.
  339. llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;
  340. if (!BranchBB)
  341. continue;
  342. // Don't process the same optimistic branch block twice.
  343. if (!ModifiedOptimisticBlocks.insert(BranchBB).second)
  344. continue;
  345. llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);
  346. // Add a case to the switch.
  347. Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);
  348. }
  349. if (ResolvedAny)
  350. EHStack.popNullFixups();
  351. }
  352. /// Pops cleanup blocks until the given savepoint is reached.
  353. void CodeGenFunction::PopCleanupBlocks(
  354. EHScopeStack::stable_iterator Old,
  355. std::initializer_list<llvm::Value **> ValuesToReload) {
  356. assert(Old.isValid());
  357. bool HadBranches = false;
  358. while (EHStack.stable_begin() != Old) {
  359. EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
  360. HadBranches |= Scope.hasBranches();
  361. // As long as Old strictly encloses the scope's enclosing normal
  362. // cleanup, we're going to emit another normal cleanup which
  363. // fallthrough can propagate through.
  364. bool FallThroughIsBranchThrough =
  365. Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
  366. PopCleanupBlock(FallThroughIsBranchThrough);
  367. }
  368. // If we didn't have any branches, the insertion point before cleanups must
  369. // dominate the current insertion point and we don't need to reload any
  370. // values.
  371. if (!HadBranches)
  372. return;
  373. // Spill and reload all values that the caller wants to be live at the current
  374. // insertion point.
  375. for (llvm::Value **ReloadedValue : ValuesToReload) {
  376. auto *Inst = dyn_cast_or_null<llvm::Instruction>(*ReloadedValue);
  377. if (!Inst)
  378. continue;
  379. // Don't spill static allocas, they dominate all cleanups. These are created
  380. // by binding a reference to a local variable or temporary.
  381. auto *AI = dyn_cast<llvm::AllocaInst>(Inst);
  382. if (AI && AI->isStaticAlloca())
  383. continue;
  384. Address Tmp =
  385. CreateDefaultAlignTempAlloca(Inst->getType(), "tmp.exprcleanup");
  386. // Find an insertion point after Inst and spill it to the temporary.
  387. llvm::BasicBlock::iterator InsertBefore;
  388. if (auto *Invoke = dyn_cast<llvm::InvokeInst>(Inst))
  389. InsertBefore = Invoke->getNormalDest()->getFirstInsertionPt();
  390. else
  391. InsertBefore = std::next(Inst->getIterator());
  392. CGBuilderTy(CGM, &*InsertBefore).CreateStore(Inst, Tmp);
  393. // Reload the value at the current insertion point.
  394. *ReloadedValue = Builder.CreateLoad(Tmp);
  395. }
  396. }
  397. /// Pops cleanup blocks until the given savepoint is reached, then add the
  398. /// cleanups from the given savepoint in the lifetime-extended cleanups stack.
  399. void CodeGenFunction::PopCleanupBlocks(
  400. EHScopeStack::stable_iterator Old, size_t OldLifetimeExtendedSize,
  401. std::initializer_list<llvm::Value **> ValuesToReload) {
  402. PopCleanupBlocks(Old, ValuesToReload);
  403. // Move our deferred cleanups onto the EH stack.
  404. for (size_t I = OldLifetimeExtendedSize,
  405. E = LifetimeExtendedCleanupStack.size(); I != E; /**/) {
  406. // Alignment should be guaranteed by the vptrs in the individual cleanups.
  407. assert((I % alignof(LifetimeExtendedCleanupHeader) == 0) &&
  408. "misaligned cleanup stack entry");
  409. LifetimeExtendedCleanupHeader &Header =
  410. reinterpret_cast<LifetimeExtendedCleanupHeader&>(
  411. LifetimeExtendedCleanupStack[I]);
  412. I += sizeof(Header);
  413. EHStack.pushCopyOfCleanup(Header.getKind(),
  414. &LifetimeExtendedCleanupStack[I],
  415. Header.getSize());
  416. I += Header.getSize();
  417. if (Header.isConditional()) {
  418. Address ActiveFlag =
  419. reinterpret_cast<Address &>(LifetimeExtendedCleanupStack[I]);
  420. initFullExprCleanupWithFlag(ActiveFlag);
  421. I += sizeof(ActiveFlag);
  422. }
  423. }
  424. LifetimeExtendedCleanupStack.resize(OldLifetimeExtendedSize);
  425. }
  426. static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
  427. EHCleanupScope &Scope) {
  428. assert(Scope.isNormalCleanup());
  429. llvm::BasicBlock *Entry = Scope.getNormalBlock();
  430. if (!Entry) {
  431. Entry = CGF.createBasicBlock("cleanup");
  432. Scope.setNormalBlock(Entry);
  433. }
  434. return Entry;
  435. }
  436. /// Attempts to reduce a cleanup's entry block to a fallthrough. This
  437. /// is basically llvm::MergeBlockIntoPredecessor, except
  438. /// simplified/optimized for the tighter constraints on cleanup blocks.
  439. ///
  440. /// Returns the new block, whatever it is.
  441. static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,
  442. llvm::BasicBlock *Entry) {
  443. llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
  444. if (!Pred) return Entry;
  445. llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
  446. if (!Br || Br->isConditional()) return Entry;
  447. assert(Br->getSuccessor(0) == Entry);
  448. // If we were previously inserting at the end of the cleanup entry
  449. // block, we'll need to continue inserting at the end of the
  450. // predecessor.
  451. bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
  452. assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
  453. // Kill the branch.
  454. Br->eraseFromParent();
  455. // Replace all uses of the entry with the predecessor, in case there
  456. // are phis in the cleanup.
  457. Entry->replaceAllUsesWith(Pred);
  458. // Merge the blocks.
  459. Pred->getInstList().splice(Pred->end(), Entry->getInstList());
  460. // Kill the entry block.
  461. Entry->eraseFromParent();
  462. if (WasInsertBlock)
  463. CGF.Builder.SetInsertPoint(Pred);
  464. return Pred;
  465. }
  466. static void EmitCleanup(CodeGenFunction &CGF,
  467. EHScopeStack::Cleanup *Fn,
  468. EHScopeStack::Cleanup::Flags flags,
  469. Address ActiveFlag) {
  470. // If there's an active flag, load it and skip the cleanup if it's
  471. // false.
  472. llvm::BasicBlock *ContBB = nullptr;
  473. if (ActiveFlag.isValid()) {
  474. ContBB = CGF.createBasicBlock("cleanup.done");
  475. llvm::BasicBlock *CleanupBB = CGF.createBasicBlock("cleanup.action");
  476. llvm::Value *IsActive
  477. = CGF.Builder.CreateLoad(ActiveFlag, "cleanup.is_active");
  478. CGF.Builder.CreateCondBr(IsActive, CleanupBB, ContBB);
  479. CGF.EmitBlock(CleanupBB);
  480. }
  481. // Ask the cleanup to emit itself.
  482. Fn->Emit(CGF, flags);
  483. assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
  484. // Emit the continuation block if there was an active flag.
  485. if (ActiveFlag.isValid())
  486. CGF.EmitBlock(ContBB);
  487. }
  488. static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit,
  489. llvm::BasicBlock *From,
  490. llvm::BasicBlock *To) {
  491. // Exit is the exit block of a cleanup, so it always terminates in
  492. // an unconditional branch or a switch.
  493. llvm::Instruction *Term = Exit->getTerminator();
  494. if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
  495. assert(Br->isUnconditional() && Br->getSuccessor(0) == From);
  496. Br->setSuccessor(0, To);
  497. } else {
  498. llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Term);
  499. for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I)
  500. if (Switch->getSuccessor(I) == From)
  501. Switch->setSuccessor(I, To);
  502. }
  503. }
  504. /// We don't need a normal entry block for the given cleanup.
  505. /// Optimistic fixup branches can cause these blocks to come into
  506. /// existence anyway; if so, destroy it.
  507. ///
  508. /// The validity of this transformation is very much specific to the
  509. /// exact ways in which we form branches to cleanup entries.
  510. static void destroyOptimisticNormalEntry(CodeGenFunction &CGF,
  511. EHCleanupScope &scope) {
  512. llvm::BasicBlock *entry = scope.getNormalBlock();
  513. if (!entry) return;
  514. // Replace all the uses with unreachable.
  515. llvm::BasicBlock *unreachableBB = CGF.getUnreachableBlock();
  516. for (llvm::BasicBlock::use_iterator
  517. i = entry->use_begin(), e = entry->use_end(); i != e; ) {
  518. llvm::Use &use = *i;
  519. ++i;
  520. use.set(unreachableBB);
  521. // The only uses should be fixup switches.
  522. llvm::SwitchInst *si = cast<llvm::SwitchInst>(use.getUser());
  523. if (si->getNumCases() == 1 && si->getDefaultDest() == unreachableBB) {
  524. // Replace the switch with a branch.
  525. llvm::BranchInst::Create(si->case_begin()->getCaseSuccessor(), si);
  526. // The switch operand is a load from the cleanup-dest alloca.
  527. llvm::LoadInst *condition = cast<llvm::LoadInst>(si->getCondition());
  528. // Destroy the switch.
  529. si->eraseFromParent();
  530. // Destroy the load.
  531. assert(condition->getOperand(0) == CGF.NormalCleanupDest.getPointer());
  532. assert(condition->use_empty());
  533. condition->eraseFromParent();
  534. }
  535. }
  536. assert(entry->use_empty());
  537. delete entry;
  538. }
  539. /// Pops a cleanup block. If the block includes a normal cleanup, the
  540. /// current insertion point is threaded through the cleanup, as are
  541. /// any branch fixups on the cleanup.
  542. void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
  543. assert(!EHStack.empty() && "cleanup stack is empty!");
  544. assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
  545. EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
  546. assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
  547. // Remember activation information.
  548. bool IsActive = Scope.isActive();
  549. Address NormalActiveFlag =
  550. Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag()
  551. : Address::invalid();
  552. Address EHActiveFlag =
  553. Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag()
  554. : Address::invalid();
  555. // Check whether we need an EH cleanup. This is only true if we've
  556. // generated a lazy EH cleanup block.
  557. llvm::BasicBlock *EHEntry = Scope.getCachedEHDispatchBlock();
  558. assert(Scope.hasEHBranches() == (EHEntry != nullptr));
  559. bool RequiresEHCleanup = (EHEntry != nullptr);
  560. EHScopeStack::stable_iterator EHParent = Scope.getEnclosingEHScope();
  561. // Check the three conditions which might require a normal cleanup:
  562. // - whether there are branch fix-ups through this cleanup
  563. unsigned FixupDepth = Scope.getFixupDepth();
  564. bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
  565. // - whether there are branch-throughs or branch-afters
  566. bool HasExistingBranches = Scope.hasBranches();
  567. // - whether there's a fallthrough
  568. llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
  569. bool HasFallthrough = (FallthroughSource != nullptr && IsActive);
  570. // Branch-through fall-throughs leave the insertion point set to the
  571. // end of the last cleanup, which points to the current scope. The
  572. // rest of IR gen doesn't need to worry about this; it only happens
  573. // during the execution of PopCleanupBlocks().
  574. bool HasPrebranchedFallthrough =
  575. (FallthroughSource && FallthroughSource->getTerminator());
  576. // If this is a normal cleanup, then having a prebranched
  577. // fallthrough implies that the fallthrough source unconditionally
  578. // jumps here.
  579. assert(!Scope.isNormalCleanup() || !HasPrebranchedFallthrough ||
  580. (Scope.getNormalBlock() &&
  581. FallthroughSource->getTerminator()->getSuccessor(0)
  582. == Scope.getNormalBlock()));
  583. bool RequiresNormalCleanup = false;
  584. if (Scope.isNormalCleanup() &&
  585. (HasFixups || HasExistingBranches || HasFallthrough)) {
  586. RequiresNormalCleanup = true;
  587. }
  588. // If we have a prebranched fallthrough into an inactive normal
  589. // cleanup, rewrite it so that it leads to the appropriate place.
  590. if (Scope.isNormalCleanup() && HasPrebranchedFallthrough && !IsActive) {
  591. llvm::BasicBlock *prebranchDest;
  592. // If the prebranch is semantically branching through the next
  593. // cleanup, just forward it to the next block, leaving the
  594. // insertion point in the prebranched block.
  595. if (FallthroughIsBranchThrough) {
  596. EHScope &enclosing = *EHStack.find(Scope.getEnclosingNormalCleanup());
  597. prebranchDest = CreateNormalEntry(*this, cast<EHCleanupScope>(enclosing));
  598. // Otherwise, we need to make a new block. If the normal cleanup
  599. // isn't being used at all, we could actually reuse the normal
  600. // entry block, but this is simpler, and it avoids conflicts with
  601. // dead optimistic fixup branches.
  602. } else {
  603. prebranchDest = createBasicBlock("forwarded-prebranch");
  604. EmitBlock(prebranchDest);
  605. }
  606. llvm::BasicBlock *normalEntry = Scope.getNormalBlock();
  607. assert(normalEntry && !normalEntry->use_empty());
  608. ForwardPrebranchedFallthrough(FallthroughSource,
  609. normalEntry, prebranchDest);
  610. }
  611. // If we don't need the cleanup at all, we're done.
  612. if (!RequiresNormalCleanup && !RequiresEHCleanup) {
  613. destroyOptimisticNormalEntry(*this, Scope);
  614. EHStack.popCleanup(); // safe because there are no fixups
  615. assert(EHStack.getNumBranchFixups() == 0 ||
  616. EHStack.hasNormalCleanups());
  617. return;
  618. }
  619. // Copy the cleanup emission data out. This uses either a stack
  620. // array or malloc'd memory, depending on the size, which is
  621. // behavior that SmallVector would provide, if we could use it
  622. // here. Unfortunately, if you ask for a SmallVector<char>, the
  623. // alignment isn't sufficient.
  624. auto *CleanupSource = reinterpret_cast<char *>(Scope.getCleanupBuffer());
  625. alignas(EHScopeStack::ScopeStackAlignment) char
  626. CleanupBufferStack[8 * sizeof(void *)];
  627. std::unique_ptr<char[]> CleanupBufferHeap;
  628. size_t CleanupSize = Scope.getCleanupSize();
  629. EHScopeStack::Cleanup *Fn;
  630. if (CleanupSize <= sizeof(CleanupBufferStack)) {
  631. memcpy(CleanupBufferStack, CleanupSource, CleanupSize);
  632. Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferStack);
  633. } else {
  634. CleanupBufferHeap.reset(new char[CleanupSize]);
  635. memcpy(CleanupBufferHeap.get(), CleanupSource, CleanupSize);
  636. Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferHeap.get());
  637. }
  638. EHScopeStack::Cleanup::Flags cleanupFlags;
  639. if (Scope.isNormalCleanup())
  640. cleanupFlags.setIsNormalCleanupKind();
  641. if (Scope.isEHCleanup())
  642. cleanupFlags.setIsEHCleanupKind();
  643. // Under -EHa, invoke seh.scope.end() to mark scope end before dtor
  644. bool IsEHa = getLangOpts().EHAsynch && !Scope.isLifetimeMarker();
  645. const EHPersonality &Personality = EHPersonality::get(*this);
  646. if (!RequiresNormalCleanup) {
  647. // Mark CPP scope end for passed-by-value Arg temp
  648. // per Windows ABI which is "normally" Cleanup in callee
  649. if (IsEHa && getInvokeDest()) {
  650. if (Personality.isMSVCXXPersonality())
  651. EmitSehCppScopeEnd();
  652. }
  653. destroyOptimisticNormalEntry(*this, Scope);
  654. EHStack.popCleanup();
  655. } else {
  656. // If we have a fallthrough and no other need for the cleanup,
  657. // emit it directly.
  658. if (HasFallthrough && !HasPrebranchedFallthrough && !HasFixups &&
  659. !HasExistingBranches) {
  660. // mark SEH scope end for fall-through flow
  661. if (IsEHa && getInvokeDest()) {
  662. if (Personality.isMSVCXXPersonality())
  663. EmitSehCppScopeEnd();
  664. else
  665. EmitSehTryScopeEnd();
  666. }
  667. destroyOptimisticNormalEntry(*this, Scope);
  668. EHStack.popCleanup();
  669. EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
  670. // Otherwise, the best approach is to thread everything through
  671. // the cleanup block and then try to clean up after ourselves.
  672. } else {
  673. // Force the entry block to exist.
  674. llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
  675. // I. Set up the fallthrough edge in.
  676. CGBuilderTy::InsertPoint savedInactiveFallthroughIP;
  677. // If there's a fallthrough, we need to store the cleanup
  678. // destination index. For fall-throughs this is always zero.
  679. if (HasFallthrough) {
  680. if (!HasPrebranchedFallthrough)
  681. Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
  682. // Otherwise, save and clear the IP if we don't have fallthrough
  683. // because the cleanup is inactive.
  684. } else if (FallthroughSource) {
  685. assert(!IsActive && "source without fallthrough for active cleanup");
  686. savedInactiveFallthroughIP = Builder.saveAndClearIP();
  687. }
  688. // II. Emit the entry block. This implicitly branches to it if
  689. // we have fallthrough. All the fixups and existing branches
  690. // should already be branched to it.
  691. EmitBlock(NormalEntry);
  692. // intercept normal cleanup to mark SEH scope end
  693. if (IsEHa) {
  694. if (Personality.isMSVCXXPersonality())
  695. EmitSehCppScopeEnd();
  696. else
  697. EmitSehTryScopeEnd();
  698. }
  699. // III. Figure out where we're going and build the cleanup
  700. // epilogue.
  701. bool HasEnclosingCleanups =
  702. (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
  703. // Compute the branch-through dest if we need it:
  704. // - if there are branch-throughs threaded through the scope
  705. // - if fall-through is a branch-through
  706. // - if there are fixups that will be optimistically forwarded
  707. // to the enclosing cleanup
  708. llvm::BasicBlock *BranchThroughDest = nullptr;
  709. if (Scope.hasBranchThroughs() ||
  710. (FallthroughSource && FallthroughIsBranchThrough) ||
  711. (HasFixups && HasEnclosingCleanups)) {
  712. assert(HasEnclosingCleanups);
  713. EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
  714. BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
  715. }
  716. llvm::BasicBlock *FallthroughDest = nullptr;
  717. SmallVector<llvm::Instruction*, 2> InstsToAppend;
  718. // If there's exactly one branch-after and no other threads,
  719. // we can route it without a switch.
  720. if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
  721. Scope.getNumBranchAfters() == 1) {
  722. assert(!BranchThroughDest || !IsActive);
  723. // Clean up the possibly dead store to the cleanup dest slot.
  724. llvm::Instruction *NormalCleanupDestSlot =
  725. cast<llvm::Instruction>(getNormalCleanupDestSlot().getPointer());
  726. if (NormalCleanupDestSlot->hasOneUse()) {
  727. NormalCleanupDestSlot->user_back()->eraseFromParent();
  728. NormalCleanupDestSlot->eraseFromParent();
  729. NormalCleanupDest = Address::invalid();
  730. }
  731. llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
  732. InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
  733. // Build a switch-out if we need it:
  734. // - if there are branch-afters threaded through the scope
  735. // - if fall-through is a branch-after
  736. // - if there are fixups that have nowhere left to go and
  737. // so must be immediately resolved
  738. } else if (Scope.getNumBranchAfters() ||
  739. (HasFallthrough && !FallthroughIsBranchThrough) ||
  740. (HasFixups && !HasEnclosingCleanups)) {
  741. llvm::BasicBlock *Default =
  742. (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
  743. // TODO: base this on the number of branch-afters and fixups
  744. const unsigned SwitchCapacity = 10;
  745. // pass the abnormal exit flag to Fn (SEH cleanup)
  746. cleanupFlags.setHasExitSwitch();
  747. llvm::LoadInst *Load =
  748. createLoadInstBefore(getNormalCleanupDestSlot(), "cleanup.dest",
  749. nullptr);
  750. llvm::SwitchInst *Switch =
  751. llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
  752. InstsToAppend.push_back(Load);
  753. InstsToAppend.push_back(Switch);
  754. // Branch-after fallthrough.
  755. if (FallthroughSource && !FallthroughIsBranchThrough) {
  756. FallthroughDest = createBasicBlock("cleanup.cont");
  757. if (HasFallthrough)
  758. Switch->addCase(Builder.getInt32(0), FallthroughDest);
  759. }
  760. for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
  761. Switch->addCase(Scope.getBranchAfterIndex(I),
  762. Scope.getBranchAfterBlock(I));
  763. }
  764. // If there aren't any enclosing cleanups, we can resolve all
  765. // the fixups now.
  766. if (HasFixups && !HasEnclosingCleanups)
  767. ResolveAllBranchFixups(*this, Switch, NormalEntry);
  768. } else {
  769. // We should always have a branch-through destination in this case.
  770. assert(BranchThroughDest);
  771. InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
  772. }
  773. // IV. Pop the cleanup and emit it.
  774. EHStack.popCleanup();
  775. assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
  776. EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
  777. // Append the prepared cleanup prologue from above.
  778. llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
  779. for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)
  780. NormalExit->getInstList().push_back(InstsToAppend[I]);
  781. // Optimistically hope that any fixups will continue falling through.
  782. for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
  783. I < E; ++I) {
  784. BranchFixup &Fixup = EHStack.getBranchFixup(I);
  785. if (!Fixup.Destination) continue;
  786. if (!Fixup.OptimisticBranchBlock) {
  787. createStoreInstBefore(Builder.getInt32(Fixup.DestinationIndex),
  788. getNormalCleanupDestSlot(),
  789. Fixup.InitialBranch);
  790. Fixup.InitialBranch->setSuccessor(0, NormalEntry);
  791. }
  792. Fixup.OptimisticBranchBlock = NormalExit;
  793. }
  794. // V. Set up the fallthrough edge out.
  795. // Case 1: a fallthrough source exists but doesn't branch to the
  796. // cleanup because the cleanup is inactive.
  797. if (!HasFallthrough && FallthroughSource) {
  798. // Prebranched fallthrough was forwarded earlier.
  799. // Non-prebranched fallthrough doesn't need to be forwarded.
  800. // Either way, all we need to do is restore the IP we cleared before.
  801. assert(!IsActive);
  802. Builder.restoreIP(savedInactiveFallthroughIP);
  803. // Case 2: a fallthrough source exists and should branch to the
  804. // cleanup, but we're not supposed to branch through to the next
  805. // cleanup.
  806. } else if (HasFallthrough && FallthroughDest) {
  807. assert(!FallthroughIsBranchThrough);
  808. EmitBlock(FallthroughDest);
  809. // Case 3: a fallthrough source exists and should branch to the
  810. // cleanup and then through to the next.
  811. } else if (HasFallthrough) {
  812. // Everything is already set up for this.
  813. // Case 4: no fallthrough source exists.
  814. } else {
  815. Builder.ClearInsertionPoint();
  816. }
  817. // VI. Assorted cleaning.
  818. // Check whether we can merge NormalEntry into a single predecessor.
  819. // This might invalidate (non-IR) pointers to NormalEntry.
  820. llvm::BasicBlock *NewNormalEntry =
  821. SimplifyCleanupEntry(*this, NormalEntry);
  822. // If it did invalidate those pointers, and NormalEntry was the same
  823. // as NormalExit, go back and patch up the fixups.
  824. if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
  825. for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
  826. I < E; ++I)
  827. EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
  828. }
  829. }
  830. assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
  831. // Emit the EH cleanup if required.
  832. if (RequiresEHCleanup) {
  833. CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
  834. EmitBlock(EHEntry);
  835. llvm::BasicBlock *NextAction = getEHDispatchBlock(EHParent);
  836. // Push a terminate scope or cleanupendpad scope around the potentially
  837. // throwing cleanups. For funclet EH personalities, the cleanupendpad models
  838. // program termination when cleanups throw.
  839. bool PushedTerminate = false;
  840. SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
  841. CurrentFuncletPad);
  842. llvm::CleanupPadInst *CPI = nullptr;
  843. const EHPersonality &Personality = EHPersonality::get(*this);
  844. if (Personality.usesFuncletPads()) {
  845. llvm::Value *ParentPad = CurrentFuncletPad;
  846. if (!ParentPad)
  847. ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
  848. CurrentFuncletPad = CPI = Builder.CreateCleanupPad(ParentPad);
  849. }
  850. // Non-MSVC personalities need to terminate when an EH cleanup throws.
  851. if (!Personality.isMSVCPersonality()) {
  852. EHStack.pushTerminate();
  853. PushedTerminate = true;
  854. }
  855. // We only actually emit the cleanup code if the cleanup is either
  856. // active or was used before it was deactivated.
  857. if (EHActiveFlag.isValid() || IsActive) {
  858. cleanupFlags.setIsForEHCleanup();
  859. EmitCleanup(*this, Fn, cleanupFlags, EHActiveFlag);
  860. }
  861. if (CPI)
  862. Builder.CreateCleanupRet(CPI, NextAction);
  863. else
  864. Builder.CreateBr(NextAction);
  865. // Leave the terminate scope.
  866. if (PushedTerminate)
  867. EHStack.popTerminate();
  868. Builder.restoreIP(SavedIP);
  869. SimplifyCleanupEntry(*this, EHEntry);
  870. }
  871. }
  872. /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
  873. /// specified destination obviously has no cleanups to run. 'false' is always
  874. /// a conservatively correct answer for this method.
  875. bool CodeGenFunction::isObviouslyBranchWithoutCleanups(JumpDest Dest) const {
  876. assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
  877. && "stale jump destination");
  878. // Calculate the innermost active normal cleanup.
  879. EHScopeStack::stable_iterator TopCleanup =
  880. EHStack.getInnermostActiveNormalCleanup();
  881. // If we're not in an active normal cleanup scope, or if the
  882. // destination scope is within the innermost active normal cleanup
  883. // scope, we don't need to worry about fixups.
  884. if (TopCleanup == EHStack.stable_end() ||
  885. TopCleanup.encloses(Dest.getScopeDepth())) // works for invalid
  886. return true;
  887. // Otherwise, we might need some cleanups.
  888. return false;
  889. }
  890. /// Terminate the current block by emitting a branch which might leave
  891. /// the current cleanup-protected scope. The target scope may not yet
  892. /// be known, in which case this will require a fixup.
  893. ///
  894. /// As a side-effect, this method clears the insertion point.
  895. void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
  896. assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
  897. && "stale jump destination");
  898. if (!HaveInsertPoint())
  899. return;
  900. // Create the branch.
  901. llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
  902. // Calculate the innermost active normal cleanup.
  903. EHScopeStack::stable_iterator
  904. TopCleanup = EHStack.getInnermostActiveNormalCleanup();
  905. // If we're not in an active normal cleanup scope, or if the
  906. // destination scope is within the innermost active normal cleanup
  907. // scope, we don't need to worry about fixups.
  908. if (TopCleanup == EHStack.stable_end() ||
  909. TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid
  910. Builder.ClearInsertionPoint();
  911. return;
  912. }
  913. // If we can't resolve the destination cleanup scope, just add this
  914. // to the current cleanup scope as a branch fixup.
  915. if (!Dest.getScopeDepth().isValid()) {
  916. BranchFixup &Fixup = EHStack.addBranchFixup();
  917. Fixup.Destination = Dest.getBlock();
  918. Fixup.DestinationIndex = Dest.getDestIndex();
  919. Fixup.InitialBranch = BI;
  920. Fixup.OptimisticBranchBlock = nullptr;
  921. Builder.ClearInsertionPoint();
  922. return;
  923. }
  924. // Otherwise, thread through all the normal cleanups in scope.
  925. // Store the index at the start.
  926. llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
  927. createStoreInstBefore(Index, getNormalCleanupDestSlot(), BI);
  928. // Adjust BI to point to the first cleanup block.
  929. {
  930. EHCleanupScope &Scope =
  931. cast<EHCleanupScope>(*EHStack.find(TopCleanup));
  932. BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
  933. }
  934. // Add this destination to all the scopes involved.
  935. EHScopeStack::stable_iterator I = TopCleanup;
  936. EHScopeStack::stable_iterator E = Dest.getScopeDepth();
  937. if (E.strictlyEncloses(I)) {
  938. while (true) {
  939. EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
  940. assert(Scope.isNormalCleanup());
  941. I = Scope.getEnclosingNormalCleanup();
  942. // If this is the last cleanup we're propagating through, tell it
  943. // that there's a resolved jump moving through it.
  944. if (!E.strictlyEncloses(I)) {
  945. Scope.addBranchAfter(Index, Dest.getBlock());
  946. break;
  947. }
  948. // Otherwise, tell the scope that there's a jump propagating
  949. // through it. If this isn't new information, all the rest of
  950. // the work has been done before.
  951. if (!Scope.addBranchThrough(Dest.getBlock()))
  952. break;
  953. }
  954. }
  955. Builder.ClearInsertionPoint();
  956. }
  957. static bool IsUsedAsNormalCleanup(EHScopeStack &EHStack,
  958. EHScopeStack::stable_iterator C) {
  959. // If we needed a normal block for any reason, that counts.
  960. if (cast<EHCleanupScope>(*EHStack.find(C)).getNormalBlock())
  961. return true;
  962. // Check whether any enclosed cleanups were needed.
  963. for (EHScopeStack::stable_iterator
  964. I = EHStack.getInnermostNormalCleanup();
  965. I != C; ) {
  966. assert(C.strictlyEncloses(I));
  967. EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
  968. if (S.getNormalBlock()) return true;
  969. I = S.getEnclosingNormalCleanup();
  970. }
  971. return false;
  972. }
  973. static bool IsUsedAsEHCleanup(EHScopeStack &EHStack,
  974. EHScopeStack::stable_iterator cleanup) {
  975. // If we needed an EH block for any reason, that counts.
  976. if (EHStack.find(cleanup)->hasEHBranches())
  977. return true;
  978. // Check whether any enclosed cleanups were needed.
  979. for (EHScopeStack::stable_iterator
  980. i = EHStack.getInnermostEHScope(); i != cleanup; ) {
  981. assert(cleanup.strictlyEncloses(i));
  982. EHScope &scope = *EHStack.find(i);
  983. if (scope.hasEHBranches())
  984. return true;
  985. i = scope.getEnclosingEHScope();
  986. }
  987. return false;
  988. }
  989. enum ForActivation_t {
  990. ForActivation,
  991. ForDeactivation
  992. };
  993. /// The given cleanup block is changing activation state. Configure a
  994. /// cleanup variable if necessary.
  995. ///
  996. /// It would be good if we had some way of determining if there were
  997. /// extra uses *after* the change-over point.
  998. static void SetupCleanupBlockActivation(CodeGenFunction &CGF,
  999. EHScopeStack::stable_iterator C,
  1000. ForActivation_t kind,
  1001. llvm::Instruction *dominatingIP) {
  1002. EHCleanupScope &Scope = cast<EHCleanupScope>(*CGF.EHStack.find(C));
  1003. // We always need the flag if we're activating the cleanup in a
  1004. // conditional context, because we have to assume that the current
  1005. // location doesn't necessarily dominate the cleanup's code.
  1006. bool isActivatedInConditional =
  1007. (kind == ForActivation && CGF.isInConditionalBranch());
  1008. bool needFlag = false;
  1009. // Calculate whether the cleanup was used:
  1010. // - as a normal cleanup
  1011. if (Scope.isNormalCleanup() &&
  1012. (isActivatedInConditional || IsUsedAsNormalCleanup(CGF.EHStack, C))) {
  1013. Scope.setTestFlagInNormalCleanup();
  1014. needFlag = true;
  1015. }
  1016. // - as an EH cleanup
  1017. if (Scope.isEHCleanup() &&
  1018. (isActivatedInConditional || IsUsedAsEHCleanup(CGF.EHStack, C))) {
  1019. Scope.setTestFlagInEHCleanup();
  1020. needFlag = true;
  1021. }
  1022. // If it hasn't yet been used as either, we're done.
  1023. if (!needFlag) return;
  1024. Address var = Scope.getActiveFlag();
  1025. if (!var.isValid()) {
  1026. var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), CharUnits::One(),
  1027. "cleanup.isactive");
  1028. Scope.setActiveFlag(var);
  1029. assert(dominatingIP && "no existing variable and no dominating IP!");
  1030. // Initialize to true or false depending on whether it was
  1031. // active up to this point.
  1032. llvm::Constant *value = CGF.Builder.getInt1(kind == ForDeactivation);
  1033. // If we're in a conditional block, ignore the dominating IP and
  1034. // use the outermost conditional branch.
  1035. if (CGF.isInConditionalBranch()) {
  1036. CGF.setBeforeOutermostConditional(value, var);
  1037. } else {
  1038. createStoreInstBefore(value, var, dominatingIP);
  1039. }
  1040. }
  1041. CGF.Builder.CreateStore(CGF.Builder.getInt1(kind == ForActivation), var);
  1042. }
  1043. /// Activate a cleanup that was created in an inactivated state.
  1044. void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C,
  1045. llvm::Instruction *dominatingIP) {
  1046. assert(C != EHStack.stable_end() && "activating bottom of stack?");
  1047. EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
  1048. assert(!Scope.isActive() && "double activation");
  1049. SetupCleanupBlockActivation(*this, C, ForActivation, dominatingIP);
  1050. Scope.setActive(true);
  1051. }
  1052. /// Deactive a cleanup that was created in an active state.
  1053. void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C,
  1054. llvm::Instruction *dominatingIP) {
  1055. assert(C != EHStack.stable_end() && "deactivating bottom of stack?");
  1056. EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
  1057. assert(Scope.isActive() && "double deactivation");
  1058. // If it's the top of the stack, just pop it, but do so only if it belongs
  1059. // to the current RunCleanupsScope.
  1060. if (C == EHStack.stable_begin() &&
  1061. CurrentCleanupScopeDepth.strictlyEncloses(C)) {
  1062. // Per comment below, checking EHAsynch is not really necessary
  1063. // it's there to assure zero-impact w/o EHAsynch option
  1064. if (!Scope.isNormalCleanup() && getLangOpts().EHAsynch) {
  1065. PopCleanupBlock();
  1066. } else {
  1067. // If it's a normal cleanup, we need to pretend that the
  1068. // fallthrough is unreachable.
  1069. CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
  1070. PopCleanupBlock();
  1071. Builder.restoreIP(SavedIP);
  1072. }
  1073. return;
  1074. }
  1075. // Otherwise, follow the general case.
  1076. SetupCleanupBlockActivation(*this, C, ForDeactivation, dominatingIP);
  1077. Scope.setActive(false);
  1078. }
  1079. Address CodeGenFunction::getNormalCleanupDestSlot() {
  1080. if (!NormalCleanupDest.isValid())
  1081. NormalCleanupDest =
  1082. CreateDefaultAlignTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
  1083. return NormalCleanupDest;
  1084. }
  1085. /// Emits all the code to cause the given temporary to be cleaned up.
  1086. void CodeGenFunction::EmitCXXTemporary(const CXXTemporary *Temporary,
  1087. QualType TempType,
  1088. Address Ptr) {
  1089. pushDestroy(NormalAndEHCleanup, Ptr, TempType, destroyCXXObject,
  1090. /*useEHCleanup*/ true);
  1091. }
  1092. // Need to set "funclet" in OperandBundle properly for noThrow
  1093. // intrinsic (see CGCall.cpp)
  1094. static void EmitSehScope(CodeGenFunction &CGF,
  1095. llvm::FunctionCallee &SehCppScope) {
  1096. llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
  1097. assert(CGF.Builder.GetInsertBlock() && InvokeDest);
  1098. llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
  1099. SmallVector<llvm::OperandBundleDef, 1> BundleList =
  1100. CGF.getBundlesForFunclet(SehCppScope.getCallee());
  1101. if (CGF.CurrentFuncletPad)
  1102. BundleList.emplace_back("funclet", CGF.CurrentFuncletPad);
  1103. CGF.Builder.CreateInvoke(SehCppScope, Cont, InvokeDest, None, BundleList);
  1104. CGF.EmitBlock(Cont);
  1105. }
  1106. // Invoke a llvm.seh.scope.begin at the beginning of a CPP scope for -EHa
  1107. void CodeGenFunction::EmitSehCppScopeBegin() {
  1108. assert(getLangOpts().EHAsynch);
  1109. llvm::FunctionType *FTy =
  1110. llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
  1111. llvm::FunctionCallee SehCppScope =
  1112. CGM.CreateRuntimeFunction(FTy, "llvm.seh.scope.begin");
  1113. EmitSehScope(*this, SehCppScope);
  1114. }
  1115. // Invoke a llvm.seh.scope.end at the end of a CPP scope for -EHa
  1116. // llvm.seh.scope.end is emitted before popCleanup, so it's "invoked"
  1117. void CodeGenFunction::EmitSehCppScopeEnd() {
  1118. assert(getLangOpts().EHAsynch);
  1119. llvm::FunctionType *FTy =
  1120. llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
  1121. llvm::FunctionCallee SehCppScope =
  1122. CGM.CreateRuntimeFunction(FTy, "llvm.seh.scope.end");
  1123. EmitSehScope(*this, SehCppScope);
  1124. }
  1125. // Invoke a llvm.seh.try.begin at the beginning of a SEH scope for -EHa
  1126. void CodeGenFunction::EmitSehTryScopeBegin() {
  1127. assert(getLangOpts().EHAsynch);
  1128. llvm::FunctionType *FTy =
  1129. llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
  1130. llvm::FunctionCallee SehCppScope =
  1131. CGM.CreateRuntimeFunction(FTy, "llvm.seh.try.begin");
  1132. EmitSehScope(*this, SehCppScope);
  1133. }
  1134. // Invoke a llvm.seh.try.end at the end of a SEH scope for -EHa
  1135. void CodeGenFunction::EmitSehTryScopeEnd() {
  1136. assert(getLangOpts().EHAsynch);
  1137. llvm::FunctionType *FTy =
  1138. llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
  1139. llvm::FunctionCallee SehCppScope =
  1140. CGM.CreateRuntimeFunction(FTy, "llvm.seh.try.end");
  1141. EmitSehScope(*this, SehCppScope);
  1142. }