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