CodeGenFunction.h revision 8a219ceda2b5afd447e7199b9c53079bead31b89
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 "llvm/ADT/DenseMap.h" 19#include "llvm/ADT/SmallVector.h" 20#include "clang/Basic/TargetInfo.h" 21#include "clang/AST/Expr.h" 22#include "clang/AST/ExprCXX.h" 23#include "clang/AST/ExprObjC.h" 24 25#include <vector> 26#include <map> 27 28#include "CGBuilder.h" 29#include "CGCall.h" 30#include "CGValue.h" 31 32namespace llvm { 33 class BasicBlock; 34 class Module; 35 class SwitchInst; 36 class Value; 37} 38 39namespace clang { 40 class ASTContext; 41 class Decl; 42 class EnumConstantDecl; 43 class FunctionDecl; 44 class FunctionTypeProto; 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 55namespace CodeGen { 56 class CodeGenModule; 57 class CodeGenTypes; 58 class CGDebugInfo; 59 class CGFunctionInfo; 60 class CGRecordLayout; 61 62/// CodeGenFunction - This class organizes the per-function state that is used 63/// while generating LLVM code. 64class CodeGenFunction { 65 CodeGenFunction(const CodeGenFunction&); // DO NOT IMPLEMENT 66 void operator=(const CodeGenFunction&); // DO NOT IMPLEMENT 67public: 68 CodeGenModule &CGM; // Per-module state. 69 TargetInfo &Target; 70 71 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy; 72 CGBuilderTy Builder; 73 74 // Holds the Decl for the current function or method 75 const Decl *CurFuncDecl; 76 const CGFunctionInfo *CurFnInfo; 77 QualType FnRetTy; 78 llvm::Function *CurFn; 79 80 /// ReturnBlock - Unified return block. 81 llvm::BasicBlock *ReturnBlock; 82 /// ReturnValue - The temporary alloca to hold the return value. This is null 83 /// iff the function has no return value. 84 llvm::Instruction *ReturnValue; 85 86 /// AllocaInsertPoint - This is an instruction in the entry block before which 87 /// we prefer to insert allocas. 88 llvm::Instruction *AllocaInsertPt; 89 90 const llvm::Type *LLVMIntTy; 91 uint32_t LLVMPointerWidth; 92 93public: 94 /// ObjCEHValueStack - Stack of Objective-C exception values, used for 95 /// rethrows. 96 llvm::SmallVector<llvm::Value*, 8> ObjCEHValueStack; 97 98 /// PushCleanupBlock - Push a new cleanup entry on the stack and set the 99 /// passed in block as the cleanup block. 100 void PushCleanupBlock(llvm::BasicBlock *CleanupBlock); 101 102 /// CleanupBlockInfo - A struct representing a popped cleanup block. 103 struct CleanupBlockInfo { 104 /// CleanupBlock - the cleanup block 105 llvm::BasicBlock *CleanupBlock; 106 107 /// SwitchBlock - the block (if any) containing the switch instruction used 108 /// for jumping to the final destination. 109 llvm::BasicBlock *SwitchBlock; 110 111 /// EndBlock - the default destination for the switch instruction. 112 llvm::BasicBlock *EndBlock; 113 114 CleanupBlockInfo(llvm::BasicBlock *cb, llvm::BasicBlock *sb, 115 llvm::BasicBlock *eb) 116 : CleanupBlock(cb), SwitchBlock(sb), EndBlock(eb) {} 117 }; 118 119 /// PopCleanupBlock - Will pop the cleanup entry on the stack, process all 120 /// branch fixups and return a block info struct with the switch block and end 121 /// block. 122 CleanupBlockInfo PopCleanupBlock(); 123 124 /// CleanupScope - RAII object that will create a cleanup block and set the 125 /// insert point to that block. When destructed, it sets the insert point to 126 /// the previous block and pushes a new cleanup entry on the stack. 127 class CleanupScope { 128 CodeGenFunction& CGF; 129 llvm::BasicBlock *CurBB; 130 llvm::BasicBlock *CleanupBB; 131 132 public: 133 CleanupScope(CodeGenFunction &cgf) 134 : CGF(cgf), CurBB(CGF.Builder.GetInsertBlock()) { 135 CleanupBB = CGF.createBasicBlock("cleanup"); 136 CGF.Builder.SetInsertPoint(CleanupBB); 137 } 138 139 ~CleanupScope() { 140 CGF.PushCleanupBlock(CleanupBB); 141 CGF.Builder.SetInsertPoint(CurBB); 142 } 143 }; 144 145 /// EmitCleanupBlocks - Takes the old cleanup stack size and emits the cleanup 146 /// blocks that have been added. 147 void EmitCleanupBlocks(size_t OldCleanupStackSize); 148 149 /// EmitBranchThroughCleanup - Emit a branch from the current insert block 150 /// through the cleanup handling code (if any) and then on to \arg Dest. 151 /// 152 /// FIXME: Maybe this should really be in EmitBranch? Don't we always want 153 /// this behavior for branches? 154 void EmitBranchThroughCleanup(llvm::BasicBlock *Dest); 155 156private: 157 CGDebugInfo* DebugInfo; 158 159 /// LabelIDs - Track arbitrary ids assigned to labels for use in implementing 160 /// the GCC address-of-label extension and indirect goto. IDs are assigned to 161 /// labels inside getIDForAddrOfLabel(). 162 std::map<const LabelStmt*, unsigned> LabelIDs; 163 164 /// IndirectSwitches - Record the list of switches for indirect 165 /// gotos. Emission of the actual switching code needs to be delayed until all 166 /// AddrLabelExprs have been seen. 167 std::vector<llvm::SwitchInst*> IndirectSwitches; 168 169 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C 170 /// decls. 171 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap; 172 173 /// LabelMap - This keeps track of the LLVM basic block for each C label. 174 llvm::DenseMap<const LabelStmt*, llvm::BasicBlock*> LabelMap; 175 176 // BreakContinueStack - This keeps track of where break and continue 177 // statements should jump to. 178 struct BreakContinue { 179 BreakContinue(llvm::BasicBlock *bb, llvm::BasicBlock *cb) 180 : BreakBlock(bb), ContinueBlock(cb) {} 181 182 llvm::BasicBlock *BreakBlock; 183 llvm::BasicBlock *ContinueBlock; 184 }; 185 llvm::SmallVector<BreakContinue, 8> BreakContinueStack; 186 187 /// SwitchInsn - This is nearest current switch instruction. It is null if if 188 /// current context is not in a switch. 189 llvm::SwitchInst *SwitchInsn; 190 191 /// CaseRangeBlock - This block holds if condition check for last case 192 /// statement range in current switch instruction. 193 llvm::BasicBlock *CaseRangeBlock; 194 195 /// InvokeDest - This is the nearest exception target for calls 196 /// which can unwind, when exceptions are being used. 197 llvm::BasicBlock *InvokeDest; 198 199 // VLASizeMap - This keeps track of the associated size for each VLA type. 200 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we 201 // enter/leave scopes. 202 llvm::DenseMap<const VariableArrayType*, llvm::Value*> VLASizeMap; 203 204 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid 205 /// calling llvm.stacksave for multiple VLAs in the same scope. 206 bool DidCallStackSave; 207 208 struct CleanupEntry { 209 /// CleanupBlock - The block of code that does the actual cleanup. 210 llvm::BasicBlock *CleanupBlock; 211 212 /// Blocks - Basic blocks that were emitted in the current cleanup scope. 213 std::vector<llvm::BasicBlock *> Blocks; 214 215 /// BranchFixups - Branch instructions to basic blocks that haven't been 216 /// inserted into the current function yet. 217 std::vector<llvm::BranchInst *> BranchFixups; 218 219 explicit CleanupEntry(llvm::BasicBlock *cb) 220 : CleanupBlock(cb) {} 221 222 ~CleanupEntry() { 223 assert(Blocks.empty() && "Did not empty blocks!"); 224 assert(BranchFixups.empty() && "Did not empty branch fixups!"); 225 } 226 }; 227 228 /// CleanupEntries - Stack of cleanup entries. 229 llvm::SmallVector<CleanupEntry, 8> CleanupEntries; 230 231 typedef llvm::DenseMap<llvm::BasicBlock*, size_t> BlockScopeMap; 232 233 /// BlockScopes - Map of which "cleanup scope" scope basic blocks have. 234 BlockScopeMap BlockScopes; 235 236public: 237 CodeGenFunction(CodeGenModule &cgm); 238 239 ASTContext &getContext() const; 240 CGDebugInfo *getDebugInfo() { return DebugInfo; } 241 242 llvm::BasicBlock *getInvokeDest() { return InvokeDest; } 243 void setInvokeDest(llvm::BasicBlock *B) { InvokeDest = B; } 244 245 //===--------------------------------------------------------------------===// 246 // Objective-C 247 //===--------------------------------------------------------------------===// 248 249 void GenerateObjCMethod(const ObjCMethodDecl *OMD); 250 251 void StartObjCMethod(const ObjCMethodDecl *MD, 252 const ObjCContainerDecl *CD); 253 254 /// GenerateObjCGetter - Synthesize an Objective-C property getter function. 255 void GenerateObjCGetter(ObjCImplementationDecl *IMP, 256 const ObjCPropertyImplDecl *PID); 257 258 /// GenerateObjCSetter - Synthesize an Objective-C property setter function 259 /// for the given property. 260 void GenerateObjCSetter(ObjCImplementationDecl *IMP, 261 const ObjCPropertyImplDecl *PID); 262 263 //===--------------------------------------------------------------------===// 264 // Block Bits 265 //===--------------------------------------------------------------------===// 266 267 llvm::Constant *BuildBlockLiteralTmp(const BlockExpr *); 268 llvm::Constant *BuildDescriptorBlockDecl(uint64_t Size); 269 270 /// BlockInfo - Information to generate a block literal. 271 struct BlockInfo { 272 /// BlockLiteralTy - The type of the block literal. 273 const llvm::Type *BlockLiteralTy; 274 275 /// Name - the name of the function this block was created for, if any 276 const char *Name; 277 278 BlockInfo(const llvm::Type *blt, const char *n) 279 : BlockLiteralTy(blt), Name(n) {} 280 }; 281 282 llvm::Function *GenerateBlockFunction(const BlockExpr *Expr, 283 const BlockInfo& Info, 284 uint64_t &Size); 285 286 ImplicitParamDecl *BlockStructDecl; 287 288 ImplicitParamDecl *getBlockStructDecl() { return BlockStructDecl; } 289 290 llvm::Value *LoadBlockStruct(); 291 292 /// BlockHasCopyDispose - True iff the block uses copy/dispose. 293 bool BlockHasCopyDispose; 294 295 uint64_t BlockOffset; 296 /// getBlockOffset - Offset for next allocated variable use in a BlockExpr. 297 uint64_t getBlockOffset(uint64_t Size, uint64_t Align) { 298 assert (((Align >> 3) > 0) && "alignment must be 1 byte or more"); 299 assert (((Align & 7) == 0) 300 && "alignment must be on at least byte boundaries"); 301 // Ensure proper alignment, even if it means we have to have a gap 302 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, Align/8); 303 304 BlockOffset += Size; 305 return BlockOffset-Size; 306 } 307 uint64_t getBlockOffset(ValueDecl *D) { 308 uint64_t Size = getContext().getTypeSize(D->getType()) / 8; 309 return getBlockOffset(Size, getContext().getDeclAlignInBytes(D)*8); 310 } 311 std::map<Decl*, uint64_t> BlockDecls; 312 313 void GenerateCode(const FunctionDecl *FD, 314 llvm::Function *Fn); 315 void StartFunction(const Decl *D, QualType RetTy, 316 llvm::Function *Fn, 317 const FunctionArgList &Args, 318 SourceLocation StartLoc); 319 320 /// EmitReturnBlock - Emit the unified return block, trying to avoid its 321 /// emission when possible. 322 void EmitReturnBlock(); 323 324 /// FinishFunction - Complete IR generation of the current function. It is 325 /// legal to call this function even if there is no current insertion point. 326 void FinishFunction(SourceLocation EndLoc=SourceLocation()); 327 328 /// EmitFunctionProlog - Emit the target specific LLVM code to load the 329 /// arguments for the given function. This is also responsible for naming the 330 /// LLVM function arguments. 331 void EmitFunctionProlog(const CGFunctionInfo &FI, 332 llvm::Function *Fn, 333 const FunctionArgList &Args); 334 335 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the 336 /// given temporary. 337 void EmitFunctionEpilog(const CGFunctionInfo &FI, llvm::Value *ReturnValue); 338 339 const llvm::Type *ConvertTypeForMem(QualType T); 340 const llvm::Type *ConvertType(QualType T); 341 342 /// LoadObjCSelf - Load the value of self. This function is only valid while 343 /// generating code for an Objective-C method. 344 llvm::Value *LoadObjCSelf(); 345 346 /// TypeOfSelfObject - Return type of object that this self represents. 347 QualType TypeOfSelfObject(); 348 349 /// isObjCPointerType - Return true if the specificed AST type will map onto 350 /// some Objective-C pointer type. 351 static bool isObjCPointerType(QualType T); 352 353 /// hasAggregateLLVMType - Return true if the specified AST type will map into 354 /// an aggregate LLVM type or is void. 355 static bool hasAggregateLLVMType(QualType T); 356 357 /// createBasicBlock - Create an LLVM basic block. 358 llvm::BasicBlock *createBasicBlock(const char *Name="", 359 llvm::Function *Parent=0, 360 llvm::BasicBlock *InsertBefore=0) { 361#ifdef NDEBUG 362 return llvm::BasicBlock::Create("", Parent, InsertBefore); 363#else 364 return llvm::BasicBlock::Create(Name, Parent, InsertBefore); 365#endif 366 } 367 368 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified 369 /// label maps to. 370 llvm::BasicBlock *getBasicBlockForLabel(const LabelStmt *S); 371 372 /// EmitBlock - Emit the given block \arg BB and set it as the insert point, 373 /// adding a fall-through branch from the current insert block if 374 /// necessary. It is legal to call this function even if there is no current 375 /// insertion point. 376 /// 377 /// IsFinished - If true, indicates that the caller has finished emitting 378 /// branches to the given block and does not expect to emit code into it. This 379 /// means the block can be ignored if it is unreachable. 380 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false); 381 382 /// EmitBranch - Emit a branch to the specified basic block from the current 383 /// insert block, taking care to avoid creation of branches from dummy 384 /// blocks. It is legal to call this function even if there is no current 385 /// insertion point. 386 /// 387 /// This function clears the current insertion point. The caller should follow 388 /// calls to this function with calls to Emit*Block prior to generation new 389 /// code. 390 void EmitBranch(llvm::BasicBlock *Block); 391 392 /// HaveInsertPoint - True if an insertion point is defined. If not, this 393 /// indicates that the current code being emitted is unreachable. 394 bool HaveInsertPoint() const { 395 return Builder.GetInsertBlock() != 0; 396 } 397 398 /// EnsureInsertPoint - Ensure that an insertion point is defined so that 399 /// emitted IR has a place to go. Note that by definition, if this function 400 /// creates a block then that block is unreachable; callers may do better to 401 /// detect when no insertion point is defined and simply skip IR generation. 402 void EnsureInsertPoint() { 403 if (!HaveInsertPoint()) 404 EmitBlock(createBasicBlock()); 405 } 406 407 /// ErrorUnsupported - Print out an error that codegen doesn't support the 408 /// specified stmt yet. 409 void ErrorUnsupported(const Stmt *S, const char *Type, 410 bool OmitOnError=false); 411 412 //===--------------------------------------------------------------------===// 413 // Helpers 414 //===--------------------------------------------------------------------===// 415 416 /// CreateTempAlloca - This creates a alloca and inserts it into the entry 417 /// block. 418 llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty, 419 const char *Name = "tmp"); 420 421 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 422 /// expression and compare the result against zero, returning an Int1Ty value. 423 llvm::Value *EvaluateExprAsBool(const Expr *E); 424 425 /// EmitAnyExpr - Emit code to compute the specified expression which can have 426 /// any type. The result is returned as an RValue struct. If this is an 427 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where 428 /// the result should be returned. 429 RValue EmitAnyExpr(const Expr *E, llvm::Value *AggLoc = 0, 430 bool isAggLocVolatile = false); 431 432 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address 433 // or the value of the expression, depending on how va_list is defined. 434 llvm::Value *EmitVAListRef(const Expr *E); 435 436 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will 437 /// always be accessible even if no aggregate location is provided. 438 RValue EmitAnyExprToTemp(const Expr *E, llvm::Value *AggLoc = 0, 439 bool isAggLocVolatile = false); 440 441 void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr, 442 QualType EltTy); 443 444 void EmitAggregateClear(llvm::Value *DestPtr, QualType Ty); 445 446 /// StartBlock - Start new block named N. If insert block is a dummy block 447 /// then reuse it. 448 void StartBlock(const char *N); 449 450 /// getCGRecordLayout - Return record layout info. 451 const CGRecordLayout *getCGRecordLayout(CodeGenTypes &CGT, QualType RTy); 452 453 /// GetAddrOfStaticLocalVar - Return the address of a static local variable. 454 llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD); 455 456 /// GetAddrOfLocalVar - Return the address of a local variable. 457 llvm::Value *GetAddrOfLocalVar(const VarDecl *VD); 458 459 /// getAccessedFieldNo - Given an encoded value and a result number, return 460 /// the input field number being accessed. 461 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts); 462 463 unsigned GetIDForAddrOfLabel(const LabelStmt *L); 464 465 /// EmitMemSetToZero - Generate code to memset a value of the given type to 0. 466 void EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty); 467 468 // EmitVAArg - Generate code to get an argument from the passed in pointer 469 // and update it accordingly. The return value is a pointer to the argument. 470 // FIXME: We should be able to get rid of this method and use the va_arg 471 // instruction in LLVM instead once it works well enough. 472 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty); 473 474 // EmitVLASize - Generate code for any VLA size expressions that might occur 475 // in a variably modified type. If Ty is a VLA, will return the value that 476 // corresponds to the size in bytes of the VLA type. Will return 0 otherwise. 477 llvm::Value *EmitVLASize(QualType Ty); 478 479 // GetVLASize - Returns an LLVM value that corresponds to the size in bytes 480 // of a variable length array type. 481 llvm::Value *GetVLASize(const VariableArrayType *); 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); 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 EmitPredefinedFunctionName(unsigned Type); 632 LValue EmitPredefinedLValue(const PredefinedExpr *E); 633 LValue EmitUnaryOpLValue(const UnaryOperator *E); 634 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E); 635 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E); 636 LValue EmitMemberExpr(const MemberExpr *E); 637 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E); 638 639 llvm::Value *EmitIvarOffset(ObjCInterfaceDecl *Interface, 640 const ObjCIvarDecl *Ivar); 641 LValue EmitLValueForField(llvm::Value* Base, FieldDecl* Field, 642 bool isUnion, unsigned CVRQualifiers); 643 LValue EmitLValueForIvar(QualType ObjectTy, 644 llvm::Value* Base, const ObjCIvarDecl *Ivar, 645 const FieldDecl *Field, 646 unsigned CVRQualifiers); 647 648 LValue EmitLValueForBitfield(llvm::Value* Base, FieldDecl* Field, 649 unsigned CVRQualifiers); 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 EmitObjCSuperExpr(const ObjCSuperExpr *E); 658 659 //===--------------------------------------------------------------------===// 660 // Scalar Expression Emission 661 //===--------------------------------------------------------------------===// 662 663 /// EmitCall - Generate a call of the given function, expecting the given 664 /// result type, and using the given argument list which specifies both the 665 /// LLVM arguments and the types they were derived from. 666 /// 667 /// \param TargetDecl - If given, the decl of the function in a 668 /// direct call; used to set attributes on the call (noreturn, 669 /// etc.). 670 RValue EmitCall(const CGFunctionInfo &FnInfo, 671 llvm::Value *Callee, 672 const CallArgList &Args, 673 const Decl *TargetDecl = 0); 674 675 RValue EmitCallExpr(const CallExpr *E); 676 677 RValue EmitCallExpr(llvm::Value *Callee, QualType FnType, 678 CallExpr::const_arg_iterator ArgBeg, 679 CallExpr::const_arg_iterator ArgEnd, 680 const Decl *TargetDecl = 0); 681 682 RValue EmitBuiltinExpr(const FunctionDecl *FD, 683 unsigned BuiltinID, const CallExpr *E); 684 685 RValue EmitBlockCallExpr(const CallExpr *E); 686 687 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call 688 /// is unhandled by the current target. 689 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 690 691 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 692 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 693 694 llvm::Value *EmitShuffleVector(llvm::Value* V1, llvm::Value *V2, ...); 695 llvm::Value *EmitVector(llvm::Value * const *Vals, unsigned NumVals, 696 bool isSplat = false); 697 698 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E); 699 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E); 700 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E); 701 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E); 702 RValue EmitObjCPropertyGet(const Expr *E); 703 void EmitObjCPropertySet(const Expr *E, RValue Src); 704 705 706 //===--------------------------------------------------------------------===// 707 // Expression Emission 708 //===--------------------------------------------------------------------===// 709 710 // Expressions are broken into three classes: scalar, complex, aggregate. 711 712 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM 713 /// scalar type, returning the result. 714 llvm::Value *EmitScalarExpr(const Expr *E); 715 716 /// EmitScalarConversion - Emit a conversion from the specified type to the 717 /// specified destination type, both of which are LLVM scalar types. 718 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy, 719 QualType DstTy); 720 721 /// EmitComplexToScalarConversion - Emit a conversion from the specified 722 /// complex type to the specified destination type, where the destination type 723 /// is an LLVM scalar type. 724 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, 725 QualType DstTy); 726 727 728 /// EmitAggExpr - Emit the computation of the specified expression of 729 /// aggregate type. The result is computed into DestPtr. Note that if 730 /// DestPtr is null, the value of the aggregate expression is not needed. 731 void EmitAggExpr(const Expr *E, llvm::Value *DestPtr, bool VolatileDest); 732 733 /// EmitComplexExpr - Emit the computation of the specified expression of 734 /// complex type, returning the result. 735 ComplexPairTy EmitComplexExpr(const Expr *E); 736 737 /// EmitComplexExprIntoAddr - Emit the computation of the specified expression 738 /// of complex type, storing into the specified Value*. 739 void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr, 740 bool DestIsVolatile); 741 742 /// StoreComplexToAddr - Store a complex number into the specified address. 743 void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr, 744 bool DestIsVolatile); 745 /// LoadComplexFromAddr - Load a complex number from the specified address. 746 ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile); 747 748 /// GenerateStaticBlockVarDecl - Return the the static declaration of local 749 /// variable. 750 llvm::GlobalValue * GenerateStaticBlockVarDecl(const VarDecl &D, 751 bool NoInit, 752 const char *Separator, 753 llvm::GlobalValue 754 ::LinkageTypes Linkage); 755 756 /// GenerateStaticCXXBlockVarDecl - Return the static declaration of a local 757 /// variable. Performs initialization of the variable if necessary. 758 llvm::GlobalValue *GenerateStaticCXXBlockVarDecl(const VarDecl &D); 759 760 //===--------------------------------------------------------------------===// 761 // Internal Helpers 762 //===--------------------------------------------------------------------===// 763 764 /// ContainsLabel - Return true if the statement contains a label in it. If 765 /// this statement is not executed normally, it not containing a label means 766 /// that we can just remove the code. 767 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false); 768 769 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 770 /// to a constant, or if it does but contains a label, return 0. If it 771 /// constant folds to 'true' and does not contain a label, return 1, if it 772 /// constant folds to 'false' and does not contain a label, return -1. 773 int ConstantFoldsToSimpleInteger(const Expr *Cond); 774 775 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an 776 /// if statement) to the specified blocks. Based on the condition, this might 777 /// try to simplify the codegen of the conditional based on the branch. 778 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, 779 llvm::BasicBlock *FalseBlock); 780private: 781 782 /// EmitIndirectSwitches - Emit code for all of the switch 783 /// instructions in IndirectSwitches. 784 void EmitIndirectSwitches(); 785 786 void EmitReturnOfRValue(RValue RV, QualType Ty); 787 788 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty 789 /// from function arguments into \arg Dst. See ABIArgInfo::Expand. 790 /// 791 /// \param AI - The first function argument of the expansion. 792 /// \return The argument following the last expanded function 793 /// argument. 794 llvm::Function::arg_iterator 795 ExpandTypeFromArgs(QualType Ty, LValue Dst, 796 llvm::Function::arg_iterator AI); 797 798 /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg 799 /// Ty, into individual arguments on the provided vector \arg Args. See 800 /// ABIArgInfo::Expand. 801 void ExpandTypeToArgs(QualType Ty, RValue Src, 802 llvm::SmallVector<llvm::Value*, 16> &Args); 803 804 llvm::Value* EmitAsmInput(const AsmStmt &S, TargetInfo::ConstraintInfo Info, 805 const Expr *InputExpr, std::string &ConstraintStr); 806 807 /// EmitCleanupBlock - emits a single cleanup block. 808 void EmitCleanupBlock(); 809 810 /// AddBranchFixup - adds a branch instruction to the list of fixups for the 811 /// current cleanup scope. 812 void AddBranchFixup(llvm::BranchInst *BI); 813 814}; 815} // end namespace CodeGen 816} // end namespace clang 817 818#endif 819