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