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