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