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 "VarBypassDetector.h" 25 #include "clang/AST/CharUnits.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/Type.h" 30 #include "clang/Basic/ABI.h" 31 #include "clang/Basic/CapturedStmt.h" 32 #include "clang/Basic/OpenMPKinds.h" 33 #include "clang/Basic/TargetInfo.h" 34 #include "clang/Frontend/CodeGenOptions.h" 35 #include "llvm/ADT/ArrayRef.h" 36 #include "llvm/ADT/DenseMap.h" 37 #include "llvm/ADT/SmallVector.h" 38 #include "llvm/IR/ValueHandle.h" 39 #include "llvm/Support/Debug.h" 40 #include "llvm/Transforms/Utils/SanitizerStats.h" 41 42 namespace llvm { 43 class BasicBlock; 44 class LLVMContext; 45 class MDNode; 46 class Module; 47 class SwitchInst; 48 class Twine; 49 class Value; 50 class CallSite; 51 } 52 53 namespace clang { 54 class ASTContext; 55 class BlockDecl; 56 class CXXDestructorDecl; 57 class CXXForRangeStmt; 58 class CXXTryStmt; 59 class Decl; 60 class LabelDecl; 61 class EnumConstantDecl; 62 class FunctionDecl; 63 class FunctionProtoType; 64 class LabelStmt; 65 class ObjCContainerDecl; 66 class ObjCInterfaceDecl; 67 class ObjCIvarDecl; 68 class ObjCMethodDecl; 69 class ObjCImplementationDecl; 70 class ObjCPropertyImplDecl; 71 class TargetInfo; 72 class VarDecl; 73 class ObjCForCollectionStmt; 74 class ObjCAtTryStmt; 75 class ObjCAtThrowStmt; 76 class ObjCAtSynchronizedStmt; 77 class ObjCAutoreleasePoolStmt; 78 79 namespace CodeGen { 80 class CodeGenTypes; 81 class CGCallee; 82 class CGFunctionInfo; 83 class CGRecordLayout; 84 class CGBlockInfo; 85 class CGCXXABI; 86 class BlockByrefHelpers; 87 class BlockByrefInfo; 88 class BlockFlags; 89 class BlockFieldFlags; 90 class RegionCodeGenTy; 91 class TargetCodeGenInfo; 92 struct OMPTaskDataTy; 93 struct CGCoroData; 94 95 /// The kind of evaluation to perform on values of a particular 96 /// type. Basically, is the code in CGExprScalar, CGExprComplex, or 97 /// CGExprAgg? 98 /// 99 /// TODO: should vectors maybe be split out into their own thing? 100 enum TypeEvaluationKind { 101 TEK_Scalar, 102 TEK_Complex, 103 TEK_Aggregate 104 }; 105 106 /// CodeGenFunction - This class organizes the per-function state that is used 107 /// while generating LLVM code. 108 class CodeGenFunction : public CodeGenTypeCache { 109 CodeGenFunction(const CodeGenFunction &) = delete; 110 void operator=(const CodeGenFunction &) = delete; 111 112 friend class CGCXXABI; 113 public: 114 /// A jump destination is an abstract label, branching to which may 115 /// require a jump out through normal cleanups. 116 struct JumpDest { 117 JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {} 118 JumpDest(llvm::BasicBlock *Block, 119 EHScopeStack::stable_iterator Depth, 120 unsigned Index) 121 : Block(Block), ScopeDepth(Depth), Index(Index) {} 122 123 bool isValid() const { return Block != nullptr; } 124 llvm::BasicBlock *getBlock() const { return Block; } 125 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; } 126 unsigned getDestIndex() const { return Index; } 127 128 // This should be used cautiously. 129 void setScopeDepth(EHScopeStack::stable_iterator depth) { 130 ScopeDepth = depth; 131 } 132 133 private: 134 llvm::BasicBlock *Block; 135 EHScopeStack::stable_iterator ScopeDepth; 136 unsigned Index; 137 }; 138 139 CodeGenModule &CGM; // Per-module state. 140 const TargetInfo &Target; 141 142 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy; 143 LoopInfoStack LoopStack; 144 CGBuilderTy Builder; 145 146 // Stores variables for which we can't generate correct lifetime markers 147 // because of jumps. 148 VarBypassDetector Bypasses; 149 150 /// \brief CGBuilder insert helper. This function is called after an 151 /// instruction is created using Builder. 152 void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, 153 llvm::BasicBlock *BB, 154 llvm::BasicBlock::iterator InsertPt) const; 155 156 /// CurFuncDecl - Holds the Decl for the current outermost 157 /// non-closure context. 158 const Decl *CurFuncDecl; 159 /// CurCodeDecl - This is the inner-most code context, which includes blocks. 160 const Decl *CurCodeDecl; 161 const CGFunctionInfo *CurFnInfo; 162 QualType FnRetTy; 163 llvm::Function *CurFn; 164 165 // Holds coroutine data if the current function is a coroutine. We use a 166 // wrapper to manage its lifetime, so that we don't have to define CGCoroData 167 // in this header. 168 struct CGCoroInfo { 169 std::unique_ptr<CGCoroData> Data; 170 CGCoroInfo(); 171 ~CGCoroInfo(); 172 }; 173 CGCoroInfo CurCoro; 174 175 /// CurGD - The GlobalDecl for the current function being compiled. 176 GlobalDecl CurGD; 177 178 /// PrologueCleanupDepth - The cleanup depth enclosing all the 179 /// cleanups associated with the parameters. 180 EHScopeStack::stable_iterator PrologueCleanupDepth; 181 182 /// ReturnBlock - Unified return block. 183 JumpDest ReturnBlock; 184 185 /// ReturnValue - The temporary alloca to hold the return 186 /// value. This is invalid iff the function has no return value. 187 Address ReturnValue; 188 189 /// AllocaInsertPoint - This is an instruction in the entry block before which 190 /// we prefer to insert allocas. 191 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt; 192 193 /// \brief API for captured statement code generation. 194 class CGCapturedStmtInfo { 195 public: 196 explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default) 197 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {} 198 explicit CGCapturedStmtInfo(const CapturedStmt &S, 199 CapturedRegionKind K = CR_Default) 200 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) { 201 202 RecordDecl::field_iterator Field = 203 S.getCapturedRecordDecl()->field_begin(); 204 for (CapturedStmt::const_capture_iterator I = S.capture_begin(), 205 E = S.capture_end(); 206 I != E; ++I, ++Field) { 207 if (I->capturesThis()) 208 CXXThisFieldDecl = *Field; 209 else if (I->capturesVariable()) 210 CaptureFields[I->getCapturedVar()] = *Field; 211 else if (I->capturesVariableByCopy()) 212 CaptureFields[I->getCapturedVar()] = *Field; 213 } 214 } 215 216 virtual ~CGCapturedStmtInfo(); 217 218 CapturedRegionKind getKind() const { return Kind; } 219 220 virtual void setContextValue(llvm::Value *V) { ThisValue = V; } 221 // \brief Retrieve the value of the context parameter. 222 virtual llvm::Value *getContextValue() const { return ThisValue; } 223 224 /// \brief Lookup the captured field decl for a variable. 225 virtual const FieldDecl *lookup(const VarDecl *VD) const { 226 return CaptureFields.lookup(VD); 227 } 228 229 bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; } 230 virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; } 231 232 static bool classof(const CGCapturedStmtInfo *) { 233 return true; 234 } 235 236 /// \brief Emit the captured statement body. 237 virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) { 238 CGF.incrementProfileCounter(S); 239 CGF.EmitStmt(S); 240 } 241 242 /// \brief Get the name of the capture helper. 243 virtual StringRef getHelperName() const { return "__captured_stmt"; } 244 245 private: 246 /// \brief The kind of captured statement being generated. 247 CapturedRegionKind Kind; 248 249 /// \brief Keep the map between VarDecl and FieldDecl. 250 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields; 251 252 /// \brief The base address of the captured record, passed in as the first 253 /// argument of the parallel region function. 254 llvm::Value *ThisValue; 255 256 /// \brief Captured 'this' type. 257 FieldDecl *CXXThisFieldDecl; 258 }; 259 CGCapturedStmtInfo *CapturedStmtInfo; 260 261 /// \brief RAII for correct setting/restoring of CapturedStmtInfo. 262 class CGCapturedStmtRAII { 263 private: 264 CodeGenFunction &CGF; 265 CGCapturedStmtInfo *PrevCapturedStmtInfo; 266 public: 267 CGCapturedStmtRAII(CodeGenFunction &CGF, 268 CGCapturedStmtInfo *NewCapturedStmtInfo) 269 : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) { 270 CGF.CapturedStmtInfo = NewCapturedStmtInfo; 271 } 272 ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; } 273 }; 274 275 /// \brief Sanitizers enabled for this function. 276 SanitizerSet SanOpts; 277 278 /// \brief True if CodeGen currently emits code implementing sanitizer checks. 279 bool IsSanitizerScope; 280 281 /// \brief RAII object to set/unset CodeGenFunction::IsSanitizerScope. 282 class SanitizerScope { 283 CodeGenFunction *CGF; 284 public: 285 SanitizerScope(CodeGenFunction *CGF); 286 ~SanitizerScope(); 287 }; 288 289 /// In C++, whether we are code generating a thunk. This controls whether we 290 /// should emit cleanups. 291 bool CurFuncIsThunk; 292 293 /// In ARC, whether we should autorelease the return value. 294 bool AutoreleaseResult; 295 296 /// Whether we processed a Microsoft-style asm block during CodeGen. These can 297 /// potentially set the return value. 298 bool SawAsmBlock; 299 300 const FunctionDecl *CurSEHParent = nullptr; 301 302 /// True if the current function is an outlined SEH helper. This can be a 303 /// finally block or filter expression. 304 bool IsOutlinedSEHHelper; 305 306 const CodeGen::CGBlockInfo *BlockInfo; 307 llvm::Value *BlockPointer; 308 309 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 310 FieldDecl *LambdaThisCaptureField; 311 312 /// \brief A mapping from NRVO variables to the flags used to indicate 313 /// when the NRVO has been applied to this variable. 314 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags; 315 316 EHScopeStack EHStack; 317 llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack; 318 llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack; 319 320 llvm::Instruction *CurrentFuncletPad = nullptr; 321 322 class CallLifetimeEnd final : public EHScopeStack::Cleanup { 323 llvm::Value *Addr; 324 llvm::Value *Size; 325 326 public: 327 CallLifetimeEnd(Address addr, llvm::Value *size) 328 : Addr(addr.getPointer()), Size(size) {} 329 330 void Emit(CodeGenFunction &CGF, Flags flags) override { 331 CGF.EmitLifetimeEnd(Size, Addr); 332 } 333 }; 334 335 /// Header for data within LifetimeExtendedCleanupStack. 336 struct LifetimeExtendedCleanupHeader { 337 /// The size of the following cleanup object. 338 unsigned Size; 339 /// The kind of cleanup to push: a value from the CleanupKind enumeration. 340 CleanupKind Kind; 341 342 size_t getSize() const { return Size; } 343 CleanupKind getKind() const { return Kind; } 344 }; 345 346 /// i32s containing the indexes of the cleanup destinations. 347 llvm::AllocaInst *NormalCleanupDest; 348 349 unsigned NextCleanupDestIndex; 350 351 /// FirstBlockInfo - The head of a singly-linked-list of block layouts. 352 CGBlockInfo *FirstBlockInfo; 353 354 /// EHResumeBlock - Unified block containing a call to llvm.eh.resume. 355 llvm::BasicBlock *EHResumeBlock; 356 357 /// The exception slot. All landing pads write the current exception pointer 358 /// into this alloca. 359 llvm::Value *ExceptionSlot; 360 361 /// The selector slot. Under the MandatoryCleanup model, all landing pads 362 /// write the current selector value into this alloca. 363 llvm::AllocaInst *EHSelectorSlot; 364 365 /// A stack of exception code slots. Entering an __except block pushes a slot 366 /// on the stack and leaving pops one. The __exception_code() intrinsic loads 367 /// a value from the top of the stack. 368 SmallVector<Address, 1> SEHCodeSlotStack; 369 370 /// Value returned by __exception_info intrinsic. 371 llvm::Value *SEHInfo = nullptr; 372 373 /// Emits a landing pad for the current EH stack. 374 llvm::BasicBlock *EmitLandingPad(); 375 376 llvm::BasicBlock *getInvokeDestImpl(); 377 378 template <class T> 379 typename DominatingValue<T>::saved_type saveValueInCond(T value) { 380 return DominatingValue<T>::save(*this, value); 381 } 382 383 public: 384 /// ObjCEHValueStack - Stack of Objective-C exception values, used for 385 /// rethrows. 386 SmallVector<llvm::Value*, 8> ObjCEHValueStack; 387 388 /// A class controlling the emission of a finally block. 389 class FinallyInfo { 390 /// Where the catchall's edge through the cleanup should go. 391 JumpDest RethrowDest; 392 393 /// A function to call to enter the catch. 394 llvm::Constant *BeginCatchFn; 395 396 /// An i1 variable indicating whether or not the @finally is 397 /// running for an exception. 398 llvm::AllocaInst *ForEHVar; 399 400 /// An i8* variable into which the exception pointer to rethrow 401 /// has been saved. 402 llvm::AllocaInst *SavedExnVar; 403 404 public: 405 void enter(CodeGenFunction &CGF, const Stmt *Finally, 406 llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn, 407 llvm::Constant *rethrowFn); 408 void exit(CodeGenFunction &CGF); 409 }; 410 411 /// Returns true inside SEH __try blocks. 412 bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); } 413 414 /// Returns true while emitting a cleanuppad. 415 bool isCleanupPadScope() const { 416 return CurrentFuncletPad && isa<llvm::CleanupPadInst>(CurrentFuncletPad); 417 } 418 419 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 420 /// current full-expression. Safe against the possibility that 421 /// we're currently inside a conditionally-evaluated expression. 422 template <class T, class... As> 423 void pushFullExprCleanup(CleanupKind kind, As... A) { 424 // If we're not in a conditional branch, or if none of the 425 // arguments requires saving, then use the unconditional cleanup. 426 if (!isInConditionalBranch()) 427 return EHStack.pushCleanup<T>(kind, A...); 428 429 // Stash values in a tuple so we can guarantee the order of saves. 430 typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple; 431 SavedTuple Saved{saveValueInCond(A)...}; 432 433 typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType; 434 EHStack.pushCleanupTuple<CleanupType>(kind, Saved); 435 initFullExprCleanup(); 436 } 437 438 /// \brief Queue a cleanup to be pushed after finishing the current 439 /// full-expression. 440 template <class T, class... As> 441 void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) { 442 assert(!isInConditionalBranch() && "can't defer conditional cleanup"); 443 444 LifetimeExtendedCleanupHeader Header = { sizeof(T), Kind }; 445 446 size_t OldSize = LifetimeExtendedCleanupStack.size(); 447 LifetimeExtendedCleanupStack.resize( 448 LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size); 449 450 static_assert(sizeof(Header) % alignof(T) == 0, 451 "Cleanup will be allocated on misaligned address"); 452 char *Buffer = &LifetimeExtendedCleanupStack[OldSize]; 453 new (Buffer) LifetimeExtendedCleanupHeader(Header); 454 new (Buffer + sizeof(Header)) T(A...); 455 } 456 457 /// Set up the last cleaup that was pushed as a conditional 458 /// full-expression cleanup. 459 void initFullExprCleanup(); 460 461 /// PushDestructorCleanup - Push a cleanup to call the 462 /// complete-object destructor of an object of the given type at the 463 /// given address. Does nothing if T is not a C++ class type with a 464 /// non-trivial destructor. 465 void PushDestructorCleanup(QualType T, Address Addr); 466 467 /// PushDestructorCleanup - Push a cleanup to call the 468 /// complete-object variant of the given destructor on the object at 469 /// the given address. 470 void PushDestructorCleanup(const CXXDestructorDecl *Dtor, Address Addr); 471 472 /// PopCleanupBlock - Will pop the cleanup entry on the stack and 473 /// process all branch fixups. 474 void PopCleanupBlock(bool FallThroughIsBranchThrough = false); 475 476 /// DeactivateCleanupBlock - Deactivates the given cleanup block. 477 /// The block cannot be reactivated. Pops it if it's the top of the 478 /// stack. 479 /// 480 /// \param DominatingIP - An instruction which is known to 481 /// dominate the current IP (if set) and which lies along 482 /// all paths of execution between the current IP and the 483 /// the point at which the cleanup comes into scope. 484 void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, 485 llvm::Instruction *DominatingIP); 486 487 /// ActivateCleanupBlock - Activates an initially-inactive cleanup. 488 /// Cannot be used to resurrect a deactivated cleanup. 489 /// 490 /// \param DominatingIP - An instruction which is known to 491 /// dominate the current IP (if set) and which lies along 492 /// all paths of execution between the current IP and the 493 /// the point at which the cleanup comes into scope. 494 void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, 495 llvm::Instruction *DominatingIP); 496 497 /// \brief Enters a new scope for capturing cleanups, all of which 498 /// will be executed once the scope is exited. 499 class RunCleanupsScope { 500 EHScopeStack::stable_iterator CleanupStackDepth; 501 size_t LifetimeExtendedCleanupStackSize; 502 bool OldDidCallStackSave; 503 protected: 504 bool PerformCleanup; 505 private: 506 507 RunCleanupsScope(const RunCleanupsScope &) = delete; 508 void operator=(const RunCleanupsScope &) = delete; 509 510 protected: 511 CodeGenFunction& CGF; 512 513 public: 514 /// \brief Enter a new cleanup scope. 515 explicit RunCleanupsScope(CodeGenFunction &CGF) 516 : PerformCleanup(true), CGF(CGF) 517 { 518 CleanupStackDepth = CGF.EHStack.stable_begin(); 519 LifetimeExtendedCleanupStackSize = 520 CGF.LifetimeExtendedCleanupStack.size(); 521 OldDidCallStackSave = CGF.DidCallStackSave; 522 CGF.DidCallStackSave = false; 523 } 524 525 /// \brief Exit this cleanup scope, emitting any accumulated 526 /// cleanups. 527 ~RunCleanupsScope() { 528 if (PerformCleanup) { 529 CGF.DidCallStackSave = OldDidCallStackSave; 530 CGF.PopCleanupBlocks(CleanupStackDepth, 531 LifetimeExtendedCleanupStackSize); 532 } 533 } 534 535 /// \brief Determine whether this scope requires any cleanups. 536 bool requiresCleanups() const { 537 return CGF.EHStack.stable_begin() != CleanupStackDepth; 538 } 539 540 /// \brief Force the emission of cleanups now, instead of waiting 541 /// until this object is destroyed. 542 void ForceCleanup() { 543 assert(PerformCleanup && "Already forced cleanup"); 544 CGF.DidCallStackSave = OldDidCallStackSave; 545 CGF.PopCleanupBlocks(CleanupStackDepth, 546 LifetimeExtendedCleanupStackSize); 547 PerformCleanup = false; 548 } 549 }; 550 551 class LexicalScope : public RunCleanupsScope { 552 SourceRange Range; 553 SmallVector<const LabelDecl*, 4> Labels; 554 LexicalScope *ParentScope; 555 556 LexicalScope(const LexicalScope &) = delete; 557 void operator=(const LexicalScope &) = delete; 558 559 public: 560 /// \brief Enter a new cleanup scope. 561 explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range) 562 : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) { 563 CGF.CurLexicalScope = this; 564 if (CGDebugInfo *DI = CGF.getDebugInfo()) 565 DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin()); 566 } 567 568 void addLabel(const LabelDecl *label) { 569 assert(PerformCleanup && "adding label to dead scope?"); 570 Labels.push_back(label); 571 } 572 573 /// \brief Exit this cleanup scope, emitting any accumulated 574 /// cleanups. 575 ~LexicalScope() { 576 if (CGDebugInfo *DI = CGF.getDebugInfo()) 577 DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd()); 578 579 // If we should perform a cleanup, force them now. Note that 580 // this ends the cleanup scope before rescoping any labels. 581 if (PerformCleanup) { 582 ApplyDebugLocation DL(CGF, Range.getEnd()); 583 ForceCleanup(); 584 } 585 } 586 587 /// \brief Force the emission of cleanups now, instead of waiting 588 /// until this object is destroyed. 589 void ForceCleanup() { 590 CGF.CurLexicalScope = ParentScope; 591 RunCleanupsScope::ForceCleanup(); 592 593 if (!Labels.empty()) 594 rescopeLabels(); 595 } 596 597 void rescopeLabels(); 598 }; 599 600 typedef llvm::DenseMap<const Decl *, Address> DeclMapTy; 601 602 /// \brief The scope used to remap some variables as private in the OpenMP 603 /// loop body (or other captured region emitted without outlining), and to 604 /// restore old vars back on exit. 605 class OMPPrivateScope : public RunCleanupsScope { 606 DeclMapTy SavedLocals; 607 DeclMapTy SavedPrivates; 608 609 private: 610 OMPPrivateScope(const OMPPrivateScope &) = delete; 611 void operator=(const OMPPrivateScope &) = delete; 612 613 public: 614 /// \brief Enter a new OpenMP private scope. 615 explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {} 616 617 /// \brief Registers \a LocalVD variable as a private and apply \a 618 /// PrivateGen function for it to generate corresponding private variable. 619 /// \a PrivateGen returns an address of the generated private variable. 620 /// \return true if the variable is registered as private, false if it has 621 /// been privatized already. 622 bool 623 addPrivate(const VarDecl *LocalVD, 624 llvm::function_ref<Address()> PrivateGen) { 625 assert(PerformCleanup && "adding private to dead scope"); 626 627 // Only save it once. 628 if (SavedLocals.count(LocalVD)) return false; 629 630 // Copy the existing local entry to SavedLocals. 631 auto it = CGF.LocalDeclMap.find(LocalVD); 632 if (it != CGF.LocalDeclMap.end()) { 633 SavedLocals.insert({LocalVD, it->second}); 634 } else { 635 SavedLocals.insert({LocalVD, Address::invalid()}); 636 } 637 638 // Generate the private entry. 639 Address Addr = PrivateGen(); 640 QualType VarTy = LocalVD->getType(); 641 if (VarTy->isReferenceType()) { 642 Address Temp = CGF.CreateMemTemp(VarTy); 643 CGF.Builder.CreateStore(Addr.getPointer(), Temp); 644 Addr = Temp; 645 } 646 SavedPrivates.insert({LocalVD, Addr}); 647 648 return true; 649 } 650 651 /// \brief Privatizes local variables previously registered as private. 652 /// Registration is separate from the actual privatization to allow 653 /// initializers use values of the original variables, not the private one. 654 /// This is important, for example, if the private variable is a class 655 /// variable initialized by a constructor that references other private 656 /// variables. But at initialization original variables must be used, not 657 /// private copies. 658 /// \return true if at least one variable was privatized, false otherwise. 659 bool Privatize() { 660 copyInto(SavedPrivates, CGF.LocalDeclMap); 661 SavedPrivates.clear(); 662 return !SavedLocals.empty(); 663 } 664 665 void ForceCleanup() { 666 RunCleanupsScope::ForceCleanup(); 667 copyInto(SavedLocals, CGF.LocalDeclMap); 668 SavedLocals.clear(); 669 } 670 671 /// \brief Exit scope - all the mapped variables are restored. 672 ~OMPPrivateScope() { 673 if (PerformCleanup) 674 ForceCleanup(); 675 } 676 677 /// Checks if the global variable is captured in current function. 678 bool isGlobalVarCaptured(const VarDecl *VD) const { 679 return !VD->isLocalVarDeclOrParm() && CGF.LocalDeclMap.count(VD) > 0; 680 } 681 682 private: 683 /// Copy all the entries in the source map over the corresponding 684 /// entries in the destination, which must exist. 685 static void copyInto(const DeclMapTy &src, DeclMapTy &dest) { 686 for (auto &pair : src) { 687 if (!pair.second.isValid()) { 688 dest.erase(pair.first); 689 continue; 690 } 691 692 auto it = dest.find(pair.first); 693 if (it != dest.end()) { 694 it->second = pair.second; 695 } else { 696 dest.insert(pair); 697 } 698 } 699 } 700 }; 701 702 /// \brief Takes the old cleanup stack size and emits the cleanup blocks 703 /// that have been added. 704 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize); 705 706 /// \brief Takes the old cleanup stack size and emits the cleanup blocks 707 /// that have been added, then adds all lifetime-extended cleanups from 708 /// the given position to the stack. 709 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize, 710 size_t OldLifetimeExtendedStackSize); 711 712 void ResolveBranchFixups(llvm::BasicBlock *Target); 713 714 /// The given basic block lies in the current EH scope, but may be a 715 /// target of a potentially scope-crossing jump; get a stable handle 716 /// to which we can perform this jump later. 717 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) { 718 return JumpDest(Target, 719 EHStack.getInnermostNormalCleanup(), 720 NextCleanupDestIndex++); 721 } 722 723 /// The given basic block lies in the current EH scope, but may be a 724 /// target of a potentially scope-crossing jump; get a stable handle 725 /// to which we can perform this jump later. 726 JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) { 727 return getJumpDestInCurrentScope(createBasicBlock(Name)); 728 } 729 730 /// EmitBranchThroughCleanup - Emit a branch from the current insert 731 /// block through the normal cleanup handling code (if any) and then 732 /// on to \arg Dest. 733 void EmitBranchThroughCleanup(JumpDest Dest); 734 735 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the 736 /// specified destination obviously has no cleanups to run. 'false' is always 737 /// a conservatively correct answer for this method. 738 bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const; 739 740 /// popCatchScope - Pops the catch scope at the top of the EHScope 741 /// stack, emitting any required code (other than the catch handlers 742 /// themselves). 743 void popCatchScope(); 744 745 llvm::BasicBlock *getEHResumeBlock(bool isCleanup); 746 llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope); 747 llvm::BasicBlock *getMSVCDispatchBlock(EHScopeStack::stable_iterator scope); 748 749 /// An object to manage conditionally-evaluated expressions. 750 class ConditionalEvaluation { 751 llvm::BasicBlock *StartBB; 752 753 public: 754 ConditionalEvaluation(CodeGenFunction &CGF) 755 : StartBB(CGF.Builder.GetInsertBlock()) {} 756 757 void begin(CodeGenFunction &CGF) { 758 assert(CGF.OutermostConditional != this); 759 if (!CGF.OutermostConditional) 760 CGF.OutermostConditional = this; 761 } 762 763 void end(CodeGenFunction &CGF) { 764 assert(CGF.OutermostConditional != nullptr); 765 if (CGF.OutermostConditional == this) 766 CGF.OutermostConditional = nullptr; 767 } 768 769 /// Returns a block which will be executed prior to each 770 /// evaluation of the conditional code. 771 llvm::BasicBlock *getStartingBlock() const { 772 return StartBB; 773 } 774 }; 775 776 /// isInConditionalBranch - Return true if we're currently emitting 777 /// one branch or the other of a conditional expression. 778 bool isInConditionalBranch() const { return OutermostConditional != nullptr; } 779 780 void setBeforeOutermostConditional(llvm::Value *value, Address addr) { 781 assert(isInConditionalBranch()); 782 llvm::BasicBlock *block = OutermostConditional->getStartingBlock(); 783 auto store = new llvm::StoreInst(value, addr.getPointer(), &block->back()); 784 store->setAlignment(addr.getAlignment().getQuantity()); 785 } 786 787 /// An RAII object to record that we're evaluating a statement 788 /// expression. 789 class StmtExprEvaluation { 790 CodeGenFunction &CGF; 791 792 /// We have to save the outermost conditional: cleanups in a 793 /// statement expression aren't conditional just because the 794 /// StmtExpr is. 795 ConditionalEvaluation *SavedOutermostConditional; 796 797 public: 798 StmtExprEvaluation(CodeGenFunction &CGF) 799 : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) { 800 CGF.OutermostConditional = nullptr; 801 } 802 803 ~StmtExprEvaluation() { 804 CGF.OutermostConditional = SavedOutermostConditional; 805 CGF.EnsureInsertPoint(); 806 } 807 }; 808 809 /// An object which temporarily prevents a value from being 810 /// destroyed by aggressive peephole optimizations that assume that 811 /// all uses of a value have been realized in the IR. 812 class PeepholeProtection { 813 llvm::Instruction *Inst; 814 friend class CodeGenFunction; 815 816 public: 817 PeepholeProtection() : Inst(nullptr) {} 818 }; 819 820 /// A non-RAII class containing all the information about a bound 821 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for 822 /// this which makes individual mappings very simple; using this 823 /// class directly is useful when you have a variable number of 824 /// opaque values or don't want the RAII functionality for some 825 /// reason. 826 class OpaqueValueMappingData { 827 const OpaqueValueExpr *OpaqueValue; 828 bool BoundLValue; 829 CodeGenFunction::PeepholeProtection Protection; 830 831 OpaqueValueMappingData(const OpaqueValueExpr *ov, 832 bool boundLValue) 833 : OpaqueValue(ov), BoundLValue(boundLValue) {} 834 public: 835 OpaqueValueMappingData() : OpaqueValue(nullptr) {} 836 837 static bool shouldBindAsLValue(const Expr *expr) { 838 // gl-values should be bound as l-values for obvious reasons. 839 // Records should be bound as l-values because IR generation 840 // always keeps them in memory. Expressions of function type 841 // act exactly like l-values but are formally required to be 842 // r-values in C. 843 return expr->isGLValue() || 844 expr->getType()->isFunctionType() || 845 hasAggregateEvaluationKind(expr->getType()); 846 } 847 848 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 849 const OpaqueValueExpr *ov, 850 const Expr *e) { 851 if (shouldBindAsLValue(ov)) 852 return bind(CGF, ov, CGF.EmitLValue(e)); 853 return bind(CGF, ov, CGF.EmitAnyExpr(e)); 854 } 855 856 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 857 const OpaqueValueExpr *ov, 858 const LValue &lv) { 859 assert(shouldBindAsLValue(ov)); 860 CGF.OpaqueLValues.insert(std::make_pair(ov, lv)); 861 return OpaqueValueMappingData(ov, true); 862 } 863 864 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 865 const OpaqueValueExpr *ov, 866 const RValue &rv) { 867 assert(!shouldBindAsLValue(ov)); 868 CGF.OpaqueRValues.insert(std::make_pair(ov, rv)); 869 870 OpaqueValueMappingData data(ov, false); 871 872 // Work around an extremely aggressive peephole optimization in 873 // EmitScalarConversion which assumes that all other uses of a 874 // value are extant. 875 data.Protection = CGF.protectFromPeepholes(rv); 876 877 return data; 878 } 879 880 bool isValid() const { return OpaqueValue != nullptr; } 881 void clear() { OpaqueValue = nullptr; } 882 883 void unbind(CodeGenFunction &CGF) { 884 assert(OpaqueValue && "no data to unbind!"); 885 886 if (BoundLValue) { 887 CGF.OpaqueLValues.erase(OpaqueValue); 888 } else { 889 CGF.OpaqueRValues.erase(OpaqueValue); 890 CGF.unprotectFromPeepholes(Protection); 891 } 892 } 893 }; 894 895 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr. 896 class OpaqueValueMapping { 897 CodeGenFunction &CGF; 898 OpaqueValueMappingData Data; 899 900 public: 901 static bool shouldBindAsLValue(const Expr *expr) { 902 return OpaqueValueMappingData::shouldBindAsLValue(expr); 903 } 904 905 /// Build the opaque value mapping for the given conditional 906 /// operator if it's the GNU ?: extension. This is a common 907 /// enough pattern that the convenience operator is really 908 /// helpful. 909 /// 910 OpaqueValueMapping(CodeGenFunction &CGF, 911 const AbstractConditionalOperator *op) : CGF(CGF) { 912 if (isa<ConditionalOperator>(op)) 913 // Leave Data empty. 914 return; 915 916 const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op); 917 Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(), 918 e->getCommon()); 919 } 920 921 /// Build the opaque value mapping for an OpaqueValueExpr whose source 922 /// expression is set to the expression the OVE represents. 923 OpaqueValueMapping(CodeGenFunction &CGF, const OpaqueValueExpr *OV) 924 : CGF(CGF) { 925 if (OV) { 926 assert(OV->getSourceExpr() && "wrong form of OpaqueValueMapping used " 927 "for OVE with no source expression"); 928 Data = OpaqueValueMappingData::bind(CGF, OV, OV->getSourceExpr()); 929 } 930 } 931 932 OpaqueValueMapping(CodeGenFunction &CGF, 933 const OpaqueValueExpr *opaqueValue, 934 LValue lvalue) 935 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) { 936 } 937 938 OpaqueValueMapping(CodeGenFunction &CGF, 939 const OpaqueValueExpr *opaqueValue, 940 RValue rvalue) 941 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) { 942 } 943 944 void pop() { 945 Data.unbind(CGF); 946 Data.clear(); 947 } 948 949 ~OpaqueValueMapping() { 950 if (Data.isValid()) Data.unbind(CGF); 951 } 952 }; 953 954 private: 955 CGDebugInfo *DebugInfo; 956 bool DisableDebugInfo; 957 958 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid 959 /// calling llvm.stacksave for multiple VLAs in the same scope. 960 bool DidCallStackSave; 961 962 /// IndirectBranch - The first time an indirect goto is seen we create a block 963 /// with an indirect branch. Every time we see the address of a label taken, 964 /// we add the label to the indirect goto. Every subsequent indirect goto is 965 /// codegen'd as a jump to the IndirectBranch's basic block. 966 llvm::IndirectBrInst *IndirectBranch; 967 968 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C 969 /// decls. 970 DeclMapTy LocalDeclMap; 971 972 /// SizeArguments - If a ParmVarDecl had the pass_object_size attribute, this 973 /// will contain a mapping from said ParmVarDecl to its implicit "object_size" 974 /// parameter. 975 llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *, 2> 976 SizeArguments; 977 978 /// Track escaped local variables with auto storage. Used during SEH 979 /// outlining to produce a call to llvm.localescape. 980 llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals; 981 982 /// LabelMap - This keeps track of the LLVM basic block for each C label. 983 llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap; 984 985 // BreakContinueStack - This keeps track of where break and continue 986 // statements should jump to. 987 struct BreakContinue { 988 BreakContinue(JumpDest Break, JumpDest Continue) 989 : BreakBlock(Break), ContinueBlock(Continue) {} 990 991 JumpDest BreakBlock; 992 JumpDest ContinueBlock; 993 }; 994 SmallVector<BreakContinue, 8> BreakContinueStack; 995 996 /// Handles cancellation exit points in OpenMP-related constructs. 997 class OpenMPCancelExitStack { 998 /// Tracks cancellation exit point and join point for cancel-related exit 999 /// and normal exit. 1000 struct CancelExit { 1001 CancelExit() = default; 1002 CancelExit(OpenMPDirectiveKind Kind, JumpDest ExitBlock, 1003 JumpDest ContBlock) 1004 : Kind(Kind), ExitBlock(ExitBlock), ContBlock(ContBlock) {} 1005 OpenMPDirectiveKind Kind = OMPD_unknown; 1006 /// true if the exit block has been emitted already by the special 1007 /// emitExit() call, false if the default codegen is used. 1008 bool HasBeenEmitted = false; 1009 JumpDest ExitBlock; 1010 JumpDest ContBlock; 1011 }; 1012 1013 SmallVector<CancelExit, 8> Stack; 1014 1015 public: 1016 OpenMPCancelExitStack() : Stack(1) {} 1017 ~OpenMPCancelExitStack() = default; 1018 /// Fetches the exit block for the current OpenMP construct. 1019 JumpDest getExitBlock() const { return Stack.back().ExitBlock; } 1020 /// Emits exit block with special codegen procedure specific for the related 1021 /// OpenMP construct + emits code for normal construct cleanup. 1022 void emitExit(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, 1023 const llvm::function_ref<void(CodeGenFunction &)> &CodeGen) { 1024 if (Stack.back().Kind == Kind && getExitBlock().isValid()) { 1025 assert(CGF.getOMPCancelDestination(Kind).isValid()); 1026 assert(CGF.HaveInsertPoint()); 1027 assert(!Stack.back().HasBeenEmitted); 1028 auto IP = CGF.Builder.saveAndClearIP(); 1029 CGF.EmitBlock(Stack.back().ExitBlock.getBlock()); 1030 CodeGen(CGF); 1031 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock); 1032 CGF.Builder.restoreIP(IP); 1033 Stack.back().HasBeenEmitted = true; 1034 } 1035 CodeGen(CGF); 1036 } 1037 /// Enter the cancel supporting \a Kind construct. 1038 /// \param Kind OpenMP directive that supports cancel constructs. 1039 /// \param HasCancel true, if the construct has inner cancel directive, 1040 /// false otherwise. 1041 void enter(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, bool HasCancel) { 1042 Stack.push_back({Kind, 1043 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.exit") 1044 : JumpDest(), 1045 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.cont") 1046 : JumpDest()}); 1047 } 1048 /// Emits default exit point for the cancel construct (if the special one 1049 /// has not be used) + join point for cancel/normal exits. 1050 void exit(CodeGenFunction &CGF) { 1051 if (getExitBlock().isValid()) { 1052 assert(CGF.getOMPCancelDestination(Stack.back().Kind).isValid()); 1053 bool HaveIP = CGF.HaveInsertPoint(); 1054 if (!Stack.back().HasBeenEmitted) { 1055 if (HaveIP) 1056 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock); 1057 CGF.EmitBlock(Stack.back().ExitBlock.getBlock()); 1058 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock); 1059 } 1060 CGF.EmitBlock(Stack.back().ContBlock.getBlock()); 1061 if (!HaveIP) { 1062 CGF.Builder.CreateUnreachable(); 1063 CGF.Builder.ClearInsertionPoint(); 1064 } 1065 } 1066 Stack.pop_back(); 1067 } 1068 }; 1069 OpenMPCancelExitStack OMPCancelStack; 1070 1071 /// Controls insertion of cancellation exit blocks in worksharing constructs. 1072 class OMPCancelStackRAII { 1073 CodeGenFunction &CGF; 1074 1075 public: 1076 OMPCancelStackRAII(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, 1077 bool HasCancel) 1078 : CGF(CGF) { 1079 CGF.OMPCancelStack.enter(CGF, Kind, HasCancel); 1080 } 1081 ~OMPCancelStackRAII() { CGF.OMPCancelStack.exit(CGF); } 1082 }; 1083 1084 CodeGenPGO PGO; 1085 1086 /// Calculate branch weights appropriate for PGO data 1087 llvm::MDNode *createProfileWeights(uint64_t TrueCount, uint64_t FalseCount); 1088 llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights); 1089 llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond, 1090 uint64_t LoopCount); 1091 1092 public: 1093 /// Increment the profiler's counter for the given statement. 1094 void incrementProfileCounter(const Stmt *S) { 1095 if (CGM.getCodeGenOpts().hasProfileClangInstr()) 1096 PGO.emitCounterIncrement(Builder, S); 1097 PGO.setCurrentStmt(S); 1098 } 1099 1100 /// Get the profiler's count for the given statement. 1101 uint64_t getProfileCount(const Stmt *S) { 1102 Optional<uint64_t> Count = PGO.getStmtCount(S); 1103 if (!Count.hasValue()) 1104 return 0; 1105 return *Count; 1106 } 1107 1108 /// Set the profiler's current count. 1109 void setCurrentProfileCount(uint64_t Count) { 1110 PGO.setCurrentRegionCount(Count); 1111 } 1112 1113 /// Get the profiler's current count. This is generally the count for the most 1114 /// recently incremented counter. 1115 uint64_t getCurrentProfileCount() { 1116 return PGO.getCurrentRegionCount(); 1117 } 1118 1119 private: 1120 1121 /// SwitchInsn - This is nearest current switch instruction. It is null if 1122 /// current context is not in a switch. 1123 llvm::SwitchInst *SwitchInsn; 1124 /// The branch weights of SwitchInsn when doing instrumentation based PGO. 1125 SmallVector<uint64_t, 16> *SwitchWeights; 1126 1127 /// CaseRangeBlock - This block holds if condition check for last case 1128 /// statement range in current switch instruction. 1129 llvm::BasicBlock *CaseRangeBlock; 1130 1131 /// OpaqueLValues - Keeps track of the current set of opaque value 1132 /// expressions. 1133 llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues; 1134 llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues; 1135 1136 // VLASizeMap - This keeps track of the associated size for each VLA type. 1137 // We track this by the size expression rather than the type itself because 1138 // in certain situations, like a const qualifier applied to an VLA typedef, 1139 // multiple VLA types can share the same size expression. 1140 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we 1141 // enter/leave scopes. 1142 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap; 1143 1144 /// A block containing a single 'unreachable' instruction. Created 1145 /// lazily by getUnreachableBlock(). 1146 llvm::BasicBlock *UnreachableBlock; 1147 1148 /// Counts of the number return expressions in the function. 1149 unsigned NumReturnExprs; 1150 1151 /// Count the number of simple (constant) return expressions in the function. 1152 unsigned NumSimpleReturnExprs; 1153 1154 /// The last regular (non-return) debug location (breakpoint) in the function. 1155 SourceLocation LastStopPoint; 1156 1157 public: 1158 /// A scope within which we are constructing the fields of an object which 1159 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use 1160 /// if we need to evaluate a CXXDefaultInitExpr within the evaluation. 1161 class FieldConstructionScope { 1162 public: 1163 FieldConstructionScope(CodeGenFunction &CGF, Address This) 1164 : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) { 1165 CGF.CXXDefaultInitExprThis = This; 1166 } 1167 ~FieldConstructionScope() { 1168 CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis; 1169 } 1170 1171 private: 1172 CodeGenFunction &CGF; 1173 Address OldCXXDefaultInitExprThis; 1174 }; 1175 1176 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this' 1177 /// is overridden to be the object under construction. 1178 class CXXDefaultInitExprScope { 1179 public: 1180 CXXDefaultInitExprScope(CodeGenFunction &CGF) 1181 : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue), 1182 OldCXXThisAlignment(CGF.CXXThisAlignment) { 1183 CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer(); 1184 CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment(); 1185 } 1186 ~CXXDefaultInitExprScope() { 1187 CGF.CXXThisValue = OldCXXThisValue; 1188 CGF.CXXThisAlignment = OldCXXThisAlignment; 1189 } 1190 1191 public: 1192 CodeGenFunction &CGF; 1193 llvm::Value *OldCXXThisValue; 1194 CharUnits OldCXXThisAlignment; 1195 }; 1196 1197 /// The scope of an ArrayInitLoopExpr. Within this scope, the value of the 1198 /// current loop index is overridden. 1199 class ArrayInitLoopExprScope { 1200 public: 1201 ArrayInitLoopExprScope(CodeGenFunction &CGF, llvm::Value *Index) 1202 : CGF(CGF), OldArrayInitIndex(CGF.ArrayInitIndex) { 1203 CGF.ArrayInitIndex = Index; 1204 } 1205 ~ArrayInitLoopExprScope() { 1206 CGF.ArrayInitIndex = OldArrayInitIndex; 1207 } 1208 1209 private: 1210 CodeGenFunction &CGF; 1211 llvm::Value *OldArrayInitIndex; 1212 }; 1213 1214 class InlinedInheritingConstructorScope { 1215 public: 1216 InlinedInheritingConstructorScope(CodeGenFunction &CGF, GlobalDecl GD) 1217 : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl), 1218 OldCurCodeDecl(CGF.CurCodeDecl), 1219 OldCXXABIThisDecl(CGF.CXXABIThisDecl), 1220 OldCXXABIThisValue(CGF.CXXABIThisValue), 1221 OldCXXThisValue(CGF.CXXThisValue), 1222 OldCXXABIThisAlignment(CGF.CXXABIThisAlignment), 1223 OldCXXThisAlignment(CGF.CXXThisAlignment), 1224 OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy), 1225 OldCXXInheritedCtorInitExprArgs( 1226 std::move(CGF.CXXInheritedCtorInitExprArgs)) { 1227 CGF.CurGD = GD; 1228 CGF.CurFuncDecl = CGF.CurCodeDecl = 1229 cast<CXXConstructorDecl>(GD.getDecl()); 1230 CGF.CXXABIThisDecl = nullptr; 1231 CGF.CXXABIThisValue = nullptr; 1232 CGF.CXXThisValue = nullptr; 1233 CGF.CXXABIThisAlignment = CharUnits(); 1234 CGF.CXXThisAlignment = CharUnits(); 1235 CGF.ReturnValue = Address::invalid(); 1236 CGF.FnRetTy = QualType(); 1237 CGF.CXXInheritedCtorInitExprArgs.clear(); 1238 } 1239 ~InlinedInheritingConstructorScope() { 1240 CGF.CurGD = OldCurGD; 1241 CGF.CurFuncDecl = OldCurFuncDecl; 1242 CGF.CurCodeDecl = OldCurCodeDecl; 1243 CGF.CXXABIThisDecl = OldCXXABIThisDecl; 1244 CGF.CXXABIThisValue = OldCXXABIThisValue; 1245 CGF.CXXThisValue = OldCXXThisValue; 1246 CGF.CXXABIThisAlignment = OldCXXABIThisAlignment; 1247 CGF.CXXThisAlignment = OldCXXThisAlignment; 1248 CGF.ReturnValue = OldReturnValue; 1249 CGF.FnRetTy = OldFnRetTy; 1250 CGF.CXXInheritedCtorInitExprArgs = 1251 std::move(OldCXXInheritedCtorInitExprArgs); 1252 } 1253 1254 private: 1255 CodeGenFunction &CGF; 1256 GlobalDecl OldCurGD; 1257 const Decl *OldCurFuncDecl; 1258 const Decl *OldCurCodeDecl; 1259 ImplicitParamDecl *OldCXXABIThisDecl; 1260 llvm::Value *OldCXXABIThisValue; 1261 llvm::Value *OldCXXThisValue; 1262 CharUnits OldCXXABIThisAlignment; 1263 CharUnits OldCXXThisAlignment; 1264 Address OldReturnValue; 1265 QualType OldFnRetTy; 1266 CallArgList OldCXXInheritedCtorInitExprArgs; 1267 }; 1268 1269 private: 1270 /// CXXThisDecl - When generating code for a C++ member function, 1271 /// this will hold the implicit 'this' declaration. 1272 ImplicitParamDecl *CXXABIThisDecl; 1273 llvm::Value *CXXABIThisValue; 1274 llvm::Value *CXXThisValue; 1275 CharUnits CXXABIThisAlignment; 1276 CharUnits CXXThisAlignment; 1277 1278 /// The value of 'this' to use when evaluating CXXDefaultInitExprs within 1279 /// this expression. 1280 Address CXXDefaultInitExprThis = Address::invalid(); 1281 1282 /// The current array initialization index when evaluating an 1283 /// ArrayInitIndexExpr within an ArrayInitLoopExpr. 1284 llvm::Value *ArrayInitIndex = nullptr; 1285 1286 /// The values of function arguments to use when evaluating 1287 /// CXXInheritedCtorInitExprs within this context. 1288 CallArgList CXXInheritedCtorInitExprArgs; 1289 1290 /// CXXStructorImplicitParamDecl - When generating code for a constructor or 1291 /// destructor, this will hold the implicit argument (e.g. VTT). 1292 ImplicitParamDecl *CXXStructorImplicitParamDecl; 1293 llvm::Value *CXXStructorImplicitParamValue; 1294 1295 /// OutermostConditional - Points to the outermost active 1296 /// conditional control. This is used so that we know if a 1297 /// temporary should be destroyed conditionally. 1298 ConditionalEvaluation *OutermostConditional; 1299 1300 /// The current lexical scope. 1301 LexicalScope *CurLexicalScope; 1302 1303 /// The current source location that should be used for exception 1304 /// handling code. 1305 SourceLocation CurEHLocation; 1306 1307 /// BlockByrefInfos - For each __block variable, contains 1308 /// information about the layout of the variable. 1309 llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos; 1310 1311 llvm::BasicBlock *TerminateLandingPad; 1312 llvm::BasicBlock *TerminateHandler; 1313 llvm::BasicBlock *TrapBB; 1314 1315 /// True if we need emit the life-time markers. 1316 const bool ShouldEmitLifetimeMarkers; 1317 1318 /// Add a kernel metadata node to the named metadata node 'opencl.kernels'. 1319 /// In the kernel metadata node, reference the kernel function and metadata 1320 /// nodes for its optional attribute qualifiers (OpenCL 1.1 6.7.2): 1321 /// - A node for the vec_type_hint(<type>) qualifier contains string 1322 /// "vec_type_hint", an undefined value of the <type> data type, 1323 /// and a Boolean that is true if the <type> is integer and signed. 1324 /// - A node for the work_group_size_hint(X,Y,Z) qualifier contains string 1325 /// "work_group_size_hint", and three 32-bit integers X, Y and Z. 1326 /// - A node for the reqd_work_group_size(X,Y,Z) qualifier contains string 1327 /// "reqd_work_group_size", and three 32-bit integers X, Y and Z. 1328 void EmitOpenCLKernelMetadata(const FunctionDecl *FD, 1329 llvm::Function *Fn); 1330 1331 public: 1332 CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false); 1333 ~CodeGenFunction(); 1334 1335 CodeGenTypes &getTypes() const { return CGM.getTypes(); } 1336 ASTContext &getContext() const { return CGM.getContext(); } 1337 CGDebugInfo *getDebugInfo() { 1338 if (DisableDebugInfo) 1339 return nullptr; 1340 return DebugInfo; 1341 } 1342 void disableDebugInfo() { DisableDebugInfo = true; } 1343 void enableDebugInfo() { DisableDebugInfo = false; } 1344 1345 bool shouldUseFusedARCCalls() { 1346 return CGM.getCodeGenOpts().OptimizationLevel == 0; 1347 } 1348 1349 const LangOptions &getLangOpts() const { return CGM.getLangOpts(); } 1350 1351 /// Returns a pointer to the function's exception object and selector slot, 1352 /// which is assigned in every landing pad. 1353 Address getExceptionSlot(); 1354 Address getEHSelectorSlot(); 1355 1356 /// Returns the contents of the function's exception object and selector 1357 /// slots. 1358 llvm::Value *getExceptionFromSlot(); 1359 llvm::Value *getSelectorFromSlot(); 1360 1361 Address getNormalCleanupDestSlot(); 1362 1363 llvm::BasicBlock *getUnreachableBlock() { 1364 if (!UnreachableBlock) { 1365 UnreachableBlock = createBasicBlock("unreachable"); 1366 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock); 1367 } 1368 return UnreachableBlock; 1369 } 1370 1371 llvm::BasicBlock *getInvokeDest() { 1372 if (!EHStack.requiresLandingPad()) return nullptr; 1373 return getInvokeDestImpl(); 1374 } 1375 1376 bool currentFunctionUsesSEHTry() const { return CurSEHParent != nullptr; } 1377 1378 const TargetInfo &getTarget() const { return Target; } 1379 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); } 1380 1381 //===--------------------------------------------------------------------===// 1382 // Cleanups 1383 //===--------------------------------------------------------------------===// 1384 1385 typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty); 1386 1387 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, 1388 Address arrayEndPointer, 1389 QualType elementType, 1390 CharUnits elementAlignment, 1391 Destroyer *destroyer); 1392 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, 1393 llvm::Value *arrayEnd, 1394 QualType elementType, 1395 CharUnits elementAlignment, 1396 Destroyer *destroyer); 1397 1398 void pushDestroy(QualType::DestructionKind dtorKind, 1399 Address addr, QualType type); 1400 void pushEHDestroy(QualType::DestructionKind dtorKind, 1401 Address addr, QualType type); 1402 void pushDestroy(CleanupKind kind, Address addr, QualType type, 1403 Destroyer *destroyer, bool useEHCleanupForArray); 1404 void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, 1405 QualType type, Destroyer *destroyer, 1406 bool useEHCleanupForArray); 1407 void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete, 1408 llvm::Value *CompletePtr, 1409 QualType ElementType); 1410 void pushStackRestore(CleanupKind kind, Address SPMem); 1411 void emitDestroy(Address addr, QualType type, Destroyer *destroyer, 1412 bool useEHCleanupForArray); 1413 llvm::Function *generateDestroyHelper(Address addr, QualType type, 1414 Destroyer *destroyer, 1415 bool useEHCleanupForArray, 1416 const VarDecl *VD); 1417 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end, 1418 QualType elementType, CharUnits elementAlign, 1419 Destroyer *destroyer, 1420 bool checkZeroLength, bool useEHCleanup); 1421 1422 Destroyer *getDestroyer(QualType::DestructionKind destructionKind); 1423 1424 /// Determines whether an EH cleanup is required to destroy a type 1425 /// with the given destruction kind. 1426 bool needsEHCleanup(QualType::DestructionKind kind) { 1427 switch (kind) { 1428 case QualType::DK_none: 1429 return false; 1430 case QualType::DK_cxx_destructor: 1431 case QualType::DK_objc_weak_lifetime: 1432 return getLangOpts().Exceptions; 1433 case QualType::DK_objc_strong_lifetime: 1434 return getLangOpts().Exceptions && 1435 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions; 1436 } 1437 llvm_unreachable("bad destruction kind"); 1438 } 1439 1440 CleanupKind getCleanupKind(QualType::DestructionKind kind) { 1441 return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup); 1442 } 1443 1444 //===--------------------------------------------------------------------===// 1445 // Objective-C 1446 //===--------------------------------------------------------------------===// 1447 1448 void GenerateObjCMethod(const ObjCMethodDecl *OMD); 1449 1450 void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD); 1451 1452 /// GenerateObjCGetter - Synthesize an Objective-C property getter function. 1453 void GenerateObjCGetter(ObjCImplementationDecl *IMP, 1454 const ObjCPropertyImplDecl *PID); 1455 void generateObjCGetterBody(const ObjCImplementationDecl *classImpl, 1456 const ObjCPropertyImplDecl *propImpl, 1457 const ObjCMethodDecl *GetterMothodDecl, 1458 llvm::Constant *AtomicHelperFn); 1459 1460 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, 1461 ObjCMethodDecl *MD, bool ctor); 1462 1463 /// GenerateObjCSetter - Synthesize an Objective-C property setter function 1464 /// for the given property. 1465 void GenerateObjCSetter(ObjCImplementationDecl *IMP, 1466 const ObjCPropertyImplDecl *PID); 1467 void generateObjCSetterBody(const ObjCImplementationDecl *classImpl, 1468 const ObjCPropertyImplDecl *propImpl, 1469 llvm::Constant *AtomicHelperFn); 1470 1471 //===--------------------------------------------------------------------===// 1472 // Block Bits 1473 //===--------------------------------------------------------------------===// 1474 1475 llvm::Value *EmitBlockLiteral(const BlockExpr *); 1476 llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info); 1477 static void destroyBlockInfos(CGBlockInfo *info); 1478 1479 llvm::Function *GenerateBlockFunction(GlobalDecl GD, 1480 const CGBlockInfo &Info, 1481 const DeclMapTy &ldm, 1482 bool IsLambdaConversionToBlock); 1483 1484 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo); 1485 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo); 1486 llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction( 1487 const ObjCPropertyImplDecl *PID); 1488 llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction( 1489 const ObjCPropertyImplDecl *PID); 1490 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty); 1491 1492 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags); 1493 1494 class AutoVarEmission; 1495 1496 void emitByrefStructureInit(const AutoVarEmission &emission); 1497 void enterByrefCleanup(const AutoVarEmission &emission); 1498 1499 void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum, 1500 llvm::Value *ptr); 1501 1502 Address LoadBlockStruct(); 1503 Address GetAddrOfBlockDecl(const VarDecl *var, bool ByRef); 1504 1505 /// BuildBlockByrefAddress - Computes the location of the 1506 /// data in a variable which is declared as __block. 1507 Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V, 1508 bool followForward = true); 1509 Address emitBlockByrefAddress(Address baseAddr, 1510 const BlockByrefInfo &info, 1511 bool followForward, 1512 const llvm::Twine &name); 1513 1514 const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var); 1515 1516 QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args); 1517 1518 void GenerateCode(GlobalDecl GD, llvm::Function *Fn, 1519 const CGFunctionInfo &FnInfo); 1520 /// \brief Emit code for the start of a function. 1521 /// \param Loc The location to be associated with the function. 1522 /// \param StartLoc The location of the function body. 1523 void StartFunction(GlobalDecl GD, 1524 QualType RetTy, 1525 llvm::Function *Fn, 1526 const CGFunctionInfo &FnInfo, 1527 const FunctionArgList &Args, 1528 SourceLocation Loc = SourceLocation(), 1529 SourceLocation StartLoc = SourceLocation()); 1530 1531 void EmitConstructorBody(FunctionArgList &Args); 1532 void EmitDestructorBody(FunctionArgList &Args); 1533 void emitImplicitAssignmentOperatorBody(FunctionArgList &Args); 1534 void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body); 1535 void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S); 1536 1537 void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator, 1538 CallArgList &CallArgs); 1539 void EmitLambdaToBlockPointerBody(FunctionArgList &Args); 1540 void EmitLambdaBlockInvokeBody(); 1541 void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD); 1542 void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD); 1543 void EmitAsanPrologueOrEpilogue(bool Prologue); 1544 1545 /// \brief Emit the unified return block, trying to avoid its emission when 1546 /// possible. 1547 /// \return The debug location of the user written return statement if the 1548 /// return block is is avoided. 1549 llvm::DebugLoc EmitReturnBlock(); 1550 1551 /// FinishFunction - Complete IR generation of the current function. It is 1552 /// legal to call this function even if there is no current insertion point. 1553 void FinishFunction(SourceLocation EndLoc=SourceLocation()); 1554 1555 void StartThunk(llvm::Function *Fn, GlobalDecl GD, 1556 const CGFunctionInfo &FnInfo); 1557 1558 void EmitCallAndReturnForThunk(llvm::Constant *Callee, 1559 const ThunkInfo *Thunk); 1560 1561 void FinishThunk(); 1562 1563 /// Emit a musttail call for a thunk with a potentially adjusted this pointer. 1564 void EmitMustTailThunk(const CXXMethodDecl *MD, llvm::Value *AdjustedThisPtr, 1565 llvm::Value *Callee); 1566 1567 /// Generate a thunk for the given method. 1568 void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, 1569 GlobalDecl GD, const ThunkInfo &Thunk); 1570 1571 llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn, 1572 const CGFunctionInfo &FnInfo, 1573 GlobalDecl GD, const ThunkInfo &Thunk); 1574 1575 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type, 1576 FunctionArgList &Args); 1577 1578 void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init, 1579 ArrayRef<VarDecl *> ArrayIndexes); 1580 1581 /// Struct with all informations about dynamic [sub]class needed to set vptr. 1582 struct VPtr { 1583 BaseSubobject Base; 1584 const CXXRecordDecl *NearestVBase; 1585 CharUnits OffsetFromNearestVBase; 1586 const CXXRecordDecl *VTableClass; 1587 }; 1588 1589 /// Initialize the vtable pointer of the given subobject. 1590 void InitializeVTablePointer(const VPtr &vptr); 1591 1592 typedef llvm::SmallVector<VPtr, 4> VPtrsVector; 1593 1594 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy; 1595 VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass); 1596 1597 void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase, 1598 CharUnits OffsetFromNearestVBase, 1599 bool BaseIsNonVirtualPrimaryBase, 1600 const CXXRecordDecl *VTableClass, 1601 VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs); 1602 1603 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl); 1604 1605 /// GetVTablePtr - Return the Value of the vtable pointer member pointed 1606 /// to by This. 1607 llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy, 1608 const CXXRecordDecl *VTableClass); 1609 1610 enum CFITypeCheckKind { 1611 CFITCK_VCall, 1612 CFITCK_NVCall, 1613 CFITCK_DerivedCast, 1614 CFITCK_UnrelatedCast, 1615 CFITCK_ICall, 1616 }; 1617 1618 /// \brief Derived is the presumed address of an object of type T after a 1619 /// cast. If T is a polymorphic class type, emit a check that the virtual 1620 /// table for Derived belongs to a class derived from T. 1621 void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived, 1622 bool MayBeNull, CFITypeCheckKind TCK, 1623 SourceLocation Loc); 1624 1625 /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable. 1626 /// If vptr CFI is enabled, emit a check that VTable is valid. 1627 void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable, 1628 CFITypeCheckKind TCK, SourceLocation Loc); 1629 1630 /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for 1631 /// RD using llvm.type.test. 1632 void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable, 1633 CFITypeCheckKind TCK, SourceLocation Loc); 1634 1635 /// If whole-program virtual table optimization is enabled, emit an assumption 1636 /// that VTable is a member of RD's type identifier. Or, if vptr CFI is 1637 /// enabled, emit a check that VTable is a member of RD's type identifier. 1638 void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD, 1639 llvm::Value *VTable, SourceLocation Loc); 1640 1641 /// Returns whether we should perform a type checked load when loading a 1642 /// virtual function for virtual calls to members of RD. This is generally 1643 /// true when both vcall CFI and whole-program-vtables are enabled. 1644 bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD); 1645 1646 /// Emit a type checked load from the given vtable. 1647 llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable, 1648 uint64_t VTableByteOffset); 1649 1650 /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given 1651 /// expr can be devirtualized. 1652 bool CanDevirtualizeMemberFunctionCall(const Expr *Base, 1653 const CXXMethodDecl *MD); 1654 1655 /// EnterDtorCleanups - Enter the cleanups necessary to complete the 1656 /// given phase of destruction for a destructor. The end result 1657 /// should call destructors on members and base classes in reverse 1658 /// order of their construction. 1659 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type); 1660 1661 /// ShouldInstrumentFunction - Return true if the current function should be 1662 /// instrumented with __cyg_profile_func_* calls 1663 bool ShouldInstrumentFunction(); 1664 1665 /// ShouldXRayInstrument - Return true if the current function should be 1666 /// instrumented with XRay nop sleds. 1667 bool ShouldXRayInstrumentFunction() const; 1668 1669 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified 1670 /// instrumentation function with the current function and the call site, if 1671 /// function instrumentation is enabled. 1672 void EmitFunctionInstrumentation(const char *Fn); 1673 1674 /// EmitMCountInstrumentation - Emit call to .mcount. 1675 void EmitMCountInstrumentation(); 1676 1677 /// EmitFunctionProlog - Emit the target specific LLVM code to load the 1678 /// arguments for the given function. This is also responsible for naming the 1679 /// LLVM function arguments. 1680 void EmitFunctionProlog(const CGFunctionInfo &FI, 1681 llvm::Function *Fn, 1682 const FunctionArgList &Args); 1683 1684 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the 1685 /// given temporary. 1686 void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc, 1687 SourceLocation EndLoc); 1688 1689 /// EmitStartEHSpec - Emit the start of the exception spec. 1690 void EmitStartEHSpec(const Decl *D); 1691 1692 /// EmitEndEHSpec - Emit the end of the exception spec. 1693 void EmitEndEHSpec(const Decl *D); 1694 1695 /// getTerminateLandingPad - Return a landing pad that just calls terminate. 1696 llvm::BasicBlock *getTerminateLandingPad(); 1697 1698 /// getTerminateHandler - Return a handler (not a landing pad, just 1699 /// a catch handler) that just calls terminate. This is used when 1700 /// a terminate scope encloses a try. 1701 llvm::BasicBlock *getTerminateHandler(); 1702 1703 llvm::Type *ConvertTypeForMem(QualType T); 1704 llvm::Type *ConvertType(QualType T); 1705 llvm::Type *ConvertType(const TypeDecl *T) { 1706 return ConvertType(getContext().getTypeDeclType(T)); 1707 } 1708 1709 /// LoadObjCSelf - Load the value of self. This function is only valid while 1710 /// generating code for an Objective-C method. 1711 llvm::Value *LoadObjCSelf(); 1712 1713 /// TypeOfSelfObject - Return type of object that this self represents. 1714 QualType TypeOfSelfObject(); 1715 1716 /// hasAggregateLLVMType - Return true if the specified AST type will map into 1717 /// an aggregate LLVM type or is void. 1718 static TypeEvaluationKind getEvaluationKind(QualType T); 1719 1720 static bool hasScalarEvaluationKind(QualType T) { 1721 return getEvaluationKind(T) == TEK_Scalar; 1722 } 1723 1724 static bool hasAggregateEvaluationKind(QualType T) { 1725 return getEvaluationKind(T) == TEK_Aggregate; 1726 } 1727 1728 /// createBasicBlock - Create an LLVM basic block. 1729 llvm::BasicBlock *createBasicBlock(const Twine &name = "", 1730 llvm::Function *parent = nullptr, 1731 llvm::BasicBlock *before = nullptr) { 1732 #ifdef NDEBUG 1733 return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before); 1734 #else 1735 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before); 1736 #endif 1737 } 1738 1739 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified 1740 /// label maps to. 1741 JumpDest getJumpDestForLabel(const LabelDecl *S); 1742 1743 /// SimplifyForwardingBlocks - If the given basic block is only a branch to 1744 /// another basic block, simplify it. This assumes that no other code could 1745 /// potentially reference the basic block. 1746 void SimplifyForwardingBlocks(llvm::BasicBlock *BB); 1747 1748 /// EmitBlock - Emit the given block \arg BB and set it as the insert point, 1749 /// adding a fall-through branch from the current insert block if 1750 /// necessary. It is legal to call this function even if there is no current 1751 /// insertion point. 1752 /// 1753 /// IsFinished - If true, indicates that the caller has finished emitting 1754 /// branches to the given block and does not expect to emit code into it. This 1755 /// means the block can be ignored if it is unreachable. 1756 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false); 1757 1758 /// EmitBlockAfterUses - Emit the given block somewhere hopefully 1759 /// near its uses, and leave the insertion point in it. 1760 void EmitBlockAfterUses(llvm::BasicBlock *BB); 1761 1762 /// EmitBranch - Emit a branch to the specified basic block from the current 1763 /// insert block, taking care to avoid creation of branches from dummy 1764 /// blocks. It is legal to call this function even if there is no current 1765 /// insertion point. 1766 /// 1767 /// This function clears the current insertion point. The caller should follow 1768 /// calls to this function with calls to Emit*Block prior to generation new 1769 /// code. 1770 void EmitBranch(llvm::BasicBlock *Block); 1771 1772 /// HaveInsertPoint - True if an insertion point is defined. If not, this 1773 /// indicates that the current code being emitted is unreachable. 1774 bool HaveInsertPoint() const { 1775 return Builder.GetInsertBlock() != nullptr; 1776 } 1777 1778 /// EnsureInsertPoint - Ensure that an insertion point is defined so that 1779 /// emitted IR has a place to go. Note that by definition, if this function 1780 /// creates a block then that block is unreachable; callers may do better to 1781 /// detect when no insertion point is defined and simply skip IR generation. 1782 void EnsureInsertPoint() { 1783 if (!HaveInsertPoint()) 1784 EmitBlock(createBasicBlock()); 1785 } 1786 1787 /// ErrorUnsupported - Print out an error that codegen doesn't support the 1788 /// specified stmt yet. 1789 void ErrorUnsupported(const Stmt *S, const char *Type); 1790 1791 //===--------------------------------------------------------------------===// 1792 // Helpers 1793 //===--------------------------------------------------------------------===// 1794 1795 LValue MakeAddrLValue(Address Addr, QualType T, 1796 AlignmentSource AlignSource = AlignmentSource::Type) { 1797 return LValue::MakeAddr(Addr, T, getContext(), AlignSource, 1798 CGM.getTBAAInfo(T)); 1799 } 1800 1801 LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment, 1802 AlignmentSource AlignSource = AlignmentSource::Type) { 1803 return LValue::MakeAddr(Address(V, Alignment), T, getContext(), 1804 AlignSource, CGM.getTBAAInfo(T)); 1805 } 1806 1807 LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T); 1808 LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T); 1809 CharUnits getNaturalTypeAlignment(QualType T, 1810 AlignmentSource *Source = nullptr, 1811 bool forPointeeType = false); 1812 CharUnits getNaturalPointeeTypeAlignment(QualType T, 1813 AlignmentSource *Source = nullptr); 1814 1815 Address EmitLoadOfReference(Address Ref, const ReferenceType *RefTy, 1816 AlignmentSource *Source = nullptr); 1817 LValue EmitLoadOfReferenceLValue(Address Ref, const ReferenceType *RefTy); 1818 1819 Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy, 1820 AlignmentSource *Source = nullptr); 1821 LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy); 1822 1823 /// CreateTempAlloca - This creates a alloca and inserts it into the entry 1824 /// block. The caller is responsible for setting an appropriate alignment on 1825 /// the alloca. 1826 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty, 1827 const Twine &Name = "tmp"); 1828 Address CreateTempAlloca(llvm::Type *Ty, CharUnits align, 1829 const Twine &Name = "tmp"); 1830 1831 /// CreateDefaultAlignedTempAlloca - This creates an alloca with the 1832 /// default ABI alignment of the given LLVM type. 1833 /// 1834 /// IMPORTANT NOTE: This is *not* generally the right alignment for 1835 /// any given AST type that happens to have been lowered to the 1836 /// given IR type. This should only ever be used for function-local, 1837 /// IR-driven manipulations like saving and restoring a value. Do 1838 /// not hand this address off to arbitrary IRGen routines, and especially 1839 /// do not pass it as an argument to a function that might expect a 1840 /// properly ABI-aligned value. 1841 Address CreateDefaultAlignTempAlloca(llvm::Type *Ty, 1842 const Twine &Name = "tmp"); 1843 1844 /// InitTempAlloca - Provide an initial value for the given alloca which 1845 /// will be observable at all locations in the function. 1846 /// 1847 /// The address should be something that was returned from one of 1848 /// the CreateTempAlloca or CreateMemTemp routines, and the 1849 /// initializer must be valid in the entry block (i.e. it must 1850 /// either be a constant or an argument value). 1851 void InitTempAlloca(Address Alloca, llvm::Value *Value); 1852 1853 /// CreateIRTemp - Create a temporary IR object of the given type, with 1854 /// appropriate alignment. This routine should only be used when an temporary 1855 /// value needs to be stored into an alloca (for example, to avoid explicit 1856 /// PHI construction), but the type is the IR type, not the type appropriate 1857 /// for storing in memory. 1858 /// 1859 /// That is, this is exactly equivalent to CreateMemTemp, but calling 1860 /// ConvertType instead of ConvertTypeForMem. 1861 Address CreateIRTemp(QualType T, const Twine &Name = "tmp"); 1862 1863 /// CreateMemTemp - Create a temporary memory object of the given type, with 1864 /// appropriate alignment. 1865 Address CreateMemTemp(QualType T, const Twine &Name = "tmp"); 1866 Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp"); 1867 1868 /// CreateAggTemp - Create a temporary memory object for the given 1869 /// aggregate type. 1870 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") { 1871 return AggValueSlot::forAddr(CreateMemTemp(T, Name), 1872 T.getQualifiers(), 1873 AggValueSlot::IsNotDestructed, 1874 AggValueSlot::DoesNotNeedGCBarriers, 1875 AggValueSlot::IsNotAliased); 1876 } 1877 1878 /// Emit a cast to void* in the appropriate address space. 1879 llvm::Value *EmitCastToVoidPtr(llvm::Value *value); 1880 1881 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 1882 /// expression and compare the result against zero, returning an Int1Ty value. 1883 llvm::Value *EvaluateExprAsBool(const Expr *E); 1884 1885 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result. 1886 void EmitIgnoredExpr(const Expr *E); 1887 1888 /// EmitAnyExpr - Emit code to compute the specified expression which can have 1889 /// any type. The result is returned as an RValue struct. If this is an 1890 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where 1891 /// the result should be returned. 1892 /// 1893 /// \param ignoreResult True if the resulting value isn't used. 1894 RValue EmitAnyExpr(const Expr *E, 1895 AggValueSlot aggSlot = AggValueSlot::ignored(), 1896 bool ignoreResult = false); 1897 1898 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address 1899 // or the value of the expression, depending on how va_list is defined. 1900 Address EmitVAListRef(const Expr *E); 1901 1902 /// Emit a "reference" to a __builtin_ms_va_list; this is 1903 /// always the value of the expression, because a __builtin_ms_va_list is a 1904 /// pointer to a char. 1905 Address EmitMSVAListRef(const Expr *E); 1906 1907 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will 1908 /// always be accessible even if no aggregate location is provided. 1909 RValue EmitAnyExprToTemp(const Expr *E); 1910 1911 /// EmitAnyExprToMem - Emits the code necessary to evaluate an 1912 /// arbitrary expression into the given memory location. 1913 void EmitAnyExprToMem(const Expr *E, Address Location, 1914 Qualifiers Quals, bool IsInitializer); 1915 1916 void EmitAnyExprToExn(const Expr *E, Address Addr); 1917 1918 /// EmitExprAsInit - Emits the code necessary to initialize a 1919 /// location in memory with the given initializer. 1920 void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue, 1921 bool capturedByInit); 1922 1923 /// hasVolatileMember - returns true if aggregate type has a volatile 1924 /// member. 1925 bool hasVolatileMember(QualType T) { 1926 if (const RecordType *RT = T->getAs<RecordType>()) { 1927 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl()); 1928 return RD->hasVolatileMember(); 1929 } 1930 return false; 1931 } 1932 /// EmitAggregateCopy - Emit an aggregate assignment. 1933 /// 1934 /// The difference to EmitAggregateCopy is that tail padding is not copied. 1935 /// This is required for correctness when assigning non-POD structures in C++. 1936 void EmitAggregateAssign(Address DestPtr, Address SrcPtr, 1937 QualType EltTy) { 1938 bool IsVolatile = hasVolatileMember(EltTy); 1939 EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, true); 1940 } 1941 1942 void EmitAggregateCopyCtor(Address DestPtr, Address SrcPtr, 1943 QualType DestTy, QualType SrcTy) { 1944 EmitAggregateCopy(DestPtr, SrcPtr, SrcTy, /*IsVolatile=*/false, 1945 /*IsAssignment=*/false); 1946 } 1947 1948 /// EmitAggregateCopy - Emit an aggregate copy. 1949 /// 1950 /// \param isVolatile - True iff either the source or the destination is 1951 /// volatile. 1952 /// \param isAssignment - If false, allow padding to be copied. This often 1953 /// yields more efficient. 1954 void EmitAggregateCopy(Address DestPtr, Address SrcPtr, 1955 QualType EltTy, bool isVolatile=false, 1956 bool isAssignment = false); 1957 1958 /// GetAddrOfLocalVar - Return the address of a local variable. 1959 Address GetAddrOfLocalVar(const VarDecl *VD) { 1960 auto it = LocalDeclMap.find(VD); 1961 assert(it != LocalDeclMap.end() && 1962 "Invalid argument to GetAddrOfLocalVar(), no decl!"); 1963 return it->second; 1964 } 1965 1966 /// getOpaqueLValueMapping - Given an opaque value expression (which 1967 /// must be mapped to an l-value), return its mapping. 1968 const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) { 1969 assert(OpaqueValueMapping::shouldBindAsLValue(e)); 1970 1971 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator 1972 it = OpaqueLValues.find(e); 1973 assert(it != OpaqueLValues.end() && "no mapping for opaque value!"); 1974 return it->second; 1975 } 1976 1977 /// getOpaqueRValueMapping - Given an opaque value expression (which 1978 /// must be mapped to an r-value), return its mapping. 1979 const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) { 1980 assert(!OpaqueValueMapping::shouldBindAsLValue(e)); 1981 1982 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator 1983 it = OpaqueRValues.find(e); 1984 assert(it != OpaqueRValues.end() && "no mapping for opaque value!"); 1985 return it->second; 1986 } 1987 1988 /// Get the index of the current ArrayInitLoopExpr, if any. 1989 llvm::Value *getArrayInitIndex() { return ArrayInitIndex; } 1990 1991 /// getAccessedFieldNo - Given an encoded value and a result number, return 1992 /// the input field number being accessed. 1993 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts); 1994 1995 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L); 1996 llvm::BasicBlock *GetIndirectGotoBlock(); 1997 1998 /// EmitNullInitialization - Generate code to set a value of the given type to 1999 /// null, If the type contains data member pointers, they will be initialized 2000 /// to -1 in accordance with the Itanium C++ ABI. 2001 void EmitNullInitialization(Address DestPtr, QualType Ty); 2002 2003 /// Emits a call to an LLVM variable-argument intrinsic, either 2004 /// \c llvm.va_start or \c llvm.va_end. 2005 /// \param ArgValue A reference to the \c va_list as emitted by either 2006 /// \c EmitVAListRef or \c EmitMSVAListRef. 2007 /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise, 2008 /// calls \c llvm.va_end. 2009 llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart); 2010 2011 /// Generate code to get an argument from the passed in pointer 2012 /// and update it accordingly. 2013 /// \param VE The \c VAArgExpr for which to generate code. 2014 /// \param VAListAddr Receives a reference to the \c va_list as emitted by 2015 /// either \c EmitVAListRef or \c EmitMSVAListRef. 2016 /// \returns A pointer to the argument. 2017 // FIXME: We should be able to get rid of this method and use the va_arg 2018 // instruction in LLVM instead once it works well enough. 2019 Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr); 2020 2021 /// emitArrayLength - Compute the length of an array, even if it's a 2022 /// VLA, and drill down to the base element type. 2023 llvm::Value *emitArrayLength(const ArrayType *arrayType, 2024 QualType &baseType, 2025 Address &addr); 2026 2027 /// EmitVLASize - Capture all the sizes for the VLA expressions in 2028 /// the given variably-modified type and store them in the VLASizeMap. 2029 /// 2030 /// This function can be called with a null (unreachable) insert point. 2031 void EmitVariablyModifiedType(QualType Ty); 2032 2033 /// getVLASize - Returns an LLVM value that corresponds to the size, 2034 /// in non-variably-sized elements, of a variable length array type, 2035 /// plus that largest non-variably-sized element type. Assumes that 2036 /// the type has already been emitted with EmitVariablyModifiedType. 2037 std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla); 2038 std::pair<llvm::Value*,QualType> getVLASize(QualType vla); 2039 2040 /// LoadCXXThis - Load the value of 'this'. This function is only valid while 2041 /// generating code for an C++ member function. 2042 llvm::Value *LoadCXXThis() { 2043 assert(CXXThisValue && "no 'this' value for this function"); 2044 return CXXThisValue; 2045 } 2046 Address LoadCXXThisAddress(); 2047 2048 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have 2049 /// virtual bases. 2050 // FIXME: Every place that calls LoadCXXVTT is something 2051 // that needs to be abstracted properly. 2052 llvm::Value *LoadCXXVTT() { 2053 assert(CXXStructorImplicitParamValue && "no VTT value for this function"); 2054 return CXXStructorImplicitParamValue; 2055 } 2056 2057 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a 2058 /// complete class to the given direct base. 2059 Address 2060 GetAddressOfDirectBaseInCompleteClass(Address Value, 2061 const CXXRecordDecl *Derived, 2062 const CXXRecordDecl *Base, 2063 bool BaseIsVirtual); 2064 2065 static bool ShouldNullCheckClassCastValue(const CastExpr *Cast); 2066 2067 /// GetAddressOfBaseClass - This function will add the necessary delta to the 2068 /// load of 'this' and returns address of the base class. 2069 Address GetAddressOfBaseClass(Address Value, 2070 const CXXRecordDecl *Derived, 2071 CastExpr::path_const_iterator PathBegin, 2072 CastExpr::path_const_iterator PathEnd, 2073 bool NullCheckValue, SourceLocation Loc); 2074 2075 Address GetAddressOfDerivedClass(Address Value, 2076 const CXXRecordDecl *Derived, 2077 CastExpr::path_const_iterator PathBegin, 2078 CastExpr::path_const_iterator PathEnd, 2079 bool NullCheckValue); 2080 2081 /// GetVTTParameter - Return the VTT parameter that should be passed to a 2082 /// base constructor/destructor with virtual bases. 2083 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move 2084 /// to ItaniumCXXABI.cpp together with all the references to VTT. 2085 llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase, 2086 bool Delegating); 2087 2088 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, 2089 CXXCtorType CtorType, 2090 const FunctionArgList &Args, 2091 SourceLocation Loc); 2092 // It's important not to confuse this and the previous function. Delegating 2093 // constructors are the C++0x feature. The constructor delegate optimization 2094 // is used to reduce duplication in the base and complete consturctors where 2095 // they are substantially the same. 2096 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor, 2097 const FunctionArgList &Args); 2098 2099 /// Emit a call to an inheriting constructor (that is, one that invokes a 2100 /// constructor inherited from a base class) by inlining its definition. This 2101 /// is necessary if the ABI does not support forwarding the arguments to the 2102 /// base class constructor (because they're variadic or similar). 2103 void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor, 2104 CXXCtorType CtorType, 2105 bool ForVirtualBase, 2106 bool Delegating, 2107 CallArgList &Args); 2108 2109 /// Emit a call to a constructor inherited from a base class, passing the 2110 /// current constructor's arguments along unmodified (without even making 2111 /// a copy). 2112 void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D, 2113 bool ForVirtualBase, Address This, 2114 bool InheritedFromVBase, 2115 const CXXInheritedCtorInitExpr *E); 2116 2117 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 2118 bool ForVirtualBase, bool Delegating, 2119 Address This, const CXXConstructExpr *E); 2120 2121 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 2122 bool ForVirtualBase, bool Delegating, 2123 Address This, CallArgList &Args); 2124 2125 /// Emit assumption load for all bases. Requires to be be called only on 2126 /// most-derived class and not under construction of the object. 2127 void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This); 2128 2129 /// Emit assumption that vptr load == global vtable. 2130 void EmitVTableAssumptionLoad(const VPtr &vptr, Address This); 2131 2132 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, 2133 Address This, Address Src, 2134 const CXXConstructExpr *E); 2135 2136 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 2137 const ArrayType *ArrayTy, 2138 Address ArrayPtr, 2139 const CXXConstructExpr *E, 2140 bool ZeroInitialization = false); 2141 2142 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 2143 llvm::Value *NumElements, 2144 Address ArrayPtr, 2145 const CXXConstructExpr *E, 2146 bool ZeroInitialization = false); 2147 2148 static Destroyer destroyCXXObject; 2149 2150 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, 2151 bool ForVirtualBase, bool Delegating, 2152 Address This); 2153 2154 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType, 2155 llvm::Type *ElementTy, Address NewPtr, 2156 llvm::Value *NumElements, 2157 llvm::Value *AllocSizeWithoutCookie); 2158 2159 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType, 2160 Address Ptr); 2161 2162 llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr); 2163 void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr); 2164 2165 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E); 2166 void EmitCXXDeleteExpr(const CXXDeleteExpr *E); 2167 2168 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr, 2169 QualType DeleteTy, llvm::Value *NumElements = nullptr, 2170 CharUnits CookieSize = CharUnits()); 2171 2172 RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type, 2173 const Expr *Arg, bool IsDelete); 2174 2175 llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E); 2176 llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE); 2177 Address EmitCXXUuidofExpr(const CXXUuidofExpr *E); 2178 2179 /// \brief Situations in which we might emit a check for the suitability of a 2180 /// pointer or glvalue. 2181 enum TypeCheckKind { 2182 /// Checking the operand of a load. Must be suitably sized and aligned. 2183 TCK_Load, 2184 /// Checking the destination of a store. Must be suitably sized and aligned. 2185 TCK_Store, 2186 /// Checking the bound value in a reference binding. Must be suitably sized 2187 /// and aligned, but is not required to refer to an object (until the 2188 /// reference is used), per core issue 453. 2189 TCK_ReferenceBinding, 2190 /// Checking the object expression in a non-static data member access. Must 2191 /// be an object within its lifetime. 2192 TCK_MemberAccess, 2193 /// Checking the 'this' pointer for a call to a non-static member function. 2194 /// Must be an object within its lifetime. 2195 TCK_MemberCall, 2196 /// Checking the 'this' pointer for a constructor call. 2197 TCK_ConstructorCall, 2198 /// Checking the operand of a static_cast to a derived pointer type. Must be 2199 /// null or an object within its lifetime. 2200 TCK_DowncastPointer, 2201 /// Checking the operand of a static_cast to a derived reference type. Must 2202 /// be an object within its lifetime. 2203 TCK_DowncastReference, 2204 /// Checking the operand of a cast to a base object. Must be suitably sized 2205 /// and aligned. 2206 TCK_Upcast, 2207 /// Checking the operand of a cast to a virtual base object. Must be an 2208 /// object within its lifetime. 2209 TCK_UpcastToVirtualBase 2210 }; 2211 2212 /// \brief Whether any type-checking sanitizers are enabled. If \c false, 2213 /// calls to EmitTypeCheck can be skipped. 2214 bool sanitizePerformTypeCheck() const; 2215 2216 /// \brief Emit a check that \p V is the address of storage of the 2217 /// appropriate size and alignment for an object of type \p Type. 2218 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V, 2219 QualType Type, CharUnits Alignment = CharUnits::Zero(), 2220 bool SkipNullCheck = false); 2221 2222 /// \brief Emit a check that \p Base points into an array object, which 2223 /// we can access at index \p Index. \p Accessed should be \c false if we 2224 /// this expression is used as an lvalue, for instance in "&Arr[Idx]". 2225 void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index, 2226 QualType IndexType, bool Accessed); 2227 2228 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 2229 bool isInc, bool isPre); 2230 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, 2231 bool isInc, bool isPre); 2232 2233 void EmitAlignmentAssumption(llvm::Value *PtrValue, unsigned Alignment, 2234 llvm::Value *OffsetValue = nullptr) { 2235 Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment, 2236 OffsetValue); 2237 } 2238 2239 /// Converts Location to a DebugLoc, if debug information is enabled. 2240 llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location); 2241 2242 2243 //===--------------------------------------------------------------------===// 2244 // Declaration Emission 2245 //===--------------------------------------------------------------------===// 2246 2247 /// EmitDecl - Emit a declaration. 2248 /// 2249 /// This function can be called with a null (unreachable) insert point. 2250 void EmitDecl(const Decl &D); 2251 2252 /// EmitVarDecl - Emit a local variable declaration. 2253 /// 2254 /// This function can be called with a null (unreachable) insert point. 2255 void EmitVarDecl(const VarDecl &D); 2256 2257 void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue, 2258 bool capturedByInit); 2259 2260 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D, 2261 llvm::Value *Address); 2262 2263 /// \brief Determine whether the given initializer is trivial in the sense 2264 /// that it requires no code to be generated. 2265 bool isTrivialInitializer(const Expr *Init); 2266 2267 /// EmitAutoVarDecl - Emit an auto variable declaration. 2268 /// 2269 /// This function can be called with a null (unreachable) insert point. 2270 void EmitAutoVarDecl(const VarDecl &D); 2271 2272 class AutoVarEmission { 2273 friend class CodeGenFunction; 2274 2275 const VarDecl *Variable; 2276 2277 /// The address of the alloca. Invalid if the variable was emitted 2278 /// as a global constant. 2279 Address Addr; 2280 2281 llvm::Value *NRVOFlag; 2282 2283 /// True if the variable is a __block variable. 2284 bool IsByRef; 2285 2286 /// True if the variable is of aggregate type and has a constant 2287 /// initializer. 2288 bool IsConstantAggregate; 2289 2290 /// Non-null if we should use lifetime annotations. 2291 llvm::Value *SizeForLifetimeMarkers; 2292 2293 struct Invalid {}; 2294 AutoVarEmission(Invalid) : Variable(nullptr), Addr(Address::invalid()) {} 2295 2296 AutoVarEmission(const VarDecl &variable) 2297 : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr), 2298 IsByRef(false), IsConstantAggregate(false), 2299 SizeForLifetimeMarkers(nullptr) {} 2300 2301 bool wasEmittedAsGlobal() const { return !Addr.isValid(); } 2302 2303 public: 2304 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); } 2305 2306 bool useLifetimeMarkers() const { 2307 return SizeForLifetimeMarkers != nullptr; 2308 } 2309 llvm::Value *getSizeForLifetimeMarkers() const { 2310 assert(useLifetimeMarkers()); 2311 return SizeForLifetimeMarkers; 2312 } 2313 2314 /// Returns the raw, allocated address, which is not necessarily 2315 /// the address of the object itself. 2316 Address getAllocatedAddress() const { 2317 return Addr; 2318 } 2319 2320 /// Returns the address of the object within this declaration. 2321 /// Note that this does not chase the forwarding pointer for 2322 /// __block decls. 2323 Address getObjectAddress(CodeGenFunction &CGF) const { 2324 if (!IsByRef) return Addr; 2325 2326 return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false); 2327 } 2328 }; 2329 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var); 2330 void EmitAutoVarInit(const AutoVarEmission &emission); 2331 void EmitAutoVarCleanups(const AutoVarEmission &emission); 2332 void emitAutoVarTypeCleanup(const AutoVarEmission &emission, 2333 QualType::DestructionKind dtorKind); 2334 2335 void EmitStaticVarDecl(const VarDecl &D, 2336 llvm::GlobalValue::LinkageTypes Linkage); 2337 2338 class ParamValue { 2339 llvm::Value *Value; 2340 unsigned Alignment; 2341 ParamValue(llvm::Value *V, unsigned A) : Value(V), Alignment(A) {} 2342 public: 2343 static ParamValue forDirect(llvm::Value *value) { 2344 return ParamValue(value, 0); 2345 } 2346 static ParamValue forIndirect(Address addr) { 2347 assert(!addr.getAlignment().isZero()); 2348 return ParamValue(addr.getPointer(), addr.getAlignment().getQuantity()); 2349 } 2350 2351 bool isIndirect() const { return Alignment != 0; } 2352 llvm::Value *getAnyValue() const { return Value; } 2353 2354 llvm::Value *getDirectValue() const { 2355 assert(!isIndirect()); 2356 return Value; 2357 } 2358 2359 Address getIndirectAddress() const { 2360 assert(isIndirect()); 2361 return Address(Value, CharUnits::fromQuantity(Alignment)); 2362 } 2363 }; 2364 2365 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl. 2366 void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo); 2367 2368 /// protectFromPeepholes - Protect a value that we're intending to 2369 /// store to the side, but which will probably be used later, from 2370 /// aggressive peepholing optimizations that might delete it. 2371 /// 2372 /// Pass the result to unprotectFromPeepholes to declare that 2373 /// protection is no longer required. 2374 /// 2375 /// There's no particular reason why this shouldn't apply to 2376 /// l-values, it's just that no existing peepholes work on pointers. 2377 PeepholeProtection protectFromPeepholes(RValue rvalue); 2378 void unprotectFromPeepholes(PeepholeProtection protection); 2379 2380 //===--------------------------------------------------------------------===// 2381 // Statement Emission 2382 //===--------------------------------------------------------------------===// 2383 2384 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info. 2385 void EmitStopPoint(const Stmt *S); 2386 2387 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call 2388 /// this function even if there is no current insertion point. 2389 /// 2390 /// This function may clear the current insertion point; callers should use 2391 /// EnsureInsertPoint if they wish to subsequently generate code without first 2392 /// calling EmitBlock, EmitBranch, or EmitStmt. 2393 void EmitStmt(const Stmt *S); 2394 2395 /// EmitSimpleStmt - Try to emit a "simple" statement which does not 2396 /// necessarily require an insertion point or debug information; typically 2397 /// because the statement amounts to a jump or a container of other 2398 /// statements. 2399 /// 2400 /// \return True if the statement was handled. 2401 bool EmitSimpleStmt(const Stmt *S); 2402 2403 Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false, 2404 AggValueSlot AVS = AggValueSlot::ignored()); 2405 Address EmitCompoundStmtWithoutScope(const CompoundStmt &S, 2406 bool GetLast = false, 2407 AggValueSlot AVS = 2408 AggValueSlot::ignored()); 2409 2410 /// EmitLabel - Emit the block for the given label. It is legal to call this 2411 /// function even if there is no current insertion point. 2412 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt. 2413 2414 void EmitLabelStmt(const LabelStmt &S); 2415 void EmitAttributedStmt(const AttributedStmt &S); 2416 void EmitGotoStmt(const GotoStmt &S); 2417 void EmitIndirectGotoStmt(const IndirectGotoStmt &S); 2418 void EmitIfStmt(const IfStmt &S); 2419 2420 void EmitWhileStmt(const WhileStmt &S, 2421 ArrayRef<const Attr *> Attrs = None); 2422 void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None); 2423 void EmitForStmt(const ForStmt &S, 2424 ArrayRef<const Attr *> Attrs = None); 2425 void EmitReturnStmt(const ReturnStmt &S); 2426 void EmitDeclStmt(const DeclStmt &S); 2427 void EmitBreakStmt(const BreakStmt &S); 2428 void EmitContinueStmt(const ContinueStmt &S); 2429 void EmitSwitchStmt(const SwitchStmt &S); 2430 void EmitDefaultStmt(const DefaultStmt &S); 2431 void EmitCaseStmt(const CaseStmt &S); 2432 void EmitCaseStmtRange(const CaseStmt &S); 2433 void EmitAsmStmt(const AsmStmt &S); 2434 2435 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S); 2436 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S); 2437 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S); 2438 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S); 2439 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S); 2440 2441 void EmitCoroutineBody(const CoroutineBodyStmt &S); 2442 RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID); 2443 2444 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 2445 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 2446 2447 void EmitCXXTryStmt(const CXXTryStmt &S); 2448 void EmitSEHTryStmt(const SEHTryStmt &S); 2449 void EmitSEHLeaveStmt(const SEHLeaveStmt &S); 2450 void EnterSEHTryStmt(const SEHTryStmt &S); 2451 void ExitSEHTryStmt(const SEHTryStmt &S); 2452 2453 void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter, 2454 const Stmt *OutlinedStmt); 2455 2456 llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF, 2457 const SEHExceptStmt &Except); 2458 2459 llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF, 2460 const SEHFinallyStmt &Finally); 2461 2462 void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF, 2463 llvm::Value *ParentFP, 2464 llvm::Value *EntryEBP); 2465 llvm::Value *EmitSEHExceptionCode(); 2466 llvm::Value *EmitSEHExceptionInfo(); 2467 llvm::Value *EmitSEHAbnormalTermination(); 2468 2469 /// Scan the outlined statement for captures from the parent function. For 2470 /// each capture, mark the capture as escaped and emit a call to 2471 /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap. 2472 void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt, 2473 bool IsFilter); 2474 2475 /// Recovers the address of a local in a parent function. ParentVar is the 2476 /// address of the variable used in the immediate parent function. It can 2477 /// either be an alloca or a call to llvm.localrecover if there are nested 2478 /// outlined functions. ParentFP is the frame pointer of the outermost parent 2479 /// frame. 2480 Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF, 2481 Address ParentVar, 2482 llvm::Value *ParentFP); 2483 2484 void EmitCXXForRangeStmt(const CXXForRangeStmt &S, 2485 ArrayRef<const Attr *> Attrs = None); 2486 2487 /// Returns calculated size of the specified type. 2488 llvm::Value *getTypeSize(QualType Ty); 2489 LValue InitCapturedStruct(const CapturedStmt &S); 2490 llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K); 2491 llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S); 2492 Address GenerateCapturedStmtArgument(const CapturedStmt &S); 2493 llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S); 2494 void GenerateOpenMPCapturedVars(const CapturedStmt &S, 2495 SmallVectorImpl<llvm::Value *> &CapturedVars); 2496 void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy, 2497 SourceLocation Loc); 2498 /// \brief Perform element by element copying of arrays with type \a 2499 /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure 2500 /// generated by \a CopyGen. 2501 /// 2502 /// \param DestAddr Address of the destination array. 2503 /// \param SrcAddr Address of the source array. 2504 /// \param OriginalType Type of destination and source arrays. 2505 /// \param CopyGen Copying procedure that copies value of single array element 2506 /// to another single array element. 2507 void EmitOMPAggregateAssign( 2508 Address DestAddr, Address SrcAddr, QualType OriginalType, 2509 const llvm::function_ref<void(Address, Address)> &CopyGen); 2510 /// \brief Emit proper copying of data from one variable to another. 2511 /// 2512 /// \param OriginalType Original type of the copied variables. 2513 /// \param DestAddr Destination address. 2514 /// \param SrcAddr Source address. 2515 /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has 2516 /// type of the base array element). 2517 /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of 2518 /// the base array element). 2519 /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a 2520 /// DestVD. 2521 void EmitOMPCopy(QualType OriginalType, 2522 Address DestAddr, Address SrcAddr, 2523 const VarDecl *DestVD, const VarDecl *SrcVD, 2524 const Expr *Copy); 2525 /// \brief Emit atomic update code for constructs: \a X = \a X \a BO \a E or 2526 /// \a X = \a E \a BO \a E. 2527 /// 2528 /// \param X Value to be updated. 2529 /// \param E Update value. 2530 /// \param BO Binary operation for update operation. 2531 /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update 2532 /// expression, false otherwise. 2533 /// \param AO Atomic ordering of the generated atomic instructions. 2534 /// \param CommonGen Code generator for complex expressions that cannot be 2535 /// expressed through atomicrmw instruction. 2536 /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was 2537 /// generated, <false, RValue::get(nullptr)> otherwise. 2538 std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr( 2539 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart, 2540 llvm::AtomicOrdering AO, SourceLocation Loc, 2541 const llvm::function_ref<RValue(RValue)> &CommonGen); 2542 bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D, 2543 OMPPrivateScope &PrivateScope); 2544 void EmitOMPPrivateClause(const OMPExecutableDirective &D, 2545 OMPPrivateScope &PrivateScope); 2546 void EmitOMPUseDevicePtrClause( 2547 const OMPClause &C, OMPPrivateScope &PrivateScope, 2548 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap); 2549 /// \brief Emit code for copyin clause in \a D directive. The next code is 2550 /// generated at the start of outlined functions for directives: 2551 /// \code 2552 /// threadprivate_var1 = master_threadprivate_var1; 2553 /// operator=(threadprivate_var2, master_threadprivate_var2); 2554 /// ... 2555 /// __kmpc_barrier(&loc, global_tid); 2556 /// \endcode 2557 /// 2558 /// \param D OpenMP directive possibly with 'copyin' clause(s). 2559 /// \returns true if at least one copyin variable is found, false otherwise. 2560 bool EmitOMPCopyinClause(const OMPExecutableDirective &D); 2561 /// \brief Emit initial code for lastprivate variables. If some variable is 2562 /// not also firstprivate, then the default initialization is used. Otherwise 2563 /// initialization of this variable is performed by EmitOMPFirstprivateClause 2564 /// method. 2565 /// 2566 /// \param D Directive that may have 'lastprivate' directives. 2567 /// \param PrivateScope Private scope for capturing lastprivate variables for 2568 /// proper codegen in internal captured statement. 2569 /// 2570 /// \returns true if there is at least one lastprivate variable, false 2571 /// otherwise. 2572 bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D, 2573 OMPPrivateScope &PrivateScope); 2574 /// \brief Emit final copying of lastprivate values to original variables at 2575 /// the end of the worksharing or simd directive. 2576 /// 2577 /// \param D Directive that has at least one 'lastprivate' directives. 2578 /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if 2579 /// it is the last iteration of the loop code in associated directive, or to 2580 /// 'i1 false' otherwise. If this item is nullptr, no final check is required. 2581 void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D, 2582 bool NoFinals, 2583 llvm::Value *IsLastIterCond = nullptr); 2584 /// Emit initial code for linear clauses. 2585 void EmitOMPLinearClause(const OMPLoopDirective &D, 2586 CodeGenFunction::OMPPrivateScope &PrivateScope); 2587 /// Emit final code for linear clauses. 2588 /// \param CondGen Optional conditional code for final part of codegen for 2589 /// linear clause. 2590 void EmitOMPLinearClauseFinal( 2591 const OMPLoopDirective &D, 2592 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen); 2593 /// \brief Emit initial code for reduction variables. Creates reduction copies 2594 /// and initializes them with the values according to OpenMP standard. 2595 /// 2596 /// \param D Directive (possibly) with the 'reduction' clause. 2597 /// \param PrivateScope Private scope for capturing reduction variables for 2598 /// proper codegen in internal captured statement. 2599 /// 2600 void EmitOMPReductionClauseInit(const OMPExecutableDirective &D, 2601 OMPPrivateScope &PrivateScope); 2602 /// \brief Emit final update of reduction values to original variables at 2603 /// the end of the directive. 2604 /// 2605 /// \param D Directive that has at least one 'reduction' directives. 2606 void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D); 2607 /// \brief Emit initial code for linear variables. Creates private copies 2608 /// and initializes them with the values according to OpenMP standard. 2609 /// 2610 /// \param D Directive (possibly) with the 'linear' clause. 2611 void EmitOMPLinearClauseInit(const OMPLoopDirective &D); 2612 2613 typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/, 2614 llvm::Value * /*OutlinedFn*/, 2615 const OMPTaskDataTy & /*Data*/)> 2616 TaskGenTy; 2617 void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S, 2618 const RegionCodeGenTy &BodyGen, 2619 const TaskGenTy &TaskGen, OMPTaskDataTy &Data); 2620 2621 void EmitOMPParallelDirective(const OMPParallelDirective &S); 2622 void EmitOMPSimdDirective(const OMPSimdDirective &S); 2623 void EmitOMPForDirective(const OMPForDirective &S); 2624 void EmitOMPForSimdDirective(const OMPForSimdDirective &S); 2625 void EmitOMPSectionsDirective(const OMPSectionsDirective &S); 2626 void EmitOMPSectionDirective(const OMPSectionDirective &S); 2627 void EmitOMPSingleDirective(const OMPSingleDirective &S); 2628 void EmitOMPMasterDirective(const OMPMasterDirective &S); 2629 void EmitOMPCriticalDirective(const OMPCriticalDirective &S); 2630 void EmitOMPParallelForDirective(const OMPParallelForDirective &S); 2631 void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S); 2632 void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S); 2633 void EmitOMPTaskDirective(const OMPTaskDirective &S); 2634 void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S); 2635 void EmitOMPBarrierDirective(const OMPBarrierDirective &S); 2636 void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S); 2637 void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S); 2638 void EmitOMPFlushDirective(const OMPFlushDirective &S); 2639 void EmitOMPOrderedDirective(const OMPOrderedDirective &S); 2640 void EmitOMPAtomicDirective(const OMPAtomicDirective &S); 2641 void EmitOMPTargetDirective(const OMPTargetDirective &S); 2642 void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S); 2643 void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S); 2644 void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S); 2645 void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S); 2646 void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S); 2647 void 2648 EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S); 2649 void EmitOMPTeamsDirective(const OMPTeamsDirective &S); 2650 void 2651 EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S); 2652 void EmitOMPCancelDirective(const OMPCancelDirective &S); 2653 void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S); 2654 void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S); 2655 void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S); 2656 void EmitOMPDistributeDirective(const OMPDistributeDirective &S); 2657 void EmitOMPDistributeLoop(const OMPDistributeDirective &S); 2658 void EmitOMPDistributeParallelForDirective( 2659 const OMPDistributeParallelForDirective &S); 2660 void EmitOMPDistributeParallelForSimdDirective( 2661 const OMPDistributeParallelForSimdDirective &S); 2662 void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S); 2663 void EmitOMPTargetParallelForSimdDirective( 2664 const OMPTargetParallelForSimdDirective &S); 2665 void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S); 2666 void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S); 2667 void 2668 EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S); 2669 void EmitOMPTeamsDistributeParallelForSimdDirective( 2670 const OMPTeamsDistributeParallelForSimdDirective &S); 2671 void EmitOMPTeamsDistributeParallelForDirective( 2672 const OMPTeamsDistributeParallelForDirective &S); 2673 2674 /// Emit outlined function for the target directive. 2675 static std::pair<llvm::Function * /*OutlinedFn*/, 2676 llvm::Constant * /*OutlinedFnID*/> 2677 EmitOMPTargetDirectiveOutlinedFunction(CodeGenModule &CGM, 2678 const OMPTargetDirective &S, 2679 StringRef ParentName, 2680 bool IsOffloadEntry); 2681 /// \brief Emit inner loop of the worksharing/simd construct. 2682 /// 2683 /// \param S Directive, for which the inner loop must be emitted. 2684 /// \param RequiresCleanup true, if directive has some associated private 2685 /// variables. 2686 /// \param LoopCond Bollean condition for loop continuation. 2687 /// \param IncExpr Increment expression for loop control variable. 2688 /// \param BodyGen Generator for the inner body of the inner loop. 2689 /// \param PostIncGen Genrator for post-increment code (required for ordered 2690 /// loop directvies). 2691 void EmitOMPInnerLoop( 2692 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond, 2693 const Expr *IncExpr, 2694 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen, 2695 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen); 2696 2697 JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind); 2698 /// Emit initial code for loop counters of loop-based directives. 2699 void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S, 2700 OMPPrivateScope &LoopScope); 2701 2702 private: 2703 /// Helpers for the OpenMP loop directives. 2704 void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit); 2705 void EmitOMPSimdInit(const OMPLoopDirective &D, bool IsMonotonic = false); 2706 void EmitOMPSimdFinal( 2707 const OMPLoopDirective &D, 2708 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen); 2709 /// \brief Emit code for the worksharing loop-based directive. 2710 /// \return true, if this construct has any lastprivate clause, false - 2711 /// otherwise. 2712 bool EmitOMPWorksharingLoop(const OMPLoopDirective &S); 2713 void EmitOMPOuterLoop(bool IsMonotonic, bool DynamicOrOrdered, 2714 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered, 2715 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk); 2716 void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind, 2717 bool IsMonotonic, const OMPLoopDirective &S, 2718 OMPPrivateScope &LoopScope, bool Ordered, Address LB, 2719 Address UB, Address ST, Address IL, 2720 llvm::Value *Chunk); 2721 void EmitOMPDistributeOuterLoop( 2722 OpenMPDistScheduleClauseKind ScheduleKind, 2723 const OMPDistributeDirective &S, OMPPrivateScope &LoopScope, 2724 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk); 2725 /// \brief Emit code for sections directive. 2726 void EmitSections(const OMPExecutableDirective &S); 2727 2728 public: 2729 2730 //===--------------------------------------------------------------------===// 2731 // LValue Expression Emission 2732 //===--------------------------------------------------------------------===// 2733 2734 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type. 2735 RValue GetUndefRValue(QualType Ty); 2736 2737 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E 2738 /// and issue an ErrorUnsupported style diagnostic (using the 2739 /// provided Name). 2740 RValue EmitUnsupportedRValue(const Expr *E, 2741 const char *Name); 2742 2743 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue 2744 /// an ErrorUnsupported style diagnostic (using the provided Name). 2745 LValue EmitUnsupportedLValue(const Expr *E, 2746 const char *Name); 2747 2748 /// EmitLValue - Emit code to compute a designator that specifies the location 2749 /// of the expression. 2750 /// 2751 /// This can return one of two things: a simple address or a bitfield 2752 /// reference. In either case, the LLVM Value* in the LValue structure is 2753 /// guaranteed to be an LLVM pointer type. 2754 /// 2755 /// If this returns a bitfield reference, nothing about the pointee type of 2756 /// the LLVM value is known: For example, it may not be a pointer to an 2757 /// integer. 2758 /// 2759 /// If this returns a normal address, and if the lvalue's C type is fixed 2760 /// size, this method guarantees that the returned pointer type will point to 2761 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a 2762 /// variable length type, this is not possible. 2763 /// 2764 LValue EmitLValue(const Expr *E); 2765 2766 /// \brief Same as EmitLValue but additionally we generate checking code to 2767 /// guard against undefined behavior. This is only suitable when we know 2768 /// that the address will be used to access the object. 2769 LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK); 2770 2771 RValue convertTempToRValue(Address addr, QualType type, 2772 SourceLocation Loc); 2773 2774 void EmitAtomicInit(Expr *E, LValue lvalue); 2775 2776 bool LValueIsSuitableForInlineAtomic(LValue Src); 2777 2778 RValue EmitAtomicLoad(LValue LV, SourceLocation SL, 2779 AggValueSlot Slot = AggValueSlot::ignored()); 2780 2781 RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc, 2782 llvm::AtomicOrdering AO, bool IsVolatile = false, 2783 AggValueSlot slot = AggValueSlot::ignored()); 2784 2785 void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit); 2786 2787 void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO, 2788 bool IsVolatile, bool isInit); 2789 2790 std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange( 2791 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc, 2792 llvm::AtomicOrdering Success = 2793 llvm::AtomicOrdering::SequentiallyConsistent, 2794 llvm::AtomicOrdering Failure = 2795 llvm::AtomicOrdering::SequentiallyConsistent, 2796 bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored()); 2797 2798 void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO, 2799 const llvm::function_ref<RValue(RValue)> &UpdateOp, 2800 bool IsVolatile); 2801 2802 /// EmitToMemory - Change a scalar value from its value 2803 /// representation to its in-memory representation. 2804 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty); 2805 2806 /// EmitFromMemory - Change a scalar value from its memory 2807 /// representation to its value representation. 2808 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty); 2809 2810 /// EmitLoadOfScalar - Load a scalar value from an address, taking 2811 /// care to appropriately convert from the memory representation to 2812 /// the LLVM value representation. 2813 llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, 2814 SourceLocation Loc, 2815 AlignmentSource AlignSource = 2816 AlignmentSource::Type, 2817 llvm::MDNode *TBAAInfo = nullptr, 2818 QualType TBAABaseTy = QualType(), 2819 uint64_t TBAAOffset = 0, 2820 bool isNontemporal = false); 2821 2822 /// EmitLoadOfScalar - Load a scalar value from an address, taking 2823 /// care to appropriately convert from the memory representation to 2824 /// the LLVM value representation. The l-value must be a simple 2825 /// l-value. 2826 llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc); 2827 2828 /// EmitStoreOfScalar - Store a scalar value to an address, taking 2829 /// care to appropriately convert from the memory representation to 2830 /// the LLVM value representation. 2831 void EmitStoreOfScalar(llvm::Value *Value, Address Addr, 2832 bool Volatile, QualType Ty, 2833 AlignmentSource AlignSource = AlignmentSource::Type, 2834 llvm::MDNode *TBAAInfo = nullptr, bool isInit = false, 2835 QualType TBAABaseTy = QualType(), 2836 uint64_t TBAAOffset = 0, bool isNontemporal = false); 2837 2838 /// EmitStoreOfScalar - Store a scalar value to an address, taking 2839 /// care to appropriately convert from the memory representation to 2840 /// the LLVM value representation. The l-value must be a simple 2841 /// l-value. The isInit flag indicates whether this is an initialization. 2842 /// If so, atomic qualifiers are ignored and the store is always non-atomic. 2843 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false); 2844 2845 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, 2846 /// this method emits the address of the lvalue, then loads the result as an 2847 /// rvalue, returning the rvalue. 2848 RValue EmitLoadOfLValue(LValue V, SourceLocation Loc); 2849 RValue EmitLoadOfExtVectorElementLValue(LValue V); 2850 RValue EmitLoadOfBitfieldLValue(LValue LV); 2851 RValue EmitLoadOfGlobalRegLValue(LValue LV); 2852 2853 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 2854 /// lvalue, where both are guaranteed to the have the same type, and that type 2855 /// is 'Ty'. 2856 void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false); 2857 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst); 2858 void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst); 2859 2860 /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints 2861 /// as EmitStoreThroughLValue. 2862 /// 2863 /// \param Result [out] - If non-null, this will be set to a Value* for the 2864 /// bit-field contents after the store, appropriate for use as the result of 2865 /// an assignment to the bit-field. 2866 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 2867 llvm::Value **Result=nullptr); 2868 2869 /// Emit an l-value for an assignment (simple or compound) of complex type. 2870 LValue EmitComplexAssignmentLValue(const BinaryOperator *E); 2871 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E); 2872 LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E, 2873 llvm::Value *&Result); 2874 2875 // Note: only available for agg return types 2876 LValue EmitBinaryOperatorLValue(const BinaryOperator *E); 2877 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E); 2878 // Note: only available for agg return types 2879 LValue EmitCallExprLValue(const CallExpr *E); 2880 // Note: only available for agg return types 2881 LValue EmitVAArgExprLValue(const VAArgExpr *E); 2882 LValue EmitDeclRefLValue(const DeclRefExpr *E); 2883 LValue EmitStringLiteralLValue(const StringLiteral *E); 2884 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E); 2885 LValue EmitPredefinedLValue(const PredefinedExpr *E); 2886 LValue EmitUnaryOpLValue(const UnaryOperator *E); 2887 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E, 2888 bool Accessed = false); 2889 LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E, 2890 bool IsLowerBound = true); 2891 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E); 2892 LValue EmitMemberExpr(const MemberExpr *E); 2893 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E); 2894 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E); 2895 LValue EmitInitListLValue(const InitListExpr *E); 2896 LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E); 2897 LValue EmitCastLValue(const CastExpr *E); 2898 LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 2899 LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e); 2900 2901 Address EmitExtVectorElementLValue(LValue V); 2902 2903 RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc); 2904 2905 Address EmitArrayToPointerDecay(const Expr *Array, 2906 AlignmentSource *AlignSource = nullptr); 2907 2908 class ConstantEmission { 2909 llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference; 2910 ConstantEmission(llvm::Constant *C, bool isReference) 2911 : ValueAndIsReference(C, isReference) {} 2912 public: 2913 ConstantEmission() {} 2914 static ConstantEmission forReference(llvm::Constant *C) { 2915 return ConstantEmission(C, true); 2916 } 2917 static ConstantEmission forValue(llvm::Constant *C) { 2918 return ConstantEmission(C, false); 2919 } 2920 2921 explicit operator bool() const { 2922 return ValueAndIsReference.getOpaqueValue() != nullptr; 2923 } 2924 2925 bool isReference() const { return ValueAndIsReference.getInt(); } 2926 LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const { 2927 assert(isReference()); 2928 return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(), 2929 refExpr->getType()); 2930 } 2931 2932 llvm::Constant *getValue() const { 2933 assert(!isReference()); 2934 return ValueAndIsReference.getPointer(); 2935 } 2936 }; 2937 2938 ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr); 2939 2940 RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, 2941 AggValueSlot slot = AggValueSlot::ignored()); 2942 LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e); 2943 2944 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface, 2945 const ObjCIvarDecl *Ivar); 2946 LValue EmitLValueForField(LValue Base, const FieldDecl* Field); 2947 LValue EmitLValueForLambdaField(const FieldDecl *Field); 2948 2949 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that 2950 /// if the Field is a reference, this will return the address of the reference 2951 /// and not the address of the value stored in the reference. 2952 LValue EmitLValueForFieldInitialization(LValue Base, 2953 const FieldDecl* Field); 2954 2955 LValue EmitLValueForIvar(QualType ObjectTy, 2956 llvm::Value* Base, const ObjCIvarDecl *Ivar, 2957 unsigned CVRQualifiers); 2958 2959 LValue EmitCXXConstructLValue(const CXXConstructExpr *E); 2960 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E); 2961 LValue EmitLambdaLValue(const LambdaExpr *E); 2962 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E); 2963 LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E); 2964 2965 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E); 2966 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E); 2967 LValue EmitStmtExprLValue(const StmtExpr *E); 2968 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E); 2969 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E); 2970 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init); 2971 2972 //===--------------------------------------------------------------------===// 2973 // Scalar Expression Emission 2974 //===--------------------------------------------------------------------===// 2975 2976 /// EmitCall - Generate a call of the given function, expecting the given 2977 /// result type, and using the given argument list which specifies both the 2978 /// LLVM arguments and the types they were derived from. 2979 RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, 2980 ReturnValueSlot ReturnValue, const CallArgList &Args, 2981 llvm::Instruction **callOrInvoke = nullptr); 2982 2983 RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E, 2984 ReturnValueSlot ReturnValue, 2985 llvm::Value *Chain = nullptr); 2986 RValue EmitCallExpr(const CallExpr *E, 2987 ReturnValueSlot ReturnValue = ReturnValueSlot()); 2988 RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue); 2989 CGCallee EmitCallee(const Expr *E); 2990 2991 void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl); 2992 2993 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee, 2994 const Twine &name = ""); 2995 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee, 2996 ArrayRef<llvm::Value*> args, 2997 const Twine &name = ""); 2998 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee, 2999 const Twine &name = ""); 3000 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee, 3001 ArrayRef<llvm::Value*> args, 3002 const Twine &name = ""); 3003 3004 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee, 3005 ArrayRef<llvm::Value *> Args, 3006 const Twine &Name = ""); 3007 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee, 3008 ArrayRef<llvm::Value*> args, 3009 const Twine &name = ""); 3010 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee, 3011 const Twine &name = ""); 3012 void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee, 3013 ArrayRef<llvm::Value*> args); 3014 3015 CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD, 3016 NestedNameSpecifier *Qual, 3017 llvm::Type *Ty); 3018 3019 CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD, 3020 CXXDtorType Type, 3021 const CXXRecordDecl *RD); 3022 3023 RValue 3024 EmitCXXMemberOrOperatorCall(const CXXMethodDecl *Method, 3025 const CGCallee &Callee, 3026 ReturnValueSlot ReturnValue, llvm::Value *This, 3027 llvm::Value *ImplicitParam, 3028 QualType ImplicitParamTy, const CallExpr *E, 3029 CallArgList *RtlArgs); 3030 RValue EmitCXXDestructorCall(const CXXDestructorDecl *DD, 3031 const CGCallee &Callee, 3032 llvm::Value *This, llvm::Value *ImplicitParam, 3033 QualType ImplicitParamTy, const CallExpr *E, 3034 StructorType Type); 3035 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E, 3036 ReturnValueSlot ReturnValue); 3037 RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE, 3038 const CXXMethodDecl *MD, 3039 ReturnValueSlot ReturnValue, 3040 bool HasQualifier, 3041 NestedNameSpecifier *Qualifier, 3042 bool IsArrow, const Expr *Base); 3043 // Compute the object pointer. 3044 Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base, 3045 llvm::Value *memberPtr, 3046 const MemberPointerType *memberPtrType, 3047 AlignmentSource *AlignSource = nullptr); 3048 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, 3049 ReturnValueSlot ReturnValue); 3050 3051 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 3052 const CXXMethodDecl *MD, 3053 ReturnValueSlot ReturnValue); 3054 RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E); 3055 3056 RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, 3057 ReturnValueSlot ReturnValue); 3058 3059 RValue EmitCUDADevicePrintfCallExpr(const CallExpr *E, 3060 ReturnValueSlot ReturnValue); 3061 3062 RValue EmitBuiltinExpr(const FunctionDecl *FD, 3063 unsigned BuiltinID, const CallExpr *E, 3064 ReturnValueSlot ReturnValue); 3065 3066 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue); 3067 3068 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call 3069 /// is unhandled by the current target. 3070 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3071 3072 llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty, 3073 const llvm::CmpInst::Predicate Fp, 3074 const llvm::CmpInst::Predicate Ip, 3075 const llvm::Twine &Name = ""); 3076 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3077 3078 llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID, 3079 unsigned LLVMIntrinsic, 3080 unsigned AltLLVMIntrinsic, 3081 const char *NameHint, 3082 unsigned Modifier, 3083 const CallExpr *E, 3084 SmallVectorImpl<llvm::Value *> &Ops, 3085 Address PtrOp0, Address PtrOp1); 3086 llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID, 3087 unsigned Modifier, llvm::Type *ArgTy, 3088 const CallExpr *E); 3089 llvm::Value *EmitNeonCall(llvm::Function *F, 3090 SmallVectorImpl<llvm::Value*> &O, 3091 const char *name, 3092 unsigned shift = 0, bool rightshift = false); 3093 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx); 3094 llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty, 3095 bool negateForRightShift); 3096 llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt, 3097 llvm::Type *Ty, bool usgn, const char *name); 3098 llvm::Value *vectorWrapScalar16(llvm::Value *Op); 3099 llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3100 3101 llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops); 3102 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3103 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3104 llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3105 llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3106 llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3107 llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID, 3108 const CallExpr *E); 3109 3110 private: 3111 enum class MSVCIntrin; 3112 3113 public: 3114 llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E); 3115 3116 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E); 3117 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E); 3118 llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E); 3119 llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E); 3120 llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E); 3121 llvm::Value *EmitObjCCollectionLiteral(const Expr *E, 3122 const ObjCMethodDecl *MethodWithObjects); 3123 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E); 3124 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, 3125 ReturnValueSlot Return = ReturnValueSlot()); 3126 3127 /// Retrieves the default cleanup kind for an ARC cleanup. 3128 /// Except under -fobjc-arc-eh, ARC cleanups are normal-only. 3129 CleanupKind getARCCleanupKind() { 3130 return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions 3131 ? NormalAndEHCleanup : NormalCleanup; 3132 } 3133 3134 // ARC primitives. 3135 void EmitARCInitWeak(Address addr, llvm::Value *value); 3136 void EmitARCDestroyWeak(Address addr); 3137 llvm::Value *EmitARCLoadWeak(Address addr); 3138 llvm::Value *EmitARCLoadWeakRetained(Address addr); 3139 llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored); 3140 void EmitARCCopyWeak(Address dst, Address src); 3141 void EmitARCMoveWeak(Address dst, Address src); 3142 llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value); 3143 llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value); 3144 llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value, 3145 bool resultIgnored); 3146 llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value, 3147 bool resultIgnored); 3148 llvm::Value *EmitARCRetain(QualType type, llvm::Value *value); 3149 llvm::Value *EmitARCRetainNonBlock(llvm::Value *value); 3150 llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory); 3151 void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise); 3152 void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise); 3153 llvm::Value *EmitARCAutorelease(llvm::Value *value); 3154 llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value); 3155 llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value); 3156 llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value); 3157 llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value); 3158 3159 std::pair<LValue,llvm::Value*> 3160 EmitARCStoreAutoreleasing(const BinaryOperator *e); 3161 std::pair<LValue,llvm::Value*> 3162 EmitARCStoreStrong(const BinaryOperator *e, bool ignored); 3163 std::pair<LValue,llvm::Value*> 3164 EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored); 3165 3166 llvm::Value *EmitObjCThrowOperand(const Expr *expr); 3167 llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr); 3168 llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr); 3169 3170 llvm::Value *EmitARCExtendBlockObject(const Expr *expr); 3171 llvm::Value *EmitARCReclaimReturnedObject(const Expr *e, 3172 bool allowUnsafeClaim); 3173 llvm::Value *EmitARCRetainScalarExpr(const Expr *expr); 3174 llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr); 3175 llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr); 3176 3177 void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values); 3178 3179 static Destroyer destroyARCStrongImprecise; 3180 static Destroyer destroyARCStrongPrecise; 3181 static Destroyer destroyARCWeak; 3182 3183 void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr); 3184 llvm::Value *EmitObjCAutoreleasePoolPush(); 3185 llvm::Value *EmitObjCMRRAutoreleasePoolPush(); 3186 void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr); 3187 void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr); 3188 3189 /// \brief Emits a reference binding to the passed in expression. 3190 RValue EmitReferenceBindingToExpr(const Expr *E); 3191 3192 //===--------------------------------------------------------------------===// 3193 // Expression Emission 3194 //===--------------------------------------------------------------------===// 3195 3196 // Expressions are broken into three classes: scalar, complex, aggregate. 3197 3198 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM 3199 /// scalar type, returning the result. 3200 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false); 3201 3202 /// Emit a conversion from the specified type to the specified destination 3203 /// type, both of which are LLVM scalar types. 3204 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy, 3205 QualType DstTy, SourceLocation Loc); 3206 3207 /// Emit a conversion from the specified complex type to the specified 3208 /// destination type, where the destination type is an LLVM scalar type. 3209 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, 3210 QualType DstTy, 3211 SourceLocation Loc); 3212 3213 /// EmitAggExpr - Emit the computation of the specified expression 3214 /// of aggregate type. The result is computed into the given slot, 3215 /// which may be null to indicate that the value is not needed. 3216 void EmitAggExpr(const Expr *E, AggValueSlot AS); 3217 3218 /// EmitAggExprToLValue - Emit the computation of the specified expression of 3219 /// aggregate type into a temporary LValue. 3220 LValue EmitAggExprToLValue(const Expr *E); 3221 3222 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object, 3223 /// make sure it survives garbage collection until this point. 3224 void EmitExtendGCLifetime(llvm::Value *object); 3225 3226 /// EmitComplexExpr - Emit the computation of the specified expression of 3227 /// complex type, returning the result. 3228 ComplexPairTy EmitComplexExpr(const Expr *E, 3229 bool IgnoreReal = false, 3230 bool IgnoreImag = false); 3231 3232 /// EmitComplexExprIntoLValue - Emit the given expression of complex 3233 /// type and place its result into the specified l-value. 3234 void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit); 3235 3236 /// EmitStoreOfComplex - Store a complex number into the specified l-value. 3237 void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit); 3238 3239 /// EmitLoadOfComplex - Load a complex number from the specified l-value. 3240 ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc); 3241 3242 Address emitAddrOfRealComponent(Address complex, QualType complexType); 3243 Address emitAddrOfImagComponent(Address complex, QualType complexType); 3244 3245 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the 3246 /// global variable that has already been created for it. If the initializer 3247 /// has a different type than GV does, this may free GV and return a different 3248 /// one. Otherwise it just returns GV. 3249 llvm::GlobalVariable * 3250 AddInitializerToStaticVarDecl(const VarDecl &D, 3251 llvm::GlobalVariable *GV); 3252 3253 3254 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++ 3255 /// variable with global storage. 3256 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr, 3257 bool PerformInit); 3258 3259 llvm::Constant *createAtExitStub(const VarDecl &VD, llvm::Constant *Dtor, 3260 llvm::Constant *Addr); 3261 3262 /// Call atexit() with a function that passes the given argument to 3263 /// the given function. 3264 void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn, 3265 llvm::Constant *addr); 3266 3267 /// Emit code in this function to perform a guarded variable 3268 /// initialization. Guarded initializations are used when it's not 3269 /// possible to prove that an initialization will be done exactly 3270 /// once, e.g. with a static local variable or a static data member 3271 /// of a class template. 3272 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr, 3273 bool PerformInit); 3274 3275 /// GenerateCXXGlobalInitFunc - Generates code for initializing global 3276 /// variables. 3277 void GenerateCXXGlobalInitFunc(llvm::Function *Fn, 3278 ArrayRef<llvm::Function *> CXXThreadLocals, 3279 Address Guard = Address::invalid()); 3280 3281 /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global 3282 /// variables. 3283 void GenerateCXXGlobalDtorsFunc(llvm::Function *Fn, 3284 const std::vector<std::pair<llvm::WeakVH, 3285 llvm::Constant*> > &DtorsAndObjects); 3286 3287 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, 3288 const VarDecl *D, 3289 llvm::GlobalVariable *Addr, 3290 bool PerformInit); 3291 3292 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest); 3293 3294 void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp); 3295 3296 void enterFullExpression(const ExprWithCleanups *E) { 3297 if (E->getNumObjects() == 0) return; 3298 enterNonTrivialFullExpression(E); 3299 } 3300 void enterNonTrivialFullExpression(const ExprWithCleanups *E); 3301 3302 void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true); 3303 3304 void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest); 3305 3306 RValue EmitAtomicExpr(AtomicExpr *E); 3307 3308 //===--------------------------------------------------------------------===// 3309 // Annotations Emission 3310 //===--------------------------------------------------------------------===// 3311 3312 /// Emit an annotation call (intrinsic or builtin). 3313 llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn, 3314 llvm::Value *AnnotatedVal, 3315 StringRef AnnotationStr, 3316 SourceLocation Location); 3317 3318 /// Emit local annotations for the local variable V, declared by D. 3319 void EmitVarAnnotations(const VarDecl *D, llvm::Value *V); 3320 3321 /// Emit field annotations for the given field & value. Returns the 3322 /// annotation result. 3323 Address EmitFieldAnnotations(const FieldDecl *D, Address V); 3324 3325 //===--------------------------------------------------------------------===// 3326 // Internal Helpers 3327 //===--------------------------------------------------------------------===// 3328 3329 /// ContainsLabel - Return true if the statement contains a label in it. If 3330 /// this statement is not executed normally, it not containing a label means 3331 /// that we can just remove the code. 3332 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false); 3333 3334 /// containsBreak - Return true if the statement contains a break out of it. 3335 /// If the statement (recursively) contains a switch or loop with a break 3336 /// inside of it, this is fine. 3337 static bool containsBreak(const Stmt *S); 3338 3339 /// Determine if the given statement might introduce a declaration into the 3340 /// current scope, by being a (possibly-labelled) DeclStmt. 3341 static bool mightAddDeclToScope(const Stmt *S); 3342 3343 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 3344 /// to a constant, or if it does but contains a label, return false. If it 3345 /// constant folds return true and set the boolean result in Result. 3346 bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result, 3347 bool AllowLabels = false); 3348 3349 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 3350 /// to a constant, or if it does but contains a label, return false. If it 3351 /// constant folds return true and set the folded value. 3352 bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result, 3353 bool AllowLabels = false); 3354 3355 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an 3356 /// if statement) to the specified blocks. Based on the condition, this might 3357 /// try to simplify the codegen of the conditional based on the branch. 3358 /// TrueCount should be the number of times we expect the condition to 3359 /// evaluate to true based on PGO data. 3360 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, 3361 llvm::BasicBlock *FalseBlock, uint64_t TrueCount); 3362 3363 /// \brief Emit a description of a type in a format suitable for passing to 3364 /// a runtime sanitizer handler. 3365 llvm::Constant *EmitCheckTypeDescriptor(QualType T); 3366 3367 /// \brief Convert a value into a format suitable for passing to a runtime 3368 /// sanitizer handler. 3369 llvm::Value *EmitCheckValue(llvm::Value *V); 3370 3371 /// \brief Emit a description of a source location in a format suitable for 3372 /// passing to a runtime sanitizer handler. 3373 llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc); 3374 3375 /// \brief Create a basic block that will call a handler function in a 3376 /// sanitizer runtime with the provided arguments, and create a conditional 3377 /// branch to it. 3378 void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked, 3379 StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs, 3380 ArrayRef<llvm::Value *> DynamicArgs); 3381 3382 /// \brief Emit a slow path cross-DSO CFI check which calls __cfi_slowpath 3383 /// if Cond if false. 3384 void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond, 3385 llvm::ConstantInt *TypeId, llvm::Value *Ptr, 3386 ArrayRef<llvm::Constant *> StaticArgs); 3387 3388 /// \brief Create a basic block that will call the trap intrinsic, and emit a 3389 /// conditional branch to it, for the -ftrapv checks. 3390 void EmitTrapCheck(llvm::Value *Checked); 3391 3392 /// \brief Emit a call to trap or debugtrap and attach function attribute 3393 /// "trap-func-name" if specified. 3394 llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID); 3395 3396 /// \brief Emit a cross-DSO CFI failure handling function. 3397 void EmitCfiCheckFail(); 3398 3399 /// \brief Create a check for a function parameter that may potentially be 3400 /// declared as non-null. 3401 void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc, 3402 const FunctionDecl *FD, unsigned ParmNum); 3403 3404 /// EmitCallArg - Emit a single call argument. 3405 void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType); 3406 3407 /// EmitDelegateCallArg - We are performing a delegate call; that 3408 /// is, the current function is delegating to another one. Produce 3409 /// a r-value suitable for passing the given parameter. 3410 void EmitDelegateCallArg(CallArgList &args, const VarDecl *param, 3411 SourceLocation loc); 3412 3413 /// SetFPAccuracy - Set the minimum required accuracy of the given floating 3414 /// point operation, expressed as the maximum relative error in ulp. 3415 void SetFPAccuracy(llvm::Value *Val, float Accuracy); 3416 3417 private: 3418 llvm::MDNode *getRangeForLoadFromType(QualType Ty); 3419 void EmitReturnOfRValue(RValue RV, QualType Ty); 3420 3421 void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New); 3422 3423 llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4> 3424 DeferredReplacements; 3425 3426 /// Set the address of a local variable. 3427 void setAddrOfLocalVar(const VarDecl *VD, Address Addr) { 3428 assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!"); 3429 LocalDeclMap.insert({VD, Addr}); 3430 } 3431 3432 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty 3433 /// from function arguments into \arg Dst. See ABIArgInfo::Expand. 3434 /// 3435 /// \param AI - The first function argument of the expansion. 3436 void ExpandTypeFromArgs(QualType Ty, LValue Dst, 3437 SmallVectorImpl<llvm::Value *>::iterator &AI); 3438 3439 /// ExpandTypeToArgs - Expand an RValue \arg RV, with the LLVM type for \arg 3440 /// Ty, into individual arguments on the provided vector \arg IRCallArgs, 3441 /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand. 3442 void ExpandTypeToArgs(QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy, 3443 SmallVectorImpl<llvm::Value *> &IRCallArgs, 3444 unsigned &IRCallArgPos); 3445 3446 llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info, 3447 const Expr *InputExpr, std::string &ConstraintStr); 3448 3449 llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info, 3450 LValue InputValue, QualType InputType, 3451 std::string &ConstraintStr, 3452 SourceLocation Loc); 3453 3454 /// \brief Attempts to statically evaluate the object size of E. If that 3455 /// fails, emits code to figure the size of E out for us. This is 3456 /// pass_object_size aware. 3457 llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type, 3458 llvm::IntegerType *ResType); 3459 3460 /// \brief Emits the size of E, as required by __builtin_object_size. This 3461 /// function is aware of pass_object_size parameters, and will act accordingly 3462 /// if E is a parameter with the pass_object_size attribute. 3463 llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type, 3464 llvm::IntegerType *ResType); 3465 3466 public: 3467 #ifndef NDEBUG 3468 // Determine whether the given argument is an Objective-C method 3469 // that may have type parameters in its signature. 3470 static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) { 3471 const DeclContext *dc = method->getDeclContext(); 3472 if (const ObjCInterfaceDecl *classDecl= dyn_cast<ObjCInterfaceDecl>(dc)) { 3473 return classDecl->getTypeParamListAsWritten(); 3474 } 3475 3476 if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) { 3477 return catDecl->getTypeParamList(); 3478 } 3479 3480 return false; 3481 } 3482 3483 template<typename T> 3484 static bool isObjCMethodWithTypeParams(const T *) { return false; } 3485 #endif 3486 3487 enum class EvaluationOrder { 3488 ///! No language constraints on evaluation order. 3489 Default, 3490 ///! Language semantics require left-to-right evaluation. 3491 ForceLeftToRight, 3492 ///! Language semantics require right-to-left evaluation. 3493 ForceRightToLeft 3494 }; 3495 3496 /// EmitCallArgs - Emit call arguments for a function. 3497 template <typename T> 3498 void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo, 3499 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange, 3500 const FunctionDecl *CalleeDecl = nullptr, 3501 unsigned ParamsToSkip = 0, 3502 EvaluationOrder Order = EvaluationOrder::Default) { 3503 SmallVector<QualType, 16> ArgTypes; 3504 CallExpr::const_arg_iterator Arg = ArgRange.begin(); 3505 3506 assert((ParamsToSkip == 0 || CallArgTypeInfo) && 3507 "Can't skip parameters if type info is not provided"); 3508 if (CallArgTypeInfo) { 3509 #ifndef NDEBUG 3510 bool isGenericMethod = isObjCMethodWithTypeParams(CallArgTypeInfo); 3511 #endif 3512 3513 // First, use the argument types that the type info knows about 3514 for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip, 3515 E = CallArgTypeInfo->param_type_end(); 3516 I != E; ++I, ++Arg) { 3517 assert(Arg != ArgRange.end() && "Running over edge of argument list!"); 3518 assert((isGenericMethod || 3519 ((*I)->isVariablyModifiedType() || 3520 (*I).getNonReferenceType()->isObjCRetainableType() || 3521 getContext() 3522 .getCanonicalType((*I).getNonReferenceType()) 3523 .getTypePtr() == 3524 getContext() 3525 .getCanonicalType((*Arg)->getType()) 3526 .getTypePtr())) && 3527 "type mismatch in call argument!"); 3528 ArgTypes.push_back(*I); 3529 } 3530 } 3531 3532 // Either we've emitted all the call args, or we have a call to variadic 3533 // function. 3534 assert((Arg == ArgRange.end() || !CallArgTypeInfo || 3535 CallArgTypeInfo->isVariadic()) && 3536 "Extra arguments in non-variadic function!"); 3537 3538 // If we still have any arguments, emit them using the type of the argument. 3539 for (auto *A : llvm::make_range(Arg, ArgRange.end())) 3540 ArgTypes.push_back(getVarArgType(A)); 3541 3542 EmitCallArgs(Args, ArgTypes, ArgRange, CalleeDecl, ParamsToSkip, Order); 3543 } 3544 3545 void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes, 3546 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange, 3547 const FunctionDecl *CalleeDecl = nullptr, 3548 unsigned ParamsToSkip = 0, 3549 EvaluationOrder Order = EvaluationOrder::Default); 3550 3551 /// EmitPointerWithAlignment - Given an expression with a pointer 3552 /// type, emit the value and compute our best estimate of the 3553 /// alignment of the pointee. 3554 /// 3555 /// Note that this function will conservatively fall back on the type 3556 /// when it doesn't 3557 /// 3558 /// \param Source - If non-null, this will be initialized with 3559 /// information about the source of the alignment. Note that this 3560 /// function will conservatively fall back on the type when it 3561 /// doesn't recognize the expression, which means that sometimes 3562 /// 3563 /// a worst-case One 3564 /// reasonable way to use this information is when there's a 3565 /// language guarantee that the pointer must be aligned to some 3566 /// stricter value, and we're simply trying to ensure that 3567 /// sufficiently obvious uses of under-aligned objects don't get 3568 /// miscompiled; for example, a placement new into the address of 3569 /// a local variable. In such a case, it's quite reasonable to 3570 /// just ignore the returned alignment when it isn't from an 3571 /// explicit source. 3572 Address EmitPointerWithAlignment(const Expr *Addr, 3573 AlignmentSource *Source = nullptr); 3574 3575 void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK); 3576 3577 private: 3578 QualType getVarArgType(const Expr *Arg); 3579 3580 const TargetCodeGenInfo &getTargetHooks() const { 3581 return CGM.getTargetCodeGenInfo(); 3582 } 3583 3584 void EmitDeclMetadata(); 3585 3586 BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType, 3587 const AutoVarEmission &emission); 3588 3589 void AddObjCARCExceptionMetadata(llvm::Instruction *Inst); 3590 3591 llvm::Value *GetValueForARMHint(unsigned BuiltinID); 3592 }; 3593 3594 /// Helper class with most of the code for saving a value for a 3595 /// conditional expression cleanup. 3596 struct DominatingLLVMValue { 3597 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type; 3598 3599 /// Answer whether the given value needs extra work to be saved. 3600 static bool needsSaving(llvm::Value *value) { 3601 // If it's not an instruction, we don't need to save. 3602 if (!isa<llvm::Instruction>(value)) return false; 3603 3604 // If it's an instruction in the entry block, we don't need to save. 3605 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent(); 3606 return (block != &block->getParent()->getEntryBlock()); 3607 } 3608 3609 /// Try to save the given value. 3610 static saved_type save(CodeGenFunction &CGF, llvm::Value *value) { 3611 if (!needsSaving(value)) return saved_type(value, false); 3612 3613 // Otherwise, we need an alloca. 3614 auto align = CharUnits::fromQuantity( 3615 CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType())); 3616 Address alloca = 3617 CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save"); 3618 CGF.Builder.CreateStore(value, alloca); 3619 3620 return saved_type(alloca.getPointer(), true); 3621 } 3622 3623 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) { 3624 // If the value says it wasn't saved, trust that it's still dominating. 3625 if (!value.getInt()) return value.getPointer(); 3626 3627 // Otherwise, it should be an alloca instruction, as set up in save(). 3628 auto alloca = cast<llvm::AllocaInst>(value.getPointer()); 3629 return CGF.Builder.CreateAlignedLoad(alloca, alloca->getAlignment()); 3630 } 3631 }; 3632 3633 /// A partial specialization of DominatingValue for llvm::Values that 3634 /// might be llvm::Instructions. 3635 template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue { 3636 typedef T *type; 3637 static type restore(CodeGenFunction &CGF, saved_type value) { 3638 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value)); 3639 } 3640 }; 3641 3642 /// A specialization of DominatingValue for Address. 3643 template <> struct DominatingValue<Address> { 3644 typedef Address type; 3645 3646 struct saved_type { 3647 DominatingLLVMValue::saved_type SavedValue; 3648 CharUnits Alignment; 3649 }; 3650 3651 static bool needsSaving(type value) { 3652 return DominatingLLVMValue::needsSaving(value.getPointer()); 3653 } 3654 static saved_type save(CodeGenFunction &CGF, type value) { 3655 return { DominatingLLVMValue::save(CGF, value.getPointer()), 3656 value.getAlignment() }; 3657 } 3658 static type restore(CodeGenFunction &CGF, saved_type value) { 3659 return Address(DominatingLLVMValue::restore(CGF, value.SavedValue), 3660 value.Alignment); 3661 } 3662 }; 3663 3664 /// A specialization of DominatingValue for RValue. 3665 template <> struct DominatingValue<RValue> { 3666 typedef RValue type; 3667 class saved_type { 3668 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral, 3669 AggregateAddress, ComplexAddress }; 3670 3671 llvm::Value *Value; 3672 unsigned K : 3; 3673 unsigned Align : 29; 3674 saved_type(llvm::Value *v, Kind k, unsigned a = 0) 3675 : Value(v), K(k), Align(a) {} 3676 3677 public: 3678 static bool needsSaving(RValue value); 3679 static saved_type save(CodeGenFunction &CGF, RValue value); 3680 RValue restore(CodeGenFunction &CGF); 3681 3682 // implementations in CGCleanup.cpp 3683 }; 3684 3685 static bool needsSaving(type value) { 3686 return saved_type::needsSaving(value); 3687 } 3688 static saved_type save(CodeGenFunction &CGF, type value) { 3689 return saved_type::save(CGF, value); 3690 } 3691 static type restore(CodeGenFunction &CGF, saved_type value) { 3692 return value.restore(CGF); 3693 } 3694 }; 3695 3696 } // end namespace CodeGen 3697 } // end namespace clang 3698 3699 #endif 3700