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