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