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