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