clang API Documentation
00001 //===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- 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 // This is the internal per-function state used for llvm translation. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #ifndef CLANG_CODEGEN_CODEGENFUNCTION_H 00015 #define CLANG_CODEGEN_CODEGENFUNCTION_H 00016 00017 #include "clang/AST/Type.h" 00018 #include "clang/AST/ExprCXX.h" 00019 #include "clang/AST/ExprObjC.h" 00020 #include "clang/AST/CharUnits.h" 00021 #include "clang/Frontend/CodeGenOptions.h" 00022 #include "clang/Basic/ABI.h" 00023 #include "clang/Basic/TargetInfo.h" 00024 #include "llvm/ADT/ArrayRef.h" 00025 #include "llvm/ADT/DenseMap.h" 00026 #include "llvm/ADT/SmallVector.h" 00027 #include "llvm/Support/ValueHandle.h" 00028 #include "llvm/Support/Debug.h" 00029 #include "CodeGenModule.h" 00030 #include "CGBuilder.h" 00031 #include "CGDebugInfo.h" 00032 #include "CGValue.h" 00033 00034 namespace llvm { 00035 class BasicBlock; 00036 class LLVMContext; 00037 class MDNode; 00038 class Module; 00039 class SwitchInst; 00040 class Twine; 00041 class Value; 00042 class CallSite; 00043 } 00044 00045 namespace clang { 00046 class ASTContext; 00047 class BlockDecl; 00048 class CXXDestructorDecl; 00049 class CXXForRangeStmt; 00050 class CXXTryStmt; 00051 class Decl; 00052 class LabelDecl; 00053 class EnumConstantDecl; 00054 class FunctionDecl; 00055 class FunctionProtoType; 00056 class LabelStmt; 00057 class ObjCContainerDecl; 00058 class ObjCInterfaceDecl; 00059 class ObjCIvarDecl; 00060 class ObjCMethodDecl; 00061 class ObjCImplementationDecl; 00062 class ObjCPropertyImplDecl; 00063 class TargetInfo; 00064 class TargetCodeGenInfo; 00065 class VarDecl; 00066 class ObjCForCollectionStmt; 00067 class ObjCAtTryStmt; 00068 class ObjCAtThrowStmt; 00069 class ObjCAtSynchronizedStmt; 00070 class ObjCAutoreleasePoolStmt; 00071 00072 namespace CodeGen { 00073 class CodeGenTypes; 00074 class CGFunctionInfo; 00075 class CGRecordLayout; 00076 class CGBlockInfo; 00077 class CGCXXABI; 00078 class BlockFlags; 00079 class BlockFieldFlags; 00080 00081 /// A branch fixup. These are required when emitting a goto to a 00082 /// label which hasn't been emitted yet. The goto is optimistically 00083 /// emitted as a branch to the basic block for the label, and (if it 00084 /// occurs in a scope with non-trivial cleanups) a fixup is added to 00085 /// the innermost cleanup. When a (normal) cleanup is popped, any 00086 /// unresolved fixups in that scope are threaded through the cleanup. 00087 struct BranchFixup { 00088 /// The block containing the terminator which needs to be modified 00089 /// into a switch if this fixup is resolved into the current scope. 00090 /// If null, LatestBranch points directly to the destination. 00091 llvm::BasicBlock *OptimisticBranchBlock; 00092 00093 /// The ultimate destination of the branch. 00094 /// 00095 /// This can be set to null to indicate that this fixup was 00096 /// successfully resolved. 00097 llvm::BasicBlock *Destination; 00098 00099 /// The destination index value. 00100 unsigned DestinationIndex; 00101 00102 /// The initial branch of the fixup. 00103 llvm::BranchInst *InitialBranch; 00104 }; 00105 00106 template <class T> struct InvariantValue { 00107 typedef T type; 00108 typedef T saved_type; 00109 static bool needsSaving(type value) { return false; } 00110 static saved_type save(CodeGenFunction &CGF, type value) { return value; } 00111 static type restore(CodeGenFunction &CGF, saved_type value) { return value; } 00112 }; 00113 00114 /// A metaprogramming class for ensuring that a value will dominate an 00115 /// arbitrary position in a function. 00116 template <class T> struct DominatingValue : InvariantValue<T> {}; 00117 00118 template <class T, bool mightBeInstruction = 00119 llvm::is_base_of<llvm::Value, T>::value && 00120 !llvm::is_base_of<llvm::Constant, T>::value && 00121 !llvm::is_base_of<llvm::BasicBlock, T>::value> 00122 struct DominatingPointer; 00123 template <class T> struct DominatingPointer<T,false> : InvariantValue<T*> {}; 00124 // template <class T> struct DominatingPointer<T,true> at end of file 00125 00126 template <class T> struct DominatingValue<T*> : DominatingPointer<T> {}; 00127 00128 enum CleanupKind { 00129 EHCleanup = 0x1, 00130 NormalCleanup = 0x2, 00131 NormalAndEHCleanup = EHCleanup | NormalCleanup, 00132 00133 InactiveCleanup = 0x4, 00134 InactiveEHCleanup = EHCleanup | InactiveCleanup, 00135 InactiveNormalCleanup = NormalCleanup | InactiveCleanup, 00136 InactiveNormalAndEHCleanup = NormalAndEHCleanup | InactiveCleanup 00137 }; 00138 00139 /// A stack of scopes which respond to exceptions, including cleanups 00140 /// and catch blocks. 00141 class EHScopeStack { 00142 public: 00143 /// A saved depth on the scope stack. This is necessary because 00144 /// pushing scopes onto the stack invalidates iterators. 00145 class stable_iterator { 00146 friend class EHScopeStack; 00147 00148 /// Offset from StartOfData to EndOfBuffer. 00149 ptrdiff_t Size; 00150 00151 stable_iterator(ptrdiff_t Size) : Size(Size) {} 00152 00153 public: 00154 static stable_iterator invalid() { return stable_iterator(-1); } 00155 stable_iterator() : Size(-1) {} 00156 00157 bool isValid() const { return Size >= 0; } 00158 00159 /// Returns true if this scope encloses I. 00160 /// Returns false if I is invalid. 00161 /// This scope must be valid. 00162 bool encloses(stable_iterator I) const { return Size <= I.Size; } 00163 00164 /// Returns true if this scope strictly encloses I: that is, 00165 /// if it encloses I and is not I. 00166 /// Returns false is I is invalid. 00167 /// This scope must be valid. 00168 bool strictlyEncloses(stable_iterator I) const { return Size < I.Size; } 00169 00170 friend bool operator==(stable_iterator A, stable_iterator B) { 00171 return A.Size == B.Size; 00172 } 00173 friend bool operator!=(stable_iterator A, stable_iterator B) { 00174 return A.Size != B.Size; 00175 } 00176 }; 00177 00178 /// Information for lazily generating a cleanup. Subclasses must be 00179 /// POD-like: cleanups will not be destructed, and they will be 00180 /// allocated on the cleanup stack and freely copied and moved 00181 /// around. 00182 /// 00183 /// Cleanup implementations should generally be declared in an 00184 /// anonymous namespace. 00185 class Cleanup { 00186 // Anchor the construction vtable. 00187 virtual void anchor(); 00188 public: 00189 /// Generation flags. 00190 class Flags { 00191 enum { 00192 F_IsForEH = 0x1, 00193 F_IsNormalCleanupKind = 0x2, 00194 F_IsEHCleanupKind = 0x4 00195 }; 00196 unsigned flags; 00197 00198 public: 00199 Flags() : flags(0) {} 00200 00201 /// isForEH - true if the current emission is for an EH cleanup. 00202 bool isForEHCleanup() const { return flags & F_IsForEH; } 00203 bool isForNormalCleanup() const { return !isForEHCleanup(); } 00204 void setIsForEHCleanup() { flags |= F_IsForEH; } 00205 00206 bool isNormalCleanupKind() const { return flags & F_IsNormalCleanupKind; } 00207 void setIsNormalCleanupKind() { flags |= F_IsNormalCleanupKind; } 00208 00209 /// isEHCleanupKind - true if the cleanup was pushed as an EH 00210 /// cleanup. 00211 bool isEHCleanupKind() const { return flags & F_IsEHCleanupKind; } 00212 void setIsEHCleanupKind() { flags |= F_IsEHCleanupKind; } 00213 }; 00214 00215 // Provide a virtual destructor to suppress a very common warning 00216 // that unfortunately cannot be suppressed without this. Cleanups 00217 // should not rely on this destructor ever being called. 00218 virtual ~Cleanup() {} 00219 00220 /// Emit the cleanup. For normal cleanups, this is run in the 00221 /// same EH context as when the cleanup was pushed, i.e. the 00222 /// immediately-enclosing context of the cleanup scope. For 00223 /// EH cleanups, this is run in a terminate context. 00224 /// 00225 // \param IsForEHCleanup true if this is for an EH cleanup, false 00226 /// if for a normal cleanup. 00227 virtual void Emit(CodeGenFunction &CGF, Flags flags) = 0; 00228 }; 00229 00230 /// ConditionalCleanupN stores the saved form of its N parameters, 00231 /// then restores them and performs the cleanup. 00232 template <class T, class A0> 00233 class ConditionalCleanup1 : public Cleanup { 00234 typedef typename DominatingValue<A0>::saved_type A0_saved; 00235 A0_saved a0_saved; 00236 00237 void Emit(CodeGenFunction &CGF, Flags flags) { 00238 A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved); 00239 T(a0).Emit(CGF, flags); 00240 } 00241 00242 public: 00243 ConditionalCleanup1(A0_saved a0) 00244 : a0_saved(a0) {} 00245 }; 00246 00247 template <class T, class A0, class A1> 00248 class ConditionalCleanup2 : public Cleanup { 00249 typedef typename DominatingValue<A0>::saved_type A0_saved; 00250 typedef typename DominatingValue<A1>::saved_type A1_saved; 00251 A0_saved a0_saved; 00252 A1_saved a1_saved; 00253 00254 void Emit(CodeGenFunction &CGF, Flags flags) { 00255 A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved); 00256 A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved); 00257 T(a0, a1).Emit(CGF, flags); 00258 } 00259 00260 public: 00261 ConditionalCleanup2(A0_saved a0, A1_saved a1) 00262 : a0_saved(a0), a1_saved(a1) {} 00263 }; 00264 00265 template <class T, class A0, class A1, class A2> 00266 class ConditionalCleanup3 : public Cleanup { 00267 typedef typename DominatingValue<A0>::saved_type A0_saved; 00268 typedef typename DominatingValue<A1>::saved_type A1_saved; 00269 typedef typename DominatingValue<A2>::saved_type A2_saved; 00270 A0_saved a0_saved; 00271 A1_saved a1_saved; 00272 A2_saved a2_saved; 00273 00274 void Emit(CodeGenFunction &CGF, Flags flags) { 00275 A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved); 00276 A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved); 00277 A2 a2 = DominatingValue<A2>::restore(CGF, a2_saved); 00278 T(a0, a1, a2).Emit(CGF, flags); 00279 } 00280 00281 public: 00282 ConditionalCleanup3(A0_saved a0, A1_saved a1, A2_saved a2) 00283 : a0_saved(a0), a1_saved(a1), a2_saved(a2) {} 00284 }; 00285 00286 template <class T, class A0, class A1, class A2, class A3> 00287 class ConditionalCleanup4 : public Cleanup { 00288 typedef typename DominatingValue<A0>::saved_type A0_saved; 00289 typedef typename DominatingValue<A1>::saved_type A1_saved; 00290 typedef typename DominatingValue<A2>::saved_type A2_saved; 00291 typedef typename DominatingValue<A3>::saved_type A3_saved; 00292 A0_saved a0_saved; 00293 A1_saved a1_saved; 00294 A2_saved a2_saved; 00295 A3_saved a3_saved; 00296 00297 void Emit(CodeGenFunction &CGF, Flags flags) { 00298 A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved); 00299 A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved); 00300 A2 a2 = DominatingValue<A2>::restore(CGF, a2_saved); 00301 A3 a3 = DominatingValue<A3>::restore(CGF, a3_saved); 00302 T(a0, a1, a2, a3).Emit(CGF, flags); 00303 } 00304 00305 public: 00306 ConditionalCleanup4(A0_saved a0, A1_saved a1, A2_saved a2, A3_saved a3) 00307 : a0_saved(a0), a1_saved(a1), a2_saved(a2), a3_saved(a3) {} 00308 }; 00309 00310 private: 00311 // The implementation for this class is in CGException.h and 00312 // CGException.cpp; the definition is here because it's used as a 00313 // member of CodeGenFunction. 00314 00315 /// The start of the scope-stack buffer, i.e. the allocated pointer 00316 /// for the buffer. All of these pointers are either simultaneously 00317 /// null or simultaneously valid. 00318 char *StartOfBuffer; 00319 00320 /// The end of the buffer. 00321 char *EndOfBuffer; 00322 00323 /// The first valid entry in the buffer. 00324 char *StartOfData; 00325 00326 /// The innermost normal cleanup on the stack. 00327 stable_iterator InnermostNormalCleanup; 00328 00329 /// The innermost EH scope on the stack. 00330 stable_iterator InnermostEHScope; 00331 00332 /// The current set of branch fixups. A branch fixup is a jump to 00333 /// an as-yet unemitted label, i.e. a label for which we don't yet 00334 /// know the EH stack depth. Whenever we pop a cleanup, we have 00335 /// to thread all the current branch fixups through it. 00336 /// 00337 /// Fixups are recorded as the Use of the respective branch or 00338 /// switch statement. The use points to the final destination. 00339 /// When popping out of a cleanup, these uses are threaded through 00340 /// the cleanup and adjusted to point to the new cleanup. 00341 /// 00342 /// Note that branches are allowed to jump into protected scopes 00343 /// in certain situations; e.g. the following code is legal: 00344 /// struct A { ~A(); }; // trivial ctor, non-trivial dtor 00345 /// goto foo; 00346 /// A a; 00347 /// foo: 00348 /// bar(); 00349 SmallVector<BranchFixup, 8> BranchFixups; 00350 00351 char *allocate(size_t Size); 00352 00353 void *pushCleanup(CleanupKind K, size_t DataSize); 00354 00355 public: 00356 EHScopeStack() : StartOfBuffer(0), EndOfBuffer(0), StartOfData(0), 00357 InnermostNormalCleanup(stable_end()), 00358 InnermostEHScope(stable_end()) {} 00359 ~EHScopeStack() { delete[] StartOfBuffer; } 00360 00361 // Variadic templates would make this not terrible. 00362 00363 /// Push a lazily-created cleanup on the stack. 00364 template <class T> 00365 void pushCleanup(CleanupKind Kind) { 00366 void *Buffer = pushCleanup(Kind, sizeof(T)); 00367 Cleanup *Obj = new(Buffer) T(); 00368 (void) Obj; 00369 } 00370 00371 /// Push a lazily-created cleanup on the stack. 00372 template <class T, class A0> 00373 void pushCleanup(CleanupKind Kind, A0 a0) { 00374 void *Buffer = pushCleanup(Kind, sizeof(T)); 00375 Cleanup *Obj = new(Buffer) T(a0); 00376 (void) Obj; 00377 } 00378 00379 /// Push a lazily-created cleanup on the stack. 00380 template <class T, class A0, class A1> 00381 void pushCleanup(CleanupKind Kind, A0 a0, A1 a1) { 00382 void *Buffer = pushCleanup(Kind, sizeof(T)); 00383 Cleanup *Obj = new(Buffer) T(a0, a1); 00384 (void) Obj; 00385 } 00386 00387 /// Push a lazily-created cleanup on the stack. 00388 template <class T, class A0, class A1, class A2> 00389 void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2) { 00390 void *Buffer = pushCleanup(Kind, sizeof(T)); 00391 Cleanup *Obj = new(Buffer) T(a0, a1, a2); 00392 (void) Obj; 00393 } 00394 00395 /// Push a lazily-created cleanup on the stack. 00396 template <class T, class A0, class A1, class A2, class A3> 00397 void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3) { 00398 void *Buffer = pushCleanup(Kind, sizeof(T)); 00399 Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3); 00400 (void) Obj; 00401 } 00402 00403 /// Push a lazily-created cleanup on the stack. 00404 template <class T, class A0, class A1, class A2, class A3, class A4> 00405 void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { 00406 void *Buffer = pushCleanup(Kind, sizeof(T)); 00407 Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3, a4); 00408 (void) Obj; 00409 } 00410 00411 // Feel free to add more variants of the following: 00412 00413 /// Push a cleanup with non-constant storage requirements on the 00414 /// stack. The cleanup type must provide an additional static method: 00415 /// static size_t getExtraSize(size_t); 00416 /// The argument to this method will be the value N, which will also 00417 /// be passed as the first argument to the constructor. 00418 /// 00419 /// The data stored in the extra storage must obey the same 00420 /// restrictions as normal cleanup member data. 00421 /// 00422 /// The pointer returned from this method is valid until the cleanup 00423 /// stack is modified. 00424 template <class T, class A0, class A1, class A2> 00425 T *pushCleanupWithExtra(CleanupKind Kind, size_t N, A0 a0, A1 a1, A2 a2) { 00426 void *Buffer = pushCleanup(Kind, sizeof(T) + T::getExtraSize(N)); 00427 return new (Buffer) T(N, a0, a1, a2); 00428 } 00429 00430 /// Pops a cleanup scope off the stack. This is private to CGCleanup.cpp. 00431 void popCleanup(); 00432 00433 /// Push a set of catch handlers on the stack. The catch is 00434 /// uninitialized and will need to have the given number of handlers 00435 /// set on it. 00436 class EHCatchScope *pushCatch(unsigned NumHandlers); 00437 00438 /// Pops a catch scope off the stack. This is private to CGException.cpp. 00439 void popCatch(); 00440 00441 /// Push an exceptions filter on the stack. 00442 class EHFilterScope *pushFilter(unsigned NumFilters); 00443 00444 /// Pops an exceptions filter off the stack. 00445 void popFilter(); 00446 00447 /// Push a terminate handler on the stack. 00448 void pushTerminate(); 00449 00450 /// Pops a terminate handler off the stack. 00451 void popTerminate(); 00452 00453 /// Determines whether the exception-scopes stack is empty. 00454 bool empty() const { return StartOfData == EndOfBuffer; } 00455 00456 bool requiresLandingPad() const { 00457 return InnermostEHScope != stable_end(); 00458 } 00459 00460 /// Determines whether there are any normal cleanups on the stack. 00461 bool hasNormalCleanups() const { 00462 return InnermostNormalCleanup != stable_end(); 00463 } 00464 00465 /// Returns the innermost normal cleanup on the stack, or 00466 /// stable_end() if there are no normal cleanups. 00467 stable_iterator getInnermostNormalCleanup() const { 00468 return InnermostNormalCleanup; 00469 } 00470 stable_iterator getInnermostActiveNormalCleanup() const; 00471 00472 stable_iterator getInnermostEHScope() const { 00473 return InnermostEHScope; 00474 } 00475 00476 stable_iterator getInnermostActiveEHScope() const; 00477 00478 /// An unstable reference to a scope-stack depth. Invalidated by 00479 /// pushes but not pops. 00480 class iterator; 00481 00482 /// Returns an iterator pointing to the innermost EH scope. 00483 iterator begin() const; 00484 00485 /// Returns an iterator pointing to the outermost EH scope. 00486 iterator end() const; 00487 00488 /// Create a stable reference to the top of the EH stack. The 00489 /// returned reference is valid until that scope is popped off the 00490 /// stack. 00491 stable_iterator stable_begin() const { 00492 return stable_iterator(EndOfBuffer - StartOfData); 00493 } 00494 00495 /// Create a stable reference to the bottom of the EH stack. 00496 static stable_iterator stable_end() { 00497 return stable_iterator(0); 00498 } 00499 00500 /// Translates an iterator into a stable_iterator. 00501 stable_iterator stabilize(iterator it) const; 00502 00503 /// Turn a stable reference to a scope depth into a unstable pointer 00504 /// to the EH stack. 00505 iterator find(stable_iterator save) const; 00506 00507 /// Removes the cleanup pointed to by the given stable_iterator. 00508 void removeCleanup(stable_iterator save); 00509 00510 /// Add a branch fixup to the current cleanup scope. 00511 BranchFixup &addBranchFixup() { 00512 assert(hasNormalCleanups() && "adding fixup in scope without cleanups"); 00513 BranchFixups.push_back(BranchFixup()); 00514 return BranchFixups.back(); 00515 } 00516 00517 unsigned getNumBranchFixups() const { return BranchFixups.size(); } 00518 BranchFixup &getBranchFixup(unsigned I) { 00519 assert(I < getNumBranchFixups()); 00520 return BranchFixups[I]; 00521 } 00522 00523 /// Pops lazily-removed fixups from the end of the list. This 00524 /// should only be called by procedures which have just popped a 00525 /// cleanup or resolved one or more fixups. 00526 void popNullFixups(); 00527 00528 /// Clears the branch-fixups list. This should only be called by 00529 /// ResolveAllBranchFixups. 00530 void clearFixups() { BranchFixups.clear(); } 00531 }; 00532 00533 /// CodeGenFunction - This class organizes the per-function state that is used 00534 /// while generating LLVM code. 00535 class CodeGenFunction : public CodeGenTypeCache { 00536 CodeGenFunction(const CodeGenFunction&); // DO NOT IMPLEMENT 00537 void operator=(const CodeGenFunction&); // DO NOT IMPLEMENT 00538 00539 friend class CGCXXABI; 00540 public: 00541 /// A jump destination is an abstract label, branching to which may 00542 /// require a jump out through normal cleanups. 00543 struct JumpDest { 00544 JumpDest() : Block(0), ScopeDepth(), Index(0) {} 00545 JumpDest(llvm::BasicBlock *Block, 00546 EHScopeStack::stable_iterator Depth, 00547 unsigned Index) 00548 : Block(Block), ScopeDepth(Depth), Index(Index) {} 00549 00550 bool isValid() const { return Block != 0; } 00551 llvm::BasicBlock *getBlock() const { return Block; } 00552 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; } 00553 unsigned getDestIndex() const { return Index; } 00554 00555 private: 00556 llvm::BasicBlock *Block; 00557 EHScopeStack::stable_iterator ScopeDepth; 00558 unsigned Index; 00559 }; 00560 00561 CodeGenModule &CGM; // Per-module state. 00562 const TargetInfo &Target; 00563 00564 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy; 00565 CGBuilderTy Builder; 00566 00567 /// CurFuncDecl - Holds the Decl for the current function or ObjC method. 00568 /// This excludes BlockDecls. 00569 const Decl *CurFuncDecl; 00570 /// CurCodeDecl - This is the inner-most code context, which includes blocks. 00571 const Decl *CurCodeDecl; 00572 const CGFunctionInfo *CurFnInfo; 00573 QualType FnRetTy; 00574 llvm::Function *CurFn; 00575 00576 /// CurGD - The GlobalDecl for the current function being compiled. 00577 GlobalDecl CurGD; 00578 00579 /// PrologueCleanupDepth - The cleanup depth enclosing all the 00580 /// cleanups associated with the parameters. 00581 EHScopeStack::stable_iterator PrologueCleanupDepth; 00582 00583 /// ReturnBlock - Unified return block. 00584 JumpDest ReturnBlock; 00585 00586 /// ReturnValue - The temporary alloca to hold the return value. This is null 00587 /// iff the function has no return value. 00588 llvm::Value *ReturnValue; 00589 00590 /// AllocaInsertPoint - This is an instruction in the entry block before which 00591 /// we prefer to insert allocas. 00592 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt; 00593 00594 /// BoundsChecking - Emit run-time bounds checks. Higher values mean 00595 /// potentially higher performance penalties. 00596 unsigned char BoundsChecking; 00597 00598 /// CatchUndefined - Emit run-time checks to catch undefined behaviors. 00599 bool CatchUndefined; 00600 00601 /// In ARC, whether we should autorelease the return value. 00602 bool AutoreleaseResult; 00603 00604 const CodeGen::CGBlockInfo *BlockInfo; 00605 llvm::Value *BlockPointer; 00606 00607 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 00608 FieldDecl *LambdaThisCaptureField; 00609 00610 /// \brief A mapping from NRVO variables to the flags used to indicate 00611 /// when the NRVO has been applied to this variable. 00612 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags; 00613 00614 EHScopeStack EHStack; 00615 00616 /// i32s containing the indexes of the cleanup destinations. 00617 llvm::AllocaInst *NormalCleanupDest; 00618 00619 unsigned NextCleanupDestIndex; 00620 00621 /// FirstBlockInfo - The head of a singly-linked-list of block layouts. 00622 CGBlockInfo *FirstBlockInfo; 00623 00624 /// EHResumeBlock - Unified block containing a call to llvm.eh.resume. 00625 llvm::BasicBlock *EHResumeBlock; 00626 00627 /// The exception slot. All landing pads write the current exception pointer 00628 /// into this alloca. 00629 llvm::Value *ExceptionSlot; 00630 00631 /// The selector slot. Under the MandatoryCleanup model, all landing pads 00632 /// write the current selector value into this alloca. 00633 llvm::AllocaInst *EHSelectorSlot; 00634 00635 /// Emits a landing pad for the current EH stack. 00636 llvm::BasicBlock *EmitLandingPad(); 00637 00638 llvm::BasicBlock *getInvokeDestImpl(); 00639 00640 template <class T> 00641 typename DominatingValue<T>::saved_type saveValueInCond(T value) { 00642 return DominatingValue<T>::save(*this, value); 00643 } 00644 00645 public: 00646 /// ObjCEHValueStack - Stack of Objective-C exception values, used for 00647 /// rethrows. 00648 SmallVector<llvm::Value*, 8> ObjCEHValueStack; 00649 00650 /// A class controlling the emission of a finally block. 00651 class FinallyInfo { 00652 /// Where the catchall's edge through the cleanup should go. 00653 JumpDest RethrowDest; 00654 00655 /// A function to call to enter the catch. 00656 llvm::Constant *BeginCatchFn; 00657 00658 /// An i1 variable indicating whether or not the @finally is 00659 /// running for an exception. 00660 llvm::AllocaInst *ForEHVar; 00661 00662 /// An i8* variable into which the exception pointer to rethrow 00663 /// has been saved. 00664 llvm::AllocaInst *SavedExnVar; 00665 00666 public: 00667 void enter(CodeGenFunction &CGF, const Stmt *Finally, 00668 llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn, 00669 llvm::Constant *rethrowFn); 00670 void exit(CodeGenFunction &CGF); 00671 }; 00672 00673 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 00674 /// current full-expression. Safe against the possibility that 00675 /// we're currently inside a conditionally-evaluated expression. 00676 template <class T, class A0> 00677 void pushFullExprCleanup(CleanupKind kind, A0 a0) { 00678 // If we're not in a conditional branch, or if none of the 00679 // arguments requires saving, then use the unconditional cleanup. 00680 if (!isInConditionalBranch()) 00681 return EHStack.pushCleanup<T>(kind, a0); 00682 00683 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 00684 00685 typedef EHScopeStack::ConditionalCleanup1<T, A0> CleanupType; 00686 EHStack.pushCleanup<CleanupType>(kind, a0_saved); 00687 initFullExprCleanup(); 00688 } 00689 00690 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 00691 /// current full-expression. Safe against the possibility that 00692 /// we're currently inside a conditionally-evaluated expression. 00693 template <class T, class A0, class A1> 00694 void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1) { 00695 // If we're not in a conditional branch, or if none of the 00696 // arguments requires saving, then use the unconditional cleanup. 00697 if (!isInConditionalBranch()) 00698 return EHStack.pushCleanup<T>(kind, a0, a1); 00699 00700 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 00701 typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1); 00702 00703 typedef EHScopeStack::ConditionalCleanup2<T, A0, A1> CleanupType; 00704 EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved); 00705 initFullExprCleanup(); 00706 } 00707 00708 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 00709 /// current full-expression. Safe against the possibility that 00710 /// we're currently inside a conditionally-evaluated expression. 00711 template <class T, class A0, class A1, class A2> 00712 void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2) { 00713 // If we're not in a conditional branch, or if none of the 00714 // arguments requires saving, then use the unconditional cleanup. 00715 if (!isInConditionalBranch()) { 00716 return EHStack.pushCleanup<T>(kind, a0, a1, a2); 00717 } 00718 00719 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 00720 typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1); 00721 typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2); 00722 00723 typedef EHScopeStack::ConditionalCleanup3<T, A0, A1, A2> CleanupType; 00724 EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved, a2_saved); 00725 initFullExprCleanup(); 00726 } 00727 00728 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 00729 /// current full-expression. Safe against the possibility that 00730 /// we're currently inside a conditionally-evaluated expression. 00731 template <class T, class A0, class A1, class A2, class A3> 00732 void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2, A3 a3) { 00733 // If we're not in a conditional branch, or if none of the 00734 // arguments requires saving, then use the unconditional cleanup. 00735 if (!isInConditionalBranch()) { 00736 return EHStack.pushCleanup<T>(kind, a0, a1, a2, a3); 00737 } 00738 00739 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 00740 typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1); 00741 typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2); 00742 typename DominatingValue<A3>::saved_type a3_saved = saveValueInCond(a3); 00743 00744 typedef EHScopeStack::ConditionalCleanup4<T, A0, A1, A2, A3> CleanupType; 00745 EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved, 00746 a2_saved, a3_saved); 00747 initFullExprCleanup(); 00748 } 00749 00750 /// Set up the last cleaup that was pushed as a conditional 00751 /// full-expression cleanup. 00752 void initFullExprCleanup(); 00753 00754 /// PushDestructorCleanup - Push a cleanup to call the 00755 /// complete-object destructor of an object of the given type at the 00756 /// given address. Does nothing if T is not a C++ class type with a 00757 /// non-trivial destructor. 00758 void PushDestructorCleanup(QualType T, llvm::Value *Addr); 00759 00760 /// PushDestructorCleanup - Push a cleanup to call the 00761 /// complete-object variant of the given destructor on the object at 00762 /// the given address. 00763 void PushDestructorCleanup(const CXXDestructorDecl *Dtor, 00764 llvm::Value *Addr); 00765 00766 /// PopCleanupBlock - Will pop the cleanup entry on the stack and 00767 /// process all branch fixups. 00768 void PopCleanupBlock(bool FallThroughIsBranchThrough = false); 00769 00770 /// DeactivateCleanupBlock - Deactivates the given cleanup block. 00771 /// The block cannot be reactivated. Pops it if it's the top of the 00772 /// stack. 00773 /// 00774 /// \param DominatingIP - An instruction which is known to 00775 /// dominate the current IP (if set) and which lies along 00776 /// all paths of execution between the current IP and the 00777 /// the point at which the cleanup comes into scope. 00778 void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, 00779 llvm::Instruction *DominatingIP); 00780 00781 /// ActivateCleanupBlock - Activates an initially-inactive cleanup. 00782 /// Cannot be used to resurrect a deactivated cleanup. 00783 /// 00784 /// \param DominatingIP - An instruction which is known to 00785 /// dominate the current IP (if set) and which lies along 00786 /// all paths of execution between the current IP and the 00787 /// the point at which the cleanup comes into scope. 00788 void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, 00789 llvm::Instruction *DominatingIP); 00790 00791 /// \brief Enters a new scope for capturing cleanups, all of which 00792 /// will be executed once the scope is exited. 00793 class RunCleanupsScope { 00794 EHScopeStack::stable_iterator CleanupStackDepth; 00795 bool OldDidCallStackSave; 00796 bool PerformCleanup; 00797 00798 RunCleanupsScope(const RunCleanupsScope &); // DO NOT IMPLEMENT 00799 RunCleanupsScope &operator=(const RunCleanupsScope &); // DO NOT IMPLEMENT 00800 00801 protected: 00802 CodeGenFunction& CGF; 00803 00804 public: 00805 /// \brief Enter a new cleanup scope. 00806 explicit RunCleanupsScope(CodeGenFunction &CGF) 00807 : PerformCleanup(true), CGF(CGF) 00808 { 00809 CleanupStackDepth = CGF.EHStack.stable_begin(); 00810 OldDidCallStackSave = CGF.DidCallStackSave; 00811 CGF.DidCallStackSave = false; 00812 } 00813 00814 /// \brief Exit this cleanup scope, emitting any accumulated 00815 /// cleanups. 00816 ~RunCleanupsScope() { 00817 if (PerformCleanup) { 00818 CGF.DidCallStackSave = OldDidCallStackSave; 00819 CGF.PopCleanupBlocks(CleanupStackDepth); 00820 } 00821 } 00822 00823 /// \brief Determine whether this scope requires any cleanups. 00824 bool requiresCleanups() const { 00825 return CGF.EHStack.stable_begin() != CleanupStackDepth; 00826 } 00827 00828 /// \brief Force the emission of cleanups now, instead of waiting 00829 /// until this object is destroyed. 00830 void ForceCleanup() { 00831 assert(PerformCleanup && "Already forced cleanup"); 00832 CGF.DidCallStackSave = OldDidCallStackSave; 00833 CGF.PopCleanupBlocks(CleanupStackDepth); 00834 PerformCleanup = false; 00835 } 00836 }; 00837 00838 class LexicalScope: protected RunCleanupsScope { 00839 SourceRange Range; 00840 bool PopDebugStack; 00841 00842 LexicalScope(const LexicalScope &); // DO NOT IMPLEMENT THESE 00843 LexicalScope &operator=(const LexicalScope &); 00844 00845 public: 00846 /// \brief Enter a new cleanup scope. 00847 explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range) 00848 : RunCleanupsScope(CGF), Range(Range), PopDebugStack(true) { 00849 if (CGDebugInfo *DI = CGF.getDebugInfo()) 00850 DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin()); 00851 } 00852 00853 /// \brief Exit this cleanup scope, emitting any accumulated 00854 /// cleanups. 00855 ~LexicalScope() { 00856 if (PopDebugStack) { 00857 CGDebugInfo *DI = CGF.getDebugInfo(); 00858 if (DI) DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd()); 00859 } 00860 } 00861 00862 /// \brief Force the emission of cleanups now, instead of waiting 00863 /// until this object is destroyed. 00864 void ForceCleanup() { 00865 RunCleanupsScope::ForceCleanup(); 00866 if (CGDebugInfo *DI = CGF.getDebugInfo()) { 00867 DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd()); 00868 PopDebugStack = false; 00869 } 00870 } 00871 }; 00872 00873 00874 /// PopCleanupBlocks - Takes the old cleanup stack size and emits 00875 /// the cleanup blocks that have been added. 00876 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize); 00877 00878 void ResolveBranchFixups(llvm::BasicBlock *Target); 00879 00880 /// The given basic block lies in the current EH scope, but may be a 00881 /// target of a potentially scope-crossing jump; get a stable handle 00882 /// to which we can perform this jump later. 00883 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) { 00884 return JumpDest(Target, 00885 EHStack.getInnermostNormalCleanup(), 00886 NextCleanupDestIndex++); 00887 } 00888 00889 /// The given basic block lies in the current EH scope, but may be a 00890 /// target of a potentially scope-crossing jump; get a stable handle 00891 /// to which we can perform this jump later. 00892 JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) { 00893 return getJumpDestInCurrentScope(createBasicBlock(Name)); 00894 } 00895 00896 /// EmitBranchThroughCleanup - Emit a branch from the current insert 00897 /// block through the normal cleanup handling code (if any) and then 00898 /// on to \arg Dest. 00899 void EmitBranchThroughCleanup(JumpDest Dest); 00900 00901 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the 00902 /// specified destination obviously has no cleanups to run. 'false' is always 00903 /// a conservatively correct answer for this method. 00904 bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const; 00905 00906 /// popCatchScope - Pops the catch scope at the top of the EHScope 00907 /// stack, emitting any required code (other than the catch handlers 00908 /// themselves). 00909 void popCatchScope(); 00910 00911 llvm::BasicBlock *getEHResumeBlock(); 00912 llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope); 00913 00914 /// An object to manage conditionally-evaluated expressions. 00915 class ConditionalEvaluation { 00916 llvm::BasicBlock *StartBB; 00917 00918 public: 00919 ConditionalEvaluation(CodeGenFunction &CGF) 00920 : StartBB(CGF.Builder.GetInsertBlock()) {} 00921 00922 void begin(CodeGenFunction &CGF) { 00923 assert(CGF.OutermostConditional != this); 00924 if (!CGF.OutermostConditional) 00925 CGF.OutermostConditional = this; 00926 } 00927 00928 void end(CodeGenFunction &CGF) { 00929 assert(CGF.OutermostConditional != 0); 00930 if (CGF.OutermostConditional == this) 00931 CGF.OutermostConditional = 0; 00932 } 00933 00934 /// Returns a block which will be executed prior to each 00935 /// evaluation of the conditional code. 00936 llvm::BasicBlock *getStartingBlock() const { 00937 return StartBB; 00938 } 00939 }; 00940 00941 /// isInConditionalBranch - Return true if we're currently emitting 00942 /// one branch or the other of a conditional expression. 00943 bool isInConditionalBranch() const { return OutermostConditional != 0; } 00944 00945 void setBeforeOutermostConditional(llvm::Value *value, llvm::Value *addr) { 00946 assert(isInConditionalBranch()); 00947 llvm::BasicBlock *block = OutermostConditional->getStartingBlock(); 00948 new llvm::StoreInst(value, addr, &block->back()); 00949 } 00950 00951 /// An RAII object to record that we're evaluating a statement 00952 /// expression. 00953 class StmtExprEvaluation { 00954 CodeGenFunction &CGF; 00955 00956 /// We have to save the outermost conditional: cleanups in a 00957 /// statement expression aren't conditional just because the 00958 /// StmtExpr is. 00959 ConditionalEvaluation *SavedOutermostConditional; 00960 00961 public: 00962 StmtExprEvaluation(CodeGenFunction &CGF) 00963 : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) { 00964 CGF.OutermostConditional = 0; 00965 } 00966 00967 ~StmtExprEvaluation() { 00968 CGF.OutermostConditional = SavedOutermostConditional; 00969 CGF.EnsureInsertPoint(); 00970 } 00971 }; 00972 00973 /// An object which temporarily prevents a value from being 00974 /// destroyed by aggressive peephole optimizations that assume that 00975 /// all uses of a value have been realized in the IR. 00976 class PeepholeProtection { 00977 llvm::Instruction *Inst; 00978 friend class CodeGenFunction; 00979 00980 public: 00981 PeepholeProtection() : Inst(0) {} 00982 }; 00983 00984 /// A non-RAII class containing all the information about a bound 00985 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for 00986 /// this which makes individual mappings very simple; using this 00987 /// class directly is useful when you have a variable number of 00988 /// opaque values or don't want the RAII functionality for some 00989 /// reason. 00990 class OpaqueValueMappingData { 00991 const OpaqueValueExpr *OpaqueValue; 00992 bool BoundLValue; 00993 CodeGenFunction::PeepholeProtection Protection; 00994 00995 OpaqueValueMappingData(const OpaqueValueExpr *ov, 00996 bool boundLValue) 00997 : OpaqueValue(ov), BoundLValue(boundLValue) {} 00998 public: 00999 OpaqueValueMappingData() : OpaqueValue(0) {} 01000 01001 static bool shouldBindAsLValue(const Expr *expr) { 01002 // gl-values should be bound as l-values for obvious reasons. 01003 // Records should be bound as l-values because IR generation 01004 // always keeps them in memory. Expressions of function type 01005 // act exactly like l-values but are formally required to be 01006 // r-values in C. 01007 return expr->isGLValue() || 01008 expr->getType()->isRecordType() || 01009 expr->getType()->isFunctionType(); 01010 } 01011 01012 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 01013 const OpaqueValueExpr *ov, 01014 const Expr *e) { 01015 if (shouldBindAsLValue(ov)) 01016 return bind(CGF, ov, CGF.EmitLValue(e)); 01017 return bind(CGF, ov, CGF.EmitAnyExpr(e)); 01018 } 01019 01020 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 01021 const OpaqueValueExpr *ov, 01022 const LValue &lv) { 01023 assert(shouldBindAsLValue(ov)); 01024 CGF.OpaqueLValues.insert(std::make_pair(ov, lv)); 01025 return OpaqueValueMappingData(ov, true); 01026 } 01027 01028 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 01029 const OpaqueValueExpr *ov, 01030 const RValue &rv) { 01031 assert(!shouldBindAsLValue(ov)); 01032 CGF.OpaqueRValues.insert(std::make_pair(ov, rv)); 01033 01034 OpaqueValueMappingData data(ov, false); 01035 01036 // Work around an extremely aggressive peephole optimization in 01037 // EmitScalarConversion which assumes that all other uses of a 01038 // value are extant. 01039 data.Protection = CGF.protectFromPeepholes(rv); 01040 01041 return data; 01042 } 01043 01044 bool isValid() const { return OpaqueValue != 0; } 01045 void clear() { OpaqueValue = 0; } 01046 01047 void unbind(CodeGenFunction &CGF) { 01048 assert(OpaqueValue && "no data to unbind!"); 01049 01050 if (BoundLValue) { 01051 CGF.OpaqueLValues.erase(OpaqueValue); 01052 } else { 01053 CGF.OpaqueRValues.erase(OpaqueValue); 01054 CGF.unprotectFromPeepholes(Protection); 01055 } 01056 } 01057 }; 01058 01059 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr. 01060 class OpaqueValueMapping { 01061 CodeGenFunction &CGF; 01062 OpaqueValueMappingData Data; 01063 01064 public: 01065 static bool shouldBindAsLValue(const Expr *expr) { 01066 return OpaqueValueMappingData::shouldBindAsLValue(expr); 01067 } 01068 01069 /// Build the opaque value mapping for the given conditional 01070 /// operator if it's the GNU ?: extension. This is a common 01071 /// enough pattern that the convenience operator is really 01072 /// helpful. 01073 /// 01074 OpaqueValueMapping(CodeGenFunction &CGF, 01075 const AbstractConditionalOperator *op) : CGF(CGF) { 01076 if (isa<ConditionalOperator>(op)) 01077 // Leave Data empty. 01078 return; 01079 01080 const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op); 01081 Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(), 01082 e->getCommon()); 01083 } 01084 01085 OpaqueValueMapping(CodeGenFunction &CGF, 01086 const OpaqueValueExpr *opaqueValue, 01087 LValue lvalue) 01088 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) { 01089 } 01090 01091 OpaqueValueMapping(CodeGenFunction &CGF, 01092 const OpaqueValueExpr *opaqueValue, 01093 RValue rvalue) 01094 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) { 01095 } 01096 01097 void pop() { 01098 Data.unbind(CGF); 01099 Data.clear(); 01100 } 01101 01102 ~OpaqueValueMapping() { 01103 if (Data.isValid()) Data.unbind(CGF); 01104 } 01105 }; 01106 01107 /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field 01108 /// number that holds the value. 01109 unsigned getByRefValueLLVMField(const ValueDecl *VD) const; 01110 01111 /// BuildBlockByrefAddress - Computes address location of the 01112 /// variable which is declared as __block. 01113 llvm::Value *BuildBlockByrefAddress(llvm::Value *BaseAddr, 01114 const VarDecl *V); 01115 private: 01116 CGDebugInfo *DebugInfo; 01117 bool DisableDebugInfo; 01118 01119 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid 01120 /// calling llvm.stacksave for multiple VLAs in the same scope. 01121 bool DidCallStackSave; 01122 01123 /// IndirectBranch - The first time an indirect goto is seen we create a block 01124 /// with an indirect branch. Every time we see the address of a label taken, 01125 /// we add the label to the indirect goto. Every subsequent indirect goto is 01126 /// codegen'd as a jump to the IndirectBranch's basic block. 01127 llvm::IndirectBrInst *IndirectBranch; 01128 01129 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C 01130 /// decls. 01131 typedef llvm::DenseMap<const Decl*, llvm::Value*> DeclMapTy; 01132 DeclMapTy LocalDeclMap; 01133 01134 /// LabelMap - This keeps track of the LLVM basic block for each C label. 01135 llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap; 01136 01137 // BreakContinueStack - This keeps track of where break and continue 01138 // statements should jump to. 01139 struct BreakContinue { 01140 BreakContinue(JumpDest Break, JumpDest Continue) 01141 : BreakBlock(Break), ContinueBlock(Continue) {} 01142 01143 JumpDest BreakBlock; 01144 JumpDest ContinueBlock; 01145 }; 01146 SmallVector<BreakContinue, 8> BreakContinueStack; 01147 01148 /// SwitchInsn - This is nearest current switch instruction. It is null if 01149 /// current context is not in a switch. 01150 llvm::SwitchInst *SwitchInsn; 01151 01152 /// CaseRangeBlock - This block holds if condition check for last case 01153 /// statement range in current switch instruction. 01154 llvm::BasicBlock *CaseRangeBlock; 01155 01156 /// OpaqueLValues - Keeps track of the current set of opaque value 01157 /// expressions. 01158 llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues; 01159 llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues; 01160 01161 // VLASizeMap - This keeps track of the associated size for each VLA type. 01162 // We track this by the size expression rather than the type itself because 01163 // in certain situations, like a const qualifier applied to an VLA typedef, 01164 // multiple VLA types can share the same size expression. 01165 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we 01166 // enter/leave scopes. 01167 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap; 01168 01169 /// A block containing a single 'unreachable' instruction. Created 01170 /// lazily by getUnreachableBlock(). 01171 llvm::BasicBlock *UnreachableBlock; 01172 01173 /// CXXThisDecl - When generating code for a C++ member function, 01174 /// this will hold the implicit 'this' declaration. 01175 ImplicitParamDecl *CXXABIThisDecl; 01176 llvm::Value *CXXABIThisValue; 01177 llvm::Value *CXXThisValue; 01178 01179 /// CXXVTTDecl - When generating code for a base object constructor or 01180 /// base object destructor with virtual bases, this will hold the implicit 01181 /// VTT parameter. 01182 ImplicitParamDecl *CXXVTTDecl; 01183 llvm::Value *CXXVTTValue; 01184 01185 /// OutermostConditional - Points to the outermost active 01186 /// conditional control. This is used so that we know if a 01187 /// temporary should be destroyed conditionally. 01188 ConditionalEvaluation *OutermostConditional; 01189 01190 01191 /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM 01192 /// type as well as the field number that contains the actual data. 01193 llvm::DenseMap<const ValueDecl *, std::pair<llvm::Type *, 01194 unsigned> > ByRefValueInfo; 01195 01196 llvm::BasicBlock *TerminateLandingPad; 01197 llvm::BasicBlock *TerminateHandler; 01198 llvm::BasicBlock *TrapBB; 01199 01200 public: 01201 CodeGenFunction(CodeGenModule &cgm); 01202 ~CodeGenFunction(); 01203 01204 CodeGenTypes &getTypes() const { return CGM.getTypes(); } 01205 ASTContext &getContext() const { return CGM.getContext(); } 01206 CGDebugInfo *getDebugInfo() { 01207 if (DisableDebugInfo) 01208 return NULL; 01209 return DebugInfo; 01210 } 01211 void disableDebugInfo() { DisableDebugInfo = true; } 01212 void enableDebugInfo() { DisableDebugInfo = false; } 01213 01214 bool shouldUseFusedARCCalls() { 01215 return CGM.getCodeGenOpts().OptimizationLevel == 0; 01216 } 01217 01218 const LangOptions &getLangOpts() const { return CGM.getLangOpts(); } 01219 01220 /// Returns a pointer to the function's exception object and selector slot, 01221 /// which is assigned in every landing pad. 01222 llvm::Value *getExceptionSlot(); 01223 llvm::Value *getEHSelectorSlot(); 01224 01225 /// Returns the contents of the function's exception object and selector 01226 /// slots. 01227 llvm::Value *getExceptionFromSlot(); 01228 llvm::Value *getSelectorFromSlot(); 01229 01230 llvm::Value *getNormalCleanupDestSlot(); 01231 01232 llvm::BasicBlock *getUnreachableBlock() { 01233 if (!UnreachableBlock) { 01234 UnreachableBlock = createBasicBlock("unreachable"); 01235 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock); 01236 } 01237 return UnreachableBlock; 01238 } 01239 01240 llvm::BasicBlock *getInvokeDest() { 01241 if (!EHStack.requiresLandingPad()) return 0; 01242 return getInvokeDestImpl(); 01243 } 01244 01245 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); } 01246 01247 //===--------------------------------------------------------------------===// 01248 // Cleanups 01249 //===--------------------------------------------------------------------===// 01250 01251 typedef void Destroyer(CodeGenFunction &CGF, llvm::Value *addr, QualType ty); 01252 01253 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, 01254 llvm::Value *arrayEndPointer, 01255 QualType elementType, 01256 Destroyer *destroyer); 01257 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, 01258 llvm::Value *arrayEnd, 01259 QualType elementType, 01260 Destroyer *destroyer); 01261 01262 void pushDestroy(QualType::DestructionKind dtorKind, 01263 llvm::Value *addr, QualType type); 01264 void pushDestroy(CleanupKind kind, llvm::Value *addr, QualType type, 01265 Destroyer *destroyer, bool useEHCleanupForArray); 01266 void emitDestroy(llvm::Value *addr, QualType type, Destroyer *destroyer, 01267 bool useEHCleanupForArray); 01268 llvm::Function *generateDestroyHelper(llvm::Constant *addr, 01269 QualType type, 01270 Destroyer *destroyer, 01271 bool useEHCleanupForArray); 01272 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end, 01273 QualType type, Destroyer *destroyer, 01274 bool checkZeroLength, bool useEHCleanup); 01275 01276 Destroyer *getDestroyer(QualType::DestructionKind destructionKind); 01277 01278 /// Determines whether an EH cleanup is required to destroy a type 01279 /// with the given destruction kind. 01280 bool needsEHCleanup(QualType::DestructionKind kind) { 01281 switch (kind) { 01282 case QualType::DK_none: 01283 return false; 01284 case QualType::DK_cxx_destructor: 01285 case QualType::DK_objc_weak_lifetime: 01286 return getLangOpts().Exceptions; 01287 case QualType::DK_objc_strong_lifetime: 01288 return getLangOpts().Exceptions && 01289 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions; 01290 } 01291 llvm_unreachable("bad destruction kind"); 01292 } 01293 01294 CleanupKind getCleanupKind(QualType::DestructionKind kind) { 01295 return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup); 01296 } 01297 01298 //===--------------------------------------------------------------------===// 01299 // Objective-C 01300 //===--------------------------------------------------------------------===// 01301 01302 void GenerateObjCMethod(const ObjCMethodDecl *OMD); 01303 01304 void StartObjCMethod(const ObjCMethodDecl *MD, 01305 const ObjCContainerDecl *CD, 01306 SourceLocation StartLoc); 01307 01308 /// GenerateObjCGetter - Synthesize an Objective-C property getter function. 01309 void GenerateObjCGetter(ObjCImplementationDecl *IMP, 01310 const ObjCPropertyImplDecl *PID); 01311 void generateObjCGetterBody(const ObjCImplementationDecl *classImpl, 01312 const ObjCPropertyImplDecl *propImpl, 01313 llvm::Constant *AtomicHelperFn); 01314 01315 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, 01316 ObjCMethodDecl *MD, bool ctor); 01317 01318 /// GenerateObjCSetter - Synthesize an Objective-C property setter function 01319 /// for the given property. 01320 void GenerateObjCSetter(ObjCImplementationDecl *IMP, 01321 const ObjCPropertyImplDecl *PID); 01322 void generateObjCSetterBody(const ObjCImplementationDecl *classImpl, 01323 const ObjCPropertyImplDecl *propImpl, 01324 llvm::Constant *AtomicHelperFn); 01325 bool IndirectObjCSetterArg(const CGFunctionInfo &FI); 01326 bool IvarTypeWithAggrGCObjects(QualType Ty); 01327 01328 //===--------------------------------------------------------------------===// 01329 // Block Bits 01330 //===--------------------------------------------------------------------===// 01331 01332 llvm::Value *EmitBlockLiteral(const BlockExpr *); 01333 llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info); 01334 static void destroyBlockInfos(CGBlockInfo *info); 01335 llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *, 01336 const CGBlockInfo &Info, 01337 llvm::StructType *, 01338 llvm::Constant *BlockVarLayout); 01339 01340 llvm::Function *GenerateBlockFunction(GlobalDecl GD, 01341 const CGBlockInfo &Info, 01342 const Decl *OuterFuncDecl, 01343 const DeclMapTy &ldm, 01344 bool IsLambdaConversionToBlock); 01345 01346 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo); 01347 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo); 01348 llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction( 01349 const ObjCPropertyImplDecl *PID); 01350 llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction( 01351 const ObjCPropertyImplDecl *PID); 01352 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty); 01353 01354 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags); 01355 01356 class AutoVarEmission; 01357 01358 void emitByrefStructureInit(const AutoVarEmission &emission); 01359 void enterByrefCleanup(const AutoVarEmission &emission); 01360 01361 llvm::Value *LoadBlockStruct() { 01362 assert(BlockPointer && "no block pointer set!"); 01363 return BlockPointer; 01364 } 01365 01366 void AllocateBlockCXXThisPointer(const CXXThisExpr *E); 01367 void AllocateBlockDecl(const DeclRefExpr *E); 01368 llvm::Value *GetAddrOfBlockDecl(const VarDecl *var, bool ByRef); 01369 llvm::Type *BuildByRefType(const VarDecl *var); 01370 01371 void GenerateCode(GlobalDecl GD, llvm::Function *Fn, 01372 const CGFunctionInfo &FnInfo); 01373 void StartFunction(GlobalDecl GD, QualType RetTy, 01374 llvm::Function *Fn, 01375 const CGFunctionInfo &FnInfo, 01376 const FunctionArgList &Args, 01377 SourceLocation StartLoc); 01378 01379 void EmitConstructorBody(FunctionArgList &Args); 01380 void EmitDestructorBody(FunctionArgList &Args); 01381 void EmitFunctionBody(FunctionArgList &Args); 01382 01383 void EmitForwardingCallToLambda(const CXXRecordDecl *Lambda, 01384 CallArgList &CallArgs); 01385 void EmitLambdaToBlockPointerBody(FunctionArgList &Args); 01386 void EmitLambdaBlockInvokeBody(); 01387 void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD); 01388 void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD); 01389 01390 /// EmitReturnBlock - Emit the unified return block, trying to avoid its 01391 /// emission when possible. 01392 void EmitReturnBlock(); 01393 01394 /// FinishFunction - Complete IR generation of the current function. It is 01395 /// legal to call this function even if there is no current insertion point. 01396 void FinishFunction(SourceLocation EndLoc=SourceLocation()); 01397 01398 /// GenerateThunk - Generate a thunk for the given method. 01399 void GenerateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, 01400 GlobalDecl GD, const ThunkInfo &Thunk); 01401 01402 void GenerateVarArgsThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, 01403 GlobalDecl GD, const ThunkInfo &Thunk); 01404 01405 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type, 01406 FunctionArgList &Args); 01407 01408 void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init, 01409 ArrayRef<VarDecl *> ArrayIndexes); 01410 01411 /// InitializeVTablePointer - Initialize the vtable pointer of the given 01412 /// subobject. 01413 /// 01414 void InitializeVTablePointer(BaseSubobject Base, 01415 const CXXRecordDecl *NearestVBase, 01416 CharUnits OffsetFromNearestVBase, 01417 llvm::Constant *VTable, 01418 const CXXRecordDecl *VTableClass); 01419 01420 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy; 01421 void InitializeVTablePointers(BaseSubobject Base, 01422 const CXXRecordDecl *NearestVBase, 01423 CharUnits OffsetFromNearestVBase, 01424 bool BaseIsNonVirtualPrimaryBase, 01425 llvm::Constant *VTable, 01426 const CXXRecordDecl *VTableClass, 01427 VisitedVirtualBasesSetTy& VBases); 01428 01429 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl); 01430 01431 /// GetVTablePtr - Return the Value of the vtable pointer member pointed 01432 /// to by This. 01433 llvm::Value *GetVTablePtr(llvm::Value *This, llvm::Type *Ty); 01434 01435 /// EnterDtorCleanups - Enter the cleanups necessary to complete the 01436 /// given phase of destruction for a destructor. The end result 01437 /// should call destructors on members and base classes in reverse 01438 /// order of their construction. 01439 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type); 01440 01441 /// ShouldInstrumentFunction - Return true if the current function should be 01442 /// instrumented with __cyg_profile_func_* calls 01443 bool ShouldInstrumentFunction(); 01444 01445 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified 01446 /// instrumentation function with the current function and the call site, if 01447 /// function instrumentation is enabled. 01448 void EmitFunctionInstrumentation(const char *Fn); 01449 01450 /// EmitMCountInstrumentation - Emit call to .mcount. 01451 void EmitMCountInstrumentation(); 01452 01453 /// EmitFunctionProlog - Emit the target specific LLVM code to load the 01454 /// arguments for the given function. This is also responsible for naming the 01455 /// LLVM function arguments. 01456 void EmitFunctionProlog(const CGFunctionInfo &FI, 01457 llvm::Function *Fn, 01458 const FunctionArgList &Args); 01459 01460 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the 01461 /// given temporary. 01462 void EmitFunctionEpilog(const CGFunctionInfo &FI); 01463 01464 /// EmitStartEHSpec - Emit the start of the exception spec. 01465 void EmitStartEHSpec(const Decl *D); 01466 01467 /// EmitEndEHSpec - Emit the end of the exception spec. 01468 void EmitEndEHSpec(const Decl *D); 01469 01470 /// getTerminateLandingPad - Return a landing pad that just calls terminate. 01471 llvm::BasicBlock *getTerminateLandingPad(); 01472 01473 /// getTerminateHandler - Return a handler (not a landing pad, just 01474 /// a catch handler) that just calls terminate. This is used when 01475 /// a terminate scope encloses a try. 01476 llvm::BasicBlock *getTerminateHandler(); 01477 01478 llvm::Type *ConvertTypeForMem(QualType T); 01479 llvm::Type *ConvertType(QualType T); 01480 llvm::Type *ConvertType(const TypeDecl *T) { 01481 return ConvertType(getContext().getTypeDeclType(T)); 01482 } 01483 01484 /// LoadObjCSelf - Load the value of self. This function is only valid while 01485 /// generating code for an Objective-C method. 01486 llvm::Value *LoadObjCSelf(); 01487 01488 /// TypeOfSelfObject - Return type of object that this self represents. 01489 QualType TypeOfSelfObject(); 01490 01491 /// hasAggregateLLVMType - Return true if the specified AST type will map into 01492 /// an aggregate LLVM type or is void. 01493 static bool hasAggregateLLVMType(QualType T); 01494 01495 /// createBasicBlock - Create an LLVM basic block. 01496 llvm::BasicBlock *createBasicBlock(StringRef name = "", 01497 llvm::Function *parent = 0, 01498 llvm::BasicBlock *before = 0) { 01499 #ifdef NDEBUG 01500 return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before); 01501 #else 01502 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before); 01503 #endif 01504 } 01505 01506 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified 01507 /// label maps to. 01508 JumpDest getJumpDestForLabel(const LabelDecl *S); 01509 01510 /// SimplifyForwardingBlocks - If the given basic block is only a branch to 01511 /// another basic block, simplify it. This assumes that no other code could 01512 /// potentially reference the basic block. 01513 void SimplifyForwardingBlocks(llvm::BasicBlock *BB); 01514 01515 /// EmitBlock - Emit the given block \arg BB and set it as the insert point, 01516 /// adding a fall-through branch from the current insert block if 01517 /// necessary. It is legal to call this function even if there is no current 01518 /// insertion point. 01519 /// 01520 /// IsFinished - If true, indicates that the caller has finished emitting 01521 /// branches to the given block and does not expect to emit code into it. This 01522 /// means the block can be ignored if it is unreachable. 01523 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false); 01524 01525 /// EmitBlockAfterUses - Emit the given block somewhere hopefully 01526 /// near its uses, and leave the insertion point in it. 01527 void EmitBlockAfterUses(llvm::BasicBlock *BB); 01528 01529 /// EmitBranch - Emit a branch to the specified basic block from the current 01530 /// insert block, taking care to avoid creation of branches from dummy 01531 /// blocks. It is legal to call this function even if there is no current 01532 /// insertion point. 01533 /// 01534 /// This function clears the current insertion point. The caller should follow 01535 /// calls to this function with calls to Emit*Block prior to generation new 01536 /// code. 01537 void EmitBranch(llvm::BasicBlock *Block); 01538 01539 /// HaveInsertPoint - True if an insertion point is defined. If not, this 01540 /// indicates that the current code being emitted is unreachable. 01541 bool HaveInsertPoint() const { 01542 return Builder.GetInsertBlock() != 0; 01543 } 01544 01545 /// EnsureInsertPoint - Ensure that an insertion point is defined so that 01546 /// emitted IR has a place to go. Note that by definition, if this function 01547 /// creates a block then that block is unreachable; callers may do better to 01548 /// detect when no insertion point is defined and simply skip IR generation. 01549 void EnsureInsertPoint() { 01550 if (!HaveInsertPoint()) 01551 EmitBlock(createBasicBlock()); 01552 } 01553 01554 /// ErrorUnsupported - Print out an error that codegen doesn't support the 01555 /// specified stmt yet. 01556 void ErrorUnsupported(const Stmt *S, const char *Type, 01557 bool OmitOnError=false); 01558 01559 //===--------------------------------------------------------------------===// 01560 // Helpers 01561 //===--------------------------------------------------------------------===// 01562 01563 LValue MakeAddrLValue(llvm::Value *V, QualType T, 01564 CharUnits Alignment = CharUnits()) { 01565 return LValue::MakeAddr(V, T, Alignment, getContext(), 01566 CGM.getTBAAInfo(T)); 01567 } 01568 LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) { 01569 CharUnits Alignment; 01570 if (!T->isIncompleteType()) 01571 Alignment = getContext().getTypeAlignInChars(T); 01572 return LValue::MakeAddr(V, T, Alignment, getContext(), 01573 CGM.getTBAAInfo(T)); 01574 } 01575 01576 /// CreateTempAlloca - This creates a alloca and inserts it into the entry 01577 /// block. The caller is responsible for setting an appropriate alignment on 01578 /// the alloca. 01579 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty, 01580 const Twine &Name = "tmp"); 01581 01582 /// InitTempAlloca - Provide an initial value for the given alloca. 01583 void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value); 01584 01585 /// CreateIRTemp - Create a temporary IR object of the given type, with 01586 /// appropriate alignment. This routine should only be used when an temporary 01587 /// value needs to be stored into an alloca (for example, to avoid explicit 01588 /// PHI construction), but the type is the IR type, not the type appropriate 01589 /// for storing in memory. 01590 llvm::AllocaInst *CreateIRTemp(QualType T, const Twine &Name = "tmp"); 01591 01592 /// CreateMemTemp - Create a temporary memory object of the given type, with 01593 /// appropriate alignment. 01594 llvm::AllocaInst *CreateMemTemp(QualType T, const Twine &Name = "tmp"); 01595 01596 /// CreateAggTemp - Create a temporary memory object for the given 01597 /// aggregate type. 01598 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") { 01599 CharUnits Alignment = getContext().getTypeAlignInChars(T); 01600 return AggValueSlot::forAddr(CreateMemTemp(T, Name), Alignment, 01601 T.getQualifiers(), 01602 AggValueSlot::IsNotDestructed, 01603 AggValueSlot::DoesNotNeedGCBarriers, 01604 AggValueSlot::IsNotAliased); 01605 } 01606 01607 /// Emit a cast to void* in the appropriate address space. 01608 llvm::Value *EmitCastToVoidPtr(llvm::Value *value); 01609 01610 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 01611 /// expression and compare the result against zero, returning an Int1Ty value. 01612 llvm::Value *EvaluateExprAsBool(const Expr *E); 01613 01614 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result. 01615 void EmitIgnoredExpr(const Expr *E); 01616 01617 /// EmitAnyExpr - Emit code to compute the specified expression which can have 01618 /// any type. The result is returned as an RValue struct. If this is an 01619 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where 01620 /// the result should be returned. 01621 /// 01622 /// \param IgnoreResult - True if the resulting value isn't used. 01623 RValue EmitAnyExpr(const Expr *E, 01624 AggValueSlot AggSlot = AggValueSlot::ignored(), 01625 bool IgnoreResult = false); 01626 01627 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address 01628 // or the value of the expression, depending on how va_list is defined. 01629 llvm::Value *EmitVAListRef(const Expr *E); 01630 01631 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will 01632 /// always be accessible even if no aggregate location is provided. 01633 RValue EmitAnyExprToTemp(const Expr *E); 01634 01635 /// EmitAnyExprToMem - Emits the code necessary to evaluate an 01636 /// arbitrary expression into the given memory location. 01637 void EmitAnyExprToMem(const Expr *E, llvm::Value *Location, 01638 Qualifiers Quals, bool IsInitializer); 01639 01640 /// EmitExprAsInit - Emits the code necessary to initialize a 01641 /// location in memory with the given initializer. 01642 void EmitExprAsInit(const Expr *init, const ValueDecl *D, 01643 LValue lvalue, bool capturedByInit); 01644 01645 /// EmitAggregateCopy - Emit an aggrate copy. 01646 /// 01647 /// \param isVolatile - True iff either the source or the destination is 01648 /// volatile. 01649 void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr, 01650 QualType EltTy, bool isVolatile=false, 01651 unsigned Alignment = 0); 01652 01653 /// StartBlock - Start new block named N. If insert block is a dummy block 01654 /// then reuse it. 01655 void StartBlock(const char *N); 01656 01657 /// GetAddrOfStaticLocalVar - Return the address of a static local variable. 01658 llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD) { 01659 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD)); 01660 } 01661 01662 /// GetAddrOfLocalVar - Return the address of a local variable. 01663 llvm::Value *GetAddrOfLocalVar(const VarDecl *VD) { 01664 llvm::Value *Res = LocalDeclMap[VD]; 01665 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!"); 01666 return Res; 01667 } 01668 01669 /// getOpaqueLValueMapping - Given an opaque value expression (which 01670 /// must be mapped to an l-value), return its mapping. 01671 const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) { 01672 assert(OpaqueValueMapping::shouldBindAsLValue(e)); 01673 01674 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator 01675 it = OpaqueLValues.find(e); 01676 assert(it != OpaqueLValues.end() && "no mapping for opaque value!"); 01677 return it->second; 01678 } 01679 01680 /// getOpaqueRValueMapping - Given an opaque value expression (which 01681 /// must be mapped to an r-value), return its mapping. 01682 const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) { 01683 assert(!OpaqueValueMapping::shouldBindAsLValue(e)); 01684 01685 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator 01686 it = OpaqueRValues.find(e); 01687 assert(it != OpaqueRValues.end() && "no mapping for opaque value!"); 01688 return it->second; 01689 } 01690 01691 /// getAccessedFieldNo - Given an encoded value and a result number, return 01692 /// the input field number being accessed. 01693 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts); 01694 01695 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L); 01696 llvm::BasicBlock *GetIndirectGotoBlock(); 01697 01698 /// EmitNullInitialization - Generate code to set a value of the given type to 01699 /// null, If the type contains data member pointers, they will be initialized 01700 /// to -1 in accordance with the Itanium C++ ABI. 01701 void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty); 01702 01703 // EmitVAArg - Generate code to get an argument from the passed in pointer 01704 // and update it accordingly. The return value is a pointer to the argument. 01705 // FIXME: We should be able to get rid of this method and use the va_arg 01706 // instruction in LLVM instead once it works well enough. 01707 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty); 01708 01709 /// emitArrayLength - Compute the length of an array, even if it's a 01710 /// VLA, and drill down to the base element type. 01711 llvm::Value *emitArrayLength(const ArrayType *arrayType, 01712 QualType &baseType, 01713 llvm::Value *&addr); 01714 01715 /// EmitVLASize - Capture all the sizes for the VLA expressions in 01716 /// the given variably-modified type and store them in the VLASizeMap. 01717 /// 01718 /// This function can be called with a null (unreachable) insert point. 01719 void EmitVariablyModifiedType(QualType Ty); 01720 01721 /// getVLASize - Returns an LLVM value that corresponds to the size, 01722 /// in non-variably-sized elements, of a variable length array type, 01723 /// plus that largest non-variably-sized element type. Assumes that 01724 /// the type has already been emitted with EmitVariablyModifiedType. 01725 std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla); 01726 std::pair<llvm::Value*,QualType> getVLASize(QualType vla); 01727 01728 /// LoadCXXThis - Load the value of 'this'. This function is only valid while 01729 /// generating code for an C++ member function. 01730 llvm::Value *LoadCXXThis() { 01731 assert(CXXThisValue && "no 'this' value for this function"); 01732 return CXXThisValue; 01733 } 01734 01735 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have 01736 /// virtual bases. 01737 llvm::Value *LoadCXXVTT() { 01738 assert(CXXVTTValue && "no VTT value for this function"); 01739 return CXXVTTValue; 01740 } 01741 01742 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a 01743 /// complete class to the given direct base. 01744 llvm::Value * 01745 GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value, 01746 const CXXRecordDecl *Derived, 01747 const CXXRecordDecl *Base, 01748 bool BaseIsVirtual); 01749 01750 /// GetAddressOfBaseClass - This function will add the necessary delta to the 01751 /// load of 'this' and returns address of the base class. 01752 llvm::Value *GetAddressOfBaseClass(llvm::Value *Value, 01753 const CXXRecordDecl *Derived, 01754 CastExpr::path_const_iterator PathBegin, 01755 CastExpr::path_const_iterator PathEnd, 01756 bool NullCheckValue); 01757 01758 llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value, 01759 const CXXRecordDecl *Derived, 01760 CastExpr::path_const_iterator PathBegin, 01761 CastExpr::path_const_iterator PathEnd, 01762 bool NullCheckValue); 01763 01764 llvm::Value *GetVirtualBaseClassOffset(llvm::Value *This, 01765 const CXXRecordDecl *ClassDecl, 01766 const CXXRecordDecl *BaseClassDecl); 01767 01768 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, 01769 CXXCtorType CtorType, 01770 const FunctionArgList &Args); 01771 // It's important not to confuse this and the previous function. Delegating 01772 // constructors are the C++0x feature. The constructor delegate optimization 01773 // is used to reduce duplication in the base and complete consturctors where 01774 // they are substantially the same. 01775 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor, 01776 const FunctionArgList &Args); 01777 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 01778 bool ForVirtualBase, llvm::Value *This, 01779 CallExpr::const_arg_iterator ArgBeg, 01780 CallExpr::const_arg_iterator ArgEnd); 01781 01782 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, 01783 llvm::Value *This, llvm::Value *Src, 01784 CallExpr::const_arg_iterator ArgBeg, 01785 CallExpr::const_arg_iterator ArgEnd); 01786 01787 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 01788 const ConstantArrayType *ArrayTy, 01789 llvm::Value *ArrayPtr, 01790 CallExpr::const_arg_iterator ArgBeg, 01791 CallExpr::const_arg_iterator ArgEnd, 01792 bool ZeroInitialization = false); 01793 01794 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 01795 llvm::Value *NumElements, 01796 llvm::Value *ArrayPtr, 01797 CallExpr::const_arg_iterator ArgBeg, 01798 CallExpr::const_arg_iterator ArgEnd, 01799 bool ZeroInitialization = false); 01800 01801 static Destroyer destroyCXXObject; 01802 01803 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, 01804 bool ForVirtualBase, llvm::Value *This); 01805 01806 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType, 01807 llvm::Value *NewPtr, llvm::Value *NumElements); 01808 01809 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType, 01810 llvm::Value *Ptr); 01811 01812 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E); 01813 void EmitCXXDeleteExpr(const CXXDeleteExpr *E); 01814 01815 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr, 01816 QualType DeleteTy); 01817 01818 llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E); 01819 llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE); 01820 01821 void MaybeEmitStdInitializerListCleanup(llvm::Value *loc, const Expr *init); 01822 void EmitStdInitializerListCleanup(llvm::Value *loc, 01823 const InitListExpr *init); 01824 01825 void EmitCheck(llvm::Value *, unsigned Size); 01826 01827 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 01828 bool isInc, bool isPre); 01829 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, 01830 bool isInc, bool isPre); 01831 //===--------------------------------------------------------------------===// 01832 // Declaration Emission 01833 //===--------------------------------------------------------------------===// 01834 01835 /// EmitDecl - Emit a declaration. 01836 /// 01837 /// This function can be called with a null (unreachable) insert point. 01838 void EmitDecl(const Decl &D); 01839 01840 /// EmitVarDecl - Emit a local variable declaration. 01841 /// 01842 /// This function can be called with a null (unreachable) insert point. 01843 void EmitVarDecl(const VarDecl &D); 01844 01845 void EmitScalarInit(const Expr *init, const ValueDecl *D, 01846 LValue lvalue, bool capturedByInit); 01847 void EmitScalarInit(llvm::Value *init, LValue lvalue); 01848 01849 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D, 01850 llvm::Value *Address); 01851 01852 /// EmitAutoVarDecl - Emit an auto variable declaration. 01853 /// 01854 /// This function can be called with a null (unreachable) insert point. 01855 void EmitAutoVarDecl(const VarDecl &D); 01856 01857 class AutoVarEmission { 01858 friend class CodeGenFunction; 01859 01860 const VarDecl *Variable; 01861 01862 /// The alignment of the variable. 01863 CharUnits Alignment; 01864 01865 /// The address of the alloca. Null if the variable was emitted 01866 /// as a global constant. 01867 llvm::Value *Address; 01868 01869 llvm::Value *NRVOFlag; 01870 01871 /// True if the variable is a __block variable. 01872 bool IsByRef; 01873 01874 /// True if the variable is of aggregate type and has a constant 01875 /// initializer. 01876 bool IsConstantAggregate; 01877 01878 struct Invalid {}; 01879 AutoVarEmission(Invalid) : Variable(0) {} 01880 01881 AutoVarEmission(const VarDecl &variable) 01882 : Variable(&variable), Address(0), NRVOFlag(0), 01883 IsByRef(false), IsConstantAggregate(false) {} 01884 01885 bool wasEmittedAsGlobal() const { return Address == 0; } 01886 01887 public: 01888 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); } 01889 01890 /// Returns the address of the object within this declaration. 01891 /// Note that this does not chase the forwarding pointer for 01892 /// __block decls. 01893 llvm::Value *getObjectAddress(CodeGenFunction &CGF) const { 01894 if (!IsByRef) return Address; 01895 01896 return CGF.Builder.CreateStructGEP(Address, 01897 CGF.getByRefValueLLVMField(Variable), 01898 Variable->getNameAsString()); 01899 } 01900 }; 01901 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var); 01902 void EmitAutoVarInit(const AutoVarEmission &emission); 01903 void EmitAutoVarCleanups(const AutoVarEmission &emission); 01904 void emitAutoVarTypeCleanup(const AutoVarEmission &emission, 01905 QualType::DestructionKind dtorKind); 01906 01907 void EmitStaticVarDecl(const VarDecl &D, 01908 llvm::GlobalValue::LinkageTypes Linkage); 01909 01910 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl. 01911 void EmitParmDecl(const VarDecl &D, llvm::Value *Arg, unsigned ArgNo); 01912 01913 /// protectFromPeepholes - Protect a value that we're intending to 01914 /// store to the side, but which will probably be used later, from 01915 /// aggressive peepholing optimizations that might delete it. 01916 /// 01917 /// Pass the result to unprotectFromPeepholes to declare that 01918 /// protection is no longer required. 01919 /// 01920 /// There's no particular reason why this shouldn't apply to 01921 /// l-values, it's just that no existing peepholes work on pointers. 01922 PeepholeProtection protectFromPeepholes(RValue rvalue); 01923 void unprotectFromPeepholes(PeepholeProtection protection); 01924 01925 //===--------------------------------------------------------------------===// 01926 // Statement Emission 01927 //===--------------------------------------------------------------------===// 01928 01929 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info. 01930 void EmitStopPoint(const Stmt *S); 01931 01932 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call 01933 /// this function even if there is no current insertion point. 01934 /// 01935 /// This function may clear the current insertion point; callers should use 01936 /// EnsureInsertPoint if they wish to subsequently generate code without first 01937 /// calling EmitBlock, EmitBranch, or EmitStmt. 01938 void EmitStmt(const Stmt *S); 01939 01940 /// EmitSimpleStmt - Try to emit a "simple" statement which does not 01941 /// necessarily require an insertion point or debug information; typically 01942 /// because the statement amounts to a jump or a container of other 01943 /// statements. 01944 /// 01945 /// \return True if the statement was handled. 01946 bool EmitSimpleStmt(const Stmt *S); 01947 01948 RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false, 01949 AggValueSlot AVS = AggValueSlot::ignored()); 01950 01951 /// EmitLabel - Emit the block for the given label. It is legal to call this 01952 /// function even if there is no current insertion point. 01953 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt. 01954 01955 void EmitLabelStmt(const LabelStmt &S); 01956 void EmitAttributedStmt(const AttributedStmt &S); 01957 void EmitGotoStmt(const GotoStmt &S); 01958 void EmitIndirectGotoStmt(const IndirectGotoStmt &S); 01959 void EmitIfStmt(const IfStmt &S); 01960 void EmitWhileStmt(const WhileStmt &S); 01961 void EmitDoStmt(const DoStmt &S); 01962 void EmitForStmt(const ForStmt &S); 01963 void EmitReturnStmt(const ReturnStmt &S); 01964 void EmitDeclStmt(const DeclStmt &S); 01965 void EmitBreakStmt(const BreakStmt &S); 01966 void EmitContinueStmt(const ContinueStmt &S); 01967 void EmitSwitchStmt(const SwitchStmt &S); 01968 void EmitDefaultStmt(const DefaultStmt &S); 01969 void EmitCaseStmt(const CaseStmt &S); 01970 void EmitCaseStmtRange(const CaseStmt &S); 01971 void EmitAsmStmt(const AsmStmt &S); 01972 01973 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S); 01974 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S); 01975 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S); 01976 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S); 01977 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S); 01978 01979 llvm::Constant *getUnwindResumeFn(); 01980 llvm::Constant *getUnwindResumeOrRethrowFn(); 01981 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 01982 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 01983 01984 void EmitCXXTryStmt(const CXXTryStmt &S); 01985 void EmitCXXForRangeStmt(const CXXForRangeStmt &S); 01986 01987 //===--------------------------------------------------------------------===// 01988 // LValue Expression Emission 01989 //===--------------------------------------------------------------------===// 01990 01991 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type. 01992 RValue GetUndefRValue(QualType Ty); 01993 01994 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E 01995 /// and issue an ErrorUnsupported style diagnostic (using the 01996 /// provided Name). 01997 RValue EmitUnsupportedRValue(const Expr *E, 01998 const char *Name); 01999 02000 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue 02001 /// an ErrorUnsupported style diagnostic (using the provided Name). 02002 LValue EmitUnsupportedLValue(const Expr *E, 02003 const char *Name); 02004 02005 /// EmitLValue - Emit code to compute a designator that specifies the location 02006 /// of the expression. 02007 /// 02008 /// This can return one of two things: a simple address or a bitfield 02009 /// reference. In either case, the LLVM Value* in the LValue structure is 02010 /// guaranteed to be an LLVM pointer type. 02011 /// 02012 /// If this returns a bitfield reference, nothing about the pointee type of 02013 /// the LLVM value is known: For example, it may not be a pointer to an 02014 /// integer. 02015 /// 02016 /// If this returns a normal address, and if the lvalue's C type is fixed 02017 /// size, this method guarantees that the returned pointer type will point to 02018 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a 02019 /// variable length type, this is not possible. 02020 /// 02021 LValue EmitLValue(const Expr *E); 02022 02023 /// EmitCheckedLValue - Same as EmitLValue but additionally we generate 02024 /// checking code to guard against undefined behavior. This is only 02025 /// suitable when we know that the address will be used to access the 02026 /// object. 02027 LValue EmitCheckedLValue(const Expr *E); 02028 02029 /// EmitToMemory - Change a scalar value from its value 02030 /// representation to its in-memory representation. 02031 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty); 02032 02033 /// EmitFromMemory - Change a scalar value from its memory 02034 /// representation to its value representation. 02035 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty); 02036 02037 /// EmitLoadOfScalar - Load a scalar value from an address, taking 02038 /// care to appropriately convert from the memory representation to 02039 /// the LLVM value representation. 02040 llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile, 02041 unsigned Alignment, QualType Ty, 02042 llvm::MDNode *TBAAInfo = 0); 02043 02044 /// EmitLoadOfScalar - Load a scalar value from an address, taking 02045 /// care to appropriately convert from the memory representation to 02046 /// the LLVM value representation. The l-value must be a simple 02047 /// l-value. 02048 llvm::Value *EmitLoadOfScalar(LValue lvalue); 02049 02050 /// EmitStoreOfScalar - Store a scalar value to an address, taking 02051 /// care to appropriately convert from the memory representation to 02052 /// the LLVM value representation. 02053 void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr, 02054 bool Volatile, unsigned Alignment, QualType Ty, 02055 llvm::MDNode *TBAAInfo = 0, bool isInit=false); 02056 02057 /// EmitStoreOfScalar - Store a scalar value to an address, taking 02058 /// care to appropriately convert from the memory representation to 02059 /// the LLVM value representation. The l-value must be a simple 02060 /// l-value. The isInit flag indicates whether this is an initialization. 02061 /// If so, atomic qualifiers are ignored and the store is always non-atomic. 02062 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false); 02063 02064 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, 02065 /// this method emits the address of the lvalue, then loads the result as an 02066 /// rvalue, returning the rvalue. 02067 RValue EmitLoadOfLValue(LValue V); 02068 RValue EmitLoadOfExtVectorElementLValue(LValue V); 02069 RValue EmitLoadOfBitfieldLValue(LValue LV); 02070 02071 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 02072 /// lvalue, where both are guaranteed to the have the same type, and that type 02073 /// is 'Ty'. 02074 void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false); 02075 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst); 02076 02077 /// EmitStoreThroughLValue - Store Src into Dst with same constraints as 02078 /// EmitStoreThroughLValue. 02079 /// 02080 /// \param Result [out] - If non-null, this will be set to a Value* for the 02081 /// bit-field contents after the store, appropriate for use as the result of 02082 /// an assignment to the bit-field. 02083 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 02084 llvm::Value **Result=0); 02085 02086 /// Emit an l-value for an assignment (simple or compound) of complex type. 02087 LValue EmitComplexAssignmentLValue(const BinaryOperator *E); 02088 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E); 02089 02090 // Note: only available for agg return types 02091 LValue EmitBinaryOperatorLValue(const BinaryOperator *E); 02092 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E); 02093 // Note: only available for agg return types 02094 LValue EmitCallExprLValue(const CallExpr *E); 02095 // Note: only available for agg return types 02096 LValue EmitVAArgExprLValue(const VAArgExpr *E); 02097 LValue EmitDeclRefLValue(const DeclRefExpr *E); 02098 LValue EmitStringLiteralLValue(const StringLiteral *E); 02099 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E); 02100 LValue EmitPredefinedLValue(const PredefinedExpr *E); 02101 LValue EmitUnaryOpLValue(const UnaryOperator *E); 02102 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E); 02103 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E); 02104 LValue EmitMemberExpr(const MemberExpr *E); 02105 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E); 02106 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E); 02107 LValue EmitInitListLValue(const InitListExpr *E); 02108 LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E); 02109 LValue EmitCastLValue(const CastExpr *E); 02110 LValue EmitNullInitializationLValue(const CXXScalarValueInitExpr *E); 02111 LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 02112 LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e); 02113 02114 RValue EmitRValueForField(LValue LV, const FieldDecl *FD); 02115 02116 class ConstantEmission { 02117 llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference; 02118 ConstantEmission(llvm::Constant *C, bool isReference) 02119 : ValueAndIsReference(C, isReference) {} 02120 public: 02121 ConstantEmission() {} 02122 static ConstantEmission forReference(llvm::Constant *C) { 02123 return ConstantEmission(C, true); 02124 } 02125 static ConstantEmission forValue(llvm::Constant *C) { 02126 return ConstantEmission(C, false); 02127 } 02128 02129 operator bool() const { return ValueAndIsReference.getOpaqueValue() != 0; } 02130 02131 bool isReference() const { return ValueAndIsReference.getInt(); } 02132 LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const { 02133 assert(isReference()); 02134 return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(), 02135 refExpr->getType()); 02136 } 02137 02138 llvm::Constant *getValue() const { 02139 assert(!isReference()); 02140 return ValueAndIsReference.getPointer(); 02141 } 02142 }; 02143 02144 ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr); 02145 02146 RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, 02147 AggValueSlot slot = AggValueSlot::ignored()); 02148 LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e); 02149 02150 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface, 02151 const ObjCIvarDecl *Ivar); 02152 LValue EmitLValueForAnonRecordField(llvm::Value* Base, 02153 const IndirectFieldDecl* Field, 02154 unsigned CVRQualifiers); 02155 LValue EmitLValueForField(LValue Base, const FieldDecl* Field); 02156 02157 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that 02158 /// if the Field is a reference, this will return the address of the reference 02159 /// and not the address of the value stored in the reference. 02160 LValue EmitLValueForFieldInitialization(LValue Base, 02161 const FieldDecl* Field); 02162 02163 LValue EmitLValueForIvar(QualType ObjectTy, 02164 llvm::Value* Base, const ObjCIvarDecl *Ivar, 02165 unsigned CVRQualifiers); 02166 02167 LValue EmitLValueForBitfield(llvm::Value* Base, const FieldDecl* Field, 02168 unsigned CVRQualifiers); 02169 02170 LValue EmitCXXConstructLValue(const CXXConstructExpr *E); 02171 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E); 02172 LValue EmitLambdaLValue(const LambdaExpr *E); 02173 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E); 02174 02175 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E); 02176 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E); 02177 LValue EmitStmtExprLValue(const StmtExpr *E); 02178 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E); 02179 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E); 02180 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::Constant *Init); 02181 02182 //===--------------------------------------------------------------------===// 02183 // Scalar Expression Emission 02184 //===--------------------------------------------------------------------===// 02185 02186 /// EmitCall - Generate a call of the given function, expecting the given 02187 /// result type, and using the given argument list which specifies both the 02188 /// LLVM arguments and the types they were derived from. 02189 /// 02190 /// \param TargetDecl - If given, the decl of the function in a direct call; 02191 /// used to set attributes on the call (noreturn, etc.). 02192 RValue EmitCall(const CGFunctionInfo &FnInfo, 02193 llvm::Value *Callee, 02194 ReturnValueSlot ReturnValue, 02195 const CallArgList &Args, 02196 const Decl *TargetDecl = 0, 02197 llvm::Instruction **callOrInvoke = 0); 02198 02199 RValue EmitCall(QualType FnType, llvm::Value *Callee, 02200 ReturnValueSlot ReturnValue, 02201 CallExpr::const_arg_iterator ArgBeg, 02202 CallExpr::const_arg_iterator ArgEnd, 02203 const Decl *TargetDecl = 0); 02204 RValue EmitCallExpr(const CallExpr *E, 02205 ReturnValueSlot ReturnValue = ReturnValueSlot()); 02206 02207 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee, 02208 ArrayRef<llvm::Value *> Args, 02209 const Twine &Name = ""); 02210 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee, 02211 const Twine &Name = ""); 02212 02213 llvm::Value *BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This, 02214 llvm::Type *Ty); 02215 llvm::Value *BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type, 02216 llvm::Value *This, llvm::Type *Ty); 02217 llvm::Value *BuildAppleKextVirtualCall(const CXXMethodDecl *MD, 02218 NestedNameSpecifier *Qual, 02219 llvm::Type *Ty); 02220 02221 llvm::Value *BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD, 02222 CXXDtorType Type, 02223 const CXXRecordDecl *RD); 02224 02225 RValue EmitCXXMemberCall(const CXXMethodDecl *MD, 02226 llvm::Value *Callee, 02227 ReturnValueSlot ReturnValue, 02228 llvm::Value *This, 02229 llvm::Value *VTT, 02230 CallExpr::const_arg_iterator ArgBeg, 02231 CallExpr::const_arg_iterator ArgEnd); 02232 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E, 02233 ReturnValueSlot ReturnValue); 02234 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, 02235 ReturnValueSlot ReturnValue); 02236 02237 llvm::Value *EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E, 02238 const CXXMethodDecl *MD, 02239 llvm::Value *This); 02240 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 02241 const CXXMethodDecl *MD, 02242 ReturnValueSlot ReturnValue); 02243 02244 RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, 02245 ReturnValueSlot ReturnValue); 02246 02247 02248 RValue EmitBuiltinExpr(const FunctionDecl *FD, 02249 unsigned BuiltinID, const CallExpr *E); 02250 02251 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue); 02252 02253 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call 02254 /// is unhandled by the current target. 02255 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 02256 02257 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 02258 llvm::Value *EmitNeonCall(llvm::Function *F, 02259 SmallVectorImpl<llvm::Value*> &O, 02260 const char *name, 02261 unsigned shift = 0, bool rightshift = false); 02262 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx); 02263 llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty, 02264 bool negateForRightShift); 02265 02266 llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops); 02267 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 02268 llvm::Value *EmitHexagonBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 02269 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 02270 02271 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E); 02272 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E); 02273 llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E); 02274 llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E); 02275 llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E); 02276 llvm::Value *EmitObjCCollectionLiteral(const Expr *E, 02277 const ObjCMethodDecl *MethodWithObjects); 02278 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E); 02279 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, 02280 ReturnValueSlot Return = ReturnValueSlot()); 02281 02282 /// Retrieves the default cleanup kind for an ARC cleanup. 02283 /// Except under -fobjc-arc-eh, ARC cleanups are normal-only. 02284 CleanupKind getARCCleanupKind() { 02285 return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions 02286 ? NormalAndEHCleanup : NormalCleanup; 02287 } 02288 02289 // ARC primitives. 02290 void EmitARCInitWeak(llvm::Value *value, llvm::Value *addr); 02291 void EmitARCDestroyWeak(llvm::Value *addr); 02292 llvm::Value *EmitARCLoadWeak(llvm::Value *addr); 02293 llvm::Value *EmitARCLoadWeakRetained(llvm::Value *addr); 02294 llvm::Value *EmitARCStoreWeak(llvm::Value *value, llvm::Value *addr, 02295 bool ignored); 02296 void EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src); 02297 void EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src); 02298 llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value); 02299 llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value); 02300 llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value, 02301 bool ignored); 02302 llvm::Value *EmitARCStoreStrongCall(llvm::Value *addr, llvm::Value *value, 02303 bool ignored); 02304 llvm::Value *EmitARCRetain(QualType type, llvm::Value *value); 02305 llvm::Value *EmitARCRetainNonBlock(llvm::Value *value); 02306 llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory); 02307 void EmitARCRelease(llvm::Value *value, bool precise); 02308 llvm::Value *EmitARCAutorelease(llvm::Value *value); 02309 llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value); 02310 llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value); 02311 llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value); 02312 02313 std::pair<LValue,llvm::Value*> 02314 EmitARCStoreAutoreleasing(const BinaryOperator *e); 02315 std::pair<LValue,llvm::Value*> 02316 EmitARCStoreStrong(const BinaryOperator *e, bool ignored); 02317 02318 llvm::Value *EmitObjCThrowOperand(const Expr *expr); 02319 02320 llvm::Value *EmitObjCProduceObject(QualType T, llvm::Value *Ptr); 02321 llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr); 02322 llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr); 02323 02324 llvm::Value *EmitARCExtendBlockObject(const Expr *expr); 02325 llvm::Value *EmitARCRetainScalarExpr(const Expr *expr); 02326 llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr); 02327 02328 static Destroyer destroyARCStrongImprecise; 02329 static Destroyer destroyARCStrongPrecise; 02330 static Destroyer destroyARCWeak; 02331 02332 void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr); 02333 llvm::Value *EmitObjCAutoreleasePoolPush(); 02334 llvm::Value *EmitObjCMRRAutoreleasePoolPush(); 02335 void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr); 02336 void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr); 02337 02338 /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in 02339 /// expression. Will emit a temporary variable if E is not an LValue. 02340 RValue EmitReferenceBindingToExpr(const Expr* E, 02341 const NamedDecl *InitializedDecl); 02342 02343 //===--------------------------------------------------------------------===// 02344 // Expression Emission 02345 //===--------------------------------------------------------------------===// 02346 02347 // Expressions are broken into three classes: scalar, complex, aggregate. 02348 02349 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM 02350 /// scalar type, returning the result. 02351 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false); 02352 02353 /// EmitScalarConversion - Emit a conversion from the specified type to the 02354 /// specified destination type, both of which are LLVM scalar types. 02355 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy, 02356 QualType DstTy); 02357 02358 /// EmitComplexToScalarConversion - Emit a conversion from the specified 02359 /// complex type to the specified destination type, where the destination type 02360 /// is an LLVM scalar type. 02361 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, 02362 QualType DstTy); 02363 02364 02365 /// EmitAggExpr - Emit the computation of the specified expression 02366 /// of aggregate type. The result is computed into the given slot, 02367 /// which may be null to indicate that the value is not needed. 02368 void EmitAggExpr(const Expr *E, AggValueSlot AS, bool IgnoreResult = false); 02369 02370 /// EmitAggExprToLValue - Emit the computation of the specified expression of 02371 /// aggregate type into a temporary LValue. 02372 LValue EmitAggExprToLValue(const Expr *E); 02373 02374 /// EmitGCMemmoveCollectable - Emit special API for structs with object 02375 /// pointers. 02376 void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr, 02377 QualType Ty); 02378 02379 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object, 02380 /// make sure it survives garbage collection until this point. 02381 void EmitExtendGCLifetime(llvm::Value *object); 02382 02383 /// EmitComplexExpr - Emit the computation of the specified expression of 02384 /// complex type, returning the result. 02385 ComplexPairTy EmitComplexExpr(const Expr *E, 02386 bool IgnoreReal = false, 02387 bool IgnoreImag = false); 02388 02389 /// EmitComplexExprIntoAddr - Emit the computation of the specified expression 02390 /// of complex type, storing into the specified Value*. 02391 void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr, 02392 bool DestIsVolatile); 02393 02394 /// StoreComplexToAddr - Store a complex number into the specified address. 02395 void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr, 02396 bool DestIsVolatile); 02397 /// LoadComplexFromAddr - Load a complex number from the specified address. 02398 ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile); 02399 02400 /// CreateStaticVarDecl - Create a zero-initialized LLVM global for 02401 /// a static local variable. 02402 llvm::GlobalVariable *CreateStaticVarDecl(const VarDecl &D, 02403 const char *Separator, 02404 llvm::GlobalValue::LinkageTypes Linkage); 02405 02406 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the 02407 /// global variable that has already been created for it. If the initializer 02408 /// has a different type than GV does, this may free GV and return a different 02409 /// one. Otherwise it just returns GV. 02410 llvm::GlobalVariable * 02411 AddInitializerToStaticVarDecl(const VarDecl &D, 02412 llvm::GlobalVariable *GV); 02413 02414 02415 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++ 02416 /// variable with global storage. 02417 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr, 02418 bool PerformInit); 02419 02420 /// Call atexit() with a function that passes the given argument to 02421 /// the given function. 02422 void registerGlobalDtorWithAtExit(llvm::Constant *fn, llvm::Constant *addr); 02423 02424 /// Emit code in this function to perform a guarded variable 02425 /// initialization. Guarded initializations are used when it's not 02426 /// possible to prove that an initialization will be done exactly 02427 /// once, e.g. with a static local variable or a static data member 02428 /// of a class template. 02429 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr, 02430 bool PerformInit); 02431 02432 /// GenerateCXXGlobalInitFunc - Generates code for initializing global 02433 /// variables. 02434 void GenerateCXXGlobalInitFunc(llvm::Function *Fn, 02435 llvm::Constant **Decls, 02436 unsigned NumDecls); 02437 02438 /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global 02439 /// variables. 02440 void GenerateCXXGlobalDtorsFunc(llvm::Function *Fn, 02441 const std::vector<std::pair<llvm::WeakVH, 02442 llvm::Constant*> > &DtorsAndObjects); 02443 02444 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, 02445 const VarDecl *D, 02446 llvm::GlobalVariable *Addr, 02447 bool PerformInit); 02448 02449 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest); 02450 02451 void EmitSynthesizedCXXCopyCtor(llvm::Value *Dest, llvm::Value *Src, 02452 const Expr *Exp); 02453 02454 void enterFullExpression(const ExprWithCleanups *E) { 02455 if (E->getNumObjects() == 0) return; 02456 enterNonTrivialFullExpression(E); 02457 } 02458 void enterNonTrivialFullExpression(const ExprWithCleanups *E); 02459 02460 void EmitCXXThrowExpr(const CXXThrowExpr *E); 02461 02462 void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest); 02463 02464 RValue EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest = 0); 02465 02466 //===--------------------------------------------------------------------===// 02467 // Annotations Emission 02468 //===--------------------------------------------------------------------===// 02469 02470 /// Emit an annotation call (intrinsic or builtin). 02471 llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn, 02472 llvm::Value *AnnotatedVal, 02473 llvm::StringRef AnnotationStr, 02474 SourceLocation Location); 02475 02476 /// Emit local annotations for the local variable V, declared by D. 02477 void EmitVarAnnotations(const VarDecl *D, llvm::Value *V); 02478 02479 /// Emit field annotations for the given field & value. Returns the 02480 /// annotation result. 02481 llvm::Value *EmitFieldAnnotations(const FieldDecl *D, llvm::Value *V); 02482 02483 //===--------------------------------------------------------------------===// 02484 // Internal Helpers 02485 //===--------------------------------------------------------------------===// 02486 02487 /// ContainsLabel - Return true if the statement contains a label in it. If 02488 /// this statement is not executed normally, it not containing a label means 02489 /// that we can just remove the code. 02490 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false); 02491 02492 /// containsBreak - Return true if the statement contains a break out of it. 02493 /// If the statement (recursively) contains a switch or loop with a break 02494 /// inside of it, this is fine. 02495 static bool containsBreak(const Stmt *S); 02496 02497 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 02498 /// to a constant, or if it does but contains a label, return false. If it 02499 /// constant folds return true and set the boolean result in Result. 02500 bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result); 02501 02502 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 02503 /// to a constant, or if it does but contains a label, return false. If it 02504 /// constant folds return true and set the folded value. 02505 bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APInt &Result); 02506 02507 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an 02508 /// if statement) to the specified blocks. Based on the condition, this might 02509 /// try to simplify the codegen of the conditional based on the branch. 02510 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, 02511 llvm::BasicBlock *FalseBlock); 02512 02513 /// getTrapBB - Create a basic block that will call the trap intrinsic. We'll 02514 /// generate a branch around the created basic block as necessary. 02515 llvm::BasicBlock *getTrapBB(); 02516 02517 /// EmitCallArg - Emit a single call argument. 02518 void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType); 02519 02520 /// EmitDelegateCallArg - We are performing a delegate call; that 02521 /// is, the current function is delegating to another one. Produce 02522 /// a r-value suitable for passing the given parameter. 02523 void EmitDelegateCallArg(CallArgList &args, const VarDecl *param); 02524 02525 /// SetFPAccuracy - Set the minimum required accuracy of the given floating 02526 /// point operation, expressed as the maximum relative error in ulp. 02527 void SetFPAccuracy(llvm::Value *Val, float Accuracy); 02528 02529 private: 02530 llvm::MDNode *getRangeForLoadFromType(QualType Ty); 02531 void EmitReturnOfRValue(RValue RV, QualType Ty); 02532 02533 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty 02534 /// from function arguments into \arg Dst. See ABIArgInfo::Expand. 02535 /// 02536 /// \param AI - The first function argument of the expansion. 02537 /// \return The argument following the last expanded function 02538 /// argument. 02539 llvm::Function::arg_iterator 02540 ExpandTypeFromArgs(QualType Ty, LValue Dst, 02541 llvm::Function::arg_iterator AI); 02542 02543 /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg 02544 /// Ty, into individual arguments on the provided vector \arg Args. See 02545 /// ABIArgInfo::Expand. 02546 void ExpandTypeToArgs(QualType Ty, RValue Src, 02547 SmallVector<llvm::Value*, 16> &Args, 02548 llvm::FunctionType *IRFuncTy); 02549 02550 llvm::Value* EmitAsmInput(const AsmStmt &S, 02551 const TargetInfo::ConstraintInfo &Info, 02552 const Expr *InputExpr, std::string &ConstraintStr); 02553 02554 llvm::Value* EmitAsmInputLValue(const AsmStmt &S, 02555 const TargetInfo::ConstraintInfo &Info, 02556 LValue InputValue, QualType InputType, 02557 std::string &ConstraintStr); 02558 02559 /// EmitCallArgs - Emit call arguments for a function. 02560 /// The CallArgTypeInfo parameter is used for iterating over the known 02561 /// argument types of the function being called. 02562 template<typename T> 02563 void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo, 02564 CallExpr::const_arg_iterator ArgBeg, 02565 CallExpr::const_arg_iterator ArgEnd) { 02566 CallExpr::const_arg_iterator Arg = ArgBeg; 02567 02568 // First, use the argument types that the type info knows about 02569 if (CallArgTypeInfo) { 02570 for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(), 02571 E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) { 02572 assert(Arg != ArgEnd && "Running over edge of argument list!"); 02573 QualType ArgType = *I; 02574 #ifndef NDEBUG 02575 QualType ActualArgType = Arg->getType(); 02576 if (ArgType->isPointerType() && ActualArgType->isPointerType()) { 02577 QualType ActualBaseType = 02578 ActualArgType->getAs<PointerType>()->getPointeeType(); 02579 QualType ArgBaseType = 02580 ArgType->getAs<PointerType>()->getPointeeType(); 02581 if (ArgBaseType->isVariableArrayType()) { 02582 if (const VariableArrayType *VAT = 02583 getContext().getAsVariableArrayType(ActualBaseType)) { 02584 if (!VAT->getSizeExpr()) 02585 ActualArgType = ArgType; 02586 } 02587 } 02588 } 02589 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()). 02590 getTypePtr() == 02591 getContext().getCanonicalType(ActualArgType).getTypePtr() && 02592 "type mismatch in call argument!"); 02593 #endif 02594 EmitCallArg(Args, *Arg, ArgType); 02595 } 02596 02597 // Either we've emitted all the call args, or we have a call to a 02598 // variadic function. 02599 assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) && 02600 "Extra arguments in non-variadic function!"); 02601 02602 } 02603 02604 // If we still have any arguments, emit them using the type of the argument. 02605 for (; Arg != ArgEnd; ++Arg) 02606 EmitCallArg(Args, *Arg, Arg->getType()); 02607 } 02608 02609 const TargetCodeGenInfo &getTargetHooks() const { 02610 return CGM.getTargetCodeGenInfo(); 02611 } 02612 02613 void EmitDeclMetadata(); 02614 02615 CodeGenModule::ByrefHelpers * 02616 buildByrefHelpers(llvm::StructType &byrefType, 02617 const AutoVarEmission &emission); 02618 02619 void AddObjCARCExceptionMetadata(llvm::Instruction *Inst); 02620 02621 /// GetPointeeAlignment - Given an expression with a pointer type, find the 02622 /// alignment of the type referenced by the pointer. Skip over implicit 02623 /// casts. 02624 unsigned GetPointeeAlignment(const Expr *Addr); 02625 02626 /// GetPointeeAlignmentValue - Given an expression with a pointer type, find 02627 /// the alignment of the type referenced by the pointer. Skip over implicit 02628 /// casts. Return the alignment as an llvm::Value. 02629 llvm::Value *GetPointeeAlignmentValue(const Expr *Addr); 02630 }; 02631 02632 /// Helper class with most of the code for saving a value for a 02633 /// conditional expression cleanup. 02634 struct DominatingLLVMValue { 02635 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type; 02636 02637 /// Answer whether the given value needs extra work to be saved. 02638 static bool needsSaving(llvm::Value *value) { 02639 // If it's not an instruction, we don't need to save. 02640 if (!isa<llvm::Instruction>(value)) return false; 02641 02642 // If it's an instruction in the entry block, we don't need to save. 02643 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent(); 02644 return (block != &block->getParent()->getEntryBlock()); 02645 } 02646 02647 /// Try to save the given value. 02648 static saved_type save(CodeGenFunction &CGF, llvm::Value *value) { 02649 if (!needsSaving(value)) return saved_type(value, false); 02650 02651 // Otherwise we need an alloca. 02652 llvm::Value *alloca = 02653 CGF.CreateTempAlloca(value->getType(), "cond-cleanup.save"); 02654 CGF.Builder.CreateStore(value, alloca); 02655 02656 return saved_type(alloca, true); 02657 } 02658 02659 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) { 02660 if (!value.getInt()) return value.getPointer(); 02661 return CGF.Builder.CreateLoad(value.getPointer()); 02662 } 02663 }; 02664 02665 /// A partial specialization of DominatingValue for llvm::Values that 02666 /// might be llvm::Instructions. 02667 template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue { 02668 typedef T *type; 02669 static type restore(CodeGenFunction &CGF, saved_type value) { 02670 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value)); 02671 } 02672 }; 02673 02674 /// A specialization of DominatingValue for RValue. 02675 template <> struct DominatingValue<RValue> { 02676 typedef RValue type; 02677 class saved_type { 02678 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral, 02679 AggregateAddress, ComplexAddress }; 02680 02681 llvm::Value *Value; 02682 Kind K; 02683 saved_type(llvm::Value *v, Kind k) : Value(v), K(k) {} 02684 02685 public: 02686 static bool needsSaving(RValue value); 02687 static saved_type save(CodeGenFunction &CGF, RValue value); 02688 RValue restore(CodeGenFunction &CGF); 02689 02690 // implementations in CGExprCXX.cpp 02691 }; 02692 02693 static bool needsSaving(type value) { 02694 return saved_type::needsSaving(value); 02695 } 02696 static saved_type save(CodeGenFunction &CGF, type value) { 02697 return saved_type::save(CGF, value); 02698 } 02699 static type restore(CodeGenFunction &CGF, saved_type value) { 02700 return value.restore(CGF); 02701 } 02702 }; 02703 02704 } // end namespace CodeGen 02705 } // end namespace clang 02706 02707 #endif