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