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