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