CodeGenFunction.h revision bdc4d80956c83a486e58d3df6bb524a1f66ff574
1//===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This is the internal per-function state used for llvm translation. 11// 12//===----------------------------------------------------------------------===// 13 14#ifndef CLANG_CODEGEN_CODEGENFUNCTION_H 15#define CLANG_CODEGEN_CODEGENFUNCTION_H 16 17#include "clang/AST/Type.h" 18#include "clang/AST/ExprCXX.h" 19#include "clang/AST/ExprObjC.h" 20#include "clang/AST/CharUnits.h" 21#include "clang/Frontend/CodeGenOptions.h" 22#include "clang/Basic/ABI.h" 23#include "clang/Basic/TargetInfo.h" 24#include "llvm/ADT/DenseMap.h" 25#include "llvm/ADT/SmallVector.h" 26#include "llvm/Support/ValueHandle.h" 27#include "CodeGenModule.h" 28#include "CGBuilder.h" 29#include "CGValue.h" 30 31namespace llvm { 32 class BasicBlock; 33 class LLVMContext; 34 class MDNode; 35 class Module; 36 class SwitchInst; 37 class Twine; 38 class Value; 39 class CallSite; 40} 41 42namespace clang { 43 class APValue; 44 class ASTContext; 45 class CXXDestructorDecl; 46 class CXXForRangeStmt; 47 class CXXTryStmt; 48 class Decl; 49 class LabelDecl; 50 class EnumConstantDecl; 51 class FunctionDecl; 52 class FunctionProtoType; 53 class LabelStmt; 54 class ObjCContainerDecl; 55 class ObjCInterfaceDecl; 56 class ObjCIvarDecl; 57 class ObjCMethodDecl; 58 class ObjCImplementationDecl; 59 class ObjCPropertyImplDecl; 60 class TargetInfo; 61 class TargetCodeGenInfo; 62 class VarDecl; 63 class ObjCForCollectionStmt; 64 class ObjCAtTryStmt; 65 class ObjCAtThrowStmt; 66 class ObjCAtSynchronizedStmt; 67 class ObjCAutoreleasePoolStmt; 68 69namespace CodeGen { 70 class CodeGenTypes; 71 class CGDebugInfo; 72 class CGFunctionInfo; 73 class CGRecordLayout; 74 class CGBlockInfo; 75 class CGCXXABI; 76 class BlockFlags; 77 class BlockFieldFlags; 78 79/// A branch fixup. These are required when emitting a goto to a 80/// label which hasn't been emitted yet. The goto is optimistically 81/// emitted as a branch to the basic block for the label, and (if it 82/// occurs in a scope with non-trivial cleanups) a fixup is added to 83/// the innermost cleanup. When a (normal) cleanup is popped, any 84/// unresolved fixups in that scope are threaded through the cleanup. 85struct BranchFixup { 86 /// The block containing the terminator which needs to be modified 87 /// into a switch if this fixup is resolved into the current scope. 88 /// If null, LatestBranch points directly to the destination. 89 llvm::BasicBlock *OptimisticBranchBlock; 90 91 /// The ultimate destination of the branch. 92 /// 93 /// This can be set to null to indicate that this fixup was 94 /// successfully resolved. 95 llvm::BasicBlock *Destination; 96 97 /// The destination index value. 98 unsigned DestinationIndex; 99 100 /// The initial branch of the fixup. 101 llvm::BranchInst *InitialBranch; 102}; 103 104template <class T> struct InvariantValue { 105 typedef T type; 106 typedef T saved_type; 107 static bool needsSaving(type value) { return false; } 108 static saved_type save(CodeGenFunction &CGF, type value) { return value; } 109 static type restore(CodeGenFunction &CGF, saved_type value) { return value; } 110}; 111 112/// A metaprogramming class for ensuring that a value will dominate an 113/// arbitrary position in a function. 114template <class T> struct DominatingValue : InvariantValue<T> {}; 115 116template <class T, bool mightBeInstruction = 117 llvm::is_base_of<llvm::Value, T>::value && 118 !llvm::is_base_of<llvm::Constant, T>::value && 119 !llvm::is_base_of<llvm::BasicBlock, T>::value> 120struct DominatingPointer; 121template <class T> struct DominatingPointer<T,false> : InvariantValue<T*> {}; 122// template <class T> struct DominatingPointer<T,true> at end of file 123 124template <class T> struct DominatingValue<T*> : DominatingPointer<T> {}; 125 126enum CleanupKind { 127 EHCleanup = 0x1, 128 NormalCleanup = 0x2, 129 NormalAndEHCleanup = EHCleanup | NormalCleanup, 130 131 InactiveCleanup = 0x4, 132 InactiveEHCleanup = EHCleanup | InactiveCleanup, 133 InactiveNormalCleanup = NormalCleanup | InactiveCleanup, 134 InactiveNormalAndEHCleanup = NormalAndEHCleanup | InactiveCleanup 135}; 136 137/// A stack of scopes which respond to exceptions, including cleanups 138/// and catch blocks. 139class EHScopeStack { 140public: 141 /// A saved depth on the scope stack. This is necessary because 142 /// pushing scopes onto the stack invalidates iterators. 143 class stable_iterator { 144 friend class EHScopeStack; 145 146 /// Offset from StartOfData to EndOfBuffer. 147 ptrdiff_t Size; 148 149 stable_iterator(ptrdiff_t Size) : Size(Size) {} 150 151 public: 152 static stable_iterator invalid() { return stable_iterator(-1); } 153 stable_iterator() : Size(-1) {} 154 155 bool isValid() const { return Size >= 0; } 156 157 /// Returns true if this scope encloses I. 158 /// Returns false if I is invalid. 159 /// This scope must be valid. 160 bool encloses(stable_iterator I) const { return Size <= I.Size; } 161 162 /// Returns true if this scope strictly encloses I: that is, 163 /// if it encloses I and is not I. 164 /// Returns false is I is invalid. 165 /// This scope must be valid. 166 bool strictlyEncloses(stable_iterator I) const { return Size < I.Size; } 167 168 friend bool operator==(stable_iterator A, stable_iterator B) { 169 return A.Size == B.Size; 170 } 171 friend bool operator!=(stable_iterator A, stable_iterator B) { 172 return A.Size != B.Size; 173 } 174 }; 175 176 /// Information for lazily generating a cleanup. Subclasses must be 177 /// POD-like: cleanups will not be destructed, and they will be 178 /// allocated on the cleanup stack and freely copied and moved 179 /// around. 180 /// 181 /// Cleanup implementations should generally be declared in an 182 /// anonymous namespace. 183 class Cleanup { 184 public: 185 // Anchor the construction vtable. We use the destructor because 186 // gcc gives an obnoxious warning if there are virtual methods 187 // with an accessible non-virtual destructor. Unfortunately, 188 // declaring this destructor makes it non-trivial, but there 189 // doesn't seem to be any other way around this warning. 190 // 191 // This destructor will never be called. 192 virtual ~Cleanup(); 193 194 /// Emit the cleanup. For normal cleanups, this is run in the 195 /// same EH context as when the cleanup was pushed, i.e. the 196 /// immediately-enclosing context of the cleanup scope. For 197 /// EH cleanups, this is run in a terminate context. 198 /// 199 // \param IsForEHCleanup true if this is for an EH cleanup, false 200 /// if for a normal cleanup. 201 virtual void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) = 0; 202 }; 203 204 /// UnconditionalCleanupN stores its N parameters and just passes 205 /// them to the real cleanup function. 206 template <class T, class A0> 207 class UnconditionalCleanup1 : public Cleanup { 208 A0 a0; 209 public: 210 UnconditionalCleanup1(A0 a0) : a0(a0) {} 211 void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) { 212 T::Emit(CGF, IsForEHCleanup, a0); 213 } 214 }; 215 216 template <class T, class A0, class A1> 217 class UnconditionalCleanup2 : public Cleanup { 218 A0 a0; A1 a1; 219 public: 220 UnconditionalCleanup2(A0 a0, A1 a1) : a0(a0), a1(a1) {} 221 void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) { 222 T::Emit(CGF, IsForEHCleanup, a0, a1); 223 } 224 }; 225 226 template <class T, class A0, class A1, class A2> 227 class UnconditionalCleanup3 : public Cleanup { 228 A0 a0; A1 a1; A2 a2; 229 public: 230 UnconditionalCleanup3(A0 a0, A1 a1, A2 a2) : a0(a0), a1(a1), a2(a2) {} 231 void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) { 232 T::Emit(CGF, IsForEHCleanup, a0, a1, a2); 233 } 234 }; 235 236 /// ConditionalCleanupN stores the saved form of its N parameters, 237 /// then restores them and performs the cleanup. 238 template <class T, class A0> 239 class ConditionalCleanup1 : public Cleanup { 240 typedef typename DominatingValue<A0>::saved_type A0_saved; 241 A0_saved a0_saved; 242 243 void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) { 244 A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved); 245 T::Emit(CGF, IsForEHCleanup, a0); 246 } 247 248 public: 249 ConditionalCleanup1(A0_saved a0) 250 : a0_saved(a0) {} 251 }; 252 253 template <class T, class A0, class A1> 254 class ConditionalCleanup2 : public Cleanup { 255 typedef typename DominatingValue<A0>::saved_type A0_saved; 256 typedef typename DominatingValue<A1>::saved_type A1_saved; 257 A0_saved a0_saved; 258 A1_saved a1_saved; 259 260 void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) { 261 A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved); 262 A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved); 263 T::Emit(CGF, IsForEHCleanup, a0, a1); 264 } 265 266 public: 267 ConditionalCleanup2(A0_saved a0, A1_saved a1) 268 : a0_saved(a0), a1_saved(a1) {} 269 }; 270 271 template <class T, class A0, class A1, class A2> 272 class ConditionalCleanup3 : public Cleanup { 273 typedef typename DominatingValue<A0>::saved_type A0_saved; 274 typedef typename DominatingValue<A1>::saved_type A1_saved; 275 typedef typename DominatingValue<A2>::saved_type A2_saved; 276 A0_saved a0_saved; 277 A1_saved a1_saved; 278 A2_saved a2_saved; 279 280 void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) { 281 A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved); 282 A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved); 283 A2 a2 = DominatingValue<A2>::restore(CGF, a2_saved); 284 T::Emit(CGF, IsForEHCleanup, a0, a1, a2); 285 } 286 287 public: 288 ConditionalCleanup3(A0_saved a0, A1_saved a1, A2_saved a2) 289 : a0_saved(a0), a1_saved(a1), a2_saved(a2) {} 290 }; 291 292private: 293 // The implementation for this class is in CGException.h and 294 // CGException.cpp; the definition is here because it's used as a 295 // member of CodeGenFunction. 296 297 /// The start of the scope-stack buffer, i.e. the allocated pointer 298 /// for the buffer. All of these pointers are either simultaneously 299 /// null or simultaneously valid. 300 char *StartOfBuffer; 301 302 /// The end of the buffer. 303 char *EndOfBuffer; 304 305 /// The first valid entry in the buffer. 306 char *StartOfData; 307 308 /// The innermost normal cleanup on the stack. 309 stable_iterator InnermostNormalCleanup; 310 311 /// The innermost EH cleanup on the stack. 312 stable_iterator InnermostEHCleanup; 313 314 /// The number of catches on the stack. 315 unsigned CatchDepth; 316 317 /// The current EH destination index. Reset to FirstCatchIndex 318 /// whenever the last EH cleanup is popped. 319 unsigned NextEHDestIndex; 320 enum { FirstEHDestIndex = 1 }; 321 322 /// The current set of branch fixups. A branch fixup is a jump to 323 /// an as-yet unemitted label, i.e. a label for which we don't yet 324 /// know the EH stack depth. Whenever we pop a cleanup, we have 325 /// to thread all the current branch fixups through it. 326 /// 327 /// Fixups are recorded as the Use of the respective branch or 328 /// switch statement. The use points to the final destination. 329 /// When popping out of a cleanup, these uses are threaded through 330 /// the cleanup and adjusted to point to the new cleanup. 331 /// 332 /// Note that branches are allowed to jump into protected scopes 333 /// in certain situations; e.g. the following code is legal: 334 /// struct A { ~A(); }; // trivial ctor, non-trivial dtor 335 /// goto foo; 336 /// A a; 337 /// foo: 338 /// bar(); 339 llvm::SmallVector<BranchFixup, 8> BranchFixups; 340 341 char *allocate(size_t Size); 342 343 void *pushCleanup(CleanupKind K, size_t DataSize); 344 345public: 346 EHScopeStack() : StartOfBuffer(0), EndOfBuffer(0), StartOfData(0), 347 InnermostNormalCleanup(stable_end()), 348 InnermostEHCleanup(stable_end()), 349 CatchDepth(0), NextEHDestIndex(FirstEHDestIndex) {} 350 ~EHScopeStack() { delete[] StartOfBuffer; } 351 352 // Variadic templates would make this not terrible. 353 354 /// Push a lazily-created cleanup on the stack. 355 template <class T> 356 void pushCleanup(CleanupKind Kind) { 357 void *Buffer = pushCleanup(Kind, sizeof(T)); 358 Cleanup *Obj = new(Buffer) T(); 359 (void) Obj; 360 } 361 362 /// Push a lazily-created cleanup on the stack. 363 template <class T, class A0> 364 void pushCleanup(CleanupKind Kind, A0 a0) { 365 void *Buffer = pushCleanup(Kind, sizeof(T)); 366 Cleanup *Obj = new(Buffer) T(a0); 367 (void) Obj; 368 } 369 370 /// Push a lazily-created cleanup on the stack. 371 template <class T, class A0, class A1> 372 void pushCleanup(CleanupKind Kind, A0 a0, A1 a1) { 373 void *Buffer = pushCleanup(Kind, sizeof(T)); 374 Cleanup *Obj = new(Buffer) T(a0, a1); 375 (void) Obj; 376 } 377 378 /// Push a lazily-created cleanup on the stack. 379 template <class T, class A0, class A1, class A2> 380 void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2) { 381 void *Buffer = pushCleanup(Kind, sizeof(T)); 382 Cleanup *Obj = new(Buffer) T(a0, a1, a2); 383 (void) Obj; 384 } 385 386 /// Push a lazily-created cleanup on the stack. 387 template <class T, class A0, class A1, class A2, class A3> 388 void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3) { 389 void *Buffer = pushCleanup(Kind, sizeof(T)); 390 Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3); 391 (void) Obj; 392 } 393 394 /// Push a lazily-created cleanup on the stack. 395 template <class T, class A0, class A1, class A2, class A3, class A4> 396 void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { 397 void *Buffer = pushCleanup(Kind, sizeof(T)); 398 Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3, a4); 399 (void) Obj; 400 } 401 402 // Feel free to add more variants of the following: 403 404 /// Push a cleanup with non-constant storage requirements on the 405 /// stack. The cleanup type must provide an additional static method: 406 /// static size_t getExtraSize(size_t); 407 /// The argument to this method will be the value N, which will also 408 /// be passed as the first argument to the constructor. 409 /// 410 /// The data stored in the extra storage must obey the same 411 /// restrictions as normal cleanup member data. 412 /// 413 /// The pointer returned from this method is valid until the cleanup 414 /// stack is modified. 415 template <class T, class A0, class A1, class A2> 416 T *pushCleanupWithExtra(CleanupKind Kind, size_t N, A0 a0, A1 a1, A2 a2) { 417 void *Buffer = pushCleanup(Kind, sizeof(T) + T::getExtraSize(N)); 418 return new (Buffer) T(N, a0, a1, a2); 419 } 420 421 /// Pops a cleanup scope off the stack. This should only be called 422 /// by CodeGenFunction::PopCleanupBlock. 423 void popCleanup(); 424 425 /// Push a set of catch handlers on the stack. The catch is 426 /// uninitialized and will need to have the given number of handlers 427 /// set on it. 428 class EHCatchScope *pushCatch(unsigned NumHandlers); 429 430 /// Pops a catch scope off the stack. 431 void popCatch(); 432 433 /// Push an exceptions filter on the stack. 434 class EHFilterScope *pushFilter(unsigned NumFilters); 435 436 /// Pops an exceptions filter off the stack. 437 void popFilter(); 438 439 /// Push a terminate handler on the stack. 440 void pushTerminate(); 441 442 /// Pops a terminate handler off the stack. 443 void popTerminate(); 444 445 /// Determines whether the exception-scopes stack is empty. 446 bool empty() const { return StartOfData == EndOfBuffer; } 447 448 bool requiresLandingPad() const { 449 return (CatchDepth || hasEHCleanups()); 450 } 451 452 /// Determines whether there are any normal cleanups on the stack. 453 bool hasNormalCleanups() const { 454 return InnermostNormalCleanup != stable_end(); 455 } 456 457 /// Returns the innermost normal cleanup on the stack, or 458 /// stable_end() if there are no normal cleanups. 459 stable_iterator getInnermostNormalCleanup() const { 460 return InnermostNormalCleanup; 461 } 462 stable_iterator getInnermostActiveNormalCleanup() const; // CGException.h 463 464 /// Determines whether there are any EH cleanups on the stack. 465 bool hasEHCleanups() const { 466 return InnermostEHCleanup != stable_end(); 467 } 468 469 /// Returns the innermost EH cleanup on the stack, or stable_end() 470 /// if there are no EH cleanups. 471 stable_iterator getInnermostEHCleanup() const { 472 return InnermostEHCleanup; 473 } 474 stable_iterator getInnermostActiveEHCleanup() const; // CGException.h 475 476 /// An unstable reference to a scope-stack depth. Invalidated by 477 /// pushes but not pops. 478 class iterator; 479 480 /// Returns an iterator pointing to the innermost EH scope. 481 iterator begin() const; 482 483 /// Returns an iterator pointing to the outermost EH scope. 484 iterator end() const; 485 486 /// Create a stable reference to the top of the EH stack. The 487 /// returned reference is valid until that scope is popped off the 488 /// stack. 489 stable_iterator stable_begin() const { 490 return stable_iterator(EndOfBuffer - StartOfData); 491 } 492 493 /// Create a stable reference to the bottom of the EH stack. 494 static stable_iterator stable_end() { 495 return stable_iterator(0); 496 } 497 498 /// Translates an iterator into a stable_iterator. 499 stable_iterator stabilize(iterator it) const; 500 501 /// Finds the nearest cleanup enclosing the given iterator. 502 /// Returns stable_iterator::invalid() if there are no such cleanups. 503 stable_iterator getEnclosingEHCleanup(iterator it) const; 504 505 /// Turn a stable reference to a scope depth into a unstable pointer 506 /// to the EH stack. 507 iterator find(stable_iterator save) const; 508 509 /// Removes the cleanup pointed to by the given stable_iterator. 510 void removeCleanup(stable_iterator save); 511 512 /// Add a branch fixup to the current cleanup scope. 513 BranchFixup &addBranchFixup() { 514 assert(hasNormalCleanups() && "adding fixup in scope without cleanups"); 515 BranchFixups.push_back(BranchFixup()); 516 return BranchFixups.back(); 517 } 518 519 unsigned getNumBranchFixups() const { return BranchFixups.size(); } 520 BranchFixup &getBranchFixup(unsigned I) { 521 assert(I < getNumBranchFixups()); 522 return BranchFixups[I]; 523 } 524 525 /// Pops lazily-removed fixups from the end of the list. This 526 /// should only be called by procedures which have just popped a 527 /// cleanup or resolved one or more fixups. 528 void popNullFixups(); 529 530 /// Clears the branch-fixups list. This should only be called by 531 /// ResolveAllBranchFixups. 532 void clearFixups() { BranchFixups.clear(); } 533 534 /// Gets the next EH destination index. 535 unsigned getNextEHDestIndex() { return NextEHDestIndex++; } 536}; 537 538/// CodeGenFunction - This class organizes the per-function state that is used 539/// while generating LLVM code. 540class CodeGenFunction : public CodeGenTypeCache { 541 CodeGenFunction(const CodeGenFunction&); // DO NOT IMPLEMENT 542 void operator=(const CodeGenFunction&); // DO NOT IMPLEMENT 543 544 friend class CGCXXABI; 545public: 546 /// A jump destination is an abstract label, branching to which may 547 /// require a jump out through normal cleanups. 548 struct JumpDest { 549 JumpDest() : Block(0), ScopeDepth(), Index(0) {} 550 JumpDest(llvm::BasicBlock *Block, 551 EHScopeStack::stable_iterator Depth, 552 unsigned Index) 553 : Block(Block), ScopeDepth(Depth), Index(Index) {} 554 555 bool isValid() const { return Block != 0; } 556 llvm::BasicBlock *getBlock() const { return Block; } 557 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; } 558 unsigned getDestIndex() const { return Index; } 559 560 private: 561 llvm::BasicBlock *Block; 562 EHScopeStack::stable_iterator ScopeDepth; 563 unsigned Index; 564 }; 565 566 /// An unwind destination is an abstract label, branching to which 567 /// may require a jump out through EH cleanups. 568 struct UnwindDest { 569 UnwindDest() : Block(0), ScopeDepth(), Index(0) {} 570 UnwindDest(llvm::BasicBlock *Block, 571 EHScopeStack::stable_iterator Depth, 572 unsigned Index) 573 : Block(Block), ScopeDepth(Depth), Index(Index) {} 574 575 bool isValid() const { return Block != 0; } 576 llvm::BasicBlock *getBlock() const { return Block; } 577 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; } 578 unsigned getDestIndex() const { return Index; } 579 580 private: 581 llvm::BasicBlock *Block; 582 EHScopeStack::stable_iterator ScopeDepth; 583 unsigned Index; 584 }; 585 586 CodeGenModule &CGM; // Per-module state. 587 const TargetInfo &Target; 588 589 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy; 590 CGBuilderTy Builder; 591 592 /// CurFuncDecl - Holds the Decl for the current function or ObjC method. 593 /// This excludes BlockDecls. 594 const Decl *CurFuncDecl; 595 /// CurCodeDecl - This is the inner-most code context, which includes blocks. 596 const Decl *CurCodeDecl; 597 const CGFunctionInfo *CurFnInfo; 598 QualType FnRetTy; 599 llvm::Function *CurFn; 600 601 /// CurGD - The GlobalDecl for the current function being compiled. 602 GlobalDecl CurGD; 603 604 /// PrologueCleanupDepth - The cleanup depth enclosing all the 605 /// cleanups associated with the parameters. 606 EHScopeStack::stable_iterator PrologueCleanupDepth; 607 608 /// ReturnBlock - Unified return block. 609 JumpDest ReturnBlock; 610 611 /// ReturnValue - The temporary alloca to hold the return value. This is null 612 /// iff the function has no return value. 613 llvm::Value *ReturnValue; 614 615 /// RethrowBlock - Unified rethrow block. 616 UnwindDest RethrowBlock; 617 618 /// AllocaInsertPoint - This is an instruction in the entry block before which 619 /// we prefer to insert allocas. 620 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt; 621 622 bool CatchUndefined; 623 624 /// In ARC, whether we should autorelease the return value. 625 bool AutoreleaseResult; 626 627 const CodeGen::CGBlockInfo *BlockInfo; 628 llvm::Value *BlockPointer; 629 630 /// \brief A mapping from NRVO variables to the flags used to indicate 631 /// when the NRVO has been applied to this variable. 632 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags; 633 634 EHScopeStack EHStack; 635 636 /// i32s containing the indexes of the cleanup destinations. 637 llvm::AllocaInst *NormalCleanupDest; 638 llvm::AllocaInst *EHCleanupDest; 639 640 unsigned NextCleanupDestIndex; 641 642 /// The exception slot. All landing pads write the current 643 /// exception pointer into this alloca. 644 llvm::Value *ExceptionSlot; 645 646 /// The selector slot. Under the MandatoryCleanup model, all 647 /// landing pads write the current selector value into this alloca. 648 llvm::AllocaInst *EHSelectorSlot; 649 650 /// Emits a landing pad for the current EH stack. 651 llvm::BasicBlock *EmitLandingPad(); 652 653 llvm::BasicBlock *getInvokeDestImpl(); 654 655 /// Set up the last cleaup that was pushed as a conditional 656 /// full-expression cleanup. 657 void initFullExprCleanup(); 658 659 template <class T> 660 typename DominatingValue<T>::saved_type saveValueInCond(T value) { 661 return DominatingValue<T>::save(*this, value); 662 } 663 664public: 665 /// ObjCEHValueStack - Stack of Objective-C exception values, used for 666 /// rethrows. 667 llvm::SmallVector<llvm::Value*, 8> ObjCEHValueStack; 668 669 /// A class controlling the emission of a finally block. 670 class FinallyInfo { 671 /// Where the catchall's edge through the cleanup should go. 672 JumpDest RethrowDest; 673 674 /// A function to call to enter the catch. 675 llvm::Constant *BeginCatchFn; 676 677 /// An i1 variable indicating whether or not the @finally is 678 /// running for an exception. 679 llvm::AllocaInst *ForEHVar; 680 681 /// An i8* variable into which the exception pointer to rethrow 682 /// has been saved. 683 llvm::AllocaInst *SavedExnVar; 684 685 public: 686 void enter(CodeGenFunction &CGF, const Stmt *Finally, 687 llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn, 688 llvm::Constant *rethrowFn); 689 void exit(CodeGenFunction &CGF); 690 }; 691 692 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 693 /// current full-expression. Safe against the possibility that 694 /// we're currently inside a conditionally-evaluated expression. 695 template <class T, class A0> 696 void pushFullExprCleanup(CleanupKind kind, A0 a0) { 697 // If we're not in a conditional branch, or if none of the 698 // arguments requires saving, then use the unconditional cleanup. 699 if (!isInConditionalBranch()) { 700 typedef EHScopeStack::UnconditionalCleanup1<T, A0> CleanupType; 701 return EHStack.pushCleanup<CleanupType>(kind, a0); 702 } 703 704 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 705 706 typedef EHScopeStack::ConditionalCleanup1<T, A0> CleanupType; 707 EHStack.pushCleanup<CleanupType>(kind, a0_saved); 708 initFullExprCleanup(); 709 } 710 711 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 712 /// current full-expression. Safe against the possibility that 713 /// we're currently inside a conditionally-evaluated expression. 714 template <class T, class A0, class A1> 715 void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1) { 716 // If we're not in a conditional branch, or if none of the 717 // arguments requires saving, then use the unconditional cleanup. 718 if (!isInConditionalBranch()) { 719 typedef EHScopeStack::UnconditionalCleanup2<T, A0, A1> CleanupType; 720 return EHStack.pushCleanup<CleanupType>(kind, a0, a1); 721 } 722 723 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 724 typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1); 725 726 typedef EHScopeStack::ConditionalCleanup2<T, A0, A1> CleanupType; 727 EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved); 728 initFullExprCleanup(); 729 } 730 731 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 732 /// current full-expression. Safe against the possibility that 733 /// we're currently inside a conditionally-evaluated expression. 734 template <class T, class A0, class A1, class A2> 735 void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2) { 736 // If we're not in a conditional branch, or if none of the 737 // arguments requires saving, then use the unconditional cleanup. 738 if (!isInConditionalBranch()) { 739 typedef EHScopeStack::UnconditionalCleanup3<T, A0, A1, A2> CleanupType; 740 return EHStack.pushCleanup<CleanupType>(kind, a0, a1, a2); 741 } 742 743 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 744 typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1); 745 typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2); 746 747 typedef EHScopeStack::ConditionalCleanup3<T, A0, A1, A2> CleanupType; 748 EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved, a2_saved); 749 initFullExprCleanup(); 750 } 751 752 /// PushDestructorCleanup - Push a cleanup to call the 753 /// complete-object destructor of an object of the given type at the 754 /// given address. Does nothing if T is not a C++ class type with a 755 /// non-trivial destructor. 756 void PushDestructorCleanup(QualType T, llvm::Value *Addr); 757 758 /// PushDestructorCleanup - Push a cleanup to call the 759 /// complete-object variant of the given destructor on the object at 760 /// the given address. 761 void PushDestructorCleanup(const CXXDestructorDecl *Dtor, 762 llvm::Value *Addr); 763 764 /// PopCleanupBlock - Will pop the cleanup entry on the stack and 765 /// process all branch fixups. 766 void PopCleanupBlock(bool FallThroughIsBranchThrough = false); 767 768 /// DeactivateCleanupBlock - Deactivates the given cleanup block. 769 /// The block cannot be reactivated. Pops it if it's the top of the 770 /// stack. 771 void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup); 772 773 /// ActivateCleanupBlock - Activates an initially-inactive cleanup. 774 /// Cannot be used to resurrect a deactivated cleanup. 775 void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup); 776 777 /// \brief Enters a new scope for capturing cleanups, all of which 778 /// will be executed once the scope is exited. 779 class RunCleanupsScope { 780 CodeGenFunction& CGF; 781 EHScopeStack::stable_iterator CleanupStackDepth; 782 bool OldDidCallStackSave; 783 bool PerformCleanup; 784 785 RunCleanupsScope(const RunCleanupsScope &); // DO NOT IMPLEMENT 786 RunCleanupsScope &operator=(const RunCleanupsScope &); // DO NOT IMPLEMENT 787 788 public: 789 /// \brief Enter a new cleanup scope. 790 explicit RunCleanupsScope(CodeGenFunction &CGF) 791 : CGF(CGF), PerformCleanup(true) 792 { 793 CleanupStackDepth = CGF.EHStack.stable_begin(); 794 OldDidCallStackSave = CGF.DidCallStackSave; 795 CGF.DidCallStackSave = false; 796 } 797 798 /// \brief Exit this cleanup scope, emitting any accumulated 799 /// cleanups. 800 ~RunCleanupsScope() { 801 if (PerformCleanup) { 802 CGF.DidCallStackSave = OldDidCallStackSave; 803 CGF.PopCleanupBlocks(CleanupStackDepth); 804 } 805 } 806 807 /// \brief Determine whether this scope requires any cleanups. 808 bool requiresCleanups() const { 809 return CGF.EHStack.stable_begin() != CleanupStackDepth; 810 } 811 812 /// \brief Force the emission of cleanups now, instead of waiting 813 /// until this object is destroyed. 814 void ForceCleanup() { 815 assert(PerformCleanup && "Already forced cleanup"); 816 CGF.DidCallStackSave = OldDidCallStackSave; 817 CGF.PopCleanupBlocks(CleanupStackDepth); 818 PerformCleanup = false; 819 } 820 }; 821 822 823 /// PopCleanupBlocks - Takes the old cleanup stack size and emits 824 /// the cleanup blocks that have been added. 825 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize); 826 827 void ResolveBranchFixups(llvm::BasicBlock *Target); 828 829 /// The given basic block lies in the current EH scope, but may be a 830 /// target of a potentially scope-crossing jump; get a stable handle 831 /// to which we can perform this jump later. 832 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) { 833 return JumpDest(Target, 834 EHStack.getInnermostNormalCleanup(), 835 NextCleanupDestIndex++); 836 } 837 838 /// The given basic block lies in the current EH scope, but may be a 839 /// target of a potentially scope-crossing jump; get a stable handle 840 /// to which we can perform this jump later. 841 JumpDest getJumpDestInCurrentScope(llvm::StringRef Name = llvm::StringRef()) { 842 return getJumpDestInCurrentScope(createBasicBlock(Name)); 843 } 844 845 /// EmitBranchThroughCleanup - Emit a branch from the current insert 846 /// block through the normal cleanup handling code (if any) and then 847 /// on to \arg Dest. 848 void EmitBranchThroughCleanup(JumpDest Dest); 849 850 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the 851 /// specified destination obviously has no cleanups to run. 'false' is always 852 /// a conservatively correct answer for this method. 853 bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const; 854 855 /// EmitBranchThroughEHCleanup - Emit a branch from the current 856 /// insert block through the EH cleanup handling code (if any) and 857 /// then on to \arg Dest. 858 void EmitBranchThroughEHCleanup(UnwindDest Dest); 859 860 /// getRethrowDest - Returns the unified outermost-scope rethrow 861 /// destination. 862 UnwindDest getRethrowDest(); 863 864 /// An object to manage conditionally-evaluated expressions. 865 class ConditionalEvaluation { 866 llvm::BasicBlock *StartBB; 867 868 public: 869 ConditionalEvaluation(CodeGenFunction &CGF) 870 : StartBB(CGF.Builder.GetInsertBlock()) {} 871 872 void begin(CodeGenFunction &CGF) { 873 assert(CGF.OutermostConditional != this); 874 if (!CGF.OutermostConditional) 875 CGF.OutermostConditional = this; 876 } 877 878 void end(CodeGenFunction &CGF) { 879 assert(CGF.OutermostConditional != 0); 880 if (CGF.OutermostConditional == this) 881 CGF.OutermostConditional = 0; 882 } 883 884 /// Returns a block which will be executed prior to each 885 /// evaluation of the conditional code. 886 llvm::BasicBlock *getStartingBlock() const { 887 return StartBB; 888 } 889 }; 890 891 /// isInConditionalBranch - Return true if we're currently emitting 892 /// one branch or the other of a conditional expression. 893 bool isInConditionalBranch() const { return OutermostConditional != 0; } 894 895 /// An RAII object to record that we're evaluating a statement 896 /// expression. 897 class StmtExprEvaluation { 898 CodeGenFunction &CGF; 899 900 /// We have to save the outermost conditional: cleanups in a 901 /// statement expression aren't conditional just because the 902 /// StmtExpr is. 903 ConditionalEvaluation *SavedOutermostConditional; 904 905 public: 906 StmtExprEvaluation(CodeGenFunction &CGF) 907 : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) { 908 CGF.OutermostConditional = 0; 909 } 910 911 ~StmtExprEvaluation() { 912 CGF.OutermostConditional = SavedOutermostConditional; 913 CGF.EnsureInsertPoint(); 914 } 915 }; 916 917 /// An object which temporarily prevents a value from being 918 /// destroyed by aggressive peephole optimizations that assume that 919 /// all uses of a value have been realized in the IR. 920 class PeepholeProtection { 921 llvm::Instruction *Inst; 922 friend class CodeGenFunction; 923 924 public: 925 PeepholeProtection() : Inst(0) {} 926 }; 927 928 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr. 929 class OpaqueValueMapping { 930 CodeGenFunction &CGF; 931 const OpaqueValueExpr *OpaqueValue; 932 bool BoundLValue; 933 CodeGenFunction::PeepholeProtection Protection; 934 935 public: 936 static bool shouldBindAsLValue(const Expr *expr) { 937 return expr->isGLValue() || expr->getType()->isRecordType(); 938 } 939 940 /// Build the opaque value mapping for the given conditional 941 /// operator if it's the GNU ?: extension. This is a common 942 /// enough pattern that the convenience operator is really 943 /// helpful. 944 /// 945 OpaqueValueMapping(CodeGenFunction &CGF, 946 const AbstractConditionalOperator *op) : CGF(CGF) { 947 if (isa<ConditionalOperator>(op)) { 948 OpaqueValue = 0; 949 BoundLValue = false; 950 return; 951 } 952 953 const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op); 954 init(e->getOpaqueValue(), e->getCommon()); 955 } 956 957 OpaqueValueMapping(CodeGenFunction &CGF, 958 const OpaqueValueExpr *opaqueValue, 959 LValue lvalue) 960 : CGF(CGF), OpaqueValue(opaqueValue), BoundLValue(true) { 961 assert(opaqueValue && "no opaque value expression!"); 962 assert(shouldBindAsLValue(opaqueValue)); 963 initLValue(lvalue); 964 } 965 966 OpaqueValueMapping(CodeGenFunction &CGF, 967 const OpaqueValueExpr *opaqueValue, 968 RValue rvalue) 969 : CGF(CGF), OpaqueValue(opaqueValue), BoundLValue(false) { 970 assert(opaqueValue && "no opaque value expression!"); 971 assert(!shouldBindAsLValue(opaqueValue)); 972 initRValue(rvalue); 973 } 974 975 void pop() { 976 assert(OpaqueValue && "mapping already popped!"); 977 popImpl(); 978 OpaqueValue = 0; 979 } 980 981 ~OpaqueValueMapping() { 982 if (OpaqueValue) popImpl(); 983 } 984 985 private: 986 void popImpl() { 987 if (BoundLValue) 988 CGF.OpaqueLValues.erase(OpaqueValue); 989 else { 990 CGF.OpaqueRValues.erase(OpaqueValue); 991 CGF.unprotectFromPeepholes(Protection); 992 } 993 } 994 995 void init(const OpaqueValueExpr *ov, const Expr *e) { 996 OpaqueValue = ov; 997 BoundLValue = shouldBindAsLValue(ov); 998 assert(BoundLValue == shouldBindAsLValue(e) 999 && "inconsistent expression value kinds!"); 1000 if (BoundLValue) 1001 initLValue(CGF.EmitLValue(e)); 1002 else 1003 initRValue(CGF.EmitAnyExpr(e)); 1004 } 1005 1006 void initLValue(const LValue &lv) { 1007 CGF.OpaqueLValues.insert(std::make_pair(OpaqueValue, lv)); 1008 } 1009 1010 void initRValue(const RValue &rv) { 1011 // Work around an extremely aggressive peephole optimization in 1012 // EmitScalarConversion which assumes that all other uses of a 1013 // value are extant. 1014 Protection = CGF.protectFromPeepholes(rv); 1015 CGF.OpaqueRValues.insert(std::make_pair(OpaqueValue, rv)); 1016 } 1017 }; 1018 1019 /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field 1020 /// number that holds the value. 1021 unsigned getByRefValueLLVMField(const ValueDecl *VD) const; 1022 1023 /// BuildBlockByrefAddress - Computes address location of the 1024 /// variable which is declared as __block. 1025 llvm::Value *BuildBlockByrefAddress(llvm::Value *BaseAddr, 1026 const VarDecl *V); 1027private: 1028 CGDebugInfo *DebugInfo; 1029 bool DisableDebugInfo; 1030 1031 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid 1032 /// calling llvm.stacksave for multiple VLAs in the same scope. 1033 bool DidCallStackSave; 1034 1035 /// IndirectBranch - The first time an indirect goto is seen we create a block 1036 /// with an indirect branch. Every time we see the address of a label taken, 1037 /// we add the label to the indirect goto. Every subsequent indirect goto is 1038 /// codegen'd as a jump to the IndirectBranch's basic block. 1039 llvm::IndirectBrInst *IndirectBranch; 1040 1041 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C 1042 /// decls. 1043 typedef llvm::DenseMap<const Decl*, llvm::Value*> DeclMapTy; 1044 DeclMapTy LocalDeclMap; 1045 1046 /// LabelMap - This keeps track of the LLVM basic block for each C label. 1047 llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap; 1048 1049 // BreakContinueStack - This keeps track of where break and continue 1050 // statements should jump to. 1051 struct BreakContinue { 1052 BreakContinue(JumpDest Break, JumpDest Continue) 1053 : BreakBlock(Break), ContinueBlock(Continue) {} 1054 1055 JumpDest BreakBlock; 1056 JumpDest ContinueBlock; 1057 }; 1058 llvm::SmallVector<BreakContinue, 8> BreakContinueStack; 1059 1060 /// SwitchInsn - This is nearest current switch instruction. It is null if if 1061 /// current context is not in a switch. 1062 llvm::SwitchInst *SwitchInsn; 1063 1064 /// CaseRangeBlock - This block holds if condition check for last case 1065 /// statement range in current switch instruction. 1066 llvm::BasicBlock *CaseRangeBlock; 1067 1068 /// OpaqueLValues - Keeps track of the current set of opaque value 1069 /// expressions. 1070 llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues; 1071 llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues; 1072 1073 // VLASizeMap - This keeps track of the associated size for each VLA type. 1074 // We track this by the size expression rather than the type itself because 1075 // in certain situations, like a const qualifier applied to an VLA typedef, 1076 // multiple VLA types can share the same size expression. 1077 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we 1078 // enter/leave scopes. 1079 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap; 1080 1081 /// A block containing a single 'unreachable' instruction. Created 1082 /// lazily by getUnreachableBlock(). 1083 llvm::BasicBlock *UnreachableBlock; 1084 1085 /// CXXThisDecl - When generating code for a C++ member function, 1086 /// this will hold the implicit 'this' declaration. 1087 ImplicitParamDecl *CXXThisDecl; 1088 llvm::Value *CXXThisValue; 1089 1090 /// CXXVTTDecl - When generating code for a base object constructor or 1091 /// base object destructor with virtual bases, this will hold the implicit 1092 /// VTT parameter. 1093 ImplicitParamDecl *CXXVTTDecl; 1094 llvm::Value *CXXVTTValue; 1095 1096 /// OutermostConditional - Points to the outermost active 1097 /// conditional control. This is used so that we know if a 1098 /// temporary should be destroyed conditionally. 1099 ConditionalEvaluation *OutermostConditional; 1100 1101 1102 /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM 1103 /// type as well as the field number that contains the actual data. 1104 llvm::DenseMap<const ValueDecl *, std::pair<const llvm::Type *, 1105 unsigned> > ByRefValueInfo; 1106 1107 llvm::BasicBlock *TerminateLandingPad; 1108 llvm::BasicBlock *TerminateHandler; 1109 llvm::BasicBlock *TrapBB; 1110 1111public: 1112 CodeGenFunction(CodeGenModule &cgm); 1113 1114 CodeGenTypes &getTypes() const { return CGM.getTypes(); } 1115 ASTContext &getContext() const { return CGM.getContext(); } 1116 CGDebugInfo *getDebugInfo() { 1117 if (DisableDebugInfo) 1118 return NULL; 1119 return DebugInfo; 1120 } 1121 void disableDebugInfo() { DisableDebugInfo = true; } 1122 void enableDebugInfo() { DisableDebugInfo = false; } 1123 1124 bool shouldUseFusedARCCalls() { 1125 return CGM.getCodeGenOpts().OptimizationLevel == 0; 1126 } 1127 1128 const LangOptions &getLangOptions() const { return CGM.getLangOptions(); } 1129 1130 /// Returns a pointer to the function's exception object slot, which 1131 /// is assigned in every landing pad. 1132 llvm::Value *getExceptionSlot(); 1133 llvm::Value *getEHSelectorSlot(); 1134 1135 llvm::Value *getNormalCleanupDestSlot(); 1136 llvm::Value *getEHCleanupDestSlot(); 1137 1138 llvm::BasicBlock *getUnreachableBlock() { 1139 if (!UnreachableBlock) { 1140 UnreachableBlock = createBasicBlock("unreachable"); 1141 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock); 1142 } 1143 return UnreachableBlock; 1144 } 1145 1146 llvm::BasicBlock *getInvokeDest() { 1147 if (!EHStack.requiresLandingPad()) return 0; 1148 return getInvokeDestImpl(); 1149 } 1150 1151 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); } 1152 1153 //===--------------------------------------------------------------------===// 1154 // Cleanups 1155 //===--------------------------------------------------------------------===// 1156 1157 typedef void Destroyer(CodeGenFunction &CGF, llvm::Value *addr, QualType ty); 1158 1159 void pushPartialArrayCleanup(llvm::Value *arrayBegin, 1160 QualType elementType, 1161 Destroyer &destroyer, 1162 llvm::Value *arrayEndPointer); 1163 1164 Destroyer &getDestroyer(QualType::DestructionKind destructionKind); 1165 void pushDestroy(CleanupKind kind, llvm::Value *addr, QualType type, 1166 Destroyer &destroyer); 1167 void emitDestroy(llvm::Value *addr, QualType type, Destroyer &destroyer); 1168 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end, 1169 QualType type, Destroyer &destroyer); 1170 1171 /// Determines whether an EH cleanup is required to destroy a type 1172 /// with the given destruction kind. 1173 bool needsEHCleanup(QualType::DestructionKind kind) { 1174 switch (kind) { 1175 case QualType::DK_none: 1176 return false; 1177 case QualType::DK_cxx_destructor: 1178 case QualType::DK_objc_weak_lifetime: 1179 return getLangOptions().Exceptions; 1180 case QualType::DK_objc_strong_lifetime: 1181 return getLangOptions().Exceptions && 1182 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions; 1183 } 1184 llvm_unreachable("bad destruction kind"); 1185 } 1186 1187 //===--------------------------------------------------------------------===// 1188 // Objective-C 1189 //===--------------------------------------------------------------------===// 1190 1191 void GenerateObjCMethod(const ObjCMethodDecl *OMD); 1192 1193 void StartObjCMethod(const ObjCMethodDecl *MD, 1194 const ObjCContainerDecl *CD, 1195 SourceLocation StartLoc); 1196 1197 /// GenerateObjCGetter - Synthesize an Objective-C property getter function. 1198 void GenerateObjCGetter(ObjCImplementationDecl *IMP, 1199 const ObjCPropertyImplDecl *PID); 1200 void GenerateObjCGetterBody(ObjCIvarDecl *Ivar, bool IsAtomic, bool IsStrong); 1201 void GenerateObjCAtomicSetterBody(ObjCMethodDecl *OMD, 1202 ObjCIvarDecl *Ivar); 1203 1204 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, 1205 ObjCMethodDecl *MD, bool ctor); 1206 1207 /// GenerateObjCSetter - Synthesize an Objective-C property setter function 1208 /// for the given property. 1209 void GenerateObjCSetter(ObjCImplementationDecl *IMP, 1210 const ObjCPropertyImplDecl *PID); 1211 bool IndirectObjCSetterArg(const CGFunctionInfo &FI); 1212 bool IvarTypeWithAggrGCObjects(QualType Ty); 1213 1214 //===--------------------------------------------------------------------===// 1215 // Block Bits 1216 //===--------------------------------------------------------------------===// 1217 1218 llvm::Value *EmitBlockLiteral(const BlockExpr *); 1219 llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *, 1220 const CGBlockInfo &Info, 1221 const llvm::StructType *, 1222 llvm::Constant *BlockVarLayout); 1223 1224 llvm::Function *GenerateBlockFunction(GlobalDecl GD, 1225 const CGBlockInfo &Info, 1226 const Decl *OuterFuncDecl, 1227 const DeclMapTy &ldm); 1228 1229 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo); 1230 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo); 1231 1232 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags); 1233 1234 class AutoVarEmission; 1235 1236 void emitByrefStructureInit(const AutoVarEmission &emission); 1237 void enterByrefCleanup(const AutoVarEmission &emission); 1238 1239 llvm::Value *LoadBlockStruct() { 1240 assert(BlockPointer && "no block pointer set!"); 1241 return BlockPointer; 1242 } 1243 1244 void AllocateBlockCXXThisPointer(const CXXThisExpr *E); 1245 void AllocateBlockDecl(const BlockDeclRefExpr *E); 1246 llvm::Value *GetAddrOfBlockDecl(const BlockDeclRefExpr *E) { 1247 return GetAddrOfBlockDecl(E->getDecl(), E->isByRef()); 1248 } 1249 llvm::Value *GetAddrOfBlockDecl(const VarDecl *var, bool ByRef); 1250 const llvm::Type *BuildByRefType(const VarDecl *var); 1251 1252 void GenerateCode(GlobalDecl GD, llvm::Function *Fn, 1253 const CGFunctionInfo &FnInfo); 1254 void StartFunction(GlobalDecl GD, QualType RetTy, 1255 llvm::Function *Fn, 1256 const CGFunctionInfo &FnInfo, 1257 const FunctionArgList &Args, 1258 SourceLocation StartLoc); 1259 1260 void EmitConstructorBody(FunctionArgList &Args); 1261 void EmitDestructorBody(FunctionArgList &Args); 1262 void EmitFunctionBody(FunctionArgList &Args); 1263 1264 /// EmitReturnBlock - Emit the unified return block, trying to avoid its 1265 /// emission when possible. 1266 void EmitReturnBlock(); 1267 1268 /// FinishFunction - Complete IR generation of the current function. It is 1269 /// legal to call this function even if there is no current insertion point. 1270 void FinishFunction(SourceLocation EndLoc=SourceLocation()); 1271 1272 /// GenerateThunk - Generate a thunk for the given method. 1273 void GenerateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, 1274 GlobalDecl GD, const ThunkInfo &Thunk); 1275 1276 void GenerateVarArgsThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, 1277 GlobalDecl GD, const ThunkInfo &Thunk); 1278 1279 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type, 1280 FunctionArgList &Args); 1281 1282 /// InitializeVTablePointer - Initialize the vtable pointer of the given 1283 /// subobject. 1284 /// 1285 void InitializeVTablePointer(BaseSubobject Base, 1286 const CXXRecordDecl *NearestVBase, 1287 CharUnits OffsetFromNearestVBase, 1288 llvm::Constant *VTable, 1289 const CXXRecordDecl *VTableClass); 1290 1291 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy; 1292 void InitializeVTablePointers(BaseSubobject Base, 1293 const CXXRecordDecl *NearestVBase, 1294 CharUnits OffsetFromNearestVBase, 1295 bool BaseIsNonVirtualPrimaryBase, 1296 llvm::Constant *VTable, 1297 const CXXRecordDecl *VTableClass, 1298 VisitedVirtualBasesSetTy& VBases); 1299 1300 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl); 1301 1302 /// GetVTablePtr - Return the Value of the vtable pointer member pointed 1303 /// to by This. 1304 llvm::Value *GetVTablePtr(llvm::Value *This, const llvm::Type *Ty); 1305 1306 /// EnterDtorCleanups - Enter the cleanups necessary to complete the 1307 /// given phase of destruction for a destructor. The end result 1308 /// should call destructors on members and base classes in reverse 1309 /// order of their construction. 1310 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type); 1311 1312 /// ShouldInstrumentFunction - Return true if the current function should be 1313 /// instrumented with __cyg_profile_func_* calls 1314 bool ShouldInstrumentFunction(); 1315 1316 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified 1317 /// instrumentation function with the current function and the call site, if 1318 /// function instrumentation is enabled. 1319 void EmitFunctionInstrumentation(const char *Fn); 1320 1321 /// EmitMCountInstrumentation - Emit call to .mcount. 1322 void EmitMCountInstrumentation(); 1323 1324 /// EmitFunctionProlog - Emit the target specific LLVM code to load the 1325 /// arguments for the given function. This is also responsible for naming the 1326 /// LLVM function arguments. 1327 void EmitFunctionProlog(const CGFunctionInfo &FI, 1328 llvm::Function *Fn, 1329 const FunctionArgList &Args); 1330 1331 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the 1332 /// given temporary. 1333 void EmitFunctionEpilog(const CGFunctionInfo &FI); 1334 1335 /// EmitStartEHSpec - Emit the start of the exception spec. 1336 void EmitStartEHSpec(const Decl *D); 1337 1338 /// EmitEndEHSpec - Emit the end of the exception spec. 1339 void EmitEndEHSpec(const Decl *D); 1340 1341 /// getTerminateLandingPad - Return a landing pad that just calls terminate. 1342 llvm::BasicBlock *getTerminateLandingPad(); 1343 1344 /// getTerminateHandler - Return a handler (not a landing pad, just 1345 /// a catch handler) that just calls terminate. This is used when 1346 /// a terminate scope encloses a try. 1347 llvm::BasicBlock *getTerminateHandler(); 1348 1349 const llvm::Type *ConvertTypeForMem(QualType T); 1350 const llvm::Type *ConvertType(QualType T); 1351 const llvm::Type *ConvertType(const TypeDecl *T) { 1352 return ConvertType(getContext().getTypeDeclType(T)); 1353 } 1354 1355 /// LoadObjCSelf - Load the value of self. This function is only valid while 1356 /// generating code for an Objective-C method. 1357 llvm::Value *LoadObjCSelf(); 1358 1359 /// TypeOfSelfObject - Return type of object that this self represents. 1360 QualType TypeOfSelfObject(); 1361 1362 /// hasAggregateLLVMType - Return true if the specified AST type will map into 1363 /// an aggregate LLVM type or is void. 1364 static bool hasAggregateLLVMType(QualType T); 1365 1366 /// createBasicBlock - Create an LLVM basic block. 1367 llvm::BasicBlock *createBasicBlock(llvm::StringRef name = "", 1368 llvm::Function *parent = 0, 1369 llvm::BasicBlock *before = 0) { 1370#ifdef NDEBUG 1371 return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before); 1372#else 1373 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before); 1374#endif 1375 } 1376 1377 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified 1378 /// label maps to. 1379 JumpDest getJumpDestForLabel(const LabelDecl *S); 1380 1381 /// SimplifyForwardingBlocks - If the given basic block is only a branch to 1382 /// another basic block, simplify it. This assumes that no other code could 1383 /// potentially reference the basic block. 1384 void SimplifyForwardingBlocks(llvm::BasicBlock *BB); 1385 1386 /// EmitBlock - Emit the given block \arg BB and set it as the insert point, 1387 /// adding a fall-through branch from the current insert block if 1388 /// necessary. It is legal to call this function even if there is no current 1389 /// insertion point. 1390 /// 1391 /// IsFinished - If true, indicates that the caller has finished emitting 1392 /// branches to the given block and does not expect to emit code into it. This 1393 /// means the block can be ignored if it is unreachable. 1394 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false); 1395 1396 /// EmitBranch - Emit a branch to the specified basic block from the current 1397 /// insert block, taking care to avoid creation of branches from dummy 1398 /// blocks. It is legal to call this function even if there is no current 1399 /// insertion point. 1400 /// 1401 /// This function clears the current insertion point. The caller should follow 1402 /// calls to this function with calls to Emit*Block prior to generation new 1403 /// code. 1404 void EmitBranch(llvm::BasicBlock *Block); 1405 1406 /// HaveInsertPoint - True if an insertion point is defined. If not, this 1407 /// indicates that the current code being emitted is unreachable. 1408 bool HaveInsertPoint() const { 1409 return Builder.GetInsertBlock() != 0; 1410 } 1411 1412 /// EnsureInsertPoint - Ensure that an insertion point is defined so that 1413 /// emitted IR has a place to go. Note that by definition, if this function 1414 /// creates a block then that block is unreachable; callers may do better to 1415 /// detect when no insertion point is defined and simply skip IR generation. 1416 void EnsureInsertPoint() { 1417 if (!HaveInsertPoint()) 1418 EmitBlock(createBasicBlock()); 1419 } 1420 1421 /// ErrorUnsupported - Print out an error that codegen doesn't support the 1422 /// specified stmt yet. 1423 void ErrorUnsupported(const Stmt *S, const char *Type, 1424 bool OmitOnError=false); 1425 1426 //===--------------------------------------------------------------------===// 1427 // Helpers 1428 //===--------------------------------------------------------------------===// 1429 1430 LValue MakeAddrLValue(llvm::Value *V, QualType T, unsigned Alignment = 0) { 1431 return LValue::MakeAddr(V, T, Alignment, getContext(), 1432 CGM.getTBAAInfo(T)); 1433 } 1434 1435 /// CreateTempAlloca - This creates a alloca and inserts it into the entry 1436 /// block. The caller is responsible for setting an appropriate alignment on 1437 /// the alloca. 1438 llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty, 1439 const llvm::Twine &Name = "tmp"); 1440 1441 /// InitTempAlloca - Provide an initial value for the given alloca. 1442 void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value); 1443 1444 /// CreateIRTemp - Create a temporary IR object of the given type, with 1445 /// appropriate alignment. This routine should only be used when an temporary 1446 /// value needs to be stored into an alloca (for example, to avoid explicit 1447 /// PHI construction), but the type is the IR type, not the type appropriate 1448 /// for storing in memory. 1449 llvm::AllocaInst *CreateIRTemp(QualType T, const llvm::Twine &Name = "tmp"); 1450 1451 /// CreateMemTemp - Create a temporary memory object of the given type, with 1452 /// appropriate alignment. 1453 llvm::AllocaInst *CreateMemTemp(QualType T, const llvm::Twine &Name = "tmp"); 1454 1455 /// CreateAggTemp - Create a temporary memory object for the given 1456 /// aggregate type. 1457 AggValueSlot CreateAggTemp(QualType T, const llvm::Twine &Name = "tmp") { 1458 return AggValueSlot::forAddr(CreateMemTemp(T, Name), T.getQualifiers(), 1459 false); 1460 } 1461 1462 /// Emit a cast to void* in the appropriate address space. 1463 llvm::Value *EmitCastToVoidPtr(llvm::Value *value); 1464 1465 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 1466 /// expression and compare the result against zero, returning an Int1Ty value. 1467 llvm::Value *EvaluateExprAsBool(const Expr *E); 1468 1469 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result. 1470 void EmitIgnoredExpr(const Expr *E); 1471 1472 /// EmitAnyExpr - Emit code to compute the specified expression which can have 1473 /// any type. The result is returned as an RValue struct. If this is an 1474 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where 1475 /// the result should be returned. 1476 /// 1477 /// \param IgnoreResult - True if the resulting value isn't used. 1478 RValue EmitAnyExpr(const Expr *E, 1479 AggValueSlot AggSlot = AggValueSlot::ignored(), 1480 bool IgnoreResult = false); 1481 1482 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address 1483 // or the value of the expression, depending on how va_list is defined. 1484 llvm::Value *EmitVAListRef(const Expr *E); 1485 1486 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will 1487 /// always be accessible even if no aggregate location is provided. 1488 RValue EmitAnyExprToTemp(const Expr *E); 1489 1490 /// EmitAnyExprToMem - Emits the code necessary to evaluate an 1491 /// arbitrary expression into the given memory location. 1492 void EmitAnyExprToMem(const Expr *E, llvm::Value *Location, 1493 Qualifiers Quals, bool IsInitializer); 1494 1495 /// EmitExprAsInit - Emits the code necessary to initialize a 1496 /// location in memory with the given initializer. 1497 void EmitExprAsInit(const Expr *init, const ValueDecl *D, 1498 LValue lvalue, bool capturedByInit); 1499 1500 /// EmitAggregateCopy - Emit an aggrate copy. 1501 /// 1502 /// \param isVolatile - True iff either the source or the destination is 1503 /// volatile. 1504 void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr, 1505 QualType EltTy, bool isVolatile=false); 1506 1507 /// StartBlock - Start new block named N. If insert block is a dummy block 1508 /// then reuse it. 1509 void StartBlock(const char *N); 1510 1511 /// GetAddrOfStaticLocalVar - Return the address of a static local variable. 1512 llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD) { 1513 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD)); 1514 } 1515 1516 /// GetAddrOfLocalVar - Return the address of a local variable. 1517 llvm::Value *GetAddrOfLocalVar(const VarDecl *VD) { 1518 llvm::Value *Res = LocalDeclMap[VD]; 1519 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!"); 1520 return Res; 1521 } 1522 1523 /// getOpaqueLValueMapping - Given an opaque value expression (which 1524 /// must be mapped to an l-value), return its mapping. 1525 const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) { 1526 assert(OpaqueValueMapping::shouldBindAsLValue(e)); 1527 1528 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator 1529 it = OpaqueLValues.find(e); 1530 assert(it != OpaqueLValues.end() && "no mapping for opaque value!"); 1531 return it->second; 1532 } 1533 1534 /// getOpaqueRValueMapping - Given an opaque value expression (which 1535 /// must be mapped to an r-value), return its mapping. 1536 const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) { 1537 assert(!OpaqueValueMapping::shouldBindAsLValue(e)); 1538 1539 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator 1540 it = OpaqueRValues.find(e); 1541 assert(it != OpaqueRValues.end() && "no mapping for opaque value!"); 1542 return it->second; 1543 } 1544 1545 /// getAccessedFieldNo - Given an encoded value and a result number, return 1546 /// the input field number being accessed. 1547 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts); 1548 1549 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L); 1550 llvm::BasicBlock *GetIndirectGotoBlock(); 1551 1552 /// EmitNullInitialization - Generate code to set a value of the given type to 1553 /// null, If the type contains data member pointers, they will be initialized 1554 /// to -1 in accordance with the Itanium C++ ABI. 1555 void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty); 1556 1557 // EmitVAArg - Generate code to get an argument from the passed in pointer 1558 // and update it accordingly. The return value is a pointer to the argument. 1559 // FIXME: We should be able to get rid of this method and use the va_arg 1560 // instruction in LLVM instead once it works well enough. 1561 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty); 1562 1563 /// emitArrayLength - Compute the length of an array, even if it's a 1564 /// VLA, and drill down to the base element type. 1565 llvm::Value *emitArrayLength(const ArrayType *arrayType, 1566 QualType &baseType, 1567 llvm::Value *&addr); 1568 1569 /// EmitVLASize - Capture all the sizes for the VLA expressions in 1570 /// the given variably-modified type and store them in the VLASizeMap. 1571 /// 1572 /// This function can be called with a null (unreachable) insert point. 1573 void EmitVariablyModifiedType(QualType Ty); 1574 1575 /// getVLASize - Returns an LLVM value that corresponds to the size, 1576 /// in non-variably-sized elements, of a variable length array type, 1577 /// plus that largest non-variably-sized element type. Assumes that 1578 /// the type has already been emitted with EmitVariablyModifiedType. 1579 std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla); 1580 std::pair<llvm::Value*,QualType> getVLASize(QualType vla); 1581 1582 /// LoadCXXThis - Load the value of 'this'. This function is only valid while 1583 /// generating code for an C++ member function. 1584 llvm::Value *LoadCXXThis() { 1585 assert(CXXThisValue && "no 'this' value for this function"); 1586 return CXXThisValue; 1587 } 1588 1589 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have 1590 /// virtual bases. 1591 llvm::Value *LoadCXXVTT() { 1592 assert(CXXVTTValue && "no VTT value for this function"); 1593 return CXXVTTValue; 1594 } 1595 1596 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a 1597 /// complete class to the given direct base. 1598 llvm::Value * 1599 GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value, 1600 const CXXRecordDecl *Derived, 1601 const CXXRecordDecl *Base, 1602 bool BaseIsVirtual); 1603 1604 /// GetAddressOfBaseClass - This function will add the necessary delta to the 1605 /// load of 'this' and returns address of the base class. 1606 llvm::Value *GetAddressOfBaseClass(llvm::Value *Value, 1607 const CXXRecordDecl *Derived, 1608 CastExpr::path_const_iterator PathBegin, 1609 CastExpr::path_const_iterator PathEnd, 1610 bool NullCheckValue); 1611 1612 llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value, 1613 const CXXRecordDecl *Derived, 1614 CastExpr::path_const_iterator PathBegin, 1615 CastExpr::path_const_iterator PathEnd, 1616 bool NullCheckValue); 1617 1618 llvm::Value *GetVirtualBaseClassOffset(llvm::Value *This, 1619 const CXXRecordDecl *ClassDecl, 1620 const CXXRecordDecl *BaseClassDecl); 1621 1622 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, 1623 CXXCtorType CtorType, 1624 const FunctionArgList &Args); 1625 // It's important not to confuse this and the previous function. Delegating 1626 // constructors are the C++0x feature. The constructor delegate optimization 1627 // is used to reduce duplication in the base and complete consturctors where 1628 // they are substantially the same. 1629 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor, 1630 const FunctionArgList &Args); 1631 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 1632 bool ForVirtualBase, llvm::Value *This, 1633 CallExpr::const_arg_iterator ArgBeg, 1634 CallExpr::const_arg_iterator ArgEnd); 1635 1636 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, 1637 llvm::Value *This, llvm::Value *Src, 1638 CallExpr::const_arg_iterator ArgBeg, 1639 CallExpr::const_arg_iterator ArgEnd); 1640 1641 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 1642 const ConstantArrayType *ArrayTy, 1643 llvm::Value *ArrayPtr, 1644 CallExpr::const_arg_iterator ArgBeg, 1645 CallExpr::const_arg_iterator ArgEnd, 1646 bool ZeroInitialization = false); 1647 1648 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 1649 llvm::Value *NumElements, 1650 llvm::Value *ArrayPtr, 1651 CallExpr::const_arg_iterator ArgBeg, 1652 CallExpr::const_arg_iterator ArgEnd, 1653 bool ZeroInitialization = false); 1654 1655 void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D, 1656 const ArrayType *Array, 1657 llvm::Value *This); 1658 1659 static Destroyer destroyCXXObject; 1660 1661 void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D, 1662 llvm::Value *NumElements, 1663 llvm::Value *This); 1664 1665 llvm::Function *GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D, 1666 const ArrayType *Array, 1667 llvm::Value *This); 1668 1669 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, 1670 bool ForVirtualBase, llvm::Value *This); 1671 1672 void EmitNewArrayInitializer(const CXXNewExpr *E, llvm::Value *NewPtr, 1673 llvm::Value *NumElements); 1674 1675 void EmitCXXTemporary(const CXXTemporary *Temporary, llvm::Value *Ptr); 1676 1677 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E); 1678 void EmitCXXDeleteExpr(const CXXDeleteExpr *E); 1679 1680 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr, 1681 QualType DeleteTy); 1682 1683 llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E); 1684 llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE); 1685 1686 void EmitCheck(llvm::Value *, unsigned Size); 1687 1688 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 1689 bool isInc, bool isPre); 1690 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, 1691 bool isInc, bool isPre); 1692 //===--------------------------------------------------------------------===// 1693 // Declaration Emission 1694 //===--------------------------------------------------------------------===// 1695 1696 /// EmitDecl - Emit a declaration. 1697 /// 1698 /// This function can be called with a null (unreachable) insert point. 1699 void EmitDecl(const Decl &D); 1700 1701 /// EmitVarDecl - Emit a local variable declaration. 1702 /// 1703 /// This function can be called with a null (unreachable) insert point. 1704 void EmitVarDecl(const VarDecl &D); 1705 1706 void EmitScalarInit(const Expr *init, const ValueDecl *D, 1707 LValue lvalue, bool capturedByInit); 1708 void EmitScalarInit(llvm::Value *init, LValue lvalue); 1709 1710 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D, 1711 llvm::Value *Address); 1712 1713 /// EmitAutoVarDecl - Emit an auto variable declaration. 1714 /// 1715 /// This function can be called with a null (unreachable) insert point. 1716 void EmitAutoVarDecl(const VarDecl &D); 1717 1718 class AutoVarEmission { 1719 friend class CodeGenFunction; 1720 1721 const VarDecl *Variable; 1722 1723 /// The alignment of the variable. 1724 CharUnits Alignment; 1725 1726 /// The address of the alloca. Null if the variable was emitted 1727 /// as a global constant. 1728 llvm::Value *Address; 1729 1730 llvm::Value *NRVOFlag; 1731 1732 /// True if the variable is a __block variable. 1733 bool IsByRef; 1734 1735 /// True if the variable is of aggregate type and has a constant 1736 /// initializer. 1737 bool IsConstantAggregate; 1738 1739 struct Invalid {}; 1740 AutoVarEmission(Invalid) : Variable(0) {} 1741 1742 AutoVarEmission(const VarDecl &variable) 1743 : Variable(&variable), Address(0), NRVOFlag(0), 1744 IsByRef(false), IsConstantAggregate(false) {} 1745 1746 bool wasEmittedAsGlobal() const { return Address == 0; } 1747 1748 public: 1749 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); } 1750 1751 /// Returns the address of the object within this declaration. 1752 /// Note that this does not chase the forwarding pointer for 1753 /// __block decls. 1754 llvm::Value *getObjectAddress(CodeGenFunction &CGF) const { 1755 if (!IsByRef) return Address; 1756 1757 return CGF.Builder.CreateStructGEP(Address, 1758 CGF.getByRefValueLLVMField(Variable), 1759 Variable->getNameAsString()); 1760 } 1761 }; 1762 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var); 1763 void EmitAutoVarInit(const AutoVarEmission &emission); 1764 void EmitAutoVarCleanups(const AutoVarEmission &emission); 1765 void emitAutoVarTypeCleanup(const AutoVarEmission &emission, 1766 QualType::DestructionKind dtorKind); 1767 1768 void EmitStaticVarDecl(const VarDecl &D, 1769 llvm::GlobalValue::LinkageTypes Linkage); 1770 1771 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl. 1772 void EmitParmDecl(const VarDecl &D, llvm::Value *Arg, unsigned ArgNo); 1773 1774 /// protectFromPeepholes - Protect a value that we're intending to 1775 /// store to the side, but which will probably be used later, from 1776 /// aggressive peepholing optimizations that might delete it. 1777 /// 1778 /// Pass the result to unprotectFromPeepholes to declare that 1779 /// protection is no longer required. 1780 /// 1781 /// There's no particular reason why this shouldn't apply to 1782 /// l-values, it's just that no existing peepholes work on pointers. 1783 PeepholeProtection protectFromPeepholes(RValue rvalue); 1784 void unprotectFromPeepholes(PeepholeProtection protection); 1785 1786 //===--------------------------------------------------------------------===// 1787 // Statement Emission 1788 //===--------------------------------------------------------------------===// 1789 1790 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info. 1791 void EmitStopPoint(const Stmt *S); 1792 1793 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call 1794 /// this function even if there is no current insertion point. 1795 /// 1796 /// This function may clear the current insertion point; callers should use 1797 /// EnsureInsertPoint if they wish to subsequently generate code without first 1798 /// calling EmitBlock, EmitBranch, or EmitStmt. 1799 void EmitStmt(const Stmt *S); 1800 1801 /// EmitSimpleStmt - Try to emit a "simple" statement which does not 1802 /// necessarily require an insertion point or debug information; typically 1803 /// because the statement amounts to a jump or a container of other 1804 /// statements. 1805 /// 1806 /// \return True if the statement was handled. 1807 bool EmitSimpleStmt(const Stmt *S); 1808 1809 RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false, 1810 AggValueSlot AVS = AggValueSlot::ignored()); 1811 1812 /// EmitLabel - Emit the block for the given label. It is legal to call this 1813 /// function even if there is no current insertion point. 1814 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt. 1815 1816 void EmitLabelStmt(const LabelStmt &S); 1817 void EmitGotoStmt(const GotoStmt &S); 1818 void EmitIndirectGotoStmt(const IndirectGotoStmt &S); 1819 void EmitIfStmt(const IfStmt &S); 1820 void EmitWhileStmt(const WhileStmt &S); 1821 void EmitDoStmt(const DoStmt &S); 1822 void EmitForStmt(const ForStmt &S); 1823 void EmitReturnStmt(const ReturnStmt &S); 1824 void EmitDeclStmt(const DeclStmt &S); 1825 void EmitBreakStmt(const BreakStmt &S); 1826 void EmitContinueStmt(const ContinueStmt &S); 1827 void EmitSwitchStmt(const SwitchStmt &S); 1828 void EmitDefaultStmt(const DefaultStmt &S); 1829 void EmitCaseStmt(const CaseStmt &S); 1830 void EmitCaseStmtRange(const CaseStmt &S); 1831 void EmitAsmStmt(const AsmStmt &S); 1832 1833 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S); 1834 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S); 1835 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S); 1836 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S); 1837 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S); 1838 1839 llvm::Constant *getUnwindResumeFn(); 1840 llvm::Constant *getUnwindResumeOrRethrowFn(); 1841 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 1842 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 1843 1844 void EmitCXXTryStmt(const CXXTryStmt &S); 1845 void EmitCXXForRangeStmt(const CXXForRangeStmt &S); 1846 1847 //===--------------------------------------------------------------------===// 1848 // LValue Expression Emission 1849 //===--------------------------------------------------------------------===// 1850 1851 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type. 1852 RValue GetUndefRValue(QualType Ty); 1853 1854 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E 1855 /// and issue an ErrorUnsupported style diagnostic (using the 1856 /// provided Name). 1857 RValue EmitUnsupportedRValue(const Expr *E, 1858 const char *Name); 1859 1860 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue 1861 /// an ErrorUnsupported style diagnostic (using the provided Name). 1862 LValue EmitUnsupportedLValue(const Expr *E, 1863 const char *Name); 1864 1865 /// EmitLValue - Emit code to compute a designator that specifies the location 1866 /// of the expression. 1867 /// 1868 /// This can return one of two things: a simple address or a bitfield 1869 /// reference. In either case, the LLVM Value* in the LValue structure is 1870 /// guaranteed to be an LLVM pointer type. 1871 /// 1872 /// If this returns a bitfield reference, nothing about the pointee type of 1873 /// the LLVM value is known: For example, it may not be a pointer to an 1874 /// integer. 1875 /// 1876 /// If this returns a normal address, and if the lvalue's C type is fixed 1877 /// size, this method guarantees that the returned pointer type will point to 1878 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a 1879 /// variable length type, this is not possible. 1880 /// 1881 LValue EmitLValue(const Expr *E); 1882 1883 /// EmitCheckedLValue - Same as EmitLValue but additionally we generate 1884 /// checking code to guard against undefined behavior. This is only 1885 /// suitable when we know that the address will be used to access the 1886 /// object. 1887 LValue EmitCheckedLValue(const Expr *E); 1888 1889 /// EmitToMemory - Change a scalar value from its value 1890 /// representation to its in-memory representation. 1891 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty); 1892 1893 /// EmitFromMemory - Change a scalar value from its memory 1894 /// representation to its value representation. 1895 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty); 1896 1897 /// EmitLoadOfScalar - Load a scalar value from an address, taking 1898 /// care to appropriately convert from the memory representation to 1899 /// the LLVM value representation. 1900 llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile, 1901 unsigned Alignment, QualType Ty, 1902 llvm::MDNode *TBAAInfo = 0); 1903 1904 /// EmitLoadOfScalar - Load a scalar value from an address, taking 1905 /// care to appropriately convert from the memory representation to 1906 /// the LLVM value representation. The l-value must be a simple 1907 /// l-value. 1908 llvm::Value *EmitLoadOfScalar(LValue lvalue); 1909 1910 /// EmitStoreOfScalar - Store a scalar value to an address, taking 1911 /// care to appropriately convert from the memory representation to 1912 /// the LLVM value representation. 1913 void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr, 1914 bool Volatile, unsigned Alignment, QualType Ty, 1915 llvm::MDNode *TBAAInfo = 0); 1916 1917 /// EmitStoreOfScalar - Store a scalar value to an address, taking 1918 /// care to appropriately convert from the memory representation to 1919 /// the LLVM value representation. The l-value must be a simple 1920 /// l-value. 1921 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue); 1922 1923 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, 1924 /// this method emits the address of the lvalue, then loads the result as an 1925 /// rvalue, returning the rvalue. 1926 RValue EmitLoadOfLValue(LValue V); 1927 RValue EmitLoadOfExtVectorElementLValue(LValue V); 1928 RValue EmitLoadOfBitfieldLValue(LValue LV); 1929 RValue EmitLoadOfPropertyRefLValue(LValue LV, 1930 ReturnValueSlot Return = ReturnValueSlot()); 1931 1932 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 1933 /// lvalue, where both are guaranteed to the have the same type, and that type 1934 /// is 'Ty'. 1935 void EmitStoreThroughLValue(RValue Src, LValue Dst); 1936 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst); 1937 void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst); 1938 1939 /// EmitStoreThroughLValue - Store Src into Dst with same constraints as 1940 /// EmitStoreThroughLValue. 1941 /// 1942 /// \param Result [out] - If non-null, this will be set to a Value* for the 1943 /// bit-field contents after the store, appropriate for use as the result of 1944 /// an assignment to the bit-field. 1945 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 1946 llvm::Value **Result=0); 1947 1948 /// Emit an l-value for an assignment (simple or compound) of complex type. 1949 LValue EmitComplexAssignmentLValue(const BinaryOperator *E); 1950 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E); 1951 1952 // Note: only available for agg return types 1953 LValue EmitBinaryOperatorLValue(const BinaryOperator *E); 1954 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E); 1955 // Note: only available for agg return types 1956 LValue EmitCallExprLValue(const CallExpr *E); 1957 // Note: only available for agg return types 1958 LValue EmitVAArgExprLValue(const VAArgExpr *E); 1959 LValue EmitDeclRefLValue(const DeclRefExpr *E); 1960 LValue EmitStringLiteralLValue(const StringLiteral *E); 1961 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E); 1962 LValue EmitPredefinedLValue(const PredefinedExpr *E); 1963 LValue EmitUnaryOpLValue(const UnaryOperator *E); 1964 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E); 1965 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E); 1966 LValue EmitMemberExpr(const MemberExpr *E); 1967 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E); 1968 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E); 1969 LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E); 1970 LValue EmitCastLValue(const CastExpr *E); 1971 LValue EmitNullInitializationLValue(const CXXScalarValueInitExpr *E); 1972 LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 1973 LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e); 1974 1975 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface, 1976 const ObjCIvarDecl *Ivar); 1977 LValue EmitLValueForAnonRecordField(llvm::Value* Base, 1978 const IndirectFieldDecl* Field, 1979 unsigned CVRQualifiers); 1980 LValue EmitLValueForField(llvm::Value* Base, const FieldDecl* Field, 1981 unsigned CVRQualifiers); 1982 1983 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that 1984 /// if the Field is a reference, this will return the address of the reference 1985 /// and not the address of the value stored in the reference. 1986 LValue EmitLValueForFieldInitialization(llvm::Value* Base, 1987 const FieldDecl* Field, 1988 unsigned CVRQualifiers); 1989 1990 LValue EmitLValueForIvar(QualType ObjectTy, 1991 llvm::Value* Base, const ObjCIvarDecl *Ivar, 1992 unsigned CVRQualifiers); 1993 1994 LValue EmitLValueForBitfield(llvm::Value* Base, const FieldDecl* Field, 1995 unsigned CVRQualifiers); 1996 1997 LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E); 1998 1999 LValue EmitCXXConstructLValue(const CXXConstructExpr *E); 2000 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E); 2001 LValue EmitExprWithCleanupsLValue(const ExprWithCleanups *E); 2002 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E); 2003 2004 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E); 2005 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E); 2006 LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E); 2007 LValue EmitStmtExprLValue(const StmtExpr *E); 2008 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E); 2009 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E); 2010 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::Constant *Init); 2011 2012 //===--------------------------------------------------------------------===// 2013 // Scalar Expression Emission 2014 //===--------------------------------------------------------------------===// 2015 2016 /// EmitCall - Generate a call of the given function, expecting the given 2017 /// result type, and using the given argument list which specifies both the 2018 /// LLVM arguments and the types they were derived from. 2019 /// 2020 /// \param TargetDecl - If given, the decl of the function in a direct call; 2021 /// used to set attributes on the call (noreturn, etc.). 2022 RValue EmitCall(const CGFunctionInfo &FnInfo, 2023 llvm::Value *Callee, 2024 ReturnValueSlot ReturnValue, 2025 const CallArgList &Args, 2026 const Decl *TargetDecl = 0, 2027 llvm::Instruction **callOrInvoke = 0); 2028 2029 RValue EmitCall(QualType FnType, llvm::Value *Callee, 2030 ReturnValueSlot ReturnValue, 2031 CallExpr::const_arg_iterator ArgBeg, 2032 CallExpr::const_arg_iterator ArgEnd, 2033 const Decl *TargetDecl = 0); 2034 RValue EmitCallExpr(const CallExpr *E, 2035 ReturnValueSlot ReturnValue = ReturnValueSlot()); 2036 2037 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee, 2038 llvm::Value * const *ArgBegin, 2039 llvm::Value * const *ArgEnd, 2040 const llvm::Twine &Name = ""); 2041 2042 llvm::Value *BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This, 2043 const llvm::Type *Ty); 2044 llvm::Value *BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type, 2045 llvm::Value *This, const llvm::Type *Ty); 2046 llvm::Value *BuildAppleKextVirtualCall(const CXXMethodDecl *MD, 2047 NestedNameSpecifier *Qual, 2048 const llvm::Type *Ty); 2049 2050 llvm::Value *BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD, 2051 CXXDtorType Type, 2052 const CXXRecordDecl *RD); 2053 2054 RValue EmitCXXMemberCall(const CXXMethodDecl *MD, 2055 llvm::Value *Callee, 2056 ReturnValueSlot ReturnValue, 2057 llvm::Value *This, 2058 llvm::Value *VTT, 2059 CallExpr::const_arg_iterator ArgBeg, 2060 CallExpr::const_arg_iterator ArgEnd); 2061 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E, 2062 ReturnValueSlot ReturnValue); 2063 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, 2064 ReturnValueSlot ReturnValue); 2065 2066 llvm::Value *EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E, 2067 const CXXMethodDecl *MD, 2068 llvm::Value *This); 2069 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 2070 const CXXMethodDecl *MD, 2071 ReturnValueSlot ReturnValue); 2072 2073 2074 RValue EmitBuiltinExpr(const FunctionDecl *FD, 2075 unsigned BuiltinID, const CallExpr *E); 2076 2077 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue); 2078 2079 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call 2080 /// is unhandled by the current target. 2081 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2082 2083 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2084 llvm::Value *EmitNeonCall(llvm::Function *F, 2085 llvm::SmallVectorImpl<llvm::Value*> &O, 2086 const char *name, 2087 unsigned shift = 0, bool rightshift = false); 2088 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx); 2089 llvm::Value *EmitNeonShiftVector(llvm::Value *V, const llvm::Type *Ty, 2090 bool negateForRightShift); 2091 2092 llvm::Value *BuildVector(const llvm::SmallVectorImpl<llvm::Value*> &Ops); 2093 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2094 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2095 2096 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E); 2097 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E); 2098 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E); 2099 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, 2100 ReturnValueSlot Return = ReturnValueSlot()); 2101 2102 /// Retrieves the default cleanup kind for an ARC cleanup. 2103 /// Except under -fobjc-arc-eh, ARC cleanups are normal-only. 2104 CleanupKind getARCCleanupKind() { 2105 return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions 2106 ? NormalAndEHCleanup : NormalCleanup; 2107 } 2108 2109 // ARC primitives. 2110 void EmitARCInitWeak(llvm::Value *value, llvm::Value *addr); 2111 void EmitARCDestroyWeak(llvm::Value *addr); 2112 llvm::Value *EmitARCLoadWeak(llvm::Value *addr); 2113 llvm::Value *EmitARCLoadWeakRetained(llvm::Value *addr); 2114 llvm::Value *EmitARCStoreWeak(llvm::Value *value, llvm::Value *addr, 2115 bool ignored); 2116 void EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src); 2117 void EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src); 2118 llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value); 2119 llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value); 2120 llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value, 2121 bool ignored); 2122 llvm::Value *EmitARCStoreStrongCall(llvm::Value *addr, llvm::Value *value, 2123 bool ignored); 2124 llvm::Value *EmitARCRetain(QualType type, llvm::Value *value); 2125 llvm::Value *EmitARCRetainNonBlock(llvm::Value *value); 2126 llvm::Value *EmitARCRetainBlock(llvm::Value *value); 2127 void EmitARCRelease(llvm::Value *value, bool precise); 2128 llvm::Value *EmitARCAutorelease(llvm::Value *value); 2129 llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value); 2130 llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value); 2131 llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value); 2132 2133 std::pair<LValue,llvm::Value*> 2134 EmitARCStoreAutoreleasing(const BinaryOperator *e); 2135 std::pair<LValue,llvm::Value*> 2136 EmitARCStoreStrong(const BinaryOperator *e, bool ignored); 2137 2138 llvm::Value *EmitObjCProduceObject(QualType T, llvm::Value *Ptr); 2139 llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr); 2140 llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr); 2141 2142 llvm::Value *EmitARCRetainScalarExpr(const Expr *expr); 2143 llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr); 2144 2145 void PushARCReleaseCleanup(CleanupKind kind, QualType type, 2146 llvm::Value *addr, bool precise, 2147 bool forFullExpr = false); 2148 void PushARCArrayReleaseCleanup(CleanupKind kind, QualType elementType, 2149 llvm::Value *addr, 2150 llvm::Value *countOrCountPtr, 2151 bool precise, bool forFullExpr = false); 2152 void PushARCWeakReleaseCleanup(CleanupKind kind, QualType type, 2153 llvm::Value *addr, bool forFullExpr = false); 2154 void PushARCArrayWeakReleaseCleanup(CleanupKind kind, QualType elementType, 2155 llvm::Value *addr, 2156 llvm::Value *countOrCountPtr, 2157 bool forFullExpr = false); 2158 static Destroyer destroyARCStrongImprecise; 2159 static Destroyer destroyARCStrongPrecise; 2160 static Destroyer destroyARCWeak; 2161 2162 void PushARCFieldReleaseCleanup(CleanupKind cleanupKind, 2163 const FieldDecl *Field); 2164 void PushARCFieldWeakReleaseCleanup(CleanupKind cleanupKind, 2165 const FieldDecl *Field); 2166 2167 void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr); 2168 llvm::Value *EmitObjCAutoreleasePoolPush(); 2169 llvm::Value *EmitObjCMRRAutoreleasePoolPush(); 2170 void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr); 2171 void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr); 2172 2173 /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in 2174 /// expression. Will emit a temporary variable if E is not an LValue. 2175 RValue EmitReferenceBindingToExpr(const Expr* E, 2176 const NamedDecl *InitializedDecl); 2177 2178 //===--------------------------------------------------------------------===// 2179 // Expression Emission 2180 //===--------------------------------------------------------------------===// 2181 2182 // Expressions are broken into three classes: scalar, complex, aggregate. 2183 2184 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM 2185 /// scalar type, returning the result. 2186 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false); 2187 2188 /// EmitScalarConversion - Emit a conversion from the specified type to the 2189 /// specified destination type, both of which are LLVM scalar types. 2190 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy, 2191 QualType DstTy); 2192 2193 /// EmitComplexToScalarConversion - Emit a conversion from the specified 2194 /// complex type to the specified destination type, where the destination type 2195 /// is an LLVM scalar type. 2196 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, 2197 QualType DstTy); 2198 2199 2200 /// EmitAggExpr - Emit the computation of the specified expression 2201 /// of aggregate type. The result is computed into the given slot, 2202 /// which may be null to indicate that the value is not needed. 2203 void EmitAggExpr(const Expr *E, AggValueSlot AS, bool IgnoreResult = false); 2204 2205 /// EmitAggExprToLValue - Emit the computation of the specified expression of 2206 /// aggregate type into a temporary LValue. 2207 LValue EmitAggExprToLValue(const Expr *E); 2208 2209 /// EmitGCMemmoveCollectable - Emit special API for structs with object 2210 /// pointers. 2211 void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr, 2212 QualType Ty); 2213 2214 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object, 2215 /// make sure it survives garbage collection until this point. 2216 void EmitExtendGCLifetime(llvm::Value *object); 2217 2218 /// EmitComplexExpr - Emit the computation of the specified expression of 2219 /// complex type, returning the result. 2220 ComplexPairTy EmitComplexExpr(const Expr *E, 2221 bool IgnoreReal = false, 2222 bool IgnoreImag = false); 2223 2224 /// EmitComplexExprIntoAddr - Emit the computation of the specified expression 2225 /// of complex type, storing into the specified Value*. 2226 void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr, 2227 bool DestIsVolatile); 2228 2229 /// StoreComplexToAddr - Store a complex number into the specified address. 2230 void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr, 2231 bool DestIsVolatile); 2232 /// LoadComplexFromAddr - Load a complex number from the specified address. 2233 ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile); 2234 2235 /// CreateStaticVarDecl - Create a zero-initialized LLVM global for 2236 /// a static local variable. 2237 llvm::GlobalVariable *CreateStaticVarDecl(const VarDecl &D, 2238 const char *Separator, 2239 llvm::GlobalValue::LinkageTypes Linkage); 2240 2241 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the 2242 /// global variable that has already been created for it. If the initializer 2243 /// has a different type than GV does, this may free GV and return a different 2244 /// one. Otherwise it just returns GV. 2245 llvm::GlobalVariable * 2246 AddInitializerToStaticVarDecl(const VarDecl &D, 2247 llvm::GlobalVariable *GV); 2248 2249 2250 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++ 2251 /// variable with global storage. 2252 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr); 2253 2254 /// EmitCXXGlobalDtorRegistration - Emits a call to register the global ptr 2255 /// with the C++ runtime so that its destructor will be called at exit. 2256 void EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn, 2257 llvm::Constant *DeclPtr); 2258 2259 /// Emit code in this function to perform a guarded variable 2260 /// initialization. Guarded initializations are used when it's not 2261 /// possible to prove that an initialization will be done exactly 2262 /// once, e.g. with a static local variable or a static data member 2263 /// of a class template. 2264 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr); 2265 2266 /// GenerateCXXGlobalInitFunc - Generates code for initializing global 2267 /// variables. 2268 void GenerateCXXGlobalInitFunc(llvm::Function *Fn, 2269 llvm::Constant **Decls, 2270 unsigned NumDecls); 2271 2272 /// GenerateCXXGlobalDtorFunc - Generates code for destroying global 2273 /// variables. 2274 void GenerateCXXGlobalDtorFunc(llvm::Function *Fn, 2275 const std::vector<std::pair<llvm::WeakVH, 2276 llvm::Constant*> > &DtorsAndObjects); 2277 2278 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, 2279 const VarDecl *D, 2280 llvm::GlobalVariable *Addr); 2281 2282 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest); 2283 2284 void EmitSynthesizedCXXCopyCtor(llvm::Value *Dest, llvm::Value *Src, 2285 const Expr *Exp); 2286 2287 RValue EmitExprWithCleanups(const ExprWithCleanups *E, 2288 AggValueSlot Slot =AggValueSlot::ignored()); 2289 2290 void EmitCXXThrowExpr(const CXXThrowExpr *E); 2291 2292 //===--------------------------------------------------------------------===// 2293 // Internal Helpers 2294 //===--------------------------------------------------------------------===// 2295 2296 /// ContainsLabel - Return true if the statement contains a label in it. If 2297 /// this statement is not executed normally, it not containing a label means 2298 /// that we can just remove the code. 2299 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false); 2300 2301 /// containsBreak - Return true if the statement contains a break out of it. 2302 /// If the statement (recursively) contains a switch or loop with a break 2303 /// inside of it, this is fine. 2304 static bool containsBreak(const Stmt *S); 2305 2306 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 2307 /// to a constant, or if it does but contains a label, return false. If it 2308 /// constant folds return true and set the boolean result in Result. 2309 bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result); 2310 2311 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 2312 /// to a constant, or if it does but contains a label, return false. If it 2313 /// constant folds return true and set the folded value. 2314 bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APInt &Result); 2315 2316 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an 2317 /// if statement) to the specified blocks. Based on the condition, this might 2318 /// try to simplify the codegen of the conditional based on the branch. 2319 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, 2320 llvm::BasicBlock *FalseBlock); 2321 2322 /// getTrapBB - Create a basic block that will call the trap intrinsic. We'll 2323 /// generate a branch around the created basic block as necessary. 2324 llvm::BasicBlock *getTrapBB(); 2325 2326 /// EmitCallArg - Emit a single call argument. 2327 void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType); 2328 2329 /// EmitDelegateCallArg - We are performing a delegate call; that 2330 /// is, the current function is delegating to another one. Produce 2331 /// a r-value suitable for passing the given parameter. 2332 void EmitDelegateCallArg(CallArgList &args, const VarDecl *param); 2333 2334private: 2335 void EmitReturnOfRValue(RValue RV, QualType Ty); 2336 2337 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty 2338 /// from function arguments into \arg Dst. See ABIArgInfo::Expand. 2339 /// 2340 /// \param AI - The first function argument of the expansion. 2341 /// \return The argument following the last expanded function 2342 /// argument. 2343 llvm::Function::arg_iterator 2344 ExpandTypeFromArgs(QualType Ty, LValue Dst, 2345 llvm::Function::arg_iterator AI); 2346 2347 /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg 2348 /// Ty, into individual arguments on the provided vector \arg Args. See 2349 /// ABIArgInfo::Expand. 2350 void ExpandTypeToArgs(QualType Ty, RValue Src, 2351 llvm::SmallVector<llvm::Value*, 16> &Args); 2352 2353 llvm::Value* EmitAsmInput(const AsmStmt &S, 2354 const TargetInfo::ConstraintInfo &Info, 2355 const Expr *InputExpr, std::string &ConstraintStr); 2356 2357 llvm::Value* EmitAsmInputLValue(const AsmStmt &S, 2358 const TargetInfo::ConstraintInfo &Info, 2359 LValue InputValue, QualType InputType, 2360 std::string &ConstraintStr); 2361 2362 /// EmitCallArgs - Emit call arguments for a function. 2363 /// The CallArgTypeInfo parameter is used for iterating over the known 2364 /// argument types of the function being called. 2365 template<typename T> 2366 void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo, 2367 CallExpr::const_arg_iterator ArgBeg, 2368 CallExpr::const_arg_iterator ArgEnd) { 2369 CallExpr::const_arg_iterator Arg = ArgBeg; 2370 2371 // First, use the argument types that the type info knows about 2372 if (CallArgTypeInfo) { 2373 for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(), 2374 E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) { 2375 assert(Arg != ArgEnd && "Running over edge of argument list!"); 2376 QualType ArgType = *I; 2377#ifndef NDEBUG 2378 QualType ActualArgType = Arg->getType(); 2379 if (ArgType->isPointerType() && ActualArgType->isPointerType()) { 2380 QualType ActualBaseType = 2381 ActualArgType->getAs<PointerType>()->getPointeeType(); 2382 QualType ArgBaseType = 2383 ArgType->getAs<PointerType>()->getPointeeType(); 2384 if (ArgBaseType->isVariableArrayType()) { 2385 if (const VariableArrayType *VAT = 2386 getContext().getAsVariableArrayType(ActualBaseType)) { 2387 if (!VAT->getSizeExpr()) 2388 ActualArgType = ArgType; 2389 } 2390 } 2391 } 2392 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()). 2393 getTypePtr() == 2394 getContext().getCanonicalType(ActualArgType).getTypePtr() && 2395 "type mismatch in call argument!"); 2396#endif 2397 EmitCallArg(Args, *Arg, ArgType); 2398 } 2399 2400 // Either we've emitted all the call args, or we have a call to a 2401 // variadic function. 2402 assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) && 2403 "Extra arguments in non-variadic function!"); 2404 2405 } 2406 2407 // If we still have any arguments, emit them using the type of the argument. 2408 for (; Arg != ArgEnd; ++Arg) 2409 EmitCallArg(Args, *Arg, Arg->getType()); 2410 } 2411 2412 const TargetCodeGenInfo &getTargetHooks() const { 2413 return CGM.getTargetCodeGenInfo(); 2414 } 2415 2416 void EmitDeclMetadata(); 2417 2418 CodeGenModule::ByrefHelpers * 2419 buildByrefHelpers(const llvm::StructType &byrefType, 2420 const AutoVarEmission &emission); 2421}; 2422 2423/// Helper class with most of the code for saving a value for a 2424/// conditional expression cleanup. 2425struct DominatingLLVMValue { 2426 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type; 2427 2428 /// Answer whether the given value needs extra work to be saved. 2429 static bool needsSaving(llvm::Value *value) { 2430 // If it's not an instruction, we don't need to save. 2431 if (!isa<llvm::Instruction>(value)) return false; 2432 2433 // If it's an instruction in the entry block, we don't need to save. 2434 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent(); 2435 return (block != &block->getParent()->getEntryBlock()); 2436 } 2437 2438 /// Try to save the given value. 2439 static saved_type save(CodeGenFunction &CGF, llvm::Value *value) { 2440 if (!needsSaving(value)) return saved_type(value, false); 2441 2442 // Otherwise we need an alloca. 2443 llvm::Value *alloca = 2444 CGF.CreateTempAlloca(value->getType(), "cond-cleanup.save"); 2445 CGF.Builder.CreateStore(value, alloca); 2446 2447 return saved_type(alloca, true); 2448 } 2449 2450 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) { 2451 if (!value.getInt()) return value.getPointer(); 2452 return CGF.Builder.CreateLoad(value.getPointer()); 2453 } 2454}; 2455 2456/// A partial specialization of DominatingValue for llvm::Values that 2457/// might be llvm::Instructions. 2458template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue { 2459 typedef T *type; 2460 static type restore(CodeGenFunction &CGF, saved_type value) { 2461 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value)); 2462 } 2463}; 2464 2465/// A specialization of DominatingValue for RValue. 2466template <> struct DominatingValue<RValue> { 2467 typedef RValue type; 2468 class saved_type { 2469 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral, 2470 AggregateAddress, ComplexAddress }; 2471 2472 llvm::Value *Value; 2473 Kind K; 2474 saved_type(llvm::Value *v, Kind k) : Value(v), K(k) {} 2475 2476 public: 2477 static bool needsSaving(RValue value); 2478 static saved_type save(CodeGenFunction &CGF, RValue value); 2479 RValue restore(CodeGenFunction &CGF); 2480 2481 // implementations in CGExprCXX.cpp 2482 }; 2483 2484 static bool needsSaving(type value) { 2485 return saved_type::needsSaving(value); 2486 } 2487 static saved_type save(CodeGenFunction &CGF, type value) { 2488 return saved_type::save(CGF, value); 2489 } 2490 static type restore(CodeGenFunction &CGF, saved_type value) { 2491 return value.restore(CGF); 2492 } 2493}; 2494 2495} // end namespace CodeGen 2496} // end namespace clang 2497 2498#endif 2499