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