CodeGenFunction.h revision 193326
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 242 llvm::SmallVector<const CXXTemporary*, 4> LiveTemporaries; 243 244public: 245 CodeGenFunction(CodeGenModule &cgm); 246 247 ASTContext &getContext() const; 248 CGDebugInfo *getDebugInfo() { return DebugInfo; } 249 250 llvm::BasicBlock *getInvokeDest() { return InvokeDest; } 251 void setInvokeDest(llvm::BasicBlock *B) { InvokeDest = B; } 252 253 //===--------------------------------------------------------------------===// 254 // Objective-C 255 //===--------------------------------------------------------------------===// 256 257 void GenerateObjCMethod(const ObjCMethodDecl *OMD); 258 259 void StartObjCMethod(const ObjCMethodDecl *MD, 260 const ObjCContainerDecl *CD); 261 262 /// GenerateObjCGetter - Synthesize an Objective-C property getter function. 263 void GenerateObjCGetter(ObjCImplementationDecl *IMP, 264 const ObjCPropertyImplDecl *PID); 265 266 /// GenerateObjCSetter - Synthesize an Objective-C property setter function 267 /// for the given property. 268 void GenerateObjCSetter(ObjCImplementationDecl *IMP, 269 const ObjCPropertyImplDecl *PID); 270 271 //===--------------------------------------------------------------------===// 272 // Block Bits 273 //===--------------------------------------------------------------------===// 274 275 llvm::Value *BuildBlockLiteralTmp(const BlockExpr *); 276 llvm::Constant *BuildDescriptorBlockDecl(bool BlockHasCopyDispose, 277 uint64_t Size, 278 const llvm::StructType *, 279 std::vector<HelperInfo> *); 280 281 llvm::Function *GenerateBlockFunction(const BlockExpr *BExpr, 282 const BlockInfo& Info, 283 const Decl *OuterFuncDecl, 284 llvm::DenseMap<const Decl*, llvm::Value*> ldm, 285 uint64_t &Size, uint64_t &Align, 286 llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls, 287 bool &subBlockHasCopyDispose); 288 289 void BlockForwardSelf(); 290 llvm::Value *LoadBlockStruct(); 291 292 llvm::Value *GetAddrOfBlockDecl(const BlockDeclRefExpr *E); 293 294 const llvm::Type *BuildByRefType(QualType Ty, uint64_t Align); 295 296 void GenerateCode(const FunctionDecl *FD, 297 llvm::Function *Fn); 298 void StartFunction(const Decl *D, QualType RetTy, 299 llvm::Function *Fn, 300 const FunctionArgList &Args, 301 SourceLocation StartLoc); 302 303 /// EmitReturnBlock - Emit the unified return block, trying to avoid its 304 /// emission when possible. 305 void EmitReturnBlock(); 306 307 /// FinishFunction - Complete IR generation of the current function. It is 308 /// legal to call this function even if there is no current insertion point. 309 void FinishFunction(SourceLocation EndLoc=SourceLocation()); 310 311 /// EmitFunctionProlog - Emit the target specific LLVM code to load the 312 /// arguments for the given function. This is also responsible for naming the 313 /// LLVM function arguments. 314 void EmitFunctionProlog(const CGFunctionInfo &FI, 315 llvm::Function *Fn, 316 const FunctionArgList &Args); 317 318 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the 319 /// given temporary. 320 void EmitFunctionEpilog(const CGFunctionInfo &FI, llvm::Value *ReturnValue); 321 322 const llvm::Type *ConvertTypeForMem(QualType T); 323 const llvm::Type *ConvertType(QualType T); 324 325 /// LoadObjCSelf - Load the value of self. This function is only valid while 326 /// generating code for an Objective-C method. 327 llvm::Value *LoadObjCSelf(); 328 329 /// TypeOfSelfObject - Return type of object that this self represents. 330 QualType TypeOfSelfObject(); 331 332 /// hasAggregateLLVMType - Return true if the specified AST type will map into 333 /// an aggregate LLVM type or is void. 334 static bool hasAggregateLLVMType(QualType T); 335 336 /// createBasicBlock - Create an LLVM basic block. 337 llvm::BasicBlock *createBasicBlock(const char *Name="", 338 llvm::Function *Parent=0, 339 llvm::BasicBlock *InsertBefore=0) { 340#ifdef NDEBUG 341 return llvm::BasicBlock::Create("", Parent, InsertBefore); 342#else 343 return llvm::BasicBlock::Create(Name, Parent, InsertBefore); 344#endif 345 } 346 347 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified 348 /// label maps to. 349 llvm::BasicBlock *getBasicBlockForLabel(const LabelStmt *S); 350 351 /// SimplifyForwardingBlocks - If the given basic block is only a 352 /// branch to another basic block, simplify it. This assumes that no 353 /// other code could potentially reference the basic block. 354 void SimplifyForwardingBlocks(llvm::BasicBlock *BB); 355 356 /// EmitBlock - Emit the given block \arg BB and set it as the insert point, 357 /// adding a fall-through branch from the current insert block if 358 /// necessary. It is legal to call this function even if there is no current 359 /// insertion point. 360 /// 361 /// IsFinished - If true, indicates that the caller has finished emitting 362 /// branches to the given block and does not expect to emit code into it. This 363 /// means the block can be ignored if it is unreachable. 364 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false); 365 366 /// EmitBranch - Emit a branch to the specified basic block from the current 367 /// insert block, taking care to avoid creation of branches from dummy 368 /// blocks. It is legal to call this function even if there is no current 369 /// insertion point. 370 /// 371 /// This function clears the current insertion point. The caller should follow 372 /// calls to this function with calls to Emit*Block prior to generation new 373 /// code. 374 void EmitBranch(llvm::BasicBlock *Block); 375 376 /// HaveInsertPoint - True if an insertion point is defined. If not, this 377 /// indicates that the current code being emitted is unreachable. 378 bool HaveInsertPoint() const { 379 return Builder.GetInsertBlock() != 0; 380 } 381 382 /// EnsureInsertPoint - Ensure that an insertion point is defined so that 383 /// emitted IR has a place to go. Note that by definition, if this function 384 /// creates a block then that block is unreachable; callers may do better to 385 /// detect when no insertion point is defined and simply skip IR generation. 386 void EnsureInsertPoint() { 387 if (!HaveInsertPoint()) 388 EmitBlock(createBasicBlock()); 389 } 390 391 /// ErrorUnsupported - Print out an error that codegen doesn't support the 392 /// specified stmt yet. 393 void ErrorUnsupported(const Stmt *S, const char *Type, 394 bool OmitOnError=false); 395 396 //===--------------------------------------------------------------------===// 397 // Helpers 398 //===--------------------------------------------------------------------===// 399 400 /// CreateTempAlloca - This creates a alloca and inserts it into the entry 401 /// block. 402 llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty, 403 const char *Name = "tmp"); 404 405 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 406 /// expression and compare the result against zero, returning an Int1Ty value. 407 llvm::Value *EvaluateExprAsBool(const Expr *E); 408 409 /// EmitAnyExpr - Emit code to compute the specified expression which can have 410 /// any type. The result is returned as an RValue struct. If this is an 411 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where 412 /// the result should be returned. 413 /// 414 /// \param IgnoreResult - True if the resulting value isn't used. 415 RValue EmitAnyExpr(const Expr *E, llvm::Value *AggLoc = 0, 416 bool isAggLocVolatile = false, bool IgnoreResult = false); 417 418 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address 419 // or the value of the expression, depending on how va_list is defined. 420 llvm::Value *EmitVAListRef(const Expr *E); 421 422 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will 423 /// always be accessible even if no aggregate location is provided. 424 RValue EmitAnyExprToTemp(const Expr *E, llvm::Value *AggLoc = 0, 425 bool isAggLocVolatile = false); 426 427 /// EmitAggregateCopy - Emit an aggrate copy. 428 /// 429 /// \param isVolatile - True iff either the source or the destination is 430 /// volatile. 431 void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr, 432 QualType EltTy, bool isVolatile=false); 433 434 void EmitAggregateClear(llvm::Value *DestPtr, QualType Ty); 435 436 /// StartBlock - Start new block named N. If insert block is a dummy block 437 /// then reuse it. 438 void StartBlock(const char *N); 439 440 /// getCGRecordLayout - Return record layout info. 441 const CGRecordLayout *getCGRecordLayout(CodeGenTypes &CGT, QualType RTy); 442 443 /// GetAddrOfStaticLocalVar - Return the address of a static local variable. 444 llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD); 445 446 /// GetAddrOfLocalVar - Return the address of a local variable. 447 llvm::Value *GetAddrOfLocalVar(const VarDecl *VD); 448 449 /// getAccessedFieldNo - Given an encoded value and a result number, return 450 /// the input field number being accessed. 451 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts); 452 453 unsigned GetIDForAddrOfLabel(const LabelStmt *L); 454 455 /// EmitMemSetToZero - Generate code to memset a value of the given type to 0. 456 void EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty); 457 458 // EmitVAArg - Generate code to get an argument from the passed in pointer 459 // and update it accordingly. The return value is a pointer to the argument. 460 // FIXME: We should be able to get rid of this method and use the va_arg 461 // instruction in LLVM instead once it works well enough. 462 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty); 463 464 // EmitVLASize - Generate code for any VLA size expressions that might occur 465 // in a variably modified type. If Ty is a VLA, will return the value that 466 // corresponds to the size in bytes of the VLA type. Will return 0 otherwise. 467 llvm::Value *EmitVLASize(QualType Ty); 468 469 // GetVLASize - Returns an LLVM value that corresponds to the size in bytes 470 // of a variable length array type. 471 llvm::Value *GetVLASize(const VariableArrayType *); 472 473 /// LoadCXXThis - Load the value of 'this'. This function is only valid while 474 /// generating code for an C++ member function. 475 llvm::Value *LoadCXXThis(); 476 477 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 478 llvm::Value *This, 479 CallExpr::const_arg_iterator ArgBeg, 480 CallExpr::const_arg_iterator ArgEnd); 481 482 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, 483 llvm::Value *This); 484 485 void PushCXXTemporary(const CXXTemporary *Temporary, llvm::Value *Ptr); 486 487 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E); 488 489 //===--------------------------------------------------------------------===// 490 // Declaration Emission 491 //===--------------------------------------------------------------------===// 492 493 void EmitDecl(const Decl &D); 494 void EmitBlockVarDecl(const VarDecl &D); 495 void EmitLocalBlockVarDecl(const VarDecl &D); 496 void EmitStaticBlockVarDecl(const VarDecl &D); 497 498 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl. 499 void EmitParmDecl(const VarDecl &D, llvm::Value *Arg); 500 501 //===--------------------------------------------------------------------===// 502 // Statement Emission 503 //===--------------------------------------------------------------------===// 504 505 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info. 506 void EmitStopPoint(const Stmt *S); 507 508 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call 509 /// this function even if there is no current insertion point. 510 /// 511 /// This function may clear the current insertion point; callers should use 512 /// EnsureInsertPoint if they wish to subsequently generate code without first 513 /// calling EmitBlock, EmitBranch, or EmitStmt. 514 void EmitStmt(const Stmt *S); 515 516 /// EmitSimpleStmt - Try to emit a "simple" statement which does not 517 /// necessarily require an insertion point or debug information; typically 518 /// because the statement amounts to a jump or a container of other 519 /// statements. 520 /// 521 /// \return True if the statement was handled. 522 bool EmitSimpleStmt(const Stmt *S); 523 524 RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false, 525 llvm::Value *AggLoc = 0, bool isAggVol = false); 526 527 /// EmitLabel - Emit the block for the given label. It is legal to call this 528 /// function even if there is no current insertion point. 529 void EmitLabel(const LabelStmt &S); // helper for EmitLabelStmt. 530 531 void EmitLabelStmt(const LabelStmt &S); 532 void EmitGotoStmt(const GotoStmt &S); 533 void EmitIndirectGotoStmt(const IndirectGotoStmt &S); 534 void EmitIfStmt(const IfStmt &S); 535 void EmitWhileStmt(const WhileStmt &S); 536 void EmitDoStmt(const DoStmt &S); 537 void EmitForStmt(const ForStmt &S); 538 void EmitReturnStmt(const ReturnStmt &S); 539 void EmitDeclStmt(const DeclStmt &S); 540 void EmitBreakStmt(const BreakStmt &S); 541 void EmitContinueStmt(const ContinueStmt &S); 542 void EmitSwitchStmt(const SwitchStmt &S); 543 void EmitDefaultStmt(const DefaultStmt &S); 544 void EmitCaseStmt(const CaseStmt &S); 545 void EmitCaseStmtRange(const CaseStmt &S); 546 void EmitAsmStmt(const AsmStmt &S); 547 548 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S); 549 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S); 550 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S); 551 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S); 552 553 //===--------------------------------------------------------------------===// 554 // LValue Expression Emission 555 //===--------------------------------------------------------------------===// 556 557 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type. 558 RValue GetUndefRValue(QualType Ty); 559 560 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E 561 /// and issue an ErrorUnsupported style diagnostic (using the 562 /// provided Name). 563 RValue EmitUnsupportedRValue(const Expr *E, 564 const char *Name); 565 566 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue 567 /// an ErrorUnsupported style diagnostic (using the provided Name). 568 LValue EmitUnsupportedLValue(const Expr *E, 569 const char *Name); 570 571 /// EmitLValue - Emit code to compute a designator that specifies the location 572 /// of the expression. 573 /// 574 /// This can return one of two things: a simple address or a bitfield 575 /// reference. In either case, the LLVM Value* in the LValue structure is 576 /// guaranteed to be an LLVM pointer type. 577 /// 578 /// If this returns a bitfield reference, nothing about the pointee type of 579 /// the LLVM value is known: For example, it may not be a pointer to an 580 /// integer. 581 /// 582 /// If this returns a normal address, and if the lvalue's C type is fixed 583 /// size, this method guarantees that the returned pointer type will point to 584 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a 585 /// variable length type, this is not possible. 586 /// 587 LValue EmitLValue(const Expr *E); 588 589 /// EmitLoadOfScalar - Load a scalar value from an address, taking 590 /// care to appropriately convert from the memory representation to 591 /// the LLVM value representation. 592 llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile, 593 QualType Ty); 594 595 /// EmitStoreOfScalar - Store a scalar value to an address, taking 596 /// care to appropriately convert from the memory representation to 597 /// the LLVM value representation. 598 void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr, 599 bool Volatile, QualType Ty); 600 601 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, 602 /// this method emits the address of the lvalue, then loads the result as an 603 /// rvalue, returning the rvalue. 604 RValue EmitLoadOfLValue(LValue V, QualType LVType); 605 RValue EmitLoadOfExtVectorElementLValue(LValue V, QualType LVType); 606 RValue EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType); 607 RValue EmitLoadOfPropertyRefLValue(LValue LV, QualType ExprType); 608 RValue EmitLoadOfKVCRefLValue(LValue LV, QualType ExprType); 609 610 611 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 612 /// lvalue, where both are guaranteed to the have the same type, and that type 613 /// is 'Ty'. 614 void EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty); 615 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst, 616 QualType Ty); 617 void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst, QualType Ty); 618 void EmitStoreThroughKVCRefLValue(RValue Src, LValue Dst, QualType Ty); 619 620 /// EmitStoreThroughLValue - Store Src into Dst with same constraints as 621 /// EmitStoreThroughLValue. 622 /// 623 /// \param Result [out] - If non-null, this will be set to a Value* for the 624 /// bit-field contents after the store, appropriate for use as the result of 625 /// an assignment to the bit-field. 626 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty, 627 llvm::Value **Result=0); 628 629 // Note: only availabe for agg return types 630 LValue EmitBinaryOperatorLValue(const BinaryOperator *E); 631 // Note: only available for agg return types 632 LValue EmitCallExprLValue(const CallExpr *E); 633 // Note: only available for agg return types 634 LValue EmitVAArgExprLValue(const VAArgExpr *E); 635 LValue EmitDeclRefLValue(const DeclRefExpr *E); 636 LValue EmitStringLiteralLValue(const StringLiteral *E); 637 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E); 638 LValue EmitPredefinedFunctionName(unsigned Type); 639 LValue EmitPredefinedLValue(const PredefinedExpr *E); 640 LValue EmitUnaryOpLValue(const UnaryOperator *E); 641 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E); 642 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E); 643 LValue EmitMemberExpr(const MemberExpr *E); 644 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E); 645 LValue EmitConditionalOperator(const ConditionalOperator *E); 646 LValue EmitCastLValue(const CastExpr *E); 647 648 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface, 649 const ObjCIvarDecl *Ivar); 650 LValue EmitLValueForField(llvm::Value* Base, FieldDecl* Field, 651 bool isUnion, unsigned CVRQualifiers); 652 LValue EmitLValueForIvar(QualType ObjectTy, 653 llvm::Value* Base, const ObjCIvarDecl *Ivar, 654 unsigned CVRQualifiers); 655 656 LValue EmitLValueForBitfield(llvm::Value* Base, FieldDecl* Field, 657 unsigned CVRQualifiers); 658 659 LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E); 660 661 LValue EmitCXXConditionDeclLValue(const CXXConditionDeclExpr *E); 662 LValue EmitCXXConstructLValue(const CXXConstructExpr *E); 663 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E); 664 665 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E); 666 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E); 667 LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E); 668 LValue EmitObjCKVCRefLValue(const ObjCKVCRefExpr *E); 669 LValue EmitObjCSuperExprLValue(const ObjCSuperExpr *E); 670 LValue EmitStmtExprLValue(const StmtExpr *E); 671 672 //===--------------------------------------------------------------------===// 673 // Scalar Expression Emission 674 //===--------------------------------------------------------------------===// 675 676 /// EmitCall - Generate a call of the given function, expecting the given 677 /// result type, and using the given argument list which specifies both the 678 /// LLVM arguments and the types they were derived from. 679 /// 680 /// \param TargetDecl - If given, the decl of the function in a 681 /// direct call; used to set attributes on the call (noreturn, 682 /// etc.). 683 RValue EmitCall(const CGFunctionInfo &FnInfo, 684 llvm::Value *Callee, 685 const CallArgList &Args, 686 const Decl *TargetDecl = 0); 687 688 RValue EmitCall(llvm::Value *Callee, QualType FnType, 689 CallExpr::const_arg_iterator ArgBeg, 690 CallExpr::const_arg_iterator ArgEnd, 691 const Decl *TargetDecl = 0); 692 RValue EmitCallExpr(const CallExpr *E); 693 694 RValue EmitCXXMemberCall(const CXXMethodDecl *MD, 695 llvm::Value *Callee, 696 llvm::Value *This, 697 CallExpr::const_arg_iterator ArgBeg, 698 CallExpr::const_arg_iterator ArgEnd); 699 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E); 700 701 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 702 const CXXMethodDecl *MD); 703 704 RValue EmitBuiltinExpr(const FunctionDecl *FD, 705 unsigned BuiltinID, const CallExpr *E); 706 707 RValue EmitBlockCallExpr(const CallExpr *E); 708 709 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call 710 /// is unhandled by the current target. 711 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 712 713 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 714 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 715 716 llvm::Value *EmitShuffleVector(llvm::Value* V1, llvm::Value *V2, ...); 717 llvm::Value *EmitVector(llvm::Value * const *Vals, unsigned NumVals, 718 bool isSplat = false); 719 720 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E); 721 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E); 722 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E); 723 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E); 724 RValue EmitObjCPropertyGet(const Expr *E); 725 RValue EmitObjCSuperPropertyGet(const Expr *Exp, const Selector &S); 726 void EmitObjCPropertySet(const Expr *E, RValue Src); 727 void EmitObjCSuperPropertySet(const Expr *E, const Selector &S, RValue Src); 728 729 730 /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in 731 /// expression. Will emit a temporary variable if E is not an LValue. 732 RValue EmitReferenceBindingToExpr(const Expr* E, QualType DestType); 733 734 //===--------------------------------------------------------------------===// 735 // Expression Emission 736 //===--------------------------------------------------------------------===// 737 738 // Expressions are broken into three classes: scalar, complex, aggregate. 739 740 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM 741 /// scalar type, returning the result. 742 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign=false); 743 744 /// EmitScalarConversion - Emit a conversion from the specified type to the 745 /// specified destination type, both of which are LLVM scalar types. 746 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy, 747 QualType DstTy); 748 749 /// EmitComplexToScalarConversion - Emit a conversion from the specified 750 /// complex type to the specified destination type, where the destination type 751 /// is an LLVM scalar type. 752 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, 753 QualType DstTy); 754 755 756 /// EmitAggExpr - Emit the computation of the specified expression of 757 /// aggregate type. The result is computed into DestPtr. Note that if 758 /// DestPtr is null, the value of the aggregate expression is not needed. 759 void EmitAggExpr(const Expr *E, llvm::Value *DestPtr, bool VolatileDest, 760 bool IgnoreResult = false); 761 762 /// EmitComplexExpr - Emit the computation of the specified expression of 763 /// complex type, returning the result. 764 ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal = false, 765 bool IgnoreImag = false, 766 bool IgnoreRealAssign = false, 767 bool IgnoreImagAssign = false); 768 769 /// EmitComplexExprIntoAddr - Emit the computation of the specified expression 770 /// of complex type, storing into the specified Value*. 771 void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr, 772 bool DestIsVolatile); 773 774 /// StoreComplexToAddr - Store a complex number into the specified address. 775 void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr, 776 bool DestIsVolatile); 777 /// LoadComplexFromAddr - Load a complex number from the specified address. 778 ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile); 779 780 /// CreateStaticBlockVarDecl - Create a zero-initialized LLVM global 781 /// for a static block var decl. 782 llvm::GlobalVariable * CreateStaticBlockVarDecl(const VarDecl &D, 783 const char *Separator, 784 llvm::GlobalValue::LinkageTypes 785 Linkage); 786 787 /// GenerateStaticCXXBlockVarDecl - Create the initializer for a C++ 788 /// runtime initialized static block var decl. 789 void GenerateStaticCXXBlockVarDeclInit(const VarDecl &D, 790 llvm::GlobalVariable *GV); 791 792 void EmitCXXConstructExpr(llvm::Value *Dest, const CXXConstructExpr *E); 793 794 RValue EmitCXXExprWithTemporaries(const CXXExprWithTemporaries *E, 795 llvm::Value *AggLoc = 0, 796 bool isAggLocVolatile = false); 797 798 //===--------------------------------------------------------------------===// 799 // Internal Helpers 800 //===--------------------------------------------------------------------===// 801 802 /// ContainsLabel - Return true if the statement contains a label in it. If 803 /// this statement is not executed normally, it not containing a label means 804 /// that we can just remove the code. 805 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false); 806 807 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 808 /// to a constant, or if it does but contains a label, return 0. If it 809 /// constant folds to 'true' and does not contain a label, return 1, if it 810 /// constant folds to 'false' and does not contain a label, return -1. 811 int ConstantFoldsToSimpleInteger(const Expr *Cond); 812 813 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an 814 /// if statement) to the specified blocks. Based on the condition, this might 815 /// try to simplify the codegen of the conditional based on the branch. 816 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, 817 llvm::BasicBlock *FalseBlock); 818private: 819 820 /// EmitIndirectSwitches - Emit code for all of the switch 821 /// instructions in IndirectSwitches. 822 void EmitIndirectSwitches(); 823 824 void EmitReturnOfRValue(RValue RV, QualType Ty); 825 826 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty 827 /// from function arguments into \arg Dst. See ABIArgInfo::Expand. 828 /// 829 /// \param AI - The first function argument of the expansion. 830 /// \return The argument following the last expanded function 831 /// argument. 832 llvm::Function::arg_iterator 833 ExpandTypeFromArgs(QualType Ty, LValue Dst, 834 llvm::Function::arg_iterator AI); 835 836 /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg 837 /// Ty, into individual arguments on the provided vector \arg Args. See 838 /// ABIArgInfo::Expand. 839 void ExpandTypeToArgs(QualType Ty, RValue Src, 840 llvm::SmallVector<llvm::Value*, 16> &Args); 841 842 llvm::Value* EmitAsmInput(const AsmStmt &S, 843 const TargetInfo::ConstraintInfo &Info, 844 const Expr *InputExpr, std::string &ConstraintStr); 845 846 /// EmitCleanupBlock - emits a single cleanup block. 847 void EmitCleanupBlock(); 848 849 /// AddBranchFixup - adds a branch instruction to the list of fixups for the 850 /// current cleanup scope. 851 void AddBranchFixup(llvm::BranchInst *BI); 852 853 /// EmitCallArg - Emit a single call argument. 854 RValue EmitCallArg(const Expr *E, QualType ArgType); 855 856 /// EmitCallArgs - Emit call arguments for a function. 857 /// The CallArgTypeInfo parameter is used for iterating over the known 858 /// argument types of the function being called. 859 template<typename T> 860 void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo, 861 CallExpr::const_arg_iterator ArgBeg, 862 CallExpr::const_arg_iterator ArgEnd) { 863 CallExpr::const_arg_iterator Arg = ArgBeg; 864 865 // First, use the argument types that the type info knows about 866 if (CallArgTypeInfo) { 867 for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(), 868 E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) { 869 QualType ArgType = *I; 870 871 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()). 872 getTypePtr() == 873 getContext().getCanonicalType(Arg->getType()).getTypePtr() && 874 "type mismatch in call argument!"); 875 876 Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType), 877 ArgType)); 878 } 879 880 // Either we've emitted all the call args, or we have a call to a 881 // variadic function. 882 assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) && 883 "Extra arguments in non-variadic function!"); 884 885 } 886 887 // If we still have any arguments, emit them using the type of the argument. 888 for (; Arg != ArgEnd; ++Arg) { 889 QualType ArgType = Arg->getType(); 890 Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType), 891 ArgType)); 892 } 893 } 894}; 895 896 897} // end namespace CodeGen 898} // end namespace clang 899 900#endif 901