clang API Documentation
00001 //===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This is the internal per-function state used for llvm translation. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H 00015 #define LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H 00016 00017 #include "CGBuilder.h" 00018 #include "CGDebugInfo.h" 00019 #include "CGLoopInfo.h" 00020 #include "CGValue.h" 00021 #include "CodeGenModule.h" 00022 #include "CodeGenPGO.h" 00023 #include "EHScopeStack.h" 00024 #include "clang/AST/CharUnits.h" 00025 #include "clang/AST/ExprCXX.h" 00026 #include "clang/AST/ExprObjC.h" 00027 #include "clang/AST/Type.h" 00028 #include "clang/Basic/ABI.h" 00029 #include "clang/Basic/CapturedStmt.h" 00030 #include "clang/Basic/TargetInfo.h" 00031 #include "clang/Frontend/CodeGenOptions.h" 00032 #include "llvm/ADT/ArrayRef.h" 00033 #include "llvm/ADT/DenseMap.h" 00034 #include "llvm/ADT/SmallVector.h" 00035 #include "llvm/IR/ValueHandle.h" 00036 #include "llvm/Support/Debug.h" 00037 00038 namespace llvm { 00039 class BasicBlock; 00040 class LLVMContext; 00041 class MDNode; 00042 class Module; 00043 class SwitchInst; 00044 class Twine; 00045 class Value; 00046 class CallSite; 00047 } 00048 00049 namespace clang { 00050 class ASTContext; 00051 class BlockDecl; 00052 class CXXDestructorDecl; 00053 class CXXForRangeStmt; 00054 class CXXTryStmt; 00055 class Decl; 00056 class LabelDecl; 00057 class EnumConstantDecl; 00058 class FunctionDecl; 00059 class FunctionProtoType; 00060 class LabelStmt; 00061 class ObjCContainerDecl; 00062 class ObjCInterfaceDecl; 00063 class ObjCIvarDecl; 00064 class ObjCMethodDecl; 00065 class ObjCImplementationDecl; 00066 class ObjCPropertyImplDecl; 00067 class TargetInfo; 00068 class TargetCodeGenInfo; 00069 class VarDecl; 00070 class ObjCForCollectionStmt; 00071 class ObjCAtTryStmt; 00072 class ObjCAtThrowStmt; 00073 class ObjCAtSynchronizedStmt; 00074 class ObjCAutoreleasePoolStmt; 00075 00076 namespace CodeGen { 00077 class CodeGenTypes; 00078 class CGFunctionInfo; 00079 class CGRecordLayout; 00080 class CGBlockInfo; 00081 class CGCXXABI; 00082 class BlockFlags; 00083 class BlockFieldFlags; 00084 00085 /// The kind of evaluation to perform on values of a particular 00086 /// type. Basically, is the code in CGExprScalar, CGExprComplex, or 00087 /// CGExprAgg? 00088 /// 00089 /// TODO: should vectors maybe be split out into their own thing? 00090 enum TypeEvaluationKind { 00091 TEK_Scalar, 00092 TEK_Complex, 00093 TEK_Aggregate 00094 }; 00095 00096 class SuppressDebugLocation { 00097 llvm::DebugLoc CurLoc; 00098 llvm::IRBuilderBase &Builder; 00099 public: 00100 SuppressDebugLocation(llvm::IRBuilderBase &Builder) 00101 : CurLoc(Builder.getCurrentDebugLocation()), Builder(Builder) { 00102 Builder.SetCurrentDebugLocation(llvm::DebugLoc()); 00103 } 00104 ~SuppressDebugLocation() { 00105 Builder.SetCurrentDebugLocation(CurLoc); 00106 } 00107 }; 00108 00109 /// CodeGenFunction - This class organizes the per-function state that is used 00110 /// while generating LLVM code. 00111 class CodeGenFunction : public CodeGenTypeCache { 00112 CodeGenFunction(const CodeGenFunction &) LLVM_DELETED_FUNCTION; 00113 void operator=(const CodeGenFunction &) LLVM_DELETED_FUNCTION; 00114 00115 friend class CGCXXABI; 00116 public: 00117 /// A jump destination is an abstract label, branching to which may 00118 /// require a jump out through normal cleanups. 00119 struct JumpDest { 00120 JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {} 00121 JumpDest(llvm::BasicBlock *Block, 00122 EHScopeStack::stable_iterator Depth, 00123 unsigned Index) 00124 : Block(Block), ScopeDepth(Depth), Index(Index) {} 00125 00126 bool isValid() const { return Block != nullptr; } 00127 llvm::BasicBlock *getBlock() const { return Block; } 00128 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; } 00129 unsigned getDestIndex() const { return Index; } 00130 00131 // This should be used cautiously. 00132 void setScopeDepth(EHScopeStack::stable_iterator depth) { 00133 ScopeDepth = depth; 00134 } 00135 00136 private: 00137 llvm::BasicBlock *Block; 00138 EHScopeStack::stable_iterator ScopeDepth; 00139 unsigned Index; 00140 }; 00141 00142 CodeGenModule &CGM; // Per-module state. 00143 const TargetInfo &Target; 00144 00145 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy; 00146 LoopInfoStack LoopStack; 00147 CGBuilderTy Builder; 00148 00149 /// \brief CGBuilder insert helper. This function is called after an 00150 /// instruction is created using Builder. 00151 void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, 00152 llvm::BasicBlock *BB, 00153 llvm::BasicBlock::iterator InsertPt) const; 00154 00155 /// CurFuncDecl - Holds the Decl for the current outermost 00156 /// non-closure context. 00157 const Decl *CurFuncDecl; 00158 /// CurCodeDecl - This is the inner-most code context, which includes blocks. 00159 const Decl *CurCodeDecl; 00160 const CGFunctionInfo *CurFnInfo; 00161 QualType FnRetTy; 00162 llvm::Function *CurFn; 00163 00164 /// CurGD - The GlobalDecl for the current function being compiled. 00165 GlobalDecl CurGD; 00166 00167 /// PrologueCleanupDepth - The cleanup depth enclosing all the 00168 /// cleanups associated with the parameters. 00169 EHScopeStack::stable_iterator PrologueCleanupDepth; 00170 00171 /// ReturnBlock - Unified return block. 00172 JumpDest ReturnBlock; 00173 00174 /// ReturnValue - The temporary alloca to hold the return value. This is null 00175 /// iff the function has no return value. 00176 llvm::Value *ReturnValue; 00177 00178 /// AllocaInsertPoint - This is an instruction in the entry block before which 00179 /// we prefer to insert allocas. 00180 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt; 00181 00182 /// \brief API for captured statement code generation. 00183 class CGCapturedStmtInfo { 00184 public: 00185 explicit CGCapturedStmtInfo(const CapturedStmt &S, 00186 CapturedRegionKind K = CR_Default) 00187 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) { 00188 00189 RecordDecl::field_iterator Field = 00190 S.getCapturedRecordDecl()->field_begin(); 00191 for (CapturedStmt::const_capture_iterator I = S.capture_begin(), 00192 E = S.capture_end(); 00193 I != E; ++I, ++Field) { 00194 if (I->capturesThis()) 00195 CXXThisFieldDecl = *Field; 00196 else if (I->capturesVariable()) 00197 CaptureFields[I->getCapturedVar()] = *Field; 00198 } 00199 } 00200 00201 virtual ~CGCapturedStmtInfo(); 00202 00203 CapturedRegionKind getKind() const { return Kind; } 00204 00205 void setContextValue(llvm::Value *V) { ThisValue = V; } 00206 // \brief Retrieve the value of the context parameter. 00207 llvm::Value *getContextValue() const { return ThisValue; } 00208 00209 /// \brief Lookup the captured field decl for a variable. 00210 const FieldDecl *lookup(const VarDecl *VD) const { 00211 return CaptureFields.lookup(VD); 00212 } 00213 00214 bool isCXXThisExprCaptured() const { return CXXThisFieldDecl != nullptr; } 00215 FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; } 00216 00217 static bool classof(const CGCapturedStmtInfo *) { 00218 return true; 00219 } 00220 00221 /// \brief Emit the captured statement body. 00222 virtual void EmitBody(CodeGenFunction &CGF, Stmt *S) { 00223 RegionCounter Cnt = CGF.getPGORegionCounter(S); 00224 Cnt.beginRegion(CGF.Builder); 00225 CGF.EmitStmt(S); 00226 } 00227 00228 /// \brief Get the name of the capture helper. 00229 virtual StringRef getHelperName() const { return "__captured_stmt"; } 00230 00231 private: 00232 /// \brief The kind of captured statement being generated. 00233 CapturedRegionKind Kind; 00234 00235 /// \brief Keep the map between VarDecl and FieldDecl. 00236 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields; 00237 00238 /// \brief The base address of the captured record, passed in as the first 00239 /// argument of the parallel region function. 00240 llvm::Value *ThisValue; 00241 00242 /// \brief Captured 'this' type. 00243 FieldDecl *CXXThisFieldDecl; 00244 }; 00245 CGCapturedStmtInfo *CapturedStmtInfo; 00246 00247 /// BoundsChecking - Emit run-time bounds checks. Higher values mean 00248 /// potentially higher performance penalties. 00249 unsigned char BoundsChecking; 00250 00251 /// \brief Sanitizers enabled for this function. 00252 SanitizerSet SanOpts; 00253 00254 /// \brief True if CodeGen currently emits code implementing sanitizer checks. 00255 bool IsSanitizerScope; 00256 00257 /// \brief RAII object to set/unset CodeGenFunction::IsSanitizerScope. 00258 class SanitizerScope { 00259 CodeGenFunction *CGF; 00260 public: 00261 SanitizerScope(CodeGenFunction *CGF); 00262 ~SanitizerScope(); 00263 }; 00264 00265 /// In C++, whether we are code generating a thunk. This controls whether we 00266 /// should emit cleanups. 00267 bool CurFuncIsThunk; 00268 00269 /// In ARC, whether we should autorelease the return value. 00270 bool AutoreleaseResult; 00271 00272 /// Whether we processed a Microsoft-style asm block during CodeGen. These can 00273 /// potentially set the return value. 00274 bool SawAsmBlock; 00275 00276 const CodeGen::CGBlockInfo *BlockInfo; 00277 llvm::Value *BlockPointer; 00278 00279 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 00280 FieldDecl *LambdaThisCaptureField; 00281 00282 /// \brief A mapping from NRVO variables to the flags used to indicate 00283 /// when the NRVO has been applied to this variable. 00284 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags; 00285 00286 EHScopeStack EHStack; 00287 llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack; 00288 00289 /// Header for data within LifetimeExtendedCleanupStack. 00290 struct LifetimeExtendedCleanupHeader { 00291 /// The size of the following cleanup object. 00292 unsigned Size : 29; 00293 /// The kind of cleanup to push: a value from the CleanupKind enumeration. 00294 unsigned Kind : 3; 00295 00296 size_t getSize() const { return size_t(Size); } 00297 CleanupKind getKind() const { return static_cast<CleanupKind>(Kind); } 00298 }; 00299 00300 /// i32s containing the indexes of the cleanup destinations. 00301 llvm::AllocaInst *NormalCleanupDest; 00302 00303 unsigned NextCleanupDestIndex; 00304 00305 /// FirstBlockInfo - The head of a singly-linked-list of block layouts. 00306 CGBlockInfo *FirstBlockInfo; 00307 00308 /// EHResumeBlock - Unified block containing a call to llvm.eh.resume. 00309 llvm::BasicBlock *EHResumeBlock; 00310 00311 /// The exception slot. All landing pads write the current exception pointer 00312 /// into this alloca. 00313 llvm::Value *ExceptionSlot; 00314 00315 /// The selector slot. Under the MandatoryCleanup model, all landing pads 00316 /// write the current selector value into this alloca. 00317 llvm::AllocaInst *EHSelectorSlot; 00318 00319 /// Emits a landing pad for the current EH stack. 00320 llvm::BasicBlock *EmitLandingPad(); 00321 00322 llvm::BasicBlock *getInvokeDestImpl(); 00323 00324 template <class T> 00325 typename DominatingValue<T>::saved_type saveValueInCond(T value) { 00326 return DominatingValue<T>::save(*this, value); 00327 } 00328 00329 public: 00330 /// ObjCEHValueStack - Stack of Objective-C exception values, used for 00331 /// rethrows. 00332 SmallVector<llvm::Value*, 8> ObjCEHValueStack; 00333 00334 /// A class controlling the emission of a finally block. 00335 class FinallyInfo { 00336 /// Where the catchall's edge through the cleanup should go. 00337 JumpDest RethrowDest; 00338 00339 /// A function to call to enter the catch. 00340 llvm::Constant *BeginCatchFn; 00341 00342 /// An i1 variable indicating whether or not the @finally is 00343 /// running for an exception. 00344 llvm::AllocaInst *ForEHVar; 00345 00346 /// An i8* variable into which the exception pointer to rethrow 00347 /// has been saved. 00348 llvm::AllocaInst *SavedExnVar; 00349 00350 public: 00351 void enter(CodeGenFunction &CGF, const Stmt *Finally, 00352 llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn, 00353 llvm::Constant *rethrowFn); 00354 void exit(CodeGenFunction &CGF); 00355 }; 00356 00357 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 00358 /// current full-expression. Safe against the possibility that 00359 /// we're currently inside a conditionally-evaluated expression. 00360 template <class T, class A0> 00361 void pushFullExprCleanup(CleanupKind kind, A0 a0) { 00362 // If we're not in a conditional branch, or if none of the 00363 // arguments requires saving, then use the unconditional cleanup. 00364 if (!isInConditionalBranch()) 00365 return EHStack.pushCleanup<T>(kind, a0); 00366 00367 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 00368 00369 typedef EHScopeStack::ConditionalCleanup1<T, A0> CleanupType; 00370 EHStack.pushCleanup<CleanupType>(kind, a0_saved); 00371 initFullExprCleanup(); 00372 } 00373 00374 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 00375 /// current full-expression. Safe against the possibility that 00376 /// we're currently inside a conditionally-evaluated expression. 00377 template <class T, class A0, class A1> 00378 void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1) { 00379 // If we're not in a conditional branch, or if none of the 00380 // arguments requires saving, then use the unconditional cleanup. 00381 if (!isInConditionalBranch()) 00382 return EHStack.pushCleanup<T>(kind, a0, a1); 00383 00384 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 00385 typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1); 00386 00387 typedef EHScopeStack::ConditionalCleanup2<T, A0, A1> CleanupType; 00388 EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved); 00389 initFullExprCleanup(); 00390 } 00391 00392 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 00393 /// current full-expression. Safe against the possibility that 00394 /// we're currently inside a conditionally-evaluated expression. 00395 template <class T, class A0, class A1, class A2> 00396 void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2) { 00397 // If we're not in a conditional branch, or if none of the 00398 // arguments requires saving, then use the unconditional cleanup. 00399 if (!isInConditionalBranch()) { 00400 return EHStack.pushCleanup<T>(kind, a0, a1, a2); 00401 } 00402 00403 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 00404 typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1); 00405 typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2); 00406 00407 typedef EHScopeStack::ConditionalCleanup3<T, A0, A1, A2> CleanupType; 00408 EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved, a2_saved); 00409 initFullExprCleanup(); 00410 } 00411 00412 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 00413 /// current full-expression. Safe against the possibility that 00414 /// we're currently inside a conditionally-evaluated expression. 00415 template <class T, class A0, class A1, class A2, class A3> 00416 void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2, A3 a3) { 00417 // If we're not in a conditional branch, or if none of the 00418 // arguments requires saving, then use the unconditional cleanup. 00419 if (!isInConditionalBranch()) { 00420 return EHStack.pushCleanup<T>(kind, a0, a1, a2, a3); 00421 } 00422 00423 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 00424 typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1); 00425 typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2); 00426 typename DominatingValue<A3>::saved_type a3_saved = saveValueInCond(a3); 00427 00428 typedef EHScopeStack::ConditionalCleanup4<T, A0, A1, A2, A3> CleanupType; 00429 EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved, 00430 a2_saved, a3_saved); 00431 initFullExprCleanup(); 00432 } 00433 00434 /// \brief Queue a cleanup to be pushed after finishing the current 00435 /// full-expression. 00436 template <class T, class A0, class A1, class A2, class A3> 00437 void pushCleanupAfterFullExpr(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3) { 00438 assert(!isInConditionalBranch() && "can't defer conditional cleanup"); 00439 00440 LifetimeExtendedCleanupHeader Header = { sizeof(T), Kind }; 00441 00442 size_t OldSize = LifetimeExtendedCleanupStack.size(); 00443 LifetimeExtendedCleanupStack.resize( 00444 LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size); 00445 00446 char *Buffer = &LifetimeExtendedCleanupStack[OldSize]; 00447 new (Buffer) LifetimeExtendedCleanupHeader(Header); 00448 new (Buffer + sizeof(Header)) T(a0, a1, a2, a3); 00449 } 00450 00451 /// Set up the last cleaup that was pushed as a conditional 00452 /// full-expression cleanup. 00453 void initFullExprCleanup(); 00454 00455 /// PushDestructorCleanup - Push a cleanup to call the 00456 /// complete-object destructor of an object of the given type at the 00457 /// given address. Does nothing if T is not a C++ class type with a 00458 /// non-trivial destructor. 00459 void PushDestructorCleanup(QualType T, llvm::Value *Addr); 00460 00461 /// PushDestructorCleanup - Push a cleanup to call the 00462 /// complete-object variant of the given destructor on the object at 00463 /// the given address. 00464 void PushDestructorCleanup(const CXXDestructorDecl *Dtor, 00465 llvm::Value *Addr); 00466 00467 /// PopCleanupBlock - Will pop the cleanup entry on the stack and 00468 /// process all branch fixups. 00469 void PopCleanupBlock(bool FallThroughIsBranchThrough = false); 00470 00471 /// DeactivateCleanupBlock - Deactivates the given cleanup block. 00472 /// The block cannot be reactivated. Pops it if it's the top of the 00473 /// stack. 00474 /// 00475 /// \param DominatingIP - An instruction which is known to 00476 /// dominate the current IP (if set) and which lies along 00477 /// all paths of execution between the current IP and the 00478 /// the point at which the cleanup comes into scope. 00479 void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, 00480 llvm::Instruction *DominatingIP); 00481 00482 /// ActivateCleanupBlock - Activates an initially-inactive cleanup. 00483 /// Cannot be used to resurrect a deactivated cleanup. 00484 /// 00485 /// \param DominatingIP - An instruction which is known to 00486 /// dominate the current IP (if set) and which lies along 00487 /// all paths of execution between the current IP and the 00488 /// the point at which the cleanup comes into scope. 00489 void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, 00490 llvm::Instruction *DominatingIP); 00491 00492 /// \brief Enters a new scope for capturing cleanups, all of which 00493 /// will be executed once the scope is exited. 00494 class RunCleanupsScope { 00495 EHScopeStack::stable_iterator CleanupStackDepth; 00496 size_t LifetimeExtendedCleanupStackSize; 00497 bool OldDidCallStackSave; 00498 protected: 00499 bool PerformCleanup; 00500 private: 00501 00502 RunCleanupsScope(const RunCleanupsScope &) LLVM_DELETED_FUNCTION; 00503 void operator=(const RunCleanupsScope &) LLVM_DELETED_FUNCTION; 00504 00505 protected: 00506 CodeGenFunction& CGF; 00507 00508 public: 00509 /// \brief Enter a new cleanup scope. 00510 explicit RunCleanupsScope(CodeGenFunction &CGF) 00511 : PerformCleanup(true), CGF(CGF) 00512 { 00513 CleanupStackDepth = CGF.EHStack.stable_begin(); 00514 LifetimeExtendedCleanupStackSize = 00515 CGF.LifetimeExtendedCleanupStack.size(); 00516 OldDidCallStackSave = CGF.DidCallStackSave; 00517 CGF.DidCallStackSave = false; 00518 } 00519 00520 /// \brief Exit this cleanup scope, emitting any accumulated 00521 /// cleanups. 00522 ~RunCleanupsScope() { 00523 if (PerformCleanup) { 00524 CGF.DidCallStackSave = OldDidCallStackSave; 00525 CGF.PopCleanupBlocks(CleanupStackDepth, 00526 LifetimeExtendedCleanupStackSize); 00527 } 00528 } 00529 00530 /// \brief Determine whether this scope requires any cleanups. 00531 bool requiresCleanups() const { 00532 return CGF.EHStack.stable_begin() != CleanupStackDepth; 00533 } 00534 00535 /// \brief Force the emission of cleanups now, instead of waiting 00536 /// until this object is destroyed. 00537 void ForceCleanup() { 00538 assert(PerformCleanup && "Already forced cleanup"); 00539 CGF.DidCallStackSave = OldDidCallStackSave; 00540 CGF.PopCleanupBlocks(CleanupStackDepth, 00541 LifetimeExtendedCleanupStackSize); 00542 PerformCleanup = false; 00543 } 00544 }; 00545 00546 class LexicalScope : public RunCleanupsScope { 00547 SourceRange Range; 00548 SmallVector<const LabelDecl*, 4> Labels; 00549 LexicalScope *ParentScope; 00550 00551 LexicalScope(const LexicalScope &) LLVM_DELETED_FUNCTION; 00552 void operator=(const LexicalScope &) LLVM_DELETED_FUNCTION; 00553 00554 public: 00555 /// \brief Enter a new cleanup scope. 00556 explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range) 00557 : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) { 00558 CGF.CurLexicalScope = this; 00559 if (CGDebugInfo *DI = CGF.getDebugInfo()) 00560 DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin()); 00561 } 00562 00563 void addLabel(const LabelDecl *label) { 00564 assert(PerformCleanup && "adding label to dead scope?"); 00565 Labels.push_back(label); 00566 } 00567 00568 /// \brief Exit this cleanup scope, emitting any accumulated 00569 /// cleanups. 00570 ~LexicalScope() { 00571 if (CGDebugInfo *DI = CGF.getDebugInfo()) 00572 DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd()); 00573 00574 // If we should perform a cleanup, force them now. Note that 00575 // this ends the cleanup scope before rescoping any labels. 00576 if (PerformCleanup) ForceCleanup(); 00577 } 00578 00579 /// \brief Force the emission of cleanups now, instead of waiting 00580 /// until this object is destroyed. 00581 void ForceCleanup() { 00582 CGF.CurLexicalScope = ParentScope; 00583 RunCleanupsScope::ForceCleanup(); 00584 00585 if (!Labels.empty()) 00586 rescopeLabels(); 00587 } 00588 00589 void rescopeLabels(); 00590 }; 00591 00592 /// \brief The scope used to remap some variables as private in the OpenMP 00593 /// loop body (or other captured region emitted without outlining), and to 00594 /// restore old vars back on exit. 00595 class OMPPrivateScope : public RunCleanupsScope { 00596 typedef llvm::DenseMap<const VarDecl *, llvm::Value *> VarDeclMapTy; 00597 VarDeclMapTy SavedLocals; 00598 VarDeclMapTy SavedPrivates; 00599 00600 private: 00601 OMPPrivateScope(const OMPPrivateScope &) LLVM_DELETED_FUNCTION; 00602 void operator=(const OMPPrivateScope &) LLVM_DELETED_FUNCTION; 00603 00604 public: 00605 /// \brief Enter a new OpenMP private scope. 00606 explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {} 00607 00608 /// \brief Registers \a LocalVD variable as a private and apply \a 00609 /// PrivateGen function for it to generate corresponding private variable. 00610 /// \a PrivateGen returns an address of the generated private variable. 00611 /// \return true if the variable is registered as private, false if it has 00612 /// been privatized already. 00613 bool 00614 addPrivate(const VarDecl *LocalVD, 00615 const std::function<llvm::Value *()> &PrivateGen) { 00616 assert(PerformCleanup && "adding private to dead scope"); 00617 assert(LocalVD->isLocalVarDecl() && "privatizing non-local variable"); 00618 if (SavedLocals.count(LocalVD) > 0) return false; 00619 SavedLocals[LocalVD] = CGF.LocalDeclMap.lookup(LocalVD); 00620 CGF.LocalDeclMap.erase(LocalVD); 00621 SavedPrivates[LocalVD] = PrivateGen(); 00622 CGF.LocalDeclMap[LocalVD] = SavedLocals[LocalVD]; 00623 return true; 00624 } 00625 00626 /// \brief Privatizes local variables previously registered as private. 00627 /// Registration is separate from the actual privatization to allow 00628 /// initializers use values of the original variables, not the private one. 00629 /// This is important, for example, if the private variable is a class 00630 /// variable initialized by a constructor that references other private 00631 /// variables. But at initialization original variables must be used, not 00632 /// private copies. 00633 /// \return true if at least one variable was privatized, false otherwise. 00634 bool Privatize() { 00635 for (auto VDPair : SavedPrivates) { 00636 CGF.LocalDeclMap[VDPair.first] = VDPair.second; 00637 } 00638 SavedPrivates.clear(); 00639 return !SavedLocals.empty(); 00640 } 00641 00642 void ForceCleanup() { 00643 RunCleanupsScope::ForceCleanup(); 00644 // Remap vars back to the original values. 00645 for (auto I : SavedLocals) { 00646 CGF.LocalDeclMap[I.first] = I.second; 00647 } 00648 SavedLocals.clear(); 00649 } 00650 00651 /// \brief Exit scope - all the mapped variables are restored. 00652 ~OMPPrivateScope() { ForceCleanup(); } 00653 }; 00654 00655 /// \brief Takes the old cleanup stack size and emits the cleanup blocks 00656 /// that have been added. 00657 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize); 00658 00659 /// \brief Takes the old cleanup stack size and emits the cleanup blocks 00660 /// that have been added, then adds all lifetime-extended cleanups from 00661 /// the given position to the stack. 00662 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize, 00663 size_t OldLifetimeExtendedStackSize); 00664 00665 void ResolveBranchFixups(llvm::BasicBlock *Target); 00666 00667 /// The given basic block lies in the current EH scope, but may be a 00668 /// target of a potentially scope-crossing jump; get a stable handle 00669 /// to which we can perform this jump later. 00670 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) { 00671 return JumpDest(Target, 00672 EHStack.getInnermostNormalCleanup(), 00673 NextCleanupDestIndex++); 00674 } 00675 00676 /// The given basic block lies in the current EH scope, but may be a 00677 /// target of a potentially scope-crossing jump; get a stable handle 00678 /// to which we can perform this jump later. 00679 JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) { 00680 return getJumpDestInCurrentScope(createBasicBlock(Name)); 00681 } 00682 00683 /// EmitBranchThroughCleanup - Emit a branch from the current insert 00684 /// block through the normal cleanup handling code (if any) and then 00685 /// on to \arg Dest. 00686 void EmitBranchThroughCleanup(JumpDest Dest); 00687 00688 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the 00689 /// specified destination obviously has no cleanups to run. 'false' is always 00690 /// a conservatively correct answer for this method. 00691 bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const; 00692 00693 /// popCatchScope - Pops the catch scope at the top of the EHScope 00694 /// stack, emitting any required code (other than the catch handlers 00695 /// themselves). 00696 void popCatchScope(); 00697 00698 llvm::BasicBlock *getEHResumeBlock(bool isCleanup); 00699 llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope); 00700 00701 /// An object to manage conditionally-evaluated expressions. 00702 class ConditionalEvaluation { 00703 llvm::BasicBlock *StartBB; 00704 00705 public: 00706 ConditionalEvaluation(CodeGenFunction &CGF) 00707 : StartBB(CGF.Builder.GetInsertBlock()) {} 00708 00709 void begin(CodeGenFunction &CGF) { 00710 assert(CGF.OutermostConditional != this); 00711 if (!CGF.OutermostConditional) 00712 CGF.OutermostConditional = this; 00713 } 00714 00715 void end(CodeGenFunction &CGF) { 00716 assert(CGF.OutermostConditional != nullptr); 00717 if (CGF.OutermostConditional == this) 00718 CGF.OutermostConditional = nullptr; 00719 } 00720 00721 /// Returns a block which will be executed prior to each 00722 /// evaluation of the conditional code. 00723 llvm::BasicBlock *getStartingBlock() const { 00724 return StartBB; 00725 } 00726 }; 00727 00728 /// isInConditionalBranch - Return true if we're currently emitting 00729 /// one branch or the other of a conditional expression. 00730 bool isInConditionalBranch() const { return OutermostConditional != nullptr; } 00731 00732 void setBeforeOutermostConditional(llvm::Value *value, llvm::Value *addr) { 00733 assert(isInConditionalBranch()); 00734 llvm::BasicBlock *block = OutermostConditional->getStartingBlock(); 00735 new llvm::StoreInst(value, addr, &block->back()); 00736 } 00737 00738 /// An RAII object to record that we're evaluating a statement 00739 /// expression. 00740 class StmtExprEvaluation { 00741 CodeGenFunction &CGF; 00742 00743 /// We have to save the outermost conditional: cleanups in a 00744 /// statement expression aren't conditional just because the 00745 /// StmtExpr is. 00746 ConditionalEvaluation *SavedOutermostConditional; 00747 00748 public: 00749 StmtExprEvaluation(CodeGenFunction &CGF) 00750 : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) { 00751 CGF.OutermostConditional = nullptr; 00752 } 00753 00754 ~StmtExprEvaluation() { 00755 CGF.OutermostConditional = SavedOutermostConditional; 00756 CGF.EnsureInsertPoint(); 00757 } 00758 }; 00759 00760 /// An object which temporarily prevents a value from being 00761 /// destroyed by aggressive peephole optimizations that assume that 00762 /// all uses of a value have been realized in the IR. 00763 class PeepholeProtection { 00764 llvm::Instruction *Inst; 00765 friend class CodeGenFunction; 00766 00767 public: 00768 PeepholeProtection() : Inst(nullptr) {} 00769 }; 00770 00771 /// A non-RAII class containing all the information about a bound 00772 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for 00773 /// this which makes individual mappings very simple; using this 00774 /// class directly is useful when you have a variable number of 00775 /// opaque values or don't want the RAII functionality for some 00776 /// reason. 00777 class OpaqueValueMappingData { 00778 const OpaqueValueExpr *OpaqueValue; 00779 bool BoundLValue; 00780 CodeGenFunction::PeepholeProtection Protection; 00781 00782 OpaqueValueMappingData(const OpaqueValueExpr *ov, 00783 bool boundLValue) 00784 : OpaqueValue(ov), BoundLValue(boundLValue) {} 00785 public: 00786 OpaqueValueMappingData() : OpaqueValue(nullptr) {} 00787 00788 static bool shouldBindAsLValue(const Expr *expr) { 00789 // gl-values should be bound as l-values for obvious reasons. 00790 // Records should be bound as l-values because IR generation 00791 // always keeps them in memory. Expressions of function type 00792 // act exactly like l-values but are formally required to be 00793 // r-values in C. 00794 return expr->isGLValue() || 00795 expr->getType()->isFunctionType() || 00796 hasAggregateEvaluationKind(expr->getType()); 00797 } 00798 00799 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 00800 const OpaqueValueExpr *ov, 00801 const Expr *e) { 00802 if (shouldBindAsLValue(ov)) 00803 return bind(CGF, ov, CGF.EmitLValue(e)); 00804 return bind(CGF, ov, CGF.EmitAnyExpr(e)); 00805 } 00806 00807 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 00808 const OpaqueValueExpr *ov, 00809 const LValue &lv) { 00810 assert(shouldBindAsLValue(ov)); 00811 CGF.OpaqueLValues.insert(std::make_pair(ov, lv)); 00812 return OpaqueValueMappingData(ov, true); 00813 } 00814 00815 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 00816 const OpaqueValueExpr *ov, 00817 const RValue &rv) { 00818 assert(!shouldBindAsLValue(ov)); 00819 CGF.OpaqueRValues.insert(std::make_pair(ov, rv)); 00820 00821 OpaqueValueMappingData data(ov, false); 00822 00823 // Work around an extremely aggressive peephole optimization in 00824 // EmitScalarConversion which assumes that all other uses of a 00825 // value are extant. 00826 data.Protection = CGF.protectFromPeepholes(rv); 00827 00828 return data; 00829 } 00830 00831 bool isValid() const { return OpaqueValue != nullptr; } 00832 void clear() { OpaqueValue = nullptr; } 00833 00834 void unbind(CodeGenFunction &CGF) { 00835 assert(OpaqueValue && "no data to unbind!"); 00836 00837 if (BoundLValue) { 00838 CGF.OpaqueLValues.erase(OpaqueValue); 00839 } else { 00840 CGF.OpaqueRValues.erase(OpaqueValue); 00841 CGF.unprotectFromPeepholes(Protection); 00842 } 00843 } 00844 }; 00845 00846 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr. 00847 class OpaqueValueMapping { 00848 CodeGenFunction &CGF; 00849 OpaqueValueMappingData Data; 00850 00851 public: 00852 static bool shouldBindAsLValue(const Expr *expr) { 00853 return OpaqueValueMappingData::shouldBindAsLValue(expr); 00854 } 00855 00856 /// Build the opaque value mapping for the given conditional 00857 /// operator if it's the GNU ?: extension. This is a common 00858 /// enough pattern that the convenience operator is really 00859 /// helpful. 00860 /// 00861 OpaqueValueMapping(CodeGenFunction &CGF, 00862 const AbstractConditionalOperator *op) : CGF(CGF) { 00863 if (isa<ConditionalOperator>(op)) 00864 // Leave Data empty. 00865 return; 00866 00867 const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op); 00868 Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(), 00869 e->getCommon()); 00870 } 00871 00872 OpaqueValueMapping(CodeGenFunction &CGF, 00873 const OpaqueValueExpr *opaqueValue, 00874 LValue lvalue) 00875 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) { 00876 } 00877 00878 OpaqueValueMapping(CodeGenFunction &CGF, 00879 const OpaqueValueExpr *opaqueValue, 00880 RValue rvalue) 00881 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) { 00882 } 00883 00884 void pop() { 00885 Data.unbind(CGF); 00886 Data.clear(); 00887 } 00888 00889 ~OpaqueValueMapping() { 00890 if (Data.isValid()) Data.unbind(CGF); 00891 } 00892 }; 00893 00894 /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field 00895 /// number that holds the value. 00896 unsigned getByRefValueLLVMField(const ValueDecl *VD) const; 00897 00898 /// BuildBlockByrefAddress - Computes address location of the 00899 /// variable which is declared as __block. 00900 llvm::Value *BuildBlockByrefAddress(llvm::Value *BaseAddr, 00901 const VarDecl *V); 00902 private: 00903 CGDebugInfo *DebugInfo; 00904 bool DisableDebugInfo; 00905 00906 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid 00907 /// calling llvm.stacksave for multiple VLAs in the same scope. 00908 bool DidCallStackSave; 00909 00910 /// IndirectBranch - The first time an indirect goto is seen we create a block 00911 /// with an indirect branch. Every time we see the address of a label taken, 00912 /// we add the label to the indirect goto. Every subsequent indirect goto is 00913 /// codegen'd as a jump to the IndirectBranch's basic block. 00914 llvm::IndirectBrInst *IndirectBranch; 00915 00916 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C 00917 /// decls. 00918 typedef llvm::DenseMap<const Decl*, llvm::Value*> DeclMapTy; 00919 DeclMapTy LocalDeclMap; 00920 00921 /// LabelMap - This keeps track of the LLVM basic block for each C label. 00922 llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap; 00923 00924 // BreakContinueStack - This keeps track of where break and continue 00925 // statements should jump to. 00926 struct BreakContinue { 00927 BreakContinue(JumpDest Break, JumpDest Continue) 00928 : BreakBlock(Break), ContinueBlock(Continue) {} 00929 00930 JumpDest BreakBlock; 00931 JumpDest ContinueBlock; 00932 }; 00933 SmallVector<BreakContinue, 8> BreakContinueStack; 00934 00935 CodeGenPGO PGO; 00936 00937 public: 00938 /// Get a counter for instrumentation of the region associated with the given 00939 /// statement. 00940 RegionCounter getPGORegionCounter(const Stmt *S) { 00941 return RegionCounter(PGO, S); 00942 } 00943 private: 00944 00945 /// SwitchInsn - This is nearest current switch instruction. It is null if 00946 /// current context is not in a switch. 00947 llvm::SwitchInst *SwitchInsn; 00948 /// The branch weights of SwitchInsn when doing instrumentation based PGO. 00949 SmallVector<uint64_t, 16> *SwitchWeights; 00950 00951 /// CaseRangeBlock - This block holds if condition check for last case 00952 /// statement range in current switch instruction. 00953 llvm::BasicBlock *CaseRangeBlock; 00954 00955 /// OpaqueLValues - Keeps track of the current set of opaque value 00956 /// expressions. 00957 llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues; 00958 llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues; 00959 00960 // VLASizeMap - This keeps track of the associated size for each VLA type. 00961 // We track this by the size expression rather than the type itself because 00962 // in certain situations, like a const qualifier applied to an VLA typedef, 00963 // multiple VLA types can share the same size expression. 00964 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we 00965 // enter/leave scopes. 00966 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap; 00967 00968 /// A block containing a single 'unreachable' instruction. Created 00969 /// lazily by getUnreachableBlock(). 00970 llvm::BasicBlock *UnreachableBlock; 00971 00972 /// Counts of the number return expressions in the function. 00973 unsigned NumReturnExprs; 00974 00975 /// Count the number of simple (constant) return expressions in the function. 00976 unsigned NumSimpleReturnExprs; 00977 00978 /// The last regular (non-return) debug location (breakpoint) in the function. 00979 SourceLocation LastStopPoint; 00980 00981 public: 00982 /// A scope within which we are constructing the fields of an object which 00983 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use 00984 /// if we need to evaluate a CXXDefaultInitExpr within the evaluation. 00985 class FieldConstructionScope { 00986 public: 00987 FieldConstructionScope(CodeGenFunction &CGF, llvm::Value *This) 00988 : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) { 00989 CGF.CXXDefaultInitExprThis = This; 00990 } 00991 ~FieldConstructionScope() { 00992 CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis; 00993 } 00994 00995 private: 00996 CodeGenFunction &CGF; 00997 llvm::Value *OldCXXDefaultInitExprThis; 00998 }; 00999 01000 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this' 01001 /// is overridden to be the object under construction. 01002 class CXXDefaultInitExprScope { 01003 public: 01004 CXXDefaultInitExprScope(CodeGenFunction &CGF) 01005 : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue) { 01006 CGF.CXXThisValue = CGF.CXXDefaultInitExprThis; 01007 } 01008 ~CXXDefaultInitExprScope() { 01009 CGF.CXXThisValue = OldCXXThisValue; 01010 } 01011 01012 public: 01013 CodeGenFunction &CGF; 01014 llvm::Value *OldCXXThisValue; 01015 }; 01016 01017 private: 01018 /// CXXThisDecl - When generating code for a C++ member function, 01019 /// this will hold the implicit 'this' declaration. 01020 ImplicitParamDecl *CXXABIThisDecl; 01021 llvm::Value *CXXABIThisValue; 01022 llvm::Value *CXXThisValue; 01023 01024 /// The value of 'this' to use when evaluating CXXDefaultInitExprs within 01025 /// this expression. 01026 llvm::Value *CXXDefaultInitExprThis; 01027 01028 /// CXXStructorImplicitParamDecl - When generating code for a constructor or 01029 /// destructor, this will hold the implicit argument (e.g. VTT). 01030 ImplicitParamDecl *CXXStructorImplicitParamDecl; 01031 llvm::Value *CXXStructorImplicitParamValue; 01032 01033 /// OutermostConditional - Points to the outermost active 01034 /// conditional control. This is used so that we know if a 01035 /// temporary should be destroyed conditionally. 01036 ConditionalEvaluation *OutermostConditional; 01037 01038 /// The current lexical scope. 01039 LexicalScope *CurLexicalScope; 01040 01041 /// The current source location that should be used for exception 01042 /// handling code. 01043 SourceLocation CurEHLocation; 01044 01045 /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM 01046 /// type as well as the field number that contains the actual data. 01047 llvm::DenseMap<const ValueDecl *, std::pair<llvm::Type *, 01048 unsigned> > ByRefValueInfo; 01049 01050 llvm::BasicBlock *TerminateLandingPad; 01051 llvm::BasicBlock *TerminateHandler; 01052 llvm::BasicBlock *TrapBB; 01053 01054 /// Add a kernel metadata node to the named metadata node 'opencl.kernels'. 01055 /// In the kernel metadata node, reference the kernel function and metadata 01056 /// nodes for its optional attribute qualifiers (OpenCL 1.1 6.7.2): 01057 /// - A node for the vec_type_hint(<type>) qualifier contains string 01058 /// "vec_type_hint", an undefined value of the <type> data type, 01059 /// and a Boolean that is true if the <type> is integer and signed. 01060 /// - A node for the work_group_size_hint(X,Y,Z) qualifier contains string 01061 /// "work_group_size_hint", and three 32-bit integers X, Y and Z. 01062 /// - A node for the reqd_work_group_size(X,Y,Z) qualifier contains string 01063 /// "reqd_work_group_size", and three 32-bit integers X, Y and Z. 01064 void EmitOpenCLKernelMetadata(const FunctionDecl *FD, 01065 llvm::Function *Fn); 01066 01067 public: 01068 CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false); 01069 ~CodeGenFunction(); 01070 01071 CodeGenTypes &getTypes() const { return CGM.getTypes(); } 01072 ASTContext &getContext() const { return CGM.getContext(); } 01073 CGDebugInfo *getDebugInfo() { 01074 if (DisableDebugInfo) 01075 return nullptr; 01076 return DebugInfo; 01077 } 01078 void disableDebugInfo() { DisableDebugInfo = true; } 01079 void enableDebugInfo() { DisableDebugInfo = false; } 01080 01081 bool shouldUseFusedARCCalls() { 01082 return CGM.getCodeGenOpts().OptimizationLevel == 0; 01083 } 01084 01085 const LangOptions &getLangOpts() const { return CGM.getLangOpts(); } 01086 01087 /// Returns a pointer to the function's exception object and selector slot, 01088 /// which is assigned in every landing pad. 01089 llvm::Value *getExceptionSlot(); 01090 llvm::Value *getEHSelectorSlot(); 01091 01092 /// Returns the contents of the function's exception object and selector 01093 /// slots. 01094 llvm::Value *getExceptionFromSlot(); 01095 llvm::Value *getSelectorFromSlot(); 01096 01097 llvm::Value *getNormalCleanupDestSlot(); 01098 01099 llvm::BasicBlock *getUnreachableBlock() { 01100 if (!UnreachableBlock) { 01101 UnreachableBlock = createBasicBlock("unreachable"); 01102 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock); 01103 } 01104 return UnreachableBlock; 01105 } 01106 01107 llvm::BasicBlock *getInvokeDest() { 01108 if (!EHStack.requiresLandingPad()) return nullptr; 01109 return getInvokeDestImpl(); 01110 } 01111 01112 const TargetInfo &getTarget() const { return Target; } 01113 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); } 01114 01115 //===--------------------------------------------------------------------===// 01116 // Cleanups 01117 //===--------------------------------------------------------------------===// 01118 01119 typedef void Destroyer(CodeGenFunction &CGF, llvm::Value *addr, QualType ty); 01120 01121 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, 01122 llvm::Value *arrayEndPointer, 01123 QualType elementType, 01124 Destroyer *destroyer); 01125 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, 01126 llvm::Value *arrayEnd, 01127 QualType elementType, 01128 Destroyer *destroyer); 01129 01130 void pushDestroy(QualType::DestructionKind dtorKind, 01131 llvm::Value *addr, QualType type); 01132 void pushEHDestroy(QualType::DestructionKind dtorKind, 01133 llvm::Value *addr, QualType type); 01134 void pushDestroy(CleanupKind kind, llvm::Value *addr, QualType type, 01135 Destroyer *destroyer, bool useEHCleanupForArray); 01136 void pushLifetimeExtendedDestroy(CleanupKind kind, llvm::Value *addr, 01137 QualType type, Destroyer *destroyer, 01138 bool useEHCleanupForArray); 01139 void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete, 01140 llvm::Value *CompletePtr, 01141 QualType ElementType); 01142 void pushStackRestore(CleanupKind kind, llvm::Value *SPMem); 01143 void emitDestroy(llvm::Value *addr, QualType type, Destroyer *destroyer, 01144 bool useEHCleanupForArray); 01145 llvm::Function *generateDestroyHelper(llvm::Constant *addr, QualType type, 01146 Destroyer *destroyer, 01147 bool useEHCleanupForArray, 01148 const VarDecl *VD); 01149 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end, 01150 QualType type, Destroyer *destroyer, 01151 bool checkZeroLength, bool useEHCleanup); 01152 01153 Destroyer *getDestroyer(QualType::DestructionKind destructionKind); 01154 01155 /// Determines whether an EH cleanup is required to destroy a type 01156 /// with the given destruction kind. 01157 bool needsEHCleanup(QualType::DestructionKind kind) { 01158 switch (kind) { 01159 case QualType::DK_none: 01160 return false; 01161 case QualType::DK_cxx_destructor: 01162 case QualType::DK_objc_weak_lifetime: 01163 return getLangOpts().Exceptions; 01164 case QualType::DK_objc_strong_lifetime: 01165 return getLangOpts().Exceptions && 01166 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions; 01167 } 01168 llvm_unreachable("bad destruction kind"); 01169 } 01170 01171 CleanupKind getCleanupKind(QualType::DestructionKind kind) { 01172 return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup); 01173 } 01174 01175 //===--------------------------------------------------------------------===// 01176 // Objective-C 01177 //===--------------------------------------------------------------------===// 01178 01179 void GenerateObjCMethod(const ObjCMethodDecl *OMD); 01180 01181 void StartObjCMethod(const ObjCMethodDecl *MD, 01182 const ObjCContainerDecl *CD, 01183 SourceLocation StartLoc); 01184 01185 /// GenerateObjCGetter - Synthesize an Objective-C property getter function. 01186 void GenerateObjCGetter(ObjCImplementationDecl *IMP, 01187 const ObjCPropertyImplDecl *PID); 01188 void generateObjCGetterBody(const ObjCImplementationDecl *classImpl, 01189 const ObjCPropertyImplDecl *propImpl, 01190 const ObjCMethodDecl *GetterMothodDecl, 01191 llvm::Constant *AtomicHelperFn); 01192 01193 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, 01194 ObjCMethodDecl *MD, bool ctor); 01195 01196 /// GenerateObjCSetter - Synthesize an Objective-C property setter function 01197 /// for the given property. 01198 void GenerateObjCSetter(ObjCImplementationDecl *IMP, 01199 const ObjCPropertyImplDecl *PID); 01200 void generateObjCSetterBody(const ObjCImplementationDecl *classImpl, 01201 const ObjCPropertyImplDecl *propImpl, 01202 llvm::Constant *AtomicHelperFn); 01203 bool IndirectObjCSetterArg(const CGFunctionInfo &FI); 01204 bool IvarTypeWithAggrGCObjects(QualType Ty); 01205 01206 //===--------------------------------------------------------------------===// 01207 // Block Bits 01208 //===--------------------------------------------------------------------===// 01209 01210 llvm::Value *EmitBlockLiteral(const BlockExpr *); 01211 llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info); 01212 static void destroyBlockInfos(CGBlockInfo *info); 01213 llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *, 01214 const CGBlockInfo &Info, 01215 llvm::StructType *, 01216 llvm::Constant *BlockVarLayout); 01217 01218 llvm::Function *GenerateBlockFunction(GlobalDecl GD, 01219 const CGBlockInfo &Info, 01220 const DeclMapTy &ldm, 01221 bool IsLambdaConversionToBlock); 01222 01223 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo); 01224 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo); 01225 llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction( 01226 const ObjCPropertyImplDecl *PID); 01227 llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction( 01228 const ObjCPropertyImplDecl *PID); 01229 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty); 01230 01231 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags); 01232 01233 class AutoVarEmission; 01234 01235 void emitByrefStructureInit(const AutoVarEmission &emission); 01236 void enterByrefCleanup(const AutoVarEmission &emission); 01237 01238 llvm::Value *LoadBlockStruct() { 01239 assert(BlockPointer && "no block pointer set!"); 01240 return BlockPointer; 01241 } 01242 01243 void AllocateBlockCXXThisPointer(const CXXThisExpr *E); 01244 void AllocateBlockDecl(const DeclRefExpr *E); 01245 llvm::Value *GetAddrOfBlockDecl(const VarDecl *var, bool ByRef); 01246 llvm::Type *BuildByRefType(const VarDecl *var); 01247 01248 void GenerateCode(GlobalDecl GD, llvm::Function *Fn, 01249 const CGFunctionInfo &FnInfo); 01250 /// \brief Emit code for the start of a function. 01251 /// \param Loc The location to be associated with the function. 01252 /// \param StartLoc The location of the function body. 01253 void StartFunction(GlobalDecl GD, 01254 QualType RetTy, 01255 llvm::Function *Fn, 01256 const CGFunctionInfo &FnInfo, 01257 const FunctionArgList &Args, 01258 SourceLocation Loc = SourceLocation(), 01259 SourceLocation StartLoc = SourceLocation()); 01260 01261 void EmitConstructorBody(FunctionArgList &Args); 01262 void EmitDestructorBody(FunctionArgList &Args); 01263 void emitImplicitAssignmentOperatorBody(FunctionArgList &Args); 01264 void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body); 01265 void EmitBlockWithFallThrough(llvm::BasicBlock *BB, RegionCounter &Cnt); 01266 01267 void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator, 01268 CallArgList &CallArgs); 01269 void EmitLambdaToBlockPointerBody(FunctionArgList &Args); 01270 void EmitLambdaBlockInvokeBody(); 01271 void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD); 01272 void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD); 01273 void EmitAsanPrologueOrEpilogue(bool Prologue); 01274 01275 /// EmitReturnBlock - Emit the unified return block, trying to avoid its 01276 /// emission when possible. 01277 void EmitReturnBlock(); 01278 01279 /// FinishFunction - Complete IR generation of the current function. It is 01280 /// legal to call this function even if there is no current insertion point. 01281 void FinishFunction(SourceLocation EndLoc=SourceLocation()); 01282 01283 void StartThunk(llvm::Function *Fn, GlobalDecl GD, const CGFunctionInfo &FnInfo); 01284 01285 void EmitCallAndReturnForThunk(llvm::Value *Callee, const ThunkInfo *Thunk); 01286 01287 /// Emit a musttail call for a thunk with a potentially adjusted this pointer. 01288 void EmitMustTailThunk(const CXXMethodDecl *MD, llvm::Value *AdjustedThisPtr, 01289 llvm::Value *Callee); 01290 01291 /// GenerateThunk - Generate a thunk for the given method. 01292 void GenerateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, 01293 GlobalDecl GD, const ThunkInfo &Thunk); 01294 01295 void GenerateVarArgsThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, 01296 GlobalDecl GD, const ThunkInfo &Thunk); 01297 01298 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type, 01299 FunctionArgList &Args); 01300 01301 void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init, 01302 ArrayRef<VarDecl *> ArrayIndexes); 01303 01304 /// InitializeVTablePointer - Initialize the vtable pointer of the given 01305 /// subobject. 01306 /// 01307 void InitializeVTablePointer(BaseSubobject Base, 01308 const CXXRecordDecl *NearestVBase, 01309 CharUnits OffsetFromNearestVBase, 01310 const CXXRecordDecl *VTableClass); 01311 01312 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy; 01313 void InitializeVTablePointers(BaseSubobject Base, 01314 const CXXRecordDecl *NearestVBase, 01315 CharUnits OffsetFromNearestVBase, 01316 bool BaseIsNonVirtualPrimaryBase, 01317 const CXXRecordDecl *VTableClass, 01318 VisitedVirtualBasesSetTy& VBases); 01319 01320 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl); 01321 01322 /// GetVTablePtr - Return the Value of the vtable pointer member pointed 01323 /// to by This. 01324 llvm::Value *GetVTablePtr(llvm::Value *This, llvm::Type *Ty); 01325 01326 01327 /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given 01328 /// expr can be devirtualized. 01329 bool CanDevirtualizeMemberFunctionCall(const Expr *Base, 01330 const CXXMethodDecl *MD); 01331 01332 /// EnterDtorCleanups - Enter the cleanups necessary to complete the 01333 /// given phase of destruction for a destructor. The end result 01334 /// should call destructors on members and base classes in reverse 01335 /// order of their construction. 01336 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type); 01337 01338 /// ShouldInstrumentFunction - Return true if the current function should be 01339 /// instrumented with __cyg_profile_func_* calls 01340 bool ShouldInstrumentFunction(); 01341 01342 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified 01343 /// instrumentation function with the current function and the call site, if 01344 /// function instrumentation is enabled. 01345 void EmitFunctionInstrumentation(const char *Fn); 01346 01347 /// EmitMCountInstrumentation - Emit call to .mcount. 01348 void EmitMCountInstrumentation(); 01349 01350 /// EmitFunctionProlog - Emit the target specific LLVM code to load the 01351 /// arguments for the given function. This is also responsible for naming the 01352 /// LLVM function arguments. 01353 void EmitFunctionProlog(const CGFunctionInfo &FI, 01354 llvm::Function *Fn, 01355 const FunctionArgList &Args); 01356 01357 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the 01358 /// given temporary. 01359 void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc, 01360 SourceLocation EndLoc); 01361 01362 /// EmitStartEHSpec - Emit the start of the exception spec. 01363 void EmitStartEHSpec(const Decl *D); 01364 01365 /// EmitEndEHSpec - Emit the end of the exception spec. 01366 void EmitEndEHSpec(const Decl *D); 01367 01368 /// getTerminateLandingPad - Return a landing pad that just calls terminate. 01369 llvm::BasicBlock *getTerminateLandingPad(); 01370 01371 /// getTerminateHandler - Return a handler (not a landing pad, just 01372 /// a catch handler) that just calls terminate. This is used when 01373 /// a terminate scope encloses a try. 01374 llvm::BasicBlock *getTerminateHandler(); 01375 01376 llvm::Type *ConvertTypeForMem(QualType T); 01377 llvm::Type *ConvertType(QualType T); 01378 llvm::Type *ConvertType(const TypeDecl *T) { 01379 return ConvertType(getContext().getTypeDeclType(T)); 01380 } 01381 01382 /// LoadObjCSelf - Load the value of self. This function is only valid while 01383 /// generating code for an Objective-C method. 01384 llvm::Value *LoadObjCSelf(); 01385 01386 /// TypeOfSelfObject - Return type of object that this self represents. 01387 QualType TypeOfSelfObject(); 01388 01389 /// hasAggregateLLVMType - Return true if the specified AST type will map into 01390 /// an aggregate LLVM type or is void. 01391 static TypeEvaluationKind getEvaluationKind(QualType T); 01392 01393 static bool hasScalarEvaluationKind(QualType T) { 01394 return getEvaluationKind(T) == TEK_Scalar; 01395 } 01396 01397 static bool hasAggregateEvaluationKind(QualType T) { 01398 return getEvaluationKind(T) == TEK_Aggregate; 01399 } 01400 01401 /// createBasicBlock - Create an LLVM basic block. 01402 llvm::BasicBlock *createBasicBlock(const Twine &name = "", 01403 llvm::Function *parent = nullptr, 01404 llvm::BasicBlock *before = nullptr) { 01405 #ifdef NDEBUG 01406 return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before); 01407 #else 01408 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before); 01409 #endif 01410 } 01411 01412 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified 01413 /// label maps to. 01414 JumpDest getJumpDestForLabel(const LabelDecl *S); 01415 01416 /// SimplifyForwardingBlocks - If the given basic block is only a branch to 01417 /// another basic block, simplify it. This assumes that no other code could 01418 /// potentially reference the basic block. 01419 void SimplifyForwardingBlocks(llvm::BasicBlock *BB); 01420 01421 /// EmitBlock - Emit the given block \arg BB and set it as the insert point, 01422 /// adding a fall-through branch from the current insert block if 01423 /// necessary. It is legal to call this function even if there is no current 01424 /// insertion point. 01425 /// 01426 /// IsFinished - If true, indicates that the caller has finished emitting 01427 /// branches to the given block and does not expect to emit code into it. This 01428 /// means the block can be ignored if it is unreachable. 01429 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false); 01430 01431 /// EmitBlockAfterUses - Emit the given block somewhere hopefully 01432 /// near its uses, and leave the insertion point in it. 01433 void EmitBlockAfterUses(llvm::BasicBlock *BB); 01434 01435 /// EmitBranch - Emit a branch to the specified basic block from the current 01436 /// insert block, taking care to avoid creation of branches from dummy 01437 /// blocks. It is legal to call this function even if there is no current 01438 /// insertion point. 01439 /// 01440 /// This function clears the current insertion point. The caller should follow 01441 /// calls to this function with calls to Emit*Block prior to generation new 01442 /// code. 01443 void EmitBranch(llvm::BasicBlock *Block); 01444 01445 /// HaveInsertPoint - True if an insertion point is defined. If not, this 01446 /// indicates that the current code being emitted is unreachable. 01447 bool HaveInsertPoint() const { 01448 return Builder.GetInsertBlock() != nullptr; 01449 } 01450 01451 /// EnsureInsertPoint - Ensure that an insertion point is defined so that 01452 /// emitted IR has a place to go. Note that by definition, if this function 01453 /// creates a block then that block is unreachable; callers may do better to 01454 /// detect when no insertion point is defined and simply skip IR generation. 01455 void EnsureInsertPoint() { 01456 if (!HaveInsertPoint()) 01457 EmitBlock(createBasicBlock()); 01458 } 01459 01460 /// ErrorUnsupported - Print out an error that codegen doesn't support the 01461 /// specified stmt yet. 01462 void ErrorUnsupported(const Stmt *S, const char *Type); 01463 01464 //===--------------------------------------------------------------------===// 01465 // Helpers 01466 //===--------------------------------------------------------------------===// 01467 01468 LValue MakeAddrLValue(llvm::Value *V, QualType T, 01469 CharUnits Alignment = CharUnits()) { 01470 return LValue::MakeAddr(V, T, Alignment, getContext(), 01471 CGM.getTBAAInfo(T)); 01472 } 01473 01474 LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T); 01475 01476 /// CreateTempAlloca - This creates a alloca and inserts it into the entry 01477 /// block. The caller is responsible for setting an appropriate alignment on 01478 /// the alloca. 01479 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty, 01480 const Twine &Name = "tmp"); 01481 01482 /// InitTempAlloca - Provide an initial value for the given alloca. 01483 void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value); 01484 01485 /// CreateIRTemp - Create a temporary IR object of the given type, with 01486 /// appropriate alignment. This routine should only be used when an temporary 01487 /// value needs to be stored into an alloca (for example, to avoid explicit 01488 /// PHI construction), but the type is the IR type, not the type appropriate 01489 /// for storing in memory. 01490 llvm::AllocaInst *CreateIRTemp(QualType T, const Twine &Name = "tmp"); 01491 01492 /// CreateMemTemp - Create a temporary memory object of the given type, with 01493 /// appropriate alignment. 01494 llvm::AllocaInst *CreateMemTemp(QualType T, const Twine &Name = "tmp"); 01495 01496 /// CreateAggTemp - Create a temporary memory object for the given 01497 /// aggregate type. 01498 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") { 01499 CharUnits Alignment = getContext().getTypeAlignInChars(T); 01500 return AggValueSlot::forAddr(CreateMemTemp(T, Name), Alignment, 01501 T.getQualifiers(), 01502 AggValueSlot::IsNotDestructed, 01503 AggValueSlot::DoesNotNeedGCBarriers, 01504 AggValueSlot::IsNotAliased); 01505 } 01506 01507 /// CreateInAllocaTmp - Create a temporary memory object for the given 01508 /// aggregate type. 01509 AggValueSlot CreateInAllocaTmp(QualType T, const Twine &Name = "inalloca"); 01510 01511 /// Emit a cast to void* in the appropriate address space. 01512 llvm::Value *EmitCastToVoidPtr(llvm::Value *value); 01513 01514 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 01515 /// expression and compare the result against zero, returning an Int1Ty value. 01516 llvm::Value *EvaluateExprAsBool(const Expr *E); 01517 01518 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result. 01519 void EmitIgnoredExpr(const Expr *E); 01520 01521 /// EmitAnyExpr - Emit code to compute the specified expression which can have 01522 /// any type. The result is returned as an RValue struct. If this is an 01523 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where 01524 /// the result should be returned. 01525 /// 01526 /// \param ignoreResult True if the resulting value isn't used. 01527 RValue EmitAnyExpr(const Expr *E, 01528 AggValueSlot aggSlot = AggValueSlot::ignored(), 01529 bool ignoreResult = false); 01530 01531 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address 01532 // or the value of the expression, depending on how va_list is defined. 01533 llvm::Value *EmitVAListRef(const Expr *E); 01534 01535 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will 01536 /// always be accessible even if no aggregate location is provided. 01537 RValue EmitAnyExprToTemp(const Expr *E); 01538 01539 /// EmitAnyExprToMem - Emits the code necessary to evaluate an 01540 /// arbitrary expression into the given memory location. 01541 void EmitAnyExprToMem(const Expr *E, llvm::Value *Location, 01542 Qualifiers Quals, bool IsInitializer); 01543 01544 /// EmitExprAsInit - Emits the code necessary to initialize a 01545 /// location in memory with the given initializer. 01546 void EmitExprAsInit(const Expr *init, const ValueDecl *D, 01547 LValue lvalue, bool capturedByInit); 01548 01549 /// hasVolatileMember - returns true if aggregate type has a volatile 01550 /// member. 01551 bool hasVolatileMember(QualType T) { 01552 if (const RecordType *RT = T->getAs<RecordType>()) { 01553 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl()); 01554 return RD->hasVolatileMember(); 01555 } 01556 return false; 01557 } 01558 /// EmitAggregateCopy - Emit an aggregate assignment. 01559 /// 01560 /// The difference to EmitAggregateCopy is that tail padding is not copied. 01561 /// This is required for correctness when assigning non-POD structures in C++. 01562 void EmitAggregateAssign(llvm::Value *DestPtr, llvm::Value *SrcPtr, 01563 QualType EltTy) { 01564 bool IsVolatile = hasVolatileMember(EltTy); 01565 EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, CharUnits::Zero(), 01566 true); 01567 } 01568 01569 /// EmitAggregateCopy - Emit an aggregate copy. 01570 /// 01571 /// \param isVolatile - True iff either the source or the destination is 01572 /// volatile. 01573 /// \param isAssignment - If false, allow padding to be copied. This often 01574 /// yields more efficient. 01575 void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr, 01576 QualType EltTy, bool isVolatile=false, 01577 CharUnits Alignment = CharUnits::Zero(), 01578 bool isAssignment = false); 01579 01580 /// StartBlock - Start new block named N. If insert block is a dummy block 01581 /// then reuse it. 01582 void StartBlock(const char *N); 01583 01584 /// GetAddrOfLocalVar - Return the address of a local variable. 01585 llvm::Value *GetAddrOfLocalVar(const VarDecl *VD) { 01586 llvm::Value *Res = LocalDeclMap[VD]; 01587 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!"); 01588 return Res; 01589 } 01590 01591 /// getOpaqueLValueMapping - Given an opaque value expression (which 01592 /// must be mapped to an l-value), return its mapping. 01593 const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) { 01594 assert(OpaqueValueMapping::shouldBindAsLValue(e)); 01595 01596 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator 01597 it = OpaqueLValues.find(e); 01598 assert(it != OpaqueLValues.end() && "no mapping for opaque value!"); 01599 return it->second; 01600 } 01601 01602 /// getOpaqueRValueMapping - Given an opaque value expression (which 01603 /// must be mapped to an r-value), return its mapping. 01604 const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) { 01605 assert(!OpaqueValueMapping::shouldBindAsLValue(e)); 01606 01607 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator 01608 it = OpaqueRValues.find(e); 01609 assert(it != OpaqueRValues.end() && "no mapping for opaque value!"); 01610 return it->second; 01611 } 01612 01613 /// getAccessedFieldNo - Given an encoded value and a result number, return 01614 /// the input field number being accessed. 01615 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts); 01616 01617 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L); 01618 llvm::BasicBlock *GetIndirectGotoBlock(); 01619 01620 /// EmitNullInitialization - Generate code to set a value of the given type to 01621 /// null, If the type contains data member pointers, they will be initialized 01622 /// to -1 in accordance with the Itanium C++ ABI. 01623 void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty); 01624 01625 // EmitVAArg - Generate code to get an argument from the passed in pointer 01626 // and update it accordingly. The return value is a pointer to the argument. 01627 // FIXME: We should be able to get rid of this method and use the va_arg 01628 // instruction in LLVM instead once it works well enough. 01629 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty); 01630 01631 /// emitArrayLength - Compute the length of an array, even if it's a 01632 /// VLA, and drill down to the base element type. 01633 llvm::Value *emitArrayLength(const ArrayType *arrayType, 01634 QualType &baseType, 01635 llvm::Value *&addr); 01636 01637 /// EmitVLASize - Capture all the sizes for the VLA expressions in 01638 /// the given variably-modified type and store them in the VLASizeMap. 01639 /// 01640 /// This function can be called with a null (unreachable) insert point. 01641 void EmitVariablyModifiedType(QualType Ty); 01642 01643 /// getVLASize - Returns an LLVM value that corresponds to the size, 01644 /// in non-variably-sized elements, of a variable length array type, 01645 /// plus that largest non-variably-sized element type. Assumes that 01646 /// the type has already been emitted with EmitVariablyModifiedType. 01647 std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla); 01648 std::pair<llvm::Value*,QualType> getVLASize(QualType vla); 01649 01650 /// LoadCXXThis - Load the value of 'this'. This function is only valid while 01651 /// generating code for an C++ member function. 01652 llvm::Value *LoadCXXThis() { 01653 assert(CXXThisValue && "no 'this' value for this function"); 01654 return CXXThisValue; 01655 } 01656 01657 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have 01658 /// virtual bases. 01659 // FIXME: Every place that calls LoadCXXVTT is something 01660 // that needs to be abstracted properly. 01661 llvm::Value *LoadCXXVTT() { 01662 assert(CXXStructorImplicitParamValue && "no VTT value for this function"); 01663 return CXXStructorImplicitParamValue; 01664 } 01665 01666 /// LoadCXXStructorImplicitParam - Load the implicit parameter 01667 /// for a constructor/destructor. 01668 llvm::Value *LoadCXXStructorImplicitParam() { 01669 assert(CXXStructorImplicitParamValue && 01670 "no implicit argument value for this function"); 01671 return CXXStructorImplicitParamValue; 01672 } 01673 01674 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a 01675 /// complete class to the given direct base. 01676 llvm::Value * 01677 GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value, 01678 const CXXRecordDecl *Derived, 01679 const CXXRecordDecl *Base, 01680 bool BaseIsVirtual); 01681 01682 /// GetAddressOfBaseClass - This function will add the necessary delta to the 01683 /// load of 'this' and returns address of the base class. 01684 llvm::Value *GetAddressOfBaseClass(llvm::Value *Value, 01685 const CXXRecordDecl *Derived, 01686 CastExpr::path_const_iterator PathBegin, 01687 CastExpr::path_const_iterator PathEnd, 01688 bool NullCheckValue, SourceLocation Loc); 01689 01690 llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value, 01691 const CXXRecordDecl *Derived, 01692 CastExpr::path_const_iterator PathBegin, 01693 CastExpr::path_const_iterator PathEnd, 01694 bool NullCheckValue); 01695 01696 /// GetVTTParameter - Return the VTT parameter that should be passed to a 01697 /// base constructor/destructor with virtual bases. 01698 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move 01699 /// to ItaniumCXXABI.cpp together with all the references to VTT. 01700 llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase, 01701 bool Delegating); 01702 01703 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, 01704 CXXCtorType CtorType, 01705 const FunctionArgList &Args, 01706 SourceLocation Loc); 01707 // It's important not to confuse this and the previous function. Delegating 01708 // constructors are the C++0x feature. The constructor delegate optimization 01709 // is used to reduce duplication in the base and complete consturctors where 01710 // they are substantially the same. 01711 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor, 01712 const FunctionArgList &Args); 01713 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 01714 bool ForVirtualBase, bool Delegating, 01715 llvm::Value *This, const CXXConstructExpr *E); 01716 01717 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, 01718 llvm::Value *This, llvm::Value *Src, 01719 const CXXConstructExpr *E); 01720 01721 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 01722 const ConstantArrayType *ArrayTy, 01723 llvm::Value *ArrayPtr, 01724 const CXXConstructExpr *E, 01725 bool ZeroInitialization = false); 01726 01727 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 01728 llvm::Value *NumElements, 01729 llvm::Value *ArrayPtr, 01730 const CXXConstructExpr *E, 01731 bool ZeroInitialization = false); 01732 01733 static Destroyer destroyCXXObject; 01734 01735 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, 01736 bool ForVirtualBase, bool Delegating, 01737 llvm::Value *This); 01738 01739 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType, 01740 llvm::Value *NewPtr, llvm::Value *NumElements, 01741 llvm::Value *AllocSizeWithoutCookie); 01742 01743 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType, 01744 llvm::Value *Ptr); 01745 01746 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E); 01747 void EmitCXXDeleteExpr(const CXXDeleteExpr *E); 01748 01749 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr, 01750 QualType DeleteTy); 01751 01752 RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type, 01753 const Expr *Arg, bool IsDelete); 01754 01755 llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E); 01756 llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE); 01757 llvm::Value* EmitCXXUuidofExpr(const CXXUuidofExpr *E); 01758 01759 /// \brief Situations in which we might emit a check for the suitability of a 01760 /// pointer or glvalue. 01761 enum TypeCheckKind { 01762 /// Checking the operand of a load. Must be suitably sized and aligned. 01763 TCK_Load, 01764 /// Checking the destination of a store. Must be suitably sized and aligned. 01765 TCK_Store, 01766 /// Checking the bound value in a reference binding. Must be suitably sized 01767 /// and aligned, but is not required to refer to an object (until the 01768 /// reference is used), per core issue 453. 01769 TCK_ReferenceBinding, 01770 /// Checking the object expression in a non-static data member access. Must 01771 /// be an object within its lifetime. 01772 TCK_MemberAccess, 01773 /// Checking the 'this' pointer for a call to a non-static member function. 01774 /// Must be an object within its lifetime. 01775 TCK_MemberCall, 01776 /// Checking the 'this' pointer for a constructor call. 01777 TCK_ConstructorCall, 01778 /// Checking the operand of a static_cast to a derived pointer type. Must be 01779 /// null or an object within its lifetime. 01780 TCK_DowncastPointer, 01781 /// Checking the operand of a static_cast to a derived reference type. Must 01782 /// be an object within its lifetime. 01783 TCK_DowncastReference, 01784 /// Checking the operand of a cast to a base object. Must be suitably sized 01785 /// and aligned. 01786 TCK_Upcast, 01787 /// Checking the operand of a cast to a virtual base object. Must be an 01788 /// object within its lifetime. 01789 TCK_UpcastToVirtualBase 01790 }; 01791 01792 /// \brief Whether any type-checking sanitizers are enabled. If \c false, 01793 /// calls to EmitTypeCheck can be skipped. 01794 bool sanitizePerformTypeCheck() const; 01795 01796 /// \brief Emit a check that \p V is the address of storage of the 01797 /// appropriate size and alignment for an object of type \p Type. 01798 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V, 01799 QualType Type, CharUnits Alignment = CharUnits::Zero(), 01800 bool SkipNullCheck = false); 01801 01802 /// \brief Emit a check that \p Base points into an array object, which 01803 /// we can access at index \p Index. \p Accessed should be \c false if we 01804 /// this expression is used as an lvalue, for instance in "&Arr[Idx]". 01805 void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index, 01806 QualType IndexType, bool Accessed); 01807 01808 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 01809 bool isInc, bool isPre); 01810 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, 01811 bool isInc, bool isPre); 01812 01813 void EmitAlignmentAssumption(llvm::Value *PtrValue, unsigned Alignment, 01814 llvm::Value *OffsetValue = nullptr) { 01815 Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment, 01816 OffsetValue); 01817 } 01818 01819 //===--------------------------------------------------------------------===// 01820 // Declaration Emission 01821 //===--------------------------------------------------------------------===// 01822 01823 /// EmitDecl - Emit a declaration. 01824 /// 01825 /// This function can be called with a null (unreachable) insert point. 01826 void EmitDecl(const Decl &D); 01827 01828 /// EmitVarDecl - Emit a local variable declaration. 01829 /// 01830 /// This function can be called with a null (unreachable) insert point. 01831 void EmitVarDecl(const VarDecl &D); 01832 01833 void EmitScalarInit(const Expr *init, const ValueDecl *D, 01834 LValue lvalue, bool capturedByInit); 01835 void EmitScalarInit(llvm::Value *init, LValue lvalue); 01836 01837 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D, 01838 llvm::Value *Address); 01839 01840 /// \brief Determine whether the given initializer is trivial in the sense 01841 /// that it requires no code to be generated. 01842 bool isTrivialInitializer(const Expr *Init); 01843 01844 /// EmitAutoVarDecl - Emit an auto variable declaration. 01845 /// 01846 /// This function can be called with a null (unreachable) insert point. 01847 void EmitAutoVarDecl(const VarDecl &D); 01848 01849 class AutoVarEmission { 01850 friend class CodeGenFunction; 01851 01852 const VarDecl *Variable; 01853 01854 /// The alignment of the variable. 01855 CharUnits Alignment; 01856 01857 /// The address of the alloca. Null if the variable was emitted 01858 /// as a global constant. 01859 llvm::Value *Address; 01860 01861 llvm::Value *NRVOFlag; 01862 01863 /// True if the variable is a __block variable. 01864 bool IsByRef; 01865 01866 /// True if the variable is of aggregate type and has a constant 01867 /// initializer. 01868 bool IsConstantAggregate; 01869 01870 /// Non-null if we should use lifetime annotations. 01871 llvm::Value *SizeForLifetimeMarkers; 01872 01873 struct Invalid {}; 01874 AutoVarEmission(Invalid) : Variable(nullptr) {} 01875 01876 AutoVarEmission(const VarDecl &variable) 01877 : Variable(&variable), Address(nullptr), NRVOFlag(nullptr), 01878 IsByRef(false), IsConstantAggregate(false), 01879 SizeForLifetimeMarkers(nullptr) {} 01880 01881 bool wasEmittedAsGlobal() const { return Address == nullptr; } 01882 01883 public: 01884 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); } 01885 01886 bool useLifetimeMarkers() const { 01887 return SizeForLifetimeMarkers != nullptr; 01888 } 01889 llvm::Value *getSizeForLifetimeMarkers() const { 01890 assert(useLifetimeMarkers()); 01891 return SizeForLifetimeMarkers; 01892 } 01893 01894 /// Returns the raw, allocated address, which is not necessarily 01895 /// the address of the object itself. 01896 llvm::Value *getAllocatedAddress() const { 01897 return Address; 01898 } 01899 01900 /// Returns the address of the object within this declaration. 01901 /// Note that this does not chase the forwarding pointer for 01902 /// __block decls. 01903 llvm::Value *getObjectAddress(CodeGenFunction &CGF) const { 01904 if (!IsByRef) return Address; 01905 01906 return CGF.Builder.CreateStructGEP(Address, 01907 CGF.getByRefValueLLVMField(Variable), 01908 Variable->getNameAsString()); 01909 } 01910 }; 01911 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var); 01912 void EmitAutoVarInit(const AutoVarEmission &emission); 01913 void EmitAutoVarCleanups(const AutoVarEmission &emission); 01914 void emitAutoVarTypeCleanup(const AutoVarEmission &emission, 01915 QualType::DestructionKind dtorKind); 01916 01917 void EmitStaticVarDecl(const VarDecl &D, 01918 llvm::GlobalValue::LinkageTypes Linkage); 01919 01920 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl. 01921 void EmitParmDecl(const VarDecl &D, llvm::Value *Arg, bool ArgIsPointer, 01922 unsigned ArgNo); 01923 01924 /// protectFromPeepholes - Protect a value that we're intending to 01925 /// store to the side, but which will probably be used later, from 01926 /// aggressive peepholing optimizations that might delete it. 01927 /// 01928 /// Pass the result to unprotectFromPeepholes to declare that 01929 /// protection is no longer required. 01930 /// 01931 /// There's no particular reason why this shouldn't apply to 01932 /// l-values, it's just that no existing peepholes work on pointers. 01933 PeepholeProtection protectFromPeepholes(RValue rvalue); 01934 void unprotectFromPeepholes(PeepholeProtection protection); 01935 01936 //===--------------------------------------------------------------------===// 01937 // Statement Emission 01938 //===--------------------------------------------------------------------===// 01939 01940 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info. 01941 void EmitStopPoint(const Stmt *S); 01942 01943 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call 01944 /// this function even if there is no current insertion point. 01945 /// 01946 /// This function may clear the current insertion point; callers should use 01947 /// EnsureInsertPoint if they wish to subsequently generate code without first 01948 /// calling EmitBlock, EmitBranch, or EmitStmt. 01949 void EmitStmt(const Stmt *S); 01950 01951 /// EmitSimpleStmt - Try to emit a "simple" statement which does not 01952 /// necessarily require an insertion point or debug information; typically 01953 /// because the statement amounts to a jump or a container of other 01954 /// statements. 01955 /// 01956 /// \return True if the statement was handled. 01957 bool EmitSimpleStmt(const Stmt *S); 01958 01959 llvm::Value *EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false, 01960 AggValueSlot AVS = AggValueSlot::ignored()); 01961 llvm::Value *EmitCompoundStmtWithoutScope(const CompoundStmt &S, 01962 bool GetLast = false, 01963 AggValueSlot AVS = 01964 AggValueSlot::ignored()); 01965 01966 /// EmitLabel - Emit the block for the given label. It is legal to call this 01967 /// function even if there is no current insertion point. 01968 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt. 01969 01970 void EmitLabelStmt(const LabelStmt &S); 01971 void EmitAttributedStmt(const AttributedStmt &S); 01972 void EmitGotoStmt(const GotoStmt &S); 01973 void EmitIndirectGotoStmt(const IndirectGotoStmt &S); 01974 void EmitIfStmt(const IfStmt &S); 01975 01976 void EmitCondBrHints(llvm::LLVMContext &Context, llvm::BranchInst *CondBr, 01977 ArrayRef<const Attr *> Attrs); 01978 void EmitWhileStmt(const WhileStmt &S, 01979 ArrayRef<const Attr *> Attrs = None); 01980 void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None); 01981 void EmitForStmt(const ForStmt &S, 01982 ArrayRef<const Attr *> Attrs = None); 01983 void EmitReturnStmt(const ReturnStmt &S); 01984 void EmitDeclStmt(const DeclStmt &S); 01985 void EmitBreakStmt(const BreakStmt &S); 01986 void EmitContinueStmt(const ContinueStmt &S); 01987 void EmitSwitchStmt(const SwitchStmt &S); 01988 void EmitDefaultStmt(const DefaultStmt &S); 01989 void EmitCaseStmt(const CaseStmt &S); 01990 void EmitCaseStmtRange(const CaseStmt &S); 01991 void EmitAsmStmt(const AsmStmt &S); 01992 01993 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S); 01994 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S); 01995 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S); 01996 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S); 01997 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S); 01998 01999 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 02000 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 02001 02002 void EmitCXXTryStmt(const CXXTryStmt &S); 02003 void EmitSEHTryStmt(const SEHTryStmt &S); 02004 void EmitSEHLeaveStmt(const SEHLeaveStmt &S); 02005 void EmitCXXForRangeStmt(const CXXForRangeStmt &S, 02006 ArrayRef<const Attr *> Attrs = None); 02007 02008 LValue InitCapturedStruct(const CapturedStmt &S); 02009 llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K); 02010 void GenerateCapturedStmtFunctionProlog(const CapturedStmt &S); 02011 llvm::Function *GenerateCapturedStmtFunctionEpilog(const CapturedStmt &S); 02012 llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S); 02013 llvm::Value *GenerateCapturedStmtArgument(const CapturedStmt &S); 02014 void EmitOMPAggregateAssign(LValue OriginalAddr, llvm::Value *PrivateAddr, 02015 const Expr *AssignExpr, QualType Type, 02016 const VarDecl *VDInit); 02017 void EmitOMPFirstprivateClause(const OMPExecutableDirective &D, 02018 OMPPrivateScope &PrivateScope); 02019 void EmitOMPPrivateClause(const OMPExecutableDirective &D, 02020 OMPPrivateScope &PrivateScope); 02021 02022 void EmitOMPParallelDirective(const OMPParallelDirective &S); 02023 void EmitOMPSimdDirective(const OMPSimdDirective &S); 02024 void EmitOMPForDirective(const OMPForDirective &S); 02025 void EmitOMPForSimdDirective(const OMPForSimdDirective &S); 02026 void EmitOMPSectionsDirective(const OMPSectionsDirective &S); 02027 void EmitOMPSectionDirective(const OMPSectionDirective &S); 02028 void EmitOMPSingleDirective(const OMPSingleDirective &S); 02029 void EmitOMPMasterDirective(const OMPMasterDirective &S); 02030 void EmitOMPCriticalDirective(const OMPCriticalDirective &S); 02031 void EmitOMPParallelForDirective(const OMPParallelForDirective &S); 02032 void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S); 02033 void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S); 02034 void EmitOMPTaskDirective(const OMPTaskDirective &S); 02035 void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S); 02036 void EmitOMPBarrierDirective(const OMPBarrierDirective &S); 02037 void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S); 02038 void EmitOMPFlushDirective(const OMPFlushDirective &S); 02039 void EmitOMPOrderedDirective(const OMPOrderedDirective &S); 02040 void EmitOMPAtomicDirective(const OMPAtomicDirective &S); 02041 void EmitOMPTargetDirective(const OMPTargetDirective &S); 02042 void EmitOMPTeamsDirective(const OMPTeamsDirective &S); 02043 02044 /// Helpers for 'omp simd' directive. 02045 void EmitOMPLoopBody(const OMPLoopDirective &Directive, 02046 bool SeparateIter = false); 02047 void EmitOMPInnerLoop(const OMPLoopDirective &S, OMPPrivateScope &LoopScope, 02048 bool SeparateIter = false); 02049 void EmitOMPSimdFinal(const OMPLoopDirective &S); 02050 02051 //===--------------------------------------------------------------------===// 02052 // LValue Expression Emission 02053 //===--------------------------------------------------------------------===// 02054 02055 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type. 02056 RValue GetUndefRValue(QualType Ty); 02057 02058 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E 02059 /// and issue an ErrorUnsupported style diagnostic (using the 02060 /// provided Name). 02061 RValue EmitUnsupportedRValue(const Expr *E, 02062 const char *Name); 02063 02064 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue 02065 /// an ErrorUnsupported style diagnostic (using the provided Name). 02066 LValue EmitUnsupportedLValue(const Expr *E, 02067 const char *Name); 02068 02069 /// EmitLValue - Emit code to compute a designator that specifies the location 02070 /// of the expression. 02071 /// 02072 /// This can return one of two things: a simple address or a bitfield 02073 /// reference. In either case, the LLVM Value* in the LValue structure is 02074 /// guaranteed to be an LLVM pointer type. 02075 /// 02076 /// If this returns a bitfield reference, nothing about the pointee type of 02077 /// the LLVM value is known: For example, it may not be a pointer to an 02078 /// integer. 02079 /// 02080 /// If this returns a normal address, and if the lvalue's C type is fixed 02081 /// size, this method guarantees that the returned pointer type will point to 02082 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a 02083 /// variable length type, this is not possible. 02084 /// 02085 LValue EmitLValue(const Expr *E); 02086 02087 /// \brief Same as EmitLValue but additionally we generate checking code to 02088 /// guard against undefined behavior. This is only suitable when we know 02089 /// that the address will be used to access the object. 02090 LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK); 02091 02092 RValue convertTempToRValue(llvm::Value *addr, QualType type, 02093 SourceLocation Loc); 02094 02095 void EmitAtomicInit(Expr *E, LValue lvalue); 02096 02097 RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc, 02098 AggValueSlot slot = AggValueSlot::ignored()); 02099 02100 void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit); 02101 02102 /// EmitToMemory - Change a scalar value from its value 02103 /// representation to its in-memory representation. 02104 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty); 02105 02106 /// EmitFromMemory - Change a scalar value from its memory 02107 /// representation to its value representation. 02108 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty); 02109 02110 /// EmitLoadOfScalar - Load a scalar value from an address, taking 02111 /// care to appropriately convert from the memory representation to 02112 /// the LLVM value representation. 02113 llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile, 02114 unsigned Alignment, QualType Ty, 02115 SourceLocation Loc, 02116 llvm::MDNode *TBAAInfo = nullptr, 02117 QualType TBAABaseTy = QualType(), 02118 uint64_t TBAAOffset = 0); 02119 02120 /// EmitLoadOfScalar - Load a scalar value from an address, taking 02121 /// care to appropriately convert from the memory representation to 02122 /// the LLVM value representation. The l-value must be a simple 02123 /// l-value. 02124 llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc); 02125 02126 /// EmitStoreOfScalar - Store a scalar value to an address, taking 02127 /// care to appropriately convert from the memory representation to 02128 /// the LLVM value representation. 02129 void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr, 02130 bool Volatile, unsigned Alignment, QualType Ty, 02131 llvm::MDNode *TBAAInfo = nullptr, bool isInit = false, 02132 QualType TBAABaseTy = QualType(), 02133 uint64_t TBAAOffset = 0); 02134 02135 /// EmitStoreOfScalar - Store a scalar value to an address, taking 02136 /// care to appropriately convert from the memory representation to 02137 /// the LLVM value representation. The l-value must be a simple 02138 /// l-value. The isInit flag indicates whether this is an initialization. 02139 /// If so, atomic qualifiers are ignored and the store is always non-atomic. 02140 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false); 02141 02142 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, 02143 /// this method emits the address of the lvalue, then loads the result as an 02144 /// rvalue, returning the rvalue. 02145 RValue EmitLoadOfLValue(LValue V, SourceLocation Loc); 02146 RValue EmitLoadOfExtVectorElementLValue(LValue V); 02147 RValue EmitLoadOfBitfieldLValue(LValue LV); 02148 RValue EmitLoadOfGlobalRegLValue(LValue LV); 02149 02150 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 02151 /// lvalue, where both are guaranteed to the have the same type, and that type 02152 /// is 'Ty'. 02153 void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false); 02154 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst); 02155 void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst); 02156 02157 /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints 02158 /// as EmitStoreThroughLValue. 02159 /// 02160 /// \param Result [out] - If non-null, this will be set to a Value* for the 02161 /// bit-field contents after the store, appropriate for use as the result of 02162 /// an assignment to the bit-field. 02163 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 02164 llvm::Value **Result=nullptr); 02165 02166 /// Emit an l-value for an assignment (simple or compound) of complex type. 02167 LValue EmitComplexAssignmentLValue(const BinaryOperator *E); 02168 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E); 02169 LValue EmitScalarCompooundAssignWithComplex(const CompoundAssignOperator *E, 02170 llvm::Value *&Result); 02171 02172 // Note: only available for agg return types 02173 LValue EmitBinaryOperatorLValue(const BinaryOperator *E); 02174 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E); 02175 // Note: only available for agg return types 02176 LValue EmitCallExprLValue(const CallExpr *E); 02177 // Note: only available for agg return types 02178 LValue EmitVAArgExprLValue(const VAArgExpr *E); 02179 LValue EmitDeclRefLValue(const DeclRefExpr *E); 02180 LValue EmitReadRegister(const VarDecl *VD); 02181 LValue EmitStringLiteralLValue(const StringLiteral *E); 02182 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E); 02183 LValue EmitPredefinedLValue(const PredefinedExpr *E); 02184 LValue EmitUnaryOpLValue(const UnaryOperator *E); 02185 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E, 02186 bool Accessed = false); 02187 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E); 02188 LValue EmitMemberExpr(const MemberExpr *E); 02189 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E); 02190 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E); 02191 LValue EmitInitListLValue(const InitListExpr *E); 02192 LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E); 02193 LValue EmitCastLValue(const CastExpr *E); 02194 LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 02195 LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e); 02196 02197 llvm::Value *EmitExtVectorElementLValue(LValue V); 02198 02199 RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc); 02200 02201 class ConstantEmission { 02202 llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference; 02203 ConstantEmission(llvm::Constant *C, bool isReference) 02204 : ValueAndIsReference(C, isReference) {} 02205 public: 02206 ConstantEmission() {} 02207 static ConstantEmission forReference(llvm::Constant *C) { 02208 return ConstantEmission(C, true); 02209 } 02210 static ConstantEmission forValue(llvm::Constant *C) { 02211 return ConstantEmission(C, false); 02212 } 02213 02214 LLVM_EXPLICIT operator bool() const { 02215 return ValueAndIsReference.getOpaqueValue() != nullptr; 02216 } 02217 02218 bool isReference() const { return ValueAndIsReference.getInt(); } 02219 LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const { 02220 assert(isReference()); 02221 return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(), 02222 refExpr->getType()); 02223 } 02224 02225 llvm::Constant *getValue() const { 02226 assert(!isReference()); 02227 return ValueAndIsReference.getPointer(); 02228 } 02229 }; 02230 02231 ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr); 02232 02233 RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, 02234 AggValueSlot slot = AggValueSlot::ignored()); 02235 LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e); 02236 02237 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface, 02238 const ObjCIvarDecl *Ivar); 02239 LValue EmitLValueForField(LValue Base, const FieldDecl* Field); 02240 LValue EmitLValueForLambdaField(const FieldDecl *Field); 02241 02242 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that 02243 /// if the Field is a reference, this will return the address of the reference 02244 /// and not the address of the value stored in the reference. 02245 LValue EmitLValueForFieldInitialization(LValue Base, 02246 const FieldDecl* Field); 02247 02248 LValue EmitLValueForIvar(QualType ObjectTy, 02249 llvm::Value* Base, const ObjCIvarDecl *Ivar, 02250 unsigned CVRQualifiers); 02251 02252 LValue EmitCXXConstructLValue(const CXXConstructExpr *E); 02253 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E); 02254 LValue EmitLambdaLValue(const LambdaExpr *E); 02255 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E); 02256 LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E); 02257 02258 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E); 02259 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E); 02260 LValue EmitStmtExprLValue(const StmtExpr *E); 02261 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E); 02262 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E); 02263 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::Constant *Init); 02264 02265 //===--------------------------------------------------------------------===// 02266 // Scalar Expression Emission 02267 //===--------------------------------------------------------------------===// 02268 02269 /// EmitCall - Generate a call of the given function, expecting the given 02270 /// result type, and using the given argument list which specifies both the 02271 /// LLVM arguments and the types they were derived from. 02272 /// 02273 /// \param TargetDecl - If given, the decl of the function in a direct call; 02274 /// used to set attributes on the call (noreturn, etc.). 02275 RValue EmitCall(const CGFunctionInfo &FnInfo, 02276 llvm::Value *Callee, 02277 ReturnValueSlot ReturnValue, 02278 const CallArgList &Args, 02279 const Decl *TargetDecl = nullptr, 02280 llvm::Instruction **callOrInvoke = nullptr); 02281 02282 RValue EmitCall(QualType FnType, llvm::Value *Callee, const CallExpr *E, 02283 ReturnValueSlot ReturnValue, 02284 const Decl *TargetDecl = nullptr); 02285 RValue EmitCallExpr(const CallExpr *E, 02286 ReturnValueSlot ReturnValue = ReturnValueSlot()); 02287 02288 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee, 02289 const Twine &name = ""); 02290 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee, 02291 ArrayRef<llvm::Value*> args, 02292 const Twine &name = ""); 02293 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee, 02294 const Twine &name = ""); 02295 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee, 02296 ArrayRef<llvm::Value*> args, 02297 const Twine &name = ""); 02298 02299 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee, 02300 ArrayRef<llvm::Value *> Args, 02301 const Twine &Name = ""); 02302 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee, 02303 const Twine &Name = ""); 02304 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee, 02305 ArrayRef<llvm::Value*> args, 02306 const Twine &name = ""); 02307 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee, 02308 const Twine &name = ""); 02309 void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee, 02310 ArrayRef<llvm::Value*> args); 02311 02312 llvm::Value *BuildAppleKextVirtualCall(const CXXMethodDecl *MD, 02313 NestedNameSpecifier *Qual, 02314 llvm::Type *Ty); 02315 02316 llvm::Value *BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD, 02317 CXXDtorType Type, 02318 const CXXRecordDecl *RD); 02319 02320 RValue 02321 EmitCXXMemberOrOperatorCall(const CXXMethodDecl *MD, llvm::Value *Callee, 02322 ReturnValueSlot ReturnValue, llvm::Value *This, 02323 llvm::Value *ImplicitParam, 02324 QualType ImplicitParamTy, const CallExpr *E); 02325 RValue EmitCXXStructorCall(const CXXMethodDecl *MD, llvm::Value *Callee, 02326 ReturnValueSlot ReturnValue, llvm::Value *This, 02327 llvm::Value *ImplicitParam, 02328 QualType ImplicitParamTy, const CallExpr *E, 02329 StructorType Type); 02330 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E, 02331 ReturnValueSlot ReturnValue); 02332 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, 02333 ReturnValueSlot ReturnValue); 02334 02335 llvm::Value *EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E, 02336 const CXXMethodDecl *MD, 02337 llvm::Value *This); 02338 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 02339 const CXXMethodDecl *MD, 02340 ReturnValueSlot ReturnValue); 02341 02342 RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, 02343 ReturnValueSlot ReturnValue); 02344 02345 02346 RValue EmitBuiltinExpr(const FunctionDecl *FD, 02347 unsigned BuiltinID, const CallExpr *E); 02348 02349 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue); 02350 02351 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call 02352 /// is unhandled by the current target. 02353 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 02354 02355 llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty, 02356 const llvm::CmpInst::Predicate Fp, 02357 const llvm::CmpInst::Predicate Ip, 02358 const llvm::Twine &Name = ""); 02359 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 02360 02361 llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID, 02362 unsigned LLVMIntrinsic, 02363 unsigned AltLLVMIntrinsic, 02364 const char *NameHint, 02365 unsigned Modifier, 02366 const CallExpr *E, 02367 SmallVectorImpl<llvm::Value *> &Ops, 02368 llvm::Value *Align = nullptr); 02369 llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID, 02370 unsigned Modifier, llvm::Type *ArgTy, 02371 const CallExpr *E); 02372 llvm::Value *EmitNeonCall(llvm::Function *F, 02373 SmallVectorImpl<llvm::Value*> &O, 02374 const char *name, 02375 unsigned shift = 0, bool rightshift = false); 02376 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx); 02377 llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty, 02378 bool negateForRightShift); 02379 llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt, 02380 llvm::Type *Ty, bool usgn, const char *name); 02381 // Helper functions for EmitAArch64BuiltinExpr. 02382 llvm::Value *vectorWrapScalar8(llvm::Value *Op); 02383 llvm::Value *vectorWrapScalar16(llvm::Value *Op); 02384 llvm::Value *emitVectorWrappedScalar8Intrinsic( 02385 unsigned Int, SmallVectorImpl<llvm::Value *> &Ops, const char *Name); 02386 llvm::Value *emitVectorWrappedScalar16Intrinsic( 02387 unsigned Int, SmallVectorImpl<llvm::Value *> &Ops, const char *Name); 02388 llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 02389 llvm::Value *EmitNeon64Call(llvm::Function *F, 02390 llvm::SmallVectorImpl<llvm::Value *> &O, 02391 const char *name); 02392 02393 llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops); 02394 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 02395 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 02396 llvm::Value *EmitR600BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 02397 02398 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E); 02399 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E); 02400 llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E); 02401 llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E); 02402 llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E); 02403 llvm::Value *EmitObjCCollectionLiteral(const Expr *E, 02404 const ObjCMethodDecl *MethodWithObjects); 02405 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E); 02406 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, 02407 ReturnValueSlot Return = ReturnValueSlot()); 02408 02409 /// Retrieves the default cleanup kind for an ARC cleanup. 02410 /// Except under -fobjc-arc-eh, ARC cleanups are normal-only. 02411 CleanupKind getARCCleanupKind() { 02412 return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions 02413 ? NormalAndEHCleanup : NormalCleanup; 02414 } 02415 02416 // ARC primitives. 02417 void EmitARCInitWeak(llvm::Value *value, llvm::Value *addr); 02418 void EmitARCDestroyWeak(llvm::Value *addr); 02419 llvm::Value *EmitARCLoadWeak(llvm::Value *addr); 02420 llvm::Value *EmitARCLoadWeakRetained(llvm::Value *addr); 02421 llvm::Value *EmitARCStoreWeak(llvm::Value *value, llvm::Value *addr, 02422 bool ignored); 02423 void EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src); 02424 void EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src); 02425 llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value); 02426 llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value); 02427 llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value, 02428 bool resultIgnored); 02429 llvm::Value *EmitARCStoreStrongCall(llvm::Value *addr, llvm::Value *value, 02430 bool resultIgnored); 02431 llvm::Value *EmitARCRetain(QualType type, llvm::Value *value); 02432 llvm::Value *EmitARCRetainNonBlock(llvm::Value *value); 02433 llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory); 02434 void EmitARCDestroyStrong(llvm::Value *addr, ARCPreciseLifetime_t precise); 02435 void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise); 02436 llvm::Value *EmitARCAutorelease(llvm::Value *value); 02437 llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value); 02438 llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value); 02439 llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value); 02440 02441 std::pair<LValue,llvm::Value*> 02442 EmitARCStoreAutoreleasing(const BinaryOperator *e); 02443 std::pair<LValue,llvm::Value*> 02444 EmitARCStoreStrong(const BinaryOperator *e, bool ignored); 02445 02446 llvm::Value *EmitObjCThrowOperand(const Expr *expr); 02447 02448 llvm::Value *EmitObjCProduceObject(QualType T, llvm::Value *Ptr); 02449 llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr); 02450 llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr); 02451 02452 llvm::Value *EmitARCExtendBlockObject(const Expr *expr); 02453 llvm::Value *EmitARCRetainScalarExpr(const Expr *expr); 02454 llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr); 02455 02456 void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values); 02457 02458 static Destroyer destroyARCStrongImprecise; 02459 static Destroyer destroyARCStrongPrecise; 02460 static Destroyer destroyARCWeak; 02461 02462 void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr); 02463 llvm::Value *EmitObjCAutoreleasePoolPush(); 02464 llvm::Value *EmitObjCMRRAutoreleasePoolPush(); 02465 void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr); 02466 void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr); 02467 02468 /// \brief Emits a reference binding to the passed in expression. 02469 RValue EmitReferenceBindingToExpr(const Expr *E); 02470 02471 //===--------------------------------------------------------------------===// 02472 // Expression Emission 02473 //===--------------------------------------------------------------------===// 02474 02475 // Expressions are broken into three classes: scalar, complex, aggregate. 02476 02477 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM 02478 /// scalar type, returning the result. 02479 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false); 02480 02481 /// EmitScalarConversion - Emit a conversion from the specified type to the 02482 /// specified destination type, both of which are LLVM scalar types. 02483 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy, 02484 QualType DstTy); 02485 02486 /// EmitComplexToScalarConversion - Emit a conversion from the specified 02487 /// complex type to the specified destination type, where the destination type 02488 /// is an LLVM scalar type. 02489 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, 02490 QualType DstTy); 02491 02492 02493 /// EmitAggExpr - Emit the computation of the specified expression 02494 /// of aggregate type. The result is computed into the given slot, 02495 /// which may be null to indicate that the value is not needed. 02496 void EmitAggExpr(const Expr *E, AggValueSlot AS); 02497 02498 /// EmitAggExprToLValue - Emit the computation of the specified expression of 02499 /// aggregate type into a temporary LValue. 02500 LValue EmitAggExprToLValue(const Expr *E); 02501 02502 /// EmitGCMemmoveCollectable - Emit special API for structs with object 02503 /// pointers. 02504 void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr, 02505 QualType Ty); 02506 02507 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object, 02508 /// make sure it survives garbage collection until this point. 02509 void EmitExtendGCLifetime(llvm::Value *object); 02510 02511 /// EmitComplexExpr - Emit the computation of the specified expression of 02512 /// complex type, returning the result. 02513 ComplexPairTy EmitComplexExpr(const Expr *E, 02514 bool IgnoreReal = false, 02515 bool IgnoreImag = false); 02516 02517 /// EmitComplexExprIntoLValue - Emit the given expression of complex 02518 /// type and place its result into the specified l-value. 02519 void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit); 02520 02521 /// EmitStoreOfComplex - Store a complex number into the specified l-value. 02522 void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit); 02523 02524 /// EmitLoadOfComplex - Load a complex number from the specified l-value. 02525 ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc); 02526 02527 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the 02528 /// global variable that has already been created for it. If the initializer 02529 /// has a different type than GV does, this may free GV and return a different 02530 /// one. Otherwise it just returns GV. 02531 llvm::GlobalVariable * 02532 AddInitializerToStaticVarDecl(const VarDecl &D, 02533 llvm::GlobalVariable *GV); 02534 02535 02536 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++ 02537 /// variable with global storage. 02538 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr, 02539 bool PerformInit); 02540 02541 llvm::Constant *createAtExitStub(const VarDecl &VD, llvm::Constant *Dtor, 02542 llvm::Constant *Addr); 02543 02544 /// Call atexit() with a function that passes the given argument to 02545 /// the given function. 02546 void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn, 02547 llvm::Constant *addr); 02548 02549 /// Emit code in this function to perform a guarded variable 02550 /// initialization. Guarded initializations are used when it's not 02551 /// possible to prove that an initialization will be done exactly 02552 /// once, e.g. with a static local variable or a static data member 02553 /// of a class template. 02554 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr, 02555 bool PerformInit); 02556 02557 /// GenerateCXXGlobalInitFunc - Generates code for initializing global 02558 /// variables. 02559 void GenerateCXXGlobalInitFunc(llvm::Function *Fn, 02560 ArrayRef<llvm::Function *> CXXThreadLocals, 02561 llvm::GlobalVariable *Guard = nullptr); 02562 02563 /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global 02564 /// variables. 02565 void GenerateCXXGlobalDtorsFunc(llvm::Function *Fn, 02566 const std::vector<std::pair<llvm::WeakVH, 02567 llvm::Constant*> > &DtorsAndObjects); 02568 02569 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, 02570 const VarDecl *D, 02571 llvm::GlobalVariable *Addr, 02572 bool PerformInit); 02573 02574 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest); 02575 02576 void EmitSynthesizedCXXCopyCtor(llvm::Value *Dest, llvm::Value *Src, 02577 const Expr *Exp); 02578 02579 void enterFullExpression(const ExprWithCleanups *E) { 02580 if (E->getNumObjects() == 0) return; 02581 enterNonTrivialFullExpression(E); 02582 } 02583 void enterNonTrivialFullExpression(const ExprWithCleanups *E); 02584 02585 void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true); 02586 02587 void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest); 02588 02589 RValue EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest = nullptr); 02590 02591 //===--------------------------------------------------------------------===// 02592 // Annotations Emission 02593 //===--------------------------------------------------------------------===// 02594 02595 /// Emit an annotation call (intrinsic or builtin). 02596 llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn, 02597 llvm::Value *AnnotatedVal, 02598 StringRef AnnotationStr, 02599 SourceLocation Location); 02600 02601 /// Emit local annotations for the local variable V, declared by D. 02602 void EmitVarAnnotations(const VarDecl *D, llvm::Value *V); 02603 02604 /// Emit field annotations for the given field & value. Returns the 02605 /// annotation result. 02606 llvm::Value *EmitFieldAnnotations(const FieldDecl *D, llvm::Value *V); 02607 02608 //===--------------------------------------------------------------------===// 02609 // Internal Helpers 02610 //===--------------------------------------------------------------------===// 02611 02612 /// ContainsLabel - Return true if the statement contains a label in it. If 02613 /// this statement is not executed normally, it not containing a label means 02614 /// that we can just remove the code. 02615 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false); 02616 02617 /// containsBreak - Return true if the statement contains a break out of it. 02618 /// If the statement (recursively) contains a switch or loop with a break 02619 /// inside of it, this is fine. 02620 static bool containsBreak(const Stmt *S); 02621 02622 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 02623 /// to a constant, or if it does but contains a label, return false. If it 02624 /// constant folds return true and set the boolean result in Result. 02625 bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result); 02626 02627 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 02628 /// to a constant, or if it does but contains a label, return false. If it 02629 /// constant folds return true and set the folded value. 02630 bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result); 02631 02632 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an 02633 /// if statement) to the specified blocks. Based on the condition, this might 02634 /// try to simplify the codegen of the conditional based on the branch. 02635 /// TrueCount should be the number of times we expect the condition to 02636 /// evaluate to true based on PGO data. 02637 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, 02638 llvm::BasicBlock *FalseBlock, uint64_t TrueCount); 02639 02640 /// \brief Emit a description of a type in a format suitable for passing to 02641 /// a runtime sanitizer handler. 02642 llvm::Constant *EmitCheckTypeDescriptor(QualType T); 02643 02644 /// \brief Convert a value into a format suitable for passing to a runtime 02645 /// sanitizer handler. 02646 llvm::Value *EmitCheckValue(llvm::Value *V); 02647 02648 /// \brief Emit a description of a source location in a format suitable for 02649 /// passing to a runtime sanitizer handler. 02650 llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc); 02651 02652 /// \brief Create a basic block that will call a handler function in a 02653 /// sanitizer runtime with the provided arguments, and create a conditional 02654 /// branch to it. 02655 void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerKind>> Checked, 02656 StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs, 02657 ArrayRef<llvm::Value *> DynamicArgs); 02658 02659 /// \brief Create a basic block that will call the trap intrinsic, and emit a 02660 /// conditional branch to it, for the -ftrapv checks. 02661 void EmitTrapCheck(llvm::Value *Checked); 02662 02663 /// EmitCallArg - Emit a single call argument. 02664 void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType); 02665 02666 /// EmitDelegateCallArg - We are performing a delegate call; that 02667 /// is, the current function is delegating to another one. Produce 02668 /// a r-value suitable for passing the given parameter. 02669 void EmitDelegateCallArg(CallArgList &args, const VarDecl *param, 02670 SourceLocation loc); 02671 02672 /// SetFPAccuracy - Set the minimum required accuracy of the given floating 02673 /// point operation, expressed as the maximum relative error in ulp. 02674 void SetFPAccuracy(llvm::Value *Val, float Accuracy); 02675 02676 private: 02677 llvm::MDNode *getRangeForLoadFromType(QualType Ty); 02678 void EmitReturnOfRValue(RValue RV, QualType Ty); 02679 02680 void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New); 02681 02682 llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4> 02683 DeferredReplacements; 02684 02685 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty 02686 /// from function arguments into \arg Dst. See ABIArgInfo::Expand. 02687 /// 02688 /// \param AI - The first function argument of the expansion. 02689 void ExpandTypeFromArgs(QualType Ty, LValue Dst, 02690 SmallVectorImpl<llvm::Argument *>::iterator &AI); 02691 02692 /// ExpandTypeToArgs - Expand an RValue \arg RV, with the LLVM type for \arg 02693 /// Ty, into individual arguments on the provided vector \arg IRCallArgs, 02694 /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand. 02695 void ExpandTypeToArgs(QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy, 02696 SmallVectorImpl<llvm::Value *> &IRCallArgs, 02697 unsigned &IRCallArgPos); 02698 02699 llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info, 02700 const Expr *InputExpr, std::string &ConstraintStr); 02701 02702 llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info, 02703 LValue InputValue, QualType InputType, 02704 std::string &ConstraintStr, 02705 SourceLocation Loc); 02706 02707 public: 02708 /// EmitCallArgs - Emit call arguments for a function. 02709 template <typename T> 02710 void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo, 02711 CallExpr::const_arg_iterator ArgBeg, 02712 CallExpr::const_arg_iterator ArgEnd, 02713 const FunctionDecl *CalleeDecl = nullptr, 02714 unsigned ParamsToSkip = 0, bool ForceColumnInfo = false) { 02715 SmallVector<QualType, 16> ArgTypes; 02716 CallExpr::const_arg_iterator Arg = ArgBeg; 02717 02718 assert((ParamsToSkip == 0 || CallArgTypeInfo) && 02719 "Can't skip parameters if type info is not provided"); 02720 if (CallArgTypeInfo) { 02721 // First, use the argument types that the type info knows about 02722 for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip, 02723 E = CallArgTypeInfo->param_type_end(); 02724 I != E; ++I, ++Arg) { 02725 assert(Arg != ArgEnd && "Running over edge of argument list!"); 02726 #ifndef NDEBUG 02727 QualType ArgType = *I; 02728 QualType ActualArgType = Arg->getType(); 02729 if (ArgType->isPointerType() && ActualArgType->isPointerType()) { 02730 QualType ActualBaseType = 02731 ActualArgType->getAs<PointerType>()->getPointeeType(); 02732 QualType ArgBaseType = 02733 ArgType->getAs<PointerType>()->getPointeeType(); 02734 if (ArgBaseType->isVariableArrayType()) { 02735 if (const VariableArrayType *VAT = 02736 getContext().getAsVariableArrayType(ActualBaseType)) { 02737 if (!VAT->getSizeExpr()) 02738 ActualArgType = ArgType; 02739 } 02740 } 02741 } 02742 assert(getContext() 02743 .getCanonicalType(ArgType.getNonReferenceType()) 02744 .getTypePtr() == 02745 getContext().getCanonicalType(ActualArgType).getTypePtr() && 02746 "type mismatch in call argument!"); 02747 #endif 02748 ArgTypes.push_back(*I); 02749 } 02750 } 02751 02752 // Either we've emitted all the call args, or we have a call to variadic 02753 // function. 02754 assert( 02755 (Arg == ArgEnd || !CallArgTypeInfo || CallArgTypeInfo->isVariadic()) && 02756 "Extra arguments in non-variadic function!"); 02757 02758 // If we still have any arguments, emit them using the type of the argument. 02759 for (; Arg != ArgEnd; ++Arg) 02760 ArgTypes.push_back(getVarArgType(*Arg)); 02761 02762 EmitCallArgs(Args, ArgTypes, ArgBeg, ArgEnd, CalleeDecl, ParamsToSkip, 02763 ForceColumnInfo); 02764 } 02765 02766 void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes, 02767 CallExpr::const_arg_iterator ArgBeg, 02768 CallExpr::const_arg_iterator ArgEnd, 02769 const FunctionDecl *CalleeDecl = nullptr, 02770 unsigned ParamsToSkip = 0, bool ForceColumnInfo = false); 02771 02772 private: 02773 QualType getVarArgType(const Expr *Arg); 02774 02775 const TargetCodeGenInfo &getTargetHooks() const { 02776 return CGM.getTargetCodeGenInfo(); 02777 } 02778 02779 void EmitDeclMetadata(); 02780 02781 CodeGenModule::ByrefHelpers * 02782 buildByrefHelpers(llvm::StructType &byrefType, 02783 const AutoVarEmission &emission); 02784 02785 void AddObjCARCExceptionMetadata(llvm::Instruction *Inst); 02786 02787 /// GetPointeeAlignment - Given an expression with a pointer type, emit the 02788 /// value and compute our best estimate of the alignment of the pointee. 02789 std::pair<llvm::Value*, unsigned> EmitPointerWithAlignment(const Expr *Addr); 02790 }; 02791 02792 /// Helper class with most of the code for saving a value for a 02793 /// conditional expression cleanup. 02794 struct DominatingLLVMValue { 02795 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type; 02796 02797 /// Answer whether the given value needs extra work to be saved. 02798 static bool needsSaving(llvm::Value *value) { 02799 // If it's not an instruction, we don't need to save. 02800 if (!isa<llvm::Instruction>(value)) return false; 02801 02802 // If it's an instruction in the entry block, we don't need to save. 02803 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent(); 02804 return (block != &block->getParent()->getEntryBlock()); 02805 } 02806 02807 /// Try to save the given value. 02808 static saved_type save(CodeGenFunction &CGF, llvm::Value *value) { 02809 if (!needsSaving(value)) return saved_type(value, false); 02810 02811 // Otherwise we need an alloca. 02812 llvm::Value *alloca = 02813 CGF.CreateTempAlloca(value->getType(), "cond-cleanup.save"); 02814 CGF.Builder.CreateStore(value, alloca); 02815 02816 return saved_type(alloca, true); 02817 } 02818 02819 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) { 02820 if (!value.getInt()) return value.getPointer(); 02821 return CGF.Builder.CreateLoad(value.getPointer()); 02822 } 02823 }; 02824 02825 /// A partial specialization of DominatingValue for llvm::Values that 02826 /// might be llvm::Instructions. 02827 template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue { 02828 typedef T *type; 02829 static type restore(CodeGenFunction &CGF, saved_type value) { 02830 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value)); 02831 } 02832 }; 02833 02834 /// A specialization of DominatingValue for RValue. 02835 template <> struct DominatingValue<RValue> { 02836 typedef RValue type; 02837 class saved_type { 02838 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral, 02839 AggregateAddress, ComplexAddress }; 02840 02841 llvm::Value *Value; 02842 Kind K; 02843 saved_type(llvm::Value *v, Kind k) : Value(v), K(k) {} 02844 02845 public: 02846 static bool needsSaving(RValue value); 02847 static saved_type save(CodeGenFunction &CGF, RValue value); 02848 RValue restore(CodeGenFunction &CGF); 02849 02850 // implementations in CGExprCXX.cpp 02851 }; 02852 02853 static bool needsSaving(type value) { 02854 return saved_type::needsSaving(value); 02855 } 02856 static saved_type save(CodeGenFunction &CGF, type value) { 02857 return saved_type::save(CGF, value); 02858 } 02859 static type restore(CodeGenFunction &CGF, saved_type value) { 02860 return value.restore(CGF); 02861 } 02862 }; 02863 02864 } // end namespace CodeGen 02865 } // end namespace clang 02866 02867 #endif