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