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