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