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