CodeGenFunction.h revision 7267c1693abe7875b0c57268be05005ae013c6c9
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 "CGBlocks.h" 26#include "CGBuilder.h" 27#include "CGCall.h" 28#include "CGCXX.h" 29#include "CGValue.h" 30 31namespace llvm { 32 class BasicBlock; 33 class Module; 34 class SwitchInst; 35 class Value; 36} 37 38namespace clang { 39 class ASTContext; 40 class CXXDestructorDecl; 41 class Decl; 42 class EnumConstantDecl; 43 class FunctionDecl; 44 class FunctionProtoType; 45 class LabelStmt; 46 class ObjCContainerDecl; 47 class ObjCInterfaceDecl; 48 class ObjCIvarDecl; 49 class ObjCMethodDecl; 50 class ObjCImplementationDecl; 51 class ObjCPropertyImplDecl; 52 class TargetInfo; 53 class VarDecl; 54 class ObjCForCollectionStmt; 55 class ObjCAtTryStmt; 56 class ObjCAtThrowStmt; 57 class ObjCAtSynchronizedStmt; 58 59namespace CodeGen { 60 class CodeGenModule; 61 class CodeGenTypes; 62 class CGDebugInfo; 63 class CGFunctionInfo; 64 class CGRecordLayout; 65 66/// CodeGenFunction - This class organizes the per-function state that is used 67/// while generating LLVM code. 68class CodeGenFunction : public BlockFunction { 69 CodeGenFunction(const CodeGenFunction&); // DO NOT IMPLEMENT 70 void operator=(const CodeGenFunction&); // DO NOT IMPLEMENT 71public: 72 CodeGenModule &CGM; // Per-module state. 73 TargetInfo &Target; 74 75 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy; 76 CGBuilderTy Builder; 77 78 /// CurFuncDecl - Holds the Decl for the current function or ObjC method. 79 /// This excludes BlockDecls. 80 const Decl *CurFuncDecl; 81 /// CurCodeDecl - This is the inner-most code context, which includes blocks. 82 const Decl *CurCodeDecl; 83 const CGFunctionInfo *CurFnInfo; 84 QualType FnRetTy; 85 llvm::Function *CurFn; 86 87 /// ReturnBlock - Unified return block. 88 llvm::BasicBlock *ReturnBlock; 89 /// ReturnValue - The temporary alloca to hold the return value. This is null 90 /// iff the function has no return value. 91 llvm::Instruction *ReturnValue; 92 93 /// AllocaInsertPoint - This is an instruction in the entry block before which 94 /// we prefer to insert allocas. 95 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt; 96 97 const llvm::Type *LLVMIntTy; 98 uint32_t LLVMPointerWidth; 99 100public: 101 /// ObjCEHValueStack - Stack of Objective-C exception values, used for 102 /// rethrows. 103 llvm::SmallVector<llvm::Value*, 8> ObjCEHValueStack; 104 105 /// PushCleanupBlock - Push a new cleanup entry on the stack and set the 106 /// passed in block as the cleanup block. 107 void PushCleanupBlock(llvm::BasicBlock *CleanupBlock); 108 109 /// CleanupBlockInfo - A struct representing a popped cleanup block. 110 struct CleanupBlockInfo { 111 /// CleanupBlock - the cleanup block 112 llvm::BasicBlock *CleanupBlock; 113 114 /// SwitchBlock - the block (if any) containing the switch instruction used 115 /// for jumping to the final destination. 116 llvm::BasicBlock *SwitchBlock; 117 118 /// EndBlock - the default destination for the switch instruction. 119 llvm::BasicBlock *EndBlock; 120 121 CleanupBlockInfo(llvm::BasicBlock *cb, llvm::BasicBlock *sb, 122 llvm::BasicBlock *eb) 123 : CleanupBlock(cb), SwitchBlock(sb), EndBlock(eb) {} 124 }; 125 126 /// PopCleanupBlock - Will pop the cleanup entry on the stack, process all 127 /// branch fixups and return a block info struct with the switch block and end 128 /// block. 129 CleanupBlockInfo PopCleanupBlock(); 130 131 /// CleanupScope - RAII object that will create a cleanup block and set the 132 /// insert point to that block. When destructed, it sets the insert point to 133 /// the previous block and pushes a new cleanup entry on the stack. 134 class CleanupScope { 135 CodeGenFunction& CGF; 136 llvm::BasicBlock *CurBB; 137 llvm::BasicBlock *CleanupBB; 138 139 public: 140 CleanupScope(CodeGenFunction &cgf) 141 : CGF(cgf), CurBB(CGF.Builder.GetInsertBlock()) { 142 CleanupBB = CGF.createBasicBlock("cleanup"); 143 CGF.Builder.SetInsertPoint(CleanupBB); 144 } 145 146 ~CleanupScope() { 147 CGF.PushCleanupBlock(CleanupBB); 148 CGF.Builder.SetInsertPoint(CurBB); 149 } 150 }; 151 152 /// EmitCleanupBlocks - Takes the old cleanup stack size and emits the cleanup 153 /// blocks that have been added. 154 void EmitCleanupBlocks(size_t OldCleanupStackSize); 155 156 /// EmitBranchThroughCleanup - Emit a branch from the current insert block 157 /// through the cleanup handling code (if any) and then on to \arg Dest. 158 /// 159 /// FIXME: Maybe this should really be in EmitBranch? Don't we always want 160 /// this behavior for branches? 161 void EmitBranchThroughCleanup(llvm::BasicBlock *Dest); 162 163private: 164 CGDebugInfo* DebugInfo; 165 166 /// LabelIDs - Track arbitrary ids assigned to labels for use in implementing 167 /// the GCC address-of-label extension and indirect goto. IDs are assigned to 168 /// labels inside getIDForAddrOfLabel(). 169 std::map<const LabelStmt*, unsigned> LabelIDs; 170 171 /// IndirectSwitches - Record the list of switches for indirect 172 /// gotos. Emission of the actual switching code needs to be delayed until all 173 /// AddrLabelExprs have been seen. 174 std::vector<llvm::SwitchInst*> IndirectSwitches; 175 176 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C 177 /// decls. 178 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap; 179 180 /// LabelMap - This keeps track of the LLVM basic block for each C label. 181 llvm::DenseMap<const LabelStmt*, llvm::BasicBlock*> LabelMap; 182 183 // BreakContinueStack - This keeps track of where break and continue 184 // statements should jump to. 185 struct BreakContinue { 186 BreakContinue(llvm::BasicBlock *bb, llvm::BasicBlock *cb) 187 : BreakBlock(bb), ContinueBlock(cb) {} 188 189 llvm::BasicBlock *BreakBlock; 190 llvm::BasicBlock *ContinueBlock; 191 }; 192 llvm::SmallVector<BreakContinue, 8> BreakContinueStack; 193 194 /// SwitchInsn - This is nearest current switch instruction. It is null if if 195 /// current context is not in a switch. 196 llvm::SwitchInst *SwitchInsn; 197 198 /// CaseRangeBlock - This block holds if condition check for last case 199 /// statement range in current switch instruction. 200 llvm::BasicBlock *CaseRangeBlock; 201 202 /// InvokeDest - This is the nearest exception target for calls 203 /// which can unwind, when exceptions are being used. 204 llvm::BasicBlock *InvokeDest; 205 206 // VLASizeMap - This keeps track of the associated size for each VLA type. 207 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we 208 // enter/leave scopes. 209 llvm::DenseMap<const VariableArrayType*, llvm::Value*> VLASizeMap; 210 211 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid 212 /// calling llvm.stacksave for multiple VLAs in the same scope. 213 bool DidCallStackSave; 214 215 struct CleanupEntry { 216 /// CleanupBlock - The block of code that does the actual cleanup. 217 llvm::BasicBlock *CleanupBlock; 218 219 /// Blocks - Basic blocks that were emitted in the current cleanup scope. 220 std::vector<llvm::BasicBlock *> Blocks; 221 222 /// BranchFixups - Branch instructions to basic blocks that haven't been 223 /// inserted into the current function yet. 224 std::vector<llvm::BranchInst *> BranchFixups; 225 226 explicit CleanupEntry(llvm::BasicBlock *cb) 227 : CleanupBlock(cb) {} 228 }; 229 230 /// CleanupEntries - Stack of cleanup entries. 231 llvm::SmallVector<CleanupEntry, 8> CleanupEntries; 232 233 typedef llvm::DenseMap<llvm::BasicBlock*, size_t> BlockScopeMap; 234 235 /// BlockScopes - Map of which "cleanup scope" scope basic blocks have. 236 BlockScopeMap BlockScopes; 237 238 /// CXXThisDecl - When parsing an C++ function, this will hold the implicit 239 /// 'this' declaration. 240 ImplicitParamDecl *CXXThisDecl; 241 242public: 243 CodeGenFunction(CodeGenModule &cgm); 244 245 ASTContext &getContext() const; 246 CGDebugInfo *getDebugInfo() { return DebugInfo; } 247 248 llvm::BasicBlock *getInvokeDest() { return InvokeDest; } 249 void setInvokeDest(llvm::BasicBlock *B) { InvokeDest = B; } 250 251 //===--------------------------------------------------------------------===// 252 // Objective-C 253 //===--------------------------------------------------------------------===// 254 255 void GenerateObjCMethod(const ObjCMethodDecl *OMD); 256 257 void StartObjCMethod(const ObjCMethodDecl *MD, 258 const ObjCContainerDecl *CD); 259 260 /// GenerateObjCGetter - Synthesize an Objective-C property getter function. 261 void GenerateObjCGetter(ObjCImplementationDecl *IMP, 262 const ObjCPropertyImplDecl *PID); 263 264 /// GenerateObjCSetter - Synthesize an Objective-C property setter function 265 /// for the given property. 266 void GenerateObjCSetter(ObjCImplementationDecl *IMP, 267 const ObjCPropertyImplDecl *PID); 268 269 //===--------------------------------------------------------------------===// 270 // Block Bits 271 //===--------------------------------------------------------------------===// 272 273 llvm::Value *BuildBlockLiteralTmp(const BlockExpr *); 274 llvm::Constant *BuildDescriptorBlockDecl(bool BlockHasCopyDispose, 275 uint64_t Size, 276 const llvm::StructType *, 277 std::vector<HelperInfo> *); 278 279 llvm::Function *GenerateBlockFunction(const BlockExpr *BExpr, 280 const BlockInfo& Info, 281 const Decl *OuterFuncDecl, 282 llvm::DenseMap<const Decl*, llvm::Value*> ldm, 283 uint64_t &Size, uint64_t &Align, 284 llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls, 285 bool &subBlockHasCopyDispose); 286 287 void BlockForwardSelf(); 288 llvm::Value *LoadBlockStruct(); 289 290 llvm::Value *GetAddrOfBlockDecl(const BlockDeclRefExpr *E); 291 292 const llvm::Type *BuildByRefType(QualType Ty, uint64_t Align); 293 294 void GenerateCode(const FunctionDecl *FD, 295 llvm::Function *Fn); 296 void StartFunction(const Decl *D, QualType RetTy, 297 llvm::Function *Fn, 298 const FunctionArgList &Args, 299 SourceLocation StartLoc); 300 301 /// EmitReturnBlock - Emit the unified return block, trying to avoid its 302 /// emission when possible. 303 void EmitReturnBlock(); 304 305 /// FinishFunction - Complete IR generation of the current function. It is 306 /// legal to call this function even if there is no current insertion point. 307 void FinishFunction(SourceLocation EndLoc=SourceLocation()); 308 309 /// EmitFunctionProlog - Emit the target specific LLVM code to load the 310 /// arguments for the given function. This is also responsible for naming the 311 /// LLVM function arguments. 312 void EmitFunctionProlog(const CGFunctionInfo &FI, 313 llvm::Function *Fn, 314 const FunctionArgList &Args); 315 316 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the 317 /// given temporary. 318 void EmitFunctionEpilog(const CGFunctionInfo &FI, llvm::Value *ReturnValue); 319 320 const llvm::Type *ConvertTypeForMem(QualType T); 321 const llvm::Type *ConvertType(QualType T); 322 323 /// LoadObjCSelf - Load the value of self. This function is only valid while 324 /// generating code for an Objective-C method. 325 llvm::Value *LoadObjCSelf(); 326 327 /// TypeOfSelfObject - Return type of object that this self represents. 328 QualType TypeOfSelfObject(); 329 330 /// hasAggregateLLVMType - Return true if the specified AST type will map into 331 /// an aggregate LLVM type or is void. 332 static bool hasAggregateLLVMType(QualType T); 333 334 /// createBasicBlock - Create an LLVM basic block. 335 llvm::BasicBlock *createBasicBlock(const char *Name="", 336 llvm::Function *Parent=0, 337 llvm::BasicBlock *InsertBefore=0) { 338#ifdef NDEBUG 339 return llvm::BasicBlock::Create("", Parent, InsertBefore); 340#else 341 return llvm::BasicBlock::Create(Name, Parent, InsertBefore); 342#endif 343 } 344 345 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified 346 /// label maps to. 347 llvm::BasicBlock *getBasicBlockForLabel(const LabelStmt *S); 348 349 /// SimplifyForwardingBlocks - If the given basic block is only a 350 /// branch to another basic block, simplify it. This assumes that no 351 /// other code could potentially reference the basic block. 352 void SimplifyForwardingBlocks(llvm::BasicBlock *BB); 353 354 /// EmitBlock - Emit the given block \arg BB and set it as the insert point, 355 /// adding a fall-through branch from the current insert block if 356 /// necessary. It is legal to call this function even if there is no current 357 /// insertion point. 358 /// 359 /// IsFinished - If true, indicates that the caller has finished emitting 360 /// branches to the given block and does not expect to emit code into it. This 361 /// means the block can be ignored if it is unreachable. 362 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false); 363 364 /// EmitBranch - Emit a branch to the specified basic block from the current 365 /// insert block, taking care to avoid creation of branches from dummy 366 /// blocks. It is legal to call this function even if there is no current 367 /// insertion point. 368 /// 369 /// This function clears the current insertion point. The caller should follow 370 /// calls to this function with calls to Emit*Block prior to generation new 371 /// code. 372 void EmitBranch(llvm::BasicBlock *Block); 373 374 /// HaveInsertPoint - True if an insertion point is defined. If not, this 375 /// indicates that the current code being emitted is unreachable. 376 bool HaveInsertPoint() const { 377 return Builder.GetInsertBlock() != 0; 378 } 379 380 /// EnsureInsertPoint - Ensure that an insertion point is defined so that 381 /// emitted IR has a place to go. Note that by definition, if this function 382 /// creates a block then that block is unreachable; callers may do better to 383 /// detect when no insertion point is defined and simply skip IR generation. 384 void EnsureInsertPoint() { 385 if (!HaveInsertPoint()) 386 EmitBlock(createBasicBlock()); 387 } 388 389 /// ErrorUnsupported - Print out an error that codegen doesn't support the 390 /// specified stmt yet. 391 void ErrorUnsupported(const Stmt *S, const char *Type, 392 bool OmitOnError=false); 393 394 //===--------------------------------------------------------------------===// 395 // Helpers 396 //===--------------------------------------------------------------------===// 397 398 /// CreateTempAlloca - This creates a alloca and inserts it into the entry 399 /// block. 400 llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty, 401 const char *Name = "tmp"); 402 403 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 404 /// expression and compare the result against zero, returning an Int1Ty value. 405 llvm::Value *EvaluateExprAsBool(const Expr *E); 406 407 /// EmitAnyExpr - Emit code to compute the specified expression which can have 408 /// any type. The result is returned as an RValue struct. If this is an 409 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where 410 /// the result should be returned. 411 /// 412 /// \param IgnoreResult - True if the resulting value isn't used. 413 RValue EmitAnyExpr(const Expr *E, llvm::Value *AggLoc = 0, 414 bool isAggLocVolatile = false, bool IgnoreResult = false); 415 416 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address 417 // or the value of the expression, depending on how va_list is defined. 418 llvm::Value *EmitVAListRef(const Expr *E); 419 420 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will 421 /// always be accessible even if no aggregate location is provided. 422 RValue EmitAnyExprToTemp(const Expr *E, llvm::Value *AggLoc = 0, 423 bool isAggLocVolatile = false); 424 425 /// EmitAggregateCopy - Emit an aggrate copy. 426 /// 427 /// \param isVolatile - True iff either the source or the destination is 428 /// volatile. 429 void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr, 430 QualType EltTy, bool isVolatile=false); 431 432 void EmitAggregateClear(llvm::Value *DestPtr, QualType Ty); 433 434 /// StartBlock - Start new block named N. If insert block is a dummy block 435 /// then reuse it. 436 void StartBlock(const char *N); 437 438 /// getCGRecordLayout - Return record layout info. 439 const CGRecordLayout *getCGRecordLayout(CodeGenTypes &CGT, QualType RTy); 440 441 /// GetAddrOfStaticLocalVar - Return the address of a static local variable. 442 llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD); 443 444 /// GetAddrOfLocalVar - Return the address of a local variable. 445 llvm::Value *GetAddrOfLocalVar(const VarDecl *VD); 446 447 /// getAccessedFieldNo - Given an encoded value and a result number, return 448 /// the input field number being accessed. 449 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts); 450 451 unsigned GetIDForAddrOfLabel(const LabelStmt *L); 452 453 /// EmitMemSetToZero - Generate code to memset a value of the given type to 0. 454 void EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty); 455 456 // EmitVAArg - Generate code to get an argument from the passed in pointer 457 // and update it accordingly. The return value is a pointer to the argument. 458 // FIXME: We should be able to get rid of this method and use the va_arg 459 // instruction in LLVM instead once it works well enough. 460 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty); 461 462 // EmitVLASize - Generate code for any VLA size expressions that might occur 463 // in a variably modified type. If Ty is a VLA, will return the value that 464 // corresponds to the size in bytes of the VLA type. Will return 0 otherwise. 465 llvm::Value *EmitVLASize(QualType Ty); 466 467 // GetVLASize - Returns an LLVM value that corresponds to the size in bytes 468 // of a variable length array type. 469 llvm::Value *GetVLASize(const VariableArrayType *); 470 471 /// LoadCXXThis - Load the value of 'this'. This function is only valid while 472 /// generating code for an C++ member function. 473 llvm::Value *LoadCXXThis(); 474 475 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 476 llvm::Value *This, 477 CallExpr::const_arg_iterator ArgBeg, 478 CallExpr::const_arg_iterator ArgEnd); 479 480 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, 481 llvm::Value *This); 482 483 //===--------------------------------------------------------------------===// 484 // Declaration Emission 485 //===--------------------------------------------------------------------===// 486 487 void EmitDecl(const Decl &D); 488 void EmitBlockVarDecl(const VarDecl &D); 489 void EmitLocalBlockVarDecl(const VarDecl &D); 490 void EmitStaticBlockVarDecl(const VarDecl &D); 491 492 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl. 493 void EmitParmDecl(const VarDecl &D, llvm::Value *Arg); 494 495 //===--------------------------------------------------------------------===// 496 // Statement Emission 497 //===--------------------------------------------------------------------===// 498 499 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info. 500 void EmitStopPoint(const Stmt *S); 501 502 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call 503 /// this function even if there is no current insertion point. 504 /// 505 /// This function may clear the current insertion point; callers should use 506 /// EnsureInsertPoint if they wish to subsequently generate code without first 507 /// calling EmitBlock, EmitBranch, or EmitStmt. 508 void EmitStmt(const Stmt *S); 509 510 /// EmitSimpleStmt - Try to emit a "simple" statement which does not 511 /// necessarily require an insertion point or debug information; typically 512 /// because the statement amounts to a jump or a container of other 513 /// statements. 514 /// 515 /// \return True if the statement was handled. 516 bool EmitSimpleStmt(const Stmt *S); 517 518 RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false, 519 llvm::Value *AggLoc = 0, bool isAggVol = false); 520 521 /// EmitLabel - Emit the block for the given label. It is legal to call this 522 /// function even if there is no current insertion point. 523 void EmitLabel(const LabelStmt &S); // helper for EmitLabelStmt. 524 525 void EmitLabelStmt(const LabelStmt &S); 526 void EmitGotoStmt(const GotoStmt &S); 527 void EmitIndirectGotoStmt(const IndirectGotoStmt &S); 528 void EmitIfStmt(const IfStmt &S); 529 void EmitWhileStmt(const WhileStmt &S); 530 void EmitDoStmt(const DoStmt &S); 531 void EmitForStmt(const ForStmt &S); 532 void EmitReturnStmt(const ReturnStmt &S); 533 void EmitDeclStmt(const DeclStmt &S); 534 void EmitBreakStmt(const BreakStmt &S); 535 void EmitContinueStmt(const ContinueStmt &S); 536 void EmitSwitchStmt(const SwitchStmt &S); 537 void EmitDefaultStmt(const DefaultStmt &S); 538 void EmitCaseStmt(const CaseStmt &S); 539 void EmitCaseStmtRange(const CaseStmt &S); 540 void EmitAsmStmt(const AsmStmt &S); 541 542 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S); 543 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S); 544 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S); 545 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S); 546 547 //===--------------------------------------------------------------------===// 548 // LValue Expression Emission 549 //===--------------------------------------------------------------------===// 550 551 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type. 552 RValue GetUndefRValue(QualType Ty); 553 554 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E 555 /// and issue an ErrorUnsupported style diagnostic (using the 556 /// provided Name). 557 RValue EmitUnsupportedRValue(const Expr *E, 558 const char *Name); 559 560 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue 561 /// an ErrorUnsupported style diagnostic (using the provided Name). 562 LValue EmitUnsupportedLValue(const Expr *E, 563 const char *Name); 564 565 /// EmitLValue - Emit code to compute a designator that specifies the location 566 /// of the expression. 567 /// 568 /// This can return one of two things: a simple address or a bitfield 569 /// reference. In either case, the LLVM Value* in the LValue structure is 570 /// guaranteed to be an LLVM pointer type. 571 /// 572 /// If this returns a bitfield reference, nothing about the pointee type of 573 /// the LLVM value is known: For example, it may not be a pointer to an 574 /// integer. 575 /// 576 /// If this returns a normal address, and if the lvalue's C type is fixed 577 /// size, this method guarantees that the returned pointer type will point to 578 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a 579 /// variable length type, this is not possible. 580 /// 581 LValue EmitLValue(const Expr *E); 582 583 /// EmitLoadOfScalar - Load a scalar value from an address, taking 584 /// care to appropriately convert from the memory representation to 585 /// the LLVM value representation. 586 llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile, 587 QualType Ty); 588 589 /// EmitStoreOfScalar - Store a scalar value to an address, taking 590 /// care to appropriately convert from the memory representation to 591 /// the LLVM value representation. 592 void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr, 593 bool Volatile, QualType Ty); 594 595 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, 596 /// this method emits the address of the lvalue, then loads the result as an 597 /// rvalue, returning the rvalue. 598 RValue EmitLoadOfLValue(LValue V, QualType LVType); 599 RValue EmitLoadOfExtVectorElementLValue(LValue V, QualType LVType); 600 RValue EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType); 601 RValue EmitLoadOfPropertyRefLValue(LValue LV, QualType ExprType); 602 RValue EmitLoadOfKVCRefLValue(LValue LV, QualType ExprType); 603 604 605 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 606 /// lvalue, where both are guaranteed to the have the same type, and that type 607 /// is 'Ty'. 608 void EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty); 609 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst, 610 QualType Ty); 611 void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst, QualType Ty); 612 void EmitStoreThroughKVCRefLValue(RValue Src, LValue Dst, QualType Ty); 613 614 /// EmitStoreThroughLValue - Store Src into Dst with same constraints as 615 /// EmitStoreThroughLValue. 616 /// 617 /// \param Result [out] - If non-null, this will be set to a Value* for the 618 /// bit-field contents after the store, appropriate for use as the result of 619 /// an assignment to the bit-field. 620 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty, 621 llvm::Value **Result=0); 622 623 // Note: only availabe for agg return types 624 LValue EmitBinaryOperatorLValue(const BinaryOperator *E); 625 // Note: only available for agg return types 626 LValue EmitCallExprLValue(const CallExpr *E); 627 // Note: only available for agg return types 628 LValue EmitVAArgExprLValue(const VAArgExpr *E); 629 LValue EmitDeclRefLValue(const DeclRefExpr *E); 630 LValue EmitStringLiteralLValue(const StringLiteral *E); 631 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E); 632 LValue EmitPredefinedFunctionName(unsigned Type); 633 LValue EmitPredefinedLValue(const PredefinedExpr *E); 634 LValue EmitUnaryOpLValue(const UnaryOperator *E); 635 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E); 636 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E); 637 LValue EmitMemberExpr(const MemberExpr *E); 638 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E); 639 LValue EmitConditionalOperator(const ConditionalOperator *E); 640 LValue EmitCastLValue(const CastExpr *E); 641 642 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface, 643 const ObjCIvarDecl *Ivar); 644 LValue EmitLValueForField(llvm::Value* Base, FieldDecl* Field, 645 bool isUnion, unsigned CVRQualifiers); 646 LValue EmitLValueForIvar(QualType ObjectTy, 647 llvm::Value* Base, const ObjCIvarDecl *Ivar, 648 unsigned CVRQualifiers); 649 650 LValue EmitLValueForBitfield(llvm::Value* Base, FieldDecl* Field, 651 unsigned CVRQualifiers); 652 653 LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E); 654 655 LValue EmitCXXConditionDeclLValue(const CXXConditionDeclExpr *E); 656 657 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E); 658 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E); 659 LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E); 660 LValue EmitObjCKVCRefLValue(const ObjCKVCRefExpr *E); 661 LValue EmitObjCSuperExprLValue(const ObjCSuperExpr *E); 662 LValue EmitStmtExprLValue(const StmtExpr *E); 663 664 //===--------------------------------------------------------------------===// 665 // Scalar Expression Emission 666 //===--------------------------------------------------------------------===// 667 668 /// EmitCall - Generate a call of the given function, expecting the given 669 /// result type, and using the given argument list which specifies both the 670 /// LLVM arguments and the types they were derived from. 671 /// 672 /// \param TargetDecl - If given, the decl of the function in a 673 /// direct call; used to set attributes on the call (noreturn, 674 /// etc.). 675 RValue EmitCall(const CGFunctionInfo &FnInfo, 676 llvm::Value *Callee, 677 const CallArgList &Args, 678 const Decl *TargetDecl = 0); 679 680 RValue EmitCall(llvm::Value *Callee, QualType FnType, 681 CallExpr::const_arg_iterator ArgBeg, 682 CallExpr::const_arg_iterator ArgEnd, 683 const Decl *TargetDecl = 0); 684 RValue EmitCallExpr(const CallExpr *E); 685 686 RValue EmitCXXMemberCall(const CXXMethodDecl *MD, 687 llvm::Value *Callee, 688 llvm::Value *This, 689 CallExpr::const_arg_iterator ArgBeg, 690 CallExpr::const_arg_iterator ArgEnd); 691 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E); 692 693 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 694 const CXXMethodDecl *MD); 695 696 RValue EmitBuiltinExpr(const FunctionDecl *FD, 697 unsigned BuiltinID, const CallExpr *E); 698 699 RValue EmitBlockCallExpr(const CallExpr *E); 700 701 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call 702 /// is unhandled by the current target. 703 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 704 705 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 706 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 707 708 llvm::Value *EmitShuffleVector(llvm::Value* V1, llvm::Value *V2, ...); 709 llvm::Value *EmitVector(llvm::Value * const *Vals, unsigned NumVals, 710 bool isSplat = false); 711 712 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E); 713 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E); 714 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E); 715 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E); 716 RValue EmitObjCPropertyGet(const Expr *E); 717 RValue EmitObjCSuperPropertyGet(const Expr *Exp, const Selector &S); 718 void EmitObjCPropertySet(const Expr *E, RValue Src); 719 void EmitObjCSuperPropertySet(const Expr *E, const Selector &S, RValue Src); 720 721 722 /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in 723 /// expression. Will emit a temporary variable if E is not an LValue. 724 RValue EmitReferenceBindingToExpr(const Expr* E, QualType DestType); 725 726 //===--------------------------------------------------------------------===// 727 // Expression Emission 728 //===--------------------------------------------------------------------===// 729 730 // Expressions are broken into three classes: scalar, complex, aggregate. 731 732 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM 733 /// scalar type, returning the result. 734 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign=false); 735 736 /// EmitScalarConversion - Emit a conversion from the specified type to the 737 /// specified destination type, both of which are LLVM scalar types. 738 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy, 739 QualType DstTy); 740 741 /// EmitComplexToScalarConversion - Emit a conversion from the specified 742 /// complex type to the specified destination type, where the destination type 743 /// is an LLVM scalar type. 744 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, 745 QualType DstTy); 746 747 748 /// EmitAggExpr - Emit the computation of the specified expression of 749 /// aggregate type. The result is computed into DestPtr. Note that if 750 /// DestPtr is null, the value of the aggregate expression is not needed. 751 void EmitAggExpr(const Expr *E, llvm::Value *DestPtr, bool VolatileDest, 752 bool IgnoreResult = false); 753 754 /// EmitComplexExpr - Emit the computation of the specified expression of 755 /// complex type, returning the result. 756 ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal = false, 757 bool IgnoreImag = false, 758 bool IgnoreRealAssign = false, 759 bool IgnoreImagAssign = false); 760 761 /// EmitComplexExprIntoAddr - Emit the computation of the specified expression 762 /// of complex type, storing into the specified Value*. 763 void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr, 764 bool DestIsVolatile); 765 766 /// StoreComplexToAddr - Store a complex number into the specified address. 767 void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr, 768 bool DestIsVolatile); 769 /// LoadComplexFromAddr - Load a complex number from the specified address. 770 ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile); 771 772 /// CreateStaticBlockVarDecl - Create a zero-initialized LLVM global 773 /// for a static block var decl. 774 llvm::GlobalVariable * CreateStaticBlockVarDecl(const VarDecl &D, 775 const char *Separator, 776 llvm::GlobalValue::LinkageTypes 777 Linkage); 778 779 /// GenerateStaticCXXBlockVarDecl - Create the initializer for a C++ 780 /// runtime initialized static block var decl. 781 void GenerateStaticCXXBlockVarDeclInit(const VarDecl &D, 782 llvm::GlobalVariable *GV); 783 784 void EmitCXXConstructExpr(llvm::Value *Dest, const CXXConstructExpr *E); 785 786 //===--------------------------------------------------------------------===// 787 // Internal Helpers 788 //===--------------------------------------------------------------------===// 789 790 /// ContainsLabel - Return true if the statement contains a label in it. If 791 /// this statement is not executed normally, it not containing a label means 792 /// that we can just remove the code. 793 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false); 794 795 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 796 /// to a constant, or if it does but contains a label, return 0. If it 797 /// constant folds to 'true' and does not contain a label, return 1, if it 798 /// constant folds to 'false' and does not contain a label, return -1. 799 int ConstantFoldsToSimpleInteger(const Expr *Cond); 800 801 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an 802 /// if statement) to the specified blocks. Based on the condition, this might 803 /// try to simplify the codegen of the conditional based on the branch. 804 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, 805 llvm::BasicBlock *FalseBlock); 806private: 807 808 /// EmitIndirectSwitches - Emit code for all of the switch 809 /// instructions in IndirectSwitches. 810 void EmitIndirectSwitches(); 811 812 void EmitReturnOfRValue(RValue RV, QualType Ty); 813 814 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty 815 /// from function arguments into \arg Dst. See ABIArgInfo::Expand. 816 /// 817 /// \param AI - The first function argument of the expansion. 818 /// \return The argument following the last expanded function 819 /// argument. 820 llvm::Function::arg_iterator 821 ExpandTypeFromArgs(QualType Ty, LValue Dst, 822 llvm::Function::arg_iterator AI); 823 824 /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg 825 /// Ty, into individual arguments on the provided vector \arg Args. See 826 /// ABIArgInfo::Expand. 827 void ExpandTypeToArgs(QualType Ty, RValue Src, 828 llvm::SmallVector<llvm::Value*, 16> &Args); 829 830 llvm::Value* EmitAsmInput(const AsmStmt &S, 831 const TargetInfo::ConstraintInfo &Info, 832 const Expr *InputExpr, std::string &ConstraintStr); 833 834 /// EmitCleanupBlock - emits a single cleanup block. 835 void EmitCleanupBlock(); 836 837 /// AddBranchFixup - adds a branch instruction to the list of fixups for the 838 /// current cleanup scope. 839 void AddBranchFixup(llvm::BranchInst *BI); 840 841 /// EmitCallArg - Emit a single call argument. 842 RValue EmitCallArg(const Expr *E, QualType ArgType); 843 844 /// EmitCallArgs - Emit call arguments for a function. 845 /// The CallArgTypeInfo parameter is used for iterating over the known 846 /// argument types of the function being called. 847 template<typename T> 848 void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo, 849 CallExpr::const_arg_iterator ArgBeg, 850 CallExpr::const_arg_iterator ArgEnd) { 851 CallExpr::const_arg_iterator Arg = ArgBeg; 852 853 // First, use the argument types that the type info knows about 854 if (CallArgTypeInfo) { 855 for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(), 856 E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) { 857 QualType ArgType = *I; 858 859 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()). 860 getTypePtr() == 861 getContext().getCanonicalType(Arg->getType()).getTypePtr() && 862 "type mismatch in call argument!"); 863 864 Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType), 865 ArgType)); 866 } 867 868 // Either we've emitted all the call args, or we have a call to a 869 // variadic function. 870 assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) && 871 "Extra arguments in non-variadic function!"); 872 873 } 874 875 // If we still have any arguments, emit them using the type of the argument. 876 for (; Arg != ArgEnd; ++Arg) { 877 QualType ArgType = Arg->getType(); 878 Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType), 879 ArgType)); 880 } 881 } 882}; 883 884 885} // end namespace CodeGen 886} // end namespace clang 887 888#endif 889