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