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