CodeGenFunction.h revision 206084
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 Module; 36 class SwitchInst; 37 class Twine; 38 class Value; 39} 40 41namespace clang { 42 class ASTContext; 43 class CXXDestructorDecl; 44 class CXXTryStmt; 45 class Decl; 46 class EnumConstantDecl; 47 class FunctionDecl; 48 class FunctionProtoType; 49 class LabelStmt; 50 class ObjCContainerDecl; 51 class ObjCInterfaceDecl; 52 class ObjCIvarDecl; 53 class ObjCMethodDecl; 54 class ObjCImplementationDecl; 55 class ObjCPropertyImplDecl; 56 class TargetInfo; 57 class TargetCodeGenInfo; 58 class VarDecl; 59 class ObjCForCollectionStmt; 60 class ObjCAtTryStmt; 61 class ObjCAtThrowStmt; 62 class ObjCAtSynchronizedStmt; 63 64namespace CodeGen { 65 class CodeGenTypes; 66 class CGDebugInfo; 67 class CGFunctionInfo; 68 class CGRecordLayout; 69 70/// CodeGenFunction - This class organizes the per-function state that is used 71/// while generating LLVM code. 72class CodeGenFunction : public BlockFunction { 73 CodeGenFunction(const CodeGenFunction&); // DO NOT IMPLEMENT 74 void operator=(const CodeGenFunction&); // DO NOT IMPLEMENT 75public: 76 CodeGenModule &CGM; // Per-module state. 77 const TargetInfo &Target; 78 79 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy; 80 CGBuilderTy Builder; 81 82 /// CurFuncDecl - Holds the Decl for the current function or ObjC method. 83 /// This excludes BlockDecls. 84 const Decl *CurFuncDecl; 85 /// CurCodeDecl - This is the inner-most code context, which includes blocks. 86 const Decl *CurCodeDecl; 87 const CGFunctionInfo *CurFnInfo; 88 QualType FnRetTy; 89 llvm::Function *CurFn; 90 91 /// CurGD - The GlobalDecl for the current function being compiled. 92 GlobalDecl CurGD; 93 94 /// ReturnBlock - Unified return block. 95 llvm::BasicBlock *ReturnBlock; 96 /// ReturnValue - The temporary alloca to hold the return value. This is null 97 /// iff the function has no return value. 98 llvm::Value *ReturnValue; 99 100 /// AllocaInsertPoint - This is an instruction in the entry block before which 101 /// we prefer to insert allocas. 102 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt; 103 104 const llvm::Type *LLVMIntTy; 105 uint32_t LLVMPointerWidth; 106 107 bool Exceptions; 108 bool CatchUndefined; 109public: 110 /// ObjCEHValueStack - Stack of Objective-C exception values, used for 111 /// rethrows. 112 llvm::SmallVector<llvm::Value*, 8> ObjCEHValueStack; 113 114 /// PushCleanupBlock - Push a new cleanup entry on the stack and set the 115 /// passed in block as the cleanup block. 116 void PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock, 117 llvm::BasicBlock *CleanupExitBlock, 118 llvm::BasicBlock *PreviousInvokeDest, 119 bool EHOnly = false); 120 void PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock) { 121 PushCleanupBlock(CleanupEntryBlock, 0, getInvokeDest(), false); 122 } 123 124 /// CleanupBlockInfo - A struct representing a popped cleanup block. 125 struct CleanupBlockInfo { 126 /// CleanupEntryBlock - the cleanup entry block 127 llvm::BasicBlock *CleanupBlock; 128 129 /// SwitchBlock - the block (if any) containing the switch instruction used 130 /// for jumping to the final destination. 131 llvm::BasicBlock *SwitchBlock; 132 133 /// EndBlock - the default destination for the switch instruction. 134 llvm::BasicBlock *EndBlock; 135 136 /// EHOnly - True iff this cleanup should only be performed on the 137 /// exceptional edge. 138 bool EHOnly; 139 140 CleanupBlockInfo(llvm::BasicBlock *cb, llvm::BasicBlock *sb, 141 llvm::BasicBlock *eb, bool ehonly = false) 142 : CleanupBlock(cb), SwitchBlock(sb), EndBlock(eb), EHOnly(ehonly) {} 143 }; 144 145 /// EHCleanupBlock - RAII object that will create a cleanup block for the 146 /// exceptional edge and set the insert point to that block. When destroyed, 147 /// it creates the cleanup edge and sets the insert point to the previous 148 /// block. 149 class EHCleanupBlock { 150 CodeGenFunction& CGF; 151 llvm::BasicBlock *Cont; 152 llvm::BasicBlock *CleanupHandler; 153 llvm::BasicBlock *CleanupEntryBB; 154 llvm::BasicBlock *PreviousInvokeDest; 155 public: 156 EHCleanupBlock(CodeGenFunction &cgf) 157 : CGF(cgf), Cont(CGF.createBasicBlock("cont")), 158 CleanupHandler(CGF.createBasicBlock("ehcleanup")), 159 CleanupEntryBB(CGF.createBasicBlock("ehcleanup.rest")), 160 PreviousInvokeDest(CGF.getInvokeDest()) { 161 CGF.EmitBranch(Cont); 162 llvm::BasicBlock *TerminateHandler = CGF.getTerminateHandler(); 163 CGF.Builder.SetInsertPoint(CleanupEntryBB); 164 CGF.setInvokeDest(TerminateHandler); 165 } 166 ~EHCleanupBlock(); 167 }; 168 169 /// PopCleanupBlock - Will pop the cleanup entry on the stack, process all 170 /// branch fixups and return a block info struct with the switch block and end 171 /// block. This will also reset the invoke handler to the previous value 172 /// from when the cleanup block was created. 173 CleanupBlockInfo PopCleanupBlock(); 174 175 /// DelayedCleanupBlock - RAII object that will create a cleanup block and set 176 /// the insert point to that block. When destructed, it sets the insert point 177 /// to the previous block and pushes a new cleanup entry on the stack. 178 class DelayedCleanupBlock { 179 CodeGenFunction& CGF; 180 llvm::BasicBlock *CurBB; 181 llvm::BasicBlock *CleanupEntryBB; 182 llvm::BasicBlock *CleanupExitBB; 183 llvm::BasicBlock *CurInvokeDest; 184 bool EHOnly; 185 186 public: 187 DelayedCleanupBlock(CodeGenFunction &cgf, bool ehonly = false) 188 : CGF(cgf), CurBB(CGF.Builder.GetInsertBlock()), 189 CleanupEntryBB(CGF.createBasicBlock("cleanup")), CleanupExitBB(0), 190 CurInvokeDest(CGF.getInvokeDest()), 191 EHOnly(ehonly) { 192 CGF.Builder.SetInsertPoint(CleanupEntryBB); 193 } 194 195 llvm::BasicBlock *getCleanupExitBlock() { 196 if (!CleanupExitBB) 197 CleanupExitBB = CGF.createBasicBlock("cleanup.exit"); 198 return CleanupExitBB; 199 } 200 201 ~DelayedCleanupBlock() { 202 CGF.PushCleanupBlock(CleanupEntryBB, CleanupExitBB, CurInvokeDest, 203 EHOnly); 204 // FIXME: This is silly, move this into the builder. 205 if (CurBB) 206 CGF.Builder.SetInsertPoint(CurBB); 207 else 208 CGF.Builder.ClearInsertionPoint(); 209 } 210 }; 211 212 /// \brief Enters a new scope for capturing cleanups, all of which will be 213 /// executed once the scope is exited. 214 class CleanupScope { 215 CodeGenFunction& CGF; 216 size_t CleanupStackDepth; 217 bool OldDidCallStackSave; 218 bool PerformCleanup; 219 220 CleanupScope(const CleanupScope &); // DO NOT IMPLEMENT 221 CleanupScope &operator=(const CleanupScope &); // DO NOT IMPLEMENT 222 223 public: 224 /// \brief Enter a new cleanup scope. 225 explicit CleanupScope(CodeGenFunction &CGF) 226 : CGF(CGF), PerformCleanup(true) 227 { 228 CleanupStackDepth = CGF.CleanupEntries.size(); 229 OldDidCallStackSave = CGF.DidCallStackSave; 230 } 231 232 /// \brief Exit this cleanup scope, emitting any accumulated 233 /// cleanups. 234 ~CleanupScope() { 235 if (PerformCleanup) { 236 CGF.DidCallStackSave = OldDidCallStackSave; 237 CGF.EmitCleanupBlocks(CleanupStackDepth); 238 } 239 } 240 241 /// \brief Determine whether this scope requires any cleanups. 242 bool requiresCleanups() const { 243 return CGF.CleanupEntries.size() > CleanupStackDepth; 244 } 245 246 /// \brief Force the emission of cleanups now, instead of waiting 247 /// until this object is destroyed. 248 void ForceCleanup() { 249 assert(PerformCleanup && "Already forced cleanup"); 250 CGF.DidCallStackSave = OldDidCallStackSave; 251 CGF.EmitCleanupBlocks(CleanupStackDepth); 252 PerformCleanup = false; 253 } 254 }; 255 256 /// CXXTemporariesCleanupScope - Enters a new scope for catching live 257 /// temporaries, all of which will be popped once the scope is exited. 258 class CXXTemporariesCleanupScope { 259 CodeGenFunction &CGF; 260 size_t NumLiveTemporaries; 261 262 // DO NOT IMPLEMENT 263 CXXTemporariesCleanupScope(const CXXTemporariesCleanupScope &); 264 CXXTemporariesCleanupScope &operator=(const CXXTemporariesCleanupScope &); 265 266 public: 267 explicit CXXTemporariesCleanupScope(CodeGenFunction &CGF) 268 : CGF(CGF), NumLiveTemporaries(CGF.LiveTemporaries.size()) { } 269 270 ~CXXTemporariesCleanupScope() { 271 while (CGF.LiveTemporaries.size() > NumLiveTemporaries) 272 CGF.PopCXXTemporary(); 273 } 274 }; 275 276 277 /// EmitCleanupBlocks - Takes the old cleanup stack size and emits the cleanup 278 /// blocks that have been added. 279 void EmitCleanupBlocks(size_t OldCleanupStackSize); 280 281 /// EmitBranchThroughCleanup - Emit a branch from the current insert block 282 /// through the cleanup handling code (if any) and then on to \arg Dest. 283 /// 284 /// FIXME: Maybe this should really be in EmitBranch? Don't we always want 285 /// this behavior for branches? 286 void EmitBranchThroughCleanup(llvm::BasicBlock *Dest); 287 288 /// BeginConditionalBranch - Should be called before a conditional part of an 289 /// expression is emitted. For example, before the RHS of the expression below 290 /// is emitted: 291 /// 292 /// b && f(T()); 293 /// 294 /// This is used to make sure that any temporaries created in the conditional 295 /// branch are only destroyed if the branch is taken. 296 void BeginConditionalBranch() { 297 ++ConditionalBranchLevel; 298 } 299 300 /// EndConditionalBranch - Should be called after a conditional part of an 301 /// expression has been emitted. 302 void EndConditionalBranch() { 303 assert(ConditionalBranchLevel != 0 && 304 "Conditional branch mismatch!"); 305 306 --ConditionalBranchLevel; 307 } 308 309private: 310 CGDebugInfo *DebugInfo; 311 312 /// IndirectBranch - The first time an indirect goto is seen we create a block 313 /// with an indirect branch. Every time we see the address of a label taken, 314 /// we add the label to the indirect goto. Every subsequent indirect goto is 315 /// codegen'd as a jump to the IndirectBranch's basic block. 316 llvm::IndirectBrInst *IndirectBranch; 317 318 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C 319 /// decls. 320 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap; 321 322 /// LabelMap - This keeps track of the LLVM basic block for each C label. 323 llvm::DenseMap<const LabelStmt*, llvm::BasicBlock*> LabelMap; 324 325 // BreakContinueStack - This keeps track of where break and continue 326 // statements should jump to. 327 struct BreakContinue { 328 BreakContinue(llvm::BasicBlock *bb, llvm::BasicBlock *cb) 329 : BreakBlock(bb), ContinueBlock(cb) {} 330 331 llvm::BasicBlock *BreakBlock; 332 llvm::BasicBlock *ContinueBlock; 333 }; 334 llvm::SmallVector<BreakContinue, 8> BreakContinueStack; 335 336 /// SwitchInsn - This is nearest current switch instruction. It is null if if 337 /// current context is not in a switch. 338 llvm::SwitchInst *SwitchInsn; 339 340 /// CaseRangeBlock - This block holds if condition check for last case 341 /// statement range in current switch instruction. 342 llvm::BasicBlock *CaseRangeBlock; 343 344 /// InvokeDest - This is the nearest exception target for calls 345 /// which can unwind, when exceptions are being used. 346 llvm::BasicBlock *InvokeDest; 347 348 // VLASizeMap - This keeps track of the associated size for each VLA type. 349 // We track this by the size expression rather than the type itself because 350 // in certain situations, like a const qualifier applied to an VLA typedef, 351 // multiple VLA types can share the same size expression. 352 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we 353 // enter/leave scopes. 354 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap; 355 356 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid 357 /// calling llvm.stacksave for multiple VLAs in the same scope. 358 bool DidCallStackSave; 359 360 struct CleanupEntry { 361 /// CleanupEntryBlock - The block of code that does the actual cleanup. 362 llvm::BasicBlock *CleanupEntryBlock; 363 364 /// CleanupExitBlock - The cleanup exit block. 365 llvm::BasicBlock *CleanupExitBlock; 366 367 /// Blocks - Basic blocks that were emitted in the current cleanup scope. 368 std::vector<llvm::BasicBlock *> Blocks; 369 370 /// BranchFixups - Branch instructions to basic blocks that haven't been 371 /// inserted into the current function yet. 372 std::vector<llvm::BranchInst *> BranchFixups; 373 374 /// PreviousInvokeDest - The invoke handler from the start of the cleanup 375 /// region. 376 llvm::BasicBlock *PreviousInvokeDest; 377 378 /// EHOnly - Perform this only on the exceptional edge, not the main edge. 379 bool EHOnly; 380 381 explicit CleanupEntry(llvm::BasicBlock *CleanupEntryBlock, 382 llvm::BasicBlock *CleanupExitBlock, 383 llvm::BasicBlock *PreviousInvokeDest, 384 bool ehonly) 385 : CleanupEntryBlock(CleanupEntryBlock), 386 CleanupExitBlock(CleanupExitBlock), 387 PreviousInvokeDest(PreviousInvokeDest), 388 EHOnly(ehonly) {} 389 }; 390 391 /// CleanupEntries - Stack of cleanup entries. 392 llvm::SmallVector<CleanupEntry, 8> CleanupEntries; 393 394 typedef llvm::DenseMap<llvm::BasicBlock*, size_t> BlockScopeMap; 395 396 /// BlockScopes - Map of which "cleanup scope" scope basic blocks have. 397 BlockScopeMap BlockScopes; 398 399 /// CXXThisDecl - When generating code for a C++ member function, 400 /// this will hold the implicit 'this' declaration. 401 ImplicitParamDecl *CXXThisDecl; 402 llvm::Value *CXXThisValue; 403 404 /// CXXVTTDecl - When generating code for a base object constructor or 405 /// base object destructor with virtual bases, this will hold the implicit 406 /// VTT parameter. 407 ImplicitParamDecl *CXXVTTDecl; 408 llvm::Value *CXXVTTValue; 409 410 /// CXXLiveTemporaryInfo - Holds information about a live C++ temporary. 411 struct CXXLiveTemporaryInfo { 412 /// Temporary - The live temporary. 413 const CXXTemporary *Temporary; 414 415 /// ThisPtr - The pointer to the temporary. 416 llvm::Value *ThisPtr; 417 418 /// DtorBlock - The destructor block. 419 llvm::BasicBlock *DtorBlock; 420 421 /// CondPtr - If this is a conditional temporary, this is the pointer to the 422 /// condition variable that states whether the destructor should be called 423 /// or not. 424 llvm::Value *CondPtr; 425 426 CXXLiveTemporaryInfo(const CXXTemporary *temporary, 427 llvm::Value *thisptr, llvm::BasicBlock *dtorblock, 428 llvm::Value *condptr) 429 : Temporary(temporary), ThisPtr(thisptr), DtorBlock(dtorblock), 430 CondPtr(condptr) { } 431 }; 432 433 llvm::SmallVector<CXXLiveTemporaryInfo, 4> LiveTemporaries; 434 435 /// ConditionalBranchLevel - Contains the nesting level of the current 436 /// conditional branch. This is used so that we know if a temporary should be 437 /// destroyed conditionally. 438 unsigned ConditionalBranchLevel; 439 440 441 /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM 442 /// type as well as the field number that contains the actual data. 443 llvm::DenseMap<const ValueDecl *, std::pair<const llvm::Type *, 444 unsigned> > ByRefValueInfo; 445 446 /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field 447 /// number that holds the value. 448 unsigned getByRefValueLLVMField(const ValueDecl *VD) const; 449 450 llvm::BasicBlock *TerminateHandler; 451 llvm::BasicBlock *TrapBB; 452 453 int UniqueAggrDestructorCount; 454public: 455 CodeGenFunction(CodeGenModule &cgm); 456 457 ASTContext &getContext() const; 458 CGDebugInfo *getDebugInfo() { return DebugInfo; } 459 460 llvm::BasicBlock *getInvokeDest() { return InvokeDest; } 461 void setInvokeDest(llvm::BasicBlock *B) { InvokeDest = B; } 462 463 llvm::LLVMContext &getLLVMContext() { return VMContext; } 464 465 //===--------------------------------------------------------------------===// 466 // Objective-C 467 //===--------------------------------------------------------------------===// 468 469 void GenerateObjCMethod(const ObjCMethodDecl *OMD); 470 471 void StartObjCMethod(const ObjCMethodDecl *MD, 472 const ObjCContainerDecl *CD); 473 474 /// GenerateObjCGetter - Synthesize an Objective-C property getter function. 475 void GenerateObjCGetter(ObjCImplementationDecl *IMP, 476 const ObjCPropertyImplDecl *PID); 477 478 /// GenerateObjCSetter - Synthesize an Objective-C property setter function 479 /// for the given property. 480 void GenerateObjCSetter(ObjCImplementationDecl *IMP, 481 const ObjCPropertyImplDecl *PID); 482 483 //===--------------------------------------------------------------------===// 484 // Block Bits 485 //===--------------------------------------------------------------------===// 486 487 llvm::Value *BuildBlockLiteralTmp(const BlockExpr *); 488 llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *, 489 bool BlockHasCopyDispose, 490 CharUnits Size, 491 const llvm::StructType *, 492 std::vector<HelperInfo> *); 493 494 llvm::Function *GenerateBlockFunction(const BlockExpr *BExpr, 495 const BlockInfo& Info, 496 const Decl *OuterFuncDecl, 497 llvm::DenseMap<const Decl*, llvm::Value*> ldm, 498 CharUnits &Size, CharUnits &Align, 499 llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls, 500 bool &subBlockHasCopyDispose); 501 502 void BlockForwardSelf(); 503 llvm::Value *LoadBlockStruct(); 504 505 CharUnits AllocateBlockDecl(const BlockDeclRefExpr *E); 506 llvm::Value *GetAddrOfBlockDecl(const BlockDeclRefExpr *E); 507 const llvm::Type *BuildByRefType(const ValueDecl *D); 508 509 void GenerateCode(GlobalDecl GD, llvm::Function *Fn); 510 void StartFunction(GlobalDecl GD, QualType RetTy, 511 llvm::Function *Fn, 512 const FunctionArgList &Args, 513 SourceLocation StartLoc); 514 515 void EmitConstructorBody(FunctionArgList &Args); 516 void EmitDestructorBody(FunctionArgList &Args); 517 void EmitFunctionBody(FunctionArgList &Args); 518 519 /// EmitReturnBlock - Emit the unified return block, trying to avoid its 520 /// emission when possible. 521 void EmitReturnBlock(); 522 523 /// FinishFunction - Complete IR generation of the current function. It is 524 /// legal to call this function even if there is no current insertion point. 525 void FinishFunction(SourceLocation EndLoc=SourceLocation()); 526 527 /// GenerateThunk - Generate a thunk for the given method. 528 void GenerateThunk(llvm::Function *Fn, GlobalDecl GD, const ThunkInfo &Thunk); 529 530 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type); 531 532 /// InitializeVTablePointer - Initialize the vtable pointer of the given 533 /// subobject. 534 /// 535 /// \param BaseIsMorallyVirtual - Whether the base subobject is a virtual base 536 /// or a direct or indirect base of a virtual base. 537 void InitializeVTablePointer(BaseSubobject Base, bool BaseIsMorallyVirtual, 538 llvm::Constant *VTable, 539 const CXXRecordDecl *VTableClass); 540 541 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy; 542 void InitializeVTablePointers(BaseSubobject Base, bool BaseIsMorallyVirtual, 543 bool BaseIsNonVirtualPrimaryBase, 544 llvm::Constant *VTable, 545 const CXXRecordDecl *VTableClass, 546 VisitedVirtualBasesSetTy& VBases); 547 548 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl); 549 550 551 void SynthesizeCXXCopyConstructor(const FunctionArgList &Args); 552 void SynthesizeCXXCopyAssignment(const FunctionArgList &Args); 553 554 /// EmitDtorEpilogue - Emit all code that comes at the end of class's 555 /// destructor. This is to call destructors on members and base classes in 556 /// reverse order of their construction. 557 void EmitDtorEpilogue(const CXXDestructorDecl *Dtor, 558 CXXDtorType Type); 559 560 /// EmitFunctionProlog - Emit the target specific LLVM code to load the 561 /// arguments for the given function. This is also responsible for naming the 562 /// LLVM function arguments. 563 void EmitFunctionProlog(const CGFunctionInfo &FI, 564 llvm::Function *Fn, 565 const FunctionArgList &Args); 566 567 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the 568 /// given temporary. 569 void EmitFunctionEpilog(const CGFunctionInfo &FI, llvm::Value *ReturnValue); 570 571 /// EmitStartEHSpec - Emit the start of the exception spec. 572 void EmitStartEHSpec(const Decl *D); 573 574 /// EmitEndEHSpec - Emit the end of the exception spec. 575 void EmitEndEHSpec(const Decl *D); 576 577 /// getTerminateHandler - Return a handler that just calls terminate. 578 llvm::BasicBlock *getTerminateHandler(); 579 580 const llvm::Type *ConvertTypeForMem(QualType T); 581 const llvm::Type *ConvertType(QualType T); 582 const llvm::Type *ConvertType(const TypeDecl *T) { 583 return ConvertType(getContext().getTypeDeclType(T)); 584 } 585 586 /// LoadObjCSelf - Load the value of self. This function is only valid while 587 /// generating code for an Objective-C method. 588 llvm::Value *LoadObjCSelf(); 589 590 /// TypeOfSelfObject - Return type of object that this self represents. 591 QualType TypeOfSelfObject(); 592 593 /// hasAggregateLLVMType - Return true if the specified AST type will map into 594 /// an aggregate LLVM type or is void. 595 static bool hasAggregateLLVMType(QualType T); 596 597 /// createBasicBlock - Create an LLVM basic block. 598 llvm::BasicBlock *createBasicBlock(const char *Name="", 599 llvm::Function *Parent=0, 600 llvm::BasicBlock *InsertBefore=0) { 601#ifdef NDEBUG 602 return llvm::BasicBlock::Create(VMContext, "", Parent, InsertBefore); 603#else 604 return llvm::BasicBlock::Create(VMContext, Name, Parent, InsertBefore); 605#endif 606 } 607 608 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified 609 /// label maps to. 610 llvm::BasicBlock *getBasicBlockForLabel(const LabelStmt *S); 611 612 /// SimplifyForwardingBlocks - If the given basic block is only a branch to 613 /// another basic block, simplify it. This assumes that no other code could 614 /// potentially reference the basic block. 615 void SimplifyForwardingBlocks(llvm::BasicBlock *BB); 616 617 /// EmitBlock - Emit the given block \arg BB and set it as the insert point, 618 /// adding a fall-through branch from the current insert block if 619 /// necessary. It is legal to call this function even if there is no current 620 /// insertion point. 621 /// 622 /// IsFinished - If true, indicates that the caller has finished emitting 623 /// branches to the given block and does not expect to emit code into it. This 624 /// means the block can be ignored if it is unreachable. 625 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false); 626 627 /// EmitBranch - Emit a branch to the specified basic block from the current 628 /// insert block, taking care to avoid creation of branches from dummy 629 /// blocks. It is legal to call this function even if there is no current 630 /// insertion point. 631 /// 632 /// This function clears the current insertion point. The caller should follow 633 /// calls to this function with calls to Emit*Block prior to generation new 634 /// code. 635 void EmitBranch(llvm::BasicBlock *Block); 636 637 /// HaveInsertPoint - True if an insertion point is defined. If not, this 638 /// indicates that the current code being emitted is unreachable. 639 bool HaveInsertPoint() const { 640 return Builder.GetInsertBlock() != 0; 641 } 642 643 /// EnsureInsertPoint - Ensure that an insertion point is defined so that 644 /// emitted IR has a place to go. Note that by definition, if this function 645 /// creates a block then that block is unreachable; callers may do better to 646 /// detect when no insertion point is defined and simply skip IR generation. 647 void EnsureInsertPoint() { 648 if (!HaveInsertPoint()) 649 EmitBlock(createBasicBlock()); 650 } 651 652 /// ErrorUnsupported - Print out an error that codegen doesn't support the 653 /// specified stmt yet. 654 void ErrorUnsupported(const Stmt *S, const char *Type, 655 bool OmitOnError=false); 656 657 //===--------------------------------------------------------------------===// 658 // Helpers 659 //===--------------------------------------------------------------------===// 660 661 Qualifiers MakeQualifiers(QualType T) { 662 Qualifiers Quals = getContext().getCanonicalType(T).getQualifiers(); 663 Quals.setObjCGCAttr(getContext().getObjCGCAttrKind(T)); 664 return Quals; 665 } 666 667 /// CreateTempAlloca - This creates a alloca and inserts it into the entry 668 /// block. The caller is responsible for setting an appropriate alignment on 669 /// the alloca. 670 llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty, 671 const llvm::Twine &Name = "tmp"); 672 673 /// CreateIRTemp - Create a temporary IR object of the given type, with 674 /// appropriate alignment. This routine should only be used when an temporary 675 /// value needs to be stored into an alloca (for example, to avoid explicit 676 /// PHI construction), but the type is the IR type, not the type appropriate 677 /// for storing in memory. 678 llvm::Value *CreateIRTemp(QualType T, const llvm::Twine &Name = "tmp"); 679 680 /// CreateMemTemp - Create a temporary memory object of the given type, with 681 /// appropriate alignment. 682 llvm::Value *CreateMemTemp(QualType T, const llvm::Twine &Name = "tmp"); 683 684 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 685 /// expression and compare the result against zero, returning an Int1Ty value. 686 llvm::Value *EvaluateExprAsBool(const Expr *E); 687 688 /// EmitAnyExpr - Emit code to compute the specified expression which can have 689 /// any type. The result is returned as an RValue struct. If this is an 690 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where 691 /// the result should be returned. 692 /// 693 /// \param IgnoreResult - True if the resulting value isn't used. 694 RValue EmitAnyExpr(const Expr *E, llvm::Value *AggLoc = 0, 695 bool IsAggLocVolatile = false, bool IgnoreResult = false, 696 bool IsInitializer = false); 697 698 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address 699 // or the value of the expression, depending on how va_list is defined. 700 llvm::Value *EmitVAListRef(const Expr *E); 701 702 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will 703 /// always be accessible even if no aggregate location is provided. 704 RValue EmitAnyExprToTemp(const Expr *E, bool IsAggLocVolatile = false, 705 bool IsInitializer = false); 706 707 /// EmitAggregateCopy - Emit an aggrate copy. 708 /// 709 /// \param isVolatile - True iff either the source or the destination is 710 /// volatile. 711 void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr, 712 QualType EltTy, bool isVolatile=false); 713 714 void EmitAggregateClear(llvm::Value *DestPtr, QualType Ty); 715 716 /// StartBlock - Start new block named N. If insert block is a dummy block 717 /// then reuse it. 718 void StartBlock(const char *N); 719 720 /// GetAddrOfStaticLocalVar - Return the address of a static local variable. 721 llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD); 722 723 /// GetAddrOfLocalVar - Return the address of a local variable. 724 llvm::Value *GetAddrOfLocalVar(const VarDecl *VD); 725 726 /// getAccessedFieldNo - Given an encoded value and a result number, return 727 /// the input field number being accessed. 728 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts); 729 730 llvm::BlockAddress *GetAddrOfLabel(const LabelStmt *L); 731 llvm::BasicBlock *GetIndirectGotoBlock(); 732 733 /// EmitMemSetToZero - Generate code to memset a value of the given type to 0. 734 void EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty); 735 736 // EmitVAArg - Generate code to get an argument from the passed in pointer 737 // and update it accordingly. The return value is a pointer to the argument. 738 // FIXME: We should be able to get rid of this method and use the va_arg 739 // instruction in LLVM instead once it works well enough. 740 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty); 741 742 /// EmitVLASize - Generate code for any VLA size expressions that might occur 743 /// in a variably modified type. If Ty is a VLA, will return the value that 744 /// corresponds to the size in bytes of the VLA type. Will return 0 otherwise. 745 /// 746 /// This function can be called with a null (unreachable) insert point. 747 llvm::Value *EmitVLASize(QualType Ty); 748 749 // GetVLASize - Returns an LLVM value that corresponds to the size in bytes 750 // of a variable length array type. 751 llvm::Value *GetVLASize(const VariableArrayType *); 752 753 /// LoadCXXThis - Load the value of 'this'. This function is only valid while 754 /// generating code for an C++ member function. 755 llvm::Value *LoadCXXThis() { 756 assert(CXXThisValue && "no 'this' value for this function"); 757 return CXXThisValue; 758 } 759 760 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have 761 /// virtual bases. 762 llvm::Value *LoadCXXVTT() { 763 assert(CXXVTTValue && "no VTT value for this function"); 764 return CXXVTTValue; 765 } 766 767 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a 768 /// complete class down to one of its virtual bases. 769 llvm::Value *GetAddressOfBaseOfCompleteClass(llvm::Value *Value, 770 bool IsVirtual, 771 const CXXRecordDecl *Derived, 772 const CXXRecordDecl *Base); 773 774 /// GetAddressOfBaseClass - This function will add the necessary delta to the 775 /// load of 'this' and returns address of the base class. 776 llvm::Value *GetAddressOfBaseClass(llvm::Value *Value, 777 const CXXRecordDecl *ClassDecl, 778 const CXXRecordDecl *BaseClassDecl, 779 bool NullCheckValue); 780 781 llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value, 782 const CXXRecordDecl *ClassDecl, 783 const CXXRecordDecl *DerivedClassDecl, 784 bool NullCheckValue); 785 786 llvm::Value *GetVirtualBaseClassOffset(llvm::Value *This, 787 const CXXRecordDecl *ClassDecl, 788 const CXXRecordDecl *BaseClassDecl); 789 790 void EmitClassAggrMemberwiseCopy(llvm::Value *DestValue, 791 llvm::Value *SrcValue, 792 const ArrayType *Array, 793 const CXXRecordDecl *BaseClassDecl, 794 QualType Ty); 795 796 void EmitClassAggrCopyAssignment(llvm::Value *DestValue, 797 llvm::Value *SrcValue, 798 const ArrayType *Array, 799 const CXXRecordDecl *BaseClassDecl, 800 QualType Ty); 801 802 void EmitClassMemberwiseCopy(llvm::Value *DestValue, llvm::Value *SrcValue, 803 const CXXRecordDecl *ClassDecl, 804 const CXXRecordDecl *BaseClassDecl, 805 QualType Ty); 806 807 void EmitClassCopyAssignment(llvm::Value *DestValue, llvm::Value *SrcValue, 808 const CXXRecordDecl *ClassDecl, 809 const CXXRecordDecl *BaseClassDecl, 810 QualType Ty); 811 812 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, 813 CXXCtorType CtorType, 814 const FunctionArgList &Args); 815 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 816 llvm::Value *This, 817 CallExpr::const_arg_iterator ArgBeg, 818 CallExpr::const_arg_iterator ArgEnd); 819 820 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 821 const ConstantArrayType *ArrayTy, 822 llvm::Value *ArrayPtr, 823 CallExpr::const_arg_iterator ArgBeg, 824 CallExpr::const_arg_iterator ArgEnd); 825 826 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 827 llvm::Value *NumElements, 828 llvm::Value *ArrayPtr, 829 CallExpr::const_arg_iterator ArgBeg, 830 CallExpr::const_arg_iterator ArgEnd); 831 832 void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D, 833 const ArrayType *Array, 834 llvm::Value *This); 835 836 void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D, 837 llvm::Value *NumElements, 838 llvm::Value *This); 839 840 llvm::Constant *GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D, 841 const ArrayType *Array, 842 llvm::Value *This); 843 844 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, 845 llvm::Value *This); 846 847 void PushCXXTemporary(const CXXTemporary *Temporary, llvm::Value *Ptr); 848 void PopCXXTemporary(); 849 850 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E); 851 void EmitCXXDeleteExpr(const CXXDeleteExpr *E); 852 853 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr, 854 QualType DeleteTy); 855 856 llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E); 857 llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE); 858 859 void EmitCheck(llvm::Value *, unsigned Size); 860 861 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 862 bool isInc, bool isPre); 863 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, 864 bool isInc, bool isPre); 865 //===--------------------------------------------------------------------===// 866 // Declaration Emission 867 //===--------------------------------------------------------------------===// 868 869 /// EmitDecl - Emit a declaration. 870 /// 871 /// This function can be called with a null (unreachable) insert point. 872 void EmitDecl(const Decl &D); 873 874 /// EmitBlockVarDecl - Emit a block variable declaration. 875 /// 876 /// This function can be called with a null (unreachable) insert point. 877 void EmitBlockVarDecl(const VarDecl &D); 878 879 /// EmitLocalBlockVarDecl - Emit a local block variable declaration. 880 /// 881 /// This function can be called with a null (unreachable) insert point. 882 void EmitLocalBlockVarDecl(const VarDecl &D); 883 884 void EmitStaticBlockVarDecl(const VarDecl &D, 885 llvm::GlobalValue::LinkageTypes Linkage); 886 887 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl. 888 void EmitParmDecl(const VarDecl &D, llvm::Value *Arg); 889 890 //===--------------------------------------------------------------------===// 891 // Statement Emission 892 //===--------------------------------------------------------------------===// 893 894 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info. 895 void EmitStopPoint(const Stmt *S); 896 897 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call 898 /// this function even if there is no current insertion point. 899 /// 900 /// This function may clear the current insertion point; callers should use 901 /// EnsureInsertPoint if they wish to subsequently generate code without first 902 /// calling EmitBlock, EmitBranch, or EmitStmt. 903 void EmitStmt(const Stmt *S); 904 905 /// EmitSimpleStmt - Try to emit a "simple" statement which does not 906 /// necessarily require an insertion point or debug information; typically 907 /// because the statement amounts to a jump or a container of other 908 /// statements. 909 /// 910 /// \return True if the statement was handled. 911 bool EmitSimpleStmt(const Stmt *S); 912 913 RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false, 914 llvm::Value *AggLoc = 0, bool isAggVol = false); 915 916 /// EmitLabel - Emit the block for the given label. It is legal to call this 917 /// function even if there is no current insertion point. 918 void EmitLabel(const LabelStmt &S); // helper for EmitLabelStmt. 919 920 void EmitLabelStmt(const LabelStmt &S); 921 void EmitGotoStmt(const GotoStmt &S); 922 void EmitIndirectGotoStmt(const IndirectGotoStmt &S); 923 void EmitIfStmt(const IfStmt &S); 924 void EmitWhileStmt(const WhileStmt &S); 925 void EmitDoStmt(const DoStmt &S); 926 void EmitForStmt(const ForStmt &S); 927 void EmitReturnStmt(const ReturnStmt &S); 928 void EmitDeclStmt(const DeclStmt &S); 929 void EmitBreakStmt(const BreakStmt &S); 930 void EmitContinueStmt(const ContinueStmt &S); 931 void EmitSwitchStmt(const SwitchStmt &S); 932 void EmitDefaultStmt(const DefaultStmt &S); 933 void EmitCaseStmt(const CaseStmt &S); 934 void EmitCaseStmtRange(const CaseStmt &S); 935 void EmitAsmStmt(const AsmStmt &S); 936 937 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S); 938 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S); 939 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S); 940 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S); 941 942 struct CXXTryStmtInfo { 943 llvm::BasicBlock *SavedLandingPad; 944 llvm::BasicBlock *HandlerBlock; 945 llvm::BasicBlock *FinallyBlock; 946 }; 947 CXXTryStmtInfo EnterCXXTryStmt(const CXXTryStmt &S); 948 void ExitCXXTryStmt(const CXXTryStmt &S, CXXTryStmtInfo Info); 949 950 void EmitCXXTryStmt(const CXXTryStmt &S); 951 952 //===--------------------------------------------------------------------===// 953 // LValue Expression Emission 954 //===--------------------------------------------------------------------===// 955 956 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type. 957 RValue GetUndefRValue(QualType Ty); 958 959 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E 960 /// and issue an ErrorUnsupported style diagnostic (using the 961 /// provided Name). 962 RValue EmitUnsupportedRValue(const Expr *E, 963 const char *Name); 964 965 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue 966 /// an ErrorUnsupported style diagnostic (using the provided Name). 967 LValue EmitUnsupportedLValue(const Expr *E, 968 const char *Name); 969 970 /// EmitLValue - Emit code to compute a designator that specifies the location 971 /// of the expression. 972 /// 973 /// This can return one of two things: a simple address or a bitfield 974 /// reference. In either case, the LLVM Value* in the LValue structure is 975 /// guaranteed to be an LLVM pointer type. 976 /// 977 /// If this returns a bitfield reference, nothing about the pointee type of 978 /// the LLVM value is known: For example, it may not be a pointer to an 979 /// integer. 980 /// 981 /// If this returns a normal address, and if the lvalue's C type is fixed 982 /// size, this method guarantees that the returned pointer type will point to 983 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a 984 /// variable length type, this is not possible. 985 /// 986 LValue EmitLValue(const Expr *E); 987 988 /// EmitCheckedLValue - Same as EmitLValue but additionally we generate 989 /// checking code to guard against undefined behavior. This is only 990 /// suitable when we know that the address will be used to access the 991 /// object. 992 LValue EmitCheckedLValue(const Expr *E); 993 994 /// EmitLoadOfScalar - Load a scalar value from an address, taking 995 /// care to appropriately convert from the memory representation to 996 /// the LLVM value representation. 997 llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile, 998 QualType Ty); 999 1000 /// EmitStoreOfScalar - Store a scalar value to an address, taking 1001 /// care to appropriately convert from the memory representation to 1002 /// the LLVM value representation. 1003 void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr, 1004 bool Volatile, QualType Ty); 1005 1006 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, 1007 /// this method emits the address of the lvalue, then loads the result as an 1008 /// rvalue, returning the rvalue. 1009 RValue EmitLoadOfLValue(LValue V, QualType LVType); 1010 RValue EmitLoadOfExtVectorElementLValue(LValue V, QualType LVType); 1011 RValue EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType); 1012 RValue EmitLoadOfPropertyRefLValue(LValue LV, QualType ExprType); 1013 RValue EmitLoadOfKVCRefLValue(LValue LV, QualType ExprType); 1014 1015 1016 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 1017 /// lvalue, where both are guaranteed to the have the same type, and that type 1018 /// is 'Ty'. 1019 void EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty); 1020 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst, 1021 QualType Ty); 1022 void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst, QualType Ty); 1023 void EmitStoreThroughKVCRefLValue(RValue Src, LValue Dst, QualType Ty); 1024 1025 /// EmitStoreThroughLValue - Store Src into Dst with same constraints as 1026 /// EmitStoreThroughLValue. 1027 /// 1028 /// \param Result [out] - If non-null, this will be set to a Value* for the 1029 /// bit-field contents after the store, appropriate for use as the result of 1030 /// an assignment to the bit-field. 1031 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty, 1032 llvm::Value **Result=0); 1033 1034 // Note: only availabe for agg return types 1035 LValue EmitBinaryOperatorLValue(const BinaryOperator *E); 1036 // Note: only available for agg return types 1037 LValue EmitCallExprLValue(const CallExpr *E); 1038 // Note: only available for agg return types 1039 LValue EmitVAArgExprLValue(const VAArgExpr *E); 1040 LValue EmitDeclRefLValue(const DeclRefExpr *E); 1041 LValue EmitStringLiteralLValue(const StringLiteral *E); 1042 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E); 1043 LValue EmitPredefinedFunctionName(unsigned Type); 1044 LValue EmitPredefinedLValue(const PredefinedExpr *E); 1045 LValue EmitUnaryOpLValue(const UnaryOperator *E); 1046 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E); 1047 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E); 1048 LValue EmitMemberExpr(const MemberExpr *E); 1049 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E); 1050 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E); 1051 LValue EmitConditionalOperatorLValue(const ConditionalOperator *E); 1052 LValue EmitCastLValue(const CastExpr *E); 1053 LValue EmitNullInitializationLValue(const CXXZeroInitValueExpr *E); 1054 1055 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface, 1056 const ObjCIvarDecl *Ivar); 1057 LValue EmitLValueForField(llvm::Value* Base, const FieldDecl* Field, 1058 unsigned CVRQualifiers); 1059 1060 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that 1061 /// if the Field is a reference, this will return the address of the reference 1062 /// and not the address of the value stored in the reference. 1063 LValue EmitLValueForFieldInitialization(llvm::Value* Base, 1064 const FieldDecl* Field, 1065 unsigned CVRQualifiers); 1066 1067 LValue EmitLValueForIvar(QualType ObjectTy, 1068 llvm::Value* Base, const ObjCIvarDecl *Ivar, 1069 unsigned CVRQualifiers); 1070 1071 LValue EmitLValueForBitfield(llvm::Value* Base, const FieldDecl* Field, 1072 unsigned CVRQualifiers); 1073 1074 LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E); 1075 1076 LValue EmitCXXConstructLValue(const CXXConstructExpr *E); 1077 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E); 1078 LValue EmitCXXExprWithTemporariesLValue(const CXXExprWithTemporaries *E); 1079 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E); 1080 1081 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E); 1082 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E); 1083 LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E); 1084 LValue EmitObjCKVCRefLValue(const ObjCImplicitSetterGetterRefExpr *E); 1085 LValue EmitObjCSuperExprLValue(const ObjCSuperExpr *E); 1086 LValue EmitStmtExprLValue(const StmtExpr *E); 1087 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E); 1088 1089 //===--------------------------------------------------------------------===// 1090 // Scalar Expression Emission 1091 //===--------------------------------------------------------------------===// 1092 1093 /// EmitCall - Generate a call of the given function, expecting the given 1094 /// result type, and using the given argument list which specifies both the 1095 /// LLVM arguments and the types they were derived from. 1096 /// 1097 /// \param TargetDecl - If given, the decl of the function in a direct call; 1098 /// used to set attributes on the call (noreturn, etc.). 1099 RValue EmitCall(const CGFunctionInfo &FnInfo, 1100 llvm::Value *Callee, 1101 ReturnValueSlot ReturnValue, 1102 const CallArgList &Args, 1103 const Decl *TargetDecl = 0); 1104 1105 RValue EmitCall(QualType FnType, llvm::Value *Callee, 1106 ReturnValueSlot ReturnValue, 1107 CallExpr::const_arg_iterator ArgBeg, 1108 CallExpr::const_arg_iterator ArgEnd, 1109 const Decl *TargetDecl = 0); 1110 RValue EmitCallExpr(const CallExpr *E, 1111 ReturnValueSlot ReturnValue = ReturnValueSlot()); 1112 1113 llvm::Value *BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This, 1114 const llvm::Type *Ty); 1115 llvm::Value *BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type, 1116 llvm::Value *&This, const llvm::Type *Ty); 1117 1118 RValue EmitCXXMemberCall(const CXXMethodDecl *MD, 1119 llvm::Value *Callee, 1120 ReturnValueSlot ReturnValue, 1121 llvm::Value *This, 1122 llvm::Value *VTT, 1123 CallExpr::const_arg_iterator ArgBeg, 1124 CallExpr::const_arg_iterator ArgEnd); 1125 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E, 1126 ReturnValueSlot ReturnValue); 1127 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, 1128 ReturnValueSlot ReturnValue); 1129 1130 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 1131 const CXXMethodDecl *MD, 1132 ReturnValueSlot ReturnValue); 1133 1134 1135 RValue EmitBuiltinExpr(const FunctionDecl *FD, 1136 unsigned BuiltinID, const CallExpr *E); 1137 1138 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue); 1139 1140 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call 1141 /// is unhandled by the current target. 1142 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 1143 1144 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 1145 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 1146 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 1147 1148 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E); 1149 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E); 1150 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E); 1151 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E); 1152 RValue EmitObjCPropertyGet(const Expr *E); 1153 RValue EmitObjCSuperPropertyGet(const Expr *Exp, const Selector &S); 1154 void EmitObjCPropertySet(const Expr *E, RValue Src); 1155 void EmitObjCSuperPropertySet(const Expr *E, const Selector &S, RValue Src); 1156 1157 1158 /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in 1159 /// expression. Will emit a temporary variable if E is not an LValue. 1160 RValue EmitReferenceBindingToExpr(const Expr* E, bool IsInitializer = false); 1161 1162 //===--------------------------------------------------------------------===// 1163 // Expression Emission 1164 //===--------------------------------------------------------------------===// 1165 1166 // Expressions are broken into three classes: scalar, complex, aggregate. 1167 1168 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM 1169 /// scalar type, returning the result. 1170 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false); 1171 1172 /// EmitScalarConversion - Emit a conversion from the specified type to the 1173 /// specified destination type, both of which are LLVM scalar types. 1174 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy, 1175 QualType DstTy); 1176 1177 /// EmitComplexToScalarConversion - Emit a conversion from the specified 1178 /// complex type to the specified destination type, where the destination type 1179 /// is an LLVM scalar type. 1180 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, 1181 QualType DstTy); 1182 1183 1184 /// EmitAggExpr - Emit the computation of the specified expression of 1185 /// aggregate type. The result is computed into DestPtr. Note that if 1186 /// DestPtr is null, the value of the aggregate expression is not needed. 1187 void EmitAggExpr(const Expr *E, llvm::Value *DestPtr, bool VolatileDest, 1188 bool IgnoreResult = false, bool IsInitializer = false, 1189 bool RequiresGCollection = false); 1190 1191 /// EmitAggExprToLValue - Emit the computation of the specified expression of 1192 /// aggregate type into a temporary LValue. 1193 LValue EmitAggExprToLValue(const Expr *E); 1194 1195 /// EmitGCMemmoveCollectable - Emit special API for structs with object 1196 /// pointers. 1197 void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr, 1198 QualType Ty); 1199 1200 /// EmitComplexExpr - Emit the computation of the specified expression of 1201 /// complex type, returning the result. 1202 ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal = false, 1203 bool IgnoreImag = false, 1204 bool IgnoreRealAssign = false, 1205 bool IgnoreImagAssign = false); 1206 1207 /// EmitComplexExprIntoAddr - Emit the computation of the specified expression 1208 /// of complex type, storing into the specified Value*. 1209 void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr, 1210 bool DestIsVolatile); 1211 1212 /// StoreComplexToAddr - Store a complex number into the specified address. 1213 void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr, 1214 bool DestIsVolatile); 1215 /// LoadComplexFromAddr - Load a complex number from the specified address. 1216 ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile); 1217 1218 /// CreateStaticBlockVarDecl - Create a zero-initialized LLVM global for a 1219 /// static block var decl. 1220 llvm::GlobalVariable *CreateStaticBlockVarDecl(const VarDecl &D, 1221 const char *Separator, 1222 llvm::GlobalValue::LinkageTypes Linkage); 1223 1224 /// AddInitializerToGlobalBlockVarDecl - Add the initializer for 'D' to the 1225 /// global variable that has already been created for it. If the initializer 1226 /// has a different type than GV does, this may free GV and return a different 1227 /// one. Otherwise it just returns GV. 1228 llvm::GlobalVariable * 1229 AddInitializerToGlobalBlockVarDecl(const VarDecl &D, 1230 llvm::GlobalVariable *GV); 1231 1232 1233 /// EmitStaticCXXBlockVarDeclInit - Create the initializer for a C++ runtime 1234 /// initialized static block var decl. 1235 void EmitStaticCXXBlockVarDeclInit(const VarDecl &D, 1236 llvm::GlobalVariable *GV); 1237 1238 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++ 1239 /// variable with global storage. 1240 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr); 1241 1242 /// EmitCXXGlobalDtorRegistration - Emits a call to register the global ptr 1243 /// with the C++ runtime so that its destructor will be called at exit. 1244 void EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn, 1245 llvm::Constant *DeclPtr); 1246 1247 /// GenerateCXXGlobalInitFunc - Generates code for initializing global 1248 /// variables. 1249 void GenerateCXXGlobalInitFunc(llvm::Function *Fn, 1250 llvm::Constant **Decls, 1251 unsigned NumDecls); 1252 1253 /// GenerateCXXGlobalDtorFunc - Generates code for destroying global 1254 /// variables. 1255 void GenerateCXXGlobalDtorFunc(llvm::Function *Fn, 1256 const std::vector<std::pair<llvm::Constant*, 1257 llvm::Constant*> > &DtorsAndObjects); 1258 1259 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, const VarDecl *D); 1260 1261 void EmitCXXConstructExpr(llvm::Value *Dest, const CXXConstructExpr *E); 1262 1263 RValue EmitCXXExprWithTemporaries(const CXXExprWithTemporaries *E, 1264 llvm::Value *AggLoc = 0, 1265 bool IsAggLocVolatile = false, 1266 bool IsInitializer = false); 1267 1268 void EmitCXXThrowExpr(const CXXThrowExpr *E); 1269 1270 //===--------------------------------------------------------------------===// 1271 // Internal Helpers 1272 //===--------------------------------------------------------------------===// 1273 1274 /// ContainsLabel - Return true if the statement contains a label in it. If 1275 /// this statement is not executed normally, it not containing a label means 1276 /// that we can just remove the code. 1277 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false); 1278 1279 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 1280 /// to a constant, or if it does but contains a label, return 0. If it 1281 /// constant folds to 'true' and does not contain a label, return 1, if it 1282 /// constant folds to 'false' and does not contain a label, return -1. 1283 int ConstantFoldsToSimpleInteger(const Expr *Cond); 1284 1285 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an 1286 /// if statement) to the specified blocks. Based on the condition, this might 1287 /// try to simplify the codegen of the conditional based on the branch. 1288 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, 1289 llvm::BasicBlock *FalseBlock); 1290 1291 /// getTrapBB - Create a basic block that will call the trap intrinsic. We'll 1292 /// generate a branch around the created basic block as necessary. 1293 llvm::BasicBlock* getTrapBB(); 1294 1295 /// EmitCallArg - Emit a single call argument. 1296 RValue EmitCallArg(const Expr *E, QualType ArgType); 1297 1298private: 1299 1300 void EmitReturnOfRValue(RValue RV, QualType Ty); 1301 1302 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty 1303 /// from function arguments into \arg Dst. See ABIArgInfo::Expand. 1304 /// 1305 /// \param AI - The first function argument of the expansion. 1306 /// \return The argument following the last expanded function 1307 /// argument. 1308 llvm::Function::arg_iterator 1309 ExpandTypeFromArgs(QualType Ty, LValue Dst, 1310 llvm::Function::arg_iterator AI); 1311 1312 /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg 1313 /// Ty, into individual arguments on the provided vector \arg Args. See 1314 /// ABIArgInfo::Expand. 1315 void ExpandTypeToArgs(QualType Ty, RValue Src, 1316 llvm::SmallVector<llvm::Value*, 16> &Args); 1317 1318 llvm::Value* EmitAsmInput(const AsmStmt &S, 1319 const TargetInfo::ConstraintInfo &Info, 1320 const Expr *InputExpr, std::string &ConstraintStr); 1321 1322 /// EmitCleanupBlock - emits a single cleanup block. 1323 void EmitCleanupBlock(); 1324 1325 /// AddBranchFixup - adds a branch instruction to the list of fixups for the 1326 /// current cleanup scope. 1327 void AddBranchFixup(llvm::BranchInst *BI); 1328 1329 /// EmitCallArgs - Emit call arguments for a function. 1330 /// The CallArgTypeInfo parameter is used for iterating over the known 1331 /// argument types of the function being called. 1332 template<typename T> 1333 void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo, 1334 CallExpr::const_arg_iterator ArgBeg, 1335 CallExpr::const_arg_iterator ArgEnd) { 1336 CallExpr::const_arg_iterator Arg = ArgBeg; 1337 1338 // First, use the argument types that the type info knows about 1339 if (CallArgTypeInfo) { 1340 for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(), 1341 E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) { 1342 assert(Arg != ArgEnd && "Running over edge of argument list!"); 1343 QualType ArgType = *I; 1344 1345 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()). 1346 getTypePtr() == 1347 getContext().getCanonicalType(Arg->getType()).getTypePtr() && 1348 "type mismatch in call argument!"); 1349 1350 Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType), 1351 ArgType)); 1352 } 1353 1354 // Either we've emitted all the call args, or we have a call to a 1355 // variadic function. 1356 assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) && 1357 "Extra arguments in non-variadic function!"); 1358 1359 } 1360 1361 // If we still have any arguments, emit them using the type of the argument. 1362 for (; Arg != ArgEnd; ++Arg) { 1363 QualType ArgType = Arg->getType(); 1364 Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType), 1365 ArgType)); 1366 } 1367 } 1368 1369 const TargetCodeGenInfo &getTargetHooks() const { 1370 return CGM.getTargetCodeGenInfo(); 1371 } 1372}; 1373 1374 1375} // end namespace CodeGen 1376} // end namespace clang 1377 1378#endif 1379