1 //===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This is the internal per-function state used for llvm translation. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H 15 #define LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H 16 17 #include "CGBuilder.h" 18 #include "CGDebugInfo.h" 19 #include "CGLoopInfo.h" 20 #include "CGValue.h" 21 #include "CodeGenModule.h" 22 #include "CodeGenPGO.h" 23 #include "EHScopeStack.h" 24 #include "clang/AST/CharUnits.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/ExprObjC.h" 27 #include "clang/AST/Type.h" 28 #include "clang/Basic/ABI.h" 29 #include "clang/Basic/CapturedStmt.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Frontend/CodeGenOptions.h" 32 #include "llvm/ADT/ArrayRef.h" 33 #include "llvm/ADT/DenseMap.h" 34 #include "llvm/ADT/SmallVector.h" 35 #include "llvm/IR/ValueHandle.h" 36 #include "llvm/Support/Debug.h" 37 38 namespace llvm { 39 class BasicBlock; 40 class LLVMContext; 41 class MDNode; 42 class Module; 43 class SwitchInst; 44 class Twine; 45 class Value; 46 class CallSite; 47 } 48 49 namespace clang { 50 class ASTContext; 51 class BlockDecl; 52 class CXXDestructorDecl; 53 class CXXForRangeStmt; 54 class CXXTryStmt; 55 class Decl; 56 class LabelDecl; 57 class EnumConstantDecl; 58 class FunctionDecl; 59 class FunctionProtoType; 60 class LabelStmt; 61 class ObjCContainerDecl; 62 class ObjCInterfaceDecl; 63 class ObjCIvarDecl; 64 class ObjCMethodDecl; 65 class ObjCImplementationDecl; 66 class ObjCPropertyImplDecl; 67 class TargetInfo; 68 class TargetCodeGenInfo; 69 class VarDecl; 70 class ObjCForCollectionStmt; 71 class ObjCAtTryStmt; 72 class ObjCAtThrowStmt; 73 class ObjCAtSynchronizedStmt; 74 class ObjCAutoreleasePoolStmt; 75 76 namespace CodeGen { 77 class CodeGenTypes; 78 class CGFunctionInfo; 79 class CGRecordLayout; 80 class CGBlockInfo; 81 class CGCXXABI; 82 class BlockFlags; 83 class BlockFieldFlags; 84 85 /// The kind of evaluation to perform on values of a particular 86 /// type. Basically, is the code in CGExprScalar, CGExprComplex, or 87 /// CGExprAgg? 88 /// 89 /// TODO: should vectors maybe be split out into their own thing? 90 enum TypeEvaluationKind { 91 TEK_Scalar, 92 TEK_Complex, 93 TEK_Aggregate 94 }; 95 96 class SuppressDebugLocation { 97 llvm::DebugLoc CurLoc; 98 llvm::IRBuilderBase &Builder; 99 public: 100 SuppressDebugLocation(llvm::IRBuilderBase &Builder) 101 : CurLoc(Builder.getCurrentDebugLocation()), Builder(Builder) { 102 Builder.SetCurrentDebugLocation(llvm::DebugLoc()); 103 } 104 ~SuppressDebugLocation() { 105 Builder.SetCurrentDebugLocation(CurLoc); 106 } 107 }; 108 109 /// CodeGenFunction - This class organizes the per-function state that is used 110 /// while generating LLVM code. 111 class CodeGenFunction : public CodeGenTypeCache { 112 CodeGenFunction(const CodeGenFunction &) LLVM_DELETED_FUNCTION; 113 void operator=(const CodeGenFunction &) LLVM_DELETED_FUNCTION; 114 115 friend class CGCXXABI; 116 public: 117 /// A jump destination is an abstract label, branching to which may 118 /// require a jump out through normal cleanups. 119 struct JumpDest { 120 JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {} 121 JumpDest(llvm::BasicBlock *Block, 122 EHScopeStack::stable_iterator Depth, 123 unsigned Index) 124 : Block(Block), ScopeDepth(Depth), Index(Index) {} 125 126 bool isValid() const { return Block != nullptr; } 127 llvm::BasicBlock *getBlock() const { return Block; } 128 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; } 129 unsigned getDestIndex() const { return Index; } 130 131 // This should be used cautiously. 132 void setScopeDepth(EHScopeStack::stable_iterator depth) { 133 ScopeDepth = depth; 134 } 135 136 private: 137 llvm::BasicBlock *Block; 138 EHScopeStack::stable_iterator ScopeDepth; 139 unsigned Index; 140 }; 141 142 CodeGenModule &CGM; // Per-module state. 143 const TargetInfo &Target; 144 145 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy; 146 LoopInfoStack LoopStack; 147 CGBuilderTy Builder; 148 149 /// \brief CGBuilder insert helper. This function is called after an 150 /// instruction is created using Builder. 151 void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, 152 llvm::BasicBlock *BB, 153 llvm::BasicBlock::iterator InsertPt) const; 154 155 /// CurFuncDecl - Holds the Decl for the current outermost 156 /// non-closure context. 157 const Decl *CurFuncDecl; 158 /// CurCodeDecl - This is the inner-most code context, which includes blocks. 159 const Decl *CurCodeDecl; 160 const CGFunctionInfo *CurFnInfo; 161 QualType FnRetTy; 162 llvm::Function *CurFn; 163 164 /// CurGD - The GlobalDecl for the current function being compiled. 165 GlobalDecl CurGD; 166 167 /// PrologueCleanupDepth - The cleanup depth enclosing all the 168 /// cleanups associated with the parameters. 169 EHScopeStack::stable_iterator PrologueCleanupDepth; 170 171 /// ReturnBlock - Unified return block. 172 JumpDest ReturnBlock; 173 174 /// ReturnValue - The temporary alloca to hold the return value. This is null 175 /// iff the function has no return value. 176 llvm::Value *ReturnValue; 177 178 /// AllocaInsertPoint - This is an instruction in the entry block before which 179 /// we prefer to insert allocas. 180 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt; 181 182 /// \brief API for captured statement code generation. 183 class CGCapturedStmtInfo { 184 public: 185 explicit CGCapturedStmtInfo(const CapturedStmt &S, 186 CapturedRegionKind K = CR_Default) 187 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) { 188 189 RecordDecl::field_iterator Field = 190 S.getCapturedRecordDecl()->field_begin(); 191 for (CapturedStmt::const_capture_iterator I = S.capture_begin(), 192 E = S.capture_end(); 193 I != E; ++I, ++Field) { 194 if (I->capturesThis()) 195 CXXThisFieldDecl = *Field; 196 else 197 CaptureFields[I->getCapturedVar()] = *Field; 198 } 199 } 200 201 virtual ~CGCapturedStmtInfo(); 202 203 CapturedRegionKind getKind() const { return Kind; } 204 205 void setContextValue(llvm::Value *V) { ThisValue = V; } 206 // \brief Retrieve the value of the context parameter. 207 llvm::Value *getContextValue() const { return ThisValue; } 208 209 /// \brief Lookup the captured field decl for a variable. 210 const FieldDecl *lookup(const VarDecl *VD) const { 211 return CaptureFields.lookup(VD); 212 } 213 214 bool isCXXThisExprCaptured() const { return CXXThisFieldDecl != nullptr; } 215 FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; } 216 217 /// \brief Emit the captured statement body. 218 virtual void EmitBody(CodeGenFunction &CGF, Stmt *S) { 219 RegionCounter Cnt = CGF.getPGORegionCounter(S); 220 Cnt.beginRegion(CGF.Builder); 221 CGF.EmitStmt(S); 222 } 223 224 /// \brief Get the name of the capture helper. 225 virtual StringRef getHelperName() const { return "__captured_stmt"; } 226 227 private: 228 /// \brief The kind of captured statement being generated. 229 CapturedRegionKind Kind; 230 231 /// \brief Keep the map between VarDecl and FieldDecl. 232 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields; 233 234 /// \brief The base address of the captured record, passed in as the first 235 /// argument of the parallel region function. 236 llvm::Value *ThisValue; 237 238 /// \brief Captured 'this' type. 239 FieldDecl *CXXThisFieldDecl; 240 }; 241 CGCapturedStmtInfo *CapturedStmtInfo; 242 243 /// BoundsChecking - Emit run-time bounds checks. Higher values mean 244 /// potentially higher performance penalties. 245 unsigned char BoundsChecking; 246 247 /// \brief Sanitizer options to use for this function. 248 const SanitizerOptions *SanOpts; 249 250 /// \brief True if CodeGen currently emits code implementing sanitizer checks. 251 bool IsSanitizerScope; 252 253 /// \brief RAII object to set/unset CodeGenFunction::IsSanitizerScope. 254 class SanitizerScope { 255 CodeGenFunction *CGF; 256 public: 257 SanitizerScope(CodeGenFunction *CGF); 258 ~SanitizerScope(); 259 }; 260 261 /// In C++, whether we are code generating a thunk. This controls whether we 262 /// should emit cleanups. 263 bool CurFuncIsThunk; 264 265 /// In ARC, whether we should autorelease the return value. 266 bool AutoreleaseResult; 267 268 /// Whether we processed a Microsoft-style asm block during CodeGen. These can 269 /// potentially set the return value. 270 bool SawAsmBlock; 271 272 const CodeGen::CGBlockInfo *BlockInfo; 273 llvm::Value *BlockPointer; 274 275 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 276 FieldDecl *LambdaThisCaptureField; 277 278 /// \brief A mapping from NRVO variables to the flags used to indicate 279 /// when the NRVO has been applied to this variable. 280 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags; 281 282 EHScopeStack EHStack; 283 llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack; 284 285 /// Header for data within LifetimeExtendedCleanupStack. 286 struct LifetimeExtendedCleanupHeader { 287 /// The size of the following cleanup object. 288 size_t Size : 29; 289 /// The kind of cleanup to push: a value from the CleanupKind enumeration. 290 unsigned Kind : 3; 291 292 size_t getSize() const { return Size; } 293 CleanupKind getKind() const { return static_cast<CleanupKind>(Kind); } 294 }; 295 296 /// i32s containing the indexes of the cleanup destinations. 297 llvm::AllocaInst *NormalCleanupDest; 298 299 unsigned NextCleanupDestIndex; 300 301 /// FirstBlockInfo - The head of a singly-linked-list of block layouts. 302 CGBlockInfo *FirstBlockInfo; 303 304 /// EHResumeBlock - Unified block containing a call to llvm.eh.resume. 305 llvm::BasicBlock *EHResumeBlock; 306 307 /// The exception slot. All landing pads write the current exception pointer 308 /// into this alloca. 309 llvm::Value *ExceptionSlot; 310 311 /// The selector slot. Under the MandatoryCleanup model, all landing pads 312 /// write the current selector value into this alloca. 313 llvm::AllocaInst *EHSelectorSlot; 314 315 /// Emits a landing pad for the current EH stack. 316 llvm::BasicBlock *EmitLandingPad(); 317 318 llvm::BasicBlock *getInvokeDestImpl(); 319 320 template <class T> 321 typename DominatingValue<T>::saved_type saveValueInCond(T value) { 322 return DominatingValue<T>::save(*this, value); 323 } 324 325 public: 326 /// ObjCEHValueStack - Stack of Objective-C exception values, used for 327 /// rethrows. 328 SmallVector<llvm::Value*, 8> ObjCEHValueStack; 329 330 /// A class controlling the emission of a finally block. 331 class FinallyInfo { 332 /// Where the catchall's edge through the cleanup should go. 333 JumpDest RethrowDest; 334 335 /// A function to call to enter the catch. 336 llvm::Constant *BeginCatchFn; 337 338 /// An i1 variable indicating whether or not the @finally is 339 /// running for an exception. 340 llvm::AllocaInst *ForEHVar; 341 342 /// An i8* variable into which the exception pointer to rethrow 343 /// has been saved. 344 llvm::AllocaInst *SavedExnVar; 345 346 public: 347 void enter(CodeGenFunction &CGF, const Stmt *Finally, 348 llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn, 349 llvm::Constant *rethrowFn); 350 void exit(CodeGenFunction &CGF); 351 }; 352 353 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 354 /// current full-expression. Safe against the possibility that 355 /// we're currently inside a conditionally-evaluated expression. 356 template <class T, class A0> 357 void pushFullExprCleanup(CleanupKind kind, A0 a0) { 358 // If we're not in a conditional branch, or if none of the 359 // arguments requires saving, then use the unconditional cleanup. 360 if (!isInConditionalBranch()) 361 return EHStack.pushCleanup<T>(kind, a0); 362 363 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 364 365 typedef EHScopeStack::ConditionalCleanup1<T, A0> CleanupType; 366 EHStack.pushCleanup<CleanupType>(kind, a0_saved); 367 initFullExprCleanup(); 368 } 369 370 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 371 /// current full-expression. Safe against the possibility that 372 /// we're currently inside a conditionally-evaluated expression. 373 template <class T, class A0, class A1> 374 void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1) { 375 // If we're not in a conditional branch, or if none of the 376 // arguments requires saving, then use the unconditional cleanup. 377 if (!isInConditionalBranch()) 378 return EHStack.pushCleanup<T>(kind, a0, a1); 379 380 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 381 typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1); 382 383 typedef EHScopeStack::ConditionalCleanup2<T, A0, A1> CleanupType; 384 EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved); 385 initFullExprCleanup(); 386 } 387 388 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 389 /// current full-expression. Safe against the possibility that 390 /// we're currently inside a conditionally-evaluated expression. 391 template <class T, class A0, class A1, class A2> 392 void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2) { 393 // If we're not in a conditional branch, or if none of the 394 // arguments requires saving, then use the unconditional cleanup. 395 if (!isInConditionalBranch()) { 396 return EHStack.pushCleanup<T>(kind, a0, a1, a2); 397 } 398 399 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 400 typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1); 401 typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2); 402 403 typedef EHScopeStack::ConditionalCleanup3<T, A0, A1, A2> CleanupType; 404 EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved, a2_saved); 405 initFullExprCleanup(); 406 } 407 408 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 409 /// current full-expression. Safe against the possibility that 410 /// we're currently inside a conditionally-evaluated expression. 411 template <class T, class A0, class A1, class A2, class A3> 412 void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2, A3 a3) { 413 // If we're not in a conditional branch, or if none of the 414 // arguments requires saving, then use the unconditional cleanup. 415 if (!isInConditionalBranch()) { 416 return EHStack.pushCleanup<T>(kind, a0, a1, a2, a3); 417 } 418 419 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 420 typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1); 421 typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2); 422 typename DominatingValue<A3>::saved_type a3_saved = saveValueInCond(a3); 423 424 typedef EHScopeStack::ConditionalCleanup4<T, A0, A1, A2, A3> CleanupType; 425 EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved, 426 a2_saved, a3_saved); 427 initFullExprCleanup(); 428 } 429 430 /// \brief Queue a cleanup to be pushed after finishing the current 431 /// full-expression. 432 template <class T, class A0, class A1, class A2, class A3> 433 void pushCleanupAfterFullExpr(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3) { 434 assert(!isInConditionalBranch() && "can't defer conditional cleanup"); 435 436 LifetimeExtendedCleanupHeader Header = { sizeof(T), Kind }; 437 438 size_t OldSize = LifetimeExtendedCleanupStack.size(); 439 LifetimeExtendedCleanupStack.resize( 440 LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size); 441 442 char *Buffer = &LifetimeExtendedCleanupStack[OldSize]; 443 new (Buffer) LifetimeExtendedCleanupHeader(Header); 444 new (Buffer + sizeof(Header)) T(a0, a1, a2, a3); 445 } 446 447 /// Set up the last cleaup that was pushed as a conditional 448 /// full-expression cleanup. 449 void initFullExprCleanup(); 450 451 /// PushDestructorCleanup - Push a cleanup to call the 452 /// complete-object destructor of an object of the given type at the 453 /// given address. Does nothing if T is not a C++ class type with a 454 /// non-trivial destructor. 455 void PushDestructorCleanup(QualType T, llvm::Value *Addr); 456 457 /// PushDestructorCleanup - Push a cleanup to call the 458 /// complete-object variant of the given destructor on the object at 459 /// the given address. 460 void PushDestructorCleanup(const CXXDestructorDecl *Dtor, 461 llvm::Value *Addr); 462 463 /// PopCleanupBlock - Will pop the cleanup entry on the stack and 464 /// process all branch fixups. 465 void PopCleanupBlock(bool FallThroughIsBranchThrough = false); 466 467 /// DeactivateCleanupBlock - Deactivates the given cleanup block. 468 /// The block cannot be reactivated. Pops it if it's the top of the 469 /// stack. 470 /// 471 /// \param DominatingIP - An instruction which is known to 472 /// dominate the current IP (if set) and which lies along 473 /// all paths of execution between the current IP and the 474 /// the point at which the cleanup comes into scope. 475 void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, 476 llvm::Instruction *DominatingIP); 477 478 /// ActivateCleanupBlock - Activates an initially-inactive cleanup. 479 /// Cannot be used to resurrect a deactivated cleanup. 480 /// 481 /// \param DominatingIP - An instruction which is known to 482 /// dominate the current IP (if set) and which lies along 483 /// all paths of execution between the current IP and the 484 /// the point at which the cleanup comes into scope. 485 void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, 486 llvm::Instruction *DominatingIP); 487 488 /// \brief Enters a new scope for capturing cleanups, all of which 489 /// will be executed once the scope is exited. 490 class RunCleanupsScope { 491 EHScopeStack::stable_iterator CleanupStackDepth; 492 size_t LifetimeExtendedCleanupStackSize; 493 bool OldDidCallStackSave; 494 protected: 495 bool PerformCleanup; 496 private: 497 498 RunCleanupsScope(const RunCleanupsScope &) LLVM_DELETED_FUNCTION; 499 void operator=(const RunCleanupsScope &) LLVM_DELETED_FUNCTION; 500 501 protected: 502 CodeGenFunction& CGF; 503 504 public: 505 /// \brief Enter a new cleanup scope. 506 explicit RunCleanupsScope(CodeGenFunction &CGF) 507 : PerformCleanup(true), CGF(CGF) 508 { 509 CleanupStackDepth = CGF.EHStack.stable_begin(); 510 LifetimeExtendedCleanupStackSize = 511 CGF.LifetimeExtendedCleanupStack.size(); 512 OldDidCallStackSave = CGF.DidCallStackSave; 513 CGF.DidCallStackSave = false; 514 } 515 516 /// \brief Exit this cleanup scope, emitting any accumulated 517 /// cleanups. 518 ~RunCleanupsScope() { 519 if (PerformCleanup) { 520 CGF.DidCallStackSave = OldDidCallStackSave; 521 CGF.PopCleanupBlocks(CleanupStackDepth, 522 LifetimeExtendedCleanupStackSize); 523 } 524 } 525 526 /// \brief Determine whether this scope requires any cleanups. 527 bool requiresCleanups() const { 528 return CGF.EHStack.stable_begin() != CleanupStackDepth; 529 } 530 531 /// \brief Force the emission of cleanups now, instead of waiting 532 /// until this object is destroyed. 533 void ForceCleanup() { 534 assert(PerformCleanup && "Already forced cleanup"); 535 CGF.DidCallStackSave = OldDidCallStackSave; 536 CGF.PopCleanupBlocks(CleanupStackDepth, 537 LifetimeExtendedCleanupStackSize); 538 PerformCleanup = false; 539 } 540 }; 541 542 class LexicalScope : public RunCleanupsScope { 543 SourceRange Range; 544 SmallVector<const LabelDecl*, 4> Labels; 545 LexicalScope *ParentScope; 546 547 LexicalScope(const LexicalScope &) LLVM_DELETED_FUNCTION; 548 void operator=(const LexicalScope &) LLVM_DELETED_FUNCTION; 549 550 public: 551 /// \brief Enter a new cleanup scope. 552 explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range) 553 : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) { 554 CGF.CurLexicalScope = this; 555 if (CGDebugInfo *DI = CGF.getDebugInfo()) 556 DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin()); 557 } 558 559 void addLabel(const LabelDecl *label) { 560 assert(PerformCleanup && "adding label to dead scope?"); 561 Labels.push_back(label); 562 } 563 564 /// \brief Exit this cleanup scope, emitting any accumulated 565 /// cleanups. 566 ~LexicalScope() { 567 if (CGDebugInfo *DI = CGF.getDebugInfo()) 568 DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd()); 569 570 // If we should perform a cleanup, force them now. Note that 571 // this ends the cleanup scope before rescoping any labels. 572 if (PerformCleanup) ForceCleanup(); 573 } 574 575 /// \brief Force the emission of cleanups now, instead of waiting 576 /// until this object is destroyed. 577 void ForceCleanup() { 578 CGF.CurLexicalScope = ParentScope; 579 RunCleanupsScope::ForceCleanup(); 580 581 if (!Labels.empty()) 582 rescopeLabels(); 583 } 584 585 void rescopeLabels(); 586 }; 587 588 589 /// \brief Takes the old cleanup stack size and emits the cleanup blocks 590 /// that have been added. 591 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize); 592 593 /// \brief Takes the old cleanup stack size and emits the cleanup blocks 594 /// that have been added, then adds all lifetime-extended cleanups from 595 /// the given position to the stack. 596 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize, 597 size_t OldLifetimeExtendedStackSize); 598 599 void ResolveBranchFixups(llvm::BasicBlock *Target); 600 601 /// The given basic block lies in the current EH scope, but may be a 602 /// target of a potentially scope-crossing jump; get a stable handle 603 /// to which we can perform this jump later. 604 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) { 605 return JumpDest(Target, 606 EHStack.getInnermostNormalCleanup(), 607 NextCleanupDestIndex++); 608 } 609 610 /// The given basic block lies in the current EH scope, but may be a 611 /// target of a potentially scope-crossing jump; get a stable handle 612 /// to which we can perform this jump later. 613 JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) { 614 return getJumpDestInCurrentScope(createBasicBlock(Name)); 615 } 616 617 /// EmitBranchThroughCleanup - Emit a branch from the current insert 618 /// block through the normal cleanup handling code (if any) and then 619 /// on to \arg Dest. 620 void EmitBranchThroughCleanup(JumpDest Dest); 621 622 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the 623 /// specified destination obviously has no cleanups to run. 'false' is always 624 /// a conservatively correct answer for this method. 625 bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const; 626 627 /// popCatchScope - Pops the catch scope at the top of the EHScope 628 /// stack, emitting any required code (other than the catch handlers 629 /// themselves). 630 void popCatchScope(); 631 632 llvm::BasicBlock *getEHResumeBlock(bool isCleanup); 633 llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope); 634 635 /// An object to manage conditionally-evaluated expressions. 636 class ConditionalEvaluation { 637 llvm::BasicBlock *StartBB; 638 639 public: 640 ConditionalEvaluation(CodeGenFunction &CGF) 641 : StartBB(CGF.Builder.GetInsertBlock()) {} 642 643 void begin(CodeGenFunction &CGF) { 644 assert(CGF.OutermostConditional != this); 645 if (!CGF.OutermostConditional) 646 CGF.OutermostConditional = this; 647 } 648 649 void end(CodeGenFunction &CGF) { 650 assert(CGF.OutermostConditional != nullptr); 651 if (CGF.OutermostConditional == this) 652 CGF.OutermostConditional = nullptr; 653 } 654 655 /// Returns a block which will be executed prior to each 656 /// evaluation of the conditional code. 657 llvm::BasicBlock *getStartingBlock() const { 658 return StartBB; 659 } 660 }; 661 662 /// isInConditionalBranch - Return true if we're currently emitting 663 /// one branch or the other of a conditional expression. 664 bool isInConditionalBranch() const { return OutermostConditional != nullptr; } 665 666 void setBeforeOutermostConditional(llvm::Value *value, llvm::Value *addr) { 667 assert(isInConditionalBranch()); 668 llvm::BasicBlock *block = OutermostConditional->getStartingBlock(); 669 new llvm::StoreInst(value, addr, &block->back()); 670 } 671 672 /// An RAII object to record that we're evaluating a statement 673 /// expression. 674 class StmtExprEvaluation { 675 CodeGenFunction &CGF; 676 677 /// We have to save the outermost conditional: cleanups in a 678 /// statement expression aren't conditional just because the 679 /// StmtExpr is. 680 ConditionalEvaluation *SavedOutermostConditional; 681 682 public: 683 StmtExprEvaluation(CodeGenFunction &CGF) 684 : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) { 685 CGF.OutermostConditional = nullptr; 686 } 687 688 ~StmtExprEvaluation() { 689 CGF.OutermostConditional = SavedOutermostConditional; 690 CGF.EnsureInsertPoint(); 691 } 692 }; 693 694 /// An object which temporarily prevents a value from being 695 /// destroyed by aggressive peephole optimizations that assume that 696 /// all uses of a value have been realized in the IR. 697 class PeepholeProtection { 698 llvm::Instruction *Inst; 699 friend class CodeGenFunction; 700 701 public: 702 PeepholeProtection() : Inst(nullptr) {} 703 }; 704 705 /// A non-RAII class containing all the information about a bound 706 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for 707 /// this which makes individual mappings very simple; using this 708 /// class directly is useful when you have a variable number of 709 /// opaque values or don't want the RAII functionality for some 710 /// reason. 711 class OpaqueValueMappingData { 712 const OpaqueValueExpr *OpaqueValue; 713 bool BoundLValue; 714 CodeGenFunction::PeepholeProtection Protection; 715 716 OpaqueValueMappingData(const OpaqueValueExpr *ov, 717 bool boundLValue) 718 : OpaqueValue(ov), BoundLValue(boundLValue) {} 719 public: 720 OpaqueValueMappingData() : OpaqueValue(nullptr) {} 721 722 static bool shouldBindAsLValue(const Expr *expr) { 723 // gl-values should be bound as l-values for obvious reasons. 724 // Records should be bound as l-values because IR generation 725 // always keeps them in memory. Expressions of function type 726 // act exactly like l-values but are formally required to be 727 // r-values in C. 728 return expr->isGLValue() || 729 expr->getType()->isFunctionType() || 730 hasAggregateEvaluationKind(expr->getType()); 731 } 732 733 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 734 const OpaqueValueExpr *ov, 735 const Expr *e) { 736 if (shouldBindAsLValue(ov)) 737 return bind(CGF, ov, CGF.EmitLValue(e)); 738 return bind(CGF, ov, CGF.EmitAnyExpr(e)); 739 } 740 741 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 742 const OpaqueValueExpr *ov, 743 const LValue &lv) { 744 assert(shouldBindAsLValue(ov)); 745 CGF.OpaqueLValues.insert(std::make_pair(ov, lv)); 746 return OpaqueValueMappingData(ov, true); 747 } 748 749 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 750 const OpaqueValueExpr *ov, 751 const RValue &rv) { 752 assert(!shouldBindAsLValue(ov)); 753 CGF.OpaqueRValues.insert(std::make_pair(ov, rv)); 754 755 OpaqueValueMappingData data(ov, false); 756 757 // Work around an extremely aggressive peephole optimization in 758 // EmitScalarConversion which assumes that all other uses of a 759 // value are extant. 760 data.Protection = CGF.protectFromPeepholes(rv); 761 762 return data; 763 } 764 765 bool isValid() const { return OpaqueValue != nullptr; } 766 void clear() { OpaqueValue = nullptr; } 767 768 void unbind(CodeGenFunction &CGF) { 769 assert(OpaqueValue && "no data to unbind!"); 770 771 if (BoundLValue) { 772 CGF.OpaqueLValues.erase(OpaqueValue); 773 } else { 774 CGF.OpaqueRValues.erase(OpaqueValue); 775 CGF.unprotectFromPeepholes(Protection); 776 } 777 } 778 }; 779 780 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr. 781 class OpaqueValueMapping { 782 CodeGenFunction &CGF; 783 OpaqueValueMappingData Data; 784 785 public: 786 static bool shouldBindAsLValue(const Expr *expr) { 787 return OpaqueValueMappingData::shouldBindAsLValue(expr); 788 } 789 790 /// Build the opaque value mapping for the given conditional 791 /// operator if it's the GNU ?: extension. This is a common 792 /// enough pattern that the convenience operator is really 793 /// helpful. 794 /// 795 OpaqueValueMapping(CodeGenFunction &CGF, 796 const AbstractConditionalOperator *op) : CGF(CGF) { 797 if (isa<ConditionalOperator>(op)) 798 // Leave Data empty. 799 return; 800 801 const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op); 802 Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(), 803 e->getCommon()); 804 } 805 806 OpaqueValueMapping(CodeGenFunction &CGF, 807 const OpaqueValueExpr *opaqueValue, 808 LValue lvalue) 809 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) { 810 } 811 812 OpaqueValueMapping(CodeGenFunction &CGF, 813 const OpaqueValueExpr *opaqueValue, 814 RValue rvalue) 815 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) { 816 } 817 818 void pop() { 819 Data.unbind(CGF); 820 Data.clear(); 821 } 822 823 ~OpaqueValueMapping() { 824 if (Data.isValid()) Data.unbind(CGF); 825 } 826 }; 827 828 /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field 829 /// number that holds the value. 830 unsigned getByRefValueLLVMField(const ValueDecl *VD) const; 831 832 /// BuildBlockByrefAddress - Computes address location of the 833 /// variable which is declared as __block. 834 llvm::Value *BuildBlockByrefAddress(llvm::Value *BaseAddr, 835 const VarDecl *V); 836 private: 837 CGDebugInfo *DebugInfo; 838 bool DisableDebugInfo; 839 840 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid 841 /// calling llvm.stacksave for multiple VLAs in the same scope. 842 bool DidCallStackSave; 843 844 /// IndirectBranch - The first time an indirect goto is seen we create a block 845 /// with an indirect branch. Every time we see the address of a label taken, 846 /// we add the label to the indirect goto. Every subsequent indirect goto is 847 /// codegen'd as a jump to the IndirectBranch's basic block. 848 llvm::IndirectBrInst *IndirectBranch; 849 850 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C 851 /// decls. 852 typedef llvm::DenseMap<const Decl*, llvm::Value*> DeclMapTy; 853 DeclMapTy LocalDeclMap; 854 855 /// LabelMap - This keeps track of the LLVM basic block for each C label. 856 llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap; 857 858 // BreakContinueStack - This keeps track of where break and continue 859 // statements should jump to. 860 struct BreakContinue { 861 BreakContinue(JumpDest Break, JumpDest Continue) 862 : BreakBlock(Break), ContinueBlock(Continue) {} 863 864 JumpDest BreakBlock; 865 JumpDest ContinueBlock; 866 }; 867 SmallVector<BreakContinue, 8> BreakContinueStack; 868 869 CodeGenPGO PGO; 870 871 public: 872 /// Get a counter for instrumentation of the region associated with the given 873 /// statement. 874 RegionCounter getPGORegionCounter(const Stmt *S) { 875 return RegionCounter(PGO, S); 876 } 877 private: 878 879 /// SwitchInsn - This is nearest current switch instruction. It is null if 880 /// current context is not in a switch. 881 llvm::SwitchInst *SwitchInsn; 882 /// The branch weights of SwitchInsn when doing instrumentation based PGO. 883 SmallVector<uint64_t, 16> *SwitchWeights; 884 885 /// CaseRangeBlock - This block holds if condition check for last case 886 /// statement range in current switch instruction. 887 llvm::BasicBlock *CaseRangeBlock; 888 889 /// OpaqueLValues - Keeps track of the current set of opaque value 890 /// expressions. 891 llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues; 892 llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues; 893 894 // VLASizeMap - This keeps track of the associated size for each VLA type. 895 // We track this by the size expression rather than the type itself because 896 // in certain situations, like a const qualifier applied to an VLA typedef, 897 // multiple VLA types can share the same size expression. 898 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we 899 // enter/leave scopes. 900 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap; 901 902 /// A block containing a single 'unreachable' instruction. Created 903 /// lazily by getUnreachableBlock(). 904 llvm::BasicBlock *UnreachableBlock; 905 906 /// Counts of the number return expressions in the function. 907 unsigned NumReturnExprs; 908 909 /// Count the number of simple (constant) return expressions in the function. 910 unsigned NumSimpleReturnExprs; 911 912 /// The last regular (non-return) debug location (breakpoint) in the function. 913 SourceLocation LastStopPoint; 914 915 public: 916 /// A scope within which we are constructing the fields of an object which 917 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use 918 /// if we need to evaluate a CXXDefaultInitExpr within the evaluation. 919 class FieldConstructionScope { 920 public: 921 FieldConstructionScope(CodeGenFunction &CGF, llvm::Value *This) 922 : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) { 923 CGF.CXXDefaultInitExprThis = This; 924 } 925 ~FieldConstructionScope() { 926 CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis; 927 } 928 929 private: 930 CodeGenFunction &CGF; 931 llvm::Value *OldCXXDefaultInitExprThis; 932 }; 933 934 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this' 935 /// is overridden to be the object under construction. 936 class CXXDefaultInitExprScope { 937 public: 938 CXXDefaultInitExprScope(CodeGenFunction &CGF) 939 : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue) { 940 CGF.CXXThisValue = CGF.CXXDefaultInitExprThis; 941 } 942 ~CXXDefaultInitExprScope() { 943 CGF.CXXThisValue = OldCXXThisValue; 944 } 945 946 public: 947 CodeGenFunction &CGF; 948 llvm::Value *OldCXXThisValue; 949 }; 950 951 private: 952 /// CXXThisDecl - When generating code for a C++ member function, 953 /// this will hold the implicit 'this' declaration. 954 ImplicitParamDecl *CXXABIThisDecl; 955 llvm::Value *CXXABIThisValue; 956 llvm::Value *CXXThisValue; 957 958 /// The value of 'this' to use when evaluating CXXDefaultInitExprs within 959 /// this expression. 960 llvm::Value *CXXDefaultInitExprThis; 961 962 /// CXXStructorImplicitParamDecl - When generating code for a constructor or 963 /// destructor, this will hold the implicit argument (e.g. VTT). 964 ImplicitParamDecl *CXXStructorImplicitParamDecl; 965 llvm::Value *CXXStructorImplicitParamValue; 966 967 /// OutermostConditional - Points to the outermost active 968 /// conditional control. This is used so that we know if a 969 /// temporary should be destroyed conditionally. 970 ConditionalEvaluation *OutermostConditional; 971 972 /// The current lexical scope. 973 LexicalScope *CurLexicalScope; 974 975 /// The current source location that should be used for exception 976 /// handling code. 977 SourceLocation CurEHLocation; 978 979 /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM 980 /// type as well as the field number that contains the actual data. 981 llvm::DenseMap<const ValueDecl *, std::pair<llvm::Type *, 982 unsigned> > ByRefValueInfo; 983 984 llvm::BasicBlock *TerminateLandingPad; 985 llvm::BasicBlock *TerminateHandler; 986 llvm::BasicBlock *TrapBB; 987 988 /// Add a kernel metadata node to the named metadata node 'opencl.kernels'. 989 /// In the kernel metadata node, reference the kernel function and metadata 990 /// nodes for its optional attribute qualifiers (OpenCL 1.1 6.7.2): 991 /// - A node for the vec_type_hint(<type>) qualifier contains string 992 /// "vec_type_hint", an undefined value of the <type> data type, 993 /// and a Boolean that is true if the <type> is integer and signed. 994 /// - A node for the work_group_size_hint(X,Y,Z) qualifier contains string 995 /// "work_group_size_hint", and three 32-bit integers X, Y and Z. 996 /// - A node for the reqd_work_group_size(X,Y,Z) qualifier contains string 997 /// "reqd_work_group_size", and three 32-bit integers X, Y and Z. 998 void EmitOpenCLKernelMetadata(const FunctionDecl *FD, 999 llvm::Function *Fn); 1000 1001 public: 1002 CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false); 1003 ~CodeGenFunction(); 1004 1005 CodeGenTypes &getTypes() const { return CGM.getTypes(); } 1006 ASTContext &getContext() const { return CGM.getContext(); } 1007 CGDebugInfo *getDebugInfo() { 1008 if (DisableDebugInfo) 1009 return nullptr; 1010 return DebugInfo; 1011 } 1012 void disableDebugInfo() { DisableDebugInfo = true; } 1013 void enableDebugInfo() { DisableDebugInfo = false; } 1014 1015 bool shouldUseFusedARCCalls() { 1016 return CGM.getCodeGenOpts().OptimizationLevel == 0; 1017 } 1018 1019 const LangOptions &getLangOpts() const { return CGM.getLangOpts(); } 1020 1021 /// Returns a pointer to the function's exception object and selector slot, 1022 /// which is assigned in every landing pad. 1023 llvm::Value *getExceptionSlot(); 1024 llvm::Value *getEHSelectorSlot(); 1025 1026 /// Returns the contents of the function's exception object and selector 1027 /// slots. 1028 llvm::Value *getExceptionFromSlot(); 1029 llvm::Value *getSelectorFromSlot(); 1030 1031 llvm::Value *getNormalCleanupDestSlot(); 1032 1033 llvm::BasicBlock *getUnreachableBlock() { 1034 if (!UnreachableBlock) { 1035 UnreachableBlock = createBasicBlock("unreachable"); 1036 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock); 1037 } 1038 return UnreachableBlock; 1039 } 1040 1041 llvm::BasicBlock *getInvokeDest() { 1042 if (!EHStack.requiresLandingPad()) return nullptr; 1043 return getInvokeDestImpl(); 1044 } 1045 1046 const TargetInfo &getTarget() const { return Target; } 1047 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); } 1048 1049 //===--------------------------------------------------------------------===// 1050 // Cleanups 1051 //===--------------------------------------------------------------------===// 1052 1053 typedef void Destroyer(CodeGenFunction &CGF, llvm::Value *addr, QualType ty); 1054 1055 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, 1056 llvm::Value *arrayEndPointer, 1057 QualType elementType, 1058 Destroyer *destroyer); 1059 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, 1060 llvm::Value *arrayEnd, 1061 QualType elementType, 1062 Destroyer *destroyer); 1063 1064 void pushDestroy(QualType::DestructionKind dtorKind, 1065 llvm::Value *addr, QualType type); 1066 void pushEHDestroy(QualType::DestructionKind dtorKind, 1067 llvm::Value *addr, QualType type); 1068 void pushDestroy(CleanupKind kind, llvm::Value *addr, QualType type, 1069 Destroyer *destroyer, bool useEHCleanupForArray); 1070 void pushLifetimeExtendedDestroy(CleanupKind kind, llvm::Value *addr, 1071 QualType type, Destroyer *destroyer, 1072 bool useEHCleanupForArray); 1073 void pushStackRestore(CleanupKind kind, llvm::Value *SPMem); 1074 void emitDestroy(llvm::Value *addr, QualType type, Destroyer *destroyer, 1075 bool useEHCleanupForArray); 1076 llvm::Function *generateDestroyHelper(llvm::Constant *addr, QualType type, 1077 Destroyer *destroyer, 1078 bool useEHCleanupForArray, 1079 const VarDecl *VD); 1080 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end, 1081 QualType type, Destroyer *destroyer, 1082 bool checkZeroLength, bool useEHCleanup); 1083 1084 Destroyer *getDestroyer(QualType::DestructionKind destructionKind); 1085 1086 /// Determines whether an EH cleanup is required to destroy a type 1087 /// with the given destruction kind. 1088 bool needsEHCleanup(QualType::DestructionKind kind) { 1089 switch (kind) { 1090 case QualType::DK_none: 1091 return false; 1092 case QualType::DK_cxx_destructor: 1093 case QualType::DK_objc_weak_lifetime: 1094 return getLangOpts().Exceptions; 1095 case QualType::DK_objc_strong_lifetime: 1096 return getLangOpts().Exceptions && 1097 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions; 1098 } 1099 llvm_unreachable("bad destruction kind"); 1100 } 1101 1102 CleanupKind getCleanupKind(QualType::DestructionKind kind) { 1103 return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup); 1104 } 1105 1106 //===--------------------------------------------------------------------===// 1107 // Objective-C 1108 //===--------------------------------------------------------------------===// 1109 1110 void GenerateObjCMethod(const ObjCMethodDecl *OMD); 1111 1112 void StartObjCMethod(const ObjCMethodDecl *MD, 1113 const ObjCContainerDecl *CD, 1114 SourceLocation StartLoc); 1115 1116 /// GenerateObjCGetter - Synthesize an Objective-C property getter function. 1117 void GenerateObjCGetter(ObjCImplementationDecl *IMP, 1118 const ObjCPropertyImplDecl *PID); 1119 void generateObjCGetterBody(const ObjCImplementationDecl *classImpl, 1120 const ObjCPropertyImplDecl *propImpl, 1121 const ObjCMethodDecl *GetterMothodDecl, 1122 llvm::Constant *AtomicHelperFn); 1123 1124 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, 1125 ObjCMethodDecl *MD, bool ctor); 1126 1127 /// GenerateObjCSetter - Synthesize an Objective-C property setter function 1128 /// for the given property. 1129 void GenerateObjCSetter(ObjCImplementationDecl *IMP, 1130 const ObjCPropertyImplDecl *PID); 1131 void generateObjCSetterBody(const ObjCImplementationDecl *classImpl, 1132 const ObjCPropertyImplDecl *propImpl, 1133 llvm::Constant *AtomicHelperFn); 1134 bool IndirectObjCSetterArg(const CGFunctionInfo &FI); 1135 bool IvarTypeWithAggrGCObjects(QualType Ty); 1136 1137 //===--------------------------------------------------------------------===// 1138 // Block Bits 1139 //===--------------------------------------------------------------------===// 1140 1141 llvm::Value *EmitBlockLiteral(const BlockExpr *); 1142 llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info); 1143 static void destroyBlockInfos(CGBlockInfo *info); 1144 llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *, 1145 const CGBlockInfo &Info, 1146 llvm::StructType *, 1147 llvm::Constant *BlockVarLayout); 1148 1149 llvm::Function *GenerateBlockFunction(GlobalDecl GD, 1150 const CGBlockInfo &Info, 1151 const DeclMapTy &ldm, 1152 bool IsLambdaConversionToBlock); 1153 1154 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo); 1155 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo); 1156 llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction( 1157 const ObjCPropertyImplDecl *PID); 1158 llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction( 1159 const ObjCPropertyImplDecl *PID); 1160 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty); 1161 1162 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags); 1163 1164 class AutoVarEmission; 1165 1166 void emitByrefStructureInit(const AutoVarEmission &emission); 1167 void enterByrefCleanup(const AutoVarEmission &emission); 1168 1169 llvm::Value *LoadBlockStruct() { 1170 assert(BlockPointer && "no block pointer set!"); 1171 return BlockPointer; 1172 } 1173 1174 void AllocateBlockCXXThisPointer(const CXXThisExpr *E); 1175 void AllocateBlockDecl(const DeclRefExpr *E); 1176 llvm::Value *GetAddrOfBlockDecl(const VarDecl *var, bool ByRef); 1177 llvm::Type *BuildByRefType(const VarDecl *var); 1178 1179 void GenerateCode(GlobalDecl GD, llvm::Function *Fn, 1180 const CGFunctionInfo &FnInfo); 1181 /// \brief Emit code for the start of a function. 1182 /// \param Loc The location to be associated with the function. 1183 /// \param StartLoc The location of the function body. 1184 void StartFunction(GlobalDecl GD, 1185 QualType RetTy, 1186 llvm::Function *Fn, 1187 const CGFunctionInfo &FnInfo, 1188 const FunctionArgList &Args, 1189 SourceLocation Loc = SourceLocation(), 1190 SourceLocation StartLoc = SourceLocation()); 1191 1192 void EmitConstructorBody(FunctionArgList &Args); 1193 void EmitDestructorBody(FunctionArgList &Args); 1194 void emitImplicitAssignmentOperatorBody(FunctionArgList &Args); 1195 void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body); 1196 void EmitBlockWithFallThrough(llvm::BasicBlock *BB, RegionCounter &Cnt); 1197 1198 void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator, 1199 CallArgList &CallArgs); 1200 void EmitLambdaToBlockPointerBody(FunctionArgList &Args); 1201 void EmitLambdaBlockInvokeBody(); 1202 void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD); 1203 void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD); 1204 1205 /// EmitReturnBlock - Emit the unified return block, trying to avoid its 1206 /// emission when possible. 1207 void EmitReturnBlock(); 1208 1209 /// FinishFunction - Complete IR generation of the current function. It is 1210 /// legal to call this function even if there is no current insertion point. 1211 void FinishFunction(SourceLocation EndLoc=SourceLocation()); 1212 1213 void StartThunk(llvm::Function *Fn, GlobalDecl GD, const CGFunctionInfo &FnInfo); 1214 1215 void EmitCallAndReturnForThunk(llvm::Value *Callee, const ThunkInfo *Thunk); 1216 1217 /// Emit a musttail call for a thunk with a potentially adjusted this pointer. 1218 void EmitMustTailThunk(const CXXMethodDecl *MD, llvm::Value *AdjustedThisPtr, 1219 llvm::Value *Callee); 1220 1221 /// GenerateThunk - Generate a thunk for the given method. 1222 void GenerateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, 1223 GlobalDecl GD, const ThunkInfo &Thunk); 1224 1225 void GenerateVarArgsThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, 1226 GlobalDecl GD, const ThunkInfo &Thunk); 1227 1228 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type, 1229 FunctionArgList &Args); 1230 1231 void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init, 1232 ArrayRef<VarDecl *> ArrayIndexes); 1233 1234 /// InitializeVTablePointer - Initialize the vtable pointer of the given 1235 /// subobject. 1236 /// 1237 void InitializeVTablePointer(BaseSubobject Base, 1238 const CXXRecordDecl *NearestVBase, 1239 CharUnits OffsetFromNearestVBase, 1240 const CXXRecordDecl *VTableClass); 1241 1242 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy; 1243 void InitializeVTablePointers(BaseSubobject Base, 1244 const CXXRecordDecl *NearestVBase, 1245 CharUnits OffsetFromNearestVBase, 1246 bool BaseIsNonVirtualPrimaryBase, 1247 const CXXRecordDecl *VTableClass, 1248 VisitedVirtualBasesSetTy& VBases); 1249 1250 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl); 1251 1252 /// GetVTablePtr - Return the Value of the vtable pointer member pointed 1253 /// to by This. 1254 llvm::Value *GetVTablePtr(llvm::Value *This, llvm::Type *Ty); 1255 1256 1257 /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given 1258 /// expr can be devirtualized. 1259 bool CanDevirtualizeMemberFunctionCall(const Expr *Base, 1260 const CXXMethodDecl *MD); 1261 1262 /// EnterDtorCleanups - Enter the cleanups necessary to complete the 1263 /// given phase of destruction for a destructor. The end result 1264 /// should call destructors on members and base classes in reverse 1265 /// order of their construction. 1266 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type); 1267 1268 /// ShouldInstrumentFunction - Return true if the current function should be 1269 /// instrumented with __cyg_profile_func_* calls 1270 bool ShouldInstrumentFunction(); 1271 1272 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified 1273 /// instrumentation function with the current function and the call site, if 1274 /// function instrumentation is enabled. 1275 void EmitFunctionInstrumentation(const char *Fn); 1276 1277 /// EmitMCountInstrumentation - Emit call to .mcount. 1278 void EmitMCountInstrumentation(); 1279 1280 /// EmitFunctionProlog - Emit the target specific LLVM code to load the 1281 /// arguments for the given function. This is also responsible for naming the 1282 /// LLVM function arguments. 1283 void EmitFunctionProlog(const CGFunctionInfo &FI, 1284 llvm::Function *Fn, 1285 const FunctionArgList &Args); 1286 1287 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the 1288 /// given temporary. 1289 void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc, 1290 SourceLocation EndLoc); 1291 1292 /// EmitStartEHSpec - Emit the start of the exception spec. 1293 void EmitStartEHSpec(const Decl *D); 1294 1295 /// EmitEndEHSpec - Emit the end of the exception spec. 1296 void EmitEndEHSpec(const Decl *D); 1297 1298 /// getTerminateLandingPad - Return a landing pad that just calls terminate. 1299 llvm::BasicBlock *getTerminateLandingPad(); 1300 1301 /// getTerminateHandler - Return a handler (not a landing pad, just 1302 /// a catch handler) that just calls terminate. This is used when 1303 /// a terminate scope encloses a try. 1304 llvm::BasicBlock *getTerminateHandler(); 1305 1306 llvm::Type *ConvertTypeForMem(QualType T); 1307 llvm::Type *ConvertType(QualType T); 1308 llvm::Type *ConvertType(const TypeDecl *T) { 1309 return ConvertType(getContext().getTypeDeclType(T)); 1310 } 1311 1312 /// LoadObjCSelf - Load the value of self. This function is only valid while 1313 /// generating code for an Objective-C method. 1314 llvm::Value *LoadObjCSelf(); 1315 1316 /// TypeOfSelfObject - Return type of object that this self represents. 1317 QualType TypeOfSelfObject(); 1318 1319 /// hasAggregateLLVMType - Return true if the specified AST type will map into 1320 /// an aggregate LLVM type or is void. 1321 static TypeEvaluationKind getEvaluationKind(QualType T); 1322 1323 static bool hasScalarEvaluationKind(QualType T) { 1324 return getEvaluationKind(T) == TEK_Scalar; 1325 } 1326 1327 static bool hasAggregateEvaluationKind(QualType T) { 1328 return getEvaluationKind(T) == TEK_Aggregate; 1329 } 1330 1331 /// createBasicBlock - Create an LLVM basic block. 1332 llvm::BasicBlock *createBasicBlock(const Twine &name = "", 1333 llvm::Function *parent = nullptr, 1334 llvm::BasicBlock *before = nullptr) { 1335 #ifdef NDEBUG 1336 return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before); 1337 #else 1338 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before); 1339 #endif 1340 } 1341 1342 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified 1343 /// label maps to. 1344 JumpDest getJumpDestForLabel(const LabelDecl *S); 1345 1346 /// SimplifyForwardingBlocks - If the given basic block is only a branch to 1347 /// another basic block, simplify it. This assumes that no other code could 1348 /// potentially reference the basic block. 1349 void SimplifyForwardingBlocks(llvm::BasicBlock *BB); 1350 1351 /// EmitBlock - Emit the given block \arg BB and set it as the insert point, 1352 /// adding a fall-through branch from the current insert block if 1353 /// necessary. It is legal to call this function even if there is no current 1354 /// insertion point. 1355 /// 1356 /// IsFinished - If true, indicates that the caller has finished emitting 1357 /// branches to the given block and does not expect to emit code into it. This 1358 /// means the block can be ignored if it is unreachable. 1359 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false); 1360 1361 /// EmitBlockAfterUses - Emit the given block somewhere hopefully 1362 /// near its uses, and leave the insertion point in it. 1363 void EmitBlockAfterUses(llvm::BasicBlock *BB); 1364 1365 /// EmitBranch - Emit a branch to the specified basic block from the current 1366 /// insert block, taking care to avoid creation of branches from dummy 1367 /// blocks. It is legal to call this function even if there is no current 1368 /// insertion point. 1369 /// 1370 /// This function clears the current insertion point. The caller should follow 1371 /// calls to this function with calls to Emit*Block prior to generation new 1372 /// code. 1373 void EmitBranch(llvm::BasicBlock *Block); 1374 1375 /// HaveInsertPoint - True if an insertion point is defined. If not, this 1376 /// indicates that the current code being emitted is unreachable. 1377 bool HaveInsertPoint() const { 1378 return Builder.GetInsertBlock() != nullptr; 1379 } 1380 1381 /// EnsureInsertPoint - Ensure that an insertion point is defined so that 1382 /// emitted IR has a place to go. Note that by definition, if this function 1383 /// creates a block then that block is unreachable; callers may do better to 1384 /// detect when no insertion point is defined and simply skip IR generation. 1385 void EnsureInsertPoint() { 1386 if (!HaveInsertPoint()) 1387 EmitBlock(createBasicBlock()); 1388 } 1389 1390 /// ErrorUnsupported - Print out an error that codegen doesn't support the 1391 /// specified stmt yet. 1392 void ErrorUnsupported(const Stmt *S, const char *Type); 1393 1394 //===--------------------------------------------------------------------===// 1395 // Helpers 1396 //===--------------------------------------------------------------------===// 1397 1398 LValue MakeAddrLValue(llvm::Value *V, QualType T, 1399 CharUnits Alignment = CharUnits()) { 1400 return LValue::MakeAddr(V, T, Alignment, getContext(), 1401 CGM.getTBAAInfo(T)); 1402 } 1403 1404 LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T); 1405 1406 /// CreateTempAlloca - This creates a alloca and inserts it into the entry 1407 /// block. The caller is responsible for setting an appropriate alignment on 1408 /// the alloca. 1409 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty, 1410 const Twine &Name = "tmp"); 1411 1412 /// InitTempAlloca - Provide an initial value for the given alloca. 1413 void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value); 1414 1415 /// CreateIRTemp - Create a temporary IR object of the given type, with 1416 /// appropriate alignment. This routine should only be used when an temporary 1417 /// value needs to be stored into an alloca (for example, to avoid explicit 1418 /// PHI construction), but the type is the IR type, not the type appropriate 1419 /// for storing in memory. 1420 llvm::AllocaInst *CreateIRTemp(QualType T, const Twine &Name = "tmp"); 1421 1422 /// CreateMemTemp - Create a temporary memory object of the given type, with 1423 /// appropriate alignment. 1424 llvm::AllocaInst *CreateMemTemp(QualType T, const Twine &Name = "tmp"); 1425 1426 /// CreateAggTemp - Create a temporary memory object for the given 1427 /// aggregate type. 1428 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") { 1429 CharUnits Alignment = getContext().getTypeAlignInChars(T); 1430 return AggValueSlot::forAddr(CreateMemTemp(T, Name), Alignment, 1431 T.getQualifiers(), 1432 AggValueSlot::IsNotDestructed, 1433 AggValueSlot::DoesNotNeedGCBarriers, 1434 AggValueSlot::IsNotAliased); 1435 } 1436 1437 /// CreateInAllocaTmp - Create a temporary memory object for the given 1438 /// aggregate type. 1439 AggValueSlot CreateInAllocaTmp(QualType T, const Twine &Name = "inalloca"); 1440 1441 /// Emit a cast to void* in the appropriate address space. 1442 llvm::Value *EmitCastToVoidPtr(llvm::Value *value); 1443 1444 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 1445 /// expression and compare the result against zero, returning an Int1Ty value. 1446 llvm::Value *EvaluateExprAsBool(const Expr *E); 1447 1448 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result. 1449 void EmitIgnoredExpr(const Expr *E); 1450 1451 /// EmitAnyExpr - Emit code to compute the specified expression which can have 1452 /// any type. The result is returned as an RValue struct. If this is an 1453 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where 1454 /// the result should be returned. 1455 /// 1456 /// \param ignoreResult True if the resulting value isn't used. 1457 RValue EmitAnyExpr(const Expr *E, 1458 AggValueSlot aggSlot = AggValueSlot::ignored(), 1459 bool ignoreResult = false); 1460 1461 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address 1462 // or the value of the expression, depending on how va_list is defined. 1463 llvm::Value *EmitVAListRef(const Expr *E); 1464 1465 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will 1466 /// always be accessible even if no aggregate location is provided. 1467 RValue EmitAnyExprToTemp(const Expr *E); 1468 1469 /// EmitAnyExprToMem - Emits the code necessary to evaluate an 1470 /// arbitrary expression into the given memory location. 1471 void EmitAnyExprToMem(const Expr *E, llvm::Value *Location, 1472 Qualifiers Quals, bool IsInitializer); 1473 1474 /// EmitExprAsInit - Emits the code necessary to initialize a 1475 /// location in memory with the given initializer. 1476 void EmitExprAsInit(const Expr *init, const ValueDecl *D, 1477 LValue lvalue, bool capturedByInit); 1478 1479 /// hasVolatileMember - returns true if aggregate type has a volatile 1480 /// member. 1481 bool hasVolatileMember(QualType T) { 1482 if (const RecordType *RT = T->getAs<RecordType>()) { 1483 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl()); 1484 return RD->hasVolatileMember(); 1485 } 1486 return false; 1487 } 1488 /// EmitAggregateCopy - Emit an aggregate assignment. 1489 /// 1490 /// The difference to EmitAggregateCopy is that tail padding is not copied. 1491 /// This is required for correctness when assigning non-POD structures in C++. 1492 void EmitAggregateAssign(llvm::Value *DestPtr, llvm::Value *SrcPtr, 1493 QualType EltTy) { 1494 bool IsVolatile = hasVolatileMember(EltTy); 1495 EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, CharUnits::Zero(), 1496 true); 1497 } 1498 1499 /// EmitAggregateCopy - Emit an aggregate copy. 1500 /// 1501 /// \param isVolatile - True iff either the source or the destination is 1502 /// volatile. 1503 /// \param isAssignment - If false, allow padding to be copied. This often 1504 /// yields more efficient. 1505 void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr, 1506 QualType EltTy, bool isVolatile=false, 1507 CharUnits Alignment = CharUnits::Zero(), 1508 bool isAssignment = false); 1509 1510 /// StartBlock - Start new block named N. If insert block is a dummy block 1511 /// then reuse it. 1512 void StartBlock(const char *N); 1513 1514 /// GetAddrOfLocalVar - Return the address of a local variable. 1515 llvm::Value *GetAddrOfLocalVar(const VarDecl *VD) { 1516 llvm::Value *Res = LocalDeclMap[VD]; 1517 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!"); 1518 return Res; 1519 } 1520 1521 /// getOpaqueLValueMapping - Given an opaque value expression (which 1522 /// must be mapped to an l-value), return its mapping. 1523 const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) { 1524 assert(OpaqueValueMapping::shouldBindAsLValue(e)); 1525 1526 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator 1527 it = OpaqueLValues.find(e); 1528 assert(it != OpaqueLValues.end() && "no mapping for opaque value!"); 1529 return it->second; 1530 } 1531 1532 /// getOpaqueRValueMapping - Given an opaque value expression (which 1533 /// must be mapped to an r-value), return its mapping. 1534 const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) { 1535 assert(!OpaqueValueMapping::shouldBindAsLValue(e)); 1536 1537 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator 1538 it = OpaqueRValues.find(e); 1539 assert(it != OpaqueRValues.end() && "no mapping for opaque value!"); 1540 return it->second; 1541 } 1542 1543 /// getAccessedFieldNo - Given an encoded value and a result number, return 1544 /// the input field number being accessed. 1545 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts); 1546 1547 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L); 1548 llvm::BasicBlock *GetIndirectGotoBlock(); 1549 1550 /// EmitNullInitialization - Generate code to set a value of the given type to 1551 /// null, If the type contains data member pointers, they will be initialized 1552 /// to -1 in accordance with the Itanium C++ ABI. 1553 void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty); 1554 1555 // EmitVAArg - Generate code to get an argument from the passed in pointer 1556 // and update it accordingly. The return value is a pointer to the argument. 1557 // FIXME: We should be able to get rid of this method and use the va_arg 1558 // instruction in LLVM instead once it works well enough. 1559 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty); 1560 1561 /// emitArrayLength - Compute the length of an array, even if it's a 1562 /// VLA, and drill down to the base element type. 1563 llvm::Value *emitArrayLength(const ArrayType *arrayType, 1564 QualType &baseType, 1565 llvm::Value *&addr); 1566 1567 /// EmitVLASize - Capture all the sizes for the VLA expressions in 1568 /// the given variably-modified type and store them in the VLASizeMap. 1569 /// 1570 /// This function can be called with a null (unreachable) insert point. 1571 void EmitVariablyModifiedType(QualType Ty); 1572 1573 /// getVLASize - Returns an LLVM value that corresponds to the size, 1574 /// in non-variably-sized elements, of a variable length array type, 1575 /// plus that largest non-variably-sized element type. Assumes that 1576 /// the type has already been emitted with EmitVariablyModifiedType. 1577 std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla); 1578 std::pair<llvm::Value*,QualType> getVLASize(QualType vla); 1579 1580 /// LoadCXXThis - Load the value of 'this'. This function is only valid while 1581 /// generating code for an C++ member function. 1582 llvm::Value *LoadCXXThis() { 1583 assert(CXXThisValue && "no 'this' value for this function"); 1584 return CXXThisValue; 1585 } 1586 1587 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have 1588 /// virtual bases. 1589 // FIXME: Every place that calls LoadCXXVTT is something 1590 // that needs to be abstracted properly. 1591 llvm::Value *LoadCXXVTT() { 1592 assert(CXXStructorImplicitParamValue && "no VTT value for this function"); 1593 return CXXStructorImplicitParamValue; 1594 } 1595 1596 /// LoadCXXStructorImplicitParam - Load the implicit parameter 1597 /// for a constructor/destructor. 1598 llvm::Value *LoadCXXStructorImplicitParam() { 1599 assert(CXXStructorImplicitParamValue && 1600 "no implicit argument value for this function"); 1601 return CXXStructorImplicitParamValue; 1602 } 1603 1604 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a 1605 /// complete class to the given direct base. 1606 llvm::Value * 1607 GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value, 1608 const CXXRecordDecl *Derived, 1609 const CXXRecordDecl *Base, 1610 bool BaseIsVirtual); 1611 1612 /// GetAddressOfBaseClass - This function will add the necessary delta to the 1613 /// load of 'this' and returns address of the base class. 1614 llvm::Value *GetAddressOfBaseClass(llvm::Value *Value, 1615 const CXXRecordDecl *Derived, 1616 CastExpr::path_const_iterator PathBegin, 1617 CastExpr::path_const_iterator PathEnd, 1618 bool NullCheckValue); 1619 1620 llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value, 1621 const CXXRecordDecl *Derived, 1622 CastExpr::path_const_iterator PathBegin, 1623 CastExpr::path_const_iterator PathEnd, 1624 bool NullCheckValue); 1625 1626 /// GetVTTParameter - Return the VTT parameter that should be passed to a 1627 /// base constructor/destructor with virtual bases. 1628 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move 1629 /// to ItaniumCXXABI.cpp together with all the references to VTT. 1630 llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase, 1631 bool Delegating); 1632 1633 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, 1634 CXXCtorType CtorType, 1635 const FunctionArgList &Args, 1636 SourceLocation Loc); 1637 // It's important not to confuse this and the previous function. Delegating 1638 // constructors are the C++0x feature. The constructor delegate optimization 1639 // is used to reduce duplication in the base and complete consturctors where 1640 // they are substantially the same. 1641 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor, 1642 const FunctionArgList &Args); 1643 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 1644 bool ForVirtualBase, bool Delegating, 1645 llvm::Value *This, const CXXConstructExpr *E); 1646 1647 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, 1648 llvm::Value *This, llvm::Value *Src, 1649 const CXXConstructExpr *E); 1650 1651 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 1652 const ConstantArrayType *ArrayTy, 1653 llvm::Value *ArrayPtr, 1654 const CXXConstructExpr *E, 1655 bool ZeroInitialization = false); 1656 1657 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 1658 llvm::Value *NumElements, 1659 llvm::Value *ArrayPtr, 1660 const CXXConstructExpr *E, 1661 bool ZeroInitialization = false); 1662 1663 static Destroyer destroyCXXObject; 1664 1665 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, 1666 bool ForVirtualBase, bool Delegating, 1667 llvm::Value *This); 1668 1669 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType, 1670 llvm::Value *NewPtr, llvm::Value *NumElements, 1671 llvm::Value *AllocSizeWithoutCookie); 1672 1673 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType, 1674 llvm::Value *Ptr); 1675 1676 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E); 1677 void EmitCXXDeleteExpr(const CXXDeleteExpr *E); 1678 1679 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr, 1680 QualType DeleteTy); 1681 1682 RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type, 1683 const Expr *Arg, bool IsDelete); 1684 1685 llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E); 1686 llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE); 1687 llvm::Value* EmitCXXUuidofExpr(const CXXUuidofExpr *E); 1688 1689 /// \brief Situations in which we might emit a check for the suitability of a 1690 /// pointer or glvalue. 1691 enum TypeCheckKind { 1692 /// Checking the operand of a load. Must be suitably sized and aligned. 1693 TCK_Load, 1694 /// Checking the destination of a store. Must be suitably sized and aligned. 1695 TCK_Store, 1696 /// Checking the bound value in a reference binding. Must be suitably sized 1697 /// and aligned, but is not required to refer to an object (until the 1698 /// reference is used), per core issue 453. 1699 TCK_ReferenceBinding, 1700 /// Checking the object expression in a non-static data member access. Must 1701 /// be an object within its lifetime. 1702 TCK_MemberAccess, 1703 /// Checking the 'this' pointer for a call to a non-static member function. 1704 /// Must be an object within its lifetime. 1705 TCK_MemberCall, 1706 /// Checking the 'this' pointer for a constructor call. 1707 TCK_ConstructorCall, 1708 /// Checking the operand of a static_cast to a derived pointer type. Must be 1709 /// null or an object within its lifetime. 1710 TCK_DowncastPointer, 1711 /// Checking the operand of a static_cast to a derived reference type. Must 1712 /// be an object within its lifetime. 1713 TCK_DowncastReference 1714 }; 1715 1716 /// \brief Whether any type-checking sanitizers are enabled. If \c false, 1717 /// calls to EmitTypeCheck can be skipped. 1718 bool sanitizePerformTypeCheck() const; 1719 1720 /// \brief Emit a check that \p V is the address of storage of the 1721 /// appropriate size and alignment for an object of type \p Type. 1722 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V, 1723 QualType Type, CharUnits Alignment = CharUnits::Zero()); 1724 1725 /// \brief Emit a check that \p Base points into an array object, which 1726 /// we can access at index \p Index. \p Accessed should be \c false if we 1727 /// this expression is used as an lvalue, for instance in "&Arr[Idx]". 1728 void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index, 1729 QualType IndexType, bool Accessed); 1730 1731 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 1732 bool isInc, bool isPre); 1733 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, 1734 bool isInc, bool isPre); 1735 1736 void EmitAlignmentAssumption(llvm::Value *PtrValue, unsigned Alignment, 1737 llvm::Value *OffsetValue = nullptr); 1738 1739 //===--------------------------------------------------------------------===// 1740 // Declaration Emission 1741 //===--------------------------------------------------------------------===// 1742 1743 /// EmitDecl - Emit a declaration. 1744 /// 1745 /// This function can be called with a null (unreachable) insert point. 1746 void EmitDecl(const Decl &D); 1747 1748 /// EmitVarDecl - Emit a local variable declaration. 1749 /// 1750 /// This function can be called with a null (unreachable) insert point. 1751 void EmitVarDecl(const VarDecl &D); 1752 1753 void EmitScalarInit(const Expr *init, const ValueDecl *D, 1754 LValue lvalue, bool capturedByInit); 1755 void EmitScalarInit(llvm::Value *init, LValue lvalue); 1756 1757 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D, 1758 llvm::Value *Address); 1759 1760 /// EmitAutoVarDecl - Emit an auto variable declaration. 1761 /// 1762 /// This function can be called with a null (unreachable) insert point. 1763 void EmitAutoVarDecl(const VarDecl &D); 1764 1765 class AutoVarEmission { 1766 friend class CodeGenFunction; 1767 1768 const VarDecl *Variable; 1769 1770 /// The alignment of the variable. 1771 CharUnits Alignment; 1772 1773 /// The address of the alloca. Null if the variable was emitted 1774 /// as a global constant. 1775 llvm::Value *Address; 1776 1777 llvm::Value *NRVOFlag; 1778 1779 /// True if the variable is a __block variable. 1780 bool IsByRef; 1781 1782 /// True if the variable is of aggregate type and has a constant 1783 /// initializer. 1784 bool IsConstantAggregate; 1785 1786 /// Non-null if we should use lifetime annotations. 1787 llvm::Value *SizeForLifetimeMarkers; 1788 1789 struct Invalid {}; 1790 AutoVarEmission(Invalid) : Variable(nullptr) {} 1791 1792 AutoVarEmission(const VarDecl &variable) 1793 : Variable(&variable), Address(nullptr), NRVOFlag(nullptr), 1794 IsByRef(false), IsConstantAggregate(false), 1795 SizeForLifetimeMarkers(nullptr) {} 1796 1797 bool wasEmittedAsGlobal() const { return Address == nullptr; } 1798 1799 public: 1800 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); } 1801 1802 bool useLifetimeMarkers() const { 1803 return SizeForLifetimeMarkers != nullptr; 1804 } 1805 llvm::Value *getSizeForLifetimeMarkers() const { 1806 assert(useLifetimeMarkers()); 1807 return SizeForLifetimeMarkers; 1808 } 1809 1810 /// Returns the raw, allocated address, which is not necessarily 1811 /// the address of the object itself. 1812 llvm::Value *getAllocatedAddress() const { 1813 return Address; 1814 } 1815 1816 /// Returns the address of the object within this declaration. 1817 /// Note that this does not chase the forwarding pointer for 1818 /// __block decls. 1819 llvm::Value *getObjectAddress(CodeGenFunction &CGF) const { 1820 if (!IsByRef) return Address; 1821 1822 return CGF.Builder.CreateStructGEP(Address, 1823 CGF.getByRefValueLLVMField(Variable), 1824 Variable->getNameAsString()); 1825 } 1826 }; 1827 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var); 1828 void EmitAutoVarInit(const AutoVarEmission &emission); 1829 void EmitAutoVarCleanups(const AutoVarEmission &emission); 1830 void emitAutoVarTypeCleanup(const AutoVarEmission &emission, 1831 QualType::DestructionKind dtorKind); 1832 1833 void EmitStaticVarDecl(const VarDecl &D, 1834 llvm::GlobalValue::LinkageTypes Linkage); 1835 1836 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl. 1837 void EmitParmDecl(const VarDecl &D, llvm::Value *Arg, bool ArgIsPointer, 1838 unsigned ArgNo); 1839 1840 /// protectFromPeepholes - Protect a value that we're intending to 1841 /// store to the side, but which will probably be used later, from 1842 /// aggressive peepholing optimizations that might delete it. 1843 /// 1844 /// Pass the result to unprotectFromPeepholes to declare that 1845 /// protection is no longer required. 1846 /// 1847 /// There's no particular reason why this shouldn't apply to 1848 /// l-values, it's just that no existing peepholes work on pointers. 1849 PeepholeProtection protectFromPeepholes(RValue rvalue); 1850 void unprotectFromPeepholes(PeepholeProtection protection); 1851 1852 //===--------------------------------------------------------------------===// 1853 // Statement Emission 1854 //===--------------------------------------------------------------------===// 1855 1856 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info. 1857 void EmitStopPoint(const Stmt *S); 1858 1859 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call 1860 /// this function even if there is no current insertion point. 1861 /// 1862 /// This function may clear the current insertion point; callers should use 1863 /// EnsureInsertPoint if they wish to subsequently generate code without first 1864 /// calling EmitBlock, EmitBranch, or EmitStmt. 1865 void EmitStmt(const Stmt *S); 1866 1867 /// EmitSimpleStmt - Try to emit a "simple" statement which does not 1868 /// necessarily require an insertion point or debug information; typically 1869 /// because the statement amounts to a jump or a container of other 1870 /// statements. 1871 /// 1872 /// \return True if the statement was handled. 1873 bool EmitSimpleStmt(const Stmt *S); 1874 1875 llvm::Value *EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false, 1876 AggValueSlot AVS = AggValueSlot::ignored()); 1877 llvm::Value *EmitCompoundStmtWithoutScope(const CompoundStmt &S, 1878 bool GetLast = false, 1879 AggValueSlot AVS = 1880 AggValueSlot::ignored()); 1881 1882 /// EmitLabel - Emit the block for the given label. It is legal to call this 1883 /// function even if there is no current insertion point. 1884 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt. 1885 1886 void EmitLabelStmt(const LabelStmt &S); 1887 void EmitAttributedStmt(const AttributedStmt &S); 1888 void EmitGotoStmt(const GotoStmt &S); 1889 void EmitIndirectGotoStmt(const IndirectGotoStmt &S); 1890 void EmitIfStmt(const IfStmt &S); 1891 1892 void EmitCondBrHints(llvm::LLVMContext &Context, llvm::BranchInst *CondBr, 1893 ArrayRef<const Attr *> Attrs); 1894 void EmitWhileStmt(const WhileStmt &S, 1895 ArrayRef<const Attr *> Attrs = None); 1896 void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None); 1897 void EmitForStmt(const ForStmt &S, 1898 ArrayRef<const Attr *> Attrs = None); 1899 void EmitReturnStmt(const ReturnStmt &S); 1900 void EmitDeclStmt(const DeclStmt &S); 1901 void EmitBreakStmt(const BreakStmt &S); 1902 void EmitContinueStmt(const ContinueStmt &S); 1903 void EmitSwitchStmt(const SwitchStmt &S); 1904 void EmitDefaultStmt(const DefaultStmt &S); 1905 void EmitCaseStmt(const CaseStmt &S); 1906 void EmitCaseStmtRange(const CaseStmt &S); 1907 void EmitAsmStmt(const AsmStmt &S); 1908 1909 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S); 1910 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S); 1911 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S); 1912 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S); 1913 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S); 1914 1915 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 1916 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 1917 1918 void EmitCXXTryStmt(const CXXTryStmt &S); 1919 void EmitSEHTryStmt(const SEHTryStmt &S); 1920 void EmitSEHLeaveStmt(const SEHLeaveStmt &S); 1921 void EmitCXXForRangeStmt(const CXXForRangeStmt &S, 1922 ArrayRef<const Attr *> Attrs = None); 1923 1924 llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K); 1925 llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S); 1926 llvm::Value *GenerateCapturedStmtArgument(const CapturedStmt &S); 1927 1928 void EmitOMPParallelDirective(const OMPParallelDirective &S); 1929 void EmitOMPSimdDirective(const OMPSimdDirective &S); 1930 void EmitOMPForDirective(const OMPForDirective &S); 1931 void EmitOMPForSimdDirective(const OMPForSimdDirective &S); 1932 void EmitOMPSectionsDirective(const OMPSectionsDirective &S); 1933 void EmitOMPSectionDirective(const OMPSectionDirective &S); 1934 void EmitOMPSingleDirective(const OMPSingleDirective &S); 1935 void EmitOMPMasterDirective(const OMPMasterDirective &S); 1936 void EmitOMPCriticalDirective(const OMPCriticalDirective &S); 1937 void EmitOMPParallelForDirective(const OMPParallelForDirective &S); 1938 void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S); 1939 void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S); 1940 void EmitOMPTaskDirective(const OMPTaskDirective &S); 1941 void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S); 1942 void EmitOMPBarrierDirective(const OMPBarrierDirective &S); 1943 void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S); 1944 void EmitOMPFlushDirective(const OMPFlushDirective &S); 1945 void EmitOMPOrderedDirective(const OMPOrderedDirective &S); 1946 void EmitOMPAtomicDirective(const OMPAtomicDirective &S); 1947 void EmitOMPTargetDirective(const OMPTargetDirective &S); 1948 1949 //===--------------------------------------------------------------------===// 1950 // LValue Expression Emission 1951 //===--------------------------------------------------------------------===// 1952 1953 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type. 1954 RValue GetUndefRValue(QualType Ty); 1955 1956 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E 1957 /// and issue an ErrorUnsupported style diagnostic (using the 1958 /// provided Name). 1959 RValue EmitUnsupportedRValue(const Expr *E, 1960 const char *Name); 1961 1962 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue 1963 /// an ErrorUnsupported style diagnostic (using the provided Name). 1964 LValue EmitUnsupportedLValue(const Expr *E, 1965 const char *Name); 1966 1967 /// EmitLValue - Emit code to compute a designator that specifies the location 1968 /// of the expression. 1969 /// 1970 /// This can return one of two things: a simple address or a bitfield 1971 /// reference. In either case, the LLVM Value* in the LValue structure is 1972 /// guaranteed to be an LLVM pointer type. 1973 /// 1974 /// If this returns a bitfield reference, nothing about the pointee type of 1975 /// the LLVM value is known: For example, it may not be a pointer to an 1976 /// integer. 1977 /// 1978 /// If this returns a normal address, and if the lvalue's C type is fixed 1979 /// size, this method guarantees that the returned pointer type will point to 1980 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a 1981 /// variable length type, this is not possible. 1982 /// 1983 LValue EmitLValue(const Expr *E); 1984 1985 /// \brief Same as EmitLValue but additionally we generate checking code to 1986 /// guard against undefined behavior. This is only suitable when we know 1987 /// that the address will be used to access the object. 1988 LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK); 1989 1990 RValue convertTempToRValue(llvm::Value *addr, QualType type, 1991 SourceLocation Loc); 1992 1993 void EmitAtomicInit(Expr *E, LValue lvalue); 1994 1995 RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc, 1996 AggValueSlot slot = AggValueSlot::ignored()); 1997 1998 void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit); 1999 2000 /// EmitToMemory - Change a scalar value from its value 2001 /// representation to its in-memory representation. 2002 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty); 2003 2004 /// EmitFromMemory - Change a scalar value from its memory 2005 /// representation to its value representation. 2006 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty); 2007 2008 /// EmitLoadOfScalar - Load a scalar value from an address, taking 2009 /// care to appropriately convert from the memory representation to 2010 /// the LLVM value representation. 2011 llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile, 2012 unsigned Alignment, QualType Ty, 2013 SourceLocation Loc, 2014 llvm::MDNode *TBAAInfo = nullptr, 2015 QualType TBAABaseTy = QualType(), 2016 uint64_t TBAAOffset = 0); 2017 2018 /// EmitLoadOfScalar - Load a scalar value from an address, taking 2019 /// care to appropriately convert from the memory representation to 2020 /// the LLVM value representation. The l-value must be a simple 2021 /// l-value. 2022 llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc); 2023 2024 /// EmitStoreOfScalar - Store a scalar value to an address, taking 2025 /// care to appropriately convert from the memory representation to 2026 /// the LLVM value representation. 2027 void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr, 2028 bool Volatile, unsigned Alignment, QualType Ty, 2029 llvm::MDNode *TBAAInfo = nullptr, bool isInit = false, 2030 QualType TBAABaseTy = QualType(), 2031 uint64_t TBAAOffset = 0); 2032 2033 /// EmitStoreOfScalar - Store a scalar value to an address, taking 2034 /// care to appropriately convert from the memory representation to 2035 /// the LLVM value representation. The l-value must be a simple 2036 /// l-value. The isInit flag indicates whether this is an initialization. 2037 /// If so, atomic qualifiers are ignored and the store is always non-atomic. 2038 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false); 2039 2040 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, 2041 /// this method emits the address of the lvalue, then loads the result as an 2042 /// rvalue, returning the rvalue. 2043 RValue EmitLoadOfLValue(LValue V, SourceLocation Loc); 2044 RValue EmitLoadOfExtVectorElementLValue(LValue V); 2045 RValue EmitLoadOfBitfieldLValue(LValue LV); 2046 RValue EmitLoadOfGlobalRegLValue(LValue LV); 2047 2048 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 2049 /// lvalue, where both are guaranteed to the have the same type, and that type 2050 /// is 'Ty'. 2051 void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false); 2052 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst); 2053 void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst); 2054 2055 /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints 2056 /// as EmitStoreThroughLValue. 2057 /// 2058 /// \param Result [out] - If non-null, this will be set to a Value* for the 2059 /// bit-field contents after the store, appropriate for use as the result of 2060 /// an assignment to the bit-field. 2061 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 2062 llvm::Value **Result=nullptr); 2063 2064 /// Emit an l-value for an assignment (simple or compound) of complex type. 2065 LValue EmitComplexAssignmentLValue(const BinaryOperator *E); 2066 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E); 2067 LValue EmitScalarCompooundAssignWithComplex(const CompoundAssignOperator *E, 2068 llvm::Value *&Result); 2069 2070 // Note: only available for agg return types 2071 LValue EmitBinaryOperatorLValue(const BinaryOperator *E); 2072 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E); 2073 // Note: only available for agg return types 2074 LValue EmitCallExprLValue(const CallExpr *E); 2075 // Note: only available for agg return types 2076 LValue EmitVAArgExprLValue(const VAArgExpr *E); 2077 LValue EmitDeclRefLValue(const DeclRefExpr *E); 2078 LValue EmitReadRegister(const VarDecl *VD); 2079 LValue EmitStringLiteralLValue(const StringLiteral *E); 2080 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E); 2081 LValue EmitPredefinedLValue(const PredefinedExpr *E); 2082 LValue EmitUnaryOpLValue(const UnaryOperator *E); 2083 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E, 2084 bool Accessed = false); 2085 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E); 2086 LValue EmitMemberExpr(const MemberExpr *E); 2087 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E); 2088 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E); 2089 LValue EmitInitListLValue(const InitListExpr *E); 2090 LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E); 2091 LValue EmitCastLValue(const CastExpr *E); 2092 LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 2093 LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e); 2094 2095 llvm::Value *EmitExtVectorElementLValue(LValue V); 2096 2097 RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc); 2098 2099 class ConstantEmission { 2100 llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference; 2101 ConstantEmission(llvm::Constant *C, bool isReference) 2102 : ValueAndIsReference(C, isReference) {} 2103 public: 2104 ConstantEmission() {} 2105 static ConstantEmission forReference(llvm::Constant *C) { 2106 return ConstantEmission(C, true); 2107 } 2108 static ConstantEmission forValue(llvm::Constant *C) { 2109 return ConstantEmission(C, false); 2110 } 2111 2112 LLVM_EXPLICIT operator bool() const { 2113 return ValueAndIsReference.getOpaqueValue() != nullptr; 2114 } 2115 2116 bool isReference() const { return ValueAndIsReference.getInt(); } 2117 LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const { 2118 assert(isReference()); 2119 return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(), 2120 refExpr->getType()); 2121 } 2122 2123 llvm::Constant *getValue() const { 2124 assert(!isReference()); 2125 return ValueAndIsReference.getPointer(); 2126 } 2127 }; 2128 2129 ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr); 2130 2131 RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, 2132 AggValueSlot slot = AggValueSlot::ignored()); 2133 LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e); 2134 2135 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface, 2136 const ObjCIvarDecl *Ivar); 2137 LValue EmitLValueForField(LValue Base, const FieldDecl* Field); 2138 LValue EmitLValueForLambdaField(const FieldDecl *Field); 2139 2140 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that 2141 /// if the Field is a reference, this will return the address of the reference 2142 /// and not the address of the value stored in the reference. 2143 LValue EmitLValueForFieldInitialization(LValue Base, 2144 const FieldDecl* Field); 2145 2146 LValue EmitLValueForIvar(QualType ObjectTy, 2147 llvm::Value* Base, const ObjCIvarDecl *Ivar, 2148 unsigned CVRQualifiers); 2149 2150 LValue EmitCXXConstructLValue(const CXXConstructExpr *E); 2151 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E); 2152 LValue EmitLambdaLValue(const LambdaExpr *E); 2153 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E); 2154 LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E); 2155 2156 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E); 2157 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E); 2158 LValue EmitStmtExprLValue(const StmtExpr *E); 2159 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E); 2160 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E); 2161 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::Constant *Init); 2162 2163 //===--------------------------------------------------------------------===// 2164 // Scalar Expression Emission 2165 //===--------------------------------------------------------------------===// 2166 2167 /// EmitCall - Generate a call of the given function, expecting the given 2168 /// result type, and using the given argument list which specifies both the 2169 /// LLVM arguments and the types they were derived from. 2170 /// 2171 /// \param TargetDecl - If given, the decl of the function in a direct call; 2172 /// used to set attributes on the call (noreturn, etc.). 2173 RValue EmitCall(const CGFunctionInfo &FnInfo, 2174 llvm::Value *Callee, 2175 ReturnValueSlot ReturnValue, 2176 const CallArgList &Args, 2177 const Decl *TargetDecl = nullptr, 2178 llvm::Instruction **callOrInvoke = nullptr); 2179 2180 RValue EmitCall(QualType FnType, llvm::Value *Callee, const CallExpr *E, 2181 ReturnValueSlot ReturnValue, 2182 const Decl *TargetDecl = nullptr); 2183 RValue EmitCallExpr(const CallExpr *E, 2184 ReturnValueSlot ReturnValue = ReturnValueSlot()); 2185 2186 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee, 2187 const Twine &name = ""); 2188 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee, 2189 ArrayRef<llvm::Value*> args, 2190 const Twine &name = ""); 2191 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee, 2192 const Twine &name = ""); 2193 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee, 2194 ArrayRef<llvm::Value*> args, 2195 const Twine &name = ""); 2196 2197 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee, 2198 ArrayRef<llvm::Value *> Args, 2199 const Twine &Name = ""); 2200 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee, 2201 const Twine &Name = ""); 2202 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee, 2203 ArrayRef<llvm::Value*> args, 2204 const Twine &name = ""); 2205 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee, 2206 const Twine &name = ""); 2207 void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee, 2208 ArrayRef<llvm::Value*> args); 2209 2210 llvm::Value *BuildAppleKextVirtualCall(const CXXMethodDecl *MD, 2211 NestedNameSpecifier *Qual, 2212 llvm::Type *Ty); 2213 2214 llvm::Value *BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD, 2215 CXXDtorType Type, 2216 const CXXRecordDecl *RD); 2217 2218 RValue 2219 EmitCXXMemberOrOperatorCall(const CXXMethodDecl *MD, llvm::Value *Callee, 2220 ReturnValueSlot ReturnValue, llvm::Value *This, 2221 llvm::Value *ImplicitParam, 2222 QualType ImplicitParamTy, const CallExpr *E); 2223 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E, 2224 ReturnValueSlot ReturnValue); 2225 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, 2226 ReturnValueSlot ReturnValue); 2227 2228 llvm::Value *EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E, 2229 const CXXMethodDecl *MD, 2230 llvm::Value *This); 2231 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 2232 const CXXMethodDecl *MD, 2233 ReturnValueSlot ReturnValue); 2234 2235 RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, 2236 ReturnValueSlot ReturnValue); 2237 2238 2239 RValue EmitBuiltinExpr(const FunctionDecl *FD, 2240 unsigned BuiltinID, const CallExpr *E); 2241 2242 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue); 2243 2244 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call 2245 /// is unhandled by the current target. 2246 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2247 2248 llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty, 2249 const llvm::CmpInst::Predicate Fp, 2250 const llvm::CmpInst::Predicate Ip, 2251 const llvm::Twine &Name = ""); 2252 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2253 2254 llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID, 2255 unsigned LLVMIntrinsic, 2256 unsigned AltLLVMIntrinsic, 2257 const char *NameHint, 2258 unsigned Modifier, 2259 const CallExpr *E, 2260 SmallVectorImpl<llvm::Value *> &Ops, 2261 llvm::Value *Align = nullptr); 2262 llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID, 2263 unsigned Modifier, llvm::Type *ArgTy, 2264 const CallExpr *E); 2265 llvm::Value *EmitNeonCall(llvm::Function *F, 2266 SmallVectorImpl<llvm::Value*> &O, 2267 const char *name, 2268 unsigned shift = 0, bool rightshift = false); 2269 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx); 2270 llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty, 2271 bool negateForRightShift); 2272 llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt, 2273 llvm::Type *Ty, bool usgn, const char *name); 2274 // Helper functions for EmitAArch64BuiltinExpr. 2275 llvm::Value *vectorWrapScalar8(llvm::Value *Op); 2276 llvm::Value *vectorWrapScalar16(llvm::Value *Op); 2277 llvm::Value *emitVectorWrappedScalar8Intrinsic( 2278 unsigned Int, SmallVectorImpl<llvm::Value *> &Ops, const char *Name); 2279 llvm::Value *emitVectorWrappedScalar16Intrinsic( 2280 unsigned Int, SmallVectorImpl<llvm::Value *> &Ops, const char *Name); 2281 llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2282 llvm::Value *EmitNeon64Call(llvm::Function *F, 2283 llvm::SmallVectorImpl<llvm::Value *> &O, 2284 const char *name); 2285 2286 llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops); 2287 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2288 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2289 llvm::Value *EmitR600BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2290 2291 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E); 2292 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E); 2293 llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E); 2294 llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E); 2295 llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E); 2296 llvm::Value *EmitObjCCollectionLiteral(const Expr *E, 2297 const ObjCMethodDecl *MethodWithObjects, 2298 const ObjCMethodDecl *AllocMethod); 2299 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E); 2300 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, 2301 ReturnValueSlot Return = ReturnValueSlot()); 2302 2303 /// Retrieves the default cleanup kind for an ARC cleanup. 2304 /// Except under -fobjc-arc-eh, ARC cleanups are normal-only. 2305 CleanupKind getARCCleanupKind() { 2306 return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions 2307 ? NormalAndEHCleanup : NormalCleanup; 2308 } 2309 2310 // ARC primitives. 2311 void EmitARCInitWeak(llvm::Value *value, llvm::Value *addr); 2312 void EmitARCDestroyWeak(llvm::Value *addr); 2313 llvm::Value *EmitARCLoadWeak(llvm::Value *addr); 2314 llvm::Value *EmitARCLoadWeakRetained(llvm::Value *addr); 2315 llvm::Value *EmitARCStoreWeak(llvm::Value *value, llvm::Value *addr, 2316 bool ignored); 2317 void EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src); 2318 void EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src); 2319 llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value); 2320 llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value); 2321 llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value, 2322 bool resultIgnored); 2323 llvm::Value *EmitARCStoreStrongCall(llvm::Value *addr, llvm::Value *value, 2324 bool resultIgnored); 2325 llvm::Value *EmitARCRetain(QualType type, llvm::Value *value); 2326 llvm::Value *EmitARCRetainNonBlock(llvm::Value *value); 2327 llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory); 2328 void EmitARCDestroyStrong(llvm::Value *addr, ARCPreciseLifetime_t precise); 2329 void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise); 2330 llvm::Value *EmitARCAutorelease(llvm::Value *value); 2331 llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value); 2332 llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value); 2333 llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value); 2334 2335 std::pair<LValue,llvm::Value*> 2336 EmitARCStoreAutoreleasing(const BinaryOperator *e); 2337 std::pair<LValue,llvm::Value*> 2338 EmitARCStoreStrong(const BinaryOperator *e, bool ignored); 2339 2340 llvm::Value *EmitObjCThrowOperand(const Expr *expr); 2341 2342 llvm::Value *EmitObjCProduceObject(QualType T, llvm::Value *Ptr); 2343 llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr); 2344 llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr); 2345 2346 llvm::Value *EmitARCExtendBlockObject(const Expr *expr); 2347 llvm::Value *EmitARCRetainScalarExpr(const Expr *expr); 2348 llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr); 2349 2350 void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values); 2351 2352 static Destroyer destroyARCStrongImprecise; 2353 static Destroyer destroyARCStrongPrecise; 2354 static Destroyer destroyARCWeak; 2355 2356 void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr); 2357 llvm::Value *EmitObjCAutoreleasePoolPush(); 2358 llvm::Value *EmitObjCMRRAutoreleasePoolPush(); 2359 void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr); 2360 void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr); 2361 2362 /// \brief Emits a reference binding to the passed in expression. 2363 RValue EmitReferenceBindingToExpr(const Expr *E); 2364 2365 //===--------------------------------------------------------------------===// 2366 // Expression Emission 2367 //===--------------------------------------------------------------------===// 2368 2369 // Expressions are broken into three classes: scalar, complex, aggregate. 2370 2371 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM 2372 /// scalar type, returning the result. 2373 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false); 2374 2375 /// EmitScalarConversion - Emit a conversion from the specified type to the 2376 /// specified destination type, both of which are LLVM scalar types. 2377 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy, 2378 QualType DstTy); 2379 2380 /// EmitComplexToScalarConversion - Emit a conversion from the specified 2381 /// complex type to the specified destination type, where the destination type 2382 /// is an LLVM scalar type. 2383 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, 2384 QualType DstTy); 2385 2386 2387 /// EmitAggExpr - Emit the computation of the specified expression 2388 /// of aggregate type. The result is computed into the given slot, 2389 /// which may be null to indicate that the value is not needed. 2390 void EmitAggExpr(const Expr *E, AggValueSlot AS); 2391 2392 /// EmitAggExprToLValue - Emit the computation of the specified expression of 2393 /// aggregate type into a temporary LValue. 2394 LValue EmitAggExprToLValue(const Expr *E); 2395 2396 /// EmitGCMemmoveCollectable - Emit special API for structs with object 2397 /// pointers. 2398 void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr, 2399 QualType Ty); 2400 2401 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object, 2402 /// make sure it survives garbage collection until this point. 2403 void EmitExtendGCLifetime(llvm::Value *object); 2404 2405 /// EmitComplexExpr - Emit the computation of the specified expression of 2406 /// complex type, returning the result. 2407 ComplexPairTy EmitComplexExpr(const Expr *E, 2408 bool IgnoreReal = false, 2409 bool IgnoreImag = false); 2410 2411 /// EmitComplexExprIntoLValue - Emit the given expression of complex 2412 /// type and place its result into the specified l-value. 2413 void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit); 2414 2415 /// EmitStoreOfComplex - Store a complex number into the specified l-value. 2416 void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit); 2417 2418 /// EmitLoadOfComplex - Load a complex number from the specified l-value. 2419 ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc); 2420 2421 /// CreateStaticVarDecl - Create a zero-initialized LLVM global for 2422 /// a static local variable. 2423 llvm::Constant *CreateStaticVarDecl(const VarDecl &D, 2424 llvm::GlobalValue::LinkageTypes Linkage); 2425 2426 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the 2427 /// global variable that has already been created for it. If the initializer 2428 /// has a different type than GV does, this may free GV and return a different 2429 /// one. Otherwise it just returns GV. 2430 llvm::GlobalVariable * 2431 AddInitializerToStaticVarDecl(const VarDecl &D, 2432 llvm::GlobalVariable *GV); 2433 2434 2435 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++ 2436 /// variable with global storage. 2437 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr, 2438 bool PerformInit); 2439 2440 /// Call atexit() with a function that passes the given argument to 2441 /// the given function. 2442 void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn, 2443 llvm::Constant *addr); 2444 2445 /// Emit code in this function to perform a guarded variable 2446 /// initialization. Guarded initializations are used when it's not 2447 /// possible to prove that an initialization will be done exactly 2448 /// once, e.g. with a static local variable or a static data member 2449 /// of a class template. 2450 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr, 2451 bool PerformInit); 2452 2453 /// GenerateCXXGlobalInitFunc - Generates code for initializing global 2454 /// variables. 2455 void GenerateCXXGlobalInitFunc(llvm::Function *Fn, 2456 ArrayRef<llvm::Constant *> Decls, 2457 llvm::GlobalVariable *Guard = nullptr); 2458 2459 /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global 2460 /// variables. 2461 void GenerateCXXGlobalDtorsFunc(llvm::Function *Fn, 2462 const std::vector<std::pair<llvm::WeakVH, 2463 llvm::Constant*> > &DtorsAndObjects); 2464 2465 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, 2466 const VarDecl *D, 2467 llvm::GlobalVariable *Addr, 2468 bool PerformInit); 2469 2470 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest); 2471 2472 void EmitSynthesizedCXXCopyCtor(llvm::Value *Dest, llvm::Value *Src, 2473 const Expr *Exp); 2474 2475 void enterFullExpression(const ExprWithCleanups *E) { 2476 if (E->getNumObjects() == 0) return; 2477 enterNonTrivialFullExpression(E); 2478 } 2479 void enterNonTrivialFullExpression(const ExprWithCleanups *E); 2480 2481 void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true); 2482 2483 void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest); 2484 2485 RValue EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest = nullptr); 2486 2487 //===--------------------------------------------------------------------===// 2488 // Annotations Emission 2489 //===--------------------------------------------------------------------===// 2490 2491 /// Emit an annotation call (intrinsic or builtin). 2492 llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn, 2493 llvm::Value *AnnotatedVal, 2494 StringRef AnnotationStr, 2495 SourceLocation Location); 2496 2497 /// Emit local annotations for the local variable V, declared by D. 2498 void EmitVarAnnotations(const VarDecl *D, llvm::Value *V); 2499 2500 /// Emit field annotations for the given field & value. Returns the 2501 /// annotation result. 2502 llvm::Value *EmitFieldAnnotations(const FieldDecl *D, llvm::Value *V); 2503 2504 //===--------------------------------------------------------------------===// 2505 // Internal Helpers 2506 //===--------------------------------------------------------------------===// 2507 2508 /// ContainsLabel - Return true if the statement contains a label in it. If 2509 /// this statement is not executed normally, it not containing a label means 2510 /// that we can just remove the code. 2511 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false); 2512 2513 /// containsBreak - Return true if the statement contains a break out of it. 2514 /// If the statement (recursively) contains a switch or loop with a break 2515 /// inside of it, this is fine. 2516 static bool containsBreak(const Stmt *S); 2517 2518 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 2519 /// to a constant, or if it does but contains a label, return false. If it 2520 /// constant folds return true and set the boolean result in Result. 2521 bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result); 2522 2523 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 2524 /// to a constant, or if it does but contains a label, return false. If it 2525 /// constant folds return true and set the folded value. 2526 bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result); 2527 2528 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an 2529 /// if statement) to the specified blocks. Based on the condition, this might 2530 /// try to simplify the codegen of the conditional based on the branch. 2531 /// TrueCount should be the number of times we expect the condition to 2532 /// evaluate to true based on PGO data. 2533 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, 2534 llvm::BasicBlock *FalseBlock, uint64_t TrueCount); 2535 2536 /// \brief Emit a description of a type in a format suitable for passing to 2537 /// a runtime sanitizer handler. 2538 llvm::Constant *EmitCheckTypeDescriptor(QualType T); 2539 2540 /// \brief Convert a value into a format suitable for passing to a runtime 2541 /// sanitizer handler. 2542 llvm::Value *EmitCheckValue(llvm::Value *V); 2543 2544 /// \brief Emit a description of a source location in a format suitable for 2545 /// passing to a runtime sanitizer handler. 2546 llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc); 2547 2548 /// \brief Specify under what conditions this check can be recovered 2549 enum CheckRecoverableKind { 2550 /// Always terminate program execution if this check fails 2551 CRK_Unrecoverable, 2552 /// Check supports recovering, allows user to specify which 2553 CRK_Recoverable, 2554 /// Runtime conditionally aborts, always need to support recovery. 2555 CRK_AlwaysRecoverable 2556 }; 2557 2558 /// \brief Create a basic block that will call a handler function in a 2559 /// sanitizer runtime with the provided arguments, and create a conditional 2560 /// branch to it. 2561 void EmitCheck(llvm::Value *Checked, StringRef CheckName, 2562 ArrayRef<llvm::Constant *> StaticArgs, 2563 ArrayRef<llvm::Value *> DynamicArgs, 2564 CheckRecoverableKind Recoverable); 2565 2566 /// \brief Create a basic block that will call the trap intrinsic, and emit a 2567 /// conditional branch to it, for the -ftrapv checks. 2568 void EmitTrapCheck(llvm::Value *Checked); 2569 2570 /// EmitCallArg - Emit a single call argument. 2571 void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType); 2572 2573 /// EmitDelegateCallArg - We are performing a delegate call; that 2574 /// is, the current function is delegating to another one. Produce 2575 /// a r-value suitable for passing the given parameter. 2576 void EmitDelegateCallArg(CallArgList &args, const VarDecl *param, 2577 SourceLocation loc); 2578 2579 /// SetFPAccuracy - Set the minimum required accuracy of the given floating 2580 /// point operation, expressed as the maximum relative error in ulp. 2581 void SetFPAccuracy(llvm::Value *Val, float Accuracy); 2582 2583 private: 2584 llvm::MDNode *getRangeForLoadFromType(QualType Ty); 2585 void EmitReturnOfRValue(RValue RV, QualType Ty); 2586 2587 void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New); 2588 2589 llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4> 2590 DeferredReplacements; 2591 2592 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty 2593 /// from function arguments into \arg Dst. See ABIArgInfo::Expand. 2594 /// 2595 /// \param AI - The first function argument of the expansion. 2596 void ExpandTypeFromArgs(QualType Ty, LValue Dst, 2597 SmallVectorImpl<llvm::Argument *>::iterator &AI); 2598 2599 /// ExpandTypeToArgs - Expand an RValue \arg RV, with the LLVM type for \arg 2600 /// Ty, into individual arguments on the provided vector \arg IRCallArgs, 2601 /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand. 2602 void ExpandTypeToArgs(QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy, 2603 SmallVectorImpl<llvm::Value *> &IRCallArgs, 2604 unsigned &IRCallArgPos); 2605 2606 llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info, 2607 const Expr *InputExpr, std::string &ConstraintStr); 2608 2609 llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info, 2610 LValue InputValue, QualType InputType, 2611 std::string &ConstraintStr, 2612 SourceLocation Loc); 2613 2614 public: 2615 /// EmitCallArgs - Emit call arguments for a function. 2616 template <typename T> 2617 void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo, 2618 CallExpr::const_arg_iterator ArgBeg, 2619 CallExpr::const_arg_iterator ArgEnd, 2620 const FunctionDecl *CalleeDecl = nullptr, 2621 unsigned ParamsToSkip = 0, bool ForceColumnInfo = false) { 2622 SmallVector<QualType, 16> ArgTypes; 2623 CallExpr::const_arg_iterator Arg = ArgBeg; 2624 2625 assert((ParamsToSkip == 0 || CallArgTypeInfo) && 2626 "Can't skip parameters if type info is not provided"); 2627 if (CallArgTypeInfo) { 2628 // First, use the argument types that the type info knows about 2629 for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip, 2630 E = CallArgTypeInfo->param_type_end(); 2631 I != E; ++I, ++Arg) { 2632 assert(Arg != ArgEnd && "Running over edge of argument list!"); 2633 #ifndef NDEBUG 2634 QualType ArgType = *I; 2635 QualType ActualArgType = Arg->getType(); 2636 if (ArgType->isPointerType() && ActualArgType->isPointerType()) { 2637 QualType ActualBaseType = 2638 ActualArgType->getAs<PointerType>()->getPointeeType(); 2639 QualType ArgBaseType = 2640 ArgType->getAs<PointerType>()->getPointeeType(); 2641 if (ArgBaseType->isVariableArrayType()) { 2642 if (const VariableArrayType *VAT = 2643 getContext().getAsVariableArrayType(ActualBaseType)) { 2644 if (!VAT->getSizeExpr()) 2645 ActualArgType = ArgType; 2646 } 2647 } 2648 } 2649 assert(getContext() 2650 .getCanonicalType(ArgType.getNonReferenceType()) 2651 .getTypePtr() == 2652 getContext().getCanonicalType(ActualArgType).getTypePtr() && 2653 "type mismatch in call argument!"); 2654 #endif 2655 ArgTypes.push_back(*I); 2656 } 2657 } 2658 2659 // Either we've emitted all the call args, or we have a call to variadic 2660 // function. 2661 assert( 2662 (Arg == ArgEnd || !CallArgTypeInfo || CallArgTypeInfo->isVariadic()) && 2663 "Extra arguments in non-variadic function!"); 2664 2665 // If we still have any arguments, emit them using the type of the argument. 2666 for (; Arg != ArgEnd; ++Arg) 2667 ArgTypes.push_back(Arg->getType()); 2668 2669 EmitCallArgs(Args, ArgTypes, ArgBeg, ArgEnd, CalleeDecl, ParamsToSkip, 2670 ForceColumnInfo); 2671 } 2672 2673 void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes, 2674 CallExpr::const_arg_iterator ArgBeg, 2675 CallExpr::const_arg_iterator ArgEnd, 2676 const FunctionDecl *CalleeDecl = nullptr, 2677 unsigned ParamsToSkip = 0, bool ForceColumnInfo = false); 2678 2679 private: 2680 const TargetCodeGenInfo &getTargetHooks() const { 2681 return CGM.getTargetCodeGenInfo(); 2682 } 2683 2684 void EmitDeclMetadata(); 2685 2686 CodeGenModule::ByrefHelpers * 2687 buildByrefHelpers(llvm::StructType &byrefType, 2688 const AutoVarEmission &emission); 2689 2690 void AddObjCARCExceptionMetadata(llvm::Instruction *Inst); 2691 2692 /// GetPointeeAlignment - Given an expression with a pointer type, emit the 2693 /// value and compute our best estimate of the alignment of the pointee. 2694 std::pair<llvm::Value*, unsigned> EmitPointerWithAlignment(const Expr *Addr); 2695 }; 2696 2697 /// Helper class with most of the code for saving a value for a 2698 /// conditional expression cleanup. 2699 struct DominatingLLVMValue { 2700 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type; 2701 2702 /// Answer whether the given value needs extra work to be saved. 2703 static bool needsSaving(llvm::Value *value) { 2704 // If it's not an instruction, we don't need to save. 2705 if (!isa<llvm::Instruction>(value)) return false; 2706 2707 // If it's an instruction in the entry block, we don't need to save. 2708 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent(); 2709 return (block != &block->getParent()->getEntryBlock()); 2710 } 2711 2712 /// Try to save the given value. 2713 static saved_type save(CodeGenFunction &CGF, llvm::Value *value) { 2714 if (!needsSaving(value)) return saved_type(value, false); 2715 2716 // Otherwise we need an alloca. 2717 llvm::Value *alloca = 2718 CGF.CreateTempAlloca(value->getType(), "cond-cleanup.save"); 2719 CGF.Builder.CreateStore(value, alloca); 2720 2721 return saved_type(alloca, true); 2722 } 2723 2724 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) { 2725 if (!value.getInt()) return value.getPointer(); 2726 return CGF.Builder.CreateLoad(value.getPointer()); 2727 } 2728 }; 2729 2730 /// A partial specialization of DominatingValue for llvm::Values that 2731 /// might be llvm::Instructions. 2732 template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue { 2733 typedef T *type; 2734 static type restore(CodeGenFunction &CGF, saved_type value) { 2735 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value)); 2736 } 2737 }; 2738 2739 /// A specialization of DominatingValue for RValue. 2740 template <> struct DominatingValue<RValue> { 2741 typedef RValue type; 2742 class saved_type { 2743 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral, 2744 AggregateAddress, ComplexAddress }; 2745 2746 llvm::Value *Value; 2747 Kind K; 2748 saved_type(llvm::Value *v, Kind k) : Value(v), K(k) {} 2749 2750 public: 2751 static bool needsSaving(RValue value); 2752 static saved_type save(CodeGenFunction &CGF, RValue value); 2753 RValue restore(CodeGenFunction &CGF); 2754 2755 // implementations in CGExprCXX.cpp 2756 }; 2757 2758 static bool needsSaving(type value) { 2759 return saved_type::needsSaving(value); 2760 } 2761 static saved_type save(CodeGenFunction &CGF, type value) { 2762 return saved_type::save(CGF, value); 2763 } 2764 static type restore(CodeGenFunction &CGF, saved_type value) { 2765 return value.restore(CGF); 2766 } 2767 }; 2768 2769 } // end namespace CodeGen 2770 } // end namespace clang 2771 2772 #endif 2773