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 Module; 50 class SwitchInst; 51 class Twine; 52 class Value; 53 class CanonicalLoopInfo; 54 } 55 56 namespace clang { 57 class ASTContext; 58 class BlockDecl; 59 class CXXDestructorDecl; 60 class CXXForRangeStmt; 61 class CXXTryStmt; 62 class Decl; 63 class LabelDecl; 64 class EnumConstantDecl; 65 class FunctionDecl; 66 class FunctionProtoType; 67 class LabelStmt; 68 class ObjCContainerDecl; 69 class ObjCInterfaceDecl; 70 class ObjCIvarDecl; 71 class ObjCMethodDecl; 72 class ObjCImplementationDecl; 73 class ObjCPropertyImplDecl; 74 class TargetInfo; 75 class VarDecl; 76 class ObjCForCollectionStmt; 77 class ObjCAtTryStmt; 78 class ObjCAtThrowStmt; 79 class ObjCAtSynchronizedStmt; 80 class ObjCAutoreleasePoolStmt; 81 class OMPUseDevicePtrClause; 82 class OMPUseDeviceAddrClause; 83 class ReturnsNonNullAttr; 84 class SVETypeFlags; 85 class OMPExecutableDirective; 86 87 namespace analyze_os_log { 88 class OSLogBufferLayout; 89 } 90 91 namespace CodeGen { 92 class CodeGenTypes; 93 class CGCallee; 94 class CGFunctionInfo; 95 class CGRecordLayout; 96 class CGBlockInfo; 97 class CGCXXABI; 98 class BlockByrefHelpers; 99 class BlockByrefInfo; 100 class BlockFlags; 101 class BlockFieldFlags; 102 class RegionCodeGenTy; 103 class TargetCodeGenInfo; 104 struct OMPTaskDataTy; 105 struct CGCoroData; 106 107 /// The kind of evaluation to perform on values of a particular 108 /// type. Basically, is the code in CGExprScalar, CGExprComplex, or 109 /// CGExprAgg? 110 /// 111 /// TODO: should vectors maybe be split out into their own thing? 112 enum TypeEvaluationKind { 113 TEK_Scalar, 114 TEK_Complex, 115 TEK_Aggregate 116 }; 117 118 #define LIST_SANITIZER_CHECKS \ 119 SANITIZER_CHECK(AddOverflow, add_overflow, 0) \ 120 SANITIZER_CHECK(BuiltinUnreachable, builtin_unreachable, 0) \ 121 SANITIZER_CHECK(CFICheckFail, cfi_check_fail, 0) \ 122 SANITIZER_CHECK(DivremOverflow, divrem_overflow, 0) \ 123 SANITIZER_CHECK(DynamicTypeCacheMiss, dynamic_type_cache_miss, 0) \ 124 SANITIZER_CHECK(FloatCastOverflow, float_cast_overflow, 0) \ 125 SANITIZER_CHECK(FunctionTypeMismatch, function_type_mismatch, 1) \ 126 SANITIZER_CHECK(ImplicitConversion, implicit_conversion, 0) \ 127 SANITIZER_CHECK(InvalidBuiltin, invalid_builtin, 0) \ 128 SANITIZER_CHECK(InvalidObjCCast, invalid_objc_cast, 0) \ 129 SANITIZER_CHECK(LoadInvalidValue, load_invalid_value, 0) \ 130 SANITIZER_CHECK(MissingReturn, missing_return, 0) \ 131 SANITIZER_CHECK(MulOverflow, mul_overflow, 0) \ 132 SANITIZER_CHECK(NegateOverflow, negate_overflow, 0) \ 133 SANITIZER_CHECK(NullabilityArg, nullability_arg, 0) \ 134 SANITIZER_CHECK(NullabilityReturn, nullability_return, 1) \ 135 SANITIZER_CHECK(NonnullArg, nonnull_arg, 0) \ 136 SANITIZER_CHECK(NonnullReturn, nonnull_return, 1) \ 137 SANITIZER_CHECK(OutOfBounds, out_of_bounds, 0) \ 138 SANITIZER_CHECK(PointerOverflow, pointer_overflow, 0) \ 139 SANITIZER_CHECK(ShiftOutOfBounds, shift_out_of_bounds, 0) \ 140 SANITIZER_CHECK(SubOverflow, sub_overflow, 0) \ 141 SANITIZER_CHECK(TypeMismatch, type_mismatch, 1) \ 142 SANITIZER_CHECK(AlignmentAssumption, alignment_assumption, 0) \ 143 SANITIZER_CHECK(VLABoundNotPositive, vla_bound_not_positive, 0) 144 145 enum SanitizerHandler { 146 #define SANITIZER_CHECK(Enum, Name, Version) Enum, 147 LIST_SANITIZER_CHECKS 148 #undef SANITIZER_CHECK 149 }; 150 151 /// Helper class with most of the code for saving a value for a 152 /// conditional expression cleanup. 153 struct DominatingLLVMValue { 154 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type; 155 156 /// Answer whether the given value needs extra work to be saved. 157 static bool needsSaving(llvm::Value *value) { 158 // If it's not an instruction, we don't need to save. 159 if (!isa<llvm::Instruction>(value)) return false; 160 161 // If it's an instruction in the entry block, we don't need to save. 162 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent(); 163 return (block != &block->getParent()->getEntryBlock()); 164 } 165 166 static saved_type save(CodeGenFunction &CGF, llvm::Value *value); 167 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value); 168 }; 169 170 /// A partial specialization of DominatingValue for llvm::Values that 171 /// might be llvm::Instructions. 172 template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue { 173 typedef T *type; 174 static type restore(CodeGenFunction &CGF, saved_type value) { 175 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value)); 176 } 177 }; 178 179 /// A specialization of DominatingValue for Address. 180 template <> struct DominatingValue<Address> { 181 typedef Address type; 182 183 struct saved_type { 184 DominatingLLVMValue::saved_type SavedValue; 185 llvm::Type *ElementType; 186 CharUnits Alignment; 187 }; 188 189 static bool needsSaving(type value) { 190 return DominatingLLVMValue::needsSaving(value.getPointer()); 191 } 192 static saved_type save(CodeGenFunction &CGF, type value) { 193 return { DominatingLLVMValue::save(CGF, value.getPointer()), 194 value.getElementType(), value.getAlignment() }; 195 } 196 static type restore(CodeGenFunction &CGF, saved_type value) { 197 return Address(DominatingLLVMValue::restore(CGF, value.SavedValue), 198 value.ElementType, value.Alignment); 199 } 200 }; 201 202 /// A specialization of DominatingValue for RValue. 203 template <> struct DominatingValue<RValue> { 204 typedef RValue type; 205 class saved_type { 206 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral, 207 AggregateAddress, ComplexAddress }; 208 209 llvm::Value *Value; 210 unsigned K : 3; 211 unsigned Align : 29; 212 saved_type(llvm::Value *v, Kind k, unsigned a = 0) 213 : Value(v), K(k), Align(a) {} 214 215 public: 216 static bool needsSaving(RValue value); 217 static saved_type save(CodeGenFunction &CGF, RValue value); 218 RValue restore(CodeGenFunction &CGF); 219 220 // implementations in CGCleanup.cpp 221 }; 222 223 static bool needsSaving(type value) { 224 return saved_type::needsSaving(value); 225 } 226 static saved_type save(CodeGenFunction &CGF, type value) { 227 return saved_type::save(CGF, value); 228 } 229 static type restore(CodeGenFunction &CGF, saved_type value) { 230 return value.restore(CGF); 231 } 232 }; 233 234 /// CodeGenFunction - This class organizes the per-function state that is used 235 /// while generating LLVM code. 236 class CodeGenFunction : public CodeGenTypeCache { 237 CodeGenFunction(const CodeGenFunction &) = delete; 238 void operator=(const CodeGenFunction &) = delete; 239 240 friend class CGCXXABI; 241 public: 242 /// A jump destination is an abstract label, branching to which may 243 /// require a jump out through normal cleanups. 244 struct JumpDest { 245 JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {} 246 JumpDest(llvm::BasicBlock *Block, 247 EHScopeStack::stable_iterator Depth, 248 unsigned Index) 249 : Block(Block), ScopeDepth(Depth), Index(Index) {} 250 251 bool isValid() const { return Block != nullptr; } 252 llvm::BasicBlock *getBlock() const { return Block; } 253 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; } 254 unsigned getDestIndex() const { return Index; } 255 256 // This should be used cautiously. 257 void setScopeDepth(EHScopeStack::stable_iterator depth) { 258 ScopeDepth = depth; 259 } 260 261 private: 262 llvm::BasicBlock *Block; 263 EHScopeStack::stable_iterator ScopeDepth; 264 unsigned Index; 265 }; 266 267 CodeGenModule &CGM; // Per-module state. 268 const TargetInfo &Target; 269 270 // For EH/SEH outlined funclets, this field points to parent's CGF 271 CodeGenFunction *ParentCGF = nullptr; 272 273 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy; 274 LoopInfoStack LoopStack; 275 CGBuilderTy Builder; 276 277 // Stores variables for which we can't generate correct lifetime markers 278 // because of jumps. 279 VarBypassDetector Bypasses; 280 281 /// List of recently emitted OMPCanonicalLoops. 282 /// 283 /// Since OMPCanonicalLoops are nested inside other statements (in particular 284 /// CapturedStmt generated by OMPExecutableDirective and non-perfectly nested 285 /// loops), we cannot directly call OMPEmitOMPCanonicalLoop and receive its 286 /// llvm::CanonicalLoopInfo. Instead, we call EmitStmt and any 287 /// OMPEmitOMPCanonicalLoop called by it will add its CanonicalLoopInfo to 288 /// this stack when done. Entering a new loop requires clearing this list; it 289 /// either means we start parsing a new loop nest (in which case the previous 290 /// loop nest goes out of scope) or a second loop in the same level in which 291 /// case it would be ambiguous into which of the two (or more) loops the loop 292 /// nest would extend. 293 SmallVector<llvm::CanonicalLoopInfo *, 4> OMPLoopNestStack; 294 295 /// Number of nested loop to be consumed by the last surrounding 296 /// loop-associated directive. 297 int ExpectedOMPLoopDepth = 0; 298 299 // CodeGen lambda for loops and support for ordered clause 300 typedef llvm::function_ref<void(CodeGenFunction &, const OMPLoopDirective &, 301 JumpDest)> 302 CodeGenLoopTy; 303 typedef llvm::function_ref<void(CodeGenFunction &, SourceLocation, 304 const unsigned, const bool)> 305 CodeGenOrderedTy; 306 307 // Codegen lambda for loop bounds in worksharing loop constructs 308 typedef llvm::function_ref<std::pair<LValue, LValue>( 309 CodeGenFunction &, const OMPExecutableDirective &S)> 310 CodeGenLoopBoundsTy; 311 312 // Codegen lambda for loop bounds in dispatch-based loop implementation 313 typedef llvm::function_ref<std::pair<llvm::Value *, llvm::Value *>( 314 CodeGenFunction &, const OMPExecutableDirective &S, Address LB, 315 Address UB)> 316 CodeGenDispatchBoundsTy; 317 318 /// CGBuilder insert helper. This function is called after an 319 /// instruction is created using Builder. 320 void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, 321 llvm::BasicBlock *BB, 322 llvm::BasicBlock::iterator InsertPt) const; 323 324 /// CurFuncDecl - Holds the Decl for the current outermost 325 /// non-closure context. 326 const Decl *CurFuncDecl; 327 /// CurCodeDecl - This is the inner-most code context, which includes blocks. 328 const Decl *CurCodeDecl; 329 const CGFunctionInfo *CurFnInfo; 330 QualType FnRetTy; 331 llvm::Function *CurFn = nullptr; 332 333 /// Save Parameter Decl for coroutine. 334 llvm::SmallVector<const ParmVarDecl *, 4> FnArgs; 335 336 // Holds coroutine data if the current function is a coroutine. We use a 337 // wrapper to manage its lifetime, so that we don't have to define CGCoroData 338 // in this header. 339 struct CGCoroInfo { 340 std::unique_ptr<CGCoroData> Data; 341 CGCoroInfo(); 342 ~CGCoroInfo(); 343 }; 344 CGCoroInfo CurCoro; 345 346 bool isCoroutine() const { 347 return CurCoro.Data != nullptr; 348 } 349 350 /// CurGD - The GlobalDecl for the current function being compiled. 351 GlobalDecl CurGD; 352 353 /// PrologueCleanupDepth - The cleanup depth enclosing all the 354 /// cleanups associated with the parameters. 355 EHScopeStack::stable_iterator PrologueCleanupDepth; 356 357 /// ReturnBlock - Unified return block. 358 JumpDest ReturnBlock; 359 360 /// ReturnValue - The temporary alloca to hold the return 361 /// value. This is invalid iff the function has no return value. 362 Address ReturnValue = Address::invalid(); 363 364 /// ReturnValuePointer - The temporary alloca to hold a pointer to sret. 365 /// This is invalid if sret is not in use. 366 Address ReturnValuePointer = Address::invalid(); 367 368 /// If a return statement is being visited, this holds the return statment's 369 /// result expression. 370 const Expr *RetExpr = nullptr; 371 372 /// Return true if a label was seen in the current scope. 373 bool hasLabelBeenSeenInCurrentScope() const { 374 if (CurLexicalScope) 375 return CurLexicalScope->hasLabels(); 376 return !LabelMap.empty(); 377 } 378 379 /// AllocaInsertPoint - This is an instruction in the entry block before which 380 /// we prefer to insert allocas. 381 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt; 382 383 private: 384 /// PostAllocaInsertPt - This is a place in the prologue where code can be 385 /// inserted that will be dominated by all the static allocas. This helps 386 /// achieve two things: 387 /// 1. Contiguity of all static allocas (within the prologue) is maintained. 388 /// 2. All other prologue code (which are dominated by static allocas) do 389 /// appear in the source order immediately after all static allocas. 390 /// 391 /// PostAllocaInsertPt will be lazily created when it is *really* required. 392 llvm::AssertingVH<llvm::Instruction> PostAllocaInsertPt = nullptr; 393 394 public: 395 /// Return PostAllocaInsertPt. If it is not yet created, then insert it 396 /// immediately after AllocaInsertPt. 397 llvm::Instruction *getPostAllocaInsertPoint() { 398 if (!PostAllocaInsertPt) { 399 assert(AllocaInsertPt && 400 "Expected static alloca insertion point at function prologue"); 401 assert(AllocaInsertPt->getParent()->isEntryBlock() && 402 "EBB should be entry block of the current code gen function"); 403 PostAllocaInsertPt = AllocaInsertPt->clone(); 404 PostAllocaInsertPt->setName("postallocapt"); 405 PostAllocaInsertPt->insertAfter(AllocaInsertPt); 406 } 407 408 return PostAllocaInsertPt; 409 } 410 411 /// API for captured statement code generation. 412 class CGCapturedStmtInfo { 413 public: 414 explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default) 415 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {} 416 explicit CGCapturedStmtInfo(const CapturedStmt &S, 417 CapturedRegionKind K = CR_Default) 418 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) { 419 420 RecordDecl::field_iterator Field = 421 S.getCapturedRecordDecl()->field_begin(); 422 for (CapturedStmt::const_capture_iterator I = S.capture_begin(), 423 E = S.capture_end(); 424 I != E; ++I, ++Field) { 425 if (I->capturesThis()) 426 CXXThisFieldDecl = *Field; 427 else if (I->capturesVariable()) 428 CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field; 429 else if (I->capturesVariableByCopy()) 430 CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field; 431 } 432 } 433 434 virtual ~CGCapturedStmtInfo(); 435 436 CapturedRegionKind getKind() const { return Kind; } 437 438 virtual void setContextValue(llvm::Value *V) { ThisValue = V; } 439 // Retrieve the value of the context parameter. 440 virtual llvm::Value *getContextValue() const { return ThisValue; } 441 442 /// Lookup the captured field decl for a variable. 443 virtual const FieldDecl *lookup(const VarDecl *VD) const { 444 return CaptureFields.lookup(VD->getCanonicalDecl()); 445 } 446 447 bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; } 448 virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; } 449 450 static bool classof(const CGCapturedStmtInfo *) { 451 return true; 452 } 453 454 /// Emit the captured statement body. 455 virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) { 456 CGF.incrementProfileCounter(S); 457 CGF.EmitStmt(S); 458 } 459 460 /// Get the name of the capture helper. 461 virtual StringRef getHelperName() const { return "__captured_stmt"; } 462 463 /// Get the CaptureFields 464 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> getCaptureFields() { 465 return CaptureFields; 466 } 467 468 private: 469 /// The kind of captured statement being generated. 470 CapturedRegionKind Kind; 471 472 /// Keep the map between VarDecl and FieldDecl. 473 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields; 474 475 /// The base address of the captured record, passed in as the first 476 /// argument of the parallel region function. 477 llvm::Value *ThisValue; 478 479 /// Captured 'this' type. 480 FieldDecl *CXXThisFieldDecl; 481 }; 482 CGCapturedStmtInfo *CapturedStmtInfo = nullptr; 483 484 /// RAII for correct setting/restoring of CapturedStmtInfo. 485 class CGCapturedStmtRAII { 486 private: 487 CodeGenFunction &CGF; 488 CGCapturedStmtInfo *PrevCapturedStmtInfo; 489 public: 490 CGCapturedStmtRAII(CodeGenFunction &CGF, 491 CGCapturedStmtInfo *NewCapturedStmtInfo) 492 : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) { 493 CGF.CapturedStmtInfo = NewCapturedStmtInfo; 494 } 495 ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; } 496 }; 497 498 /// An abstract representation of regular/ObjC call/message targets. 499 class AbstractCallee { 500 /// The function declaration of the callee. 501 const Decl *CalleeDecl; 502 503 public: 504 AbstractCallee() : CalleeDecl(nullptr) {} 505 AbstractCallee(const FunctionDecl *FD) : CalleeDecl(FD) {} 506 AbstractCallee(const ObjCMethodDecl *OMD) : CalleeDecl(OMD) {} 507 bool hasFunctionDecl() const { 508 return isa_and_nonnull<FunctionDecl>(CalleeDecl); 509 } 510 const Decl *getDecl() const { return CalleeDecl; } 511 unsigned getNumParams() const { 512 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl)) 513 return FD->getNumParams(); 514 return cast<ObjCMethodDecl>(CalleeDecl)->param_size(); 515 } 516 const ParmVarDecl *getParamDecl(unsigned I) const { 517 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl)) 518 return FD->getParamDecl(I); 519 return *(cast<ObjCMethodDecl>(CalleeDecl)->param_begin() + I); 520 } 521 }; 522 523 /// Sanitizers enabled for this function. 524 SanitizerSet SanOpts; 525 526 /// True if CodeGen currently emits code implementing sanitizer checks. 527 bool IsSanitizerScope = false; 528 529 /// RAII object to set/unset CodeGenFunction::IsSanitizerScope. 530 class SanitizerScope { 531 CodeGenFunction *CGF; 532 public: 533 SanitizerScope(CodeGenFunction *CGF); 534 ~SanitizerScope(); 535 }; 536 537 /// In C++, whether we are code generating a thunk. This controls whether we 538 /// should emit cleanups. 539 bool CurFuncIsThunk = false; 540 541 /// In ARC, whether we should autorelease the return value. 542 bool AutoreleaseResult = false; 543 544 /// Whether we processed a Microsoft-style asm block during CodeGen. These can 545 /// potentially set the return value. 546 bool SawAsmBlock = false; 547 548 const NamedDecl *CurSEHParent = nullptr; 549 550 /// True if the current function is an outlined SEH helper. This can be a 551 /// finally block or filter expression. 552 bool IsOutlinedSEHHelper = false; 553 554 /// True if CodeGen currently emits code inside presereved access index 555 /// region. 556 bool IsInPreservedAIRegion = false; 557 558 /// True if the current statement has nomerge attribute. 559 bool InNoMergeAttributedStmt = false; 560 561 // The CallExpr within the current statement that the musttail attribute 562 // applies to. nullptr if there is no 'musttail' on the current statement. 563 const CallExpr *MustTailCall = nullptr; 564 565 /// Returns true if a function must make progress, which means the 566 /// mustprogress attribute can be added. 567 bool checkIfFunctionMustProgress() { 568 if (CGM.getCodeGenOpts().getFiniteLoops() == 569 CodeGenOptions::FiniteLoopsKind::Never) 570 return false; 571 572 // C++11 and later guarantees that a thread eventually will do one of the 573 // following (6.9.2.3.1 in C++11): 574 // - terminate, 575 // - make a call to a library I/O function, 576 // - perform an access through a volatile glvalue, or 577 // - perform a synchronization operation or an atomic operation. 578 // 579 // Hence each function is 'mustprogress' in C++11 or later. 580 return getLangOpts().CPlusPlus11; 581 } 582 583 /// Returns true if a loop must make progress, which means the mustprogress 584 /// attribute can be added. \p HasConstantCond indicates whether the branch 585 /// condition is a known constant. 586 bool checkIfLoopMustProgress(bool HasConstantCond) { 587 if (CGM.getCodeGenOpts().getFiniteLoops() == 588 CodeGenOptions::FiniteLoopsKind::Always) 589 return true; 590 if (CGM.getCodeGenOpts().getFiniteLoops() == 591 CodeGenOptions::FiniteLoopsKind::Never) 592 return false; 593 594 // If the containing function must make progress, loops also must make 595 // progress (as in C++11 and later). 596 if (checkIfFunctionMustProgress()) 597 return true; 598 599 // Now apply rules for plain C (see 6.8.5.6 in C11). 600 // Loops with constant conditions do not have to make progress in any C 601 // version. 602 if (HasConstantCond) 603 return false; 604 605 // Loops with non-constant conditions must make progress in C11 and later. 606 return getLangOpts().C11; 607 } 608 609 const CodeGen::CGBlockInfo *BlockInfo = nullptr; 610 llvm::Value *BlockPointer = nullptr; 611 612 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 613 FieldDecl *LambdaThisCaptureField = nullptr; 614 615 /// A mapping from NRVO variables to the flags used to indicate 616 /// when the NRVO has been applied to this variable. 617 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags; 618 619 EHScopeStack EHStack; 620 llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack; 621 llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack; 622 623 llvm::Instruction *CurrentFuncletPad = nullptr; 624 625 class CallLifetimeEnd final : public EHScopeStack::Cleanup { 626 bool isRedundantBeforeReturn() override { return true; } 627 628 llvm::Value *Addr; 629 llvm::Value *Size; 630 631 public: 632 CallLifetimeEnd(Address addr, llvm::Value *size) 633 : Addr(addr.getPointer()), Size(size) {} 634 635 void Emit(CodeGenFunction &CGF, Flags flags) override { 636 CGF.EmitLifetimeEnd(Size, Addr); 637 } 638 }; 639 640 /// Header for data within LifetimeExtendedCleanupStack. 641 struct LifetimeExtendedCleanupHeader { 642 /// The size of the following cleanup object. 643 unsigned Size; 644 /// The kind of cleanup to push: a value from the CleanupKind enumeration. 645 unsigned Kind : 31; 646 /// Whether this is a conditional cleanup. 647 unsigned IsConditional : 1; 648 649 size_t getSize() const { return Size; } 650 CleanupKind getKind() const { return (CleanupKind)Kind; } 651 bool isConditional() const { return IsConditional; } 652 }; 653 654 /// i32s containing the indexes of the cleanup destinations. 655 Address NormalCleanupDest = Address::invalid(); 656 657 unsigned NextCleanupDestIndex = 1; 658 659 /// EHResumeBlock - Unified block containing a call to llvm.eh.resume. 660 llvm::BasicBlock *EHResumeBlock = nullptr; 661 662 /// The exception slot. All landing pads write the current exception pointer 663 /// into this alloca. 664 llvm::Value *ExceptionSlot = nullptr; 665 666 /// The selector slot. Under the MandatoryCleanup model, all landing pads 667 /// write the current selector value into this alloca. 668 llvm::AllocaInst *EHSelectorSlot = nullptr; 669 670 /// A stack of exception code slots. Entering an __except block pushes a slot 671 /// on the stack and leaving pops one. The __exception_code() intrinsic loads 672 /// a value from the top of the stack. 673 SmallVector<Address, 1> SEHCodeSlotStack; 674 675 /// Value returned by __exception_info intrinsic. 676 llvm::Value *SEHInfo = nullptr; 677 678 /// Emits a landing pad for the current EH stack. 679 llvm::BasicBlock *EmitLandingPad(); 680 681 llvm::BasicBlock *getInvokeDestImpl(); 682 683 /// Parent loop-based directive for scan directive. 684 const OMPExecutableDirective *OMPParentLoopDirectiveForScan = nullptr; 685 llvm::BasicBlock *OMPBeforeScanBlock = nullptr; 686 llvm::BasicBlock *OMPAfterScanBlock = nullptr; 687 llvm::BasicBlock *OMPScanExitBlock = nullptr; 688 llvm::BasicBlock *OMPScanDispatch = nullptr; 689 bool OMPFirstScanLoop = false; 690 691 /// Manages parent directive for scan directives. 692 class ParentLoopDirectiveForScanRegion { 693 CodeGenFunction &CGF; 694 const OMPExecutableDirective *ParentLoopDirectiveForScan; 695 696 public: 697 ParentLoopDirectiveForScanRegion( 698 CodeGenFunction &CGF, 699 const OMPExecutableDirective &ParentLoopDirectiveForScan) 700 : CGF(CGF), 701 ParentLoopDirectiveForScan(CGF.OMPParentLoopDirectiveForScan) { 702 CGF.OMPParentLoopDirectiveForScan = &ParentLoopDirectiveForScan; 703 } 704 ~ParentLoopDirectiveForScanRegion() { 705 CGF.OMPParentLoopDirectiveForScan = ParentLoopDirectiveForScan; 706 } 707 }; 708 709 template <class T> 710 typename DominatingValue<T>::saved_type saveValueInCond(T value) { 711 return DominatingValue<T>::save(*this, value); 712 } 713 714 class CGFPOptionsRAII { 715 public: 716 CGFPOptionsRAII(CodeGenFunction &CGF, FPOptions FPFeatures); 717 CGFPOptionsRAII(CodeGenFunction &CGF, const Expr *E); 718 ~CGFPOptionsRAII(); 719 720 private: 721 void ConstructorHelper(FPOptions FPFeatures); 722 CodeGenFunction &CGF; 723 FPOptions OldFPFeatures; 724 llvm::fp::ExceptionBehavior OldExcept; 725 llvm::RoundingMode OldRounding; 726 Optional<CGBuilderTy::FastMathFlagGuard> FMFGuard; 727 }; 728 FPOptions CurFPFeatures; 729 730 public: 731 /// ObjCEHValueStack - Stack of Objective-C exception values, used for 732 /// rethrows. 733 SmallVector<llvm::Value*, 8> ObjCEHValueStack; 734 735 /// A class controlling the emission of a finally block. 736 class FinallyInfo { 737 /// Where the catchall's edge through the cleanup should go. 738 JumpDest RethrowDest; 739 740 /// A function to call to enter the catch. 741 llvm::FunctionCallee BeginCatchFn; 742 743 /// An i1 variable indicating whether or not the @finally is 744 /// running for an exception. 745 llvm::AllocaInst *ForEHVar; 746 747 /// An i8* variable into which the exception pointer to rethrow 748 /// has been saved. 749 llvm::AllocaInst *SavedExnVar; 750 751 public: 752 void enter(CodeGenFunction &CGF, const Stmt *Finally, 753 llvm::FunctionCallee beginCatchFn, 754 llvm::FunctionCallee endCatchFn, llvm::FunctionCallee rethrowFn); 755 void exit(CodeGenFunction &CGF); 756 }; 757 758 /// Returns true inside SEH __try blocks. 759 bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); } 760 761 /// Returns true while emitting a cleanuppad. 762 bool isCleanupPadScope() const { 763 return CurrentFuncletPad && isa<llvm::CleanupPadInst>(CurrentFuncletPad); 764 } 765 766 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 767 /// current full-expression. Safe against the possibility that 768 /// we're currently inside a conditionally-evaluated expression. 769 template <class T, class... As> 770 void pushFullExprCleanup(CleanupKind kind, As... A) { 771 // If we're not in a conditional branch, or if none of the 772 // arguments requires saving, then use the unconditional cleanup. 773 if (!isInConditionalBranch()) 774 return EHStack.pushCleanup<T>(kind, A...); 775 776 // Stash values in a tuple so we can guarantee the order of saves. 777 typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple; 778 SavedTuple Saved{saveValueInCond(A)...}; 779 780 typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType; 781 EHStack.pushCleanupTuple<CleanupType>(kind, Saved); 782 initFullExprCleanup(); 783 } 784 785 /// Queue a cleanup to be pushed after finishing the current full-expression, 786 /// potentially with an active flag. 787 template <class T, class... As> 788 void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) { 789 if (!isInConditionalBranch()) 790 return pushCleanupAfterFullExprWithActiveFlag<T>(Kind, Address::invalid(), 791 A...); 792 793 Address ActiveFlag = createCleanupActiveFlag(); 794 assert(!DominatingValue<Address>::needsSaving(ActiveFlag) && 795 "cleanup active flag should never need saving"); 796 797 typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple; 798 SavedTuple Saved{saveValueInCond(A)...}; 799 800 typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType; 801 pushCleanupAfterFullExprWithActiveFlag<CleanupType>(Kind, ActiveFlag, Saved); 802 } 803 804 template <class T, class... As> 805 void pushCleanupAfterFullExprWithActiveFlag(CleanupKind Kind, 806 Address ActiveFlag, As... A) { 807 LifetimeExtendedCleanupHeader Header = {sizeof(T), Kind, 808 ActiveFlag.isValid()}; 809 810 size_t OldSize = LifetimeExtendedCleanupStack.size(); 811 LifetimeExtendedCleanupStack.resize( 812 LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size + 813 (Header.IsConditional ? sizeof(ActiveFlag) : 0)); 814 815 static_assert(sizeof(Header) % alignof(T) == 0, 816 "Cleanup will be allocated on misaligned address"); 817 char *Buffer = &LifetimeExtendedCleanupStack[OldSize]; 818 new (Buffer) LifetimeExtendedCleanupHeader(Header); 819 new (Buffer + sizeof(Header)) T(A...); 820 if (Header.IsConditional) 821 new (Buffer + sizeof(Header) + sizeof(T)) Address(ActiveFlag); 822 } 823 824 /// Set up the last cleanup that was pushed as a conditional 825 /// full-expression cleanup. 826 void initFullExprCleanup() { 827 initFullExprCleanupWithFlag(createCleanupActiveFlag()); 828 } 829 830 void initFullExprCleanupWithFlag(Address ActiveFlag); 831 Address createCleanupActiveFlag(); 832 833 /// PushDestructorCleanup - Push a cleanup to call the 834 /// complete-object destructor of an object of the given type at the 835 /// given address. Does nothing if T is not a C++ class type with a 836 /// non-trivial destructor. 837 void PushDestructorCleanup(QualType T, Address Addr); 838 839 /// PushDestructorCleanup - Push a cleanup to call the 840 /// complete-object variant of the given destructor on the object at 841 /// the given address. 842 void PushDestructorCleanup(const CXXDestructorDecl *Dtor, QualType T, 843 Address Addr); 844 845 /// PopCleanupBlock - Will pop the cleanup entry on the stack and 846 /// process all branch fixups. 847 void PopCleanupBlock(bool FallThroughIsBranchThrough = false); 848 849 /// DeactivateCleanupBlock - Deactivates the given cleanup block. 850 /// The block cannot be reactivated. Pops it if it's the top of the 851 /// stack. 852 /// 853 /// \param DominatingIP - An instruction which is known to 854 /// dominate the current IP (if set) and which lies along 855 /// all paths of execution between the current IP and the 856 /// the point at which the cleanup comes into scope. 857 void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, 858 llvm::Instruction *DominatingIP); 859 860 /// ActivateCleanupBlock - Activates an initially-inactive cleanup. 861 /// Cannot be used to resurrect a deactivated cleanup. 862 /// 863 /// \param DominatingIP - An instruction which is known to 864 /// dominate the current IP (if set) and which lies along 865 /// all paths of execution between the current IP and the 866 /// the point at which the cleanup comes into scope. 867 void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, 868 llvm::Instruction *DominatingIP); 869 870 /// Enters a new scope for capturing cleanups, all of which 871 /// will be executed once the scope is exited. 872 class RunCleanupsScope { 873 EHScopeStack::stable_iterator CleanupStackDepth, OldCleanupScopeDepth; 874 size_t LifetimeExtendedCleanupStackSize; 875 bool OldDidCallStackSave; 876 protected: 877 bool PerformCleanup; 878 private: 879 880 RunCleanupsScope(const RunCleanupsScope &) = delete; 881 void operator=(const RunCleanupsScope &) = delete; 882 883 protected: 884 CodeGenFunction& CGF; 885 886 public: 887 /// Enter a new cleanup scope. 888 explicit RunCleanupsScope(CodeGenFunction &CGF) 889 : PerformCleanup(true), CGF(CGF) 890 { 891 CleanupStackDepth = CGF.EHStack.stable_begin(); 892 LifetimeExtendedCleanupStackSize = 893 CGF.LifetimeExtendedCleanupStack.size(); 894 OldDidCallStackSave = CGF.DidCallStackSave; 895 CGF.DidCallStackSave = false; 896 OldCleanupScopeDepth = CGF.CurrentCleanupScopeDepth; 897 CGF.CurrentCleanupScopeDepth = CleanupStackDepth; 898 } 899 900 /// Exit this cleanup scope, emitting any accumulated cleanups. 901 ~RunCleanupsScope() { 902 if (PerformCleanup) 903 ForceCleanup(); 904 } 905 906 /// Determine whether this scope requires any cleanups. 907 bool requiresCleanups() const { 908 return CGF.EHStack.stable_begin() != CleanupStackDepth; 909 } 910 911 /// Force the emission of cleanups now, instead of waiting 912 /// until this object is destroyed. 913 /// \param ValuesToReload - A list of values that need to be available at 914 /// the insertion point after cleanup emission. If cleanup emission created 915 /// a shared cleanup block, these value pointers will be rewritten. 916 /// Otherwise, they not will be modified. 917 void ForceCleanup(std::initializer_list<llvm::Value**> ValuesToReload = {}) { 918 assert(PerformCleanup && "Already forced cleanup"); 919 CGF.DidCallStackSave = OldDidCallStackSave; 920 CGF.PopCleanupBlocks(CleanupStackDepth, LifetimeExtendedCleanupStackSize, 921 ValuesToReload); 922 PerformCleanup = false; 923 CGF.CurrentCleanupScopeDepth = OldCleanupScopeDepth; 924 } 925 }; 926 927 // Cleanup stack depth of the RunCleanupsScope that was pushed most recently. 928 EHScopeStack::stable_iterator CurrentCleanupScopeDepth = 929 EHScopeStack::stable_end(); 930 931 class LexicalScope : public RunCleanupsScope { 932 SourceRange Range; 933 SmallVector<const LabelDecl*, 4> Labels; 934 LexicalScope *ParentScope; 935 936 LexicalScope(const LexicalScope &) = delete; 937 void operator=(const LexicalScope &) = delete; 938 939 public: 940 /// Enter a new cleanup scope. 941 explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range) 942 : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) { 943 CGF.CurLexicalScope = this; 944 if (CGDebugInfo *DI = CGF.getDebugInfo()) 945 DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin()); 946 } 947 948 void addLabel(const LabelDecl *label) { 949 assert(PerformCleanup && "adding label to dead scope?"); 950 Labels.push_back(label); 951 } 952 953 /// Exit this cleanup scope, emitting any accumulated 954 /// cleanups. 955 ~LexicalScope() { 956 if (CGDebugInfo *DI = CGF.getDebugInfo()) 957 DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd()); 958 959 // If we should perform a cleanup, force them now. Note that 960 // this ends the cleanup scope before rescoping any labels. 961 if (PerformCleanup) { 962 ApplyDebugLocation DL(CGF, Range.getEnd()); 963 ForceCleanup(); 964 } 965 } 966 967 /// Force the emission of cleanups now, instead of waiting 968 /// until this object is destroyed. 969 void ForceCleanup() { 970 CGF.CurLexicalScope = ParentScope; 971 RunCleanupsScope::ForceCleanup(); 972 973 if (!Labels.empty()) 974 rescopeLabels(); 975 } 976 977 bool hasLabels() const { 978 return !Labels.empty(); 979 } 980 981 void rescopeLabels(); 982 }; 983 984 typedef llvm::DenseMap<const Decl *, Address> DeclMapTy; 985 986 /// The class used to assign some variables some temporarily addresses. 987 class OMPMapVars { 988 DeclMapTy SavedLocals; 989 DeclMapTy SavedTempAddresses; 990 OMPMapVars(const OMPMapVars &) = delete; 991 void operator=(const OMPMapVars &) = delete; 992 993 public: 994 explicit OMPMapVars() = default; 995 ~OMPMapVars() { 996 assert(SavedLocals.empty() && "Did not restored original addresses."); 997 }; 998 999 /// Sets the address of the variable \p LocalVD to be \p TempAddr in 1000 /// function \p CGF. 1001 /// \return true if at least one variable was set already, false otherwise. 1002 bool setVarAddr(CodeGenFunction &CGF, const VarDecl *LocalVD, 1003 Address TempAddr) { 1004 LocalVD = LocalVD->getCanonicalDecl(); 1005 // Only save it once. 1006 if (SavedLocals.count(LocalVD)) return false; 1007 1008 // Copy the existing local entry to SavedLocals. 1009 auto it = CGF.LocalDeclMap.find(LocalVD); 1010 if (it != CGF.LocalDeclMap.end()) 1011 SavedLocals.try_emplace(LocalVD, it->second); 1012 else 1013 SavedLocals.try_emplace(LocalVD, Address::invalid()); 1014 1015 // Generate the private entry. 1016 QualType VarTy = LocalVD->getType(); 1017 if (VarTy->isReferenceType()) { 1018 Address Temp = CGF.CreateMemTemp(VarTy); 1019 CGF.Builder.CreateStore(TempAddr.getPointer(), Temp); 1020 TempAddr = Temp; 1021 } 1022 SavedTempAddresses.try_emplace(LocalVD, TempAddr); 1023 1024 return true; 1025 } 1026 1027 /// Applies new addresses to the list of the variables. 1028 /// \return true if at least one variable is using new address, false 1029 /// otherwise. 1030 bool apply(CodeGenFunction &CGF) { 1031 copyInto(SavedTempAddresses, CGF.LocalDeclMap); 1032 SavedTempAddresses.clear(); 1033 return !SavedLocals.empty(); 1034 } 1035 1036 /// Restores original addresses of the variables. 1037 void restore(CodeGenFunction &CGF) { 1038 if (!SavedLocals.empty()) { 1039 copyInto(SavedLocals, CGF.LocalDeclMap); 1040 SavedLocals.clear(); 1041 } 1042 } 1043 1044 private: 1045 /// Copy all the entries in the source map over the corresponding 1046 /// entries in the destination, which must exist. 1047 static void copyInto(const DeclMapTy &Src, DeclMapTy &Dest) { 1048 for (auto &Pair : Src) { 1049 if (!Pair.second.isValid()) { 1050 Dest.erase(Pair.first); 1051 continue; 1052 } 1053 1054 auto I = Dest.find(Pair.first); 1055 if (I != Dest.end()) 1056 I->second = Pair.second; 1057 else 1058 Dest.insert(Pair); 1059 } 1060 } 1061 }; 1062 1063 /// The scope used to remap some variables as private in the OpenMP loop body 1064 /// (or other captured region emitted without outlining), and to restore old 1065 /// vars back on exit. 1066 class OMPPrivateScope : public RunCleanupsScope { 1067 OMPMapVars MappedVars; 1068 OMPPrivateScope(const OMPPrivateScope &) = delete; 1069 void operator=(const OMPPrivateScope &) = delete; 1070 1071 public: 1072 /// Enter a new OpenMP private scope. 1073 explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {} 1074 1075 /// Registers \p LocalVD variable as a private and apply \p PrivateGen 1076 /// function for it to generate corresponding private variable. \p 1077 /// PrivateGen returns an address of the generated private variable. 1078 /// \return true if the variable is registered as private, false if it has 1079 /// been privatized already. 1080 bool addPrivate(const VarDecl *LocalVD, 1081 const llvm::function_ref<Address()> PrivateGen) { 1082 assert(PerformCleanup && "adding private to dead scope"); 1083 return MappedVars.setVarAddr(CGF, LocalVD, PrivateGen()); 1084 } 1085 1086 /// Privatizes local variables previously registered as private. 1087 /// Registration is separate from the actual privatization to allow 1088 /// initializers use values of the original variables, not the private one. 1089 /// This is important, for example, if the private variable is a class 1090 /// variable initialized by a constructor that references other private 1091 /// variables. But at initialization original variables must be used, not 1092 /// private copies. 1093 /// \return true if at least one variable was privatized, false otherwise. 1094 bool Privatize() { return MappedVars.apply(CGF); } 1095 1096 void ForceCleanup() { 1097 RunCleanupsScope::ForceCleanup(); 1098 MappedVars.restore(CGF); 1099 } 1100 1101 /// Exit scope - all the mapped variables are restored. 1102 ~OMPPrivateScope() { 1103 if (PerformCleanup) 1104 ForceCleanup(); 1105 } 1106 1107 /// Checks if the global variable is captured in current function. 1108 bool isGlobalVarCaptured(const VarDecl *VD) const { 1109 VD = VD->getCanonicalDecl(); 1110 return !VD->isLocalVarDeclOrParm() && CGF.LocalDeclMap.count(VD) > 0; 1111 } 1112 }; 1113 1114 /// Save/restore original map of previously emitted local vars in case when we 1115 /// need to duplicate emission of the same code several times in the same 1116 /// function for OpenMP code. 1117 class OMPLocalDeclMapRAII { 1118 CodeGenFunction &CGF; 1119 DeclMapTy SavedMap; 1120 1121 public: 1122 OMPLocalDeclMapRAII(CodeGenFunction &CGF) 1123 : CGF(CGF), SavedMap(CGF.LocalDeclMap) {} 1124 ~OMPLocalDeclMapRAII() { SavedMap.swap(CGF.LocalDeclMap); } 1125 }; 1126 1127 /// Takes the old cleanup stack size and emits the cleanup blocks 1128 /// that have been added. 1129 void 1130 PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize, 1131 std::initializer_list<llvm::Value **> ValuesToReload = {}); 1132 1133 /// Takes the old cleanup stack size and emits the cleanup blocks 1134 /// that have been added, then adds all lifetime-extended cleanups from 1135 /// the given position to the stack. 1136 void 1137 PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize, 1138 size_t OldLifetimeExtendedStackSize, 1139 std::initializer_list<llvm::Value **> ValuesToReload = {}); 1140 1141 void ResolveBranchFixups(llvm::BasicBlock *Target); 1142 1143 /// The given basic block lies in the current EH scope, but may be a 1144 /// target of a potentially scope-crossing jump; get a stable handle 1145 /// to which we can perform this jump later. 1146 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) { 1147 return JumpDest(Target, 1148 EHStack.getInnermostNormalCleanup(), 1149 NextCleanupDestIndex++); 1150 } 1151 1152 /// The given basic block lies in the current EH scope, but may be a 1153 /// target of a potentially scope-crossing jump; get a stable handle 1154 /// to which we can perform this jump later. 1155 JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) { 1156 return getJumpDestInCurrentScope(createBasicBlock(Name)); 1157 } 1158 1159 /// EmitBranchThroughCleanup - Emit a branch from the current insert 1160 /// block through the normal cleanup handling code (if any) and then 1161 /// on to \arg Dest. 1162 void EmitBranchThroughCleanup(JumpDest Dest); 1163 1164 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the 1165 /// specified destination obviously has no cleanups to run. 'false' is always 1166 /// a conservatively correct answer for this method. 1167 bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const; 1168 1169 /// popCatchScope - Pops the catch scope at the top of the EHScope 1170 /// stack, emitting any required code (other than the catch handlers 1171 /// themselves). 1172 void popCatchScope(); 1173 1174 llvm::BasicBlock *getEHResumeBlock(bool isCleanup); 1175 llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope); 1176 llvm::BasicBlock * 1177 getFuncletEHDispatchBlock(EHScopeStack::stable_iterator scope); 1178 1179 /// An object to manage conditionally-evaluated expressions. 1180 class ConditionalEvaluation { 1181 llvm::BasicBlock *StartBB; 1182 1183 public: 1184 ConditionalEvaluation(CodeGenFunction &CGF) 1185 : StartBB(CGF.Builder.GetInsertBlock()) {} 1186 1187 void begin(CodeGenFunction &CGF) { 1188 assert(CGF.OutermostConditional != this); 1189 if (!CGF.OutermostConditional) 1190 CGF.OutermostConditional = this; 1191 } 1192 1193 void end(CodeGenFunction &CGF) { 1194 assert(CGF.OutermostConditional != nullptr); 1195 if (CGF.OutermostConditional == this) 1196 CGF.OutermostConditional = nullptr; 1197 } 1198 1199 /// Returns a block which will be executed prior to each 1200 /// evaluation of the conditional code. 1201 llvm::BasicBlock *getStartingBlock() const { 1202 return StartBB; 1203 } 1204 }; 1205 1206 /// isInConditionalBranch - Return true if we're currently emitting 1207 /// one branch or the other of a conditional expression. 1208 bool isInConditionalBranch() const { return OutermostConditional != nullptr; } 1209 1210 void setBeforeOutermostConditional(llvm::Value *value, Address addr) { 1211 assert(isInConditionalBranch()); 1212 llvm::BasicBlock *block = OutermostConditional->getStartingBlock(); 1213 auto store = new llvm::StoreInst(value, addr.getPointer(), &block->back()); 1214 store->setAlignment(addr.getAlignment().getAsAlign()); 1215 } 1216 1217 /// An RAII object to record that we're evaluating a statement 1218 /// expression. 1219 class StmtExprEvaluation { 1220 CodeGenFunction &CGF; 1221 1222 /// We have to save the outermost conditional: cleanups in a 1223 /// statement expression aren't conditional just because the 1224 /// StmtExpr is. 1225 ConditionalEvaluation *SavedOutermostConditional; 1226 1227 public: 1228 StmtExprEvaluation(CodeGenFunction &CGF) 1229 : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) { 1230 CGF.OutermostConditional = nullptr; 1231 } 1232 1233 ~StmtExprEvaluation() { 1234 CGF.OutermostConditional = SavedOutermostConditional; 1235 CGF.EnsureInsertPoint(); 1236 } 1237 }; 1238 1239 /// An object which temporarily prevents a value from being 1240 /// destroyed by aggressive peephole optimizations that assume that 1241 /// all uses of a value have been realized in the IR. 1242 class PeepholeProtection { 1243 llvm::Instruction *Inst; 1244 friend class CodeGenFunction; 1245 1246 public: 1247 PeepholeProtection() : Inst(nullptr) {} 1248 }; 1249 1250 /// A non-RAII class containing all the information about a bound 1251 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for 1252 /// this which makes individual mappings very simple; using this 1253 /// class directly is useful when you have a variable number of 1254 /// opaque values or don't want the RAII functionality for some 1255 /// reason. 1256 class OpaqueValueMappingData { 1257 const OpaqueValueExpr *OpaqueValue; 1258 bool BoundLValue; 1259 CodeGenFunction::PeepholeProtection Protection; 1260 1261 OpaqueValueMappingData(const OpaqueValueExpr *ov, 1262 bool boundLValue) 1263 : OpaqueValue(ov), BoundLValue(boundLValue) {} 1264 public: 1265 OpaqueValueMappingData() : OpaqueValue(nullptr) {} 1266 1267 static bool shouldBindAsLValue(const Expr *expr) { 1268 // gl-values should be bound as l-values for obvious reasons. 1269 // Records should be bound as l-values because IR generation 1270 // always keeps them in memory. Expressions of function type 1271 // act exactly like l-values but are formally required to be 1272 // r-values in C. 1273 return expr->isGLValue() || 1274 expr->getType()->isFunctionType() || 1275 hasAggregateEvaluationKind(expr->getType()); 1276 } 1277 1278 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 1279 const OpaqueValueExpr *ov, 1280 const Expr *e) { 1281 if (shouldBindAsLValue(ov)) 1282 return bind(CGF, ov, CGF.EmitLValue(e)); 1283 return bind(CGF, ov, CGF.EmitAnyExpr(e)); 1284 } 1285 1286 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 1287 const OpaqueValueExpr *ov, 1288 const LValue &lv) { 1289 assert(shouldBindAsLValue(ov)); 1290 CGF.OpaqueLValues.insert(std::make_pair(ov, lv)); 1291 return OpaqueValueMappingData(ov, true); 1292 } 1293 1294 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 1295 const OpaqueValueExpr *ov, 1296 const RValue &rv) { 1297 assert(!shouldBindAsLValue(ov)); 1298 CGF.OpaqueRValues.insert(std::make_pair(ov, rv)); 1299 1300 OpaqueValueMappingData data(ov, false); 1301 1302 // Work around an extremely aggressive peephole optimization in 1303 // EmitScalarConversion which assumes that all other uses of a 1304 // value are extant. 1305 data.Protection = CGF.protectFromPeepholes(rv); 1306 1307 return data; 1308 } 1309 1310 bool isValid() const { return OpaqueValue != nullptr; } 1311 void clear() { OpaqueValue = nullptr; } 1312 1313 void unbind(CodeGenFunction &CGF) { 1314 assert(OpaqueValue && "no data to unbind!"); 1315 1316 if (BoundLValue) { 1317 CGF.OpaqueLValues.erase(OpaqueValue); 1318 } else { 1319 CGF.OpaqueRValues.erase(OpaqueValue); 1320 CGF.unprotectFromPeepholes(Protection); 1321 } 1322 } 1323 }; 1324 1325 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr. 1326 class OpaqueValueMapping { 1327 CodeGenFunction &CGF; 1328 OpaqueValueMappingData Data; 1329 1330 public: 1331 static bool shouldBindAsLValue(const Expr *expr) { 1332 return OpaqueValueMappingData::shouldBindAsLValue(expr); 1333 } 1334 1335 /// Build the opaque value mapping for the given conditional 1336 /// operator if it's the GNU ?: extension. This is a common 1337 /// enough pattern that the convenience operator is really 1338 /// helpful. 1339 /// 1340 OpaqueValueMapping(CodeGenFunction &CGF, 1341 const AbstractConditionalOperator *op) : CGF(CGF) { 1342 if (isa<ConditionalOperator>(op)) 1343 // Leave Data empty. 1344 return; 1345 1346 const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op); 1347 Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(), 1348 e->getCommon()); 1349 } 1350 1351 /// Build the opaque value mapping for an OpaqueValueExpr whose source 1352 /// expression is set to the expression the OVE represents. 1353 OpaqueValueMapping(CodeGenFunction &CGF, const OpaqueValueExpr *OV) 1354 : CGF(CGF) { 1355 if (OV) { 1356 assert(OV->getSourceExpr() && "wrong form of OpaqueValueMapping used " 1357 "for OVE with no source expression"); 1358 Data = OpaqueValueMappingData::bind(CGF, OV, OV->getSourceExpr()); 1359 } 1360 } 1361 1362 OpaqueValueMapping(CodeGenFunction &CGF, 1363 const OpaqueValueExpr *opaqueValue, 1364 LValue lvalue) 1365 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) { 1366 } 1367 1368 OpaqueValueMapping(CodeGenFunction &CGF, 1369 const OpaqueValueExpr *opaqueValue, 1370 RValue rvalue) 1371 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) { 1372 } 1373 1374 void pop() { 1375 Data.unbind(CGF); 1376 Data.clear(); 1377 } 1378 1379 ~OpaqueValueMapping() { 1380 if (Data.isValid()) Data.unbind(CGF); 1381 } 1382 }; 1383 1384 private: 1385 CGDebugInfo *DebugInfo; 1386 /// Used to create unique names for artificial VLA size debug info variables. 1387 unsigned VLAExprCounter = 0; 1388 bool DisableDebugInfo = false; 1389 1390 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid 1391 /// calling llvm.stacksave for multiple VLAs in the same scope. 1392 bool DidCallStackSave = false; 1393 1394 /// IndirectBranch - The first time an indirect goto is seen we create a block 1395 /// with an indirect branch. Every time we see the address of a label taken, 1396 /// we add the label to the indirect goto. Every subsequent indirect goto is 1397 /// codegen'd as a jump to the IndirectBranch's basic block. 1398 llvm::IndirectBrInst *IndirectBranch = nullptr; 1399 1400 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C 1401 /// decls. 1402 DeclMapTy LocalDeclMap; 1403 1404 // Keep track of the cleanups for callee-destructed parameters pushed to the 1405 // cleanup stack so that they can be deactivated later. 1406 llvm::DenseMap<const ParmVarDecl *, EHScopeStack::stable_iterator> 1407 CalleeDestructedParamCleanups; 1408 1409 /// SizeArguments - If a ParmVarDecl had the pass_object_size attribute, this 1410 /// will contain a mapping from said ParmVarDecl to its implicit "object_size" 1411 /// parameter. 1412 llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *, 2> 1413 SizeArguments; 1414 1415 /// Track escaped local variables with auto storage. Used during SEH 1416 /// outlining to produce a call to llvm.localescape. 1417 llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals; 1418 1419 /// LabelMap - This keeps track of the LLVM basic block for each C label. 1420 llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap; 1421 1422 // BreakContinueStack - This keeps track of where break and continue 1423 // statements should jump to. 1424 struct BreakContinue { 1425 BreakContinue(JumpDest Break, JumpDest Continue) 1426 : BreakBlock(Break), ContinueBlock(Continue) {} 1427 1428 JumpDest BreakBlock; 1429 JumpDest ContinueBlock; 1430 }; 1431 SmallVector<BreakContinue, 8> BreakContinueStack; 1432 1433 /// Handles cancellation exit points in OpenMP-related constructs. 1434 class OpenMPCancelExitStack { 1435 /// Tracks cancellation exit point and join point for cancel-related exit 1436 /// and normal exit. 1437 struct CancelExit { 1438 CancelExit() = default; 1439 CancelExit(OpenMPDirectiveKind Kind, JumpDest ExitBlock, 1440 JumpDest ContBlock) 1441 : Kind(Kind), ExitBlock(ExitBlock), ContBlock(ContBlock) {} 1442 OpenMPDirectiveKind Kind = llvm::omp::OMPD_unknown; 1443 /// true if the exit block has been emitted already by the special 1444 /// emitExit() call, false if the default codegen is used. 1445 bool HasBeenEmitted = false; 1446 JumpDest ExitBlock; 1447 JumpDest ContBlock; 1448 }; 1449 1450 SmallVector<CancelExit, 8> Stack; 1451 1452 public: 1453 OpenMPCancelExitStack() : Stack(1) {} 1454 ~OpenMPCancelExitStack() = default; 1455 /// Fetches the exit block for the current OpenMP construct. 1456 JumpDest getExitBlock() const { return Stack.back().ExitBlock; } 1457 /// Emits exit block with special codegen procedure specific for the related 1458 /// OpenMP construct + emits code for normal construct cleanup. 1459 void emitExit(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, 1460 const llvm::function_ref<void(CodeGenFunction &)> CodeGen) { 1461 if (Stack.back().Kind == Kind && getExitBlock().isValid()) { 1462 assert(CGF.getOMPCancelDestination(Kind).isValid()); 1463 assert(CGF.HaveInsertPoint()); 1464 assert(!Stack.back().HasBeenEmitted); 1465 auto IP = CGF.Builder.saveAndClearIP(); 1466 CGF.EmitBlock(Stack.back().ExitBlock.getBlock()); 1467 CodeGen(CGF); 1468 CGF.EmitBranch(Stack.back().ContBlock.getBlock()); 1469 CGF.Builder.restoreIP(IP); 1470 Stack.back().HasBeenEmitted = true; 1471 } 1472 CodeGen(CGF); 1473 } 1474 /// Enter the cancel supporting \a Kind construct. 1475 /// \param Kind OpenMP directive that supports cancel constructs. 1476 /// \param HasCancel true, if the construct has inner cancel directive, 1477 /// false otherwise. 1478 void enter(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, bool HasCancel) { 1479 Stack.push_back({Kind, 1480 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.exit") 1481 : JumpDest(), 1482 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.cont") 1483 : JumpDest()}); 1484 } 1485 /// Emits default exit point for the cancel construct (if the special one 1486 /// has not be used) + join point for cancel/normal exits. 1487 void exit(CodeGenFunction &CGF) { 1488 if (getExitBlock().isValid()) { 1489 assert(CGF.getOMPCancelDestination(Stack.back().Kind).isValid()); 1490 bool HaveIP = CGF.HaveInsertPoint(); 1491 if (!Stack.back().HasBeenEmitted) { 1492 if (HaveIP) 1493 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock); 1494 CGF.EmitBlock(Stack.back().ExitBlock.getBlock()); 1495 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock); 1496 } 1497 CGF.EmitBlock(Stack.back().ContBlock.getBlock()); 1498 if (!HaveIP) { 1499 CGF.Builder.CreateUnreachable(); 1500 CGF.Builder.ClearInsertionPoint(); 1501 } 1502 } 1503 Stack.pop_back(); 1504 } 1505 }; 1506 OpenMPCancelExitStack OMPCancelStack; 1507 1508 /// Lower the Likelihood knowledge about the \p Cond via llvm.expect intrin. 1509 llvm::Value *emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond, 1510 Stmt::Likelihood LH); 1511 1512 CodeGenPGO PGO; 1513 1514 /// Calculate branch weights appropriate for PGO data 1515 llvm::MDNode *createProfileWeights(uint64_t TrueCount, 1516 uint64_t FalseCount) const; 1517 llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights) const; 1518 llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond, 1519 uint64_t LoopCount) const; 1520 1521 public: 1522 /// Increment the profiler's counter for the given statement by \p StepV. 1523 /// If \p StepV is null, the default increment is 1. 1524 void incrementProfileCounter(const Stmt *S, llvm::Value *StepV = nullptr) { 1525 if (CGM.getCodeGenOpts().hasProfileClangInstr() && 1526 !CurFn->hasFnAttribute(llvm::Attribute::NoProfile)) 1527 PGO.emitCounterIncrement(Builder, S, StepV); 1528 PGO.setCurrentStmt(S); 1529 } 1530 1531 /// Get the profiler's count for the given statement. 1532 uint64_t getProfileCount(const Stmt *S) { 1533 Optional<uint64_t> Count = PGO.getStmtCount(S); 1534 if (!Count.hasValue()) 1535 return 0; 1536 return *Count; 1537 } 1538 1539 /// Set the profiler's current count. 1540 void setCurrentProfileCount(uint64_t Count) { 1541 PGO.setCurrentRegionCount(Count); 1542 } 1543 1544 /// Get the profiler's current count. This is generally the count for the most 1545 /// recently incremented counter. 1546 uint64_t getCurrentProfileCount() { 1547 return PGO.getCurrentRegionCount(); 1548 } 1549 1550 private: 1551 1552 /// SwitchInsn - This is nearest current switch instruction. It is null if 1553 /// current context is not in a switch. 1554 llvm::SwitchInst *SwitchInsn = nullptr; 1555 /// The branch weights of SwitchInsn when doing instrumentation based PGO. 1556 SmallVector<uint64_t, 16> *SwitchWeights = nullptr; 1557 1558 /// The likelihood attributes of the SwitchCase. 1559 SmallVector<Stmt::Likelihood, 16> *SwitchLikelihood = nullptr; 1560 1561 /// CaseRangeBlock - This block holds if condition check for last case 1562 /// statement range in current switch instruction. 1563 llvm::BasicBlock *CaseRangeBlock = nullptr; 1564 1565 /// OpaqueLValues - Keeps track of the current set of opaque value 1566 /// expressions. 1567 llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues; 1568 llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues; 1569 1570 // VLASizeMap - This keeps track of the associated size for each VLA type. 1571 // We track this by the size expression rather than the type itself because 1572 // in certain situations, like a const qualifier applied to an VLA typedef, 1573 // multiple VLA types can share the same size expression. 1574 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we 1575 // enter/leave scopes. 1576 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap; 1577 1578 /// A block containing a single 'unreachable' instruction. Created 1579 /// lazily by getUnreachableBlock(). 1580 llvm::BasicBlock *UnreachableBlock = nullptr; 1581 1582 /// Counts of the number return expressions in the function. 1583 unsigned NumReturnExprs = 0; 1584 1585 /// Count the number of simple (constant) return expressions in the function. 1586 unsigned NumSimpleReturnExprs = 0; 1587 1588 /// The last regular (non-return) debug location (breakpoint) in the function. 1589 SourceLocation LastStopPoint; 1590 1591 public: 1592 /// Source location information about the default argument or member 1593 /// initializer expression we're evaluating, if any. 1594 CurrentSourceLocExprScope CurSourceLocExprScope; 1595 using SourceLocExprScopeGuard = 1596 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 1597 1598 /// A scope within which we are constructing the fields of an object which 1599 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use 1600 /// if we need to evaluate a CXXDefaultInitExpr within the evaluation. 1601 class FieldConstructionScope { 1602 public: 1603 FieldConstructionScope(CodeGenFunction &CGF, Address This) 1604 : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) { 1605 CGF.CXXDefaultInitExprThis = This; 1606 } 1607 ~FieldConstructionScope() { 1608 CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis; 1609 } 1610 1611 private: 1612 CodeGenFunction &CGF; 1613 Address OldCXXDefaultInitExprThis; 1614 }; 1615 1616 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this' 1617 /// is overridden to be the object under construction. 1618 class CXXDefaultInitExprScope { 1619 public: 1620 CXXDefaultInitExprScope(CodeGenFunction &CGF, const CXXDefaultInitExpr *E) 1621 : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue), 1622 OldCXXThisAlignment(CGF.CXXThisAlignment), 1623 SourceLocScope(E, CGF.CurSourceLocExprScope) { 1624 CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer(); 1625 CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment(); 1626 } 1627 ~CXXDefaultInitExprScope() { 1628 CGF.CXXThisValue = OldCXXThisValue; 1629 CGF.CXXThisAlignment = OldCXXThisAlignment; 1630 } 1631 1632 public: 1633 CodeGenFunction &CGF; 1634 llvm::Value *OldCXXThisValue; 1635 CharUnits OldCXXThisAlignment; 1636 SourceLocExprScopeGuard SourceLocScope; 1637 }; 1638 1639 struct CXXDefaultArgExprScope : SourceLocExprScopeGuard { 1640 CXXDefaultArgExprScope(CodeGenFunction &CGF, const CXXDefaultArgExpr *E) 1641 : SourceLocExprScopeGuard(E, CGF.CurSourceLocExprScope) {} 1642 }; 1643 1644 /// The scope of an ArrayInitLoopExpr. Within this scope, the value of the 1645 /// current loop index is overridden. 1646 class ArrayInitLoopExprScope { 1647 public: 1648 ArrayInitLoopExprScope(CodeGenFunction &CGF, llvm::Value *Index) 1649 : CGF(CGF), OldArrayInitIndex(CGF.ArrayInitIndex) { 1650 CGF.ArrayInitIndex = Index; 1651 } 1652 ~ArrayInitLoopExprScope() { 1653 CGF.ArrayInitIndex = OldArrayInitIndex; 1654 } 1655 1656 private: 1657 CodeGenFunction &CGF; 1658 llvm::Value *OldArrayInitIndex; 1659 }; 1660 1661 class InlinedInheritingConstructorScope { 1662 public: 1663 InlinedInheritingConstructorScope(CodeGenFunction &CGF, GlobalDecl GD) 1664 : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl), 1665 OldCurCodeDecl(CGF.CurCodeDecl), 1666 OldCXXABIThisDecl(CGF.CXXABIThisDecl), 1667 OldCXXABIThisValue(CGF.CXXABIThisValue), 1668 OldCXXThisValue(CGF.CXXThisValue), 1669 OldCXXABIThisAlignment(CGF.CXXABIThisAlignment), 1670 OldCXXThisAlignment(CGF.CXXThisAlignment), 1671 OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy), 1672 OldCXXInheritedCtorInitExprArgs( 1673 std::move(CGF.CXXInheritedCtorInitExprArgs)) { 1674 CGF.CurGD = GD; 1675 CGF.CurFuncDecl = CGF.CurCodeDecl = 1676 cast<CXXConstructorDecl>(GD.getDecl()); 1677 CGF.CXXABIThisDecl = nullptr; 1678 CGF.CXXABIThisValue = nullptr; 1679 CGF.CXXThisValue = nullptr; 1680 CGF.CXXABIThisAlignment = CharUnits(); 1681 CGF.CXXThisAlignment = CharUnits(); 1682 CGF.ReturnValue = Address::invalid(); 1683 CGF.FnRetTy = QualType(); 1684 CGF.CXXInheritedCtorInitExprArgs.clear(); 1685 } 1686 ~InlinedInheritingConstructorScope() { 1687 CGF.CurGD = OldCurGD; 1688 CGF.CurFuncDecl = OldCurFuncDecl; 1689 CGF.CurCodeDecl = OldCurCodeDecl; 1690 CGF.CXXABIThisDecl = OldCXXABIThisDecl; 1691 CGF.CXXABIThisValue = OldCXXABIThisValue; 1692 CGF.CXXThisValue = OldCXXThisValue; 1693 CGF.CXXABIThisAlignment = OldCXXABIThisAlignment; 1694 CGF.CXXThisAlignment = OldCXXThisAlignment; 1695 CGF.ReturnValue = OldReturnValue; 1696 CGF.FnRetTy = OldFnRetTy; 1697 CGF.CXXInheritedCtorInitExprArgs = 1698 std::move(OldCXXInheritedCtorInitExprArgs); 1699 } 1700 1701 private: 1702 CodeGenFunction &CGF; 1703 GlobalDecl OldCurGD; 1704 const Decl *OldCurFuncDecl; 1705 const Decl *OldCurCodeDecl; 1706 ImplicitParamDecl *OldCXXABIThisDecl; 1707 llvm::Value *OldCXXABIThisValue; 1708 llvm::Value *OldCXXThisValue; 1709 CharUnits OldCXXABIThisAlignment; 1710 CharUnits OldCXXThisAlignment; 1711 Address OldReturnValue; 1712 QualType OldFnRetTy; 1713 CallArgList OldCXXInheritedCtorInitExprArgs; 1714 }; 1715 1716 // Helper class for the OpenMP IR Builder. Allows reusability of code used for 1717 // region body, and finalization codegen callbacks. This will class will also 1718 // contain privatization functions used by the privatization call backs 1719 // 1720 // TODO: this is temporary class for things that are being moved out of 1721 // CGOpenMPRuntime, new versions of current CodeGenFunction methods, or 1722 // utility function for use with the OMPBuilder. Once that move to use the 1723 // OMPBuilder is done, everything here will either become part of CodeGenFunc. 1724 // directly, or a new helper class that will contain functions used by both 1725 // this and the OMPBuilder 1726 1727 struct OMPBuilderCBHelpers { 1728 1729 OMPBuilderCBHelpers() = delete; 1730 OMPBuilderCBHelpers(const OMPBuilderCBHelpers &) = delete; 1731 OMPBuilderCBHelpers &operator=(const OMPBuilderCBHelpers &) = delete; 1732 1733 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 1734 1735 /// Cleanup action for allocate support. 1736 class OMPAllocateCleanupTy final : public EHScopeStack::Cleanup { 1737 1738 private: 1739 llvm::CallInst *RTLFnCI; 1740 1741 public: 1742 OMPAllocateCleanupTy(llvm::CallInst *RLFnCI) : RTLFnCI(RLFnCI) { 1743 RLFnCI->removeFromParent(); 1744 } 1745 1746 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override { 1747 if (!CGF.HaveInsertPoint()) 1748 return; 1749 CGF.Builder.Insert(RTLFnCI); 1750 } 1751 }; 1752 1753 /// Returns address of the threadprivate variable for the current 1754 /// thread. This Also create any necessary OMP runtime calls. 1755 /// 1756 /// \param VD VarDecl for Threadprivate variable. 1757 /// \param VDAddr Address of the Vardecl 1758 /// \param Loc The location where the barrier directive was encountered 1759 static Address getAddrOfThreadPrivate(CodeGenFunction &CGF, 1760 const VarDecl *VD, Address VDAddr, 1761 SourceLocation Loc); 1762 1763 /// Gets the OpenMP-specific address of the local variable /p VD. 1764 static Address getAddressOfLocalVariable(CodeGenFunction &CGF, 1765 const VarDecl *VD); 1766 /// Get the platform-specific name separator. 1767 /// \param Parts different parts of the final name that needs separation 1768 /// \param FirstSeparator First separator used between the initial two 1769 /// parts of the name. 1770 /// \param Separator separator used between all of the rest consecutinve 1771 /// parts of the name 1772 static std::string getNameWithSeparators(ArrayRef<StringRef> Parts, 1773 StringRef FirstSeparator = ".", 1774 StringRef Separator = "."); 1775 /// Emit the Finalization for an OMP region 1776 /// \param CGF The Codegen function this belongs to 1777 /// \param IP Insertion point for generating the finalization code. 1778 static void FinalizeOMPRegion(CodeGenFunction &CGF, InsertPointTy IP) { 1779 CGBuilderTy::InsertPointGuard IPG(CGF.Builder); 1780 assert(IP.getBlock()->end() != IP.getPoint() && 1781 "OpenMP IR Builder should cause terminated block!"); 1782 1783 llvm::BasicBlock *IPBB = IP.getBlock(); 1784 llvm::BasicBlock *DestBB = IPBB->getUniqueSuccessor(); 1785 assert(DestBB && "Finalization block should have one successor!"); 1786 1787 // erase and replace with cleanup branch. 1788 IPBB->getTerminator()->eraseFromParent(); 1789 CGF.Builder.SetInsertPoint(IPBB); 1790 CodeGenFunction::JumpDest Dest = CGF.getJumpDestInCurrentScope(DestBB); 1791 CGF.EmitBranchThroughCleanup(Dest); 1792 } 1793 1794 /// Emit the body of an OMP region 1795 /// \param CGF The Codegen function this belongs to 1796 /// \param RegionBodyStmt The body statement for the OpenMP region being 1797 /// generated 1798 /// \param CodeGenIP Insertion point for generating the body code. 1799 /// \param FiniBB The finalization basic block 1800 static void EmitOMPRegionBody(CodeGenFunction &CGF, 1801 const Stmt *RegionBodyStmt, 1802 InsertPointTy CodeGenIP, 1803 llvm::BasicBlock &FiniBB) { 1804 llvm::BasicBlock *CodeGenIPBB = CodeGenIP.getBlock(); 1805 if (llvm::Instruction *CodeGenIPBBTI = CodeGenIPBB->getTerminator()) 1806 CodeGenIPBBTI->eraseFromParent(); 1807 1808 CGF.Builder.SetInsertPoint(CodeGenIPBB); 1809 1810 CGF.EmitStmt(RegionBodyStmt); 1811 1812 if (CGF.Builder.saveIP().isSet()) 1813 CGF.Builder.CreateBr(&FiniBB); 1814 } 1815 1816 static void EmitCaptureStmt(CodeGenFunction &CGF, InsertPointTy CodeGenIP, 1817 llvm::BasicBlock &FiniBB, llvm::Function *Fn, 1818 ArrayRef<llvm::Value *> Args) { 1819 llvm::BasicBlock *CodeGenIPBB = CodeGenIP.getBlock(); 1820 if (llvm::Instruction *CodeGenIPBBTI = CodeGenIPBB->getTerminator()) 1821 CodeGenIPBBTI->eraseFromParent(); 1822 1823 CGF.Builder.SetInsertPoint(CodeGenIPBB); 1824 1825 if (Fn->doesNotThrow()) 1826 CGF.EmitNounwindRuntimeCall(Fn, Args); 1827 else 1828 CGF.EmitRuntimeCall(Fn, Args); 1829 1830 if (CGF.Builder.saveIP().isSet()) 1831 CGF.Builder.CreateBr(&FiniBB); 1832 } 1833 1834 /// RAII for preserving necessary info during Outlined region body codegen. 1835 class OutlinedRegionBodyRAII { 1836 1837 llvm::AssertingVH<llvm::Instruction> OldAllocaIP; 1838 CodeGenFunction::JumpDest OldReturnBlock; 1839 CGBuilderTy::InsertPoint IP; 1840 CodeGenFunction &CGF; 1841 1842 public: 1843 OutlinedRegionBodyRAII(CodeGenFunction &cgf, InsertPointTy &AllocaIP, 1844 llvm::BasicBlock &RetBB) 1845 : CGF(cgf) { 1846 assert(AllocaIP.isSet() && 1847 "Must specify Insertion point for allocas of outlined function"); 1848 OldAllocaIP = CGF.AllocaInsertPt; 1849 CGF.AllocaInsertPt = &*AllocaIP.getPoint(); 1850 IP = CGF.Builder.saveIP(); 1851 1852 OldReturnBlock = CGF.ReturnBlock; 1853 CGF.ReturnBlock = CGF.getJumpDestInCurrentScope(&RetBB); 1854 } 1855 1856 ~OutlinedRegionBodyRAII() { 1857 CGF.AllocaInsertPt = OldAllocaIP; 1858 CGF.ReturnBlock = OldReturnBlock; 1859 CGF.Builder.restoreIP(IP); 1860 } 1861 }; 1862 1863 /// RAII for preserving necessary info during inlined region body codegen. 1864 class InlinedRegionBodyRAII { 1865 1866 llvm::AssertingVH<llvm::Instruction> OldAllocaIP; 1867 CodeGenFunction &CGF; 1868 1869 public: 1870 InlinedRegionBodyRAII(CodeGenFunction &cgf, InsertPointTy &AllocaIP, 1871 llvm::BasicBlock &FiniBB) 1872 : CGF(cgf) { 1873 // Alloca insertion block should be in the entry block of the containing 1874 // function so it expects an empty AllocaIP in which case will reuse the 1875 // old alloca insertion point, or a new AllocaIP in the same block as 1876 // the old one 1877 assert((!AllocaIP.isSet() || 1878 CGF.AllocaInsertPt->getParent() == AllocaIP.getBlock()) && 1879 "Insertion point should be in the entry block of containing " 1880 "function!"); 1881 OldAllocaIP = CGF.AllocaInsertPt; 1882 if (AllocaIP.isSet()) 1883 CGF.AllocaInsertPt = &*AllocaIP.getPoint(); 1884 1885 // TODO: Remove the call, after making sure the counter is not used by 1886 // the EHStack. 1887 // Since this is an inlined region, it should not modify the 1888 // ReturnBlock, and should reuse the one for the enclosing outlined 1889 // region. So, the JumpDest being return by the function is discarded 1890 (void)CGF.getJumpDestInCurrentScope(&FiniBB); 1891 } 1892 1893 ~InlinedRegionBodyRAII() { CGF.AllocaInsertPt = OldAllocaIP; } 1894 }; 1895 }; 1896 1897 private: 1898 /// CXXThisDecl - When generating code for a C++ member function, 1899 /// this will hold the implicit 'this' declaration. 1900 ImplicitParamDecl *CXXABIThisDecl = nullptr; 1901 llvm::Value *CXXABIThisValue = nullptr; 1902 llvm::Value *CXXThisValue = nullptr; 1903 CharUnits CXXABIThisAlignment; 1904 CharUnits CXXThisAlignment; 1905 1906 /// The value of 'this' to use when evaluating CXXDefaultInitExprs within 1907 /// this expression. 1908 Address CXXDefaultInitExprThis = Address::invalid(); 1909 1910 /// The current array initialization index when evaluating an 1911 /// ArrayInitIndexExpr within an ArrayInitLoopExpr. 1912 llvm::Value *ArrayInitIndex = nullptr; 1913 1914 /// The values of function arguments to use when evaluating 1915 /// CXXInheritedCtorInitExprs within this context. 1916 CallArgList CXXInheritedCtorInitExprArgs; 1917 1918 /// CXXStructorImplicitParamDecl - When generating code for a constructor or 1919 /// destructor, this will hold the implicit argument (e.g. VTT). 1920 ImplicitParamDecl *CXXStructorImplicitParamDecl = nullptr; 1921 llvm::Value *CXXStructorImplicitParamValue = nullptr; 1922 1923 /// OutermostConditional - Points to the outermost active 1924 /// conditional control. This is used so that we know if a 1925 /// temporary should be destroyed conditionally. 1926 ConditionalEvaluation *OutermostConditional = nullptr; 1927 1928 /// The current lexical scope. 1929 LexicalScope *CurLexicalScope = nullptr; 1930 1931 /// The current source location that should be used for exception 1932 /// handling code. 1933 SourceLocation CurEHLocation; 1934 1935 /// BlockByrefInfos - For each __block variable, contains 1936 /// information about the layout of the variable. 1937 llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos; 1938 1939 /// Used by -fsanitize=nullability-return to determine whether the return 1940 /// value can be checked. 1941 llvm::Value *RetValNullabilityPrecondition = nullptr; 1942 1943 /// Check if -fsanitize=nullability-return instrumentation is required for 1944 /// this function. 1945 bool requiresReturnValueNullabilityCheck() const { 1946 return RetValNullabilityPrecondition; 1947 } 1948 1949 /// Used to store precise source locations for return statements by the 1950 /// runtime return value checks. 1951 Address ReturnLocation = Address::invalid(); 1952 1953 /// Check if the return value of this function requires sanitization. 1954 bool requiresReturnValueCheck() const; 1955 1956 llvm::BasicBlock *TerminateLandingPad = nullptr; 1957 llvm::BasicBlock *TerminateHandler = nullptr; 1958 llvm::SmallVector<llvm::BasicBlock *, 2> TrapBBs; 1959 1960 /// Terminate funclets keyed by parent funclet pad. 1961 llvm::MapVector<llvm::Value *, llvm::BasicBlock *> TerminateFunclets; 1962 1963 /// Largest vector width used in ths function. Will be used to create a 1964 /// function attribute. 1965 unsigned LargestVectorWidth = 0; 1966 1967 /// True if we need emit the life-time markers. This is initially set in 1968 /// the constructor, but could be overwritten to true if this is a coroutine. 1969 bool ShouldEmitLifetimeMarkers; 1970 1971 /// Add OpenCL kernel arg metadata and the kernel attribute metadata to 1972 /// the function metadata. 1973 void EmitOpenCLKernelMetadata(const FunctionDecl *FD, 1974 llvm::Function *Fn); 1975 1976 public: 1977 CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false); 1978 ~CodeGenFunction(); 1979 1980 CodeGenTypes &getTypes() const { return CGM.getTypes(); } 1981 ASTContext &getContext() const { return CGM.getContext(); } 1982 CGDebugInfo *getDebugInfo() { 1983 if (DisableDebugInfo) 1984 return nullptr; 1985 return DebugInfo; 1986 } 1987 void disableDebugInfo() { DisableDebugInfo = true; } 1988 void enableDebugInfo() { DisableDebugInfo = false; } 1989 1990 bool shouldUseFusedARCCalls() { 1991 return CGM.getCodeGenOpts().OptimizationLevel == 0; 1992 } 1993 1994 const LangOptions &getLangOpts() const { return CGM.getLangOpts(); } 1995 1996 /// Returns a pointer to the function's exception object and selector slot, 1997 /// which is assigned in every landing pad. 1998 Address getExceptionSlot(); 1999 Address getEHSelectorSlot(); 2000 2001 /// Returns the contents of the function's exception object and selector 2002 /// slots. 2003 llvm::Value *getExceptionFromSlot(); 2004 llvm::Value *getSelectorFromSlot(); 2005 2006 Address getNormalCleanupDestSlot(); 2007 2008 llvm::BasicBlock *getUnreachableBlock() { 2009 if (!UnreachableBlock) { 2010 UnreachableBlock = createBasicBlock("unreachable"); 2011 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock); 2012 } 2013 return UnreachableBlock; 2014 } 2015 2016 llvm::BasicBlock *getInvokeDest() { 2017 if (!EHStack.requiresLandingPad()) return nullptr; 2018 return getInvokeDestImpl(); 2019 } 2020 2021 bool currentFunctionUsesSEHTry() const { return CurSEHParent != nullptr; } 2022 2023 const TargetInfo &getTarget() const { return Target; } 2024 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); } 2025 const TargetCodeGenInfo &getTargetHooks() const { 2026 return CGM.getTargetCodeGenInfo(); 2027 } 2028 2029 //===--------------------------------------------------------------------===// 2030 // Cleanups 2031 //===--------------------------------------------------------------------===// 2032 2033 typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty); 2034 2035 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, 2036 Address arrayEndPointer, 2037 QualType elementType, 2038 CharUnits elementAlignment, 2039 Destroyer *destroyer); 2040 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, 2041 llvm::Value *arrayEnd, 2042 QualType elementType, 2043 CharUnits elementAlignment, 2044 Destroyer *destroyer); 2045 2046 void pushDestroy(QualType::DestructionKind dtorKind, 2047 Address addr, QualType type); 2048 void pushEHDestroy(QualType::DestructionKind dtorKind, 2049 Address addr, QualType type); 2050 void pushDestroy(CleanupKind kind, Address addr, QualType type, 2051 Destroyer *destroyer, bool useEHCleanupForArray); 2052 void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, 2053 QualType type, Destroyer *destroyer, 2054 bool useEHCleanupForArray); 2055 void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete, 2056 llvm::Value *CompletePtr, 2057 QualType ElementType); 2058 void pushStackRestore(CleanupKind kind, Address SPMem); 2059 void emitDestroy(Address addr, QualType type, Destroyer *destroyer, 2060 bool useEHCleanupForArray); 2061 llvm::Function *generateDestroyHelper(Address addr, QualType type, 2062 Destroyer *destroyer, 2063 bool useEHCleanupForArray, 2064 const VarDecl *VD); 2065 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end, 2066 QualType elementType, CharUnits elementAlign, 2067 Destroyer *destroyer, 2068 bool checkZeroLength, bool useEHCleanup); 2069 2070 Destroyer *getDestroyer(QualType::DestructionKind destructionKind); 2071 2072 /// Determines whether an EH cleanup is required to destroy a type 2073 /// with the given destruction kind. 2074 bool needsEHCleanup(QualType::DestructionKind kind) { 2075 switch (kind) { 2076 case QualType::DK_none: 2077 return false; 2078 case QualType::DK_cxx_destructor: 2079 case QualType::DK_objc_weak_lifetime: 2080 case QualType::DK_nontrivial_c_struct: 2081 return getLangOpts().Exceptions; 2082 case QualType::DK_objc_strong_lifetime: 2083 return getLangOpts().Exceptions && 2084 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions; 2085 } 2086 llvm_unreachable("bad destruction kind"); 2087 } 2088 2089 CleanupKind getCleanupKind(QualType::DestructionKind kind) { 2090 return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup); 2091 } 2092 2093 //===--------------------------------------------------------------------===// 2094 // Objective-C 2095 //===--------------------------------------------------------------------===// 2096 2097 void GenerateObjCMethod(const ObjCMethodDecl *OMD); 2098 2099 void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD); 2100 2101 /// GenerateObjCGetter - Synthesize an Objective-C property getter function. 2102 void GenerateObjCGetter(ObjCImplementationDecl *IMP, 2103 const ObjCPropertyImplDecl *PID); 2104 void generateObjCGetterBody(const ObjCImplementationDecl *classImpl, 2105 const ObjCPropertyImplDecl *propImpl, 2106 const ObjCMethodDecl *GetterMothodDecl, 2107 llvm::Constant *AtomicHelperFn); 2108 2109 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, 2110 ObjCMethodDecl *MD, bool ctor); 2111 2112 /// GenerateObjCSetter - Synthesize an Objective-C property setter function 2113 /// for the given property. 2114 void GenerateObjCSetter(ObjCImplementationDecl *IMP, 2115 const ObjCPropertyImplDecl *PID); 2116 void generateObjCSetterBody(const ObjCImplementationDecl *classImpl, 2117 const ObjCPropertyImplDecl *propImpl, 2118 llvm::Constant *AtomicHelperFn); 2119 2120 //===--------------------------------------------------------------------===// 2121 // Block Bits 2122 //===--------------------------------------------------------------------===// 2123 2124 /// Emit block literal. 2125 /// \return an LLVM value which is a pointer to a struct which contains 2126 /// information about the block, including the block invoke function, the 2127 /// captured variables, etc. 2128 llvm::Value *EmitBlockLiteral(const BlockExpr *); 2129 2130 llvm::Function *GenerateBlockFunction(GlobalDecl GD, 2131 const CGBlockInfo &Info, 2132 const DeclMapTy &ldm, 2133 bool IsLambdaConversionToBlock, 2134 bool BuildGlobalBlock); 2135 2136 /// Check if \p T is a C++ class that has a destructor that can throw. 2137 static bool cxxDestructorCanThrow(QualType T); 2138 2139 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo); 2140 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo); 2141 llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction( 2142 const ObjCPropertyImplDecl *PID); 2143 llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction( 2144 const ObjCPropertyImplDecl *PID); 2145 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty); 2146 2147 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags, 2148 bool CanThrow); 2149 2150 class AutoVarEmission; 2151 2152 void emitByrefStructureInit(const AutoVarEmission &emission); 2153 2154 /// Enter a cleanup to destroy a __block variable. Note that this 2155 /// cleanup should be a no-op if the variable hasn't left the stack 2156 /// yet; if a cleanup is required for the variable itself, that needs 2157 /// to be done externally. 2158 /// 2159 /// \param Kind Cleanup kind. 2160 /// 2161 /// \param Addr When \p LoadBlockVarAddr is false, the address of the __block 2162 /// structure that will be passed to _Block_object_dispose. When 2163 /// \p LoadBlockVarAddr is true, the address of the field of the block 2164 /// structure that holds the address of the __block structure. 2165 /// 2166 /// \param Flags The flag that will be passed to _Block_object_dispose. 2167 /// 2168 /// \param LoadBlockVarAddr Indicates whether we need to emit a load from 2169 /// \p Addr to get the address of the __block structure. 2170 void enterByrefCleanup(CleanupKind Kind, Address Addr, BlockFieldFlags Flags, 2171 bool LoadBlockVarAddr, bool CanThrow); 2172 2173 void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum, 2174 llvm::Value *ptr); 2175 2176 Address LoadBlockStruct(); 2177 Address GetAddrOfBlockDecl(const VarDecl *var); 2178 2179 /// BuildBlockByrefAddress - Computes the location of the 2180 /// data in a variable which is declared as __block. 2181 Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V, 2182 bool followForward = true); 2183 Address emitBlockByrefAddress(Address baseAddr, 2184 const BlockByrefInfo &info, 2185 bool followForward, 2186 const llvm::Twine &name); 2187 2188 const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var); 2189 2190 QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args); 2191 2192 void GenerateCode(GlobalDecl GD, llvm::Function *Fn, 2193 const CGFunctionInfo &FnInfo); 2194 2195 /// Annotate the function with an attribute that disables TSan checking at 2196 /// runtime. 2197 void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn); 2198 2199 /// Emit code for the start of a function. 2200 /// \param Loc The location to be associated with the function. 2201 /// \param StartLoc The location of the function body. 2202 void StartFunction(GlobalDecl GD, 2203 QualType RetTy, 2204 llvm::Function *Fn, 2205 const CGFunctionInfo &FnInfo, 2206 const FunctionArgList &Args, 2207 SourceLocation Loc = SourceLocation(), 2208 SourceLocation StartLoc = SourceLocation()); 2209 2210 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor); 2211 2212 void EmitConstructorBody(FunctionArgList &Args); 2213 void EmitDestructorBody(FunctionArgList &Args); 2214 void emitImplicitAssignmentOperatorBody(FunctionArgList &Args); 2215 void EmitFunctionBody(const Stmt *Body); 2216 void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S); 2217 2218 void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator, 2219 CallArgList &CallArgs); 2220 void EmitLambdaBlockInvokeBody(); 2221 void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD); 2222 void EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD); 2223 void EmitLambdaVLACapture(const VariableArrayType *VAT, LValue LV) { 2224 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV); 2225 } 2226 void EmitAsanPrologueOrEpilogue(bool Prologue); 2227 2228 /// Emit the unified return block, trying to avoid its emission when 2229 /// possible. 2230 /// \return The debug location of the user written return statement if the 2231 /// return block is is avoided. 2232 llvm::DebugLoc EmitReturnBlock(); 2233 2234 /// FinishFunction - Complete IR generation of the current function. It is 2235 /// legal to call this function even if there is no current insertion point. 2236 void FinishFunction(SourceLocation EndLoc=SourceLocation()); 2237 2238 void StartThunk(llvm::Function *Fn, GlobalDecl GD, 2239 const CGFunctionInfo &FnInfo, bool IsUnprototyped); 2240 2241 void EmitCallAndReturnForThunk(llvm::FunctionCallee Callee, 2242 const ThunkInfo *Thunk, bool IsUnprototyped); 2243 2244 void FinishThunk(); 2245 2246 /// Emit a musttail call for a thunk with a potentially adjusted this pointer. 2247 void EmitMustTailThunk(GlobalDecl GD, llvm::Value *AdjustedThisPtr, 2248 llvm::FunctionCallee Callee); 2249 2250 /// Generate a thunk for the given method. 2251 void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, 2252 GlobalDecl GD, const ThunkInfo &Thunk, 2253 bool IsUnprototyped); 2254 2255 llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn, 2256 const CGFunctionInfo &FnInfo, 2257 GlobalDecl GD, const ThunkInfo &Thunk); 2258 2259 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type, 2260 FunctionArgList &Args); 2261 2262 void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init); 2263 2264 /// Struct with all information about dynamic [sub]class needed to set vptr. 2265 struct VPtr { 2266 BaseSubobject Base; 2267 const CXXRecordDecl *NearestVBase; 2268 CharUnits OffsetFromNearestVBase; 2269 const CXXRecordDecl *VTableClass; 2270 }; 2271 2272 /// Initialize the vtable pointer of the given subobject. 2273 void InitializeVTablePointer(const VPtr &vptr); 2274 2275 typedef llvm::SmallVector<VPtr, 4> VPtrsVector; 2276 2277 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy; 2278 VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass); 2279 2280 void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase, 2281 CharUnits OffsetFromNearestVBase, 2282 bool BaseIsNonVirtualPrimaryBase, 2283 const CXXRecordDecl *VTableClass, 2284 VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs); 2285 2286 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl); 2287 2288 /// GetVTablePtr - Return the Value of the vtable pointer member pointed 2289 /// to by This. 2290 llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy, 2291 const CXXRecordDecl *VTableClass); 2292 2293 enum CFITypeCheckKind { 2294 CFITCK_VCall, 2295 CFITCK_NVCall, 2296 CFITCK_DerivedCast, 2297 CFITCK_UnrelatedCast, 2298 CFITCK_ICall, 2299 CFITCK_NVMFCall, 2300 CFITCK_VMFCall, 2301 }; 2302 2303 /// Derived is the presumed address of an object of type T after a 2304 /// cast. If T is a polymorphic class type, emit a check that the virtual 2305 /// table for Derived belongs to a class derived from T. 2306 void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived, 2307 bool MayBeNull, CFITypeCheckKind TCK, 2308 SourceLocation Loc); 2309 2310 /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable. 2311 /// If vptr CFI is enabled, emit a check that VTable is valid. 2312 void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable, 2313 CFITypeCheckKind TCK, SourceLocation Loc); 2314 2315 /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for 2316 /// RD using llvm.type.test. 2317 void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable, 2318 CFITypeCheckKind TCK, SourceLocation Loc); 2319 2320 /// If whole-program virtual table optimization is enabled, emit an assumption 2321 /// that VTable is a member of RD's type identifier. Or, if vptr CFI is 2322 /// enabled, emit a check that VTable is a member of RD's type identifier. 2323 void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD, 2324 llvm::Value *VTable, SourceLocation Loc); 2325 2326 /// Returns whether we should perform a type checked load when loading a 2327 /// virtual function for virtual calls to members of RD. This is generally 2328 /// true when both vcall CFI and whole-program-vtables are enabled. 2329 bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD); 2330 2331 /// Emit a type checked load from the given vtable. 2332 llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable, 2333 uint64_t VTableByteOffset); 2334 2335 /// EnterDtorCleanups - Enter the cleanups necessary to complete the 2336 /// given phase of destruction for a destructor. The end result 2337 /// should call destructors on members and base classes in reverse 2338 /// order of their construction. 2339 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type); 2340 2341 /// ShouldInstrumentFunction - Return true if the current function should be 2342 /// instrumented with __cyg_profile_func_* calls 2343 bool ShouldInstrumentFunction(); 2344 2345 /// ShouldSkipSanitizerInstrumentation - Return true if the current function 2346 /// should not be instrumented with sanitizers. 2347 bool ShouldSkipSanitizerInstrumentation(); 2348 2349 /// ShouldXRayInstrument - Return true if the current function should be 2350 /// instrumented with XRay nop sleds. 2351 bool ShouldXRayInstrumentFunction() const; 2352 2353 /// AlwaysEmitXRayCustomEvents - Return true if we must unconditionally emit 2354 /// XRay custom event handling calls. 2355 bool AlwaysEmitXRayCustomEvents() const; 2356 2357 /// AlwaysEmitXRayTypedEvents - Return true if clang must unconditionally emit 2358 /// XRay typed event handling calls. 2359 bool AlwaysEmitXRayTypedEvents() const; 2360 2361 /// Encode an address into a form suitable for use in a function prologue. 2362 llvm::Constant *EncodeAddrForUseInPrologue(llvm::Function *F, 2363 llvm::Constant *Addr); 2364 2365 /// Decode an address used in a function prologue, encoded by \c 2366 /// EncodeAddrForUseInPrologue. 2367 llvm::Value *DecodeAddrUsedInPrologue(llvm::Value *F, 2368 llvm::Value *EncodedAddr); 2369 2370 /// EmitFunctionProlog - Emit the target specific LLVM code to load the 2371 /// arguments for the given function. This is also responsible for naming the 2372 /// LLVM function arguments. 2373 void EmitFunctionProlog(const CGFunctionInfo &FI, 2374 llvm::Function *Fn, 2375 const FunctionArgList &Args); 2376 2377 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the 2378 /// given temporary. 2379 void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc, 2380 SourceLocation EndLoc); 2381 2382 /// Emit a test that checks if the return value \p RV is nonnull. 2383 void EmitReturnValueCheck(llvm::Value *RV); 2384 2385 /// EmitStartEHSpec - Emit the start of the exception spec. 2386 void EmitStartEHSpec(const Decl *D); 2387 2388 /// EmitEndEHSpec - Emit the end of the exception spec. 2389 void EmitEndEHSpec(const Decl *D); 2390 2391 /// getTerminateLandingPad - Return a landing pad that just calls terminate. 2392 llvm::BasicBlock *getTerminateLandingPad(); 2393 2394 /// getTerminateLandingPad - Return a cleanup funclet that just calls 2395 /// terminate. 2396 llvm::BasicBlock *getTerminateFunclet(); 2397 2398 /// getTerminateHandler - Return a handler (not a landing pad, just 2399 /// a catch handler) that just calls terminate. This is used when 2400 /// a terminate scope encloses a try. 2401 llvm::BasicBlock *getTerminateHandler(); 2402 2403 llvm::Type *ConvertTypeForMem(QualType T); 2404 llvm::Type *ConvertType(QualType T); 2405 llvm::Type *ConvertType(const TypeDecl *T) { 2406 return ConvertType(getContext().getTypeDeclType(T)); 2407 } 2408 2409 /// LoadObjCSelf - Load the value of self. This function is only valid while 2410 /// generating code for an Objective-C method. 2411 llvm::Value *LoadObjCSelf(); 2412 2413 /// TypeOfSelfObject - Return type of object that this self represents. 2414 QualType TypeOfSelfObject(); 2415 2416 /// getEvaluationKind - Return the TypeEvaluationKind of QualType \c T. 2417 static TypeEvaluationKind getEvaluationKind(QualType T); 2418 2419 static bool hasScalarEvaluationKind(QualType T) { 2420 return getEvaluationKind(T) == TEK_Scalar; 2421 } 2422 2423 static bool hasAggregateEvaluationKind(QualType T) { 2424 return getEvaluationKind(T) == TEK_Aggregate; 2425 } 2426 2427 /// createBasicBlock - Create an LLVM basic block. 2428 llvm::BasicBlock *createBasicBlock(const Twine &name = "", 2429 llvm::Function *parent = nullptr, 2430 llvm::BasicBlock *before = nullptr) { 2431 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before); 2432 } 2433 2434 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified 2435 /// label maps to. 2436 JumpDest getJumpDestForLabel(const LabelDecl *S); 2437 2438 /// SimplifyForwardingBlocks - If the given basic block is only a branch to 2439 /// another basic block, simplify it. This assumes that no other code could 2440 /// potentially reference the basic block. 2441 void SimplifyForwardingBlocks(llvm::BasicBlock *BB); 2442 2443 /// EmitBlock - Emit the given block \arg BB and set it as the insert point, 2444 /// adding a fall-through branch from the current insert block if 2445 /// necessary. It is legal to call this function even if there is no current 2446 /// insertion point. 2447 /// 2448 /// IsFinished - If true, indicates that the caller has finished emitting 2449 /// branches to the given block and does not expect to emit code into it. This 2450 /// means the block can be ignored if it is unreachable. 2451 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false); 2452 2453 /// EmitBlockAfterUses - Emit the given block somewhere hopefully 2454 /// near its uses, and leave the insertion point in it. 2455 void EmitBlockAfterUses(llvm::BasicBlock *BB); 2456 2457 /// EmitBranch - Emit a branch to the specified basic block from the current 2458 /// insert block, taking care to avoid creation of branches from dummy 2459 /// blocks. It is legal to call this function even if there is no current 2460 /// insertion point. 2461 /// 2462 /// This function clears the current insertion point. The caller should follow 2463 /// calls to this function with calls to Emit*Block prior to generation new 2464 /// code. 2465 void EmitBranch(llvm::BasicBlock *Block); 2466 2467 /// HaveInsertPoint - True if an insertion point is defined. If not, this 2468 /// indicates that the current code being emitted is unreachable. 2469 bool HaveInsertPoint() const { 2470 return Builder.GetInsertBlock() != nullptr; 2471 } 2472 2473 /// EnsureInsertPoint - Ensure that an insertion point is defined so that 2474 /// emitted IR has a place to go. Note that by definition, if this function 2475 /// creates a block then that block is unreachable; callers may do better to 2476 /// detect when no insertion point is defined and simply skip IR generation. 2477 void EnsureInsertPoint() { 2478 if (!HaveInsertPoint()) 2479 EmitBlock(createBasicBlock()); 2480 } 2481 2482 /// ErrorUnsupported - Print out an error that codegen doesn't support the 2483 /// specified stmt yet. 2484 void ErrorUnsupported(const Stmt *S, const char *Type); 2485 2486 //===--------------------------------------------------------------------===// 2487 // Helpers 2488 //===--------------------------------------------------------------------===// 2489 2490 LValue MakeAddrLValue(Address Addr, QualType T, 2491 AlignmentSource Source = AlignmentSource::Type) { 2492 return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source), 2493 CGM.getTBAAAccessInfo(T)); 2494 } 2495 2496 LValue MakeAddrLValue(Address Addr, QualType T, LValueBaseInfo BaseInfo, 2497 TBAAAccessInfo TBAAInfo) { 2498 return LValue::MakeAddr(Addr, T, getContext(), BaseInfo, TBAAInfo); 2499 } 2500 2501 LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment, 2502 AlignmentSource Source = AlignmentSource::Type) { 2503 Address Addr(V, ConvertTypeForMem(T), Alignment); 2504 return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source), 2505 CGM.getTBAAAccessInfo(T)); 2506 } 2507 2508 LValue 2509 MakeAddrLValueWithoutTBAA(Address Addr, QualType T, 2510 AlignmentSource Source = AlignmentSource::Type) { 2511 return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source), 2512 TBAAAccessInfo()); 2513 } 2514 2515 LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T); 2516 LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T); 2517 2518 Address EmitLoadOfReference(LValue RefLVal, 2519 LValueBaseInfo *PointeeBaseInfo = nullptr, 2520 TBAAAccessInfo *PointeeTBAAInfo = nullptr); 2521 LValue EmitLoadOfReferenceLValue(LValue RefLVal); 2522 LValue EmitLoadOfReferenceLValue(Address RefAddr, QualType RefTy, 2523 AlignmentSource Source = 2524 AlignmentSource::Type) { 2525 LValue RefLVal = MakeAddrLValue(RefAddr, RefTy, LValueBaseInfo(Source), 2526 CGM.getTBAAAccessInfo(RefTy)); 2527 return EmitLoadOfReferenceLValue(RefLVal); 2528 } 2529 2530 Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy, 2531 LValueBaseInfo *BaseInfo = nullptr, 2532 TBAAAccessInfo *TBAAInfo = nullptr); 2533 LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy); 2534 2535 /// CreateTempAlloca - This creates an alloca and inserts it into the entry 2536 /// block if \p ArraySize is nullptr, otherwise inserts it at the current 2537 /// insertion point of the builder. The caller is responsible for setting an 2538 /// appropriate alignment on 2539 /// the alloca. 2540 /// 2541 /// \p ArraySize is the number of array elements to be allocated if it 2542 /// is not nullptr. 2543 /// 2544 /// LangAS::Default is the address space of pointers to local variables and 2545 /// temporaries, as exposed in the source language. In certain 2546 /// configurations, this is not the same as the alloca address space, and a 2547 /// cast is needed to lift the pointer from the alloca AS into 2548 /// LangAS::Default. This can happen when the target uses a restricted 2549 /// address space for the stack but the source language requires 2550 /// LangAS::Default to be a generic address space. The latter condition is 2551 /// common for most programming languages; OpenCL is an exception in that 2552 /// LangAS::Default is the private address space, which naturally maps 2553 /// to the stack. 2554 /// 2555 /// Because the address of a temporary is often exposed to the program in 2556 /// various ways, this function will perform the cast. The original alloca 2557 /// instruction is returned through \p Alloca if it is not nullptr. 2558 /// 2559 /// The cast is not performaed in CreateTempAllocaWithoutCast. This is 2560 /// more efficient if the caller knows that the address will not be exposed. 2561 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty, const Twine &Name = "tmp", 2562 llvm::Value *ArraySize = nullptr); 2563 Address CreateTempAlloca(llvm::Type *Ty, CharUnits align, 2564 const Twine &Name = "tmp", 2565 llvm::Value *ArraySize = nullptr, 2566 Address *Alloca = nullptr); 2567 Address CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits align, 2568 const Twine &Name = "tmp", 2569 llvm::Value *ArraySize = nullptr); 2570 2571 /// CreateDefaultAlignedTempAlloca - This creates an alloca with the 2572 /// default ABI alignment of the given LLVM type. 2573 /// 2574 /// IMPORTANT NOTE: This is *not* generally the right alignment for 2575 /// any given AST type that happens to have been lowered to the 2576 /// given IR type. This should only ever be used for function-local, 2577 /// IR-driven manipulations like saving and restoring a value. Do 2578 /// not hand this address off to arbitrary IRGen routines, and especially 2579 /// do not pass it as an argument to a function that might expect a 2580 /// properly ABI-aligned value. 2581 Address CreateDefaultAlignTempAlloca(llvm::Type *Ty, 2582 const Twine &Name = "tmp"); 2583 2584 /// CreateIRTemp - Create a temporary IR object of the given type, with 2585 /// appropriate alignment. This routine should only be used when an temporary 2586 /// value needs to be stored into an alloca (for example, to avoid explicit 2587 /// PHI construction), but the type is the IR type, not the type appropriate 2588 /// for storing in memory. 2589 /// 2590 /// That is, this is exactly equivalent to CreateMemTemp, but calling 2591 /// ConvertType instead of ConvertTypeForMem. 2592 Address CreateIRTemp(QualType T, const Twine &Name = "tmp"); 2593 2594 /// CreateMemTemp - Create a temporary memory object of the given type, with 2595 /// appropriate alignmen and cast it to the default address space. Returns 2596 /// the original alloca instruction by \p Alloca if it is not nullptr. 2597 Address CreateMemTemp(QualType T, const Twine &Name = "tmp", 2598 Address *Alloca = nullptr); 2599 Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp", 2600 Address *Alloca = nullptr); 2601 2602 /// CreateMemTemp - Create a temporary memory object of the given type, with 2603 /// appropriate alignmen without casting it to the default address space. 2604 Address CreateMemTempWithoutCast(QualType T, const Twine &Name = "tmp"); 2605 Address CreateMemTempWithoutCast(QualType T, CharUnits Align, 2606 const Twine &Name = "tmp"); 2607 2608 /// CreateAggTemp - Create a temporary memory object for the given 2609 /// aggregate type. 2610 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp", 2611 Address *Alloca = nullptr) { 2612 return AggValueSlot::forAddr(CreateMemTemp(T, Name, Alloca), 2613 T.getQualifiers(), 2614 AggValueSlot::IsNotDestructed, 2615 AggValueSlot::DoesNotNeedGCBarriers, 2616 AggValueSlot::IsNotAliased, 2617 AggValueSlot::DoesNotOverlap); 2618 } 2619 2620 /// Emit a cast to void* in the appropriate address space. 2621 llvm::Value *EmitCastToVoidPtr(llvm::Value *value); 2622 2623 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 2624 /// expression and compare the result against zero, returning an Int1Ty value. 2625 llvm::Value *EvaluateExprAsBool(const Expr *E); 2626 2627 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result. 2628 void EmitIgnoredExpr(const Expr *E); 2629 2630 /// EmitAnyExpr - Emit code to compute the specified expression which can have 2631 /// any type. The result is returned as an RValue struct. If this is an 2632 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where 2633 /// the result should be returned. 2634 /// 2635 /// \param ignoreResult True if the resulting value isn't used. 2636 RValue EmitAnyExpr(const Expr *E, 2637 AggValueSlot aggSlot = AggValueSlot::ignored(), 2638 bool ignoreResult = false); 2639 2640 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address 2641 // or the value of the expression, depending on how va_list is defined. 2642 Address EmitVAListRef(const Expr *E); 2643 2644 /// Emit a "reference" to a __builtin_ms_va_list; this is 2645 /// always the value of the expression, because a __builtin_ms_va_list is a 2646 /// pointer to a char. 2647 Address EmitMSVAListRef(const Expr *E); 2648 2649 /// EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will 2650 /// always be accessible even if no aggregate location is provided. 2651 RValue EmitAnyExprToTemp(const Expr *E); 2652 2653 /// EmitAnyExprToMem - Emits the code necessary to evaluate an 2654 /// arbitrary expression into the given memory location. 2655 void EmitAnyExprToMem(const Expr *E, Address Location, 2656 Qualifiers Quals, bool IsInitializer); 2657 2658 void EmitAnyExprToExn(const Expr *E, Address Addr); 2659 2660 /// EmitExprAsInit - Emits the code necessary to initialize a 2661 /// location in memory with the given initializer. 2662 void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue, 2663 bool capturedByInit); 2664 2665 /// hasVolatileMember - returns true if aggregate type has a volatile 2666 /// member. 2667 bool hasVolatileMember(QualType T) { 2668 if (const RecordType *RT = T->getAs<RecordType>()) { 2669 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl()); 2670 return RD->hasVolatileMember(); 2671 } 2672 return false; 2673 } 2674 2675 /// Determine whether a return value slot may overlap some other object. 2676 AggValueSlot::Overlap_t getOverlapForReturnValue() { 2677 // FIXME: Assuming no overlap here breaks guaranteed copy elision for base 2678 // class subobjects. These cases may need to be revisited depending on the 2679 // resolution of the relevant core issue. 2680 return AggValueSlot::DoesNotOverlap; 2681 } 2682 2683 /// Determine whether a field initialization may overlap some other object. 2684 AggValueSlot::Overlap_t getOverlapForFieldInit(const FieldDecl *FD); 2685 2686 /// Determine whether a base class initialization may overlap some other 2687 /// object. 2688 AggValueSlot::Overlap_t getOverlapForBaseInit(const CXXRecordDecl *RD, 2689 const CXXRecordDecl *BaseRD, 2690 bool IsVirtual); 2691 2692 /// Emit an aggregate assignment. 2693 void EmitAggregateAssign(LValue Dest, LValue Src, QualType EltTy) { 2694 bool IsVolatile = hasVolatileMember(EltTy); 2695 EmitAggregateCopy(Dest, Src, EltTy, AggValueSlot::MayOverlap, IsVolatile); 2696 } 2697 2698 void EmitAggregateCopyCtor(LValue Dest, LValue Src, 2699 AggValueSlot::Overlap_t MayOverlap) { 2700 EmitAggregateCopy(Dest, Src, Src.getType(), MayOverlap); 2701 } 2702 2703 /// EmitAggregateCopy - Emit an aggregate copy. 2704 /// 2705 /// \param isVolatile \c true iff either the source or the destination is 2706 /// volatile. 2707 /// \param MayOverlap Whether the tail padding of the destination might be 2708 /// occupied by some other object. More efficient code can often be 2709 /// generated if not. 2710 void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy, 2711 AggValueSlot::Overlap_t MayOverlap, 2712 bool isVolatile = false); 2713 2714 /// GetAddrOfLocalVar - Return the address of a local variable. 2715 Address GetAddrOfLocalVar(const VarDecl *VD) { 2716 auto it = LocalDeclMap.find(VD); 2717 assert(it != LocalDeclMap.end() && 2718 "Invalid argument to GetAddrOfLocalVar(), no decl!"); 2719 return it->second; 2720 } 2721 2722 /// Given an opaque value expression, return its LValue mapping if it exists, 2723 /// otherwise create one. 2724 LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e); 2725 2726 /// Given an opaque value expression, return its RValue mapping if it exists, 2727 /// otherwise create one. 2728 RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e); 2729 2730 /// Get the index of the current ArrayInitLoopExpr, if any. 2731 llvm::Value *getArrayInitIndex() { return ArrayInitIndex; } 2732 2733 /// getAccessedFieldNo - Given an encoded value and a result number, return 2734 /// the input field number being accessed. 2735 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts); 2736 2737 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L); 2738 llvm::BasicBlock *GetIndirectGotoBlock(); 2739 2740 /// Check if \p E is a C++ "this" pointer wrapped in value-preserving casts. 2741 static bool IsWrappedCXXThis(const Expr *E); 2742 2743 /// EmitNullInitialization - Generate code to set a value of the given type to 2744 /// null, If the type contains data member pointers, they will be initialized 2745 /// to -1 in accordance with the Itanium C++ ABI. 2746 void EmitNullInitialization(Address DestPtr, QualType Ty); 2747 2748 /// Emits a call to an LLVM variable-argument intrinsic, either 2749 /// \c llvm.va_start or \c llvm.va_end. 2750 /// \param ArgValue A reference to the \c va_list as emitted by either 2751 /// \c EmitVAListRef or \c EmitMSVAListRef. 2752 /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise, 2753 /// calls \c llvm.va_end. 2754 llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart); 2755 2756 /// Generate code to get an argument from the passed in pointer 2757 /// and update it accordingly. 2758 /// \param VE The \c VAArgExpr for which to generate code. 2759 /// \param VAListAddr Receives a reference to the \c va_list as emitted by 2760 /// either \c EmitVAListRef or \c EmitMSVAListRef. 2761 /// \returns A pointer to the argument. 2762 // FIXME: We should be able to get rid of this method and use the va_arg 2763 // instruction in LLVM instead once it works well enough. 2764 Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr); 2765 2766 /// emitArrayLength - Compute the length of an array, even if it's a 2767 /// VLA, and drill down to the base element type. 2768 llvm::Value *emitArrayLength(const ArrayType *arrayType, 2769 QualType &baseType, 2770 Address &addr); 2771 2772 /// EmitVLASize - Capture all the sizes for the VLA expressions in 2773 /// the given variably-modified type and store them in the VLASizeMap. 2774 /// 2775 /// This function can be called with a null (unreachable) insert point. 2776 void EmitVariablyModifiedType(QualType Ty); 2777 2778 struct VlaSizePair { 2779 llvm::Value *NumElts; 2780 QualType Type; 2781 2782 VlaSizePair(llvm::Value *NE, QualType T) : NumElts(NE), Type(T) {} 2783 }; 2784 2785 /// Return the number of elements for a single dimension 2786 /// for the given array type. 2787 VlaSizePair getVLAElements1D(const VariableArrayType *vla); 2788 VlaSizePair getVLAElements1D(QualType vla); 2789 2790 /// Returns an LLVM value that corresponds to the size, 2791 /// in non-variably-sized elements, of a variable length array type, 2792 /// plus that largest non-variably-sized element type. Assumes that 2793 /// the type has already been emitted with EmitVariablyModifiedType. 2794 VlaSizePair getVLASize(const VariableArrayType *vla); 2795 VlaSizePair getVLASize(QualType vla); 2796 2797 /// LoadCXXThis - Load the value of 'this'. This function is only valid while 2798 /// generating code for an C++ member function. 2799 llvm::Value *LoadCXXThis() { 2800 assert(CXXThisValue && "no 'this' value for this function"); 2801 return CXXThisValue; 2802 } 2803 Address LoadCXXThisAddress(); 2804 2805 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have 2806 /// virtual bases. 2807 // FIXME: Every place that calls LoadCXXVTT is something 2808 // that needs to be abstracted properly. 2809 llvm::Value *LoadCXXVTT() { 2810 assert(CXXStructorImplicitParamValue && "no VTT value for this function"); 2811 return CXXStructorImplicitParamValue; 2812 } 2813 2814 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a 2815 /// complete class to the given direct base. 2816 Address 2817 GetAddressOfDirectBaseInCompleteClass(Address Value, 2818 const CXXRecordDecl *Derived, 2819 const CXXRecordDecl *Base, 2820 bool BaseIsVirtual); 2821 2822 static bool ShouldNullCheckClassCastValue(const CastExpr *Cast); 2823 2824 /// GetAddressOfBaseClass - This function will add the necessary delta to the 2825 /// load of 'this' and returns address of the base class. 2826 Address GetAddressOfBaseClass(Address Value, 2827 const CXXRecordDecl *Derived, 2828 CastExpr::path_const_iterator PathBegin, 2829 CastExpr::path_const_iterator PathEnd, 2830 bool NullCheckValue, SourceLocation Loc); 2831 2832 Address GetAddressOfDerivedClass(Address Value, 2833 const CXXRecordDecl *Derived, 2834 CastExpr::path_const_iterator PathBegin, 2835 CastExpr::path_const_iterator PathEnd, 2836 bool NullCheckValue); 2837 2838 /// GetVTTParameter - Return the VTT parameter that should be passed to a 2839 /// base constructor/destructor with virtual bases. 2840 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move 2841 /// to ItaniumCXXABI.cpp together with all the references to VTT. 2842 llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase, 2843 bool Delegating); 2844 2845 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, 2846 CXXCtorType CtorType, 2847 const FunctionArgList &Args, 2848 SourceLocation Loc); 2849 // It's important not to confuse this and the previous function. Delegating 2850 // constructors are the C++0x feature. The constructor delegate optimization 2851 // is used to reduce duplication in the base and complete consturctors where 2852 // they are substantially the same. 2853 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor, 2854 const FunctionArgList &Args); 2855 2856 /// Emit a call to an inheriting constructor (that is, one that invokes a 2857 /// constructor inherited from a base class) by inlining its definition. This 2858 /// is necessary if the ABI does not support forwarding the arguments to the 2859 /// base class constructor (because they're variadic or similar). 2860 void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor, 2861 CXXCtorType CtorType, 2862 bool ForVirtualBase, 2863 bool Delegating, 2864 CallArgList &Args); 2865 2866 /// Emit a call to a constructor inherited from a base class, passing the 2867 /// current constructor's arguments along unmodified (without even making 2868 /// a copy). 2869 void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D, 2870 bool ForVirtualBase, Address This, 2871 bool InheritedFromVBase, 2872 const CXXInheritedCtorInitExpr *E); 2873 2874 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 2875 bool ForVirtualBase, bool Delegating, 2876 AggValueSlot ThisAVS, const CXXConstructExpr *E); 2877 2878 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 2879 bool ForVirtualBase, bool Delegating, 2880 Address This, CallArgList &Args, 2881 AggValueSlot::Overlap_t Overlap, 2882 SourceLocation Loc, bool NewPointerIsChecked); 2883 2884 /// Emit assumption load for all bases. Requires to be be called only on 2885 /// most-derived class and not under construction of the object. 2886 void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This); 2887 2888 /// Emit assumption that vptr load == global vtable. 2889 void EmitVTableAssumptionLoad(const VPtr &vptr, Address This); 2890 2891 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, 2892 Address This, Address Src, 2893 const CXXConstructExpr *E); 2894 2895 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 2896 const ArrayType *ArrayTy, 2897 Address ArrayPtr, 2898 const CXXConstructExpr *E, 2899 bool NewPointerIsChecked, 2900 bool ZeroInitialization = false); 2901 2902 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 2903 llvm::Value *NumElements, 2904 Address ArrayPtr, 2905 const CXXConstructExpr *E, 2906 bool NewPointerIsChecked, 2907 bool ZeroInitialization = false); 2908 2909 static Destroyer destroyCXXObject; 2910 2911 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, 2912 bool ForVirtualBase, bool Delegating, Address This, 2913 QualType ThisTy); 2914 2915 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType, 2916 llvm::Type *ElementTy, Address NewPtr, 2917 llvm::Value *NumElements, 2918 llvm::Value *AllocSizeWithoutCookie); 2919 2920 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType, 2921 Address Ptr); 2922 2923 void EmitSehCppScopeBegin(); 2924 void EmitSehCppScopeEnd(); 2925 void EmitSehTryScopeBegin(); 2926 void EmitSehTryScopeEnd(); 2927 2928 llvm::Value *EmitLifetimeStart(llvm::TypeSize Size, llvm::Value *Addr); 2929 void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr); 2930 2931 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E); 2932 void EmitCXXDeleteExpr(const CXXDeleteExpr *E); 2933 2934 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr, 2935 QualType DeleteTy, llvm::Value *NumElements = nullptr, 2936 CharUnits CookieSize = CharUnits()); 2937 2938 RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type, 2939 const CallExpr *TheCallExpr, bool IsDelete); 2940 2941 llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E); 2942 llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE); 2943 Address EmitCXXUuidofExpr(const CXXUuidofExpr *E); 2944 2945 /// Situations in which we might emit a check for the suitability of a 2946 /// pointer or glvalue. Needs to be kept in sync with ubsan_handlers.cpp in 2947 /// compiler-rt. 2948 enum TypeCheckKind { 2949 /// Checking the operand of a load. Must be suitably sized and aligned. 2950 TCK_Load, 2951 /// Checking the destination of a store. Must be suitably sized and aligned. 2952 TCK_Store, 2953 /// Checking the bound value in a reference binding. Must be suitably sized 2954 /// and aligned, but is not required to refer to an object (until the 2955 /// reference is used), per core issue 453. 2956 TCK_ReferenceBinding, 2957 /// Checking the object expression in a non-static data member access. Must 2958 /// be an object within its lifetime. 2959 TCK_MemberAccess, 2960 /// Checking the 'this' pointer for a call to a non-static member function. 2961 /// Must be an object within its lifetime. 2962 TCK_MemberCall, 2963 /// Checking the 'this' pointer for a constructor call. 2964 TCK_ConstructorCall, 2965 /// Checking the operand of a static_cast to a derived pointer type. Must be 2966 /// null or an object within its lifetime. 2967 TCK_DowncastPointer, 2968 /// Checking the operand of a static_cast to a derived reference type. Must 2969 /// be an object within its lifetime. 2970 TCK_DowncastReference, 2971 /// Checking the operand of a cast to a base object. Must be suitably sized 2972 /// and aligned. 2973 TCK_Upcast, 2974 /// Checking the operand of a cast to a virtual base object. Must be an 2975 /// object within its lifetime. 2976 TCK_UpcastToVirtualBase, 2977 /// Checking the value assigned to a _Nonnull pointer. Must not be null. 2978 TCK_NonnullAssign, 2979 /// Checking the operand of a dynamic_cast or a typeid expression. Must be 2980 /// null or an object within its lifetime. 2981 TCK_DynamicOperation 2982 }; 2983 2984 /// Determine whether the pointer type check \p TCK permits null pointers. 2985 static bool isNullPointerAllowed(TypeCheckKind TCK); 2986 2987 /// Determine whether the pointer type check \p TCK requires a vptr check. 2988 static bool isVptrCheckRequired(TypeCheckKind TCK, QualType Ty); 2989 2990 /// Whether any type-checking sanitizers are enabled. If \c false, 2991 /// calls to EmitTypeCheck can be skipped. 2992 bool sanitizePerformTypeCheck() const; 2993 2994 /// Emit a check that \p V is the address of storage of the 2995 /// appropriate size and alignment for an object of type \p Type 2996 /// (or if ArraySize is provided, for an array of that bound). 2997 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V, 2998 QualType Type, CharUnits Alignment = CharUnits::Zero(), 2999 SanitizerSet SkippedChecks = SanitizerSet(), 3000 llvm::Value *ArraySize = nullptr); 3001 3002 /// Emit a check that \p Base points into an array object, which 3003 /// we can access at index \p Index. \p Accessed should be \c false if we 3004 /// this expression is used as an lvalue, for instance in "&Arr[Idx]". 3005 void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index, 3006 QualType IndexType, bool Accessed); 3007 3008 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 3009 bool isInc, bool isPre); 3010 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, 3011 bool isInc, bool isPre); 3012 3013 /// Converts Location to a DebugLoc, if debug information is enabled. 3014 llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location); 3015 3016 /// Get the record field index as represented in debug info. 3017 unsigned getDebugInfoFIndex(const RecordDecl *Rec, unsigned FieldIndex); 3018 3019 3020 //===--------------------------------------------------------------------===// 3021 // Declaration Emission 3022 //===--------------------------------------------------------------------===// 3023 3024 /// EmitDecl - Emit a declaration. 3025 /// 3026 /// This function can be called with a null (unreachable) insert point. 3027 void EmitDecl(const Decl &D); 3028 3029 /// EmitVarDecl - Emit a local variable declaration. 3030 /// 3031 /// This function can be called with a null (unreachable) insert point. 3032 void EmitVarDecl(const VarDecl &D); 3033 3034 void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue, 3035 bool capturedByInit); 3036 3037 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D, 3038 llvm::Value *Address); 3039 3040 /// Determine whether the given initializer is trivial in the sense 3041 /// that it requires no code to be generated. 3042 bool isTrivialInitializer(const Expr *Init); 3043 3044 /// EmitAutoVarDecl - Emit an auto variable declaration. 3045 /// 3046 /// This function can be called with a null (unreachable) insert point. 3047 void EmitAutoVarDecl(const VarDecl &D); 3048 3049 class AutoVarEmission { 3050 friend class CodeGenFunction; 3051 3052 const VarDecl *Variable; 3053 3054 /// The address of the alloca for languages with explicit address space 3055 /// (e.g. OpenCL) or alloca casted to generic pointer for address space 3056 /// agnostic languages (e.g. C++). Invalid if the variable was emitted 3057 /// as a global constant. 3058 Address Addr; 3059 3060 llvm::Value *NRVOFlag; 3061 3062 /// True if the variable is a __block variable that is captured by an 3063 /// escaping block. 3064 bool IsEscapingByRef; 3065 3066 /// True if the variable is of aggregate type and has a constant 3067 /// initializer. 3068 bool IsConstantAggregate; 3069 3070 /// Non-null if we should use lifetime annotations. 3071 llvm::Value *SizeForLifetimeMarkers; 3072 3073 /// Address with original alloca instruction. Invalid if the variable was 3074 /// emitted as a global constant. 3075 Address AllocaAddr; 3076 3077 struct Invalid {}; 3078 AutoVarEmission(Invalid) 3079 : Variable(nullptr), Addr(Address::invalid()), 3080 AllocaAddr(Address::invalid()) {} 3081 3082 AutoVarEmission(const VarDecl &variable) 3083 : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr), 3084 IsEscapingByRef(false), IsConstantAggregate(false), 3085 SizeForLifetimeMarkers(nullptr), AllocaAddr(Address::invalid()) {} 3086 3087 bool wasEmittedAsGlobal() const { return !Addr.isValid(); } 3088 3089 public: 3090 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); } 3091 3092 bool useLifetimeMarkers() const { 3093 return SizeForLifetimeMarkers != nullptr; 3094 } 3095 llvm::Value *getSizeForLifetimeMarkers() const { 3096 assert(useLifetimeMarkers()); 3097 return SizeForLifetimeMarkers; 3098 } 3099 3100 /// Returns the raw, allocated address, which is not necessarily 3101 /// the address of the object itself. It is casted to default 3102 /// address space for address space agnostic languages. 3103 Address getAllocatedAddress() const { 3104 return Addr; 3105 } 3106 3107 /// Returns the address for the original alloca instruction. 3108 Address getOriginalAllocatedAddress() const { return AllocaAddr; } 3109 3110 /// Returns the address of the object within this declaration. 3111 /// Note that this does not chase the forwarding pointer for 3112 /// __block decls. 3113 Address getObjectAddress(CodeGenFunction &CGF) const { 3114 if (!IsEscapingByRef) return Addr; 3115 3116 return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false); 3117 } 3118 }; 3119 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var); 3120 void EmitAutoVarInit(const AutoVarEmission &emission); 3121 void EmitAutoVarCleanups(const AutoVarEmission &emission); 3122 void emitAutoVarTypeCleanup(const AutoVarEmission &emission, 3123 QualType::DestructionKind dtorKind); 3124 3125 /// Emits the alloca and debug information for the size expressions for each 3126 /// dimension of an array. It registers the association of its (1-dimensional) 3127 /// QualTypes and size expression's debug node, so that CGDebugInfo can 3128 /// reference this node when creating the DISubrange object to describe the 3129 /// array types. 3130 void EmitAndRegisterVariableArrayDimensions(CGDebugInfo *DI, 3131 const VarDecl &D, 3132 bool EmitDebugInfo); 3133 3134 void EmitStaticVarDecl(const VarDecl &D, 3135 llvm::GlobalValue::LinkageTypes Linkage); 3136 3137 class ParamValue { 3138 llvm::Value *Value; 3139 llvm::Type *ElementType; 3140 unsigned Alignment; 3141 ParamValue(llvm::Value *V, llvm::Type *T, unsigned A) 3142 : Value(V), ElementType(T), Alignment(A) {} 3143 public: 3144 static ParamValue forDirect(llvm::Value *value) { 3145 return ParamValue(value, nullptr, 0); 3146 } 3147 static ParamValue forIndirect(Address addr) { 3148 assert(!addr.getAlignment().isZero()); 3149 return ParamValue(addr.getPointer(), addr.getElementType(), 3150 addr.getAlignment().getQuantity()); 3151 } 3152 3153 bool isIndirect() const { return Alignment != 0; } 3154 llvm::Value *getAnyValue() const { return Value; } 3155 3156 llvm::Value *getDirectValue() const { 3157 assert(!isIndirect()); 3158 return Value; 3159 } 3160 3161 Address getIndirectAddress() const { 3162 assert(isIndirect()); 3163 return Address(Value, ElementType, CharUnits::fromQuantity(Alignment)); 3164 } 3165 }; 3166 3167 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl. 3168 void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo); 3169 3170 /// protectFromPeepholes - Protect a value that we're intending to 3171 /// store to the side, but which will probably be used later, from 3172 /// aggressive peepholing optimizations that might delete it. 3173 /// 3174 /// Pass the result to unprotectFromPeepholes to declare that 3175 /// protection is no longer required. 3176 /// 3177 /// There's no particular reason why this shouldn't apply to 3178 /// l-values, it's just that no existing peepholes work on pointers. 3179 PeepholeProtection protectFromPeepholes(RValue rvalue); 3180 void unprotectFromPeepholes(PeepholeProtection protection); 3181 3182 void emitAlignmentAssumptionCheck(llvm::Value *Ptr, QualType Ty, 3183 SourceLocation Loc, 3184 SourceLocation AssumptionLoc, 3185 llvm::Value *Alignment, 3186 llvm::Value *OffsetValue, 3187 llvm::Value *TheCheck, 3188 llvm::Instruction *Assumption); 3189 3190 void emitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty, 3191 SourceLocation Loc, SourceLocation AssumptionLoc, 3192 llvm::Value *Alignment, 3193 llvm::Value *OffsetValue = nullptr); 3194 3195 void emitAlignmentAssumption(llvm::Value *PtrValue, const Expr *E, 3196 SourceLocation AssumptionLoc, 3197 llvm::Value *Alignment, 3198 llvm::Value *OffsetValue = nullptr); 3199 3200 //===--------------------------------------------------------------------===// 3201 // Statement Emission 3202 //===--------------------------------------------------------------------===// 3203 3204 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info. 3205 void EmitStopPoint(const Stmt *S); 3206 3207 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call 3208 /// this function even if there is no current insertion point. 3209 /// 3210 /// This function may clear the current insertion point; callers should use 3211 /// EnsureInsertPoint if they wish to subsequently generate code without first 3212 /// calling EmitBlock, EmitBranch, or EmitStmt. 3213 void EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs = None); 3214 3215 /// EmitSimpleStmt - Try to emit a "simple" statement which does not 3216 /// necessarily require an insertion point or debug information; typically 3217 /// because the statement amounts to a jump or a container of other 3218 /// statements. 3219 /// 3220 /// \return True if the statement was handled. 3221 bool EmitSimpleStmt(const Stmt *S, ArrayRef<const Attr *> Attrs); 3222 3223 Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false, 3224 AggValueSlot AVS = AggValueSlot::ignored()); 3225 Address EmitCompoundStmtWithoutScope(const CompoundStmt &S, 3226 bool GetLast = false, 3227 AggValueSlot AVS = 3228 AggValueSlot::ignored()); 3229 3230 /// EmitLabel - Emit the block for the given label. It is legal to call this 3231 /// function even if there is no current insertion point. 3232 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt. 3233 3234 void EmitLabelStmt(const LabelStmt &S); 3235 void EmitAttributedStmt(const AttributedStmt &S); 3236 void EmitGotoStmt(const GotoStmt &S); 3237 void EmitIndirectGotoStmt(const IndirectGotoStmt &S); 3238 void EmitIfStmt(const IfStmt &S); 3239 3240 void EmitWhileStmt(const WhileStmt &S, 3241 ArrayRef<const Attr *> Attrs = None); 3242 void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None); 3243 void EmitForStmt(const ForStmt &S, 3244 ArrayRef<const Attr *> Attrs = None); 3245 void EmitReturnStmt(const ReturnStmt &S); 3246 void EmitDeclStmt(const DeclStmt &S); 3247 void EmitBreakStmt(const BreakStmt &S); 3248 void EmitContinueStmt(const ContinueStmt &S); 3249 void EmitSwitchStmt(const SwitchStmt &S); 3250 void EmitDefaultStmt(const DefaultStmt &S, ArrayRef<const Attr *> Attrs); 3251 void EmitCaseStmt(const CaseStmt &S, ArrayRef<const Attr *> Attrs); 3252 void EmitCaseStmtRange(const CaseStmt &S, ArrayRef<const Attr *> Attrs); 3253 void EmitAsmStmt(const AsmStmt &S); 3254 3255 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S); 3256 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S); 3257 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S); 3258 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S); 3259 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S); 3260 3261 void EmitCoroutineBody(const CoroutineBodyStmt &S); 3262 void EmitCoreturnStmt(const CoreturnStmt &S); 3263 RValue EmitCoawaitExpr(const CoawaitExpr &E, 3264 AggValueSlot aggSlot = AggValueSlot::ignored(), 3265 bool ignoreResult = false); 3266 LValue EmitCoawaitLValue(const CoawaitExpr *E); 3267 RValue EmitCoyieldExpr(const CoyieldExpr &E, 3268 AggValueSlot aggSlot = AggValueSlot::ignored(), 3269 bool ignoreResult = false); 3270 LValue EmitCoyieldLValue(const CoyieldExpr *E); 3271 RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID); 3272 3273 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 3274 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 3275 3276 void EmitCXXTryStmt(const CXXTryStmt &S); 3277 void EmitSEHTryStmt(const SEHTryStmt &S); 3278 void EmitSEHLeaveStmt(const SEHLeaveStmt &S); 3279 void EnterSEHTryStmt(const SEHTryStmt &S); 3280 void ExitSEHTryStmt(const SEHTryStmt &S); 3281 void VolatilizeTryBlocks(llvm::BasicBlock *BB, 3282 llvm::SmallPtrSet<llvm::BasicBlock *, 10> &V); 3283 3284 void pushSEHCleanup(CleanupKind kind, 3285 llvm::Function *FinallyFunc); 3286 void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter, 3287 const Stmt *OutlinedStmt); 3288 3289 llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF, 3290 const SEHExceptStmt &Except); 3291 3292 llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF, 3293 const SEHFinallyStmt &Finally); 3294 3295 void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF, 3296 llvm::Value *ParentFP, 3297 llvm::Value *EntryEBP); 3298 llvm::Value *EmitSEHExceptionCode(); 3299 llvm::Value *EmitSEHExceptionInfo(); 3300 llvm::Value *EmitSEHAbnormalTermination(); 3301 3302 /// Emit simple code for OpenMP directives in Simd-only mode. 3303 void EmitSimpleOMPExecutableDirective(const OMPExecutableDirective &D); 3304 3305 /// Scan the outlined statement for captures from the parent function. For 3306 /// each capture, mark the capture as escaped and emit a call to 3307 /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap. 3308 void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt, 3309 bool IsFilter); 3310 3311 /// Recovers the address of a local in a parent function. ParentVar is the 3312 /// address of the variable used in the immediate parent function. It can 3313 /// either be an alloca or a call to llvm.localrecover if there are nested 3314 /// outlined functions. ParentFP is the frame pointer of the outermost parent 3315 /// frame. 3316 Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF, 3317 Address ParentVar, 3318 llvm::Value *ParentFP); 3319 3320 void EmitCXXForRangeStmt(const CXXForRangeStmt &S, 3321 ArrayRef<const Attr *> Attrs = None); 3322 3323 /// Controls insertion of cancellation exit blocks in worksharing constructs. 3324 class OMPCancelStackRAII { 3325 CodeGenFunction &CGF; 3326 3327 public: 3328 OMPCancelStackRAII(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, 3329 bool HasCancel) 3330 : CGF(CGF) { 3331 CGF.OMPCancelStack.enter(CGF, Kind, HasCancel); 3332 } 3333 ~OMPCancelStackRAII() { CGF.OMPCancelStack.exit(CGF); } 3334 }; 3335 3336 /// Returns calculated size of the specified type. 3337 llvm::Value *getTypeSize(QualType Ty); 3338 LValue InitCapturedStruct(const CapturedStmt &S); 3339 llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K); 3340 llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S); 3341 Address GenerateCapturedStmtArgument(const CapturedStmt &S); 3342 llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S, 3343 SourceLocation Loc); 3344 void GenerateOpenMPCapturedVars(const CapturedStmt &S, 3345 SmallVectorImpl<llvm::Value *> &CapturedVars); 3346 void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy, 3347 SourceLocation Loc); 3348 /// Perform element by element copying of arrays with type \a 3349 /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure 3350 /// generated by \a CopyGen. 3351 /// 3352 /// \param DestAddr Address of the destination array. 3353 /// \param SrcAddr Address of the source array. 3354 /// \param OriginalType Type of destination and source arrays. 3355 /// \param CopyGen Copying procedure that copies value of single array element 3356 /// to another single array element. 3357 void EmitOMPAggregateAssign( 3358 Address DestAddr, Address SrcAddr, QualType OriginalType, 3359 const llvm::function_ref<void(Address, Address)> CopyGen); 3360 /// Emit proper copying of data from one variable to another. 3361 /// 3362 /// \param OriginalType Original type of the copied variables. 3363 /// \param DestAddr Destination address. 3364 /// \param SrcAddr Source address. 3365 /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has 3366 /// type of the base array element). 3367 /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of 3368 /// the base array element). 3369 /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a 3370 /// DestVD. 3371 void EmitOMPCopy(QualType OriginalType, 3372 Address DestAddr, Address SrcAddr, 3373 const VarDecl *DestVD, const VarDecl *SrcVD, 3374 const Expr *Copy); 3375 /// Emit atomic update code for constructs: \a X = \a X \a BO \a E or 3376 /// \a X = \a E \a BO \a E. 3377 /// 3378 /// \param X Value to be updated. 3379 /// \param E Update value. 3380 /// \param BO Binary operation for update operation. 3381 /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update 3382 /// expression, false otherwise. 3383 /// \param AO Atomic ordering of the generated atomic instructions. 3384 /// \param CommonGen Code generator for complex expressions that cannot be 3385 /// expressed through atomicrmw instruction. 3386 /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was 3387 /// generated, <false, RValue::get(nullptr)> otherwise. 3388 std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr( 3389 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart, 3390 llvm::AtomicOrdering AO, SourceLocation Loc, 3391 const llvm::function_ref<RValue(RValue)> CommonGen); 3392 bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D, 3393 OMPPrivateScope &PrivateScope); 3394 void EmitOMPPrivateClause(const OMPExecutableDirective &D, 3395 OMPPrivateScope &PrivateScope); 3396 void EmitOMPUseDevicePtrClause( 3397 const OMPUseDevicePtrClause &C, OMPPrivateScope &PrivateScope, 3398 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap); 3399 void EmitOMPUseDeviceAddrClause( 3400 const OMPUseDeviceAddrClause &C, OMPPrivateScope &PrivateScope, 3401 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap); 3402 /// Emit code for copyin clause in \a D directive. The next code is 3403 /// generated at the start of outlined functions for directives: 3404 /// \code 3405 /// threadprivate_var1 = master_threadprivate_var1; 3406 /// operator=(threadprivate_var2, master_threadprivate_var2); 3407 /// ... 3408 /// __kmpc_barrier(&loc, global_tid); 3409 /// \endcode 3410 /// 3411 /// \param D OpenMP directive possibly with 'copyin' clause(s). 3412 /// \returns true if at least one copyin variable is found, false otherwise. 3413 bool EmitOMPCopyinClause(const OMPExecutableDirective &D); 3414 /// Emit initial code for lastprivate variables. If some variable is 3415 /// not also firstprivate, then the default initialization is used. Otherwise 3416 /// initialization of this variable is performed by EmitOMPFirstprivateClause 3417 /// method. 3418 /// 3419 /// \param D Directive that may have 'lastprivate' directives. 3420 /// \param PrivateScope Private scope for capturing lastprivate variables for 3421 /// proper codegen in internal captured statement. 3422 /// 3423 /// \returns true if there is at least one lastprivate variable, false 3424 /// otherwise. 3425 bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D, 3426 OMPPrivateScope &PrivateScope); 3427 /// Emit final copying of lastprivate values to original variables at 3428 /// the end of the worksharing or simd directive. 3429 /// 3430 /// \param D Directive that has at least one 'lastprivate' directives. 3431 /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if 3432 /// it is the last iteration of the loop code in associated directive, or to 3433 /// 'i1 false' otherwise. If this item is nullptr, no final check is required. 3434 void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D, 3435 bool NoFinals, 3436 llvm::Value *IsLastIterCond = nullptr); 3437 /// Emit initial code for linear clauses. 3438 void EmitOMPLinearClause(const OMPLoopDirective &D, 3439 CodeGenFunction::OMPPrivateScope &PrivateScope); 3440 /// Emit final code for linear clauses. 3441 /// \param CondGen Optional conditional code for final part of codegen for 3442 /// linear clause. 3443 void EmitOMPLinearClauseFinal( 3444 const OMPLoopDirective &D, 3445 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen); 3446 /// Emit initial code for reduction variables. Creates reduction copies 3447 /// and initializes them with the values according to OpenMP standard. 3448 /// 3449 /// \param D Directive (possibly) with the 'reduction' clause. 3450 /// \param PrivateScope Private scope for capturing reduction variables for 3451 /// proper codegen in internal captured statement. 3452 /// 3453 void EmitOMPReductionClauseInit(const OMPExecutableDirective &D, 3454 OMPPrivateScope &PrivateScope, 3455 bool ForInscan = false); 3456 /// Emit final update of reduction values to original variables at 3457 /// the end of the directive. 3458 /// 3459 /// \param D Directive that has at least one 'reduction' directives. 3460 /// \param ReductionKind The kind of reduction to perform. 3461 void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D, 3462 const OpenMPDirectiveKind ReductionKind); 3463 /// Emit initial code for linear variables. Creates private copies 3464 /// and initializes them with the values according to OpenMP standard. 3465 /// 3466 /// \param D Directive (possibly) with the 'linear' clause. 3467 /// \return true if at least one linear variable is found that should be 3468 /// initialized with the value of the original variable, false otherwise. 3469 bool EmitOMPLinearClauseInit(const OMPLoopDirective &D); 3470 3471 typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/, 3472 llvm::Function * /*OutlinedFn*/, 3473 const OMPTaskDataTy & /*Data*/)> 3474 TaskGenTy; 3475 void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S, 3476 const OpenMPDirectiveKind CapturedRegion, 3477 const RegionCodeGenTy &BodyGen, 3478 const TaskGenTy &TaskGen, OMPTaskDataTy &Data); 3479 struct OMPTargetDataInfo { 3480 Address BasePointersArray = Address::invalid(); 3481 Address PointersArray = Address::invalid(); 3482 Address SizesArray = Address::invalid(); 3483 Address MappersArray = Address::invalid(); 3484 unsigned NumberOfTargetItems = 0; 3485 explicit OMPTargetDataInfo() = default; 3486 OMPTargetDataInfo(Address BasePointersArray, Address PointersArray, 3487 Address SizesArray, Address MappersArray, 3488 unsigned NumberOfTargetItems) 3489 : BasePointersArray(BasePointersArray), PointersArray(PointersArray), 3490 SizesArray(SizesArray), MappersArray(MappersArray), 3491 NumberOfTargetItems(NumberOfTargetItems) {} 3492 }; 3493 void EmitOMPTargetTaskBasedDirective(const OMPExecutableDirective &S, 3494 const RegionCodeGenTy &BodyGen, 3495 OMPTargetDataInfo &InputInfo); 3496 3497 void EmitOMPMetaDirective(const OMPMetaDirective &S); 3498 void EmitOMPParallelDirective(const OMPParallelDirective &S); 3499 void EmitOMPSimdDirective(const OMPSimdDirective &S); 3500 void EmitOMPTileDirective(const OMPTileDirective &S); 3501 void EmitOMPUnrollDirective(const OMPUnrollDirective &S); 3502 void EmitOMPForDirective(const OMPForDirective &S); 3503 void EmitOMPForSimdDirective(const OMPForSimdDirective &S); 3504 void EmitOMPSectionsDirective(const OMPSectionsDirective &S); 3505 void EmitOMPSectionDirective(const OMPSectionDirective &S); 3506 void EmitOMPSingleDirective(const OMPSingleDirective &S); 3507 void EmitOMPMasterDirective(const OMPMasterDirective &S); 3508 void EmitOMPMaskedDirective(const OMPMaskedDirective &S); 3509 void EmitOMPCriticalDirective(const OMPCriticalDirective &S); 3510 void EmitOMPParallelForDirective(const OMPParallelForDirective &S); 3511 void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S); 3512 void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S); 3513 void EmitOMPParallelMasterDirective(const OMPParallelMasterDirective &S); 3514 void EmitOMPTaskDirective(const OMPTaskDirective &S); 3515 void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S); 3516 void EmitOMPBarrierDirective(const OMPBarrierDirective &S); 3517 void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S); 3518 void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S); 3519 void EmitOMPFlushDirective(const OMPFlushDirective &S); 3520 void EmitOMPDepobjDirective(const OMPDepobjDirective &S); 3521 void EmitOMPScanDirective(const OMPScanDirective &S); 3522 void EmitOMPOrderedDirective(const OMPOrderedDirective &S); 3523 void EmitOMPAtomicDirective(const OMPAtomicDirective &S); 3524 void EmitOMPTargetDirective(const OMPTargetDirective &S); 3525 void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S); 3526 void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S); 3527 void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S); 3528 void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S); 3529 void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S); 3530 void 3531 EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S); 3532 void EmitOMPTeamsDirective(const OMPTeamsDirective &S); 3533 void 3534 EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S); 3535 void EmitOMPCancelDirective(const OMPCancelDirective &S); 3536 void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S); 3537 void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S); 3538 void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S); 3539 void EmitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective &S); 3540 void 3541 EmitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective &S); 3542 void EmitOMPParallelMasterTaskLoopDirective( 3543 const OMPParallelMasterTaskLoopDirective &S); 3544 void EmitOMPParallelMasterTaskLoopSimdDirective( 3545 const OMPParallelMasterTaskLoopSimdDirective &S); 3546 void EmitOMPDistributeDirective(const OMPDistributeDirective &S); 3547 void EmitOMPDistributeParallelForDirective( 3548 const OMPDistributeParallelForDirective &S); 3549 void EmitOMPDistributeParallelForSimdDirective( 3550 const OMPDistributeParallelForSimdDirective &S); 3551 void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S); 3552 void EmitOMPTargetParallelForSimdDirective( 3553 const OMPTargetParallelForSimdDirective &S); 3554 void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S); 3555 void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S); 3556 void 3557 EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S); 3558 void EmitOMPTeamsDistributeParallelForSimdDirective( 3559 const OMPTeamsDistributeParallelForSimdDirective &S); 3560 void EmitOMPTeamsDistributeParallelForDirective( 3561 const OMPTeamsDistributeParallelForDirective &S); 3562 void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S); 3563 void EmitOMPTargetTeamsDistributeDirective( 3564 const OMPTargetTeamsDistributeDirective &S); 3565 void EmitOMPTargetTeamsDistributeParallelForDirective( 3566 const OMPTargetTeamsDistributeParallelForDirective &S); 3567 void EmitOMPTargetTeamsDistributeParallelForSimdDirective( 3568 const OMPTargetTeamsDistributeParallelForSimdDirective &S); 3569 void EmitOMPTargetTeamsDistributeSimdDirective( 3570 const OMPTargetTeamsDistributeSimdDirective &S); 3571 void EmitOMPGenericLoopDirective(const OMPGenericLoopDirective &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 private: 4653 llvm::MDNode *getRangeForLoadFromType(QualType Ty); 4654 void EmitReturnOfRValue(RValue RV, QualType Ty); 4655 4656 void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New); 4657 4658 llvm::SmallVector<std::pair<llvm::WeakTrackingVH, llvm::Value *>, 4> 4659 DeferredReplacements; 4660 4661 /// Set the address of a local variable. 4662 void setAddrOfLocalVar(const VarDecl *VD, Address Addr) { 4663 assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!"); 4664 LocalDeclMap.insert({VD, Addr}); 4665 } 4666 4667 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty 4668 /// from function arguments into \arg Dst. See ABIArgInfo::Expand. 4669 /// 4670 /// \param AI - The first function argument of the expansion. 4671 void ExpandTypeFromArgs(QualType Ty, LValue Dst, 4672 llvm::Function::arg_iterator &AI); 4673 4674 /// ExpandTypeToArgs - Expand an CallArg \arg Arg, with the LLVM type for \arg 4675 /// Ty, into individual arguments on the provided vector \arg IRCallArgs, 4676 /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand. 4677 void ExpandTypeToArgs(QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy, 4678 SmallVectorImpl<llvm::Value *> &IRCallArgs, 4679 unsigned &IRCallArgPos); 4680 4681 llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info, 4682 const Expr *InputExpr, std::string &ConstraintStr); 4683 4684 llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info, 4685 LValue InputValue, QualType InputType, 4686 std::string &ConstraintStr, 4687 SourceLocation Loc); 4688 4689 /// Attempts to statically evaluate the object size of E. If that 4690 /// fails, emits code to figure the size of E out for us. This is 4691 /// pass_object_size aware. 4692 /// 4693 /// If EmittedExpr is non-null, this will use that instead of re-emitting E. 4694 llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type, 4695 llvm::IntegerType *ResType, 4696 llvm::Value *EmittedE, 4697 bool IsDynamic); 4698 4699 /// Emits the size of E, as required by __builtin_object_size. This 4700 /// function is aware of pass_object_size parameters, and will act accordingly 4701 /// if E is a parameter with the pass_object_size attribute. 4702 llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type, 4703 llvm::IntegerType *ResType, 4704 llvm::Value *EmittedE, 4705 bool IsDynamic); 4706 4707 void emitZeroOrPatternForAutoVarInit(QualType type, const VarDecl &D, 4708 Address Loc); 4709 4710 public: 4711 enum class EvaluationOrder { 4712 ///! No language constraints on evaluation order. 4713 Default, 4714 ///! Language semantics require left-to-right evaluation. 4715 ForceLeftToRight, 4716 ///! Language semantics require right-to-left evaluation. 4717 ForceRightToLeft 4718 }; 4719 4720 // Wrapper for function prototype sources. Wraps either a FunctionProtoType or 4721 // an ObjCMethodDecl. 4722 struct PrototypeWrapper { 4723 llvm::PointerUnion<const FunctionProtoType *, const ObjCMethodDecl *> P; 4724 4725 PrototypeWrapper(const FunctionProtoType *FT) : P(FT) {} 4726 PrototypeWrapper(const ObjCMethodDecl *MD) : P(MD) {} 4727 }; 4728 4729 void EmitCallArgs(CallArgList &Args, PrototypeWrapper Prototype, 4730 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange, 4731 AbstractCallee AC = AbstractCallee(), 4732 unsigned ParamsToSkip = 0, 4733 EvaluationOrder Order = EvaluationOrder::Default); 4734 4735 /// EmitPointerWithAlignment - Given an expression with a pointer type, 4736 /// emit the value and compute our best estimate of the alignment of the 4737 /// pointee. 4738 /// 4739 /// \param BaseInfo - If non-null, this will be initialized with 4740 /// information about the source of the alignment and the may-alias 4741 /// attribute. Note that this function will conservatively fall back on 4742 /// the type when it doesn't recognize the expression and may-alias will 4743 /// be set to false. 4744 /// 4745 /// One reasonable way to use this information is when there's a language 4746 /// guarantee that the pointer must be aligned to some stricter value, and 4747 /// we're simply trying to ensure that sufficiently obvious uses of under- 4748 /// aligned objects don't get miscompiled; for example, a placement new 4749 /// into the address of a local variable. In such a case, it's quite 4750 /// reasonable to just ignore the returned alignment when it isn't from an 4751 /// explicit source. 4752 Address EmitPointerWithAlignment(const Expr *Addr, 4753 LValueBaseInfo *BaseInfo = nullptr, 4754 TBAAAccessInfo *TBAAInfo = nullptr); 4755 4756 /// If \p E references a parameter with pass_object_size info or a constant 4757 /// array size modifier, emit the object size divided by the size of \p EltTy. 4758 /// Otherwise return null. 4759 llvm::Value *LoadPassedObjectSize(const Expr *E, QualType EltTy); 4760 4761 void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK); 4762 4763 struct MultiVersionResolverOption { 4764 llvm::Function *Function; 4765 struct Conds { 4766 StringRef Architecture; 4767 llvm::SmallVector<StringRef, 8> Features; 4768 4769 Conds(StringRef Arch, ArrayRef<StringRef> Feats) 4770 : Architecture(Arch), Features(Feats.begin(), Feats.end()) {} 4771 } Conditions; 4772 4773 MultiVersionResolverOption(llvm::Function *F, StringRef Arch, 4774 ArrayRef<StringRef> Feats) 4775 : Function(F), Conditions(Arch, Feats) {} 4776 }; 4777 4778 // Emits the body of a multiversion function's resolver. Assumes that the 4779 // options are already sorted in the proper order, with the 'default' option 4780 // last (if it exists). 4781 void EmitMultiVersionResolver(llvm::Function *Resolver, 4782 ArrayRef<MultiVersionResolverOption> Options); 4783 4784 private: 4785 QualType getVarArgType(const Expr *Arg); 4786 4787 void EmitDeclMetadata(); 4788 4789 BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType, 4790 const AutoVarEmission &emission); 4791 4792 void AddObjCARCExceptionMetadata(llvm::Instruction *Inst); 4793 4794 llvm::Value *GetValueForARMHint(unsigned BuiltinID); 4795 llvm::Value *EmitX86CpuIs(const CallExpr *E); 4796 llvm::Value *EmitX86CpuIs(StringRef CPUStr); 4797 llvm::Value *EmitX86CpuSupports(const CallExpr *E); 4798 llvm::Value *EmitX86CpuSupports(ArrayRef<StringRef> FeatureStrs); 4799 llvm::Value *EmitX86CpuSupports(uint64_t Mask); 4800 llvm::Value *EmitX86CpuInit(); 4801 llvm::Value *FormResolverCondition(const MultiVersionResolverOption &RO); 4802 }; 4803 4804 /// TargetFeatures - This class is used to check whether the builtin function 4805 /// has the required tagert specific features. It is able to support the 4806 /// combination of ','(and), '|'(or), and '()'. By default, the priority of 4807 /// ',' is higher than that of '|' . 4808 /// E.g: 4809 /// A,B|C means the builtin function requires both A and B, or C. 4810 /// If we want the builtin function requires both A and B, or both A and C, 4811 /// there are two ways: A,B|A,C or A,(B|C). 4812 /// The FeaturesList should not contain spaces, and brackets must appear in 4813 /// pairs. 4814 class TargetFeatures { 4815 struct FeatureListStatus { 4816 bool HasFeatures; 4817 StringRef CurFeaturesList; 4818 }; 4819 4820 const llvm::StringMap<bool> &CallerFeatureMap; 4821 4822 FeatureListStatus getAndFeatures(StringRef FeatureList) { 4823 int InParentheses = 0; 4824 bool HasFeatures = true; 4825 size_t SubexpressionStart = 0; 4826 for (size_t i = 0, e = FeatureList.size(); i < e; ++i) { 4827 char CurrentToken = FeatureList[i]; 4828 switch (CurrentToken) { 4829 default: 4830 break; 4831 case '(': 4832 if (InParentheses == 0) 4833 SubexpressionStart = i + 1; 4834 ++InParentheses; 4835 break; 4836 case ')': 4837 --InParentheses; 4838 assert(InParentheses >= 0 && "Parentheses are not in pair"); 4839 LLVM_FALLTHROUGH; 4840 case '|': 4841 case ',': 4842 if (InParentheses == 0) { 4843 if (HasFeatures && i != SubexpressionStart) { 4844 StringRef F = FeatureList.slice(SubexpressionStart, i); 4845 HasFeatures = CurrentToken == ')' ? hasRequiredFeatures(F) 4846 : CallerFeatureMap.lookup(F); 4847 } 4848 SubexpressionStart = i + 1; 4849 if (CurrentToken == '|') { 4850 return {HasFeatures, FeatureList.substr(SubexpressionStart)}; 4851 } 4852 } 4853 break; 4854 } 4855 } 4856 assert(InParentheses == 0 && "Parentheses are not in pair"); 4857 if (HasFeatures && SubexpressionStart != FeatureList.size()) 4858 HasFeatures = 4859 CallerFeatureMap.lookup(FeatureList.substr(SubexpressionStart)); 4860 return {HasFeatures, StringRef()}; 4861 } 4862 4863 public: 4864 bool hasRequiredFeatures(StringRef FeatureList) { 4865 FeatureListStatus FS = {false, FeatureList}; 4866 while (!FS.HasFeatures && !FS.CurFeaturesList.empty()) 4867 FS = getAndFeatures(FS.CurFeaturesList); 4868 return FS.HasFeatures; 4869 } 4870 4871 TargetFeatures(const llvm::StringMap<bool> &CallerFeatureMap) 4872 : CallerFeatureMap(CallerFeatureMap) {} 4873 }; 4874 4875 inline DominatingLLVMValue::saved_type 4876 DominatingLLVMValue::save(CodeGenFunction &CGF, llvm::Value *value) { 4877 if (!needsSaving(value)) return saved_type(value, false); 4878 4879 // Otherwise, we need an alloca. 4880 auto align = CharUnits::fromQuantity( 4881 CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType())); 4882 Address alloca = 4883 CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save"); 4884 CGF.Builder.CreateStore(value, alloca); 4885 4886 return saved_type(alloca.getPointer(), true); 4887 } 4888 4889 inline llvm::Value *DominatingLLVMValue::restore(CodeGenFunction &CGF, 4890 saved_type value) { 4891 // If the value says it wasn't saved, trust that it's still dominating. 4892 if (!value.getInt()) return value.getPointer(); 4893 4894 // Otherwise, it should be an alloca instruction, as set up in save(). 4895 auto alloca = cast<llvm::AllocaInst>(value.getPointer()); 4896 return CGF.Builder.CreateAlignedLoad(alloca->getAllocatedType(), alloca, 4897 alloca->getAlign()); 4898 } 4899 4900 } // end namespace CodeGen 4901 4902 // Map the LangOption for floating point exception behavior into 4903 // the corresponding enum in the IR. 4904 llvm::fp::ExceptionBehavior 4905 ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind); 4906 } // end namespace clang 4907 4908 #endif 4909