Coverage Report

Created: 2019-07-24 05:18

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