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