CodeGenFunction.h revision f871d0cc377a1367b519a6cce26be74607566eba
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/TargetInfo.h" 22#include "llvm/ADT/DenseMap.h" 23#include "llvm/ADT/SmallVector.h" 24#include "llvm/Support/ValueHandle.h" 25#include "CodeGenModule.h" 26#include "CGBlocks.h" 27#include "CGBuilder.h" 28#include "CGCall.h" 29#include "CGCXX.h" 30#include "CGValue.h" 31 32namespace llvm { 33 class BasicBlock; 34 class LLVMContext; 35 class MDNode; 36 class Module; 37 class SwitchInst; 38 class Twine; 39 class Value; 40 class CallSite; 41} 42 43namespace clang { 44 class ASTContext; 45 class CXXDestructorDecl; 46 class CXXTryStmt; 47 class Decl; 48 class EnumConstantDecl; 49 class FunctionDecl; 50 class FunctionProtoType; 51 class LabelStmt; 52 class ObjCContainerDecl; 53 class ObjCInterfaceDecl; 54 class ObjCIvarDecl; 55 class ObjCMethodDecl; 56 class ObjCImplementationDecl; 57 class ObjCPropertyImplDecl; 58 class TargetInfo; 59 class TargetCodeGenInfo; 60 class VarDecl; 61 class ObjCForCollectionStmt; 62 class ObjCAtTryStmt; 63 class ObjCAtThrowStmt; 64 class ObjCAtSynchronizedStmt; 65 66namespace CodeGen { 67 class CodeGenTypes; 68 class CGDebugInfo; 69 class CGFunctionInfo; 70 class CGRecordLayout; 71 class CGBlockInfo; 72 73/// A branch fixup. These are required when emitting a goto to a 74/// label which hasn't been emitted yet. The goto is optimistically 75/// emitted as a branch to the basic block for the label, and (if it 76/// occurs in a scope with non-trivial cleanups) a fixup is added to 77/// the innermost cleanup. When a (normal) cleanup is popped, any 78/// unresolved fixups in that scope are threaded through the cleanup. 79struct BranchFixup { 80 /// The block containing the terminator which needs to be modified 81 /// into a switch if this fixup is resolved into the current scope. 82 /// If null, LatestBranch points directly to the destination. 83 llvm::BasicBlock *OptimisticBranchBlock; 84 85 /// The ultimate destination of the branch. 86 /// 87 /// This can be set to null to indicate that this fixup was 88 /// successfully resolved. 89 llvm::BasicBlock *Destination; 90 91 /// The destination index value. 92 unsigned DestinationIndex; 93 94 /// The initial branch of the fixup. 95 llvm::BranchInst *InitialBranch; 96}; 97 98enum CleanupKind { NormalAndEHCleanup, EHCleanup, NormalCleanup }; 99 100/// A stack of scopes which respond to exceptions, including cleanups 101/// and catch blocks. 102class EHScopeStack { 103public: 104 /// A saved depth on the scope stack. This is necessary because 105 /// pushing scopes onto the stack invalidates iterators. 106 class stable_iterator { 107 friend class EHScopeStack; 108 109 /// Offset from StartOfData to EndOfBuffer. 110 ptrdiff_t Size; 111 112 stable_iterator(ptrdiff_t Size) : Size(Size) {} 113 114 public: 115 static stable_iterator invalid() { return stable_iterator(-1); } 116 stable_iterator() : Size(-1) {} 117 118 bool isValid() const { return Size >= 0; } 119 120 bool encloses(stable_iterator I) const { return Size <= I.Size; } 121 bool strictlyEncloses(stable_iterator I) const { return Size < I.Size; } 122 123 friend bool operator==(stable_iterator A, stable_iterator B) { 124 return A.Size == B.Size; 125 } 126 friend bool operator!=(stable_iterator A, stable_iterator B) { 127 return A.Size != B.Size; 128 } 129 }; 130 131 /// Information for lazily generating a cleanup. Subclasses must be 132 /// POD-like: cleanups will not be destructed, and they will be 133 /// allocated on the cleanup stack and freely copied and moved 134 /// around. 135 /// 136 /// Cleanup implementations should generally be declared in an 137 /// anonymous namespace. 138 class Cleanup { 139 public: 140 // Anchor the construction vtable. We use the destructor because 141 // gcc gives an obnoxious warning if there are virtual methods 142 // with an accessible non-virtual destructor. Unfortunately, 143 // declaring this destructor makes it non-trivial, but there 144 // doesn't seem to be any other way around this warning. 145 // 146 // This destructor will never be called. 147 virtual ~Cleanup(); 148 149 /// Emit the cleanup. For normal cleanups, this is run in the 150 /// same EH context as when the cleanup was pushed, i.e. the 151 /// immediately-enclosing context of the cleanup scope. For 152 /// EH cleanups, this is run in a terminate context. 153 /// 154 // \param IsForEHCleanup true if this is for an EH cleanup, false 155 /// if for a normal cleanup. 156 virtual void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) = 0; 157 }; 158 159private: 160 // The implementation for this class is in CGException.h and 161 // CGException.cpp; the definition is here because it's used as a 162 // member of CodeGenFunction. 163 164 /// The start of the scope-stack buffer, i.e. the allocated pointer 165 /// for the buffer. All of these pointers are either simultaneously 166 /// null or simultaneously valid. 167 char *StartOfBuffer; 168 169 /// The end of the buffer. 170 char *EndOfBuffer; 171 172 /// The first valid entry in the buffer. 173 char *StartOfData; 174 175 /// The innermost normal cleanup on the stack. 176 stable_iterator InnermostNormalCleanup; 177 178 /// The innermost EH cleanup on the stack. 179 stable_iterator InnermostEHCleanup; 180 181 /// The number of catches on the stack. 182 unsigned CatchDepth; 183 184 /// The current EH destination index. Reset to FirstCatchIndex 185 /// whenever the last EH cleanup is popped. 186 unsigned NextEHDestIndex; 187 enum { FirstEHDestIndex = 1 }; 188 189 /// The current set of branch fixups. A branch fixup is a jump to 190 /// an as-yet unemitted label, i.e. a label for which we don't yet 191 /// know the EH stack depth. Whenever we pop a cleanup, we have 192 /// to thread all the current branch fixups through it. 193 /// 194 /// Fixups are recorded as the Use of the respective branch or 195 /// switch statement. The use points to the final destination. 196 /// When popping out of a cleanup, these uses are threaded through 197 /// the cleanup and adjusted to point to the new cleanup. 198 /// 199 /// Note that branches are allowed to jump into protected scopes 200 /// in certain situations; e.g. the following code is legal: 201 /// struct A { ~A(); }; // trivial ctor, non-trivial dtor 202 /// goto foo; 203 /// A a; 204 /// foo: 205 /// bar(); 206 llvm::SmallVector<BranchFixup, 8> BranchFixups; 207 208 char *allocate(size_t Size); 209 210 void *pushCleanup(CleanupKind K, size_t DataSize); 211 212public: 213 EHScopeStack() : StartOfBuffer(0), EndOfBuffer(0), StartOfData(0), 214 InnermostNormalCleanup(stable_end()), 215 InnermostEHCleanup(stable_end()), 216 CatchDepth(0), NextEHDestIndex(FirstEHDestIndex) {} 217 ~EHScopeStack() { delete[] StartOfBuffer; } 218 219 // Variadic templates would make this not terrible. 220 221 /// Push a lazily-created cleanup on the stack. 222 template <class T> 223 void pushCleanup(CleanupKind Kind) { 224 void *Buffer = pushCleanup(Kind, sizeof(T)); 225 Cleanup *Obj = new(Buffer) T(); 226 (void) Obj; 227 } 228 229 /// Push a lazily-created cleanup on the stack. 230 template <class T, class A0> 231 void pushCleanup(CleanupKind Kind, A0 a0) { 232 void *Buffer = pushCleanup(Kind, sizeof(T)); 233 Cleanup *Obj = new(Buffer) T(a0); 234 (void) Obj; 235 } 236 237 /// Push a lazily-created cleanup on the stack. 238 template <class T, class A0, class A1> 239 void pushCleanup(CleanupKind Kind, A0 a0, A1 a1) { 240 void *Buffer = pushCleanup(Kind, sizeof(T)); 241 Cleanup *Obj = new(Buffer) T(a0, a1); 242 (void) Obj; 243 } 244 245 /// Push a lazily-created cleanup on the stack. 246 template <class T, class A0, class A1, class A2> 247 void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2) { 248 void *Buffer = pushCleanup(Kind, sizeof(T)); 249 Cleanup *Obj = new(Buffer) T(a0, a1, a2); 250 (void) Obj; 251 } 252 253 /// Push a lazily-created cleanup on the stack. 254 template <class T, class A0, class A1, class A2, class A3> 255 void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3) { 256 void *Buffer = pushCleanup(Kind, sizeof(T)); 257 Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3); 258 (void) Obj; 259 } 260 261 /// Push a lazily-created cleanup on the stack. 262 template <class T, class A0, class A1, class A2, class A3, class A4> 263 void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { 264 void *Buffer = pushCleanup(Kind, sizeof(T)); 265 Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3, a4); 266 (void) Obj; 267 } 268 269 /// Pops a cleanup scope off the stack. This should only be called 270 /// by CodeGenFunction::PopCleanupBlock. 271 void popCleanup(); 272 273 /// Push a set of catch handlers on the stack. The catch is 274 /// uninitialized and will need to have the given number of handlers 275 /// set on it. 276 class EHCatchScope *pushCatch(unsigned NumHandlers); 277 278 /// Pops a catch scope off the stack. 279 void popCatch(); 280 281 /// Push an exceptions filter on the stack. 282 class EHFilterScope *pushFilter(unsigned NumFilters); 283 284 /// Pops an exceptions filter off the stack. 285 void popFilter(); 286 287 /// Push a terminate handler on the stack. 288 void pushTerminate(); 289 290 /// Pops a terminate handler off the stack. 291 void popTerminate(); 292 293 /// Determines whether the exception-scopes stack is empty. 294 bool empty() const { return StartOfData == EndOfBuffer; } 295 296 bool requiresLandingPad() const { 297 return (CatchDepth || hasEHCleanups()); 298 } 299 300 /// Determines whether there are any normal cleanups on the stack. 301 bool hasNormalCleanups() const { 302 return InnermostNormalCleanup != stable_end(); 303 } 304 305 /// Returns the innermost normal cleanup on the stack, or 306 /// stable_end() if there are no normal cleanups. 307 stable_iterator getInnermostNormalCleanup() const { 308 return InnermostNormalCleanup; 309 } 310 311 /// Determines whether there are any EH cleanups on the stack. 312 bool hasEHCleanups() const { 313 return InnermostEHCleanup != stable_end(); 314 } 315 316 /// Returns the innermost EH cleanup on the stack, or stable_end() 317 /// if there are no EH cleanups. 318 stable_iterator getInnermostEHCleanup() const { 319 return InnermostEHCleanup; 320 } 321 322 /// An unstable reference to a scope-stack depth. Invalidated by 323 /// pushes but not pops. 324 class iterator; 325 326 /// Returns an iterator pointing to the innermost EH scope. 327 iterator begin() const; 328 329 /// Returns an iterator pointing to the outermost EH scope. 330 iterator end() const; 331 332 /// Create a stable reference to the top of the EH stack. The 333 /// returned reference is valid until that scope is popped off the 334 /// stack. 335 stable_iterator stable_begin() const { 336 return stable_iterator(EndOfBuffer - StartOfData); 337 } 338 339 /// Create a stable reference to the bottom of the EH stack. 340 static stable_iterator stable_end() { 341 return stable_iterator(0); 342 } 343 344 /// Translates an iterator into a stable_iterator. 345 stable_iterator stabilize(iterator it) const; 346 347 /// Finds the nearest cleanup enclosing the given iterator. 348 /// Returns stable_iterator::invalid() if there are no such cleanups. 349 stable_iterator getEnclosingEHCleanup(iterator it) const; 350 351 /// Turn a stable reference to a scope depth into a unstable pointer 352 /// to the EH stack. 353 iterator find(stable_iterator save) const; 354 355 /// Removes the cleanup pointed to by the given stable_iterator. 356 void removeCleanup(stable_iterator save); 357 358 /// Add a branch fixup to the current cleanup scope. 359 BranchFixup &addBranchFixup() { 360 assert(hasNormalCleanups() && "adding fixup in scope without cleanups"); 361 BranchFixups.push_back(BranchFixup()); 362 return BranchFixups.back(); 363 } 364 365 unsigned getNumBranchFixups() const { return BranchFixups.size(); } 366 BranchFixup &getBranchFixup(unsigned I) { 367 assert(I < getNumBranchFixups()); 368 return BranchFixups[I]; 369 } 370 371 /// Pops lazily-removed fixups from the end of the list. This 372 /// should only be called by procedures which have just popped a 373 /// cleanup or resolved one or more fixups. 374 void popNullFixups(); 375 376 /// Clears the branch-fixups list. This should only be called by 377 /// CodeGenFunction::ResolveAllBranchFixups. 378 void clearFixups() { BranchFixups.clear(); } 379 380 /// Gets the next EH destination index. 381 unsigned getNextEHDestIndex() { return NextEHDestIndex++; } 382}; 383 384/// CodeGenFunction - This class organizes the per-function state that is used 385/// while generating LLVM code. 386class CodeGenFunction : public BlockFunction { 387 CodeGenFunction(const CodeGenFunction&); // DO NOT IMPLEMENT 388 void operator=(const CodeGenFunction&); // DO NOT IMPLEMENT 389public: 390 /// A jump destination is an abstract label, branching to which may 391 /// require a jump out through normal cleanups. 392 struct JumpDest { 393 JumpDest() : Block(0), ScopeDepth(), Index(0) {} 394 JumpDest(llvm::BasicBlock *Block, 395 EHScopeStack::stable_iterator Depth, 396 unsigned Index) 397 : Block(Block), ScopeDepth(Depth), Index(Index) {} 398 399 bool isValid() const { return Block != 0; } 400 llvm::BasicBlock *getBlock() const { return Block; } 401 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; } 402 unsigned getDestIndex() const { return Index; } 403 404 private: 405 llvm::BasicBlock *Block; 406 EHScopeStack::stable_iterator ScopeDepth; 407 unsigned Index; 408 }; 409 410 /// An unwind destination is an abstract label, branching to which 411 /// may require a jump out through EH cleanups. 412 struct UnwindDest { 413 UnwindDest() : Block(0), ScopeDepth(), Index(0) {} 414 UnwindDest(llvm::BasicBlock *Block, 415 EHScopeStack::stable_iterator Depth, 416 unsigned Index) 417 : Block(Block), ScopeDepth(Depth), Index(Index) {} 418 419 bool isValid() const { return Block != 0; } 420 llvm::BasicBlock *getBlock() const { return Block; } 421 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; } 422 unsigned getDestIndex() const { return Index; } 423 424 private: 425 llvm::BasicBlock *Block; 426 EHScopeStack::stable_iterator ScopeDepth; 427 unsigned Index; 428 }; 429 430 CodeGenModule &CGM; // Per-module state. 431 const TargetInfo &Target; 432 433 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy; 434 CGBuilderTy Builder; 435 436 /// CurFuncDecl - Holds the Decl for the current function or ObjC method. 437 /// This excludes BlockDecls. 438 const Decl *CurFuncDecl; 439 /// CurCodeDecl - This is the inner-most code context, which includes blocks. 440 const Decl *CurCodeDecl; 441 const CGFunctionInfo *CurFnInfo; 442 QualType FnRetTy; 443 llvm::Function *CurFn; 444 445 /// CurGD - The GlobalDecl for the current function being compiled. 446 GlobalDecl CurGD; 447 448 /// ReturnBlock - Unified return block. 449 JumpDest ReturnBlock; 450 451 /// ReturnValue - The temporary alloca to hold the return value. This is null 452 /// iff the function has no return value. 453 llvm::Value *ReturnValue; 454 455 /// RethrowBlock - Unified rethrow block. 456 UnwindDest RethrowBlock; 457 458 /// AllocaInsertPoint - This is an instruction in the entry block before which 459 /// we prefer to insert allocas. 460 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt; 461 462 // intptr_t, i32, i64 463 const llvm::IntegerType *IntPtrTy, *Int32Ty, *Int64Ty; 464 uint32_t LLVMPointerWidth; 465 466 bool Exceptions; 467 bool CatchUndefined; 468 469 /// \brief A mapping from NRVO variables to the flags used to indicate 470 /// when the NRVO has been applied to this variable. 471 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags; 472 473 EHScopeStack EHStack; 474 475 /// i32s containing the indexes of the cleanup destinations. 476 llvm::AllocaInst *NormalCleanupDest; 477 llvm::AllocaInst *EHCleanupDest; 478 479 unsigned NextCleanupDestIndex; 480 481 /// The exception slot. All landing pads write the current 482 /// exception pointer into this alloca. 483 llvm::Value *ExceptionSlot; 484 485 /// Emits a landing pad for the current EH stack. 486 llvm::BasicBlock *EmitLandingPad(); 487 488 llvm::BasicBlock *getInvokeDestImpl(); 489 490public: 491 /// ObjCEHValueStack - Stack of Objective-C exception values, used for 492 /// rethrows. 493 llvm::SmallVector<llvm::Value*, 8> ObjCEHValueStack; 494 495 // A struct holding information about a finally block's IR 496 // generation. For now, doesn't actually hold anything. 497 struct FinallyInfo { 498 }; 499 500 FinallyInfo EnterFinallyBlock(const Stmt *Stmt, 501 llvm::Constant *BeginCatchFn, 502 llvm::Constant *EndCatchFn, 503 llvm::Constant *RethrowFn); 504 void ExitFinallyBlock(FinallyInfo &FinallyInfo); 505 506 /// PushDestructorCleanup - Push a cleanup to call the 507 /// complete-object destructor of an object of the given type at the 508 /// given address. Does nothing if T is not a C++ class type with a 509 /// non-trivial destructor. 510 void PushDestructorCleanup(QualType T, llvm::Value *Addr); 511 512 /// PushDestructorCleanup - Push a cleanup to call the 513 /// complete-object variant of the given destructor on the object at 514 /// the given address. 515 void PushDestructorCleanup(const CXXDestructorDecl *Dtor, 516 llvm::Value *Addr); 517 518 /// PopCleanupBlock - Will pop the cleanup entry on the stack and 519 /// process all branch fixups. 520 void PopCleanupBlock(bool FallThroughIsBranchThrough = false); 521 522 /// \brief Enters a new scope for capturing cleanups, all of which 523 /// will be executed once the scope is exited. 524 class RunCleanupsScope { 525 CodeGenFunction& CGF; 526 EHScopeStack::stable_iterator CleanupStackDepth; 527 bool OldDidCallStackSave; 528 bool PerformCleanup; 529 530 RunCleanupsScope(const RunCleanupsScope &); // DO NOT IMPLEMENT 531 RunCleanupsScope &operator=(const RunCleanupsScope &); // DO NOT IMPLEMENT 532 533 public: 534 /// \brief Enter a new cleanup scope. 535 explicit RunCleanupsScope(CodeGenFunction &CGF) 536 : CGF(CGF), PerformCleanup(true) 537 { 538 CleanupStackDepth = CGF.EHStack.stable_begin(); 539 OldDidCallStackSave = CGF.DidCallStackSave; 540 } 541 542 /// \brief Exit this cleanup scope, emitting any accumulated 543 /// cleanups. 544 ~RunCleanupsScope() { 545 if (PerformCleanup) { 546 CGF.DidCallStackSave = OldDidCallStackSave; 547 CGF.PopCleanupBlocks(CleanupStackDepth); 548 } 549 } 550 551 /// \brief Determine whether this scope requires any cleanups. 552 bool requiresCleanups() const { 553 return CGF.EHStack.stable_begin() != CleanupStackDepth; 554 } 555 556 /// \brief Force the emission of cleanups now, instead of waiting 557 /// until this object is destroyed. 558 void ForceCleanup() { 559 assert(PerformCleanup && "Already forced cleanup"); 560 CGF.DidCallStackSave = OldDidCallStackSave; 561 CGF.PopCleanupBlocks(CleanupStackDepth); 562 PerformCleanup = false; 563 } 564 }; 565 566 567 /// PopCleanupBlocks - Takes the old cleanup stack size and emits 568 /// the cleanup blocks that have been added. 569 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize); 570 571 void ResolveAllBranchFixups(llvm::SwitchInst *Switch); 572 void ResolveBranchFixups(llvm::BasicBlock *Target); 573 574 /// The given basic block lies in the current EH scope, but may be a 575 /// target of a potentially scope-crossing jump; get a stable handle 576 /// to which we can perform this jump later. 577 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) { 578 return JumpDest(Target, 579 EHStack.getInnermostNormalCleanup(), 580 NextCleanupDestIndex++); 581 } 582 583 /// The given basic block lies in the current EH scope, but may be a 584 /// target of a potentially scope-crossing jump; get a stable handle 585 /// to which we can perform this jump later. 586 JumpDest getJumpDestInCurrentScope(const char *Name = 0) { 587 return getJumpDestInCurrentScope(createBasicBlock(Name)); 588 } 589 590 /// EmitBranchThroughCleanup - Emit a branch from the current insert 591 /// block through the normal cleanup handling code (if any) and then 592 /// on to \arg Dest. 593 void EmitBranchThroughCleanup(JumpDest Dest); 594 595 /// EmitBranchThroughEHCleanup - Emit a branch from the current 596 /// insert block through the EH cleanup handling code (if any) and 597 /// then on to \arg Dest. 598 void EmitBranchThroughEHCleanup(UnwindDest Dest); 599 600 /// getRethrowDest - Returns the unified outermost-scope rethrow 601 /// destination. 602 UnwindDest getRethrowDest(); 603 604 /// BeginConditionalBranch - Should be called before a conditional part of an 605 /// expression is emitted. For example, before the RHS of the expression below 606 /// is emitted: 607 /// 608 /// b && f(T()); 609 /// 610 /// This is used to make sure that any temporaries created in the conditional 611 /// branch are only destroyed if the branch is taken. 612 void BeginConditionalBranch() { 613 ++ConditionalBranchLevel; 614 } 615 616 /// EndConditionalBranch - Should be called after a conditional part of an 617 /// expression has been emitted. 618 void EndConditionalBranch() { 619 assert(ConditionalBranchLevel != 0 && 620 "Conditional branch mismatch!"); 621 622 --ConditionalBranchLevel; 623 } 624 625private: 626 CGDebugInfo *DebugInfo; 627 628 /// IndirectBranch - The first time an indirect goto is seen we create a block 629 /// with an indirect branch. Every time we see the address of a label taken, 630 /// we add the label to the indirect goto. Every subsequent indirect goto is 631 /// codegen'd as a jump to the IndirectBranch's basic block. 632 llvm::IndirectBrInst *IndirectBranch; 633 634 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C 635 /// decls. 636 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap; 637 638 /// LabelMap - This keeps track of the LLVM basic block for each C label. 639 llvm::DenseMap<const LabelStmt*, JumpDest> LabelMap; 640 641 // BreakContinueStack - This keeps track of where break and continue 642 // statements should jump to. 643 struct BreakContinue { 644 BreakContinue(JumpDest Break, JumpDest Continue) 645 : BreakBlock(Break), ContinueBlock(Continue) {} 646 647 JumpDest BreakBlock; 648 JumpDest ContinueBlock; 649 }; 650 llvm::SmallVector<BreakContinue, 8> BreakContinueStack; 651 652 /// SwitchInsn - This is nearest current switch instruction. It is null if if 653 /// current context is not in a switch. 654 llvm::SwitchInst *SwitchInsn; 655 656 /// CaseRangeBlock - This block holds if condition check for last case 657 /// statement range in current switch instruction. 658 llvm::BasicBlock *CaseRangeBlock; 659 660 // VLASizeMap - This keeps track of the associated size for each VLA type. 661 // We track this by the size expression rather than the type itself because 662 // in certain situations, like a const qualifier applied to an VLA typedef, 663 // multiple VLA types can share the same size expression. 664 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we 665 // enter/leave scopes. 666 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap; 667 668 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid 669 /// calling llvm.stacksave for multiple VLAs in the same scope. 670 bool DidCallStackSave; 671 672 /// A block containing a single 'unreachable' instruction. Created 673 /// lazily by getUnreachableBlock(). 674 llvm::BasicBlock *UnreachableBlock; 675 676 /// CXXThisDecl - When generating code for a C++ member function, 677 /// this will hold the implicit 'this' declaration. 678 ImplicitParamDecl *CXXThisDecl; 679 llvm::Value *CXXThisValue; 680 681 /// CXXVTTDecl - When generating code for a base object constructor or 682 /// base object destructor with virtual bases, this will hold the implicit 683 /// VTT parameter. 684 ImplicitParamDecl *CXXVTTDecl; 685 llvm::Value *CXXVTTValue; 686 687 /// ConditionalBranchLevel - Contains the nesting level of the current 688 /// conditional branch. This is used so that we know if a temporary should be 689 /// destroyed conditionally. 690 unsigned ConditionalBranchLevel; 691 692 693 /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM 694 /// type as well as the field number that contains the actual data. 695 llvm::DenseMap<const ValueDecl *, std::pair<const llvm::Type *, 696 unsigned> > ByRefValueInfo; 697 698 /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field 699 /// number that holds the value. 700 unsigned getByRefValueLLVMField(const ValueDecl *VD) const; 701 702 llvm::BasicBlock *TerminateLandingPad; 703 llvm::BasicBlock *TerminateHandler; 704 llvm::BasicBlock *TrapBB; 705 706public: 707 CodeGenFunction(CodeGenModule &cgm); 708 709 ASTContext &getContext() const; 710 CGDebugInfo *getDebugInfo() { return DebugInfo; } 711 712 /// Returns a pointer to the function's exception object slot, which 713 /// is assigned in every landing pad. 714 llvm::Value *getExceptionSlot(); 715 716 llvm::Value *getNormalCleanupDestSlot(); 717 llvm::Value *getEHCleanupDestSlot(); 718 719 llvm::BasicBlock *getUnreachableBlock() { 720 if (!UnreachableBlock) { 721 UnreachableBlock = createBasicBlock("unreachable"); 722 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock); 723 } 724 return UnreachableBlock; 725 } 726 727 llvm::BasicBlock *getInvokeDest() { 728 if (!EHStack.requiresLandingPad()) return 0; 729 return getInvokeDestImpl(); 730 } 731 732 llvm::LLVMContext &getLLVMContext() { return VMContext; } 733 734 //===--------------------------------------------------------------------===// 735 // Objective-C 736 //===--------------------------------------------------------------------===// 737 738 void GenerateObjCMethod(const ObjCMethodDecl *OMD); 739 740 void StartObjCMethod(const ObjCMethodDecl *MD, 741 const ObjCContainerDecl *CD); 742 743 /// GenerateObjCGetter - Synthesize an Objective-C property getter function. 744 void GenerateObjCGetter(ObjCImplementationDecl *IMP, 745 const ObjCPropertyImplDecl *PID); 746 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, 747 ObjCMethodDecl *MD, bool ctor); 748 749 /// GenerateObjCSetter - Synthesize an Objective-C property setter function 750 /// for the given property. 751 void GenerateObjCSetter(ObjCImplementationDecl *IMP, 752 const ObjCPropertyImplDecl *PID); 753 bool IndirectObjCSetterArg(const CGFunctionInfo &FI); 754 bool IvarTypeWithAggrGCObjects(QualType Ty); 755 756 //===--------------------------------------------------------------------===// 757 // Block Bits 758 //===--------------------------------------------------------------------===// 759 760 llvm::Value *BuildBlockLiteralTmp(const BlockExpr *); 761 llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *, 762 const CGBlockInfo &Info, 763 const llvm::StructType *, 764 llvm::Constant *BlockVarLayout, 765 std::vector<HelperInfo> *); 766 767 llvm::Function *GenerateBlockFunction(GlobalDecl GD, 768 const BlockExpr *BExpr, 769 CGBlockInfo &Info, 770 const Decl *OuterFuncDecl, 771 llvm::Constant *& BlockVarLayout, 772 llvm::DenseMap<const Decl*, llvm::Value*> ldm); 773 774 llvm::Value *LoadBlockStruct(); 775 776 void AllocateBlockCXXThisPointer(const CXXThisExpr *E); 777 void AllocateBlockDecl(const BlockDeclRefExpr *E); 778 llvm::Value *GetAddrOfBlockDecl(const BlockDeclRefExpr *E) { 779 return GetAddrOfBlockDecl(E->getDecl(), E->isByRef()); 780 } 781 llvm::Value *GetAddrOfBlockDecl(const ValueDecl *D, bool ByRef); 782 const llvm::Type *BuildByRefType(const ValueDecl *D); 783 784 void GenerateCode(GlobalDecl GD, llvm::Function *Fn); 785 void StartFunction(GlobalDecl GD, QualType RetTy, 786 llvm::Function *Fn, 787 const FunctionArgList &Args, 788 SourceLocation StartLoc); 789 790 void EmitConstructorBody(FunctionArgList &Args); 791 void EmitDestructorBody(FunctionArgList &Args); 792 void EmitFunctionBody(FunctionArgList &Args); 793 794 /// EmitReturnBlock - Emit the unified return block, trying to avoid its 795 /// emission when possible. 796 void EmitReturnBlock(); 797 798 /// FinishFunction - Complete IR generation of the current function. It is 799 /// legal to call this function even if there is no current insertion point. 800 void FinishFunction(SourceLocation EndLoc=SourceLocation()); 801 802 /// GenerateThunk - Generate a thunk for the given method. 803 void GenerateThunk(llvm::Function *Fn, GlobalDecl GD, const ThunkInfo &Thunk); 804 805 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type, 806 FunctionArgList &Args); 807 808 /// InitializeVTablePointer - Initialize the vtable pointer of the given 809 /// subobject. 810 /// 811 void InitializeVTablePointer(BaseSubobject Base, 812 const CXXRecordDecl *NearestVBase, 813 uint64_t OffsetFromNearestVBase, 814 llvm::Constant *VTable, 815 const CXXRecordDecl *VTableClass); 816 817 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy; 818 void InitializeVTablePointers(BaseSubobject Base, 819 const CXXRecordDecl *NearestVBase, 820 uint64_t OffsetFromNearestVBase, 821 bool BaseIsNonVirtualPrimaryBase, 822 llvm::Constant *VTable, 823 const CXXRecordDecl *VTableClass, 824 VisitedVirtualBasesSetTy& VBases); 825 826 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl); 827 828 829 /// EnterDtorCleanups - Enter the cleanups necessary to complete the 830 /// given phase of destruction for a destructor. The end result 831 /// should call destructors on members and base classes in reverse 832 /// order of their construction. 833 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type); 834 835 /// ShouldInstrumentFunction - Return true if the current function should be 836 /// instrumented with __cyg_profile_func_* calls 837 bool ShouldInstrumentFunction(); 838 839 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified 840 /// instrumentation function with the current function and the call site, if 841 /// function instrumentation is enabled. 842 void EmitFunctionInstrumentation(const char *Fn); 843 844 /// EmitFunctionProlog - Emit the target specific LLVM code to load the 845 /// arguments for the given function. This is also responsible for naming the 846 /// LLVM function arguments. 847 void EmitFunctionProlog(const CGFunctionInfo &FI, 848 llvm::Function *Fn, 849 const FunctionArgList &Args); 850 851 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the 852 /// given temporary. 853 void EmitFunctionEpilog(const CGFunctionInfo &FI); 854 855 /// EmitStartEHSpec - Emit the start of the exception spec. 856 void EmitStartEHSpec(const Decl *D); 857 858 /// EmitEndEHSpec - Emit the end of the exception spec. 859 void EmitEndEHSpec(const Decl *D); 860 861 /// getTerminateLandingPad - Return a landing pad that just calls terminate. 862 llvm::BasicBlock *getTerminateLandingPad(); 863 864 /// getTerminateHandler - Return a handler (not a landing pad, just 865 /// a catch handler) that just calls terminate. This is used when 866 /// a terminate scope encloses a try. 867 llvm::BasicBlock *getTerminateHandler(); 868 869 const llvm::Type *ConvertTypeForMem(QualType T); 870 const llvm::Type *ConvertType(QualType T); 871 const llvm::Type *ConvertType(const TypeDecl *T) { 872 return ConvertType(getContext().getTypeDeclType(T)); 873 } 874 875 /// LoadObjCSelf - Load the value of self. This function is only valid while 876 /// generating code for an Objective-C method. 877 llvm::Value *LoadObjCSelf(); 878 879 /// TypeOfSelfObject - Return type of object that this self represents. 880 QualType TypeOfSelfObject(); 881 882 /// hasAggregateLLVMType - Return true if the specified AST type will map into 883 /// an aggregate LLVM type or is void. 884 static bool hasAggregateLLVMType(QualType T); 885 886 /// createBasicBlock - Create an LLVM basic block. 887 llvm::BasicBlock *createBasicBlock(const char *Name="", 888 llvm::Function *Parent=0, 889 llvm::BasicBlock *InsertBefore=0) { 890#ifdef NDEBUG 891 return llvm::BasicBlock::Create(VMContext, "", Parent, InsertBefore); 892#else 893 return llvm::BasicBlock::Create(VMContext, Name, Parent, InsertBefore); 894#endif 895 } 896 897 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified 898 /// label maps to. 899 JumpDest getJumpDestForLabel(const LabelStmt *S); 900 901 /// SimplifyForwardingBlocks - If the given basic block is only a branch to 902 /// another basic block, simplify it. This assumes that no other code could 903 /// potentially reference the basic block. 904 void SimplifyForwardingBlocks(llvm::BasicBlock *BB); 905 906 /// EmitBlock - Emit the given block \arg BB and set it as the insert point, 907 /// adding a fall-through branch from the current insert block if 908 /// necessary. It is legal to call this function even if there is no current 909 /// insertion point. 910 /// 911 /// IsFinished - If true, indicates that the caller has finished emitting 912 /// branches to the given block and does not expect to emit code into it. This 913 /// means the block can be ignored if it is unreachable. 914 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false); 915 916 /// EmitBranch - Emit a branch to the specified basic block from the current 917 /// insert block, taking care to avoid creation of branches from dummy 918 /// blocks. It is legal to call this function even if there is no current 919 /// insertion point. 920 /// 921 /// This function clears the current insertion point. The caller should follow 922 /// calls to this function with calls to Emit*Block prior to generation new 923 /// code. 924 void EmitBranch(llvm::BasicBlock *Block); 925 926 /// HaveInsertPoint - True if an insertion point is defined. If not, this 927 /// indicates that the current code being emitted is unreachable. 928 bool HaveInsertPoint() const { 929 return Builder.GetInsertBlock() != 0; 930 } 931 932 /// EnsureInsertPoint - Ensure that an insertion point is defined so that 933 /// emitted IR has a place to go. Note that by definition, if this function 934 /// creates a block then that block is unreachable; callers may do better to 935 /// detect when no insertion point is defined and simply skip IR generation. 936 void EnsureInsertPoint() { 937 if (!HaveInsertPoint()) 938 EmitBlock(createBasicBlock()); 939 } 940 941 /// ErrorUnsupported - Print out an error that codegen doesn't support the 942 /// specified stmt yet. 943 void ErrorUnsupported(const Stmt *S, const char *Type, 944 bool OmitOnError=false); 945 946 //===--------------------------------------------------------------------===// 947 // Helpers 948 //===--------------------------------------------------------------------===// 949 950 Qualifiers MakeQualifiers(QualType T) { 951 Qualifiers Quals = getContext().getCanonicalType(T).getQualifiers(); 952 Quals.setObjCGCAttr(getContext().getObjCGCAttrKind(T)); 953 return Quals; 954 } 955 956 /// CreateTempAlloca - This creates a alloca and inserts it into the entry 957 /// block. The caller is responsible for setting an appropriate alignment on 958 /// the alloca. 959 llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty, 960 const llvm::Twine &Name = "tmp"); 961 962 /// InitTempAlloca - Provide an initial value for the given alloca. 963 void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value); 964 965 /// CreateIRTemp - Create a temporary IR object of the given type, with 966 /// appropriate alignment. This routine should only be used when an temporary 967 /// value needs to be stored into an alloca (for example, to avoid explicit 968 /// PHI construction), but the type is the IR type, not the type appropriate 969 /// for storing in memory. 970 llvm::AllocaInst *CreateIRTemp(QualType T, const llvm::Twine &Name = "tmp"); 971 972 /// CreateMemTemp - Create a temporary memory object of the given type, with 973 /// appropriate alignment. 974 llvm::AllocaInst *CreateMemTemp(QualType T, const llvm::Twine &Name = "tmp"); 975 976 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 977 /// expression and compare the result against zero, returning an Int1Ty value. 978 llvm::Value *EvaluateExprAsBool(const Expr *E); 979 980 /// EmitAnyExpr - Emit code to compute the specified expression which can have 981 /// any type. The result is returned as an RValue struct. If this is an 982 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where 983 /// the result should be returned. 984 /// 985 /// \param IgnoreResult - True if the resulting value isn't used. 986 RValue EmitAnyExpr(const Expr *E, llvm::Value *AggLoc = 0, 987 bool IsAggLocVolatile = false, bool IgnoreResult = false, 988 bool IsInitializer = false); 989 990 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address 991 // or the value of the expression, depending on how va_list is defined. 992 llvm::Value *EmitVAListRef(const Expr *E); 993 994 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will 995 /// always be accessible even if no aggregate location is provided. 996 RValue EmitAnyExprToTemp(const Expr *E, bool IsAggLocVolatile = false, 997 bool IsInitializer = false); 998 999 /// EmitsAnyExprToMem - Emits the code necessary to evaluate an 1000 /// arbitrary expression into the given memory location. 1001 void EmitAnyExprToMem(const Expr *E, llvm::Value *Location, 1002 bool IsLocationVolatile = false, 1003 bool IsInitializer = false); 1004 1005 /// EmitAggregateCopy - Emit an aggrate copy. 1006 /// 1007 /// \param isVolatile - True iff either the source or the destination is 1008 /// volatile. 1009 void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr, 1010 QualType EltTy, bool isVolatile=false); 1011 1012 /// StartBlock - Start new block named N. If insert block is a dummy block 1013 /// then reuse it. 1014 void StartBlock(const char *N); 1015 1016 /// GetAddrOfStaticLocalVar - Return the address of a static local variable. 1017 llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD); 1018 1019 /// GetAddrOfLocalVar - Return the address of a local variable. 1020 llvm::Value *GetAddrOfLocalVar(const VarDecl *VD); 1021 1022 /// getAccessedFieldNo - Given an encoded value and a result number, return 1023 /// the input field number being accessed. 1024 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts); 1025 1026 llvm::BlockAddress *GetAddrOfLabel(const LabelStmt *L); 1027 llvm::BasicBlock *GetIndirectGotoBlock(); 1028 1029 /// EmitNullInitialization - Generate code to set a value of the given type to 1030 /// null, If the type contains data member pointers, they will be initialized 1031 /// to -1 in accordance with the Itanium C++ ABI. 1032 void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty); 1033 1034 // EmitVAArg - Generate code to get an argument from the passed in pointer 1035 // and update it accordingly. The return value is a pointer to the argument. 1036 // FIXME: We should be able to get rid of this method and use the va_arg 1037 // instruction in LLVM instead once it works well enough. 1038 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty); 1039 1040 /// EmitVLASize - Generate code for any VLA size expressions that might occur 1041 /// in a variably modified type. If Ty is a VLA, will return the value that 1042 /// corresponds to the size in bytes of the VLA type. Will return 0 otherwise. 1043 /// 1044 /// This function can be called with a null (unreachable) insert point. 1045 llvm::Value *EmitVLASize(QualType Ty); 1046 1047 // GetVLASize - Returns an LLVM value that corresponds to the size in bytes 1048 // of a variable length array type. 1049 llvm::Value *GetVLASize(const VariableArrayType *); 1050 1051 /// LoadCXXThis - Load the value of 'this'. This function is only valid while 1052 /// generating code for an C++ member function. 1053 llvm::Value *LoadCXXThis() { 1054 assert(CXXThisValue && "no 'this' value for this function"); 1055 return CXXThisValue; 1056 } 1057 1058 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have 1059 /// virtual bases. 1060 llvm::Value *LoadCXXVTT() { 1061 assert(CXXVTTValue && "no VTT value for this function"); 1062 return CXXVTTValue; 1063 } 1064 1065 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a 1066 /// complete class to the given direct base. 1067 llvm::Value * 1068 GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value, 1069 const CXXRecordDecl *Derived, 1070 const CXXRecordDecl *Base, 1071 bool BaseIsVirtual); 1072 1073 /// GetAddressOfBaseClass - This function will add the necessary delta to the 1074 /// load of 'this' and returns address of the base class. 1075 llvm::Value *GetAddressOfBaseClass(llvm::Value *Value, 1076 const CXXRecordDecl *Derived, 1077 CastExpr::path_const_iterator PathBegin, 1078 CastExpr::path_const_iterator PathEnd, 1079 bool NullCheckValue); 1080 1081 llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value, 1082 const CXXRecordDecl *Derived, 1083 CastExpr::path_const_iterator PathBegin, 1084 CastExpr::path_const_iterator PathEnd, 1085 bool NullCheckValue); 1086 1087 llvm::Value *GetVirtualBaseClassOffset(llvm::Value *This, 1088 const CXXRecordDecl *ClassDecl, 1089 const CXXRecordDecl *BaseClassDecl); 1090 1091 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, 1092 CXXCtorType CtorType, 1093 const FunctionArgList &Args); 1094 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 1095 bool ForVirtualBase, llvm::Value *This, 1096 CallExpr::const_arg_iterator ArgBeg, 1097 CallExpr::const_arg_iterator ArgEnd); 1098 1099 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 1100 const ConstantArrayType *ArrayTy, 1101 llvm::Value *ArrayPtr, 1102 CallExpr::const_arg_iterator ArgBeg, 1103 CallExpr::const_arg_iterator ArgEnd, 1104 bool ZeroInitialization = false); 1105 1106 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 1107 llvm::Value *NumElements, 1108 llvm::Value *ArrayPtr, 1109 CallExpr::const_arg_iterator ArgBeg, 1110 CallExpr::const_arg_iterator ArgEnd, 1111 bool ZeroInitialization = false); 1112 1113 void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D, 1114 const ArrayType *Array, 1115 llvm::Value *This); 1116 1117 void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D, 1118 llvm::Value *NumElements, 1119 llvm::Value *This); 1120 1121 llvm::Function *GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D, 1122 const ArrayType *Array, 1123 llvm::Value *This); 1124 1125 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, 1126 bool ForVirtualBase, llvm::Value *This); 1127 1128 void EmitNewArrayInitializer(const CXXNewExpr *E, llvm::Value *NewPtr, 1129 llvm::Value *NumElements); 1130 1131 void EmitCXXTemporary(const CXXTemporary *Temporary, llvm::Value *Ptr); 1132 1133 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E); 1134 void EmitCXXDeleteExpr(const CXXDeleteExpr *E); 1135 1136 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr, 1137 QualType DeleteTy); 1138 1139 llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E); 1140 llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE); 1141 1142 void EmitCheck(llvm::Value *, unsigned Size); 1143 1144 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 1145 bool isInc, bool isPre); 1146 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, 1147 bool isInc, bool isPre); 1148 //===--------------------------------------------------------------------===// 1149 // Declaration Emission 1150 //===--------------------------------------------------------------------===// 1151 1152 /// EmitDecl - Emit a declaration. 1153 /// 1154 /// This function can be called with a null (unreachable) insert point. 1155 void EmitDecl(const Decl &D); 1156 1157 /// EmitBlockVarDecl - Emit a block variable declaration. 1158 /// 1159 /// This function can be called with a null (unreachable) insert point. 1160 void EmitBlockVarDecl(const VarDecl &D); 1161 1162 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D, 1163 llvm::Value *Address); 1164 1165 /// EmitLocalBlockVarDecl - Emit a local block variable declaration. 1166 /// 1167 /// This function can be called with a null (unreachable) insert point. 1168 void EmitLocalBlockVarDecl(const VarDecl &D, SpecialInitFn *SpecialInit = 0); 1169 1170 void EmitStaticBlockVarDecl(const VarDecl &D, 1171 llvm::GlobalValue::LinkageTypes Linkage); 1172 1173 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl. 1174 void EmitParmDecl(const VarDecl &D, llvm::Value *Arg); 1175 1176 //===--------------------------------------------------------------------===// 1177 // Statement Emission 1178 //===--------------------------------------------------------------------===// 1179 1180 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info. 1181 void EmitStopPoint(const Stmt *S); 1182 1183 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call 1184 /// this function even if there is no current insertion point. 1185 /// 1186 /// This function may clear the current insertion point; callers should use 1187 /// EnsureInsertPoint if they wish to subsequently generate code without first 1188 /// calling EmitBlock, EmitBranch, or EmitStmt. 1189 void EmitStmt(const Stmt *S); 1190 1191 /// EmitSimpleStmt - Try to emit a "simple" statement which does not 1192 /// necessarily require an insertion point or debug information; typically 1193 /// because the statement amounts to a jump or a container of other 1194 /// statements. 1195 /// 1196 /// \return True if the statement was handled. 1197 bool EmitSimpleStmt(const Stmt *S); 1198 1199 RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false, 1200 llvm::Value *AggLoc = 0, bool isAggVol = false); 1201 1202 /// EmitLabel - Emit the block for the given label. It is legal to call this 1203 /// function even if there is no current insertion point. 1204 void EmitLabel(const LabelStmt &S); // helper for EmitLabelStmt. 1205 1206 void EmitLabelStmt(const LabelStmt &S); 1207 void EmitGotoStmt(const GotoStmt &S); 1208 void EmitIndirectGotoStmt(const IndirectGotoStmt &S); 1209 void EmitIfStmt(const IfStmt &S); 1210 void EmitWhileStmt(const WhileStmt &S); 1211 void EmitDoStmt(const DoStmt &S); 1212 void EmitForStmt(const ForStmt &S); 1213 void EmitReturnStmt(const ReturnStmt &S); 1214 void EmitDeclStmt(const DeclStmt &S); 1215 void EmitBreakStmt(const BreakStmt &S); 1216 void EmitContinueStmt(const ContinueStmt &S); 1217 void EmitSwitchStmt(const SwitchStmt &S); 1218 void EmitDefaultStmt(const DefaultStmt &S); 1219 void EmitCaseStmt(const CaseStmt &S); 1220 void EmitCaseStmtRange(const CaseStmt &S); 1221 void EmitAsmStmt(const AsmStmt &S); 1222 1223 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S); 1224 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S); 1225 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S); 1226 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S); 1227 1228 llvm::Constant *getUnwindResumeOrRethrowFn(); 1229 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 1230 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 1231 1232 void EmitCXXTryStmt(const CXXTryStmt &S); 1233 1234 //===--------------------------------------------------------------------===// 1235 // LValue Expression Emission 1236 //===--------------------------------------------------------------------===// 1237 1238 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type. 1239 RValue GetUndefRValue(QualType Ty); 1240 1241 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E 1242 /// and issue an ErrorUnsupported style diagnostic (using the 1243 /// provided Name). 1244 RValue EmitUnsupportedRValue(const Expr *E, 1245 const char *Name); 1246 1247 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue 1248 /// an ErrorUnsupported style diagnostic (using the provided Name). 1249 LValue EmitUnsupportedLValue(const Expr *E, 1250 const char *Name); 1251 1252 /// EmitLValue - Emit code to compute a designator that specifies the location 1253 /// of the expression. 1254 /// 1255 /// This can return one of two things: a simple address or a bitfield 1256 /// reference. In either case, the LLVM Value* in the LValue structure is 1257 /// guaranteed to be an LLVM pointer type. 1258 /// 1259 /// If this returns a bitfield reference, nothing about the pointee type of 1260 /// the LLVM value is known: For example, it may not be a pointer to an 1261 /// integer. 1262 /// 1263 /// If this returns a normal address, and if the lvalue's C type is fixed 1264 /// size, this method guarantees that the returned pointer type will point to 1265 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a 1266 /// variable length type, this is not possible. 1267 /// 1268 LValue EmitLValue(const Expr *E); 1269 1270 /// EmitCheckedLValue - Same as EmitLValue but additionally we generate 1271 /// checking code to guard against undefined behavior. This is only 1272 /// suitable when we know that the address will be used to access the 1273 /// object. 1274 LValue EmitCheckedLValue(const Expr *E); 1275 1276 /// EmitLoadOfScalar - Load a scalar value from an address, taking 1277 /// care to appropriately convert from the memory representation to 1278 /// the LLVM value representation. 1279 llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile, 1280 QualType Ty); 1281 1282 /// EmitStoreOfScalar - Store a scalar value to an address, taking 1283 /// care to appropriately convert from the memory representation to 1284 /// the LLVM value representation. 1285 void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr, 1286 bool Volatile, QualType Ty); 1287 1288 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, 1289 /// this method emits the address of the lvalue, then loads the result as an 1290 /// rvalue, returning the rvalue. 1291 RValue EmitLoadOfLValue(LValue V, QualType LVType); 1292 RValue EmitLoadOfExtVectorElementLValue(LValue V, QualType LVType); 1293 RValue EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType); 1294 RValue EmitLoadOfPropertyRefLValue(LValue LV, QualType ExprType); 1295 RValue EmitLoadOfKVCRefLValue(LValue LV, QualType ExprType); 1296 1297 1298 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 1299 /// lvalue, where both are guaranteed to the have the same type, and that type 1300 /// is 'Ty'. 1301 void EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty); 1302 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst, 1303 QualType Ty); 1304 void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst, QualType Ty); 1305 void EmitStoreThroughKVCRefLValue(RValue Src, LValue Dst, QualType Ty); 1306 1307 /// EmitStoreThroughLValue - Store Src into Dst with same constraints as 1308 /// EmitStoreThroughLValue. 1309 /// 1310 /// \param Result [out] - If non-null, this will be set to a Value* for the 1311 /// bit-field contents after the store, appropriate for use as the result of 1312 /// an assignment to the bit-field. 1313 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty, 1314 llvm::Value **Result=0); 1315 1316 // Note: only availabe for agg return types 1317 LValue EmitBinaryOperatorLValue(const BinaryOperator *E); 1318 LValue EmitCompoundAssignOperatorLValue(const CompoundAssignOperator *E); 1319 // Note: only available for agg return types 1320 LValue EmitCallExprLValue(const CallExpr *E); 1321 // Note: only available for agg return types 1322 LValue EmitVAArgExprLValue(const VAArgExpr *E); 1323 LValue EmitDeclRefLValue(const DeclRefExpr *E); 1324 LValue EmitStringLiteralLValue(const StringLiteral *E); 1325 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E); 1326 LValue EmitPredefinedFunctionName(unsigned Type); 1327 LValue EmitPredefinedLValue(const PredefinedExpr *E); 1328 LValue EmitUnaryOpLValue(const UnaryOperator *E); 1329 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E); 1330 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E); 1331 LValue EmitMemberExpr(const MemberExpr *E); 1332 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E); 1333 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E); 1334 LValue EmitConditionalOperatorLValue(const ConditionalOperator *E); 1335 LValue EmitCastLValue(const CastExpr *E); 1336 LValue EmitNullInitializationLValue(const CXXScalarValueInitExpr *E); 1337 1338 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface, 1339 const ObjCIvarDecl *Ivar); 1340 LValue EmitLValueForAnonRecordField(llvm::Value* Base, 1341 const FieldDecl* Field, 1342 unsigned CVRQualifiers); 1343 LValue EmitLValueForField(llvm::Value* Base, const FieldDecl* Field, 1344 unsigned CVRQualifiers); 1345 1346 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that 1347 /// if the Field is a reference, this will return the address of the reference 1348 /// and not the address of the value stored in the reference. 1349 LValue EmitLValueForFieldInitialization(llvm::Value* Base, 1350 const FieldDecl* Field, 1351 unsigned CVRQualifiers); 1352 1353 LValue EmitLValueForIvar(QualType ObjectTy, 1354 llvm::Value* Base, const ObjCIvarDecl *Ivar, 1355 unsigned CVRQualifiers); 1356 1357 LValue EmitLValueForBitfield(llvm::Value* Base, const FieldDecl* Field, 1358 unsigned CVRQualifiers); 1359 1360 LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E); 1361 1362 LValue EmitCXXConstructLValue(const CXXConstructExpr *E); 1363 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E); 1364 LValue EmitCXXExprWithTemporariesLValue(const CXXExprWithTemporaries *E); 1365 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E); 1366 1367 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E); 1368 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E); 1369 LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E); 1370 LValue EmitObjCKVCRefLValue(const ObjCImplicitSetterGetterRefExpr *E); 1371 LValue EmitObjCSuperExprLValue(const ObjCSuperExpr *E); 1372 LValue EmitStmtExprLValue(const StmtExpr *E); 1373 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E); 1374 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E); 1375 1376 //===--------------------------------------------------------------------===// 1377 // Scalar Expression Emission 1378 //===--------------------------------------------------------------------===// 1379 1380 /// EmitCall - Generate a call of the given function, expecting the given 1381 /// result type, and using the given argument list which specifies both the 1382 /// LLVM arguments and the types they were derived from. 1383 /// 1384 /// \param TargetDecl - If given, the decl of the function in a direct call; 1385 /// used to set attributes on the call (noreturn, etc.). 1386 RValue EmitCall(const CGFunctionInfo &FnInfo, 1387 llvm::Value *Callee, 1388 ReturnValueSlot ReturnValue, 1389 const CallArgList &Args, 1390 const Decl *TargetDecl = 0, 1391 llvm::Instruction **callOrInvoke = 0); 1392 1393 RValue EmitCall(QualType FnType, llvm::Value *Callee, 1394 ReturnValueSlot ReturnValue, 1395 CallExpr::const_arg_iterator ArgBeg, 1396 CallExpr::const_arg_iterator ArgEnd, 1397 const Decl *TargetDecl = 0); 1398 RValue EmitCallExpr(const CallExpr *E, 1399 ReturnValueSlot ReturnValue = ReturnValueSlot()); 1400 1401 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee, 1402 llvm::Value * const *ArgBegin, 1403 llvm::Value * const *ArgEnd, 1404 const llvm::Twine &Name = ""); 1405 1406 llvm::Value *BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This, 1407 const llvm::Type *Ty); 1408 llvm::Value *BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type, 1409 llvm::Value *&This, const llvm::Type *Ty); 1410 1411 RValue EmitCXXMemberCall(const CXXMethodDecl *MD, 1412 llvm::Value *Callee, 1413 ReturnValueSlot ReturnValue, 1414 llvm::Value *This, 1415 llvm::Value *VTT, 1416 CallExpr::const_arg_iterator ArgBeg, 1417 CallExpr::const_arg_iterator ArgEnd); 1418 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E, 1419 ReturnValueSlot ReturnValue); 1420 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, 1421 ReturnValueSlot ReturnValue); 1422 1423 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 1424 const CXXMethodDecl *MD, 1425 ReturnValueSlot ReturnValue); 1426 1427 1428 RValue EmitBuiltinExpr(const FunctionDecl *FD, 1429 unsigned BuiltinID, const CallExpr *E); 1430 1431 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue); 1432 1433 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call 1434 /// is unhandled by the current target. 1435 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 1436 1437 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 1438 llvm::Value *EmitNeonCall(llvm::Function *F, 1439 llvm::SmallVectorImpl<llvm::Value*> &O, 1440 const char *name, bool splat = false, 1441 unsigned shift = 0, bool rightshift = false); 1442 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx, 1443 bool widen = false); 1444 llvm::Value *EmitNeonShiftVector(llvm::Value *V, const llvm::Type *Ty, 1445 bool negateForRightShift); 1446 1447 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 1448 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 1449 1450 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E); 1451 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E); 1452 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E); 1453 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, 1454 ReturnValueSlot Return = ReturnValueSlot()); 1455 RValue EmitObjCPropertyGet(const Expr *E, 1456 ReturnValueSlot Return = ReturnValueSlot()); 1457 RValue EmitObjCSuperPropertyGet(const Expr *Exp, const Selector &S, 1458 ReturnValueSlot Return = ReturnValueSlot()); 1459 void EmitObjCPropertySet(const Expr *E, RValue Src); 1460 void EmitObjCSuperPropertySet(const Expr *E, const Selector &S, RValue Src); 1461 1462 1463 /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in 1464 /// expression. Will emit a temporary variable if E is not an LValue. 1465 RValue EmitReferenceBindingToExpr(const Expr* E, 1466 const NamedDecl *InitializedDecl); 1467 1468 //===--------------------------------------------------------------------===// 1469 // Expression Emission 1470 //===--------------------------------------------------------------------===// 1471 1472 // Expressions are broken into three classes: scalar, complex, aggregate. 1473 1474 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM 1475 /// scalar type, returning the result. 1476 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false); 1477 1478 /// EmitScalarConversion - Emit a conversion from the specified type to the 1479 /// specified destination type, both of which are LLVM scalar types. 1480 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy, 1481 QualType DstTy); 1482 1483 /// EmitComplexToScalarConversion - Emit a conversion from the specified 1484 /// complex type to the specified destination type, where the destination type 1485 /// is an LLVM scalar type. 1486 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, 1487 QualType DstTy); 1488 1489 1490 /// EmitAggExpr - Emit the computation of the specified expression of 1491 /// aggregate type. The result is computed into DestPtr. Note that if 1492 /// DestPtr is null, the value of the aggregate expression is not needed. 1493 void EmitAggExpr(const Expr *E, llvm::Value *DestPtr, bool VolatileDest, 1494 bool IgnoreResult = false, bool IsInitializer = false, 1495 bool RequiresGCollection = false); 1496 1497 /// EmitAggExprToLValue - Emit the computation of the specified expression of 1498 /// aggregate type into a temporary LValue. 1499 LValue EmitAggExprToLValue(const Expr *E); 1500 1501 /// EmitGCMemmoveCollectable - Emit special API for structs with object 1502 /// pointers. 1503 void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr, 1504 QualType Ty); 1505 1506 /// EmitComplexExpr - Emit the computation of the specified expression of 1507 /// complex type, returning the result. 1508 ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal = false, 1509 bool IgnoreImag = false, 1510 bool IgnoreRealAssign = false, 1511 bool IgnoreImagAssign = false); 1512 1513 /// EmitComplexExprIntoAddr - Emit the computation of the specified expression 1514 /// of complex type, storing into the specified Value*. 1515 void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr, 1516 bool DestIsVolatile); 1517 1518 /// StoreComplexToAddr - Store a complex number into the specified address. 1519 void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr, 1520 bool DestIsVolatile); 1521 /// LoadComplexFromAddr - Load a complex number from the specified address. 1522 ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile); 1523 1524 /// CreateStaticBlockVarDecl - Create a zero-initialized LLVM global for a 1525 /// static block var decl. 1526 llvm::GlobalVariable *CreateStaticBlockVarDecl(const VarDecl &D, 1527 const char *Separator, 1528 llvm::GlobalValue::LinkageTypes Linkage); 1529 1530 /// AddInitializerToGlobalBlockVarDecl - Add the initializer for 'D' to the 1531 /// global variable that has already been created for it. If the initializer 1532 /// has a different type than GV does, this may free GV and return a different 1533 /// one. Otherwise it just returns GV. 1534 llvm::GlobalVariable * 1535 AddInitializerToGlobalBlockVarDecl(const VarDecl &D, 1536 llvm::GlobalVariable *GV); 1537 1538 1539 /// EmitStaticCXXBlockVarDeclInit - Create the initializer for a C++ runtime 1540 /// initialized static block var decl. 1541 void EmitStaticCXXBlockVarDeclInit(const VarDecl &D, 1542 llvm::GlobalVariable *GV); 1543 1544 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++ 1545 /// variable with global storage. 1546 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr); 1547 1548 /// EmitCXXGlobalDtorRegistration - Emits a call to register the global ptr 1549 /// with the C++ runtime so that its destructor will be called at exit. 1550 void EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn, 1551 llvm::Constant *DeclPtr); 1552 1553 /// GenerateCXXGlobalInitFunc - Generates code for initializing global 1554 /// variables. 1555 void GenerateCXXGlobalInitFunc(llvm::Function *Fn, 1556 llvm::Constant **Decls, 1557 unsigned NumDecls); 1558 1559 /// GenerateCXXGlobalDtorFunc - Generates code for destroying global 1560 /// variables. 1561 void GenerateCXXGlobalDtorFunc(llvm::Function *Fn, 1562 const std::vector<std::pair<llvm::WeakVH, 1563 llvm::Constant*> > &DtorsAndObjects); 1564 1565 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, const VarDecl *D); 1566 1567 void EmitCXXConstructExpr(llvm::Value *Dest, const CXXConstructExpr *E); 1568 1569 RValue EmitCXXExprWithTemporaries(const CXXExprWithTemporaries *E, 1570 llvm::Value *AggLoc = 0, 1571 bool IsAggLocVolatile = false, 1572 bool IsInitializer = false); 1573 1574 void EmitCXXThrowExpr(const CXXThrowExpr *E); 1575 1576 //===--------------------------------------------------------------------===// 1577 // Internal Helpers 1578 //===--------------------------------------------------------------------===// 1579 1580 /// ContainsLabel - Return true if the statement contains a label in it. If 1581 /// this statement is not executed normally, it not containing a label means 1582 /// that we can just remove the code. 1583 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false); 1584 1585 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 1586 /// to a constant, or if it does but contains a label, return 0. If it 1587 /// constant folds to 'true' and does not contain a label, return 1, if it 1588 /// constant folds to 'false' and does not contain a label, return -1. 1589 int ConstantFoldsToSimpleInteger(const Expr *Cond); 1590 1591 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an 1592 /// if statement) to the specified blocks. Based on the condition, this might 1593 /// try to simplify the codegen of the conditional based on the branch. 1594 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, 1595 llvm::BasicBlock *FalseBlock); 1596 1597 /// getTrapBB - Create a basic block that will call the trap intrinsic. We'll 1598 /// generate a branch around the created basic block as necessary. 1599 llvm::BasicBlock *getTrapBB(); 1600 1601 /// EmitCallArg - Emit a single call argument. 1602 RValue EmitCallArg(const Expr *E, QualType ArgType); 1603 1604 /// EmitDelegateCallArg - We are performing a delegate call; that 1605 /// is, the current function is delegating to another one. Produce 1606 /// a r-value suitable for passing the given parameter. 1607 RValue EmitDelegateCallArg(const VarDecl *Param); 1608 1609private: 1610 void EmitReturnOfRValue(RValue RV, QualType Ty); 1611 1612 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty 1613 /// from function arguments into \arg Dst. See ABIArgInfo::Expand. 1614 /// 1615 /// \param AI - The first function argument of the expansion. 1616 /// \return The argument following the last expanded function 1617 /// argument. 1618 llvm::Function::arg_iterator 1619 ExpandTypeFromArgs(QualType Ty, LValue Dst, 1620 llvm::Function::arg_iterator AI); 1621 1622 /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg 1623 /// Ty, into individual arguments on the provided vector \arg Args. See 1624 /// ABIArgInfo::Expand. 1625 void ExpandTypeToArgs(QualType Ty, RValue Src, 1626 llvm::SmallVector<llvm::Value*, 16> &Args); 1627 1628 llvm::Value* EmitAsmInput(const AsmStmt &S, 1629 const TargetInfo::ConstraintInfo &Info, 1630 const Expr *InputExpr, std::string &ConstraintStr); 1631 1632 llvm::Value* EmitAsmInputLValue(const AsmStmt &S, 1633 const TargetInfo::ConstraintInfo &Info, 1634 LValue InputValue, QualType InputType, 1635 std::string &ConstraintStr); 1636 1637 /// EmitCallArgs - Emit call arguments for a function. 1638 /// The CallArgTypeInfo parameter is used for iterating over the known 1639 /// argument types of the function being called. 1640 template<typename T> 1641 void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo, 1642 CallExpr::const_arg_iterator ArgBeg, 1643 CallExpr::const_arg_iterator ArgEnd) { 1644 CallExpr::const_arg_iterator Arg = ArgBeg; 1645 1646 // First, use the argument types that the type info knows about 1647 if (CallArgTypeInfo) { 1648 for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(), 1649 E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) { 1650 assert(Arg != ArgEnd && "Running over edge of argument list!"); 1651 QualType ArgType = *I; 1652 1653 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()). 1654 getTypePtr() == 1655 getContext().getCanonicalType(Arg->getType()).getTypePtr() && 1656 "type mismatch in call argument!"); 1657 1658 Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType), 1659 ArgType)); 1660 } 1661 1662 // Either we've emitted all the call args, or we have a call to a 1663 // variadic function. 1664 assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) && 1665 "Extra arguments in non-variadic function!"); 1666 1667 } 1668 1669 // If we still have any arguments, emit them using the type of the argument. 1670 for (; Arg != ArgEnd; ++Arg) { 1671 QualType ArgType = Arg->getType(); 1672 Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType), 1673 ArgType)); 1674 } 1675 } 1676 1677 const TargetCodeGenInfo &getTargetHooks() const { 1678 return CGM.getTargetCodeGenInfo(); 1679 } 1680 1681 void EmitDeclMetadata(); 1682}; 1683 1684/// CGBlockInfo - Information to generate a block literal. 1685class CGBlockInfo { 1686public: 1687 /// Name - The name of the block, kindof. 1688 const char *Name; 1689 1690 /// DeclRefs - Variables from parent scopes that have been 1691 /// imported into this block. 1692 llvm::SmallVector<const BlockDeclRefExpr *, 8> DeclRefs; 1693 1694 /// InnerBlocks - This block and the blocks it encloses. 1695 llvm::SmallPtrSet<const DeclContext *, 4> InnerBlocks; 1696 1697 /// CXXThisRef - Non-null if 'this' was required somewhere, in 1698 /// which case this is that expression. 1699 const CXXThisExpr *CXXThisRef; 1700 1701 /// NeedsObjCSelf - True if something in this block has an implicit 1702 /// reference to 'self'. 1703 bool NeedsObjCSelf; 1704 1705 /// These are initialized by GenerateBlockFunction. 1706 bool BlockHasCopyDispose; 1707 CharUnits BlockSize; 1708 CharUnits BlockAlign; 1709 llvm::SmallVector<const Expr*, 8> BlockLayout; 1710 1711 CGBlockInfo(const char *Name); 1712}; 1713 1714} // end namespace CodeGen 1715} // end namespace clang 1716 1717#endif 1718