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