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