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