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