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