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