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