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