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