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