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 OpaqueValueMapping(CodeGenFunction &CGF, 922 const OpaqueValueExpr *opaqueValue, 923 LValue lvalue) 924 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) { 925 } 926 927 OpaqueValueMapping(CodeGenFunction &CGF, 928 const OpaqueValueExpr *opaqueValue, 929 RValue rvalue) 930 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) { 931 } 932 933 void pop() { 934 Data.unbind(CGF); 935 Data.clear(); 936 } 937 938 ~OpaqueValueMapping() { 939 if (Data.isValid()) Data.unbind(CGF); 940 } 941 }; 942 943 private: 944 CGDebugInfo *DebugInfo; 945 bool DisableDebugInfo; 946 947 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid 948 /// calling llvm.stacksave for multiple VLAs in the same scope. 949 bool DidCallStackSave; 950 951 /// IndirectBranch - The first time an indirect goto is seen we create a block 952 /// with an indirect branch. Every time we see the address of a label taken, 953 /// we add the label to the indirect goto. Every subsequent indirect goto is 954 /// codegen'd as a jump to the IndirectBranch's basic block. 955 llvm::IndirectBrInst *IndirectBranch; 956 957 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C 958 /// decls. 959 DeclMapTy LocalDeclMap; 960 961 /// SizeArguments - If a ParmVarDecl had the pass_object_size attribute, this 962 /// will contain a mapping from said ParmVarDecl to its implicit "object_size" 963 /// parameter. 964 llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *, 2> 965 SizeArguments; 966 967 /// Track escaped local variables with auto storage. Used during SEH 968 /// outlining to produce a call to llvm.localescape. 969 llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals; 970 971 /// LabelMap - This keeps track of the LLVM basic block for each C label. 972 llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap; 973 974 // BreakContinueStack - This keeps track of where break and continue 975 // statements should jump to. 976 struct BreakContinue { 977 BreakContinue(JumpDest Break, JumpDest Continue) 978 : BreakBlock(Break), ContinueBlock(Continue) {} 979 980 JumpDest BreakBlock; 981 JumpDest ContinueBlock; 982 }; 983 SmallVector<BreakContinue, 8> BreakContinueStack; 984 985 /// Handles cancellation exit points in OpenMP-related constructs. 986 class OpenMPCancelExitStack { 987 /// Tracks cancellation exit point and join point for cancel-related exit 988 /// and normal exit. 989 struct CancelExit { 990 CancelExit() = default; 991 CancelExit(OpenMPDirectiveKind Kind, JumpDest ExitBlock, 992 JumpDest ContBlock) 993 : Kind(Kind), ExitBlock(ExitBlock), ContBlock(ContBlock) {} 994 OpenMPDirectiveKind Kind = OMPD_unknown; 995 /// true if the exit block has been emitted already by the special 996 /// emitExit() call, false if the default codegen is used. 997 bool HasBeenEmitted = false; 998 JumpDest ExitBlock; 999 JumpDest ContBlock; 1000 }; 1001 1002 SmallVector<CancelExit, 8> Stack; 1003 1004 public: 1005 OpenMPCancelExitStack() : Stack(1) {} 1006 ~OpenMPCancelExitStack() = default; 1007 /// Fetches the exit block for the current OpenMP construct. 1008 JumpDest getExitBlock() const { return Stack.back().ExitBlock; } 1009 /// Emits exit block with special codegen procedure specific for the related 1010 /// OpenMP construct + emits code for normal construct cleanup. 1011 void emitExit(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, 1012 const llvm::function_ref<void(CodeGenFunction &)> &CodeGen) { 1013 if (Stack.back().Kind == Kind && getExitBlock().isValid()) { 1014 assert(CGF.getOMPCancelDestination(Kind).isValid()); 1015 assert(CGF.HaveInsertPoint()); 1016 assert(!Stack.back().HasBeenEmitted); 1017 auto IP = CGF.Builder.saveAndClearIP(); 1018 CGF.EmitBlock(Stack.back().ExitBlock.getBlock()); 1019 CodeGen(CGF); 1020 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock); 1021 CGF.Builder.restoreIP(IP); 1022 Stack.back().HasBeenEmitted = true; 1023 } 1024 CodeGen(CGF); 1025 } 1026 /// Enter the cancel supporting \a Kind construct. 1027 /// \param Kind OpenMP directive that supports cancel constructs. 1028 /// \param HasCancel true, if the construct has inner cancel directive, 1029 /// false otherwise. 1030 void enter(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, bool HasCancel) { 1031 Stack.push_back({Kind, 1032 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.exit") 1033 : JumpDest(), 1034 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.cont") 1035 : JumpDest()}); 1036 } 1037 /// Emits default exit point for the cancel construct (if the special one 1038 /// has not be used) + join point for cancel/normal exits. 1039 void exit(CodeGenFunction &CGF) { 1040 if (getExitBlock().isValid()) { 1041 assert(CGF.getOMPCancelDestination(Stack.back().Kind).isValid()); 1042 bool HaveIP = CGF.HaveInsertPoint(); 1043 if (!Stack.back().HasBeenEmitted) { 1044 if (HaveIP) 1045 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock); 1046 CGF.EmitBlock(Stack.back().ExitBlock.getBlock()); 1047 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock); 1048 } 1049 CGF.EmitBlock(Stack.back().ContBlock.getBlock()); 1050 if (!HaveIP) { 1051 CGF.Builder.CreateUnreachable(); 1052 CGF.Builder.ClearInsertionPoint(); 1053 } 1054 } 1055 Stack.pop_back(); 1056 } 1057 }; 1058 OpenMPCancelExitStack OMPCancelStack; 1059 1060 /// Controls insertion of cancellation exit blocks in worksharing constructs. 1061 class OMPCancelStackRAII { 1062 CodeGenFunction &CGF; 1063 1064 public: 1065 OMPCancelStackRAII(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, 1066 bool HasCancel) 1067 : CGF(CGF) { 1068 CGF.OMPCancelStack.enter(CGF, Kind, HasCancel); 1069 } 1070 ~OMPCancelStackRAII() { CGF.OMPCancelStack.exit(CGF); } 1071 }; 1072 1073 CodeGenPGO PGO; 1074 1075 /// Calculate branch weights appropriate for PGO data 1076 llvm::MDNode *createProfileWeights(uint64_t TrueCount, uint64_t FalseCount); 1077 llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights); 1078 llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond, 1079 uint64_t LoopCount); 1080 1081 public: 1082 /// Increment the profiler's counter for the given statement. 1083 void incrementProfileCounter(const Stmt *S) { 1084 if (CGM.getCodeGenOpts().hasProfileClangInstr()) 1085 PGO.emitCounterIncrement(Builder, S); 1086 PGO.setCurrentStmt(S); 1087 } 1088 1089 /// Get the profiler's count for the given statement. 1090 uint64_t getProfileCount(const Stmt *S) { 1091 Optional<uint64_t> Count = PGO.getStmtCount(S); 1092 if (!Count.hasValue()) 1093 return 0; 1094 return *Count; 1095 } 1096 1097 /// Set the profiler's current count. 1098 void setCurrentProfileCount(uint64_t Count) { 1099 PGO.setCurrentRegionCount(Count); 1100 } 1101 1102 /// Get the profiler's current count. This is generally the count for the most 1103 /// recently incremented counter. 1104 uint64_t getCurrentProfileCount() { 1105 return PGO.getCurrentRegionCount(); 1106 } 1107 1108 private: 1109 1110 /// SwitchInsn - This is nearest current switch instruction. It is null if 1111 /// current context is not in a switch. 1112 llvm::SwitchInst *SwitchInsn; 1113 /// The branch weights of SwitchInsn when doing instrumentation based PGO. 1114 SmallVector<uint64_t, 16> *SwitchWeights; 1115 1116 /// CaseRangeBlock - This block holds if condition check for last case 1117 /// statement range in current switch instruction. 1118 llvm::BasicBlock *CaseRangeBlock; 1119 1120 /// OpaqueLValues - Keeps track of the current set of opaque value 1121 /// expressions. 1122 llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues; 1123 llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues; 1124 1125 // VLASizeMap - This keeps track of the associated size for each VLA type. 1126 // We track this by the size expression rather than the type itself because 1127 // in certain situations, like a const qualifier applied to an VLA typedef, 1128 // multiple VLA types can share the same size expression. 1129 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we 1130 // enter/leave scopes. 1131 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap; 1132 1133 /// A block containing a single 'unreachable' instruction. Created 1134 /// lazily by getUnreachableBlock(). 1135 llvm::BasicBlock *UnreachableBlock; 1136 1137 /// Counts of the number return expressions in the function. 1138 unsigned NumReturnExprs; 1139 1140 /// Count the number of simple (constant) return expressions in the function. 1141 unsigned NumSimpleReturnExprs; 1142 1143 /// The last regular (non-return) debug location (breakpoint) in the function. 1144 SourceLocation LastStopPoint; 1145 1146 public: 1147 /// A scope within which we are constructing the fields of an object which 1148 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use 1149 /// if we need to evaluate a CXXDefaultInitExpr within the evaluation. 1150 class FieldConstructionScope { 1151 public: 1152 FieldConstructionScope(CodeGenFunction &CGF, Address This) 1153 : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) { 1154 CGF.CXXDefaultInitExprThis = This; 1155 } 1156 ~FieldConstructionScope() { 1157 CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis; 1158 } 1159 1160 private: 1161 CodeGenFunction &CGF; 1162 Address OldCXXDefaultInitExprThis; 1163 }; 1164 1165 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this' 1166 /// is overridden to be the object under construction. 1167 class CXXDefaultInitExprScope { 1168 public: 1169 CXXDefaultInitExprScope(CodeGenFunction &CGF) 1170 : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue), 1171 OldCXXThisAlignment(CGF.CXXThisAlignment) { 1172 CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer(); 1173 CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment(); 1174 } 1175 ~CXXDefaultInitExprScope() { 1176 CGF.CXXThisValue = OldCXXThisValue; 1177 CGF.CXXThisAlignment = OldCXXThisAlignment; 1178 } 1179 1180 public: 1181 CodeGenFunction &CGF; 1182 llvm::Value *OldCXXThisValue; 1183 CharUnits OldCXXThisAlignment; 1184 }; 1185 1186 class InlinedInheritingConstructorScope { 1187 public: 1188 InlinedInheritingConstructorScope(CodeGenFunction &CGF, GlobalDecl GD) 1189 : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl), 1190 OldCurCodeDecl(CGF.CurCodeDecl), 1191 OldCXXABIThisDecl(CGF.CXXABIThisDecl), 1192 OldCXXABIThisValue(CGF.CXXABIThisValue), 1193 OldCXXThisValue(CGF.CXXThisValue), 1194 OldCXXABIThisAlignment(CGF.CXXABIThisAlignment), 1195 OldCXXThisAlignment(CGF.CXXThisAlignment), 1196 OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy), 1197 OldCXXInheritedCtorInitExprArgs( 1198 std::move(CGF.CXXInheritedCtorInitExprArgs)) { 1199 CGF.CurGD = GD; 1200 CGF.CurFuncDecl = CGF.CurCodeDecl = 1201 cast<CXXConstructorDecl>(GD.getDecl()); 1202 CGF.CXXABIThisDecl = nullptr; 1203 CGF.CXXABIThisValue = nullptr; 1204 CGF.CXXThisValue = nullptr; 1205 CGF.CXXABIThisAlignment = CharUnits(); 1206 CGF.CXXThisAlignment = CharUnits(); 1207 CGF.ReturnValue = Address::invalid(); 1208 CGF.FnRetTy = QualType(); 1209 CGF.CXXInheritedCtorInitExprArgs.clear(); 1210 } 1211 ~InlinedInheritingConstructorScope() { 1212 CGF.CurGD = OldCurGD; 1213 CGF.CurFuncDecl = OldCurFuncDecl; 1214 CGF.CurCodeDecl = OldCurCodeDecl; 1215 CGF.CXXABIThisDecl = OldCXXABIThisDecl; 1216 CGF.CXXABIThisValue = OldCXXABIThisValue; 1217 CGF.CXXThisValue = OldCXXThisValue; 1218 CGF.CXXABIThisAlignment = OldCXXABIThisAlignment; 1219 CGF.CXXThisAlignment = OldCXXThisAlignment; 1220 CGF.ReturnValue = OldReturnValue; 1221 CGF.FnRetTy = OldFnRetTy; 1222 CGF.CXXInheritedCtorInitExprArgs = 1223 std::move(OldCXXInheritedCtorInitExprArgs); 1224 } 1225 1226 private: 1227 CodeGenFunction &CGF; 1228 GlobalDecl OldCurGD; 1229 const Decl *OldCurFuncDecl; 1230 const Decl *OldCurCodeDecl; 1231 ImplicitParamDecl *OldCXXABIThisDecl; 1232 llvm::Value *OldCXXABIThisValue; 1233 llvm::Value *OldCXXThisValue; 1234 CharUnits OldCXXABIThisAlignment; 1235 CharUnits OldCXXThisAlignment; 1236 Address OldReturnValue; 1237 QualType OldFnRetTy; 1238 CallArgList OldCXXInheritedCtorInitExprArgs; 1239 }; 1240 1241 private: 1242 /// CXXThisDecl - When generating code for a C++ member function, 1243 /// this will hold the implicit 'this' declaration. 1244 ImplicitParamDecl *CXXABIThisDecl; 1245 llvm::Value *CXXABIThisValue; 1246 llvm::Value *CXXThisValue; 1247 CharUnits CXXABIThisAlignment; 1248 CharUnits CXXThisAlignment; 1249 1250 /// The value of 'this' to use when evaluating CXXDefaultInitExprs within 1251 /// this expression. 1252 Address CXXDefaultInitExprThis = Address::invalid(); 1253 1254 /// The values of function arguments to use when evaluating 1255 /// CXXInheritedCtorInitExprs within this context. 1256 CallArgList CXXInheritedCtorInitExprArgs; 1257 1258 /// CXXStructorImplicitParamDecl - When generating code for a constructor or 1259 /// destructor, this will hold the implicit argument (e.g. VTT). 1260 ImplicitParamDecl *CXXStructorImplicitParamDecl; 1261 llvm::Value *CXXStructorImplicitParamValue; 1262 1263 /// OutermostConditional - Points to the outermost active 1264 /// conditional control. This is used so that we know if a 1265 /// temporary should be destroyed conditionally. 1266 ConditionalEvaluation *OutermostConditional; 1267 1268 /// The current lexical scope. 1269 LexicalScope *CurLexicalScope; 1270 1271 /// The current source location that should be used for exception 1272 /// handling code. 1273 SourceLocation CurEHLocation; 1274 1275 /// BlockByrefInfos - For each __block variable, contains 1276 /// information about the layout of the variable. 1277 llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos; 1278 1279 llvm::BasicBlock *TerminateLandingPad; 1280 llvm::BasicBlock *TerminateHandler; 1281 llvm::BasicBlock *TrapBB; 1282 1283 /// True if we need emit the life-time markers. 1284 const bool ShouldEmitLifetimeMarkers; 1285 1286 /// Add a kernel metadata node to the named metadata node 'opencl.kernels'. 1287 /// In the kernel metadata node, reference the kernel function and metadata 1288 /// nodes for its optional attribute qualifiers (OpenCL 1.1 6.7.2): 1289 /// - A node for the vec_type_hint(<type>) qualifier contains string 1290 /// "vec_type_hint", an undefined value of the <type> data type, 1291 /// and a Boolean that is true if the <type> is integer and signed. 1292 /// - A node for the work_group_size_hint(X,Y,Z) qualifier contains string 1293 /// "work_group_size_hint", and three 32-bit integers X, Y and Z. 1294 /// - A node for the reqd_work_group_size(X,Y,Z) qualifier contains string 1295 /// "reqd_work_group_size", and three 32-bit integers X, Y and Z. 1296 void EmitOpenCLKernelMetadata(const FunctionDecl *FD, 1297 llvm::Function *Fn); 1298 1299 public: 1300 CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false); 1301 ~CodeGenFunction(); 1302 1303 CodeGenTypes &getTypes() const { return CGM.getTypes(); } 1304 ASTContext &getContext() const { return CGM.getContext(); } 1305 CGDebugInfo *getDebugInfo() { 1306 if (DisableDebugInfo) 1307 return nullptr; 1308 return DebugInfo; 1309 } 1310 void disableDebugInfo() { DisableDebugInfo = true; } 1311 void enableDebugInfo() { DisableDebugInfo = false; } 1312 1313 bool shouldUseFusedARCCalls() { 1314 return CGM.getCodeGenOpts().OptimizationLevel == 0; 1315 } 1316 1317 const LangOptions &getLangOpts() const { return CGM.getLangOpts(); } 1318 1319 /// Returns a pointer to the function's exception object and selector slot, 1320 /// which is assigned in every landing pad. 1321 Address getExceptionSlot(); 1322 Address getEHSelectorSlot(); 1323 1324 /// Returns the contents of the function's exception object and selector 1325 /// slots. 1326 llvm::Value *getExceptionFromSlot(); 1327 llvm::Value *getSelectorFromSlot(); 1328 1329 Address getNormalCleanupDestSlot(); 1330 1331 llvm::BasicBlock *getUnreachableBlock() { 1332 if (!UnreachableBlock) { 1333 UnreachableBlock = createBasicBlock("unreachable"); 1334 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock); 1335 } 1336 return UnreachableBlock; 1337 } 1338 1339 llvm::BasicBlock *getInvokeDest() { 1340 if (!EHStack.requiresLandingPad()) return nullptr; 1341 return getInvokeDestImpl(); 1342 } 1343 1344 bool currentFunctionUsesSEHTry() const { return CurSEHParent != nullptr; } 1345 1346 const TargetInfo &getTarget() const { return Target; } 1347 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); } 1348 1349 //===--------------------------------------------------------------------===// 1350 // Cleanups 1351 //===--------------------------------------------------------------------===// 1352 1353 typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty); 1354 1355 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, 1356 Address arrayEndPointer, 1357 QualType elementType, 1358 CharUnits elementAlignment, 1359 Destroyer *destroyer); 1360 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, 1361 llvm::Value *arrayEnd, 1362 QualType elementType, 1363 CharUnits elementAlignment, 1364 Destroyer *destroyer); 1365 1366 void pushDestroy(QualType::DestructionKind dtorKind, 1367 Address addr, QualType type); 1368 void pushEHDestroy(QualType::DestructionKind dtorKind, 1369 Address addr, QualType type); 1370 void pushDestroy(CleanupKind kind, Address addr, QualType type, 1371 Destroyer *destroyer, bool useEHCleanupForArray); 1372 void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, 1373 QualType type, Destroyer *destroyer, 1374 bool useEHCleanupForArray); 1375 void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete, 1376 llvm::Value *CompletePtr, 1377 QualType ElementType); 1378 void pushStackRestore(CleanupKind kind, Address SPMem); 1379 void emitDestroy(Address addr, QualType type, Destroyer *destroyer, 1380 bool useEHCleanupForArray); 1381 llvm::Function *generateDestroyHelper(Address addr, QualType type, 1382 Destroyer *destroyer, 1383 bool useEHCleanupForArray, 1384 const VarDecl *VD); 1385 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end, 1386 QualType elementType, CharUnits elementAlign, 1387 Destroyer *destroyer, 1388 bool checkZeroLength, bool useEHCleanup); 1389 1390 Destroyer *getDestroyer(QualType::DestructionKind destructionKind); 1391 1392 /// Determines whether an EH cleanup is required to destroy a type 1393 /// with the given destruction kind. 1394 bool needsEHCleanup(QualType::DestructionKind kind) { 1395 switch (kind) { 1396 case QualType::DK_none: 1397 return false; 1398 case QualType::DK_cxx_destructor: 1399 case QualType::DK_objc_weak_lifetime: 1400 return getLangOpts().Exceptions; 1401 case QualType::DK_objc_strong_lifetime: 1402 return getLangOpts().Exceptions && 1403 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions; 1404 } 1405 llvm_unreachable("bad destruction kind"); 1406 } 1407 1408 CleanupKind getCleanupKind(QualType::DestructionKind kind) { 1409 return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup); 1410 } 1411 1412 //===--------------------------------------------------------------------===// 1413 // Objective-C 1414 //===--------------------------------------------------------------------===// 1415 1416 void GenerateObjCMethod(const ObjCMethodDecl *OMD); 1417 1418 void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD); 1419 1420 /// GenerateObjCGetter - Synthesize an Objective-C property getter function. 1421 void GenerateObjCGetter(ObjCImplementationDecl *IMP, 1422 const ObjCPropertyImplDecl *PID); 1423 void generateObjCGetterBody(const ObjCImplementationDecl *classImpl, 1424 const ObjCPropertyImplDecl *propImpl, 1425 const ObjCMethodDecl *GetterMothodDecl, 1426 llvm::Constant *AtomicHelperFn); 1427 1428 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, 1429 ObjCMethodDecl *MD, bool ctor); 1430 1431 /// GenerateObjCSetter - Synthesize an Objective-C property setter function 1432 /// for the given property. 1433 void GenerateObjCSetter(ObjCImplementationDecl *IMP, 1434 const ObjCPropertyImplDecl *PID); 1435 void generateObjCSetterBody(const ObjCImplementationDecl *classImpl, 1436 const ObjCPropertyImplDecl *propImpl, 1437 llvm::Constant *AtomicHelperFn); 1438 1439 //===--------------------------------------------------------------------===// 1440 // Block Bits 1441 //===--------------------------------------------------------------------===// 1442 1443 llvm::Value *EmitBlockLiteral(const BlockExpr *); 1444 llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info); 1445 static void destroyBlockInfos(CGBlockInfo *info); 1446 1447 llvm::Function *GenerateBlockFunction(GlobalDecl GD, 1448 const CGBlockInfo &Info, 1449 const DeclMapTy &ldm, 1450 bool IsLambdaConversionToBlock); 1451 1452 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo); 1453 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo); 1454 llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction( 1455 const ObjCPropertyImplDecl *PID); 1456 llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction( 1457 const ObjCPropertyImplDecl *PID); 1458 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty); 1459 1460 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags); 1461 1462 class AutoVarEmission; 1463 1464 void emitByrefStructureInit(const AutoVarEmission &emission); 1465 void enterByrefCleanup(const AutoVarEmission &emission); 1466 1467 void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum, 1468 llvm::Value *ptr); 1469 1470 Address LoadBlockStruct(); 1471 Address GetAddrOfBlockDecl(const VarDecl *var, bool ByRef); 1472 1473 /// BuildBlockByrefAddress - Computes the location of the 1474 /// data in a variable which is declared as __block. 1475 Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V, 1476 bool followForward = true); 1477 Address emitBlockByrefAddress(Address baseAddr, 1478 const BlockByrefInfo &info, 1479 bool followForward, 1480 const llvm::Twine &name); 1481 1482 const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var); 1483 1484 QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args); 1485 1486 void GenerateCode(GlobalDecl GD, llvm::Function *Fn, 1487 const CGFunctionInfo &FnInfo); 1488 /// \brief Emit code for the start of a function. 1489 /// \param Loc The location to be associated with the function. 1490 /// \param StartLoc The location of the function body. 1491 void StartFunction(GlobalDecl GD, 1492 QualType RetTy, 1493 llvm::Function *Fn, 1494 const CGFunctionInfo &FnInfo, 1495 const FunctionArgList &Args, 1496 SourceLocation Loc = SourceLocation(), 1497 SourceLocation StartLoc = SourceLocation()); 1498 1499 void EmitConstructorBody(FunctionArgList &Args); 1500 void EmitDestructorBody(FunctionArgList &Args); 1501 void emitImplicitAssignmentOperatorBody(FunctionArgList &Args); 1502 void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body); 1503 void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S); 1504 1505 void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator, 1506 CallArgList &CallArgs); 1507 void EmitLambdaToBlockPointerBody(FunctionArgList &Args); 1508 void EmitLambdaBlockInvokeBody(); 1509 void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD); 1510 void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD); 1511 void EmitAsanPrologueOrEpilogue(bool Prologue); 1512 1513 /// \brief Emit the unified return block, trying to avoid its emission when 1514 /// possible. 1515 /// \return The debug location of the user written return statement if the 1516 /// return block is is avoided. 1517 llvm::DebugLoc EmitReturnBlock(); 1518 1519 /// FinishFunction - Complete IR generation of the current function. It is 1520 /// legal to call this function even if there is no current insertion point. 1521 void FinishFunction(SourceLocation EndLoc=SourceLocation()); 1522 1523 void StartThunk(llvm::Function *Fn, GlobalDecl GD, 1524 const CGFunctionInfo &FnInfo); 1525 1526 void EmitCallAndReturnForThunk(llvm::Constant *Callee, 1527 const ThunkInfo *Thunk); 1528 1529 void FinishThunk(); 1530 1531 /// Emit a musttail call for a thunk with a potentially adjusted this pointer. 1532 void EmitMustTailThunk(const CXXMethodDecl *MD, llvm::Value *AdjustedThisPtr, 1533 llvm::Value *Callee); 1534 1535 /// Generate a thunk for the given method. 1536 void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, 1537 GlobalDecl GD, const ThunkInfo &Thunk); 1538 1539 llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn, 1540 const CGFunctionInfo &FnInfo, 1541 GlobalDecl GD, const ThunkInfo &Thunk); 1542 1543 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type, 1544 FunctionArgList &Args); 1545 1546 void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init, 1547 ArrayRef<VarDecl *> ArrayIndexes); 1548 1549 /// Struct with all informations about dynamic [sub]class needed to set vptr. 1550 struct VPtr { 1551 BaseSubobject Base; 1552 const CXXRecordDecl *NearestVBase; 1553 CharUnits OffsetFromNearestVBase; 1554 const CXXRecordDecl *VTableClass; 1555 }; 1556 1557 /// Initialize the vtable pointer of the given subobject. 1558 void InitializeVTablePointer(const VPtr &vptr); 1559 1560 typedef llvm::SmallVector<VPtr, 4> VPtrsVector; 1561 1562 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy; 1563 VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass); 1564 1565 void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase, 1566 CharUnits OffsetFromNearestVBase, 1567 bool BaseIsNonVirtualPrimaryBase, 1568 const CXXRecordDecl *VTableClass, 1569 VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs); 1570 1571 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl); 1572 1573 /// GetVTablePtr - Return the Value of the vtable pointer member pointed 1574 /// to by This. 1575 llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy, 1576 const CXXRecordDecl *VTableClass); 1577 1578 enum CFITypeCheckKind { 1579 CFITCK_VCall, 1580 CFITCK_NVCall, 1581 CFITCK_DerivedCast, 1582 CFITCK_UnrelatedCast, 1583 CFITCK_ICall, 1584 }; 1585 1586 /// \brief Derived is the presumed address of an object of type T after a 1587 /// cast. If T is a polymorphic class type, emit a check that the virtual 1588 /// table for Derived belongs to a class derived from T. 1589 void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived, 1590 bool MayBeNull, CFITypeCheckKind TCK, 1591 SourceLocation Loc); 1592 1593 /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable. 1594 /// If vptr CFI is enabled, emit a check that VTable is valid. 1595 void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable, 1596 CFITypeCheckKind TCK, SourceLocation Loc); 1597 1598 /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for 1599 /// RD using llvm.type.test. 1600 void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable, 1601 CFITypeCheckKind TCK, SourceLocation Loc); 1602 1603 /// If whole-program virtual table optimization is enabled, emit an assumption 1604 /// that VTable is a member of RD's type identifier. Or, if vptr CFI is 1605 /// enabled, emit a check that VTable is a member of RD's type identifier. 1606 void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD, 1607 llvm::Value *VTable, SourceLocation Loc); 1608 1609 /// Returns whether we should perform a type checked load when loading a 1610 /// virtual function for virtual calls to members of RD. This is generally 1611 /// true when both vcall CFI and whole-program-vtables are enabled. 1612 bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD); 1613 1614 /// Emit a type checked load from the given vtable. 1615 llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable, 1616 uint64_t VTableByteOffset); 1617 1618 /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given 1619 /// expr can be devirtualized. 1620 bool CanDevirtualizeMemberFunctionCall(const Expr *Base, 1621 const CXXMethodDecl *MD); 1622 1623 /// EnterDtorCleanups - Enter the cleanups necessary to complete the 1624 /// given phase of destruction for a destructor. The end result 1625 /// should call destructors on members and base classes in reverse 1626 /// order of their construction. 1627 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type); 1628 1629 /// ShouldInstrumentFunction - Return true if the current function should be 1630 /// instrumented with __cyg_profile_func_* calls 1631 bool ShouldInstrumentFunction(); 1632 1633 /// ShouldXRayInstrument - Return true if the current function should be 1634 /// instrumented with XRay nop sleds. 1635 bool ShouldXRayInstrumentFunction() const; 1636 1637 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified 1638 /// instrumentation function with the current function and the call site, if 1639 /// function instrumentation is enabled. 1640 void EmitFunctionInstrumentation(const char *Fn); 1641 1642 /// EmitMCountInstrumentation - Emit call to .mcount. 1643 void EmitMCountInstrumentation(); 1644 1645 /// EmitFunctionProlog - Emit the target specific LLVM code to load the 1646 /// arguments for the given function. This is also responsible for naming the 1647 /// LLVM function arguments. 1648 void EmitFunctionProlog(const CGFunctionInfo &FI, 1649 llvm::Function *Fn, 1650 const FunctionArgList &Args); 1651 1652 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the 1653 /// given temporary. 1654 void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc, 1655 SourceLocation EndLoc); 1656 1657 /// EmitStartEHSpec - Emit the start of the exception spec. 1658 void EmitStartEHSpec(const Decl *D); 1659 1660 /// EmitEndEHSpec - Emit the end of the exception spec. 1661 void EmitEndEHSpec(const Decl *D); 1662 1663 /// getTerminateLandingPad - Return a landing pad that just calls terminate. 1664 llvm::BasicBlock *getTerminateLandingPad(); 1665 1666 /// getTerminateHandler - Return a handler (not a landing pad, just 1667 /// a catch handler) that just calls terminate. This is used when 1668 /// a terminate scope encloses a try. 1669 llvm::BasicBlock *getTerminateHandler(); 1670 1671 llvm::Type *ConvertTypeForMem(QualType T); 1672 llvm::Type *ConvertType(QualType T); 1673 llvm::Type *ConvertType(const TypeDecl *T) { 1674 return ConvertType(getContext().getTypeDeclType(T)); 1675 } 1676 1677 /// LoadObjCSelf - Load the value of self. This function is only valid while 1678 /// generating code for an Objective-C method. 1679 llvm::Value *LoadObjCSelf(); 1680 1681 /// TypeOfSelfObject - Return type of object that this self represents. 1682 QualType TypeOfSelfObject(); 1683 1684 /// hasAggregateLLVMType - Return true if the specified AST type will map into 1685 /// an aggregate LLVM type or is void. 1686 static TypeEvaluationKind getEvaluationKind(QualType T); 1687 1688 static bool hasScalarEvaluationKind(QualType T) { 1689 return getEvaluationKind(T) == TEK_Scalar; 1690 } 1691 1692 static bool hasAggregateEvaluationKind(QualType T) { 1693 return getEvaluationKind(T) == TEK_Aggregate; 1694 } 1695 1696 /// createBasicBlock - Create an LLVM basic block. 1697 llvm::BasicBlock *createBasicBlock(const Twine &name = "", 1698 llvm::Function *parent = nullptr, 1699 llvm::BasicBlock *before = nullptr) { 1700 #ifdef NDEBUG 1701 return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before); 1702 #else 1703 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before); 1704 #endif 1705 } 1706 1707 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified 1708 /// label maps to. 1709 JumpDest getJumpDestForLabel(const LabelDecl *S); 1710 1711 /// SimplifyForwardingBlocks - If the given basic block is only a branch to 1712 /// another basic block, simplify it. This assumes that no other code could 1713 /// potentially reference the basic block. 1714 void SimplifyForwardingBlocks(llvm::BasicBlock *BB); 1715 1716 /// EmitBlock - Emit the given block \arg BB and set it as the insert point, 1717 /// adding a fall-through branch from the current insert block if 1718 /// necessary. It is legal to call this function even if there is no current 1719 /// insertion point. 1720 /// 1721 /// IsFinished - If true, indicates that the caller has finished emitting 1722 /// branches to the given block and does not expect to emit code into it. This 1723 /// means the block can be ignored if it is unreachable. 1724 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false); 1725 1726 /// EmitBlockAfterUses - Emit the given block somewhere hopefully 1727 /// near its uses, and leave the insertion point in it. 1728 void EmitBlockAfterUses(llvm::BasicBlock *BB); 1729 1730 /// EmitBranch - Emit a branch to the specified basic block from the current 1731 /// insert block, taking care to avoid creation of branches from dummy 1732 /// blocks. It is legal to call this function even if there is no current 1733 /// insertion point. 1734 /// 1735 /// This function clears the current insertion point. The caller should follow 1736 /// calls to this function with calls to Emit*Block prior to generation new 1737 /// code. 1738 void EmitBranch(llvm::BasicBlock *Block); 1739 1740 /// HaveInsertPoint - True if an insertion point is defined. If not, this 1741 /// indicates that the current code being emitted is unreachable. 1742 bool HaveInsertPoint() const { 1743 return Builder.GetInsertBlock() != nullptr; 1744 } 1745 1746 /// EnsureInsertPoint - Ensure that an insertion point is defined so that 1747 /// emitted IR has a place to go. Note that by definition, if this function 1748 /// creates a block then that block is unreachable; callers may do better to 1749 /// detect when no insertion point is defined and simply skip IR generation. 1750 void EnsureInsertPoint() { 1751 if (!HaveInsertPoint()) 1752 EmitBlock(createBasicBlock()); 1753 } 1754 1755 /// ErrorUnsupported - Print out an error that codegen doesn't support the 1756 /// specified stmt yet. 1757 void ErrorUnsupported(const Stmt *S, const char *Type); 1758 1759 //===--------------------------------------------------------------------===// 1760 // Helpers 1761 //===--------------------------------------------------------------------===// 1762 1763 LValue MakeAddrLValue(Address Addr, QualType T, 1764 AlignmentSource AlignSource = AlignmentSource::Type) { 1765 return LValue::MakeAddr(Addr, T, getContext(), AlignSource, 1766 CGM.getTBAAInfo(T)); 1767 } 1768 1769 LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment, 1770 AlignmentSource AlignSource = AlignmentSource::Type) { 1771 return LValue::MakeAddr(Address(V, Alignment), T, getContext(), 1772 AlignSource, CGM.getTBAAInfo(T)); 1773 } 1774 1775 LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T); 1776 LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T); 1777 CharUnits getNaturalTypeAlignment(QualType T, 1778 AlignmentSource *Source = nullptr, 1779 bool forPointeeType = false); 1780 CharUnits getNaturalPointeeTypeAlignment(QualType T, 1781 AlignmentSource *Source = nullptr); 1782 1783 Address EmitLoadOfReference(Address Ref, const ReferenceType *RefTy, 1784 AlignmentSource *Source = nullptr); 1785 LValue EmitLoadOfReferenceLValue(Address Ref, const ReferenceType *RefTy); 1786 1787 Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy, 1788 AlignmentSource *Source = nullptr); 1789 LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy); 1790 1791 /// CreateTempAlloca - This creates a alloca and inserts it into the entry 1792 /// block. The caller is responsible for setting an appropriate alignment on 1793 /// the alloca. 1794 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty, 1795 const Twine &Name = "tmp"); 1796 Address CreateTempAlloca(llvm::Type *Ty, CharUnits align, 1797 const Twine &Name = "tmp"); 1798 1799 /// CreateDefaultAlignedTempAlloca - This creates an alloca with the 1800 /// default ABI alignment of the given LLVM type. 1801 /// 1802 /// IMPORTANT NOTE: This is *not* generally the right alignment for 1803 /// any given AST type that happens to have been lowered to the 1804 /// given IR type. This should only ever be used for function-local, 1805 /// IR-driven manipulations like saving and restoring a value. Do 1806 /// not hand this address off to arbitrary IRGen routines, and especially 1807 /// do not pass it as an argument to a function that might expect a 1808 /// properly ABI-aligned value. 1809 Address CreateDefaultAlignTempAlloca(llvm::Type *Ty, 1810 const Twine &Name = "tmp"); 1811 1812 /// InitTempAlloca - Provide an initial value for the given alloca which 1813 /// will be observable at all locations in the function. 1814 /// 1815 /// The address should be something that was returned from one of 1816 /// the CreateTempAlloca or CreateMemTemp routines, and the 1817 /// initializer must be valid in the entry block (i.e. it must 1818 /// either be a constant or an argument value). 1819 void InitTempAlloca(Address Alloca, llvm::Value *Value); 1820 1821 /// CreateIRTemp - Create a temporary IR object of the given type, with 1822 /// appropriate alignment. This routine should only be used when an temporary 1823 /// value needs to be stored into an alloca (for example, to avoid explicit 1824 /// PHI construction), but the type is the IR type, not the type appropriate 1825 /// for storing in memory. 1826 /// 1827 /// That is, this is exactly equivalent to CreateMemTemp, but calling 1828 /// ConvertType instead of ConvertTypeForMem. 1829 Address CreateIRTemp(QualType T, const Twine &Name = "tmp"); 1830 1831 /// CreateMemTemp - Create a temporary memory object of the given type, with 1832 /// appropriate alignment. 1833 Address CreateMemTemp(QualType T, const Twine &Name = "tmp"); 1834 Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp"); 1835 1836 /// CreateAggTemp - Create a temporary memory object for the given 1837 /// aggregate type. 1838 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") { 1839 return AggValueSlot::forAddr(CreateMemTemp(T, Name), 1840 T.getQualifiers(), 1841 AggValueSlot::IsNotDestructed, 1842 AggValueSlot::DoesNotNeedGCBarriers, 1843 AggValueSlot::IsNotAliased); 1844 } 1845 1846 /// Emit a cast to void* in the appropriate address space. 1847 llvm::Value *EmitCastToVoidPtr(llvm::Value *value); 1848 1849 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 1850 /// expression and compare the result against zero, returning an Int1Ty value. 1851 llvm::Value *EvaluateExprAsBool(const Expr *E); 1852 1853 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result. 1854 void EmitIgnoredExpr(const Expr *E); 1855 1856 /// EmitAnyExpr - Emit code to compute the specified expression which can have 1857 /// any type. The result is returned as an RValue struct. If this is an 1858 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where 1859 /// the result should be returned. 1860 /// 1861 /// \param ignoreResult True if the resulting value isn't used. 1862 RValue EmitAnyExpr(const Expr *E, 1863 AggValueSlot aggSlot = AggValueSlot::ignored(), 1864 bool ignoreResult = false); 1865 1866 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address 1867 // or the value of the expression, depending on how va_list is defined. 1868 Address EmitVAListRef(const Expr *E); 1869 1870 /// Emit a "reference" to a __builtin_ms_va_list; this is 1871 /// always the value of the expression, because a __builtin_ms_va_list is a 1872 /// pointer to a char. 1873 Address EmitMSVAListRef(const Expr *E); 1874 1875 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will 1876 /// always be accessible even if no aggregate location is provided. 1877 RValue EmitAnyExprToTemp(const Expr *E); 1878 1879 /// EmitAnyExprToMem - Emits the code necessary to evaluate an 1880 /// arbitrary expression into the given memory location. 1881 void EmitAnyExprToMem(const Expr *E, Address Location, 1882 Qualifiers Quals, bool IsInitializer); 1883 1884 void EmitAnyExprToExn(const Expr *E, Address Addr); 1885 1886 /// EmitExprAsInit - Emits the code necessary to initialize a 1887 /// location in memory with the given initializer. 1888 void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue, 1889 bool capturedByInit); 1890 1891 /// hasVolatileMember - returns true if aggregate type has a volatile 1892 /// member. 1893 bool hasVolatileMember(QualType T) { 1894 if (const RecordType *RT = T->getAs<RecordType>()) { 1895 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl()); 1896 return RD->hasVolatileMember(); 1897 } 1898 return false; 1899 } 1900 /// EmitAggregateCopy - Emit an aggregate assignment. 1901 /// 1902 /// The difference to EmitAggregateCopy is that tail padding is not copied. 1903 /// This is required for correctness when assigning non-POD structures in C++. 1904 void EmitAggregateAssign(Address DestPtr, Address SrcPtr, 1905 QualType EltTy) { 1906 bool IsVolatile = hasVolatileMember(EltTy); 1907 EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, true); 1908 } 1909 1910 void EmitAggregateCopyCtor(Address DestPtr, Address SrcPtr, 1911 QualType DestTy, QualType SrcTy) { 1912 EmitAggregateCopy(DestPtr, SrcPtr, SrcTy, /*IsVolatile=*/false, 1913 /*IsAssignment=*/false); 1914 } 1915 1916 /// EmitAggregateCopy - Emit an aggregate copy. 1917 /// 1918 /// \param isVolatile - True iff either the source or the destination is 1919 /// volatile. 1920 /// \param isAssignment - If false, allow padding to be copied. This often 1921 /// yields more efficient. 1922 void EmitAggregateCopy(Address DestPtr, Address SrcPtr, 1923 QualType EltTy, bool isVolatile=false, 1924 bool isAssignment = false); 1925 1926 /// GetAddrOfLocalVar - Return the address of a local variable. 1927 Address GetAddrOfLocalVar(const VarDecl *VD) { 1928 auto it = LocalDeclMap.find(VD); 1929 assert(it != LocalDeclMap.end() && 1930 "Invalid argument to GetAddrOfLocalVar(), no decl!"); 1931 return it->second; 1932 } 1933 1934 /// getOpaqueLValueMapping - Given an opaque value expression (which 1935 /// must be mapped to an l-value), return its mapping. 1936 const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) { 1937 assert(OpaqueValueMapping::shouldBindAsLValue(e)); 1938 1939 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator 1940 it = OpaqueLValues.find(e); 1941 assert(it != OpaqueLValues.end() && "no mapping for opaque value!"); 1942 return it->second; 1943 } 1944 1945 /// getOpaqueRValueMapping - Given an opaque value expression (which 1946 /// must be mapped to an r-value), return its mapping. 1947 const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) { 1948 assert(!OpaqueValueMapping::shouldBindAsLValue(e)); 1949 1950 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator 1951 it = OpaqueRValues.find(e); 1952 assert(it != OpaqueRValues.end() && "no mapping for opaque value!"); 1953 return it->second; 1954 } 1955 1956 /// getAccessedFieldNo - Given an encoded value and a result number, return 1957 /// the input field number being accessed. 1958 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts); 1959 1960 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L); 1961 llvm::BasicBlock *GetIndirectGotoBlock(); 1962 1963 /// EmitNullInitialization - Generate code to set a value of the given type to 1964 /// null, If the type contains data member pointers, they will be initialized 1965 /// to -1 in accordance with the Itanium C++ ABI. 1966 void EmitNullInitialization(Address DestPtr, QualType Ty); 1967 1968 /// Emits a call to an LLVM variable-argument intrinsic, either 1969 /// \c llvm.va_start or \c llvm.va_end. 1970 /// \param ArgValue A reference to the \c va_list as emitted by either 1971 /// \c EmitVAListRef or \c EmitMSVAListRef. 1972 /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise, 1973 /// calls \c llvm.va_end. 1974 llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart); 1975 1976 /// Generate code to get an argument from the passed in pointer 1977 /// and update it accordingly. 1978 /// \param VE The \c VAArgExpr for which to generate code. 1979 /// \param VAListAddr Receives a reference to the \c va_list as emitted by 1980 /// either \c EmitVAListRef or \c EmitMSVAListRef. 1981 /// \returns A pointer to the argument. 1982 // FIXME: We should be able to get rid of this method and use the va_arg 1983 // instruction in LLVM instead once it works well enough. 1984 Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr); 1985 1986 /// emitArrayLength - Compute the length of an array, even if it's a 1987 /// VLA, and drill down to the base element type. 1988 llvm::Value *emitArrayLength(const ArrayType *arrayType, 1989 QualType &baseType, 1990 Address &addr); 1991 1992 /// EmitVLASize - Capture all the sizes for the VLA expressions in 1993 /// the given variably-modified type and store them in the VLASizeMap. 1994 /// 1995 /// This function can be called with a null (unreachable) insert point. 1996 void EmitVariablyModifiedType(QualType Ty); 1997 1998 /// getVLASize - Returns an LLVM value that corresponds to the size, 1999 /// in non-variably-sized elements, of a variable length array type, 2000 /// plus that largest non-variably-sized element type. Assumes that 2001 /// the type has already been emitted with EmitVariablyModifiedType. 2002 std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla); 2003 std::pair<llvm::Value*,QualType> getVLASize(QualType vla); 2004 2005 /// LoadCXXThis - Load the value of 'this'. This function is only valid while 2006 /// generating code for an C++ member function. 2007 llvm::Value *LoadCXXThis() { 2008 assert(CXXThisValue && "no 'this' value for this function"); 2009 return CXXThisValue; 2010 } 2011 Address LoadCXXThisAddress(); 2012 2013 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have 2014 /// virtual bases. 2015 // FIXME: Every place that calls LoadCXXVTT is something 2016 // that needs to be abstracted properly. 2017 llvm::Value *LoadCXXVTT() { 2018 assert(CXXStructorImplicitParamValue && "no VTT value for this function"); 2019 return CXXStructorImplicitParamValue; 2020 } 2021 2022 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a 2023 /// complete class to the given direct base. 2024 Address 2025 GetAddressOfDirectBaseInCompleteClass(Address Value, 2026 const CXXRecordDecl *Derived, 2027 const CXXRecordDecl *Base, 2028 bool BaseIsVirtual); 2029 2030 static bool ShouldNullCheckClassCastValue(const CastExpr *Cast); 2031 2032 /// GetAddressOfBaseClass - This function will add the necessary delta to the 2033 /// load of 'this' and returns address of the base class. 2034 Address GetAddressOfBaseClass(Address Value, 2035 const CXXRecordDecl *Derived, 2036 CastExpr::path_const_iterator PathBegin, 2037 CastExpr::path_const_iterator PathEnd, 2038 bool NullCheckValue, SourceLocation Loc); 2039 2040 Address GetAddressOfDerivedClass(Address Value, 2041 const CXXRecordDecl *Derived, 2042 CastExpr::path_const_iterator PathBegin, 2043 CastExpr::path_const_iterator PathEnd, 2044 bool NullCheckValue); 2045 2046 /// GetVTTParameter - Return the VTT parameter that should be passed to a 2047 /// base constructor/destructor with virtual bases. 2048 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move 2049 /// to ItaniumCXXABI.cpp together with all the references to VTT. 2050 llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase, 2051 bool Delegating); 2052 2053 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, 2054 CXXCtorType CtorType, 2055 const FunctionArgList &Args, 2056 SourceLocation Loc); 2057 // It's important not to confuse this and the previous function. Delegating 2058 // constructors are the C++0x feature. The constructor delegate optimization 2059 // is used to reduce duplication in the base and complete consturctors where 2060 // they are substantially the same. 2061 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor, 2062 const FunctionArgList &Args); 2063 2064 /// Emit a call to an inheriting constructor (that is, one that invokes a 2065 /// constructor inherited from a base class) by inlining its definition. This 2066 /// is necessary if the ABI does not support forwarding the arguments to the 2067 /// base class constructor (because they're variadic or similar). 2068 void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor, 2069 CXXCtorType CtorType, 2070 bool ForVirtualBase, 2071 bool Delegating, 2072 CallArgList &Args); 2073 2074 /// Emit a call to a constructor inherited from a base class, passing the 2075 /// current constructor's arguments along unmodified (without even making 2076 /// a copy). 2077 void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D, 2078 bool ForVirtualBase, Address This, 2079 bool InheritedFromVBase, 2080 const CXXInheritedCtorInitExpr *E); 2081 2082 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 2083 bool ForVirtualBase, bool Delegating, 2084 Address This, const CXXConstructExpr *E); 2085 2086 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 2087 bool ForVirtualBase, bool Delegating, 2088 Address This, CallArgList &Args); 2089 2090 /// Emit assumption load for all bases. Requires to be be called only on 2091 /// most-derived class and not under construction of the object. 2092 void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This); 2093 2094 /// Emit assumption that vptr load == global vtable. 2095 void EmitVTableAssumptionLoad(const VPtr &vptr, Address This); 2096 2097 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, 2098 Address This, Address Src, 2099 const CXXConstructExpr *E); 2100 2101 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 2102 const ArrayType *ArrayTy, 2103 Address ArrayPtr, 2104 const CXXConstructExpr *E, 2105 bool ZeroInitialization = false); 2106 2107 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 2108 llvm::Value *NumElements, 2109 Address ArrayPtr, 2110 const CXXConstructExpr *E, 2111 bool ZeroInitialization = false); 2112 2113 static Destroyer destroyCXXObject; 2114 2115 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, 2116 bool ForVirtualBase, bool Delegating, 2117 Address This); 2118 2119 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType, 2120 llvm::Type *ElementTy, Address NewPtr, 2121 llvm::Value *NumElements, 2122 llvm::Value *AllocSizeWithoutCookie); 2123 2124 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType, 2125 Address Ptr); 2126 2127 llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr); 2128 void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr); 2129 2130 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E); 2131 void EmitCXXDeleteExpr(const CXXDeleteExpr *E); 2132 2133 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr, 2134 QualType DeleteTy, llvm::Value *NumElements = nullptr, 2135 CharUnits CookieSize = CharUnits()); 2136 2137 RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type, 2138 const Expr *Arg, bool IsDelete); 2139 2140 llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E); 2141 llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE); 2142 Address EmitCXXUuidofExpr(const CXXUuidofExpr *E); 2143 2144 /// \brief Situations in which we might emit a check for the suitability of a 2145 /// pointer or glvalue. 2146 enum TypeCheckKind { 2147 /// Checking the operand of a load. Must be suitably sized and aligned. 2148 TCK_Load, 2149 /// Checking the destination of a store. Must be suitably sized and aligned. 2150 TCK_Store, 2151 /// Checking the bound value in a reference binding. Must be suitably sized 2152 /// and aligned, but is not required to refer to an object (until the 2153 /// reference is used), per core issue 453. 2154 TCK_ReferenceBinding, 2155 /// Checking the object expression in a non-static data member access. Must 2156 /// be an object within its lifetime. 2157 TCK_MemberAccess, 2158 /// Checking the 'this' pointer for a call to a non-static member function. 2159 /// Must be an object within its lifetime. 2160 TCK_MemberCall, 2161 /// Checking the 'this' pointer for a constructor call. 2162 TCK_ConstructorCall, 2163 /// Checking the operand of a static_cast to a derived pointer type. Must be 2164 /// null or an object within its lifetime. 2165 TCK_DowncastPointer, 2166 /// Checking the operand of a static_cast to a derived reference type. Must 2167 /// be an object within its lifetime. 2168 TCK_DowncastReference, 2169 /// Checking the operand of a cast to a base object. Must be suitably sized 2170 /// and aligned. 2171 TCK_Upcast, 2172 /// Checking the operand of a cast to a virtual base object. Must be an 2173 /// object within its lifetime. 2174 TCK_UpcastToVirtualBase 2175 }; 2176 2177 /// \brief Whether any type-checking sanitizers are enabled. If \c false, 2178 /// calls to EmitTypeCheck can be skipped. 2179 bool sanitizePerformTypeCheck() const; 2180 2181 /// \brief Emit a check that \p V is the address of storage of the 2182 /// appropriate size and alignment for an object of type \p Type. 2183 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V, 2184 QualType Type, CharUnits Alignment = CharUnits::Zero(), 2185 bool SkipNullCheck = false); 2186 2187 /// \brief Emit a check that \p Base points into an array object, which 2188 /// we can access at index \p Index. \p Accessed should be \c false if we 2189 /// this expression is used as an lvalue, for instance in "&Arr[Idx]". 2190 void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index, 2191 QualType IndexType, bool Accessed); 2192 2193 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 2194 bool isInc, bool isPre); 2195 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, 2196 bool isInc, bool isPre); 2197 2198 void EmitAlignmentAssumption(llvm::Value *PtrValue, unsigned Alignment, 2199 llvm::Value *OffsetValue = nullptr) { 2200 Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment, 2201 OffsetValue); 2202 } 2203 2204 /// Converts Location to a DebugLoc, if debug information is enabled. 2205 llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location); 2206 2207 2208 //===--------------------------------------------------------------------===// 2209 // Declaration Emission 2210 //===--------------------------------------------------------------------===// 2211 2212 /// EmitDecl - Emit a declaration. 2213 /// 2214 /// This function can be called with a null (unreachable) insert point. 2215 void EmitDecl(const Decl &D); 2216 2217 /// EmitVarDecl - Emit a local variable declaration. 2218 /// 2219 /// This function can be called with a null (unreachable) insert point. 2220 void EmitVarDecl(const VarDecl &D); 2221 2222 void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue, 2223 bool capturedByInit); 2224 2225 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D, 2226 llvm::Value *Address); 2227 2228 /// \brief Determine whether the given initializer is trivial in the sense 2229 /// that it requires no code to be generated. 2230 bool isTrivialInitializer(const Expr *Init); 2231 2232 /// EmitAutoVarDecl - Emit an auto variable declaration. 2233 /// 2234 /// This function can be called with a null (unreachable) insert point. 2235 void EmitAutoVarDecl(const VarDecl &D); 2236 2237 class AutoVarEmission { 2238 friend class CodeGenFunction; 2239 2240 const VarDecl *Variable; 2241 2242 /// The address of the alloca. Invalid if the variable was emitted 2243 /// as a global constant. 2244 Address Addr; 2245 2246 llvm::Value *NRVOFlag; 2247 2248 /// True if the variable is a __block variable. 2249 bool IsByRef; 2250 2251 /// True if the variable is of aggregate type and has a constant 2252 /// initializer. 2253 bool IsConstantAggregate; 2254 2255 /// Non-null if we should use lifetime annotations. 2256 llvm::Value *SizeForLifetimeMarkers; 2257 2258 struct Invalid {}; 2259 AutoVarEmission(Invalid) : Variable(nullptr), Addr(Address::invalid()) {} 2260 2261 AutoVarEmission(const VarDecl &variable) 2262 : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr), 2263 IsByRef(false), IsConstantAggregate(false), 2264 SizeForLifetimeMarkers(nullptr) {} 2265 2266 bool wasEmittedAsGlobal() const { return !Addr.isValid(); } 2267 2268 public: 2269 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); } 2270 2271 bool useLifetimeMarkers() const { 2272 return SizeForLifetimeMarkers != nullptr; 2273 } 2274 llvm::Value *getSizeForLifetimeMarkers() const { 2275 assert(useLifetimeMarkers()); 2276 return SizeForLifetimeMarkers; 2277 } 2278 2279 /// Returns the raw, allocated address, which is not necessarily 2280 /// the address of the object itself. 2281 Address getAllocatedAddress() const { 2282 return Addr; 2283 } 2284 2285 /// Returns the address of the object within this declaration. 2286 /// Note that this does not chase the forwarding pointer for 2287 /// __block decls. 2288 Address getObjectAddress(CodeGenFunction &CGF) const { 2289 if (!IsByRef) return Addr; 2290 2291 return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false); 2292 } 2293 }; 2294 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var); 2295 void EmitAutoVarInit(const AutoVarEmission &emission); 2296 void EmitAutoVarCleanups(const AutoVarEmission &emission); 2297 void emitAutoVarTypeCleanup(const AutoVarEmission &emission, 2298 QualType::DestructionKind dtorKind); 2299 2300 void EmitStaticVarDecl(const VarDecl &D, 2301 llvm::GlobalValue::LinkageTypes Linkage); 2302 2303 class ParamValue { 2304 llvm::Value *Value; 2305 unsigned Alignment; 2306 ParamValue(llvm::Value *V, unsigned A) : Value(V), Alignment(A) {} 2307 public: 2308 static ParamValue forDirect(llvm::Value *value) { 2309 return ParamValue(value, 0); 2310 } 2311 static ParamValue forIndirect(Address addr) { 2312 assert(!addr.getAlignment().isZero()); 2313 return ParamValue(addr.getPointer(), addr.getAlignment().getQuantity()); 2314 } 2315 2316 bool isIndirect() const { return Alignment != 0; } 2317 llvm::Value *getAnyValue() const { return Value; } 2318 2319 llvm::Value *getDirectValue() const { 2320 assert(!isIndirect()); 2321 return Value; 2322 } 2323 2324 Address getIndirectAddress() const { 2325 assert(isIndirect()); 2326 return Address(Value, CharUnits::fromQuantity(Alignment)); 2327 } 2328 }; 2329 2330 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl. 2331 void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo); 2332 2333 /// protectFromPeepholes - Protect a value that we're intending to 2334 /// store to the side, but which will probably be used later, from 2335 /// aggressive peepholing optimizations that might delete it. 2336 /// 2337 /// Pass the result to unprotectFromPeepholes to declare that 2338 /// protection is no longer required. 2339 /// 2340 /// There's no particular reason why this shouldn't apply to 2341 /// l-values, it's just that no existing peepholes work on pointers. 2342 PeepholeProtection protectFromPeepholes(RValue rvalue); 2343 void unprotectFromPeepholes(PeepholeProtection protection); 2344 2345 //===--------------------------------------------------------------------===// 2346 // Statement Emission 2347 //===--------------------------------------------------------------------===// 2348 2349 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info. 2350 void EmitStopPoint(const Stmt *S); 2351 2352 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call 2353 /// this function even if there is no current insertion point. 2354 /// 2355 /// This function may clear the current insertion point; callers should use 2356 /// EnsureInsertPoint if they wish to subsequently generate code without first 2357 /// calling EmitBlock, EmitBranch, or EmitStmt. 2358 void EmitStmt(const Stmt *S); 2359 2360 /// EmitSimpleStmt - Try to emit a "simple" statement which does not 2361 /// necessarily require an insertion point or debug information; typically 2362 /// because the statement amounts to a jump or a container of other 2363 /// statements. 2364 /// 2365 /// \return True if the statement was handled. 2366 bool EmitSimpleStmt(const Stmt *S); 2367 2368 Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false, 2369 AggValueSlot AVS = AggValueSlot::ignored()); 2370 Address EmitCompoundStmtWithoutScope(const CompoundStmt &S, 2371 bool GetLast = false, 2372 AggValueSlot AVS = 2373 AggValueSlot::ignored()); 2374 2375 /// EmitLabel - Emit the block for the given label. It is legal to call this 2376 /// function even if there is no current insertion point. 2377 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt. 2378 2379 void EmitLabelStmt(const LabelStmt &S); 2380 void EmitAttributedStmt(const AttributedStmt &S); 2381 void EmitGotoStmt(const GotoStmt &S); 2382 void EmitIndirectGotoStmt(const IndirectGotoStmt &S); 2383 void EmitIfStmt(const IfStmt &S); 2384 2385 void EmitWhileStmt(const WhileStmt &S, 2386 ArrayRef<const Attr *> Attrs = None); 2387 void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None); 2388 void EmitForStmt(const ForStmt &S, 2389 ArrayRef<const Attr *> Attrs = None); 2390 void EmitReturnStmt(const ReturnStmt &S); 2391 void EmitDeclStmt(const DeclStmt &S); 2392 void EmitBreakStmt(const BreakStmt &S); 2393 void EmitContinueStmt(const ContinueStmt &S); 2394 void EmitSwitchStmt(const SwitchStmt &S); 2395 void EmitDefaultStmt(const DefaultStmt &S); 2396 void EmitCaseStmt(const CaseStmt &S); 2397 void EmitCaseStmtRange(const CaseStmt &S); 2398 void EmitAsmStmt(const AsmStmt &S); 2399 2400 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S); 2401 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S); 2402 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S); 2403 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S); 2404 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S); 2405 2406 void EmitCoroutineBody(const CoroutineBodyStmt &S); 2407 RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID); 2408 2409 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 2410 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 2411 2412 void EmitCXXTryStmt(const CXXTryStmt &S); 2413 void EmitSEHTryStmt(const SEHTryStmt &S); 2414 void EmitSEHLeaveStmt(const SEHLeaveStmt &S); 2415 void EnterSEHTryStmt(const SEHTryStmt &S); 2416 void ExitSEHTryStmt(const SEHTryStmt &S); 2417 2418 void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter, 2419 const Stmt *OutlinedStmt); 2420 2421 llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF, 2422 const SEHExceptStmt &Except); 2423 2424 llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF, 2425 const SEHFinallyStmt &Finally); 2426 2427 void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF, 2428 llvm::Value *ParentFP, 2429 llvm::Value *EntryEBP); 2430 llvm::Value *EmitSEHExceptionCode(); 2431 llvm::Value *EmitSEHExceptionInfo(); 2432 llvm::Value *EmitSEHAbnormalTermination(); 2433 2434 /// Scan the outlined statement for captures from the parent function. For 2435 /// each capture, mark the capture as escaped and emit a call to 2436 /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap. 2437 void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt, 2438 bool IsFilter); 2439 2440 /// Recovers the address of a local in a parent function. ParentVar is the 2441 /// address of the variable used in the immediate parent function. It can 2442 /// either be an alloca or a call to llvm.localrecover if there are nested 2443 /// outlined functions. ParentFP is the frame pointer of the outermost parent 2444 /// frame. 2445 Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF, 2446 Address ParentVar, 2447 llvm::Value *ParentFP); 2448 2449 void EmitCXXForRangeStmt(const CXXForRangeStmt &S, 2450 ArrayRef<const Attr *> Attrs = None); 2451 2452 /// Returns calculated size of the specified type. 2453 llvm::Value *getTypeSize(QualType Ty); 2454 LValue InitCapturedStruct(const CapturedStmt &S); 2455 llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K); 2456 llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S); 2457 Address GenerateCapturedStmtArgument(const CapturedStmt &S); 2458 llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S); 2459 void GenerateOpenMPCapturedVars(const CapturedStmt &S, 2460 SmallVectorImpl<llvm::Value *> &CapturedVars); 2461 void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy, 2462 SourceLocation Loc); 2463 /// \brief Perform element by element copying of arrays with type \a 2464 /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure 2465 /// generated by \a CopyGen. 2466 /// 2467 /// \param DestAddr Address of the destination array. 2468 /// \param SrcAddr Address of the source array. 2469 /// \param OriginalType Type of destination and source arrays. 2470 /// \param CopyGen Copying procedure that copies value of single array element 2471 /// to another single array element. 2472 void EmitOMPAggregateAssign( 2473 Address DestAddr, Address SrcAddr, QualType OriginalType, 2474 const llvm::function_ref<void(Address, Address)> &CopyGen); 2475 /// \brief Emit proper copying of data from one variable to another. 2476 /// 2477 /// \param OriginalType Original type of the copied variables. 2478 /// \param DestAddr Destination address. 2479 /// \param SrcAddr Source address. 2480 /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has 2481 /// type of the base array element). 2482 /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of 2483 /// the base array element). 2484 /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a 2485 /// DestVD. 2486 void EmitOMPCopy(QualType OriginalType, 2487 Address DestAddr, Address SrcAddr, 2488 const VarDecl *DestVD, const VarDecl *SrcVD, 2489 const Expr *Copy); 2490 /// \brief Emit atomic update code for constructs: \a X = \a X \a BO \a E or 2491 /// \a X = \a E \a BO \a E. 2492 /// 2493 /// \param X Value to be updated. 2494 /// \param E Update value. 2495 /// \param BO Binary operation for update operation. 2496 /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update 2497 /// expression, false otherwise. 2498 /// \param AO Atomic ordering of the generated atomic instructions. 2499 /// \param CommonGen Code generator for complex expressions that cannot be 2500 /// expressed through atomicrmw instruction. 2501 /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was 2502 /// generated, <false, RValue::get(nullptr)> otherwise. 2503 std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr( 2504 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart, 2505 llvm::AtomicOrdering AO, SourceLocation Loc, 2506 const llvm::function_ref<RValue(RValue)> &CommonGen); 2507 bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D, 2508 OMPPrivateScope &PrivateScope); 2509 void EmitOMPPrivateClause(const OMPExecutableDirective &D, 2510 OMPPrivateScope &PrivateScope); 2511 void EmitOMPUseDevicePtrClause( 2512 const OMPClause &C, OMPPrivateScope &PrivateScope, 2513 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap); 2514 /// \brief Emit code for copyin clause in \a D directive. The next code is 2515 /// generated at the start of outlined functions for directives: 2516 /// \code 2517 /// threadprivate_var1 = master_threadprivate_var1; 2518 /// operator=(threadprivate_var2, master_threadprivate_var2); 2519 /// ... 2520 /// __kmpc_barrier(&loc, global_tid); 2521 /// \endcode 2522 /// 2523 /// \param D OpenMP directive possibly with 'copyin' clause(s). 2524 /// \returns true if at least one copyin variable is found, false otherwise. 2525 bool EmitOMPCopyinClause(const OMPExecutableDirective &D); 2526 /// \brief Emit initial code for lastprivate variables. If some variable is 2527 /// not also firstprivate, then the default initialization is used. Otherwise 2528 /// initialization of this variable is performed by EmitOMPFirstprivateClause 2529 /// method. 2530 /// 2531 /// \param D Directive that may have 'lastprivate' directives. 2532 /// \param PrivateScope Private scope for capturing lastprivate variables for 2533 /// proper codegen in internal captured statement. 2534 /// 2535 /// \returns true if there is at least one lastprivate variable, false 2536 /// otherwise. 2537 bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D, 2538 OMPPrivateScope &PrivateScope); 2539 /// \brief Emit final copying of lastprivate values to original variables at 2540 /// the end of the worksharing or simd directive. 2541 /// 2542 /// \param D Directive that has at least one 'lastprivate' directives. 2543 /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if 2544 /// it is the last iteration of the loop code in associated directive, or to 2545 /// 'i1 false' otherwise. If this item is nullptr, no final check is required. 2546 void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D, 2547 bool NoFinals, 2548 llvm::Value *IsLastIterCond = nullptr); 2549 /// Emit initial code for linear clauses. 2550 void EmitOMPLinearClause(const OMPLoopDirective &D, 2551 CodeGenFunction::OMPPrivateScope &PrivateScope); 2552 /// Emit final code for linear clauses. 2553 /// \param CondGen Optional conditional code for final part of codegen for 2554 /// linear clause. 2555 void EmitOMPLinearClauseFinal( 2556 const OMPLoopDirective &D, 2557 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen); 2558 /// \brief Emit initial code for reduction variables. Creates reduction copies 2559 /// and initializes them with the values according to OpenMP standard. 2560 /// 2561 /// \param D Directive (possibly) with the 'reduction' clause. 2562 /// \param PrivateScope Private scope for capturing reduction variables for 2563 /// proper codegen in internal captured statement. 2564 /// 2565 void EmitOMPReductionClauseInit(const OMPExecutableDirective &D, 2566 OMPPrivateScope &PrivateScope); 2567 /// \brief Emit final update of reduction values to original variables at 2568 /// the end of the directive. 2569 /// 2570 /// \param D Directive that has at least one 'reduction' directives. 2571 void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D); 2572 /// \brief Emit initial code for linear variables. Creates private copies 2573 /// and initializes them with the values according to OpenMP standard. 2574 /// 2575 /// \param D Directive (possibly) with the 'linear' clause. 2576 void EmitOMPLinearClauseInit(const OMPLoopDirective &D); 2577 2578 typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/, 2579 llvm::Value * /*OutlinedFn*/, 2580 const OMPTaskDataTy & /*Data*/)> 2581 TaskGenTy; 2582 void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S, 2583 const RegionCodeGenTy &BodyGen, 2584 const TaskGenTy &TaskGen, OMPTaskDataTy &Data); 2585 2586 void EmitOMPParallelDirective(const OMPParallelDirective &S); 2587 void EmitOMPSimdDirective(const OMPSimdDirective &S); 2588 void EmitOMPForDirective(const OMPForDirective &S); 2589 void EmitOMPForSimdDirective(const OMPForSimdDirective &S); 2590 void EmitOMPSectionsDirective(const OMPSectionsDirective &S); 2591 void EmitOMPSectionDirective(const OMPSectionDirective &S); 2592 void EmitOMPSingleDirective(const OMPSingleDirective &S); 2593 void EmitOMPMasterDirective(const OMPMasterDirective &S); 2594 void EmitOMPCriticalDirective(const OMPCriticalDirective &S); 2595 void EmitOMPParallelForDirective(const OMPParallelForDirective &S); 2596 void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S); 2597 void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S); 2598 void EmitOMPTaskDirective(const OMPTaskDirective &S); 2599 void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S); 2600 void EmitOMPBarrierDirective(const OMPBarrierDirective &S); 2601 void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S); 2602 void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S); 2603 void EmitOMPFlushDirective(const OMPFlushDirective &S); 2604 void EmitOMPOrderedDirective(const OMPOrderedDirective &S); 2605 void EmitOMPAtomicDirective(const OMPAtomicDirective &S); 2606 void EmitOMPTargetDirective(const OMPTargetDirective &S); 2607 void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S); 2608 void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S); 2609 void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S); 2610 void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S); 2611 void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S); 2612 void 2613 EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S); 2614 void EmitOMPTeamsDirective(const OMPTeamsDirective &S); 2615 void 2616 EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S); 2617 void EmitOMPCancelDirective(const OMPCancelDirective &S); 2618 void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S); 2619 void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S); 2620 void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S); 2621 void EmitOMPDistributeDirective(const OMPDistributeDirective &S); 2622 void EmitOMPDistributeLoop(const OMPDistributeDirective &S); 2623 void EmitOMPDistributeParallelForDirective( 2624 const OMPDistributeParallelForDirective &S); 2625 void EmitOMPDistributeParallelForSimdDirective( 2626 const OMPDistributeParallelForSimdDirective &S); 2627 void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S); 2628 void EmitOMPTargetParallelForSimdDirective( 2629 const OMPTargetParallelForSimdDirective &S); 2630 void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S); 2631 void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S); 2632 void 2633 EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S); 2634 2635 /// Emit outlined function for the target directive. 2636 static std::pair<llvm::Function * /*OutlinedFn*/, 2637 llvm::Constant * /*OutlinedFnID*/> 2638 EmitOMPTargetDirectiveOutlinedFunction(CodeGenModule &CGM, 2639 const OMPTargetDirective &S, 2640 StringRef ParentName, 2641 bool IsOffloadEntry); 2642 /// \brief Emit inner loop of the worksharing/simd construct. 2643 /// 2644 /// \param S Directive, for which the inner loop must be emitted. 2645 /// \param RequiresCleanup true, if directive has some associated private 2646 /// variables. 2647 /// \param LoopCond Bollean condition for loop continuation. 2648 /// \param IncExpr Increment expression for loop control variable. 2649 /// \param BodyGen Generator for the inner body of the inner loop. 2650 /// \param PostIncGen Genrator for post-increment code (required for ordered 2651 /// loop directvies). 2652 void EmitOMPInnerLoop( 2653 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond, 2654 const Expr *IncExpr, 2655 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen, 2656 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen); 2657 2658 JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind); 2659 /// Emit initial code for loop counters of loop-based directives. 2660 void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S, 2661 OMPPrivateScope &LoopScope); 2662 2663 private: 2664 /// Helpers for the OpenMP loop directives. 2665 void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit); 2666 void EmitOMPSimdInit(const OMPLoopDirective &D, bool IsMonotonic = false); 2667 void EmitOMPSimdFinal( 2668 const OMPLoopDirective &D, 2669 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen); 2670 /// \brief Emit code for the worksharing loop-based directive. 2671 /// \return true, if this construct has any lastprivate clause, false - 2672 /// otherwise. 2673 bool EmitOMPWorksharingLoop(const OMPLoopDirective &S); 2674 void EmitOMPOuterLoop(bool IsMonotonic, bool DynamicOrOrdered, 2675 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered, 2676 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk); 2677 void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind, 2678 bool IsMonotonic, const OMPLoopDirective &S, 2679 OMPPrivateScope &LoopScope, bool Ordered, Address LB, 2680 Address UB, Address ST, Address IL, 2681 llvm::Value *Chunk); 2682 void EmitOMPDistributeOuterLoop( 2683 OpenMPDistScheduleClauseKind ScheduleKind, 2684 const OMPDistributeDirective &S, OMPPrivateScope &LoopScope, 2685 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk); 2686 /// \brief Emit code for sections directive. 2687 void EmitSections(const OMPExecutableDirective &S); 2688 2689 public: 2690 2691 //===--------------------------------------------------------------------===// 2692 // LValue Expression Emission 2693 //===--------------------------------------------------------------------===// 2694 2695 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type. 2696 RValue GetUndefRValue(QualType Ty); 2697 2698 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E 2699 /// and issue an ErrorUnsupported style diagnostic (using the 2700 /// provided Name). 2701 RValue EmitUnsupportedRValue(const Expr *E, 2702 const char *Name); 2703 2704 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue 2705 /// an ErrorUnsupported style diagnostic (using the provided Name). 2706 LValue EmitUnsupportedLValue(const Expr *E, 2707 const char *Name); 2708 2709 /// EmitLValue - Emit code to compute a designator that specifies the location 2710 /// of the expression. 2711 /// 2712 /// This can return one of two things: a simple address or a bitfield 2713 /// reference. In either case, the LLVM Value* in the LValue structure is 2714 /// guaranteed to be an LLVM pointer type. 2715 /// 2716 /// If this returns a bitfield reference, nothing about the pointee type of 2717 /// the LLVM value is known: For example, it may not be a pointer to an 2718 /// integer. 2719 /// 2720 /// If this returns a normal address, and if the lvalue's C type is fixed 2721 /// size, this method guarantees that the returned pointer type will point to 2722 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a 2723 /// variable length type, this is not possible. 2724 /// 2725 LValue EmitLValue(const Expr *E); 2726 2727 /// \brief Same as EmitLValue but additionally we generate checking code to 2728 /// guard against undefined behavior. This is only suitable when we know 2729 /// that the address will be used to access the object. 2730 LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK); 2731 2732 RValue convertTempToRValue(Address addr, QualType type, 2733 SourceLocation Loc); 2734 2735 void EmitAtomicInit(Expr *E, LValue lvalue); 2736 2737 bool LValueIsSuitableForInlineAtomic(LValue Src); 2738 2739 RValue EmitAtomicLoad(LValue LV, SourceLocation SL, 2740 AggValueSlot Slot = AggValueSlot::ignored()); 2741 2742 RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc, 2743 llvm::AtomicOrdering AO, bool IsVolatile = false, 2744 AggValueSlot slot = AggValueSlot::ignored()); 2745 2746 void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit); 2747 2748 void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO, 2749 bool IsVolatile, bool isInit); 2750 2751 std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange( 2752 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc, 2753 llvm::AtomicOrdering Success = 2754 llvm::AtomicOrdering::SequentiallyConsistent, 2755 llvm::AtomicOrdering Failure = 2756 llvm::AtomicOrdering::SequentiallyConsistent, 2757 bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored()); 2758 2759 void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO, 2760 const llvm::function_ref<RValue(RValue)> &UpdateOp, 2761 bool IsVolatile); 2762 2763 /// EmitToMemory - Change a scalar value from its value 2764 /// representation to its in-memory representation. 2765 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty); 2766 2767 /// EmitFromMemory - Change a scalar value from its memory 2768 /// representation to its value representation. 2769 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty); 2770 2771 /// EmitLoadOfScalar - Load a scalar value from an address, taking 2772 /// care to appropriately convert from the memory representation to 2773 /// the LLVM value representation. 2774 llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, 2775 SourceLocation Loc, 2776 AlignmentSource AlignSource = 2777 AlignmentSource::Type, 2778 llvm::MDNode *TBAAInfo = nullptr, 2779 QualType TBAABaseTy = QualType(), 2780 uint64_t TBAAOffset = 0, 2781 bool isNontemporal = false); 2782 2783 /// EmitLoadOfScalar - Load a scalar value from an address, taking 2784 /// care to appropriately convert from the memory representation to 2785 /// the LLVM value representation. The l-value must be a simple 2786 /// l-value. 2787 llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc); 2788 2789 /// EmitStoreOfScalar - Store a scalar value to an address, taking 2790 /// care to appropriately convert from the memory representation to 2791 /// the LLVM value representation. 2792 void EmitStoreOfScalar(llvm::Value *Value, Address Addr, 2793 bool Volatile, QualType Ty, 2794 AlignmentSource AlignSource = AlignmentSource::Type, 2795 llvm::MDNode *TBAAInfo = nullptr, bool isInit = false, 2796 QualType TBAABaseTy = QualType(), 2797 uint64_t TBAAOffset = 0, bool isNontemporal = false); 2798 2799 /// EmitStoreOfScalar - Store a scalar value to an address, taking 2800 /// care to appropriately convert from the memory representation to 2801 /// the LLVM value representation. The l-value must be a simple 2802 /// l-value. The isInit flag indicates whether this is an initialization. 2803 /// If so, atomic qualifiers are ignored and the store is always non-atomic. 2804 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false); 2805 2806 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, 2807 /// this method emits the address of the lvalue, then loads the result as an 2808 /// rvalue, returning the rvalue. 2809 RValue EmitLoadOfLValue(LValue V, SourceLocation Loc); 2810 RValue EmitLoadOfExtVectorElementLValue(LValue V); 2811 RValue EmitLoadOfBitfieldLValue(LValue LV); 2812 RValue EmitLoadOfGlobalRegLValue(LValue LV); 2813 2814 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 2815 /// lvalue, where both are guaranteed to the have the same type, and that type 2816 /// is 'Ty'. 2817 void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false); 2818 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst); 2819 void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst); 2820 2821 /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints 2822 /// as EmitStoreThroughLValue. 2823 /// 2824 /// \param Result [out] - If non-null, this will be set to a Value* for the 2825 /// bit-field contents after the store, appropriate for use as the result of 2826 /// an assignment to the bit-field. 2827 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 2828 llvm::Value **Result=nullptr); 2829 2830 /// Emit an l-value for an assignment (simple or compound) of complex type. 2831 LValue EmitComplexAssignmentLValue(const BinaryOperator *E); 2832 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E); 2833 LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E, 2834 llvm::Value *&Result); 2835 2836 // Note: only available for agg return types 2837 LValue EmitBinaryOperatorLValue(const BinaryOperator *E); 2838 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E); 2839 // Note: only available for agg return types 2840 LValue EmitCallExprLValue(const CallExpr *E); 2841 // Note: only available for agg return types 2842 LValue EmitVAArgExprLValue(const VAArgExpr *E); 2843 LValue EmitDeclRefLValue(const DeclRefExpr *E); 2844 LValue EmitStringLiteralLValue(const StringLiteral *E); 2845 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E); 2846 LValue EmitPredefinedLValue(const PredefinedExpr *E); 2847 LValue EmitUnaryOpLValue(const UnaryOperator *E); 2848 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E, 2849 bool Accessed = false); 2850 LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E, 2851 bool IsLowerBound = true); 2852 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E); 2853 LValue EmitMemberExpr(const MemberExpr *E); 2854 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E); 2855 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E); 2856 LValue EmitInitListLValue(const InitListExpr *E); 2857 LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E); 2858 LValue EmitCastLValue(const CastExpr *E); 2859 LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 2860 LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e); 2861 2862 Address EmitExtVectorElementLValue(LValue V); 2863 2864 RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc); 2865 2866 Address EmitArrayToPointerDecay(const Expr *Array, 2867 AlignmentSource *AlignSource = nullptr); 2868 2869 class ConstantEmission { 2870 llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference; 2871 ConstantEmission(llvm::Constant *C, bool isReference) 2872 : ValueAndIsReference(C, isReference) {} 2873 public: 2874 ConstantEmission() {} 2875 static ConstantEmission forReference(llvm::Constant *C) { 2876 return ConstantEmission(C, true); 2877 } 2878 static ConstantEmission forValue(llvm::Constant *C) { 2879 return ConstantEmission(C, false); 2880 } 2881 2882 explicit operator bool() const { 2883 return ValueAndIsReference.getOpaqueValue() != nullptr; 2884 } 2885 2886 bool isReference() const { return ValueAndIsReference.getInt(); } 2887 LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const { 2888 assert(isReference()); 2889 return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(), 2890 refExpr->getType()); 2891 } 2892 2893 llvm::Constant *getValue() const { 2894 assert(!isReference()); 2895 return ValueAndIsReference.getPointer(); 2896 } 2897 }; 2898 2899 ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr); 2900 2901 RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, 2902 AggValueSlot slot = AggValueSlot::ignored()); 2903 LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e); 2904 2905 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface, 2906 const ObjCIvarDecl *Ivar); 2907 LValue EmitLValueForField(LValue Base, const FieldDecl* Field); 2908 LValue EmitLValueForLambdaField(const FieldDecl *Field); 2909 2910 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that 2911 /// if the Field is a reference, this will return the address of the reference 2912 /// and not the address of the value stored in the reference. 2913 LValue EmitLValueForFieldInitialization(LValue Base, 2914 const FieldDecl* Field); 2915 2916 LValue EmitLValueForIvar(QualType ObjectTy, 2917 llvm::Value* Base, const ObjCIvarDecl *Ivar, 2918 unsigned CVRQualifiers); 2919 2920 LValue EmitCXXConstructLValue(const CXXConstructExpr *E); 2921 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E); 2922 LValue EmitLambdaLValue(const LambdaExpr *E); 2923 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E); 2924 LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E); 2925 2926 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E); 2927 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E); 2928 LValue EmitStmtExprLValue(const StmtExpr *E); 2929 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E); 2930 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E); 2931 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init); 2932 2933 //===--------------------------------------------------------------------===// 2934 // Scalar Expression Emission 2935 //===--------------------------------------------------------------------===// 2936 2937 /// EmitCall - Generate a call of the given function, expecting the given 2938 /// result type, and using the given argument list which specifies both the 2939 /// LLVM arguments and the types they were derived from. 2940 RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, 2941 ReturnValueSlot ReturnValue, const CallArgList &Args, 2942 llvm::Instruction **callOrInvoke = nullptr); 2943 2944 RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E, 2945 ReturnValueSlot ReturnValue, 2946 llvm::Value *Chain = nullptr); 2947 RValue EmitCallExpr(const CallExpr *E, 2948 ReturnValueSlot ReturnValue = ReturnValueSlot()); 2949 RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue); 2950 CGCallee EmitCallee(const Expr *E); 2951 2952 void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl); 2953 2954 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee, 2955 const Twine &name = ""); 2956 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee, 2957 ArrayRef<llvm::Value*> args, 2958 const Twine &name = ""); 2959 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee, 2960 const Twine &name = ""); 2961 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee, 2962 ArrayRef<llvm::Value*> args, 2963 const Twine &name = ""); 2964 2965 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee, 2966 ArrayRef<llvm::Value *> Args, 2967 const Twine &Name = ""); 2968 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee, 2969 ArrayRef<llvm::Value*> args, 2970 const Twine &name = ""); 2971 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee, 2972 const Twine &name = ""); 2973 void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee, 2974 ArrayRef<llvm::Value*> args); 2975 2976 CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD, 2977 NestedNameSpecifier *Qual, 2978 llvm::Type *Ty); 2979 2980 CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD, 2981 CXXDtorType Type, 2982 const CXXRecordDecl *RD); 2983 2984 RValue 2985 EmitCXXMemberOrOperatorCall(const CXXMethodDecl *Method, 2986 const CGCallee &Callee, 2987 ReturnValueSlot ReturnValue, llvm::Value *This, 2988 llvm::Value *ImplicitParam, 2989 QualType ImplicitParamTy, const CallExpr *E, 2990 CallArgList *RtlArgs); 2991 RValue EmitCXXDestructorCall(const CXXDestructorDecl *DD, 2992 const CGCallee &Callee, 2993 llvm::Value *This, llvm::Value *ImplicitParam, 2994 QualType ImplicitParamTy, const CallExpr *E, 2995 StructorType Type); 2996 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E, 2997 ReturnValueSlot ReturnValue); 2998 RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE, 2999 const CXXMethodDecl *MD, 3000 ReturnValueSlot ReturnValue, 3001 bool HasQualifier, 3002 NestedNameSpecifier *Qualifier, 3003 bool IsArrow, const Expr *Base); 3004 // Compute the object pointer. 3005 Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base, 3006 llvm::Value *memberPtr, 3007 const MemberPointerType *memberPtrType, 3008 AlignmentSource *AlignSource = nullptr); 3009 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, 3010 ReturnValueSlot ReturnValue); 3011 3012 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 3013 const CXXMethodDecl *MD, 3014 ReturnValueSlot ReturnValue); 3015 RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E); 3016 3017 RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, 3018 ReturnValueSlot ReturnValue); 3019 3020 RValue EmitCUDADevicePrintfCallExpr(const CallExpr *E, 3021 ReturnValueSlot ReturnValue); 3022 3023 RValue EmitBuiltinExpr(const FunctionDecl *FD, 3024 unsigned BuiltinID, const CallExpr *E, 3025 ReturnValueSlot ReturnValue); 3026 3027 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue); 3028 3029 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call 3030 /// is unhandled by the current target. 3031 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3032 3033 llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty, 3034 const llvm::CmpInst::Predicate Fp, 3035 const llvm::CmpInst::Predicate Ip, 3036 const llvm::Twine &Name = ""); 3037 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3038 3039 llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID, 3040 unsigned LLVMIntrinsic, 3041 unsigned AltLLVMIntrinsic, 3042 const char *NameHint, 3043 unsigned Modifier, 3044 const CallExpr *E, 3045 SmallVectorImpl<llvm::Value *> &Ops, 3046 Address PtrOp0, Address PtrOp1); 3047 llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID, 3048 unsigned Modifier, llvm::Type *ArgTy, 3049 const CallExpr *E); 3050 llvm::Value *EmitNeonCall(llvm::Function *F, 3051 SmallVectorImpl<llvm::Value*> &O, 3052 const char *name, 3053 unsigned shift = 0, bool rightshift = false); 3054 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx); 3055 llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty, 3056 bool negateForRightShift); 3057 llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt, 3058 llvm::Type *Ty, bool usgn, const char *name); 3059 llvm::Value *vectorWrapScalar16(llvm::Value *Op); 3060 llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3061 3062 llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops); 3063 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3064 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3065 llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3066 llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3067 llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3068 llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID, 3069 const CallExpr *E); 3070 3071 private: 3072 enum class MSVCIntrin; 3073 3074 public: 3075 llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E); 3076 3077 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E); 3078 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E); 3079 llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E); 3080 llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E); 3081 llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E); 3082 llvm::Value *EmitObjCCollectionLiteral(const Expr *E, 3083 const ObjCMethodDecl *MethodWithObjects); 3084 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E); 3085 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, 3086 ReturnValueSlot Return = ReturnValueSlot()); 3087 3088 /// Retrieves the default cleanup kind for an ARC cleanup. 3089 /// Except under -fobjc-arc-eh, ARC cleanups are normal-only. 3090 CleanupKind getARCCleanupKind() { 3091 return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions 3092 ? NormalAndEHCleanup : NormalCleanup; 3093 } 3094 3095 // ARC primitives. 3096 void EmitARCInitWeak(Address addr, llvm::Value *value); 3097 void EmitARCDestroyWeak(Address addr); 3098 llvm::Value *EmitARCLoadWeak(Address addr); 3099 llvm::Value *EmitARCLoadWeakRetained(Address addr); 3100 llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored); 3101 void EmitARCCopyWeak(Address dst, Address src); 3102 void EmitARCMoveWeak(Address dst, Address src); 3103 llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value); 3104 llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value); 3105 llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value, 3106 bool resultIgnored); 3107 llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value, 3108 bool resultIgnored); 3109 llvm::Value *EmitARCRetain(QualType type, llvm::Value *value); 3110 llvm::Value *EmitARCRetainNonBlock(llvm::Value *value); 3111 llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory); 3112 void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise); 3113 void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise); 3114 llvm::Value *EmitARCAutorelease(llvm::Value *value); 3115 llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value); 3116 llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value); 3117 llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value); 3118 llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value); 3119 3120 std::pair<LValue,llvm::Value*> 3121 EmitARCStoreAutoreleasing(const BinaryOperator *e); 3122 std::pair<LValue,llvm::Value*> 3123 EmitARCStoreStrong(const BinaryOperator *e, bool ignored); 3124 std::pair<LValue,llvm::Value*> 3125 EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored); 3126 3127 llvm::Value *EmitObjCThrowOperand(const Expr *expr); 3128 llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr); 3129 llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr); 3130 3131 llvm::Value *EmitARCExtendBlockObject(const Expr *expr); 3132 llvm::Value *EmitARCReclaimReturnedObject(const Expr *e, 3133 bool allowUnsafeClaim); 3134 llvm::Value *EmitARCRetainScalarExpr(const Expr *expr); 3135 llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr); 3136 llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr); 3137 3138 void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values); 3139 3140 static Destroyer destroyARCStrongImprecise; 3141 static Destroyer destroyARCStrongPrecise; 3142 static Destroyer destroyARCWeak; 3143 3144 void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr); 3145 llvm::Value *EmitObjCAutoreleasePoolPush(); 3146 llvm::Value *EmitObjCMRRAutoreleasePoolPush(); 3147 void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr); 3148 void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr); 3149 3150 /// \brief Emits a reference binding to the passed in expression. 3151 RValue EmitReferenceBindingToExpr(const Expr *E); 3152 3153 //===--------------------------------------------------------------------===// 3154 // Expression Emission 3155 //===--------------------------------------------------------------------===// 3156 3157 // Expressions are broken into three classes: scalar, complex, aggregate. 3158 3159 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM 3160 /// scalar type, returning the result. 3161 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false); 3162 3163 /// Emit a conversion from the specified type to the specified destination 3164 /// type, both of which are LLVM scalar types. 3165 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy, 3166 QualType DstTy, SourceLocation Loc); 3167 3168 /// Emit a conversion from the specified complex type to the specified 3169 /// destination type, where the destination type is an LLVM scalar type. 3170 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, 3171 QualType DstTy, 3172 SourceLocation Loc); 3173 3174 /// EmitAggExpr - Emit the computation of the specified expression 3175 /// of aggregate type. The result is computed into the given slot, 3176 /// which may be null to indicate that the value is not needed. 3177 void EmitAggExpr(const Expr *E, AggValueSlot AS); 3178 3179 /// EmitAggExprToLValue - Emit the computation of the specified expression of 3180 /// aggregate type into a temporary LValue. 3181 LValue EmitAggExprToLValue(const Expr *E); 3182 3183 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object, 3184 /// make sure it survives garbage collection until this point. 3185 void EmitExtendGCLifetime(llvm::Value *object); 3186 3187 /// EmitComplexExpr - Emit the computation of the specified expression of 3188 /// complex type, returning the result. 3189 ComplexPairTy EmitComplexExpr(const Expr *E, 3190 bool IgnoreReal = false, 3191 bool IgnoreImag = false); 3192 3193 /// EmitComplexExprIntoLValue - Emit the given expression of complex 3194 /// type and place its result into the specified l-value. 3195 void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit); 3196 3197 /// EmitStoreOfComplex - Store a complex number into the specified l-value. 3198 void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit); 3199 3200 /// EmitLoadOfComplex - Load a complex number from the specified l-value. 3201 ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc); 3202 3203 Address emitAddrOfRealComponent(Address complex, QualType complexType); 3204 Address emitAddrOfImagComponent(Address complex, QualType complexType); 3205 3206 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the 3207 /// global variable that has already been created for it. If the initializer 3208 /// has a different type than GV does, this may free GV and return a different 3209 /// one. Otherwise it just returns GV. 3210 llvm::GlobalVariable * 3211 AddInitializerToStaticVarDecl(const VarDecl &D, 3212 llvm::GlobalVariable *GV); 3213 3214 3215 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++ 3216 /// variable with global storage. 3217 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr, 3218 bool PerformInit); 3219 3220 llvm::Constant *createAtExitStub(const VarDecl &VD, llvm::Constant *Dtor, 3221 llvm::Constant *Addr); 3222 3223 /// Call atexit() with a function that passes the given argument to 3224 /// the given function. 3225 void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn, 3226 llvm::Constant *addr); 3227 3228 /// Emit code in this function to perform a guarded variable 3229 /// initialization. Guarded initializations are used when it's not 3230 /// possible to prove that an initialization will be done exactly 3231 /// once, e.g. with a static local variable or a static data member 3232 /// of a class template. 3233 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr, 3234 bool PerformInit); 3235 3236 /// GenerateCXXGlobalInitFunc - Generates code for initializing global 3237 /// variables. 3238 void GenerateCXXGlobalInitFunc(llvm::Function *Fn, 3239 ArrayRef<llvm::Function *> CXXThreadLocals, 3240 Address Guard = Address::invalid()); 3241 3242 /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global 3243 /// variables. 3244 void GenerateCXXGlobalDtorsFunc(llvm::Function *Fn, 3245 const std::vector<std::pair<llvm::WeakVH, 3246 llvm::Constant*> > &DtorsAndObjects); 3247 3248 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, 3249 const VarDecl *D, 3250 llvm::GlobalVariable *Addr, 3251 bool PerformInit); 3252 3253 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest); 3254 3255 void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp); 3256 3257 void enterFullExpression(const ExprWithCleanups *E) { 3258 if (E->getNumObjects() == 0) return; 3259 enterNonTrivialFullExpression(E); 3260 } 3261 void enterNonTrivialFullExpression(const ExprWithCleanups *E); 3262 3263 void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true); 3264 3265 void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest); 3266 3267 RValue EmitAtomicExpr(AtomicExpr *E); 3268 3269 //===--------------------------------------------------------------------===// 3270 // Annotations Emission 3271 //===--------------------------------------------------------------------===// 3272 3273 /// Emit an annotation call (intrinsic or builtin). 3274 llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn, 3275 llvm::Value *AnnotatedVal, 3276 StringRef AnnotationStr, 3277 SourceLocation Location); 3278 3279 /// Emit local annotations for the local variable V, declared by D. 3280 void EmitVarAnnotations(const VarDecl *D, llvm::Value *V); 3281 3282 /// Emit field annotations for the given field & value. Returns the 3283 /// annotation result. 3284 Address EmitFieldAnnotations(const FieldDecl *D, Address V); 3285 3286 //===--------------------------------------------------------------------===// 3287 // Internal Helpers 3288 //===--------------------------------------------------------------------===// 3289 3290 /// ContainsLabel - Return true if the statement contains a label in it. If 3291 /// this statement is not executed normally, it not containing a label means 3292 /// that we can just remove the code. 3293 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false); 3294 3295 /// containsBreak - Return true if the statement contains a break out of it. 3296 /// If the statement (recursively) contains a switch or loop with a break 3297 /// inside of it, this is fine. 3298 static bool containsBreak(const Stmt *S); 3299 3300 /// Determine if the given statement might introduce a declaration into the 3301 /// current scope, by being a (possibly-labelled) DeclStmt. 3302 static bool mightAddDeclToScope(const Stmt *S); 3303 3304 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 3305 /// to a constant, or if it does but contains a label, return false. If it 3306 /// constant folds return true and set the boolean result in Result. 3307 bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result, 3308 bool AllowLabels = false); 3309 3310 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 3311 /// to a constant, or if it does but contains a label, return false. If it 3312 /// constant folds return true and set the folded value. 3313 bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result, 3314 bool AllowLabels = false); 3315 3316 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an 3317 /// if statement) to the specified blocks. Based on the condition, this might 3318 /// try to simplify the codegen of the conditional based on the branch. 3319 /// TrueCount should be the number of times we expect the condition to 3320 /// evaluate to true based on PGO data. 3321 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, 3322 llvm::BasicBlock *FalseBlock, uint64_t TrueCount); 3323 3324 /// \brief Emit a description of a type in a format suitable for passing to 3325 /// a runtime sanitizer handler. 3326 llvm::Constant *EmitCheckTypeDescriptor(QualType T); 3327 3328 /// \brief Convert a value into a format suitable for passing to a runtime 3329 /// sanitizer handler. 3330 llvm::Value *EmitCheckValue(llvm::Value *V); 3331 3332 /// \brief Emit a description of a source location in a format suitable for 3333 /// passing to a runtime sanitizer handler. 3334 llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc); 3335 3336 /// \brief Create a basic block that will call a handler function in a 3337 /// sanitizer runtime with the provided arguments, and create a conditional 3338 /// branch to it. 3339 void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked, 3340 StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs, 3341 ArrayRef<llvm::Value *> DynamicArgs); 3342 3343 /// \brief Emit a slow path cross-DSO CFI check which calls __cfi_slowpath 3344 /// if Cond if false. 3345 void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond, 3346 llvm::ConstantInt *TypeId, llvm::Value *Ptr, 3347 ArrayRef<llvm::Constant *> StaticArgs); 3348 3349 /// \brief Create a basic block that will call the trap intrinsic, and emit a 3350 /// conditional branch to it, for the -ftrapv checks. 3351 void EmitTrapCheck(llvm::Value *Checked); 3352 3353 /// \brief Emit a call to trap or debugtrap and attach function attribute 3354 /// "trap-func-name" if specified. 3355 llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID); 3356 3357 /// \brief Emit a cross-DSO CFI failure handling function. 3358 void EmitCfiCheckFail(); 3359 3360 /// \brief Create a check for a function parameter that may potentially be 3361 /// declared as non-null. 3362 void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc, 3363 const FunctionDecl *FD, unsigned ParmNum); 3364 3365 /// EmitCallArg - Emit a single call argument. 3366 void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType); 3367 3368 /// EmitDelegateCallArg - We are performing a delegate call; that 3369 /// is, the current function is delegating to another one. Produce 3370 /// a r-value suitable for passing the given parameter. 3371 void EmitDelegateCallArg(CallArgList &args, const VarDecl *param, 3372 SourceLocation loc); 3373 3374 /// SetFPAccuracy - Set the minimum required accuracy of the given floating 3375 /// point operation, expressed as the maximum relative error in ulp. 3376 void SetFPAccuracy(llvm::Value *Val, float Accuracy); 3377 3378 private: 3379 llvm::MDNode *getRangeForLoadFromType(QualType Ty); 3380 void EmitReturnOfRValue(RValue RV, QualType Ty); 3381 3382 void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New); 3383 3384 llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4> 3385 DeferredReplacements; 3386 3387 /// Set the address of a local variable. 3388 void setAddrOfLocalVar(const VarDecl *VD, Address Addr) { 3389 assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!"); 3390 LocalDeclMap.insert({VD, Addr}); 3391 } 3392 3393 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty 3394 /// from function arguments into \arg Dst. See ABIArgInfo::Expand. 3395 /// 3396 /// \param AI - The first function argument of the expansion. 3397 void ExpandTypeFromArgs(QualType Ty, LValue Dst, 3398 SmallVectorImpl<llvm::Value *>::iterator &AI); 3399 3400 /// ExpandTypeToArgs - Expand an RValue \arg RV, with the LLVM type for \arg 3401 /// Ty, into individual arguments on the provided vector \arg IRCallArgs, 3402 /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand. 3403 void ExpandTypeToArgs(QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy, 3404 SmallVectorImpl<llvm::Value *> &IRCallArgs, 3405 unsigned &IRCallArgPos); 3406 3407 llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info, 3408 const Expr *InputExpr, std::string &ConstraintStr); 3409 3410 llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info, 3411 LValue InputValue, QualType InputType, 3412 std::string &ConstraintStr, 3413 SourceLocation Loc); 3414 3415 /// \brief Attempts to statically evaluate the object size of E. If that 3416 /// fails, emits code to figure the size of E out for us. This is 3417 /// pass_object_size aware. 3418 llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type, 3419 llvm::IntegerType *ResType); 3420 3421 /// \brief Emits the size of E, as required by __builtin_object_size. This 3422 /// function is aware of pass_object_size parameters, and will act accordingly 3423 /// if E is a parameter with the pass_object_size attribute. 3424 llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type, 3425 llvm::IntegerType *ResType); 3426 3427 public: 3428 #ifndef NDEBUG 3429 // Determine whether the given argument is an Objective-C method 3430 // that may have type parameters in its signature. 3431 static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) { 3432 const DeclContext *dc = method->getDeclContext(); 3433 if (const ObjCInterfaceDecl *classDecl= dyn_cast<ObjCInterfaceDecl>(dc)) { 3434 return classDecl->getTypeParamListAsWritten(); 3435 } 3436 3437 if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) { 3438 return catDecl->getTypeParamList(); 3439 } 3440 3441 return false; 3442 } 3443 3444 template<typename T> 3445 static bool isObjCMethodWithTypeParams(const T *) { return false; } 3446 #endif 3447 3448 enum class EvaluationOrder { 3449 ///! No language constraints on evaluation order. 3450 Default, 3451 ///! Language semantics require left-to-right evaluation. 3452 ForceLeftToRight, 3453 ///! Language semantics require right-to-left evaluation. 3454 ForceRightToLeft 3455 }; 3456 3457 /// EmitCallArgs - Emit call arguments for a function. 3458 template <typename T> 3459 void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo, 3460 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange, 3461 const FunctionDecl *CalleeDecl = nullptr, 3462 unsigned ParamsToSkip = 0, 3463 EvaluationOrder Order = EvaluationOrder::Default) { 3464 SmallVector<QualType, 16> ArgTypes; 3465 CallExpr::const_arg_iterator Arg = ArgRange.begin(); 3466 3467 assert((ParamsToSkip == 0 || CallArgTypeInfo) && 3468 "Can't skip parameters if type info is not provided"); 3469 if (CallArgTypeInfo) { 3470 #ifndef NDEBUG 3471 bool isGenericMethod = isObjCMethodWithTypeParams(CallArgTypeInfo); 3472 #endif 3473 3474 // First, use the argument types that the type info knows about 3475 for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip, 3476 E = CallArgTypeInfo->param_type_end(); 3477 I != E; ++I, ++Arg) { 3478 assert(Arg != ArgRange.end() && "Running over edge of argument list!"); 3479 assert((isGenericMethod || 3480 ((*I)->isVariablyModifiedType() || 3481 (*I).getNonReferenceType()->isObjCRetainableType() || 3482 getContext() 3483 .getCanonicalType((*I).getNonReferenceType()) 3484 .getTypePtr() == 3485 getContext() 3486 .getCanonicalType((*Arg)->getType()) 3487 .getTypePtr())) && 3488 "type mismatch in call argument!"); 3489 ArgTypes.push_back(*I); 3490 } 3491 } 3492 3493 // Either we've emitted all the call args, or we have a call to variadic 3494 // function. 3495 assert((Arg == ArgRange.end() || !CallArgTypeInfo || 3496 CallArgTypeInfo->isVariadic()) && 3497 "Extra arguments in non-variadic function!"); 3498 3499 // If we still have any arguments, emit them using the type of the argument. 3500 for (auto *A : llvm::make_range(Arg, ArgRange.end())) 3501 ArgTypes.push_back(getVarArgType(A)); 3502 3503 EmitCallArgs(Args, ArgTypes, ArgRange, CalleeDecl, ParamsToSkip, Order); 3504 } 3505 3506 void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes, 3507 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange, 3508 const FunctionDecl *CalleeDecl = nullptr, 3509 unsigned ParamsToSkip = 0, 3510 EvaluationOrder Order = EvaluationOrder::Default); 3511 3512 /// EmitPointerWithAlignment - Given an expression with a pointer 3513 /// type, emit the value and compute our best estimate of the 3514 /// alignment of the pointee. 3515 /// 3516 /// Note that this function will conservatively fall back on the type 3517 /// when it doesn't 3518 /// 3519 /// \param Source - If non-null, this will be initialized with 3520 /// information about the source of the alignment. Note that this 3521 /// function will conservatively fall back on the type when it 3522 /// doesn't recognize the expression, which means that sometimes 3523 /// 3524 /// a worst-case One 3525 /// reasonable way to use this information is when there's a 3526 /// language guarantee that the pointer must be aligned to some 3527 /// stricter value, and we're simply trying to ensure that 3528 /// sufficiently obvious uses of under-aligned objects don't get 3529 /// miscompiled; for example, a placement new into the address of 3530 /// a local variable. In such a case, it's quite reasonable to 3531 /// just ignore the returned alignment when it isn't from an 3532 /// explicit source. 3533 Address EmitPointerWithAlignment(const Expr *Addr, 3534 AlignmentSource *Source = nullptr); 3535 3536 void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK); 3537 3538 private: 3539 QualType getVarArgType(const Expr *Arg); 3540 3541 const TargetCodeGenInfo &getTargetHooks() const { 3542 return CGM.getTargetCodeGenInfo(); 3543 } 3544 3545 void EmitDeclMetadata(); 3546 3547 BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType, 3548 const AutoVarEmission &emission); 3549 3550 void AddObjCARCExceptionMetadata(llvm::Instruction *Inst); 3551 3552 llvm::Value *GetValueForARMHint(unsigned BuiltinID); 3553 }; 3554 3555 /// Helper class with most of the code for saving a value for a 3556 /// conditional expression cleanup. 3557 struct DominatingLLVMValue { 3558 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type; 3559 3560 /// Answer whether the given value needs extra work to be saved. 3561 static bool needsSaving(llvm::Value *value) { 3562 // If it's not an instruction, we don't need to save. 3563 if (!isa<llvm::Instruction>(value)) return false; 3564 3565 // If it's an instruction in the entry block, we don't need to save. 3566 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent(); 3567 return (block != &block->getParent()->getEntryBlock()); 3568 } 3569 3570 /// Try to save the given value. 3571 static saved_type save(CodeGenFunction &CGF, llvm::Value *value) { 3572 if (!needsSaving(value)) return saved_type(value, false); 3573 3574 // Otherwise, we need an alloca. 3575 auto align = CharUnits::fromQuantity( 3576 CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType())); 3577 Address alloca = 3578 CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save"); 3579 CGF.Builder.CreateStore(value, alloca); 3580 3581 return saved_type(alloca.getPointer(), true); 3582 } 3583 3584 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) { 3585 // If the value says it wasn't saved, trust that it's still dominating. 3586 if (!value.getInt()) return value.getPointer(); 3587 3588 // Otherwise, it should be an alloca instruction, as set up in save(). 3589 auto alloca = cast<llvm::AllocaInst>(value.getPointer()); 3590 return CGF.Builder.CreateAlignedLoad(alloca, alloca->getAlignment()); 3591 } 3592 }; 3593 3594 /// A partial specialization of DominatingValue for llvm::Values that 3595 /// might be llvm::Instructions. 3596 template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue { 3597 typedef T *type; 3598 static type restore(CodeGenFunction &CGF, saved_type value) { 3599 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value)); 3600 } 3601 }; 3602 3603 /// A specialization of DominatingValue for Address. 3604 template <> struct DominatingValue<Address> { 3605 typedef Address type; 3606 3607 struct saved_type { 3608 DominatingLLVMValue::saved_type SavedValue; 3609 CharUnits Alignment; 3610 }; 3611 3612 static bool needsSaving(type value) { 3613 return DominatingLLVMValue::needsSaving(value.getPointer()); 3614 } 3615 static saved_type save(CodeGenFunction &CGF, type value) { 3616 return { DominatingLLVMValue::save(CGF, value.getPointer()), 3617 value.getAlignment() }; 3618 } 3619 static type restore(CodeGenFunction &CGF, saved_type value) { 3620 return Address(DominatingLLVMValue::restore(CGF, value.SavedValue), 3621 value.Alignment); 3622 } 3623 }; 3624 3625 /// A specialization of DominatingValue for RValue. 3626 template <> struct DominatingValue<RValue> { 3627 typedef RValue type; 3628 class saved_type { 3629 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral, 3630 AggregateAddress, ComplexAddress }; 3631 3632 llvm::Value *Value; 3633 unsigned K : 3; 3634 unsigned Align : 29; 3635 saved_type(llvm::Value *v, Kind k, unsigned a = 0) 3636 : Value(v), K(k), Align(a) {} 3637 3638 public: 3639 static bool needsSaving(RValue value); 3640 static saved_type save(CodeGenFunction &CGF, RValue value); 3641 RValue restore(CodeGenFunction &CGF); 3642 3643 // implementations in CGCleanup.cpp 3644 }; 3645 3646 static bool needsSaving(type value) { 3647 return saved_type::needsSaving(value); 3648 } 3649 static saved_type save(CodeGenFunction &CGF, type value) { 3650 return saved_type::save(CGF, value); 3651 } 3652 static type restore(CodeGenFunction &CGF, saved_type value) { 3653 return value.restore(CGF); 3654 } 3655 }; 3656 3657 } // end namespace CodeGen 3658 } // end namespace clang 3659 3660 #endif 3661