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