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