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