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