clang API Documentation

CGCleanup.h
Go to the documentation of this file.
00001 //===-- CGCleanup.h - Classes for cleanups IR generation --------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // These classes support the generation of LLVM IR for cleanups.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #ifndef CLANG_CODEGEN_CGCLEANUP_H
00015 #define CLANG_CODEGEN_CGCLEANUP_H
00016 
00017 /// EHScopeStack is defined in CodeGenFunction.h, but its
00018 /// implementation is in this file and in CGCleanup.cpp.
00019 #include "CodeGenFunction.h"
00020 
00021 namespace llvm {
00022   class Value;
00023   class BasicBlock;
00024 }
00025 
00026 namespace clang {
00027 namespace CodeGen {
00028 
00029 /// A protected scope for zero-cost EH handling.
00030 class EHScope {
00031   llvm::BasicBlock *CachedLandingPad;
00032   llvm::BasicBlock *CachedEHDispatchBlock;
00033 
00034   EHScopeStack::stable_iterator EnclosingEHScope;
00035 
00036   class CommonBitFields {
00037     friend class EHScope;
00038     unsigned Kind : 2;
00039   };
00040   enum { NumCommonBits = 2 };
00041 
00042 protected:
00043   class CatchBitFields {
00044     friend class EHCatchScope;
00045     unsigned : NumCommonBits;
00046 
00047     unsigned NumHandlers : 32 - NumCommonBits;
00048   };
00049 
00050   class CleanupBitFields {
00051     friend class EHCleanupScope;
00052     unsigned : NumCommonBits;
00053 
00054     /// Whether this cleanup needs to be run along normal edges.
00055     unsigned IsNormalCleanup : 1;
00056 
00057     /// Whether this cleanup needs to be run along exception edges.
00058     unsigned IsEHCleanup : 1;
00059 
00060     /// Whether this cleanup is currently active.
00061     unsigned IsActive : 1;
00062 
00063     /// Whether the normal cleanup should test the activation flag.
00064     unsigned TestFlagInNormalCleanup : 1;
00065 
00066     /// Whether the EH cleanup should test the activation flag.
00067     unsigned TestFlagInEHCleanup : 1;
00068 
00069     /// The amount of extra storage needed by the Cleanup.
00070     /// Always a multiple of the scope-stack alignment.
00071     unsigned CleanupSize : 12;
00072 
00073     /// The number of fixups required by enclosing scopes (not including
00074     /// this one).  If this is the top cleanup scope, all the fixups
00075     /// from this index onwards belong to this scope.
00076     unsigned FixupDepth : 32 - 17 - NumCommonBits; // currently 13    
00077   };
00078 
00079   class FilterBitFields {
00080     friend class EHFilterScope;
00081     unsigned : NumCommonBits;
00082 
00083     unsigned NumFilters : 32 - NumCommonBits;
00084   };
00085 
00086   union {
00087     CommonBitFields CommonBits;
00088     CatchBitFields CatchBits;
00089     CleanupBitFields CleanupBits;
00090     FilterBitFields FilterBits;
00091   };
00092 
00093 public:
00094   enum Kind { Cleanup, Catch, Terminate, Filter };
00095 
00096   EHScope(Kind kind, EHScopeStack::stable_iterator enclosingEHScope)
00097     : CachedLandingPad(0), CachedEHDispatchBlock(0),
00098       EnclosingEHScope(enclosingEHScope) {
00099     CommonBits.Kind = kind;
00100   }
00101 
00102   Kind getKind() const { return static_cast<Kind>(CommonBits.Kind); }
00103 
00104   llvm::BasicBlock *getCachedLandingPad() const {
00105     return CachedLandingPad;
00106   }
00107 
00108   void setCachedLandingPad(llvm::BasicBlock *block) {
00109     CachedLandingPad = block;
00110   }
00111 
00112   llvm::BasicBlock *getCachedEHDispatchBlock() const {
00113     return CachedEHDispatchBlock;
00114   }
00115 
00116   void setCachedEHDispatchBlock(llvm::BasicBlock *block) {
00117     CachedEHDispatchBlock = block;
00118   }
00119 
00120   bool hasEHBranches() const {
00121     if (llvm::BasicBlock *block = getCachedEHDispatchBlock())
00122       return !block->use_empty();
00123     return false;
00124   }
00125 
00126   EHScopeStack::stable_iterator getEnclosingEHScope() const {
00127     return EnclosingEHScope;
00128   }
00129 };
00130 
00131 /// A scope which attempts to handle some, possibly all, types of
00132 /// exceptions.
00133 ///
00134 /// Objective C @finally blocks are represented using a cleanup scope
00135 /// after the catch scope.
00136 class EHCatchScope : public EHScope {
00137   // In effect, we have a flexible array member
00138   //   Handler Handlers[0];
00139   // But that's only standard in C99, not C++, so we have to do
00140   // annoying pointer arithmetic instead.
00141 
00142 public:
00143   struct Handler {
00144     /// A type info value, or null (C++ null, not an LLVM null pointer)
00145     /// for a catch-all.
00146     llvm::Value *Type;
00147 
00148     /// The catch handler for this type.
00149     llvm::BasicBlock *Block;
00150 
00151     bool isCatchAll() const { return Type == 0; }
00152   };
00153 
00154 private:
00155   friend class EHScopeStack;
00156 
00157   Handler *getHandlers() {
00158     return reinterpret_cast<Handler*>(this+1);
00159   }
00160 
00161   const Handler *getHandlers() const {
00162     return reinterpret_cast<const Handler*>(this+1);
00163   }
00164 
00165 public:
00166   static size_t getSizeForNumHandlers(unsigned N) {
00167     return sizeof(EHCatchScope) + N * sizeof(Handler);
00168   }
00169 
00170   EHCatchScope(unsigned numHandlers,
00171                EHScopeStack::stable_iterator enclosingEHScope)
00172     : EHScope(Catch, enclosingEHScope) {
00173     CatchBits.NumHandlers = numHandlers;
00174   }
00175 
00176   unsigned getNumHandlers() const {
00177     return CatchBits.NumHandlers;
00178   }
00179 
00180   void setCatchAllHandler(unsigned I, llvm::BasicBlock *Block) {
00181     setHandler(I, /*catchall*/ 0, Block);
00182   }
00183 
00184   void setHandler(unsigned I, llvm::Value *Type, llvm::BasicBlock *Block) {
00185     assert(I < getNumHandlers());
00186     getHandlers()[I].Type = Type;
00187     getHandlers()[I].Block = Block;
00188   }
00189 
00190   const Handler &getHandler(unsigned I) const {
00191     assert(I < getNumHandlers());
00192     return getHandlers()[I];
00193   }
00194 
00195   typedef const Handler *iterator;
00196   iterator begin() const { return getHandlers(); }
00197   iterator end() const { return getHandlers() + getNumHandlers(); }
00198 
00199   static bool classof(const EHScope *Scope) {
00200     return Scope->getKind() == Catch;
00201   }
00202 };
00203 
00204 /// A cleanup scope which generates the cleanup blocks lazily.
00205 class EHCleanupScope : public EHScope {
00206   /// The nearest normal cleanup scope enclosing this one.
00207   EHScopeStack::stable_iterator EnclosingNormal;
00208 
00209   /// The nearest EH scope enclosing this one.
00210   EHScopeStack::stable_iterator EnclosingEH;
00211 
00212   /// The dual entry/exit block along the normal edge.  This is lazily
00213   /// created if needed before the cleanup is popped.
00214   llvm::BasicBlock *NormalBlock;
00215 
00216   /// An optional i1 variable indicating whether this cleanup has been
00217   /// activated yet.
00218   llvm::AllocaInst *ActiveFlag;
00219 
00220   /// Extra information required for cleanups that have resolved
00221   /// branches through them.  This has to be allocated on the side
00222   /// because everything on the cleanup stack has be trivially
00223   /// movable.
00224   struct ExtInfo {
00225     /// The destinations of normal branch-afters and branch-throughs.
00226     llvm::SmallPtrSet<llvm::BasicBlock*, 4> Branches;
00227 
00228     /// Normal branch-afters.
00229     SmallVector<std::pair<llvm::BasicBlock*,llvm::ConstantInt*>, 4>
00230       BranchAfters;
00231   };
00232   mutable struct ExtInfo *ExtInfo;
00233 
00234   struct ExtInfo &getExtInfo() {
00235     if (!ExtInfo) ExtInfo = new struct ExtInfo();
00236     return *ExtInfo;
00237   }
00238 
00239   const struct ExtInfo &getExtInfo() const {
00240     if (!ExtInfo) ExtInfo = new struct ExtInfo();
00241     return *ExtInfo;
00242   }
00243 
00244 public:
00245   /// Gets the size required for a lazy cleanup scope with the given
00246   /// cleanup-data requirements.
00247   static size_t getSizeForCleanupSize(size_t Size) {
00248     return sizeof(EHCleanupScope) + Size;
00249   }
00250 
00251   size_t getAllocatedSize() const {
00252     return sizeof(EHCleanupScope) + CleanupBits.CleanupSize;
00253   }
00254 
00255   EHCleanupScope(bool isNormal, bool isEH, bool isActive,
00256                  unsigned cleanupSize, unsigned fixupDepth,
00257                  EHScopeStack::stable_iterator enclosingNormal,
00258                  EHScopeStack::stable_iterator enclosingEH)
00259     : EHScope(EHScope::Cleanup, enclosingEH), EnclosingNormal(enclosingNormal),
00260       NormalBlock(0), ActiveFlag(0), ExtInfo(0) {
00261     CleanupBits.IsNormalCleanup = isNormal;
00262     CleanupBits.IsEHCleanup = isEH;
00263     CleanupBits.IsActive = isActive;
00264     CleanupBits.TestFlagInNormalCleanup = false;
00265     CleanupBits.TestFlagInEHCleanup = false;
00266     CleanupBits.CleanupSize = cleanupSize;
00267     CleanupBits.FixupDepth = fixupDepth;
00268 
00269     assert(CleanupBits.CleanupSize == cleanupSize && "cleanup size overflow");
00270   }
00271 
00272   ~EHCleanupScope() {
00273     delete ExtInfo;
00274   }
00275 
00276   bool isNormalCleanup() const { return CleanupBits.IsNormalCleanup; }
00277   llvm::BasicBlock *getNormalBlock() const { return NormalBlock; }
00278   void setNormalBlock(llvm::BasicBlock *BB) { NormalBlock = BB; }
00279 
00280   bool isEHCleanup() const { return CleanupBits.IsEHCleanup; }
00281   llvm::BasicBlock *getEHBlock() const { return getCachedEHDispatchBlock(); }
00282   void setEHBlock(llvm::BasicBlock *BB) { setCachedEHDispatchBlock(BB); }
00283 
00284   bool isActive() const { return CleanupBits.IsActive; }
00285   void setActive(bool A) { CleanupBits.IsActive = A; }
00286 
00287   llvm::AllocaInst *getActiveFlag() const { return ActiveFlag; }
00288   void setActiveFlag(llvm::AllocaInst *Var) { ActiveFlag = Var; }
00289 
00290   void setTestFlagInNormalCleanup() {
00291     CleanupBits.TestFlagInNormalCleanup = true;
00292   }
00293   bool shouldTestFlagInNormalCleanup() const {
00294     return CleanupBits.TestFlagInNormalCleanup;
00295   }
00296 
00297   void setTestFlagInEHCleanup() {
00298     CleanupBits.TestFlagInEHCleanup = true;
00299   }
00300   bool shouldTestFlagInEHCleanup() const {
00301     return CleanupBits.TestFlagInEHCleanup;
00302   }
00303 
00304   unsigned getFixupDepth() const { return CleanupBits.FixupDepth; }
00305   EHScopeStack::stable_iterator getEnclosingNormalCleanup() const {
00306     return EnclosingNormal;
00307   }
00308 
00309   size_t getCleanupSize() const { return CleanupBits.CleanupSize; }
00310   void *getCleanupBuffer() { return this + 1; }
00311 
00312   EHScopeStack::Cleanup *getCleanup() {
00313     return reinterpret_cast<EHScopeStack::Cleanup*>(getCleanupBuffer());
00314   }
00315 
00316   /// True if this cleanup scope has any branch-afters or branch-throughs.
00317   bool hasBranches() const { return ExtInfo && !ExtInfo->Branches.empty(); }
00318 
00319   /// Add a branch-after to this cleanup scope.  A branch-after is a
00320   /// branch from a point protected by this (normal) cleanup to a
00321   /// point in the normal cleanup scope immediately containing it.
00322   /// For example,
00323   ///   for (;;) { A a; break; }
00324   /// contains a branch-after.
00325   ///
00326   /// Branch-afters each have their own destination out of the
00327   /// cleanup, guaranteed distinct from anything else threaded through
00328   /// it.  Therefore branch-afters usually force a switch after the
00329   /// cleanup.
00330   void addBranchAfter(llvm::ConstantInt *Index,
00331                       llvm::BasicBlock *Block) {
00332     struct ExtInfo &ExtInfo = getExtInfo();
00333     if (ExtInfo.Branches.insert(Block))
00334       ExtInfo.BranchAfters.push_back(std::make_pair(Block, Index));
00335   }
00336 
00337   /// Return the number of unique branch-afters on this scope.
00338   unsigned getNumBranchAfters() const {
00339     return ExtInfo ? ExtInfo->BranchAfters.size() : 0;
00340   }
00341 
00342   llvm::BasicBlock *getBranchAfterBlock(unsigned I) const {
00343     assert(I < getNumBranchAfters());
00344     return ExtInfo->BranchAfters[I].first;
00345   }
00346 
00347   llvm::ConstantInt *getBranchAfterIndex(unsigned I) const {
00348     assert(I < getNumBranchAfters());
00349     return ExtInfo->BranchAfters[I].second;
00350   }
00351 
00352   /// Add a branch-through to this cleanup scope.  A branch-through is
00353   /// a branch from a scope protected by this (normal) cleanup to an
00354   /// enclosing scope other than the immediately-enclosing normal
00355   /// cleanup scope.
00356   ///
00357   /// In the following example, the branch through B's scope is a
00358   /// branch-through, while the branch through A's scope is a
00359   /// branch-after:
00360   ///   for (;;) { A a; B b; break; }
00361   ///
00362   /// All branch-throughs have a common destination out of the
00363   /// cleanup, one possibly shared with the fall-through.  Therefore
00364   /// branch-throughs usually don't force a switch after the cleanup.
00365   ///
00366   /// \return true if the branch-through was new to this scope
00367   bool addBranchThrough(llvm::BasicBlock *Block) {
00368     return getExtInfo().Branches.insert(Block);
00369   }
00370 
00371   /// Determines if this cleanup scope has any branch throughs.
00372   bool hasBranchThroughs() const {
00373     if (!ExtInfo) return false;
00374     return (ExtInfo->BranchAfters.size() != ExtInfo->Branches.size());
00375   }
00376 
00377   static bool classof(const EHScope *Scope) {
00378     return (Scope->getKind() == Cleanup);
00379   }
00380 };
00381 
00382 /// An exceptions scope which filters exceptions thrown through it.
00383 /// Only exceptions matching the filter types will be permitted to be
00384 /// thrown.
00385 ///
00386 /// This is used to implement C++ exception specifications.
00387 class EHFilterScope : public EHScope {
00388   // Essentially ends in a flexible array member:
00389   // llvm::Value *FilterTypes[0];
00390 
00391   llvm::Value **getFilters() {
00392     return reinterpret_cast<llvm::Value**>(this+1);
00393   }
00394 
00395   llvm::Value * const *getFilters() const {
00396     return reinterpret_cast<llvm::Value* const *>(this+1);
00397   }
00398 
00399 public:
00400   EHFilterScope(unsigned numFilters)
00401     : EHScope(Filter, EHScopeStack::stable_end()) {
00402     FilterBits.NumFilters = numFilters;
00403   }
00404 
00405   static size_t getSizeForNumFilters(unsigned numFilters) {
00406     return sizeof(EHFilterScope) + numFilters * sizeof(llvm::Value*);
00407   }
00408 
00409   unsigned getNumFilters() const { return FilterBits.NumFilters; }
00410 
00411   void setFilter(unsigned i, llvm::Value *filterValue) {
00412     assert(i < getNumFilters());
00413     getFilters()[i] = filterValue;
00414   }
00415 
00416   llvm::Value *getFilter(unsigned i) const {
00417     assert(i < getNumFilters());
00418     return getFilters()[i];
00419   }
00420 
00421   static bool classof(const EHScope *scope) {
00422     return scope->getKind() == Filter;
00423   }
00424 };
00425 
00426 /// An exceptions scope which calls std::terminate if any exception
00427 /// reaches it.
00428 class EHTerminateScope : public EHScope {
00429 public:
00430   EHTerminateScope(EHScopeStack::stable_iterator enclosingEHScope)
00431     : EHScope(Terminate, enclosingEHScope) {}
00432   static size_t getSize() { return sizeof(EHTerminateScope); }
00433 
00434   static bool classof(const EHScope *scope) {
00435     return scope->getKind() == Terminate;
00436   }
00437 };
00438 
00439 /// A non-stable pointer into the scope stack.
00440 class EHScopeStack::iterator {
00441   char *Ptr;
00442 
00443   friend class EHScopeStack;
00444   explicit iterator(char *Ptr) : Ptr(Ptr) {}
00445 
00446 public:
00447   iterator() : Ptr(0) {}
00448 
00449   EHScope *get() const { 
00450     return reinterpret_cast<EHScope*>(Ptr);
00451   }
00452 
00453   EHScope *operator->() const { return get(); }
00454   EHScope &operator*() const { return *get(); }
00455 
00456   iterator &operator++() {
00457     switch (get()->getKind()) {
00458     case EHScope::Catch:
00459       Ptr += EHCatchScope::getSizeForNumHandlers(
00460           static_cast<const EHCatchScope*>(get())->getNumHandlers());
00461       break;
00462 
00463     case EHScope::Filter:
00464       Ptr += EHFilterScope::getSizeForNumFilters(
00465           static_cast<const EHFilterScope*>(get())->getNumFilters());
00466       break;
00467 
00468     case EHScope::Cleanup:
00469       Ptr += static_cast<const EHCleanupScope*>(get())
00470         ->getAllocatedSize();
00471       break;
00472 
00473     case EHScope::Terminate:
00474       Ptr += EHTerminateScope::getSize();
00475       break;
00476     }
00477 
00478     return *this;
00479   }
00480 
00481   iterator next() {
00482     iterator copy = *this;
00483     ++copy;
00484     return copy;
00485   }
00486 
00487   iterator operator++(int) {
00488     iterator copy = *this;
00489     operator++();
00490     return copy;
00491   }
00492 
00493   bool encloses(iterator other) const { return Ptr >= other.Ptr; }
00494   bool strictlyEncloses(iterator other) const { return Ptr > other.Ptr; }
00495 
00496   bool operator==(iterator other) const { return Ptr == other.Ptr; }
00497   bool operator!=(iterator other) const { return Ptr != other.Ptr; }
00498 };
00499 
00500 inline EHScopeStack::iterator EHScopeStack::begin() const {
00501   return iterator(StartOfData);
00502 }
00503 
00504 inline EHScopeStack::iterator EHScopeStack::end() const {
00505   return iterator(EndOfBuffer);
00506 }
00507 
00508 inline void EHScopeStack::popCatch() {
00509   assert(!empty() && "popping exception stack when not empty");
00510 
00511   EHCatchScope &scope = cast<EHCatchScope>(*begin());
00512   InnermostEHScope = scope.getEnclosingEHScope();
00513   StartOfData += EHCatchScope::getSizeForNumHandlers(scope.getNumHandlers());
00514 }
00515 
00516 inline void EHScopeStack::popTerminate() {
00517   assert(!empty() && "popping exception stack when not empty");
00518 
00519   EHTerminateScope &scope = cast<EHTerminateScope>(*begin());
00520   InnermostEHScope = scope.getEnclosingEHScope();
00521   StartOfData += EHTerminateScope::getSize();
00522 }
00523 
00524 inline EHScopeStack::iterator EHScopeStack::find(stable_iterator sp) const {
00525   assert(sp.isValid() && "finding invalid savepoint");
00526   assert(sp.Size <= stable_begin().Size && "finding savepoint after pop");
00527   return iterator(EndOfBuffer - sp.Size);
00528 }
00529 
00530 inline EHScopeStack::stable_iterator
00531 EHScopeStack::stabilize(iterator ir) const {
00532   assert(StartOfData <= ir.Ptr && ir.Ptr <= EndOfBuffer);
00533   return stable_iterator(EndOfBuffer - ir.Ptr);
00534 }
00535 
00536 }
00537 }
00538 
00539 #endif