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 "CGBuilder.h" 18 #include "CGDebugInfo.h" 19 #include "CGValue.h" 20 #include "CodeGenModule.h" 21 #include "CodeGenPGO.h" 22 #include "EHScopeStack.h" 23 #include "clang/AST/CharUnits.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/Type.h" 27 #include "clang/Basic/ABI.h" 28 #include "clang/Basic/CapturedStmt.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Frontend/CodeGenOptions.h" 31 #include "llvm/ADT/ArrayRef.h" 32 #include "llvm/ADT/DenseMap.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/IR/ValueHandle.h" 35 #include "llvm/Support/Debug.h" 36 37 namespace llvm { 38 class BasicBlock; 39 class LLVMContext; 40 class MDNode; 41 class Module; 42 class SwitchInst; 43 class Twine; 44 class Value; 45 class CallSite; 46 } 47 48 namespace clang { 49 class ASTContext; 50 class BlockDecl; 51 class CXXDestructorDecl; 52 class CXXForRangeStmt; 53 class CXXTryStmt; 54 class Decl; 55 class LabelDecl; 56 class EnumConstantDecl; 57 class FunctionDecl; 58 class FunctionProtoType; 59 class LabelStmt; 60 class ObjCContainerDecl; 61 class ObjCInterfaceDecl; 62 class ObjCIvarDecl; 63 class ObjCMethodDecl; 64 class ObjCImplementationDecl; 65 class ObjCPropertyImplDecl; 66 class TargetInfo; 67 class TargetCodeGenInfo; 68 class VarDecl; 69 class ObjCForCollectionStmt; 70 class ObjCAtTryStmt; 71 class ObjCAtThrowStmt; 72 class ObjCAtSynchronizedStmt; 73 class ObjCAutoreleasePoolStmt; 74 75 namespace CodeGen { 76 class CodeGenTypes; 77 class CGFunctionInfo; 78 class CGRecordLayout; 79 class CGBlockInfo; 80 class CGCXXABI; 81 class BlockFlags; 82 class BlockFieldFlags; 83 84 /// The kind of evaluation to perform on values of a particular 85 /// type. Basically, is the code in CGExprScalar, CGExprComplex, or 86 /// CGExprAgg? 87 /// 88 /// TODO: should vectors maybe be split out into their own thing? 89 enum TypeEvaluationKind { 90 TEK_Scalar, 91 TEK_Complex, 92 TEK_Aggregate 93 }; 94 95 /// CodeGenFunction - This class organizes the per-function state that is used 96 /// while generating LLVM code. 97 class CodeGenFunction : public CodeGenTypeCache { 98 CodeGenFunction(const CodeGenFunction &) LLVM_DELETED_FUNCTION; 99 void operator=(const CodeGenFunction &) LLVM_DELETED_FUNCTION; 100 101 friend class CGCXXABI; 102 public: 103 /// A jump destination is an abstract label, branching to which may 104 /// require a jump out through normal cleanups. 105 struct JumpDest { 106 JumpDest() : Block(0), ScopeDepth(), Index(0) {} 107 JumpDest(llvm::BasicBlock *Block, 108 EHScopeStack::stable_iterator Depth, 109 unsigned Index) 110 : Block(Block), ScopeDepth(Depth), Index(Index) {} 111 112 bool isValid() const { return Block != 0; } 113 llvm::BasicBlock *getBlock() const { return Block; } 114 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; } 115 unsigned getDestIndex() const { return Index; } 116 117 // This should be used cautiously. 118 void setScopeDepth(EHScopeStack::stable_iterator depth) { 119 ScopeDepth = depth; 120 } 121 122 private: 123 llvm::BasicBlock *Block; 124 EHScopeStack::stable_iterator ScopeDepth; 125 unsigned Index; 126 }; 127 128 CodeGenModule &CGM; // Per-module state. 129 const TargetInfo &Target; 130 131 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy; 132 CGBuilderTy Builder; 133 134 /// CurFuncDecl - Holds the Decl for the current outermost 135 /// non-closure context. 136 const Decl *CurFuncDecl; 137 /// CurCodeDecl - This is the inner-most code context, which includes blocks. 138 const Decl *CurCodeDecl; 139 const CGFunctionInfo *CurFnInfo; 140 QualType FnRetTy; 141 llvm::Function *CurFn; 142 143 /// CurGD - The GlobalDecl for the current function being compiled. 144 GlobalDecl CurGD; 145 146 /// PrologueCleanupDepth - The cleanup depth enclosing all the 147 /// cleanups associated with the parameters. 148 EHScopeStack::stable_iterator PrologueCleanupDepth; 149 150 /// ReturnBlock - Unified return block. 151 JumpDest ReturnBlock; 152 153 /// ReturnValue - The temporary alloca to hold the return value. This is null 154 /// iff the function has no return value. 155 llvm::Value *ReturnValue; 156 157 /// AllocaInsertPoint - This is an instruction in the entry block before which 158 /// we prefer to insert allocas. 159 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt; 160 161 /// \brief API for captured statement code generation. 162 class CGCapturedStmtInfo { 163 public: 164 explicit CGCapturedStmtInfo(const CapturedStmt &S, 165 CapturedRegionKind K = CR_Default) 166 : Kind(K), ThisValue(0), CXXThisFieldDecl(0) { 167 168 RecordDecl::field_iterator Field = 169 S.getCapturedRecordDecl()->field_begin(); 170 for (CapturedStmt::const_capture_iterator I = S.capture_begin(), 171 E = S.capture_end(); 172 I != E; ++I, ++Field) { 173 if (I->capturesThis()) 174 CXXThisFieldDecl = *Field; 175 else 176 CaptureFields[I->getCapturedVar()] = *Field; 177 } 178 } 179 180 virtual ~CGCapturedStmtInfo(); 181 182 CapturedRegionKind getKind() const { return Kind; } 183 184 void setContextValue(llvm::Value *V) { ThisValue = V; } 185 // \brief Retrieve the value of the context parameter. 186 llvm::Value *getContextValue() const { return ThisValue; } 187 188 /// \brief Lookup the captured field decl for a variable. 189 const FieldDecl *lookup(const VarDecl *VD) const { 190 return CaptureFields.lookup(VD); 191 } 192 193 bool isCXXThisExprCaptured() const { return CXXThisFieldDecl != 0; } 194 FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; } 195 196 /// \brief Emit the captured statement body. 197 virtual void EmitBody(CodeGenFunction &CGF, Stmt *S) { 198 CGF.EmitStmt(S); 199 } 200 201 /// \brief Get the name of the capture helper. 202 virtual StringRef getHelperName() const { return "__captured_stmt"; } 203 204 private: 205 /// \brief The kind of captured statement being generated. 206 CapturedRegionKind Kind; 207 208 /// \brief Keep the map between VarDecl and FieldDecl. 209 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields; 210 211 /// \brief The base address of the captured record, passed in as the first 212 /// argument of the parallel region function. 213 llvm::Value *ThisValue; 214 215 /// \brief Captured 'this' type. 216 FieldDecl *CXXThisFieldDecl; 217 }; 218 CGCapturedStmtInfo *CapturedStmtInfo; 219 220 /// BoundsChecking - Emit run-time bounds checks. Higher values mean 221 /// potentially higher performance penalties. 222 unsigned char BoundsChecking; 223 224 /// \brief Whether any type-checking sanitizers are enabled. If \c false, 225 /// calls to EmitTypeCheck can be skipped. 226 bool SanitizePerformTypeCheck; 227 228 /// \brief Sanitizer options to use for this function. 229 const SanitizerOptions *SanOpts; 230 231 /// In ARC, whether we should autorelease the return value. 232 bool AutoreleaseResult; 233 234 const CodeGen::CGBlockInfo *BlockInfo; 235 llvm::Value *BlockPointer; 236 237 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 238 FieldDecl *LambdaThisCaptureField; 239 240 /// \brief A mapping from NRVO variables to the flags used to indicate 241 /// when the NRVO has been applied to this variable. 242 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags; 243 244 EHScopeStack EHStack; 245 llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack; 246 247 /// Header for data within LifetimeExtendedCleanupStack. 248 struct LifetimeExtendedCleanupHeader { 249 /// The size of the following cleanup object. 250 size_t Size : 29; 251 /// The kind of cleanup to push: a value from the CleanupKind enumeration. 252 unsigned Kind : 3; 253 254 size_t getSize() const { return Size; } 255 CleanupKind getKind() const { return static_cast<CleanupKind>(Kind); } 256 }; 257 258 /// i32s containing the indexes of the cleanup destinations. 259 llvm::AllocaInst *NormalCleanupDest; 260 261 unsigned NextCleanupDestIndex; 262 263 /// FirstBlockInfo - The head of a singly-linked-list of block layouts. 264 CGBlockInfo *FirstBlockInfo; 265 266 /// EHResumeBlock - Unified block containing a call to llvm.eh.resume. 267 llvm::BasicBlock *EHResumeBlock; 268 269 /// The exception slot. All landing pads write the current exception pointer 270 /// into this alloca. 271 llvm::Value *ExceptionSlot; 272 273 /// The selector slot. Under the MandatoryCleanup model, all landing pads 274 /// write the current selector value into this alloca. 275 llvm::AllocaInst *EHSelectorSlot; 276 277 /// Emits a landing pad for the current EH stack. 278 llvm::BasicBlock *EmitLandingPad(); 279 280 llvm::BasicBlock *getInvokeDestImpl(); 281 282 template <class T> 283 typename DominatingValue<T>::saved_type saveValueInCond(T value) { 284 return DominatingValue<T>::save(*this, value); 285 } 286 287 public: 288 /// ObjCEHValueStack - Stack of Objective-C exception values, used for 289 /// rethrows. 290 SmallVector<llvm::Value*, 8> ObjCEHValueStack; 291 292 /// A class controlling the emission of a finally block. 293 class FinallyInfo { 294 /// Where the catchall's edge through the cleanup should go. 295 JumpDest RethrowDest; 296 297 /// A function to call to enter the catch. 298 llvm::Constant *BeginCatchFn; 299 300 /// An i1 variable indicating whether or not the @finally is 301 /// running for an exception. 302 llvm::AllocaInst *ForEHVar; 303 304 /// An i8* variable into which the exception pointer to rethrow 305 /// has been saved. 306 llvm::AllocaInst *SavedExnVar; 307 308 public: 309 void enter(CodeGenFunction &CGF, const Stmt *Finally, 310 llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn, 311 llvm::Constant *rethrowFn); 312 void exit(CodeGenFunction &CGF); 313 }; 314 315 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 316 /// current full-expression. Safe against the possibility that 317 /// we're currently inside a conditionally-evaluated expression. 318 template <class T, class A0> 319 void pushFullExprCleanup(CleanupKind kind, A0 a0) { 320 // If we're not in a conditional branch, or if none of the 321 // arguments requires saving, then use the unconditional cleanup. 322 if (!isInConditionalBranch()) 323 return EHStack.pushCleanup<T>(kind, a0); 324 325 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 326 327 typedef EHScopeStack::ConditionalCleanup1<T, A0> CleanupType; 328 EHStack.pushCleanup<CleanupType>(kind, a0_saved); 329 initFullExprCleanup(); 330 } 331 332 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 333 /// current full-expression. Safe against the possibility that 334 /// we're currently inside a conditionally-evaluated expression. 335 template <class T, class A0, class A1> 336 void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1) { 337 // If we're not in a conditional branch, or if none of the 338 // arguments requires saving, then use the unconditional cleanup. 339 if (!isInConditionalBranch()) 340 return EHStack.pushCleanup<T>(kind, a0, a1); 341 342 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 343 typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1); 344 345 typedef EHScopeStack::ConditionalCleanup2<T, A0, A1> CleanupType; 346 EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved); 347 initFullExprCleanup(); 348 } 349 350 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 351 /// current full-expression. Safe against the possibility that 352 /// we're currently inside a conditionally-evaluated expression. 353 template <class T, class A0, class A1, class A2> 354 void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2) { 355 // If we're not in a conditional branch, or if none of the 356 // arguments requires saving, then use the unconditional cleanup. 357 if (!isInConditionalBranch()) { 358 return EHStack.pushCleanup<T>(kind, a0, a1, a2); 359 } 360 361 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 362 typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1); 363 typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2); 364 365 typedef EHScopeStack::ConditionalCleanup3<T, A0, A1, A2> CleanupType; 366 EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved, a2_saved); 367 initFullExprCleanup(); 368 } 369 370 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 371 /// current full-expression. Safe against the possibility that 372 /// we're currently inside a conditionally-evaluated expression. 373 template <class T, class A0, class A1, class A2, class A3> 374 void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2, A3 a3) { 375 // If we're not in a conditional branch, or if none of the 376 // arguments requires saving, then use the unconditional cleanup. 377 if (!isInConditionalBranch()) { 378 return EHStack.pushCleanup<T>(kind, a0, a1, a2, a3); 379 } 380 381 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 382 typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1); 383 typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2); 384 typename DominatingValue<A3>::saved_type a3_saved = saveValueInCond(a3); 385 386 typedef EHScopeStack::ConditionalCleanup4<T, A0, A1, A2, A3> CleanupType; 387 EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved, 388 a2_saved, a3_saved); 389 initFullExprCleanup(); 390 } 391 392 /// \brief Queue a cleanup to be pushed after finishing the current 393 /// full-expression. 394 template <class T, class A0, class A1, class A2, class A3> 395 void pushCleanupAfterFullExpr(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3) { 396 assert(!isInConditionalBranch() && "can't defer conditional cleanup"); 397 398 LifetimeExtendedCleanupHeader Header = { sizeof(T), Kind }; 399 400 size_t OldSize = LifetimeExtendedCleanupStack.size(); 401 LifetimeExtendedCleanupStack.resize( 402 LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size); 403 404 char *Buffer = &LifetimeExtendedCleanupStack[OldSize]; 405 new (Buffer) LifetimeExtendedCleanupHeader(Header); 406 new (Buffer + sizeof(Header)) T(a0, a1, a2, a3); 407 } 408 409 /// Set up the last cleaup that was pushed as a conditional 410 /// full-expression cleanup. 411 void initFullExprCleanup(); 412 413 /// PushDestructorCleanup - Push a cleanup to call the 414 /// complete-object destructor of an object of the given type at the 415 /// given address. Does nothing if T is not a C++ class type with a 416 /// non-trivial destructor. 417 void PushDestructorCleanup(QualType T, llvm::Value *Addr); 418 419 /// PushDestructorCleanup - Push a cleanup to call the 420 /// complete-object variant of the given destructor on the object at 421 /// the given address. 422 void PushDestructorCleanup(const CXXDestructorDecl *Dtor, 423 llvm::Value *Addr); 424 425 /// PopCleanupBlock - Will pop the cleanup entry on the stack and 426 /// process all branch fixups. 427 void PopCleanupBlock(bool FallThroughIsBranchThrough = false); 428 429 /// DeactivateCleanupBlock - Deactivates the given cleanup block. 430 /// The block cannot be reactivated. Pops it if it's the top of the 431 /// stack. 432 /// 433 /// \param DominatingIP - An instruction which is known to 434 /// dominate the current IP (if set) and which lies along 435 /// all paths of execution between the current IP and the 436 /// the point at which the cleanup comes into scope. 437 void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, 438 llvm::Instruction *DominatingIP); 439 440 /// ActivateCleanupBlock - Activates an initially-inactive cleanup. 441 /// Cannot be used to resurrect a deactivated cleanup. 442 /// 443 /// \param DominatingIP - An instruction which is known to 444 /// dominate the current IP (if set) and which lies along 445 /// all paths of execution between the current IP and the 446 /// the point at which the cleanup comes into scope. 447 void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, 448 llvm::Instruction *DominatingIP); 449 450 /// \brief Enters a new scope for capturing cleanups, all of which 451 /// will be executed once the scope is exited. 452 class RunCleanupsScope { 453 EHScopeStack::stable_iterator CleanupStackDepth; 454 size_t LifetimeExtendedCleanupStackSize; 455 bool OldDidCallStackSave; 456 protected: 457 bool PerformCleanup; 458 private: 459 460 RunCleanupsScope(const RunCleanupsScope &) LLVM_DELETED_FUNCTION; 461 void operator=(const RunCleanupsScope &) LLVM_DELETED_FUNCTION; 462 463 protected: 464 CodeGenFunction& CGF; 465 466 public: 467 /// \brief Enter a new cleanup scope. 468 explicit RunCleanupsScope(CodeGenFunction &CGF) 469 : PerformCleanup(true), CGF(CGF) 470 { 471 CleanupStackDepth = CGF.EHStack.stable_begin(); 472 LifetimeExtendedCleanupStackSize = 473 CGF.LifetimeExtendedCleanupStack.size(); 474 OldDidCallStackSave = CGF.DidCallStackSave; 475 CGF.DidCallStackSave = false; 476 } 477 478 /// \brief Exit this cleanup scope, emitting any accumulated 479 /// cleanups. 480 ~RunCleanupsScope() { 481 if (PerformCleanup) { 482 CGF.DidCallStackSave = OldDidCallStackSave; 483 CGF.PopCleanupBlocks(CleanupStackDepth, 484 LifetimeExtendedCleanupStackSize); 485 } 486 } 487 488 /// \brief Determine whether this scope requires any cleanups. 489 bool requiresCleanups() const { 490 return CGF.EHStack.stable_begin() != CleanupStackDepth; 491 } 492 493 /// \brief Force the emission of cleanups now, instead of waiting 494 /// until this object is destroyed. 495 void ForceCleanup() { 496 assert(PerformCleanup && "Already forced cleanup"); 497 CGF.DidCallStackSave = OldDidCallStackSave; 498 CGF.PopCleanupBlocks(CleanupStackDepth, 499 LifetimeExtendedCleanupStackSize); 500 PerformCleanup = false; 501 } 502 }; 503 504 class LexicalScope: protected RunCleanupsScope { 505 SourceRange Range; 506 SmallVector<const LabelDecl*, 4> Labels; 507 LexicalScope *ParentScope; 508 509 LexicalScope(const LexicalScope &) LLVM_DELETED_FUNCTION; 510 void operator=(const LexicalScope &) LLVM_DELETED_FUNCTION; 511 512 public: 513 /// \brief Enter a new cleanup scope. 514 explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range) 515 : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) { 516 CGF.CurLexicalScope = this; 517 if (CGDebugInfo *DI = CGF.getDebugInfo()) 518 DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin()); 519 } 520 521 void addLabel(const LabelDecl *label) { 522 assert(PerformCleanup && "adding label to dead scope?"); 523 Labels.push_back(label); 524 } 525 526 /// \brief Exit this cleanup scope, emitting any accumulated 527 /// cleanups. 528 ~LexicalScope() { 529 if (CGDebugInfo *DI = CGF.getDebugInfo()) 530 DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd()); 531 532 // If we should perform a cleanup, force them now. Note that 533 // this ends the cleanup scope before rescoping any labels. 534 if (PerformCleanup) ForceCleanup(); 535 } 536 537 /// \brief Force the emission of cleanups now, instead of waiting 538 /// until this object is destroyed. 539 void ForceCleanup() { 540 CGF.CurLexicalScope = ParentScope; 541 RunCleanupsScope::ForceCleanup(); 542 543 if (!Labels.empty()) 544 rescopeLabels(); 545 } 546 547 void rescopeLabels(); 548 }; 549 550 551 /// \brief Takes the old cleanup stack size and emits the cleanup blocks 552 /// that have been added. 553 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize); 554 555 /// \brief Takes the old cleanup stack size and emits the cleanup blocks 556 /// that have been added, then adds all lifetime-extended cleanups from 557 /// the given position to the stack. 558 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize, 559 size_t OldLifetimeExtendedStackSize); 560 561 void ResolveBranchFixups(llvm::BasicBlock *Target); 562 563 /// The given basic block lies in the current EH scope, but may be a 564 /// target of a potentially scope-crossing jump; get a stable handle 565 /// to which we can perform this jump later. 566 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) { 567 return JumpDest(Target, 568 EHStack.getInnermostNormalCleanup(), 569 NextCleanupDestIndex++); 570 } 571 572 /// The given basic block lies in the current EH scope, but may be a 573 /// target of a potentially scope-crossing jump; get a stable handle 574 /// to which we can perform this jump later. 575 JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) { 576 return getJumpDestInCurrentScope(createBasicBlock(Name)); 577 } 578 579 /// EmitBranchThroughCleanup - Emit a branch from the current insert 580 /// block through the normal cleanup handling code (if any) and then 581 /// on to \arg Dest. 582 void EmitBranchThroughCleanup(JumpDest Dest); 583 584 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the 585 /// specified destination obviously has no cleanups to run. 'false' is always 586 /// a conservatively correct answer for this method. 587 bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const; 588 589 /// popCatchScope - Pops the catch scope at the top of the EHScope 590 /// stack, emitting any required code (other than the catch handlers 591 /// themselves). 592 void popCatchScope(); 593 594 llvm::BasicBlock *getEHResumeBlock(bool isCleanup); 595 llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope); 596 597 /// An object to manage conditionally-evaluated expressions. 598 class ConditionalEvaluation { 599 llvm::BasicBlock *StartBB; 600 601 public: 602 ConditionalEvaluation(CodeGenFunction &CGF) 603 : StartBB(CGF.Builder.GetInsertBlock()) {} 604 605 void begin(CodeGenFunction &CGF) { 606 assert(CGF.OutermostConditional != this); 607 if (!CGF.OutermostConditional) 608 CGF.OutermostConditional = this; 609 } 610 611 void end(CodeGenFunction &CGF) { 612 assert(CGF.OutermostConditional != 0); 613 if (CGF.OutermostConditional == this) 614 CGF.OutermostConditional = 0; 615 } 616 617 /// Returns a block which will be executed prior to each 618 /// evaluation of the conditional code. 619 llvm::BasicBlock *getStartingBlock() const { 620 return StartBB; 621 } 622 }; 623 624 /// isInConditionalBranch - Return true if we're currently emitting 625 /// one branch or the other of a conditional expression. 626 bool isInConditionalBranch() const { return OutermostConditional != 0; } 627 628 void setBeforeOutermostConditional(llvm::Value *value, llvm::Value *addr) { 629 assert(isInConditionalBranch()); 630 llvm::BasicBlock *block = OutermostConditional->getStartingBlock(); 631 new llvm::StoreInst(value, addr, &block->back()); 632 } 633 634 /// An RAII object to record that we're evaluating a statement 635 /// expression. 636 class StmtExprEvaluation { 637 CodeGenFunction &CGF; 638 639 /// We have to save the outermost conditional: cleanups in a 640 /// statement expression aren't conditional just because the 641 /// StmtExpr is. 642 ConditionalEvaluation *SavedOutermostConditional; 643 644 public: 645 StmtExprEvaluation(CodeGenFunction &CGF) 646 : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) { 647 CGF.OutermostConditional = 0; 648 } 649 650 ~StmtExprEvaluation() { 651 CGF.OutermostConditional = SavedOutermostConditional; 652 CGF.EnsureInsertPoint(); 653 } 654 }; 655 656 /// An object which temporarily prevents a value from being 657 /// destroyed by aggressive peephole optimizations that assume that 658 /// all uses of a value have been realized in the IR. 659 class PeepholeProtection { 660 llvm::Instruction *Inst; 661 friend class CodeGenFunction; 662 663 public: 664 PeepholeProtection() : Inst(0) {} 665 }; 666 667 /// A non-RAII class containing all the information about a bound 668 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for 669 /// this which makes individual mappings very simple; using this 670 /// class directly is useful when you have a variable number of 671 /// opaque values or don't want the RAII functionality for some 672 /// reason. 673 class OpaqueValueMappingData { 674 const OpaqueValueExpr *OpaqueValue; 675 bool BoundLValue; 676 CodeGenFunction::PeepholeProtection Protection; 677 678 OpaqueValueMappingData(const OpaqueValueExpr *ov, 679 bool boundLValue) 680 : OpaqueValue(ov), BoundLValue(boundLValue) {} 681 public: 682 OpaqueValueMappingData() : OpaqueValue(0) {} 683 684 static bool shouldBindAsLValue(const Expr *expr) { 685 // gl-values should be bound as l-values for obvious reasons. 686 // Records should be bound as l-values because IR generation 687 // always keeps them in memory. Expressions of function type 688 // act exactly like l-values but are formally required to be 689 // r-values in C. 690 return expr->isGLValue() || 691 expr->getType()->isFunctionType() || 692 hasAggregateEvaluationKind(expr->getType()); 693 } 694 695 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 696 const OpaqueValueExpr *ov, 697 const Expr *e) { 698 if (shouldBindAsLValue(ov)) 699 return bind(CGF, ov, CGF.EmitLValue(e)); 700 return bind(CGF, ov, CGF.EmitAnyExpr(e)); 701 } 702 703 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 704 const OpaqueValueExpr *ov, 705 const LValue &lv) { 706 assert(shouldBindAsLValue(ov)); 707 CGF.OpaqueLValues.insert(std::make_pair(ov, lv)); 708 return OpaqueValueMappingData(ov, true); 709 } 710 711 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 712 const OpaqueValueExpr *ov, 713 const RValue &rv) { 714 assert(!shouldBindAsLValue(ov)); 715 CGF.OpaqueRValues.insert(std::make_pair(ov, rv)); 716 717 OpaqueValueMappingData data(ov, false); 718 719 // Work around an extremely aggressive peephole optimization in 720 // EmitScalarConversion which assumes that all other uses of a 721 // value are extant. 722 data.Protection = CGF.protectFromPeepholes(rv); 723 724 return data; 725 } 726 727 bool isValid() const { return OpaqueValue != 0; } 728 void clear() { OpaqueValue = 0; } 729 730 void unbind(CodeGenFunction &CGF) { 731 assert(OpaqueValue && "no data to unbind!"); 732 733 if (BoundLValue) { 734 CGF.OpaqueLValues.erase(OpaqueValue); 735 } else { 736 CGF.OpaqueRValues.erase(OpaqueValue); 737 CGF.unprotectFromPeepholes(Protection); 738 } 739 } 740 }; 741 742 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr. 743 class OpaqueValueMapping { 744 CodeGenFunction &CGF; 745 OpaqueValueMappingData Data; 746 747 public: 748 static bool shouldBindAsLValue(const Expr *expr) { 749 return OpaqueValueMappingData::shouldBindAsLValue(expr); 750 } 751 752 /// Build the opaque value mapping for the given conditional 753 /// operator if it's the GNU ?: extension. This is a common 754 /// enough pattern that the convenience operator is really 755 /// helpful. 756 /// 757 OpaqueValueMapping(CodeGenFunction &CGF, 758 const AbstractConditionalOperator *op) : CGF(CGF) { 759 if (isa<ConditionalOperator>(op)) 760 // Leave Data empty. 761 return; 762 763 const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op); 764 Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(), 765 e->getCommon()); 766 } 767 768 OpaqueValueMapping(CodeGenFunction &CGF, 769 const OpaqueValueExpr *opaqueValue, 770 LValue lvalue) 771 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) { 772 } 773 774 OpaqueValueMapping(CodeGenFunction &CGF, 775 const OpaqueValueExpr *opaqueValue, 776 RValue rvalue) 777 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) { 778 } 779 780 void pop() { 781 Data.unbind(CGF); 782 Data.clear(); 783 } 784 785 ~OpaqueValueMapping() { 786 if (Data.isValid()) Data.unbind(CGF); 787 } 788 }; 789 790 /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field 791 /// number that holds the value. 792 unsigned getByRefValueLLVMField(const ValueDecl *VD) const; 793 794 /// BuildBlockByrefAddress - Computes address location of the 795 /// variable which is declared as __block. 796 llvm::Value *BuildBlockByrefAddress(llvm::Value *BaseAddr, 797 const VarDecl *V); 798 private: 799 CGDebugInfo *DebugInfo; 800 bool DisableDebugInfo; 801 802 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid 803 /// calling llvm.stacksave for multiple VLAs in the same scope. 804 bool DidCallStackSave; 805 806 /// IndirectBranch - The first time an indirect goto is seen we create a block 807 /// with an indirect branch. Every time we see the address of a label taken, 808 /// we add the label to the indirect goto. Every subsequent indirect goto is 809 /// codegen'd as a jump to the IndirectBranch's basic block. 810 llvm::IndirectBrInst *IndirectBranch; 811 812 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C 813 /// decls. 814 typedef llvm::DenseMap<const Decl*, llvm::Value*> DeclMapTy; 815 DeclMapTy LocalDeclMap; 816 817 /// LabelMap - This keeps track of the LLVM basic block for each C label. 818 llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap; 819 820 // BreakContinueStack - This keeps track of where break and continue 821 // statements should jump to. 822 struct BreakContinue { 823 BreakContinue(JumpDest Break, JumpDest Continue) 824 : BreakBlock(Break), ContinueBlock(Continue) {} 825 826 JumpDest BreakBlock; 827 JumpDest ContinueBlock; 828 }; 829 SmallVector<BreakContinue, 8> BreakContinueStack; 830 831 CodeGenPGO PGO; 832 833 public: 834 /// Get a counter for instrumentation of the region associated with the given 835 /// statement. 836 RegionCounter getPGORegionCounter(const Stmt *S) { 837 return RegionCounter(PGO, S); 838 } 839 private: 840 841 /// SwitchInsn - This is nearest current switch instruction. It is null if 842 /// current context is not in a switch. 843 llvm::SwitchInst *SwitchInsn; 844 /// The branch weights of SwitchInsn when doing instrumentation based PGO. 845 SmallVector<uint64_t, 16> *SwitchWeights; 846 847 /// CaseRangeBlock - This block holds if condition check for last case 848 /// statement range in current switch instruction. 849 llvm::BasicBlock *CaseRangeBlock; 850 851 /// OpaqueLValues - Keeps track of the current set of opaque value 852 /// expressions. 853 llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues; 854 llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues; 855 856 // VLASizeMap - This keeps track of the associated size for each VLA type. 857 // We track this by the size expression rather than the type itself because 858 // in certain situations, like a const qualifier applied to an VLA typedef, 859 // multiple VLA types can share the same size expression. 860 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we 861 // enter/leave scopes. 862 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap; 863 864 /// A block containing a single 'unreachable' instruction. Created 865 /// lazily by getUnreachableBlock(). 866 llvm::BasicBlock *UnreachableBlock; 867 868 /// Counts of the number return expressions in the function. 869 unsigned NumReturnExprs; 870 871 /// Count the number of simple (constant) return expressions in the function. 872 unsigned NumSimpleReturnExprs; 873 874 /// The last regular (non-return) debug location (breakpoint) in the function. 875 SourceLocation LastStopPoint; 876 877 public: 878 /// A scope within which we are constructing the fields of an object which 879 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use 880 /// if we need to evaluate a CXXDefaultInitExpr within the evaluation. 881 class FieldConstructionScope { 882 public: 883 FieldConstructionScope(CodeGenFunction &CGF, llvm::Value *This) 884 : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) { 885 CGF.CXXDefaultInitExprThis = This; 886 } 887 ~FieldConstructionScope() { 888 CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis; 889 } 890 891 private: 892 CodeGenFunction &CGF; 893 llvm::Value *OldCXXDefaultInitExprThis; 894 }; 895 896 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this' 897 /// is overridden to be the object under construction. 898 class CXXDefaultInitExprScope { 899 public: 900 CXXDefaultInitExprScope(CodeGenFunction &CGF) 901 : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue) { 902 CGF.CXXThisValue = CGF.CXXDefaultInitExprThis; 903 } 904 ~CXXDefaultInitExprScope() { 905 CGF.CXXThisValue = OldCXXThisValue; 906 } 907 908 public: 909 CodeGenFunction &CGF; 910 llvm::Value *OldCXXThisValue; 911 }; 912 913 private: 914 /// CXXThisDecl - When generating code for a C++ member function, 915 /// this will hold the implicit 'this' declaration. 916 ImplicitParamDecl *CXXABIThisDecl; 917 llvm::Value *CXXABIThisValue; 918 llvm::Value *CXXThisValue; 919 920 /// The value of 'this' to use when evaluating CXXDefaultInitExprs within 921 /// this expression. 922 llvm::Value *CXXDefaultInitExprThis; 923 924 /// CXXStructorImplicitParamDecl - When generating code for a constructor or 925 /// destructor, this will hold the implicit argument (e.g. VTT). 926 ImplicitParamDecl *CXXStructorImplicitParamDecl; 927 llvm::Value *CXXStructorImplicitParamValue; 928 929 /// OutermostConditional - Points to the outermost active 930 /// conditional control. This is used so that we know if a 931 /// temporary should be destroyed conditionally. 932 ConditionalEvaluation *OutermostConditional; 933 934 /// The current lexical scope. 935 LexicalScope *CurLexicalScope; 936 937 /// The current source location that should be used for exception 938 /// handling code. 939 SourceLocation CurEHLocation; 940 941 /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM 942 /// type as well as the field number that contains the actual data. 943 llvm::DenseMap<const ValueDecl *, std::pair<llvm::Type *, 944 unsigned> > ByRefValueInfo; 945 946 llvm::BasicBlock *TerminateLandingPad; 947 llvm::BasicBlock *TerminateHandler; 948 llvm::BasicBlock *TrapBB; 949 950 /// Add a kernel metadata node to the named metadata node 'opencl.kernels'. 951 /// In the kernel metadata node, reference the kernel function and metadata 952 /// nodes for its optional attribute qualifiers (OpenCL 1.1 6.7.2): 953 /// - A node for the vec_type_hint(<type>) qualifier contains string 954 /// "vec_type_hint", an undefined value of the <type> data type, 955 /// and a Boolean that is true if the <type> is integer and signed. 956 /// - A node for the work_group_size_hint(X,Y,Z) qualifier contains string 957 /// "work_group_size_hint", and three 32-bit integers X, Y and Z. 958 /// - A node for the reqd_work_group_size(X,Y,Z) qualifier contains string 959 /// "reqd_work_group_size", and three 32-bit integers X, Y and Z. 960 void EmitOpenCLKernelMetadata(const FunctionDecl *FD, 961 llvm::Function *Fn); 962 963 public: 964 CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false); 965 ~CodeGenFunction(); 966 967 CodeGenTypes &getTypes() const { return CGM.getTypes(); } 968 ASTContext &getContext() const { return CGM.getContext(); } 969 CGDebugInfo *getDebugInfo() { 970 if (DisableDebugInfo) 971 return NULL; 972 return DebugInfo; 973 } 974 void disableDebugInfo() { DisableDebugInfo = true; } 975 void enableDebugInfo() { DisableDebugInfo = false; } 976 977 bool shouldUseFusedARCCalls() { 978 return CGM.getCodeGenOpts().OptimizationLevel == 0; 979 } 980 981 const LangOptions &getLangOpts() const { return CGM.getLangOpts(); } 982 983 /// Returns a pointer to the function's exception object and selector slot, 984 /// which is assigned in every landing pad. 985 llvm::Value *getExceptionSlot(); 986 llvm::Value *getEHSelectorSlot(); 987 988 /// Returns the contents of the function's exception object and selector 989 /// slots. 990 llvm::Value *getExceptionFromSlot(); 991 llvm::Value *getSelectorFromSlot(); 992 993 llvm::Value *getNormalCleanupDestSlot(); 994 995 llvm::BasicBlock *getUnreachableBlock() { 996 if (!UnreachableBlock) { 997 UnreachableBlock = createBasicBlock("unreachable"); 998 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock); 999 } 1000 return UnreachableBlock; 1001 } 1002 1003 llvm::BasicBlock *getInvokeDest() { 1004 if (!EHStack.requiresLandingPad()) return 0; 1005 return getInvokeDestImpl(); 1006 } 1007 1008 const TargetInfo &getTarget() const { return Target; } 1009 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); } 1010 1011 //===--------------------------------------------------------------------===// 1012 // Cleanups 1013 //===--------------------------------------------------------------------===// 1014 1015 typedef void Destroyer(CodeGenFunction &CGF, llvm::Value *addr, QualType ty); 1016 1017 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, 1018 llvm::Value *arrayEndPointer, 1019 QualType elementType, 1020 Destroyer *destroyer); 1021 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, 1022 llvm::Value *arrayEnd, 1023 QualType elementType, 1024 Destroyer *destroyer); 1025 1026 void pushDestroy(QualType::DestructionKind dtorKind, 1027 llvm::Value *addr, QualType type); 1028 void pushEHDestroy(QualType::DestructionKind dtorKind, 1029 llvm::Value *addr, QualType type); 1030 void pushDestroy(CleanupKind kind, llvm::Value *addr, QualType type, 1031 Destroyer *destroyer, bool useEHCleanupForArray); 1032 void pushLifetimeExtendedDestroy(CleanupKind kind, llvm::Value *addr, 1033 QualType type, Destroyer *destroyer, 1034 bool useEHCleanupForArray); 1035 void pushStackRestore(CleanupKind kind, llvm::Value *SPMem); 1036 void emitDestroy(llvm::Value *addr, QualType type, Destroyer *destroyer, 1037 bool useEHCleanupForArray); 1038 llvm::Function *generateDestroyHelper(llvm::Constant *addr, QualType type, 1039 Destroyer *destroyer, 1040 bool useEHCleanupForArray, 1041 const VarDecl *VD); 1042 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end, 1043 QualType type, Destroyer *destroyer, 1044 bool checkZeroLength, bool useEHCleanup); 1045 1046 Destroyer *getDestroyer(QualType::DestructionKind destructionKind); 1047 1048 /// Determines whether an EH cleanup is required to destroy a type 1049 /// with the given destruction kind. 1050 bool needsEHCleanup(QualType::DestructionKind kind) { 1051 switch (kind) { 1052 case QualType::DK_none: 1053 return false; 1054 case QualType::DK_cxx_destructor: 1055 case QualType::DK_objc_weak_lifetime: 1056 return getLangOpts().Exceptions; 1057 case QualType::DK_objc_strong_lifetime: 1058 return getLangOpts().Exceptions && 1059 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions; 1060 } 1061 llvm_unreachable("bad destruction kind"); 1062 } 1063 1064 CleanupKind getCleanupKind(QualType::DestructionKind kind) { 1065 return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup); 1066 } 1067 1068 //===--------------------------------------------------------------------===// 1069 // Objective-C 1070 //===--------------------------------------------------------------------===// 1071 1072 void GenerateObjCMethod(const ObjCMethodDecl *OMD); 1073 1074 void StartObjCMethod(const ObjCMethodDecl *MD, 1075 const ObjCContainerDecl *CD, 1076 SourceLocation StartLoc); 1077 1078 /// GenerateObjCGetter - Synthesize an Objective-C property getter function. 1079 void GenerateObjCGetter(ObjCImplementationDecl *IMP, 1080 const ObjCPropertyImplDecl *PID); 1081 void generateObjCGetterBody(const ObjCImplementationDecl *classImpl, 1082 const ObjCPropertyImplDecl *propImpl, 1083 const ObjCMethodDecl *GetterMothodDecl, 1084 llvm::Constant *AtomicHelperFn); 1085 1086 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, 1087 ObjCMethodDecl *MD, bool ctor); 1088 1089 /// GenerateObjCSetter - Synthesize an Objective-C property setter function 1090 /// for the given property. 1091 void GenerateObjCSetter(ObjCImplementationDecl *IMP, 1092 const ObjCPropertyImplDecl *PID); 1093 void generateObjCSetterBody(const ObjCImplementationDecl *classImpl, 1094 const ObjCPropertyImplDecl *propImpl, 1095 llvm::Constant *AtomicHelperFn); 1096 bool IndirectObjCSetterArg(const CGFunctionInfo &FI); 1097 bool IvarTypeWithAggrGCObjects(QualType Ty); 1098 1099 //===--------------------------------------------------------------------===// 1100 // Block Bits 1101 //===--------------------------------------------------------------------===// 1102 1103 llvm::Value *EmitBlockLiteral(const BlockExpr *); 1104 llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info); 1105 static void destroyBlockInfos(CGBlockInfo *info); 1106 llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *, 1107 const CGBlockInfo &Info, 1108 llvm::StructType *, 1109 llvm::Constant *BlockVarLayout); 1110 1111 llvm::Function *GenerateBlockFunction(GlobalDecl GD, 1112 const CGBlockInfo &Info, 1113 const DeclMapTy &ldm, 1114 bool IsLambdaConversionToBlock); 1115 1116 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo); 1117 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo); 1118 llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction( 1119 const ObjCPropertyImplDecl *PID); 1120 llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction( 1121 const ObjCPropertyImplDecl *PID); 1122 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty); 1123 1124 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags); 1125 1126 class AutoVarEmission; 1127 1128 void emitByrefStructureInit(const AutoVarEmission &emission); 1129 void enterByrefCleanup(const AutoVarEmission &emission); 1130 1131 llvm::Value *LoadBlockStruct() { 1132 assert(BlockPointer && "no block pointer set!"); 1133 return BlockPointer; 1134 } 1135 1136 void AllocateBlockCXXThisPointer(const CXXThisExpr *E); 1137 void AllocateBlockDecl(const DeclRefExpr *E); 1138 llvm::Value *GetAddrOfBlockDecl(const VarDecl *var, bool ByRef); 1139 llvm::Type *BuildByRefType(const VarDecl *var); 1140 1141 void GenerateCode(GlobalDecl GD, llvm::Function *Fn, 1142 const CGFunctionInfo &FnInfo); 1143 void StartFunction(GlobalDecl GD, 1144 QualType RetTy, 1145 llvm::Function *Fn, 1146 const CGFunctionInfo &FnInfo, 1147 const FunctionArgList &Args, 1148 SourceLocation StartLoc); 1149 1150 void EmitConstructorBody(FunctionArgList &Args); 1151 void EmitDestructorBody(FunctionArgList &Args); 1152 void emitImplicitAssignmentOperatorBody(FunctionArgList &Args); 1153 void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body); 1154 void EmitBlockWithFallThrough(llvm::BasicBlock *BB, RegionCounter &Cnt); 1155 1156 void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator, 1157 CallArgList &CallArgs); 1158 void EmitLambdaToBlockPointerBody(FunctionArgList &Args); 1159 void EmitLambdaBlockInvokeBody(); 1160 void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD); 1161 void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD); 1162 1163 /// EmitReturnBlock - Emit the unified return block, trying to avoid its 1164 /// emission when possible. 1165 void EmitReturnBlock(); 1166 1167 /// FinishFunction - Complete IR generation of the current function. It is 1168 /// legal to call this function even if there is no current insertion point. 1169 void FinishFunction(SourceLocation EndLoc=SourceLocation()); 1170 1171 void StartThunk(llvm::Function *Fn, GlobalDecl GD, const CGFunctionInfo &FnInfo); 1172 1173 void EmitCallAndReturnForThunk(GlobalDecl GD, llvm::Value *Callee, 1174 const ThunkInfo *Thunk); 1175 1176 /// GenerateThunk - Generate a thunk for the given method. 1177 void GenerateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, 1178 GlobalDecl GD, const ThunkInfo &Thunk); 1179 1180 void GenerateVarArgsThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, 1181 GlobalDecl GD, const ThunkInfo &Thunk); 1182 1183 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type, 1184 FunctionArgList &Args); 1185 1186 void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init, 1187 ArrayRef<VarDecl *> ArrayIndexes); 1188 1189 /// InitializeVTablePointer - Initialize the vtable pointer of the given 1190 /// subobject. 1191 /// 1192 void InitializeVTablePointer(BaseSubobject Base, 1193 const CXXRecordDecl *NearestVBase, 1194 CharUnits OffsetFromNearestVBase, 1195 const CXXRecordDecl *VTableClass); 1196 1197 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy; 1198 void InitializeVTablePointers(BaseSubobject Base, 1199 const CXXRecordDecl *NearestVBase, 1200 CharUnits OffsetFromNearestVBase, 1201 bool BaseIsNonVirtualPrimaryBase, 1202 const CXXRecordDecl *VTableClass, 1203 VisitedVirtualBasesSetTy& VBases); 1204 1205 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl); 1206 1207 /// GetVTablePtr - Return the Value of the vtable pointer member pointed 1208 /// to by This. 1209 llvm::Value *GetVTablePtr(llvm::Value *This, llvm::Type *Ty); 1210 1211 1212 /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given 1213 /// expr can be devirtualized. 1214 bool CanDevirtualizeMemberFunctionCall(const Expr *Base, 1215 const CXXMethodDecl *MD); 1216 1217 /// EnterDtorCleanups - Enter the cleanups necessary to complete the 1218 /// given phase of destruction for a destructor. The end result 1219 /// should call destructors on members and base classes in reverse 1220 /// order of their construction. 1221 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type); 1222 1223 /// ShouldInstrumentFunction - Return true if the current function should be 1224 /// instrumented with __cyg_profile_func_* calls 1225 bool ShouldInstrumentFunction(); 1226 1227 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified 1228 /// instrumentation function with the current function and the call site, if 1229 /// function instrumentation is enabled. 1230 void EmitFunctionInstrumentation(const char *Fn); 1231 1232 /// EmitMCountInstrumentation - Emit call to .mcount. 1233 void EmitMCountInstrumentation(); 1234 1235 /// EmitFunctionProlog - Emit the target specific LLVM code to load the 1236 /// arguments for the given function. This is also responsible for naming the 1237 /// LLVM function arguments. 1238 void EmitFunctionProlog(const CGFunctionInfo &FI, 1239 llvm::Function *Fn, 1240 const FunctionArgList &Args); 1241 1242 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the 1243 /// given temporary. 1244 void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc, 1245 SourceLocation EndLoc); 1246 1247 /// EmitStartEHSpec - Emit the start of the exception spec. 1248 void EmitStartEHSpec(const Decl *D); 1249 1250 /// EmitEndEHSpec - Emit the end of the exception spec. 1251 void EmitEndEHSpec(const Decl *D); 1252 1253 /// getTerminateLandingPad - Return a landing pad that just calls terminate. 1254 llvm::BasicBlock *getTerminateLandingPad(); 1255 1256 /// getTerminateHandler - Return a handler (not a landing pad, just 1257 /// a catch handler) that just calls terminate. This is used when 1258 /// a terminate scope encloses a try. 1259 llvm::BasicBlock *getTerminateHandler(); 1260 1261 llvm::Type *ConvertTypeForMem(QualType T); 1262 llvm::Type *ConvertType(QualType T); 1263 llvm::Type *ConvertType(const TypeDecl *T) { 1264 return ConvertType(getContext().getTypeDeclType(T)); 1265 } 1266 1267 /// LoadObjCSelf - Load the value of self. This function is only valid while 1268 /// generating code for an Objective-C method. 1269 llvm::Value *LoadObjCSelf(); 1270 1271 /// TypeOfSelfObject - Return type of object that this self represents. 1272 QualType TypeOfSelfObject(); 1273 1274 /// hasAggregateLLVMType - Return true if the specified AST type will map into 1275 /// an aggregate LLVM type or is void. 1276 static TypeEvaluationKind getEvaluationKind(QualType T); 1277 1278 static bool hasScalarEvaluationKind(QualType T) { 1279 return getEvaluationKind(T) == TEK_Scalar; 1280 } 1281 1282 static bool hasAggregateEvaluationKind(QualType T) { 1283 return getEvaluationKind(T) == TEK_Aggregate; 1284 } 1285 1286 /// createBasicBlock - Create an LLVM basic block. 1287 llvm::BasicBlock *createBasicBlock(const Twine &name = "", 1288 llvm::Function *parent = 0, 1289 llvm::BasicBlock *before = 0) { 1290 #ifdef NDEBUG 1291 return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before); 1292 #else 1293 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before); 1294 #endif 1295 } 1296 1297 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified 1298 /// label maps to. 1299 JumpDest getJumpDestForLabel(const LabelDecl *S); 1300 1301 /// SimplifyForwardingBlocks - If the given basic block is only a branch to 1302 /// another basic block, simplify it. This assumes that no other code could 1303 /// potentially reference the basic block. 1304 void SimplifyForwardingBlocks(llvm::BasicBlock *BB); 1305 1306 /// EmitBlock - Emit the given block \arg BB and set it as the insert point, 1307 /// adding a fall-through branch from the current insert block if 1308 /// necessary. It is legal to call this function even if there is no current 1309 /// insertion point. 1310 /// 1311 /// IsFinished - If true, indicates that the caller has finished emitting 1312 /// branches to the given block and does not expect to emit code into it. This 1313 /// means the block can be ignored if it is unreachable. 1314 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false); 1315 1316 /// EmitBlockAfterUses - Emit the given block somewhere hopefully 1317 /// near its uses, and leave the insertion point in it. 1318 void EmitBlockAfterUses(llvm::BasicBlock *BB); 1319 1320 /// EmitBranch - Emit a branch to the specified basic block from the current 1321 /// insert block, taking care to avoid creation of branches from dummy 1322 /// blocks. It is legal to call this function even if there is no current 1323 /// insertion point. 1324 /// 1325 /// This function clears the current insertion point. The caller should follow 1326 /// calls to this function with calls to Emit*Block prior to generation new 1327 /// code. 1328 void EmitBranch(llvm::BasicBlock *Block); 1329 1330 /// HaveInsertPoint - True if an insertion point is defined. If not, this 1331 /// indicates that the current code being emitted is unreachable. 1332 bool HaveInsertPoint() const { 1333 return Builder.GetInsertBlock() != 0; 1334 } 1335 1336 /// EnsureInsertPoint - Ensure that an insertion point is defined so that 1337 /// emitted IR has a place to go. Note that by definition, if this function 1338 /// creates a block then that block is unreachable; callers may do better to 1339 /// detect when no insertion point is defined and simply skip IR generation. 1340 void EnsureInsertPoint() { 1341 if (!HaveInsertPoint()) 1342 EmitBlock(createBasicBlock()); 1343 } 1344 1345 /// ErrorUnsupported - Print out an error that codegen doesn't support the 1346 /// specified stmt yet. 1347 void ErrorUnsupported(const Stmt *S, const char *Type); 1348 1349 //===--------------------------------------------------------------------===// 1350 // Helpers 1351 //===--------------------------------------------------------------------===// 1352 1353 LValue MakeAddrLValue(llvm::Value *V, QualType T, 1354 CharUnits Alignment = CharUnits()) { 1355 return LValue::MakeAddr(V, T, Alignment, getContext(), 1356 CGM.getTBAAInfo(T)); 1357 } 1358 1359 LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) { 1360 CharUnits Alignment; 1361 if (!T->isIncompleteType()) 1362 Alignment = getContext().getTypeAlignInChars(T); 1363 return LValue::MakeAddr(V, T, Alignment, getContext(), 1364 CGM.getTBAAInfo(T)); 1365 } 1366 1367 /// CreateTempAlloca - This creates a alloca and inserts it into the entry 1368 /// block. The caller is responsible for setting an appropriate alignment on 1369 /// the alloca. 1370 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty, 1371 const Twine &Name = "tmp"); 1372 1373 /// InitTempAlloca - Provide an initial value for the given alloca. 1374 void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value); 1375 1376 /// CreateIRTemp - Create a temporary IR object of the given type, with 1377 /// appropriate alignment. This routine should only be used when an temporary 1378 /// value needs to be stored into an alloca (for example, to avoid explicit 1379 /// PHI construction), but the type is the IR type, not the type appropriate 1380 /// for storing in memory. 1381 llvm::AllocaInst *CreateIRTemp(QualType T, const Twine &Name = "tmp"); 1382 1383 /// CreateMemTemp - Create a temporary memory object of the given type, with 1384 /// appropriate alignment. 1385 llvm::AllocaInst *CreateMemTemp(QualType T, const Twine &Name = "tmp"); 1386 1387 /// CreateAggTemp - Create a temporary memory object for the given 1388 /// aggregate type. 1389 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") { 1390 CharUnits Alignment = getContext().getTypeAlignInChars(T); 1391 return AggValueSlot::forAddr(CreateMemTemp(T, Name), Alignment, 1392 T.getQualifiers(), 1393 AggValueSlot::IsNotDestructed, 1394 AggValueSlot::DoesNotNeedGCBarriers, 1395 AggValueSlot::IsNotAliased); 1396 } 1397 1398 /// CreateInAllocaTmp - Create a temporary memory object for the given 1399 /// aggregate type. 1400 AggValueSlot CreateInAllocaTmp(QualType T, const Twine &Name = "inalloca"); 1401 1402 /// Emit a cast to void* in the appropriate address space. 1403 llvm::Value *EmitCastToVoidPtr(llvm::Value *value); 1404 1405 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 1406 /// expression and compare the result against zero, returning an Int1Ty value. 1407 llvm::Value *EvaluateExprAsBool(const Expr *E); 1408 1409 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result. 1410 void EmitIgnoredExpr(const Expr *E); 1411 1412 /// EmitAnyExpr - Emit code to compute the specified expression which can have 1413 /// any type. The result is returned as an RValue struct. If this is an 1414 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where 1415 /// the result should be returned. 1416 /// 1417 /// \param ignoreResult True if the resulting value isn't used. 1418 RValue EmitAnyExpr(const Expr *E, 1419 AggValueSlot aggSlot = AggValueSlot::ignored(), 1420 bool ignoreResult = false); 1421 1422 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address 1423 // or the value of the expression, depending on how va_list is defined. 1424 llvm::Value *EmitVAListRef(const Expr *E); 1425 1426 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will 1427 /// always be accessible even if no aggregate location is provided. 1428 RValue EmitAnyExprToTemp(const Expr *E); 1429 1430 /// EmitAnyExprToMem - Emits the code necessary to evaluate an 1431 /// arbitrary expression into the given memory location. 1432 void EmitAnyExprToMem(const Expr *E, llvm::Value *Location, 1433 Qualifiers Quals, bool IsInitializer); 1434 1435 /// EmitExprAsInit - Emits the code necessary to initialize a 1436 /// location in memory with the given initializer. 1437 void EmitExprAsInit(const Expr *init, const ValueDecl *D, 1438 LValue lvalue, bool capturedByInit); 1439 1440 /// hasVolatileMember - returns true if aggregate type has a volatile 1441 /// member. 1442 bool hasVolatileMember(QualType T) { 1443 if (const RecordType *RT = T->getAs<RecordType>()) { 1444 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl()); 1445 return RD->hasVolatileMember(); 1446 } 1447 return false; 1448 } 1449 /// EmitAggregateCopy - Emit an aggregate assignment. 1450 /// 1451 /// The difference to EmitAggregateCopy is that tail padding is not copied. 1452 /// This is required for correctness when assigning non-POD structures in C++. 1453 void EmitAggregateAssign(llvm::Value *DestPtr, llvm::Value *SrcPtr, 1454 QualType EltTy) { 1455 bool IsVolatile = hasVolatileMember(EltTy); 1456 EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, CharUnits::Zero(), 1457 true); 1458 } 1459 1460 /// EmitAggregateCopy - Emit an aggregate copy. 1461 /// 1462 /// \param isVolatile - True iff either the source or the destination is 1463 /// volatile. 1464 /// \param isAssignment - If false, allow padding to be copied. This often 1465 /// yields more efficient. 1466 void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr, 1467 QualType EltTy, bool isVolatile=false, 1468 CharUnits Alignment = CharUnits::Zero(), 1469 bool isAssignment = false); 1470 1471 /// StartBlock - Start new block named N. If insert block is a dummy block 1472 /// then reuse it. 1473 void StartBlock(const char *N); 1474 1475 /// GetAddrOfLocalVar - Return the address of a local variable. 1476 llvm::Value *GetAddrOfLocalVar(const VarDecl *VD) { 1477 llvm::Value *Res = LocalDeclMap[VD]; 1478 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!"); 1479 return Res; 1480 } 1481 1482 /// getOpaqueLValueMapping - Given an opaque value expression (which 1483 /// must be mapped to an l-value), return its mapping. 1484 const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) { 1485 assert(OpaqueValueMapping::shouldBindAsLValue(e)); 1486 1487 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator 1488 it = OpaqueLValues.find(e); 1489 assert(it != OpaqueLValues.end() && "no mapping for opaque value!"); 1490 return it->second; 1491 } 1492 1493 /// getOpaqueRValueMapping - Given an opaque value expression (which 1494 /// must be mapped to an r-value), return its mapping. 1495 const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) { 1496 assert(!OpaqueValueMapping::shouldBindAsLValue(e)); 1497 1498 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator 1499 it = OpaqueRValues.find(e); 1500 assert(it != OpaqueRValues.end() && "no mapping for opaque value!"); 1501 return it->second; 1502 } 1503 1504 /// getAccessedFieldNo - Given an encoded value and a result number, return 1505 /// the input field number being accessed. 1506 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts); 1507 1508 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L); 1509 llvm::BasicBlock *GetIndirectGotoBlock(); 1510 1511 /// EmitNullInitialization - Generate code to set a value of the given type to 1512 /// null, If the type contains data member pointers, they will be initialized 1513 /// to -1 in accordance with the Itanium C++ ABI. 1514 void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty); 1515 1516 // EmitVAArg - Generate code to get an argument from the passed in pointer 1517 // and update it accordingly. The return value is a pointer to the argument. 1518 // FIXME: We should be able to get rid of this method and use the va_arg 1519 // instruction in LLVM instead once it works well enough. 1520 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty); 1521 1522 /// emitArrayLength - Compute the length of an array, even if it's a 1523 /// VLA, and drill down to the base element type. 1524 llvm::Value *emitArrayLength(const ArrayType *arrayType, 1525 QualType &baseType, 1526 llvm::Value *&addr); 1527 1528 /// EmitVLASize - Capture all the sizes for the VLA expressions in 1529 /// the given variably-modified type and store them in the VLASizeMap. 1530 /// 1531 /// This function can be called with a null (unreachable) insert point. 1532 void EmitVariablyModifiedType(QualType Ty); 1533 1534 /// getVLASize - Returns an LLVM value that corresponds to the size, 1535 /// in non-variably-sized elements, of a variable length array type, 1536 /// plus that largest non-variably-sized element type. Assumes that 1537 /// the type has already been emitted with EmitVariablyModifiedType. 1538 std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla); 1539 std::pair<llvm::Value*,QualType> getVLASize(QualType vla); 1540 1541 /// LoadCXXThis - Load the value of 'this'. This function is only valid while 1542 /// generating code for an C++ member function. 1543 llvm::Value *LoadCXXThis() { 1544 assert(CXXThisValue && "no 'this' value for this function"); 1545 return CXXThisValue; 1546 } 1547 1548 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have 1549 /// virtual bases. 1550 // FIXME: Every place that calls LoadCXXVTT is something 1551 // that needs to be abstracted properly. 1552 llvm::Value *LoadCXXVTT() { 1553 assert(CXXStructorImplicitParamValue && "no VTT value for this function"); 1554 return CXXStructorImplicitParamValue; 1555 } 1556 1557 /// LoadCXXStructorImplicitParam - Load the implicit parameter 1558 /// for a constructor/destructor. 1559 llvm::Value *LoadCXXStructorImplicitParam() { 1560 assert(CXXStructorImplicitParamValue && 1561 "no implicit argument value for this function"); 1562 return CXXStructorImplicitParamValue; 1563 } 1564 1565 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a 1566 /// complete class to the given direct base. 1567 llvm::Value * 1568 GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value, 1569 const CXXRecordDecl *Derived, 1570 const CXXRecordDecl *Base, 1571 bool BaseIsVirtual); 1572 1573 /// GetAddressOfBaseClass - This function will add the necessary delta to the 1574 /// load of 'this' and returns address of the base class. 1575 llvm::Value *GetAddressOfBaseClass(llvm::Value *Value, 1576 const CXXRecordDecl *Derived, 1577 CastExpr::path_const_iterator PathBegin, 1578 CastExpr::path_const_iterator PathEnd, 1579 bool NullCheckValue); 1580 1581 llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value, 1582 const CXXRecordDecl *Derived, 1583 CastExpr::path_const_iterator PathBegin, 1584 CastExpr::path_const_iterator PathEnd, 1585 bool NullCheckValue); 1586 1587 /// GetVTTParameter - Return the VTT parameter that should be passed to a 1588 /// base constructor/destructor with virtual bases. 1589 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move 1590 /// to ItaniumCXXABI.cpp together with all the references to VTT. 1591 llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase, 1592 bool Delegating); 1593 1594 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, 1595 CXXCtorType CtorType, 1596 const FunctionArgList &Args, 1597 SourceLocation Loc); 1598 // It's important not to confuse this and the previous function. Delegating 1599 // constructors are the C++0x feature. The constructor delegate optimization 1600 // is used to reduce duplication in the base and complete consturctors where 1601 // they are substantially the same. 1602 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor, 1603 const FunctionArgList &Args); 1604 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 1605 bool ForVirtualBase, bool Delegating, 1606 llvm::Value *This, 1607 CallExpr::const_arg_iterator ArgBeg, 1608 CallExpr::const_arg_iterator ArgEnd); 1609 1610 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, 1611 llvm::Value *This, llvm::Value *Src, 1612 CallExpr::const_arg_iterator ArgBeg, 1613 CallExpr::const_arg_iterator ArgEnd); 1614 1615 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 1616 const ConstantArrayType *ArrayTy, 1617 llvm::Value *ArrayPtr, 1618 CallExpr::const_arg_iterator ArgBeg, 1619 CallExpr::const_arg_iterator ArgEnd, 1620 bool ZeroInitialization = false); 1621 1622 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 1623 llvm::Value *NumElements, 1624 llvm::Value *ArrayPtr, 1625 CallExpr::const_arg_iterator ArgBeg, 1626 CallExpr::const_arg_iterator ArgEnd, 1627 bool ZeroInitialization = false); 1628 1629 static Destroyer destroyCXXObject; 1630 1631 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, 1632 bool ForVirtualBase, bool Delegating, 1633 llvm::Value *This); 1634 1635 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType, 1636 llvm::Value *NewPtr, llvm::Value *NumElements); 1637 1638 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType, 1639 llvm::Value *Ptr); 1640 1641 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E); 1642 void EmitCXXDeleteExpr(const CXXDeleteExpr *E); 1643 1644 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr, 1645 QualType DeleteTy); 1646 1647 llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E); 1648 llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE); 1649 llvm::Value* EmitCXXUuidofExpr(const CXXUuidofExpr *E); 1650 1651 /// \brief Situations in which we might emit a check for the suitability of a 1652 /// pointer or glvalue. 1653 enum TypeCheckKind { 1654 /// Checking the operand of a load. Must be suitably sized and aligned. 1655 TCK_Load, 1656 /// Checking the destination of a store. Must be suitably sized and aligned. 1657 TCK_Store, 1658 /// Checking the bound value in a reference binding. Must be suitably sized 1659 /// and aligned, but is not required to refer to an object (until the 1660 /// reference is used), per core issue 453. 1661 TCK_ReferenceBinding, 1662 /// Checking the object expression in a non-static data member access. Must 1663 /// be an object within its lifetime. 1664 TCK_MemberAccess, 1665 /// Checking the 'this' pointer for a call to a non-static member function. 1666 /// Must be an object within its lifetime. 1667 TCK_MemberCall, 1668 /// Checking the 'this' pointer for a constructor call. 1669 TCK_ConstructorCall, 1670 /// Checking the operand of a static_cast to a derived pointer type. Must be 1671 /// null or an object within its lifetime. 1672 TCK_DowncastPointer, 1673 /// Checking the operand of a static_cast to a derived reference type. Must 1674 /// be an object within its lifetime. 1675 TCK_DowncastReference 1676 }; 1677 1678 /// \brief Emit a check that \p V is the address of storage of the 1679 /// appropriate size and alignment for an object of type \p Type. 1680 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V, 1681 QualType Type, CharUnits Alignment = CharUnits::Zero()); 1682 1683 /// \brief Emit a check that \p Base points into an array object, which 1684 /// we can access at index \p Index. \p Accessed should be \c false if we 1685 /// this expression is used as an lvalue, for instance in "&Arr[Idx]". 1686 void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index, 1687 QualType IndexType, bool Accessed); 1688 1689 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 1690 bool isInc, bool isPre); 1691 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, 1692 bool isInc, bool isPre); 1693 //===--------------------------------------------------------------------===// 1694 // Declaration Emission 1695 //===--------------------------------------------------------------------===// 1696 1697 /// EmitDecl - Emit a declaration. 1698 /// 1699 /// This function can be called with a null (unreachable) insert point. 1700 void EmitDecl(const Decl &D); 1701 1702 /// EmitVarDecl - Emit a local variable declaration. 1703 /// 1704 /// This function can be called with a null (unreachable) insert point. 1705 void EmitVarDecl(const VarDecl &D); 1706 1707 void EmitScalarInit(const Expr *init, const ValueDecl *D, 1708 LValue lvalue, bool capturedByInit); 1709 void EmitScalarInit(llvm::Value *init, LValue lvalue); 1710 1711 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D, 1712 llvm::Value *Address); 1713 1714 /// EmitAutoVarDecl - Emit an auto variable declaration. 1715 /// 1716 /// This function can be called with a null (unreachable) insert point. 1717 void EmitAutoVarDecl(const VarDecl &D); 1718 1719 class AutoVarEmission { 1720 friend class CodeGenFunction; 1721 1722 const VarDecl *Variable; 1723 1724 /// The alignment of the variable. 1725 CharUnits Alignment; 1726 1727 /// The address of the alloca. Null if the variable was emitted 1728 /// as a global constant. 1729 llvm::Value *Address; 1730 1731 llvm::Value *NRVOFlag; 1732 1733 /// True if the variable is a __block variable. 1734 bool IsByRef; 1735 1736 /// True if the variable is of aggregate type and has a constant 1737 /// initializer. 1738 bool IsConstantAggregate; 1739 1740 /// Non-null if we should use lifetime annotations. 1741 llvm::Value *SizeForLifetimeMarkers; 1742 1743 struct Invalid {}; 1744 AutoVarEmission(Invalid) : Variable(0) {} 1745 1746 AutoVarEmission(const VarDecl &variable) 1747 : Variable(&variable), Address(0), NRVOFlag(0), 1748 IsByRef(false), IsConstantAggregate(false), 1749 SizeForLifetimeMarkers(0) {} 1750 1751 bool wasEmittedAsGlobal() const { return Address == 0; } 1752 1753 public: 1754 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); } 1755 1756 bool useLifetimeMarkers() const { return SizeForLifetimeMarkers != 0; } 1757 llvm::Value *getSizeForLifetimeMarkers() const { 1758 assert(useLifetimeMarkers()); 1759 return SizeForLifetimeMarkers; 1760 } 1761 1762 /// Returns the raw, allocated address, which is not necessarily 1763 /// the address of the object itself. 1764 llvm::Value *getAllocatedAddress() const { 1765 return Address; 1766 } 1767 1768 /// Returns the address of the object within this declaration. 1769 /// Note that this does not chase the forwarding pointer for 1770 /// __block decls. 1771 llvm::Value *getObjectAddress(CodeGenFunction &CGF) const { 1772 if (!IsByRef) return Address; 1773 1774 return CGF.Builder.CreateStructGEP(Address, 1775 CGF.getByRefValueLLVMField(Variable), 1776 Variable->getNameAsString()); 1777 } 1778 }; 1779 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var); 1780 void EmitAutoVarInit(const AutoVarEmission &emission); 1781 void EmitAutoVarCleanups(const AutoVarEmission &emission); 1782 void emitAutoVarTypeCleanup(const AutoVarEmission &emission, 1783 QualType::DestructionKind dtorKind); 1784 1785 void EmitStaticVarDecl(const VarDecl &D, 1786 llvm::GlobalValue::LinkageTypes Linkage); 1787 1788 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl. 1789 void EmitParmDecl(const VarDecl &D, llvm::Value *Arg, bool ArgIsPointer, 1790 unsigned ArgNo); 1791 1792 /// protectFromPeepholes - Protect a value that we're intending to 1793 /// store to the side, but which will probably be used later, from 1794 /// aggressive peepholing optimizations that might delete it. 1795 /// 1796 /// Pass the result to unprotectFromPeepholes to declare that 1797 /// protection is no longer required. 1798 /// 1799 /// There's no particular reason why this shouldn't apply to 1800 /// l-values, it's just that no existing peepholes work on pointers. 1801 PeepholeProtection protectFromPeepholes(RValue rvalue); 1802 void unprotectFromPeepholes(PeepholeProtection protection); 1803 1804 //===--------------------------------------------------------------------===// 1805 // Statement Emission 1806 //===--------------------------------------------------------------------===// 1807 1808 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info. 1809 void EmitStopPoint(const Stmt *S); 1810 1811 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call 1812 /// this function even if there is no current insertion point. 1813 /// 1814 /// This function may clear the current insertion point; callers should use 1815 /// EnsureInsertPoint if they wish to subsequently generate code without first 1816 /// calling EmitBlock, EmitBranch, or EmitStmt. 1817 void EmitStmt(const Stmt *S); 1818 1819 /// EmitSimpleStmt - Try to emit a "simple" statement which does not 1820 /// necessarily require an insertion point or debug information; typically 1821 /// because the statement amounts to a jump or a container of other 1822 /// statements. 1823 /// 1824 /// \return True if the statement was handled. 1825 bool EmitSimpleStmt(const Stmt *S); 1826 1827 llvm::Value *EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false, 1828 AggValueSlot AVS = AggValueSlot::ignored()); 1829 llvm::Value *EmitCompoundStmtWithoutScope(const CompoundStmt &S, 1830 bool GetLast = false, 1831 AggValueSlot AVS = 1832 AggValueSlot::ignored()); 1833 1834 /// EmitLabel - Emit the block for the given label. It is legal to call this 1835 /// function even if there is no current insertion point. 1836 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt. 1837 1838 void EmitLabelStmt(const LabelStmt &S); 1839 void EmitAttributedStmt(const AttributedStmt &S); 1840 void EmitGotoStmt(const GotoStmt &S); 1841 void EmitIndirectGotoStmt(const IndirectGotoStmt &S); 1842 void EmitIfStmt(const IfStmt &S); 1843 void EmitWhileStmt(const WhileStmt &S); 1844 void EmitDoStmt(const DoStmt &S); 1845 void EmitForStmt(const ForStmt &S); 1846 void EmitReturnStmt(const ReturnStmt &S); 1847 void EmitDeclStmt(const DeclStmt &S); 1848 void EmitBreakStmt(const BreakStmt &S); 1849 void EmitContinueStmt(const ContinueStmt &S); 1850 void EmitSwitchStmt(const SwitchStmt &S); 1851 void EmitDefaultStmt(const DefaultStmt &S); 1852 void EmitCaseStmt(const CaseStmt &S); 1853 void EmitCaseStmtRange(const CaseStmt &S); 1854 void EmitAsmStmt(const AsmStmt &S); 1855 1856 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S); 1857 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S); 1858 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S); 1859 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S); 1860 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S); 1861 1862 llvm::Constant *getUnwindResumeFn(); 1863 llvm::Constant *getUnwindResumeOrRethrowFn(); 1864 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 1865 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 1866 1867 void EmitCXXTryStmt(const CXXTryStmt &S); 1868 void EmitSEHTryStmt(const SEHTryStmt &S); 1869 void EmitCXXForRangeStmt(const CXXForRangeStmt &S); 1870 1871 llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K); 1872 llvm::Function *GenerateCapturedStmtFunction(const CapturedDecl *CD, 1873 const RecordDecl *RD, 1874 SourceLocation Loc); 1875 1876 //===--------------------------------------------------------------------===// 1877 // LValue Expression Emission 1878 //===--------------------------------------------------------------------===// 1879 1880 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type. 1881 RValue GetUndefRValue(QualType Ty); 1882 1883 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E 1884 /// and issue an ErrorUnsupported style diagnostic (using the 1885 /// provided Name). 1886 RValue EmitUnsupportedRValue(const Expr *E, 1887 const char *Name); 1888 1889 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue 1890 /// an ErrorUnsupported style diagnostic (using the provided Name). 1891 LValue EmitUnsupportedLValue(const Expr *E, 1892 const char *Name); 1893 1894 /// EmitLValue - Emit code to compute a designator that specifies the location 1895 /// of the expression. 1896 /// 1897 /// This can return one of two things: a simple address or a bitfield 1898 /// reference. In either case, the LLVM Value* in the LValue structure is 1899 /// guaranteed to be an LLVM pointer type. 1900 /// 1901 /// If this returns a bitfield reference, nothing about the pointee type of 1902 /// the LLVM value is known: For example, it may not be a pointer to an 1903 /// integer. 1904 /// 1905 /// If this returns a normal address, and if the lvalue's C type is fixed 1906 /// size, this method guarantees that the returned pointer type will point to 1907 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a 1908 /// variable length type, this is not possible. 1909 /// 1910 LValue EmitLValue(const Expr *E); 1911 1912 /// \brief Same as EmitLValue but additionally we generate checking code to 1913 /// guard against undefined behavior. This is only suitable when we know 1914 /// that the address will be used to access the object. 1915 LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK); 1916 1917 RValue convertTempToRValue(llvm::Value *addr, QualType type, 1918 SourceLocation Loc); 1919 1920 void EmitAtomicInit(Expr *E, LValue lvalue); 1921 1922 RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc, 1923 AggValueSlot slot = AggValueSlot::ignored()); 1924 1925 void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit); 1926 1927 /// EmitToMemory - Change a scalar value from its value 1928 /// representation to its in-memory representation. 1929 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty); 1930 1931 /// EmitFromMemory - Change a scalar value from its memory 1932 /// representation to its value representation. 1933 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty); 1934 1935 /// EmitLoadOfScalar - Load a scalar value from an address, taking 1936 /// care to appropriately convert from the memory representation to 1937 /// the LLVM value representation. 1938 llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile, 1939 unsigned Alignment, QualType Ty, 1940 SourceLocation Loc, 1941 llvm::MDNode *TBAAInfo = 0, 1942 QualType TBAABaseTy = QualType(), 1943 uint64_t TBAAOffset = 0); 1944 1945 /// EmitLoadOfScalar - Load a scalar value from an address, taking 1946 /// care to appropriately convert from the memory representation to 1947 /// the LLVM value representation. The l-value must be a simple 1948 /// l-value. 1949 llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc); 1950 1951 /// EmitStoreOfScalar - Store a scalar value to an address, taking 1952 /// care to appropriately convert from the memory representation to 1953 /// the LLVM value representation. 1954 void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr, 1955 bool Volatile, unsigned Alignment, QualType Ty, 1956 llvm::MDNode *TBAAInfo = 0, bool isInit = false, 1957 QualType TBAABaseTy = QualType(), 1958 uint64_t TBAAOffset = 0); 1959 1960 /// EmitStoreOfScalar - Store a scalar value to an address, taking 1961 /// care to appropriately convert from the memory representation to 1962 /// the LLVM value representation. The l-value must be a simple 1963 /// l-value. The isInit flag indicates whether this is an initialization. 1964 /// If so, atomic qualifiers are ignored and the store is always non-atomic. 1965 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false); 1966 1967 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, 1968 /// this method emits the address of the lvalue, then loads the result as an 1969 /// rvalue, returning the rvalue. 1970 RValue EmitLoadOfLValue(LValue V, SourceLocation Loc); 1971 RValue EmitLoadOfExtVectorElementLValue(LValue V); 1972 RValue EmitLoadOfBitfieldLValue(LValue LV); 1973 1974 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 1975 /// lvalue, where both are guaranteed to the have the same type, and that type 1976 /// is 'Ty'. 1977 void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false); 1978 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst); 1979 1980 /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints 1981 /// as EmitStoreThroughLValue. 1982 /// 1983 /// \param Result [out] - If non-null, this will be set to a Value* for the 1984 /// bit-field contents after the store, appropriate for use as the result of 1985 /// an assignment to the bit-field. 1986 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 1987 llvm::Value **Result=0); 1988 1989 /// Emit an l-value for an assignment (simple or compound) of complex type. 1990 LValue EmitComplexAssignmentLValue(const BinaryOperator *E); 1991 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E); 1992 LValue EmitScalarCompooundAssignWithComplex(const CompoundAssignOperator *E, 1993 llvm::Value *&Result); 1994 1995 // Note: only available for agg return types 1996 LValue EmitBinaryOperatorLValue(const BinaryOperator *E); 1997 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E); 1998 // Note: only available for agg return types 1999 LValue EmitCallExprLValue(const CallExpr *E); 2000 // Note: only available for agg return types 2001 LValue EmitVAArgExprLValue(const VAArgExpr *E); 2002 LValue EmitDeclRefLValue(const DeclRefExpr *E); 2003 LValue EmitStringLiteralLValue(const StringLiteral *E); 2004 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E); 2005 LValue EmitPredefinedLValue(const PredefinedExpr *E); 2006 LValue EmitUnaryOpLValue(const UnaryOperator *E); 2007 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E, 2008 bool Accessed = false); 2009 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E); 2010 LValue EmitMemberExpr(const MemberExpr *E); 2011 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E); 2012 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E); 2013 LValue EmitInitListLValue(const InitListExpr *E); 2014 LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E); 2015 LValue EmitCastLValue(const CastExpr *E); 2016 LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 2017 LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e); 2018 2019 RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc); 2020 2021 class ConstantEmission { 2022 llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference; 2023 ConstantEmission(llvm::Constant *C, bool isReference) 2024 : ValueAndIsReference(C, isReference) {} 2025 public: 2026 ConstantEmission() {} 2027 static ConstantEmission forReference(llvm::Constant *C) { 2028 return ConstantEmission(C, true); 2029 } 2030 static ConstantEmission forValue(llvm::Constant *C) { 2031 return ConstantEmission(C, false); 2032 } 2033 2034 LLVM_EXPLICIT operator bool() const { return ValueAndIsReference.getOpaqueValue() != 0; } 2035 2036 bool isReference() const { return ValueAndIsReference.getInt(); } 2037 LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const { 2038 assert(isReference()); 2039 return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(), 2040 refExpr->getType()); 2041 } 2042 2043 llvm::Constant *getValue() const { 2044 assert(!isReference()); 2045 return ValueAndIsReference.getPointer(); 2046 } 2047 }; 2048 2049 ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr); 2050 2051 RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, 2052 AggValueSlot slot = AggValueSlot::ignored()); 2053 LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e); 2054 2055 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface, 2056 const ObjCIvarDecl *Ivar); 2057 LValue EmitLValueForField(LValue Base, const FieldDecl* Field); 2058 LValue EmitLValueForLambdaField(const FieldDecl *Field); 2059 2060 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that 2061 /// if the Field is a reference, this will return the address of the reference 2062 /// and not the address of the value stored in the reference. 2063 LValue EmitLValueForFieldInitialization(LValue Base, 2064 const FieldDecl* Field); 2065 2066 LValue EmitLValueForIvar(QualType ObjectTy, 2067 llvm::Value* Base, const ObjCIvarDecl *Ivar, 2068 unsigned CVRQualifiers); 2069 2070 LValue EmitCXXConstructLValue(const CXXConstructExpr *E); 2071 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E); 2072 LValue EmitLambdaLValue(const LambdaExpr *E); 2073 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E); 2074 LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E); 2075 2076 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E); 2077 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E); 2078 LValue EmitStmtExprLValue(const StmtExpr *E); 2079 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E); 2080 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E); 2081 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::Constant *Init); 2082 2083 //===--------------------------------------------------------------------===// 2084 // Scalar Expression Emission 2085 //===--------------------------------------------------------------------===// 2086 2087 /// EmitCall - Generate a call of the given function, expecting the given 2088 /// result type, and using the given argument list which specifies both the 2089 /// LLVM arguments and the types they were derived from. 2090 /// 2091 /// \param TargetDecl - If given, the decl of the function in a direct call; 2092 /// used to set attributes on the call (noreturn, etc.). 2093 RValue EmitCall(const CGFunctionInfo &FnInfo, 2094 llvm::Value *Callee, 2095 ReturnValueSlot ReturnValue, 2096 const CallArgList &Args, 2097 const Decl *TargetDecl = 0, 2098 llvm::Instruction **callOrInvoke = 0); 2099 2100 RValue EmitCall(QualType FnType, llvm::Value *Callee, 2101 SourceLocation CallLoc, 2102 ReturnValueSlot ReturnValue, 2103 CallExpr::const_arg_iterator ArgBeg, 2104 CallExpr::const_arg_iterator ArgEnd, 2105 const Decl *TargetDecl = 0); 2106 RValue EmitCallExpr(const CallExpr *E, 2107 ReturnValueSlot ReturnValue = ReturnValueSlot()); 2108 2109 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee, 2110 const Twine &name = ""); 2111 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee, 2112 ArrayRef<llvm::Value*> args, 2113 const Twine &name = ""); 2114 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee, 2115 const Twine &name = ""); 2116 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee, 2117 ArrayRef<llvm::Value*> args, 2118 const Twine &name = ""); 2119 2120 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee, 2121 ArrayRef<llvm::Value *> Args, 2122 const Twine &Name = ""); 2123 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee, 2124 const Twine &Name = ""); 2125 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee, 2126 ArrayRef<llvm::Value*> args, 2127 const Twine &name = ""); 2128 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee, 2129 const Twine &name = ""); 2130 void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee, 2131 ArrayRef<llvm::Value*> args); 2132 2133 llvm::Value *BuildAppleKextVirtualCall(const CXXMethodDecl *MD, 2134 NestedNameSpecifier *Qual, 2135 llvm::Type *Ty); 2136 2137 llvm::Value *BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD, 2138 CXXDtorType Type, 2139 const CXXRecordDecl *RD); 2140 2141 RValue EmitCXXMemberCall(const CXXMethodDecl *MD, 2142 SourceLocation CallLoc, 2143 llvm::Value *Callee, 2144 ReturnValueSlot ReturnValue, 2145 llvm::Value *This, 2146 llvm::Value *ImplicitParam, 2147 QualType ImplicitParamTy, 2148 CallExpr::const_arg_iterator ArgBeg, 2149 CallExpr::const_arg_iterator ArgEnd); 2150 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E, 2151 ReturnValueSlot ReturnValue); 2152 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, 2153 ReturnValueSlot ReturnValue); 2154 2155 llvm::Value *EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E, 2156 const CXXMethodDecl *MD, 2157 llvm::Value *This); 2158 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 2159 const CXXMethodDecl *MD, 2160 ReturnValueSlot ReturnValue); 2161 2162 RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, 2163 ReturnValueSlot ReturnValue); 2164 2165 2166 RValue EmitBuiltinExpr(const FunctionDecl *FD, 2167 unsigned BuiltinID, const CallExpr *E); 2168 2169 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue); 2170 2171 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call 2172 /// is unhandled by the current target. 2173 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2174 2175 llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty, 2176 const llvm::CmpInst::Predicate Fp, 2177 const llvm::CmpInst::Predicate Ip, 2178 const llvm::Twine &Name = ""); 2179 llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty); 2180 llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2181 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2182 2183 llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID, 2184 unsigned LLVMIntrinsic, 2185 unsigned AltLLVMIntrinsic, 2186 const char *NameHint, 2187 unsigned Modifier, 2188 const CallExpr *E, 2189 SmallVectorImpl<llvm::Value *> &Ops, 2190 llvm::Value *Align = 0); 2191 llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID, 2192 unsigned Modifier, llvm::Type *ArgTy, 2193 const CallExpr *E); 2194 llvm::Value *EmitNeonCall(llvm::Function *F, 2195 SmallVectorImpl<llvm::Value*> &O, 2196 const char *name, 2197 unsigned shift = 0, bool rightshift = false); 2198 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx); 2199 llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty, 2200 bool negateForRightShift); 2201 llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt, 2202 llvm::Type *Ty, bool usgn, const char *name); 2203 2204 llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops); 2205 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2206 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2207 2208 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E); 2209 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E); 2210 llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E); 2211 llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E); 2212 llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E); 2213 llvm::Value *EmitObjCCollectionLiteral(const Expr *E, 2214 const ObjCMethodDecl *MethodWithObjects); 2215 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E); 2216 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, 2217 ReturnValueSlot Return = ReturnValueSlot()); 2218 2219 /// Retrieves the default cleanup kind for an ARC cleanup. 2220 /// Except under -fobjc-arc-eh, ARC cleanups are normal-only. 2221 CleanupKind getARCCleanupKind() { 2222 return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions 2223 ? NormalAndEHCleanup : NormalCleanup; 2224 } 2225 2226 // ARC primitives. 2227 void EmitARCInitWeak(llvm::Value *value, llvm::Value *addr); 2228 void EmitARCDestroyWeak(llvm::Value *addr); 2229 llvm::Value *EmitARCLoadWeak(llvm::Value *addr); 2230 llvm::Value *EmitARCLoadWeakRetained(llvm::Value *addr); 2231 llvm::Value *EmitARCStoreWeak(llvm::Value *value, llvm::Value *addr, 2232 bool ignored); 2233 void EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src); 2234 void EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src); 2235 llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value); 2236 llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value); 2237 llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value, 2238 bool resultIgnored); 2239 llvm::Value *EmitARCStoreStrongCall(llvm::Value *addr, llvm::Value *value, 2240 bool resultIgnored); 2241 llvm::Value *EmitARCRetain(QualType type, llvm::Value *value); 2242 llvm::Value *EmitARCRetainNonBlock(llvm::Value *value); 2243 llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory); 2244 void EmitARCDestroyStrong(llvm::Value *addr, ARCPreciseLifetime_t precise); 2245 void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise); 2246 llvm::Value *EmitARCAutorelease(llvm::Value *value); 2247 llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value); 2248 llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value); 2249 llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value); 2250 2251 std::pair<LValue,llvm::Value*> 2252 EmitARCStoreAutoreleasing(const BinaryOperator *e); 2253 std::pair<LValue,llvm::Value*> 2254 EmitARCStoreStrong(const BinaryOperator *e, bool ignored); 2255 2256 llvm::Value *EmitObjCThrowOperand(const Expr *expr); 2257 2258 llvm::Value *EmitObjCProduceObject(QualType T, llvm::Value *Ptr); 2259 llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr); 2260 llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr); 2261 2262 llvm::Value *EmitARCExtendBlockObject(const Expr *expr); 2263 llvm::Value *EmitARCRetainScalarExpr(const Expr *expr); 2264 llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr); 2265 2266 void EmitARCIntrinsicUse(llvm::ArrayRef<llvm::Value*> values); 2267 2268 static Destroyer destroyARCStrongImprecise; 2269 static Destroyer destroyARCStrongPrecise; 2270 static Destroyer destroyARCWeak; 2271 2272 void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr); 2273 llvm::Value *EmitObjCAutoreleasePoolPush(); 2274 llvm::Value *EmitObjCMRRAutoreleasePoolPush(); 2275 void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr); 2276 void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr); 2277 2278 /// \brief Emits a reference binding to the passed in expression. 2279 RValue EmitReferenceBindingToExpr(const Expr *E); 2280 2281 //===--------------------------------------------------------------------===// 2282 // Expression Emission 2283 //===--------------------------------------------------------------------===// 2284 2285 // Expressions are broken into three classes: scalar, complex, aggregate. 2286 2287 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM 2288 /// scalar type, returning the result. 2289 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false); 2290 2291 /// EmitScalarConversion - Emit a conversion from the specified type to the 2292 /// specified destination type, both of which are LLVM scalar types. 2293 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy, 2294 QualType DstTy); 2295 2296 /// EmitComplexToScalarConversion - Emit a conversion from the specified 2297 /// complex type to the specified destination type, where the destination type 2298 /// is an LLVM scalar type. 2299 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, 2300 QualType DstTy); 2301 2302 2303 /// EmitAggExpr - Emit the computation of the specified expression 2304 /// of aggregate type. The result is computed into the given slot, 2305 /// which may be null to indicate that the value is not needed. 2306 void EmitAggExpr(const Expr *E, AggValueSlot AS); 2307 2308 /// EmitAggExprToLValue - Emit the computation of the specified expression of 2309 /// aggregate type into a temporary LValue. 2310 LValue EmitAggExprToLValue(const Expr *E); 2311 2312 /// EmitGCMemmoveCollectable - Emit special API for structs with object 2313 /// pointers. 2314 void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr, 2315 QualType Ty); 2316 2317 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object, 2318 /// make sure it survives garbage collection until this point. 2319 void EmitExtendGCLifetime(llvm::Value *object); 2320 2321 /// EmitComplexExpr - Emit the computation of the specified expression of 2322 /// complex type, returning the result. 2323 ComplexPairTy EmitComplexExpr(const Expr *E, 2324 bool IgnoreReal = false, 2325 bool IgnoreImag = false); 2326 2327 /// EmitComplexExprIntoLValue - Emit the given expression of complex 2328 /// type and place its result into the specified l-value. 2329 void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit); 2330 2331 /// EmitStoreOfComplex - Store a complex number into the specified l-value. 2332 void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit); 2333 2334 /// EmitLoadOfComplex - Load a complex number from the specified l-value. 2335 ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc); 2336 2337 /// CreateStaticVarDecl - Create a zero-initialized LLVM global for 2338 /// a static local variable. 2339 llvm::GlobalVariable *CreateStaticVarDecl(const VarDecl &D, 2340 const char *Separator, 2341 llvm::GlobalValue::LinkageTypes Linkage); 2342 2343 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the 2344 /// global variable that has already been created for it. If the initializer 2345 /// has a different type than GV does, this may free GV and return a different 2346 /// one. Otherwise it just returns GV. 2347 llvm::GlobalVariable * 2348 AddInitializerToStaticVarDecl(const VarDecl &D, 2349 llvm::GlobalVariable *GV); 2350 2351 2352 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++ 2353 /// variable with global storage. 2354 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr, 2355 bool PerformInit); 2356 2357 /// Call atexit() with a function that passes the given argument to 2358 /// the given function. 2359 void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn, 2360 llvm::Constant *addr); 2361 2362 /// Emit code in this function to perform a guarded variable 2363 /// initialization. Guarded initializations are used when it's not 2364 /// possible to prove that an initialization will be done exactly 2365 /// once, e.g. with a static local variable or a static data member 2366 /// of a class template. 2367 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr, 2368 bool PerformInit); 2369 2370 /// GenerateCXXGlobalInitFunc - Generates code for initializing global 2371 /// variables. 2372 void GenerateCXXGlobalInitFunc(llvm::Function *Fn, 2373 ArrayRef<llvm::Constant *> Decls, 2374 llvm::GlobalVariable *Guard = 0); 2375 2376 /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global 2377 /// variables. 2378 void GenerateCXXGlobalDtorsFunc(llvm::Function *Fn, 2379 const std::vector<std::pair<llvm::WeakVH, 2380 llvm::Constant*> > &DtorsAndObjects); 2381 2382 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, 2383 const VarDecl *D, 2384 llvm::GlobalVariable *Addr, 2385 bool PerformInit); 2386 2387 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest); 2388 2389 void EmitSynthesizedCXXCopyCtor(llvm::Value *Dest, llvm::Value *Src, 2390 const Expr *Exp); 2391 2392 void enterFullExpression(const ExprWithCleanups *E) { 2393 if (E->getNumObjects() == 0) return; 2394 enterNonTrivialFullExpression(E); 2395 } 2396 void enterNonTrivialFullExpression(const ExprWithCleanups *E); 2397 2398 void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true); 2399 2400 void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest); 2401 2402 RValue EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest = 0); 2403 2404 //===--------------------------------------------------------------------===// 2405 // Annotations Emission 2406 //===--------------------------------------------------------------------===// 2407 2408 /// Emit an annotation call (intrinsic or builtin). 2409 llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn, 2410 llvm::Value *AnnotatedVal, 2411 StringRef AnnotationStr, 2412 SourceLocation Location); 2413 2414 /// Emit local annotations for the local variable V, declared by D. 2415 void EmitVarAnnotations(const VarDecl *D, llvm::Value *V); 2416 2417 /// Emit field annotations for the given field & value. Returns the 2418 /// annotation result. 2419 llvm::Value *EmitFieldAnnotations(const FieldDecl *D, llvm::Value *V); 2420 2421 //===--------------------------------------------------------------------===// 2422 // Internal Helpers 2423 //===--------------------------------------------------------------------===// 2424 2425 /// ContainsLabel - Return true if the statement contains a label in it. If 2426 /// this statement is not executed normally, it not containing a label means 2427 /// that we can just remove the code. 2428 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false); 2429 2430 /// containsBreak - Return true if the statement contains a break out of it. 2431 /// If the statement (recursively) contains a switch or loop with a break 2432 /// inside of it, this is fine. 2433 static bool containsBreak(const Stmt *S); 2434 2435 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 2436 /// to a constant, or if it does but contains a label, return false. If it 2437 /// constant folds return true and set the boolean result in Result. 2438 bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result); 2439 2440 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 2441 /// to a constant, or if it does but contains a label, return false. If it 2442 /// constant folds return true and set the folded value. 2443 bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result); 2444 2445 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an 2446 /// if statement) to the specified blocks. Based on the condition, this might 2447 /// try to simplify the codegen of the conditional based on the branch. 2448 /// TrueCount should be the number of times we expect the condition to 2449 /// evaluate to true based on PGO data. 2450 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, 2451 llvm::BasicBlock *FalseBlock, uint64_t TrueCount); 2452 2453 /// \brief Emit a description of a type in a format suitable for passing to 2454 /// a runtime sanitizer handler. 2455 llvm::Constant *EmitCheckTypeDescriptor(QualType T); 2456 2457 /// \brief Convert a value into a format suitable for passing to a runtime 2458 /// sanitizer handler. 2459 llvm::Value *EmitCheckValue(llvm::Value *V); 2460 2461 /// \brief Emit a description of a source location in a format suitable for 2462 /// passing to a runtime sanitizer handler. 2463 llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc); 2464 2465 /// \brief Specify under what conditions this check can be recovered 2466 enum CheckRecoverableKind { 2467 /// Always terminate program execution if this check fails 2468 CRK_Unrecoverable, 2469 /// Check supports recovering, allows user to specify which 2470 CRK_Recoverable, 2471 /// Runtime conditionally aborts, always need to support recovery. 2472 CRK_AlwaysRecoverable 2473 }; 2474 2475 /// \brief Create a basic block that will call a handler function in a 2476 /// sanitizer runtime with the provided arguments, and create a conditional 2477 /// branch to it. 2478 void EmitCheck(llvm::Value *Checked, StringRef CheckName, 2479 ArrayRef<llvm::Constant *> StaticArgs, 2480 ArrayRef<llvm::Value *> DynamicArgs, 2481 CheckRecoverableKind Recoverable); 2482 2483 /// \brief Create a basic block that will call the trap intrinsic, and emit a 2484 /// conditional branch to it, for the -ftrapv checks. 2485 void EmitTrapCheck(llvm::Value *Checked); 2486 2487 /// EmitCallArg - Emit a single call argument. 2488 void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType); 2489 2490 /// EmitDelegateCallArg - We are performing a delegate call; that 2491 /// is, the current function is delegating to another one. Produce 2492 /// a r-value suitable for passing the given parameter. 2493 void EmitDelegateCallArg(CallArgList &args, const VarDecl *param, 2494 SourceLocation loc); 2495 2496 /// SetFPAccuracy - Set the minimum required accuracy of the given floating 2497 /// point operation, expressed as the maximum relative error in ulp. 2498 void SetFPAccuracy(llvm::Value *Val, float Accuracy); 2499 2500 private: 2501 llvm::MDNode *getRangeForLoadFromType(QualType Ty); 2502 void EmitReturnOfRValue(RValue RV, QualType Ty); 2503 2504 void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New); 2505 2506 llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4> 2507 DeferredReplacements; 2508 2509 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty 2510 /// from function arguments into \arg Dst. See ABIArgInfo::Expand. 2511 /// 2512 /// \param AI - The first function argument of the expansion. 2513 /// \return The argument following the last expanded function 2514 /// argument. 2515 llvm::Function::arg_iterator 2516 ExpandTypeFromArgs(QualType Ty, LValue Dst, 2517 llvm::Function::arg_iterator AI); 2518 2519 /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg 2520 /// Ty, into individual arguments on the provided vector \arg Args. See 2521 /// ABIArgInfo::Expand. 2522 void ExpandTypeToArgs(QualType Ty, RValue Src, 2523 SmallVectorImpl<llvm::Value *> &Args, 2524 llvm::FunctionType *IRFuncTy); 2525 2526 llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info, 2527 const Expr *InputExpr, std::string &ConstraintStr); 2528 2529 llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info, 2530 LValue InputValue, QualType InputType, 2531 std::string &ConstraintStr, 2532 SourceLocation Loc); 2533 2534 public: 2535 /// EmitCallArgs - Emit call arguments for a function. 2536 template <typename T> 2537 void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo, 2538 CallExpr::const_arg_iterator ArgBeg, 2539 CallExpr::const_arg_iterator ArgEnd, 2540 bool ForceColumnInfo = false) { 2541 if (CallArgTypeInfo) { 2542 EmitCallArgs(Args, CallArgTypeInfo->isVariadic(), 2543 CallArgTypeInfo->param_type_begin(), 2544 CallArgTypeInfo->param_type_end(), ArgBeg, ArgEnd, 2545 ForceColumnInfo); 2546 } else { 2547 // T::param_type_iterator might not have a default ctor. 2548 const QualType *NoIter = 0; 2549 EmitCallArgs(Args, /*AllowExtraArguments=*/true, NoIter, NoIter, ArgBeg, 2550 ArgEnd, ForceColumnInfo); 2551 } 2552 } 2553 2554 template<typename ArgTypeIterator> 2555 void EmitCallArgs(CallArgList& Args, 2556 bool AllowExtraArguments, 2557 ArgTypeIterator ArgTypeBeg, 2558 ArgTypeIterator ArgTypeEnd, 2559 CallExpr::const_arg_iterator ArgBeg, 2560 CallExpr::const_arg_iterator ArgEnd, 2561 bool ForceColumnInfo = false) { 2562 SmallVector<QualType, 16> ArgTypes; 2563 CallExpr::const_arg_iterator Arg = ArgBeg; 2564 2565 // First, use the argument types that the type info knows about 2566 for (ArgTypeIterator I = ArgTypeBeg, E = ArgTypeEnd; I != E; ++I, ++Arg) { 2567 assert(Arg != ArgEnd && "Running over edge of argument list!"); 2568 #ifndef NDEBUG 2569 QualType ArgType = *I; 2570 QualType ActualArgType = Arg->getType(); 2571 if (ArgType->isPointerType() && ActualArgType->isPointerType()) { 2572 QualType ActualBaseType = 2573 ActualArgType->getAs<PointerType>()->getPointeeType(); 2574 QualType ArgBaseType = 2575 ArgType->getAs<PointerType>()->getPointeeType(); 2576 if (ArgBaseType->isVariableArrayType()) { 2577 if (const VariableArrayType *VAT = 2578 getContext().getAsVariableArrayType(ActualBaseType)) { 2579 if (!VAT->getSizeExpr()) 2580 ActualArgType = ArgType; 2581 } 2582 } 2583 } 2584 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()). 2585 getTypePtr() == 2586 getContext().getCanonicalType(ActualArgType).getTypePtr() && 2587 "type mismatch in call argument!"); 2588 #endif 2589 ArgTypes.push_back(*I); 2590 } 2591 2592 // Either we've emitted all the call args, or we have a call to variadic 2593 // function or some other call that allows extra arguments. 2594 assert((Arg == ArgEnd || AllowExtraArguments) && 2595 "Extra arguments in non-variadic function!"); 2596 2597 // If we still have any arguments, emit them using the type of the argument. 2598 for (; Arg != ArgEnd; ++Arg) 2599 ArgTypes.push_back(Arg->getType()); 2600 2601 EmitCallArgs(Args, ArgTypes, ArgBeg, ArgEnd, ForceColumnInfo); 2602 } 2603 2604 void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes, 2605 CallExpr::const_arg_iterator ArgBeg, 2606 CallExpr::const_arg_iterator ArgEnd, bool ForceColumnInfo); 2607 2608 private: 2609 const TargetCodeGenInfo &getTargetHooks() const { 2610 return CGM.getTargetCodeGenInfo(); 2611 } 2612 2613 void EmitDeclMetadata(); 2614 2615 CodeGenModule::ByrefHelpers * 2616 buildByrefHelpers(llvm::StructType &byrefType, 2617 const AutoVarEmission &emission); 2618 2619 void AddObjCARCExceptionMetadata(llvm::Instruction *Inst); 2620 2621 /// GetPointeeAlignment - Given an expression with a pointer type, emit the 2622 /// value and compute our best estimate of the alignment of the pointee. 2623 std::pair<llvm::Value*, unsigned> EmitPointerWithAlignment(const Expr *Addr); 2624 }; 2625 2626 /// Helper class with most of the code for saving a value for a 2627 /// conditional expression cleanup. 2628 struct DominatingLLVMValue { 2629 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type; 2630 2631 /// Answer whether the given value needs extra work to be saved. 2632 static bool needsSaving(llvm::Value *value) { 2633 // If it's not an instruction, we don't need to save. 2634 if (!isa<llvm::Instruction>(value)) return false; 2635 2636 // If it's an instruction in the entry block, we don't need to save. 2637 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent(); 2638 return (block != &block->getParent()->getEntryBlock()); 2639 } 2640 2641 /// Try to save the given value. 2642 static saved_type save(CodeGenFunction &CGF, llvm::Value *value) { 2643 if (!needsSaving(value)) return saved_type(value, false); 2644 2645 // Otherwise we need an alloca. 2646 llvm::Value *alloca = 2647 CGF.CreateTempAlloca(value->getType(), "cond-cleanup.save"); 2648 CGF.Builder.CreateStore(value, alloca); 2649 2650 return saved_type(alloca, true); 2651 } 2652 2653 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) { 2654 if (!value.getInt()) return value.getPointer(); 2655 return CGF.Builder.CreateLoad(value.getPointer()); 2656 } 2657 }; 2658 2659 /// A partial specialization of DominatingValue for llvm::Values that 2660 /// might be llvm::Instructions. 2661 template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue { 2662 typedef T *type; 2663 static type restore(CodeGenFunction &CGF, saved_type value) { 2664 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value)); 2665 } 2666 }; 2667 2668 /// A specialization of DominatingValue for RValue. 2669 template <> struct DominatingValue<RValue> { 2670 typedef RValue type; 2671 class saved_type { 2672 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral, 2673 AggregateAddress, ComplexAddress }; 2674 2675 llvm::Value *Value; 2676 Kind K; 2677 saved_type(llvm::Value *v, Kind k) : Value(v), K(k) {} 2678 2679 public: 2680 static bool needsSaving(RValue value); 2681 static saved_type save(CodeGenFunction &CGF, RValue value); 2682 RValue restore(CodeGenFunction &CGF); 2683 2684 // implementations in CGExprCXX.cpp 2685 }; 2686 2687 static bool needsSaving(type value) { 2688 return saved_type::needsSaving(value); 2689 } 2690 static saved_type save(CodeGenFunction &CGF, type value) { 2691 return saved_type::save(CGF, value); 2692 } 2693 static type restore(CodeGenFunction &CGF, saved_type value) { 2694 return value.restore(CGF); 2695 } 2696 }; 2697 2698 } // end namespace CodeGen 2699 } // end namespace clang 2700 2701 #endif 2702