clang API Documentation
00001 //===--- MicrosoftCXXABI.cpp - Emit LLVM Code from ASTs for a Module ------===// 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 provides C++ code generation targeting the Microsoft Visual C++ ABI. 00011 // The class in this file generates structures that follow the Microsoft 00012 // Visual C++ ABI, which is actually not very well documented at all outside 00013 // of Microsoft. 00014 // 00015 //===----------------------------------------------------------------------===// 00016 00017 #include "CGCXXABI.h" 00018 #include "CGVTables.h" 00019 #include "CodeGenModule.h" 00020 #include "clang/AST/Decl.h" 00021 #include "clang/AST/DeclCXX.h" 00022 #include "clang/AST/VTableBuilder.h" 00023 #include "llvm/ADT/StringExtras.h" 00024 #include "llvm/ADT/StringSet.h" 00025 #include "llvm/IR/CallSite.h" 00026 00027 using namespace clang; 00028 using namespace CodeGen; 00029 00030 namespace { 00031 00032 /// Holds all the vbtable globals for a given class. 00033 struct VBTableGlobals { 00034 const VPtrInfoVector *VBTables; 00035 SmallVector<llvm::GlobalVariable *, 2> Globals; 00036 }; 00037 00038 class MicrosoftCXXABI : public CGCXXABI { 00039 public: 00040 MicrosoftCXXABI(CodeGenModule &CGM) 00041 : CGCXXABI(CGM), BaseClassDescriptorType(nullptr), 00042 ClassHierarchyDescriptorType(nullptr), 00043 CompleteObjectLocatorType(nullptr) {} 00044 00045 bool HasThisReturn(GlobalDecl GD) const override; 00046 bool hasMostDerivedReturn(GlobalDecl GD) const override; 00047 00048 bool classifyReturnType(CGFunctionInfo &FI) const override; 00049 00050 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override; 00051 00052 bool isSRetParameterAfterThis() const override { return true; } 00053 00054 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *CD, 00055 FunctionArgList &Args) const override { 00056 assert(Args.size() >= 2 && 00057 "expected the arglist to have at least two args!"); 00058 // The 'most_derived' parameter goes second if the ctor is variadic and 00059 // has v-bases. 00060 if (CD->getParent()->getNumVBases() > 0 && 00061 CD->getType()->castAs<FunctionProtoType>()->isVariadic()) 00062 return 2; 00063 return 1; 00064 } 00065 00066 StringRef GetPureVirtualCallName() override { return "_purecall"; } 00067 StringRef GetDeletedVirtualCallName() override { return "_purecall"; } 00068 00069 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE, 00070 llvm::Value *Ptr, QualType ElementType, 00071 const CXXDestructorDecl *Dtor) override; 00072 00073 llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD, 00074 const VPtrInfo *Info); 00075 00076 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override; 00077 00078 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override; 00079 void EmitBadTypeidCall(CodeGenFunction &CGF) override; 00080 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy, 00081 llvm::Value *ThisPtr, 00082 llvm::Type *StdTypeInfoPtrTy) override; 00083 00084 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr, 00085 QualType SrcRecordTy) override; 00086 00087 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value, 00088 QualType SrcRecordTy, QualType DestTy, 00089 QualType DestRecordTy, 00090 llvm::BasicBlock *CastEnd) override; 00091 00092 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value, 00093 QualType SrcRecordTy, 00094 QualType DestTy) override; 00095 00096 bool EmitBadCastCall(CodeGenFunction &CGF) override; 00097 00098 llvm::Value * 00099 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This, 00100 const CXXRecordDecl *ClassDecl, 00101 const CXXRecordDecl *BaseClassDecl) override; 00102 00103 llvm::BasicBlock * 00104 EmitCtorCompleteObjectHandler(CodeGenFunction &CGF, 00105 const CXXRecordDecl *RD) override; 00106 00107 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF, 00108 const CXXRecordDecl *RD) override; 00109 00110 void EmitCXXConstructors(const CXXConstructorDecl *D) override; 00111 00112 // Background on MSVC destructors 00113 // ============================== 00114 // 00115 // Both Itanium and MSVC ABIs have destructor variants. The variant names 00116 // roughly correspond in the following way: 00117 // Itanium Microsoft 00118 // Base -> no name, just ~Class 00119 // Complete -> vbase destructor 00120 // Deleting -> scalar deleting destructor 00121 // vector deleting destructor 00122 // 00123 // The base and complete destructors are the same as in Itanium, although the 00124 // complete destructor does not accept a VTT parameter when there are virtual 00125 // bases. A separate mechanism involving vtordisps is used to ensure that 00126 // virtual methods of destroyed subobjects are not called. 00127 // 00128 // The deleting destructors accept an i32 bitfield as a second parameter. Bit 00129 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this 00130 // pointer points to an array. The scalar deleting destructor assumes that 00131 // bit 2 is zero, and therefore does not contain a loop. 00132 // 00133 // For virtual destructors, only one entry is reserved in the vftable, and it 00134 // always points to the vector deleting destructor. The vector deleting 00135 // destructor is the most general, so it can be used to destroy objects in 00136 // place, delete single heap objects, or delete arrays. 00137 // 00138 // A TU defining a non-inline destructor is only guaranteed to emit a base 00139 // destructor, and all of the other variants are emitted on an as-needed basis 00140 // in COMDATs. Because a non-base destructor can be emitted in a TU that 00141 // lacks a definition for the destructor, non-base destructors must always 00142 // delegate to or alias the base destructor. 00143 00144 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T, 00145 SmallVectorImpl<CanQualType> &ArgTys) override; 00146 00147 /// Non-base dtors should be emitted as delegating thunks in this ABI. 00148 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor, 00149 CXXDtorType DT) const override { 00150 return DT != Dtor_Base; 00151 } 00152 00153 void EmitCXXDestructors(const CXXDestructorDecl *D) override; 00154 00155 const CXXRecordDecl * 00156 getThisArgumentTypeForMethod(const CXXMethodDecl *MD) override { 00157 MD = MD->getCanonicalDecl(); 00158 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) { 00159 MicrosoftVTableContext::MethodVFTableLocation ML = 00160 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD); 00161 // The vbases might be ordered differently in the final overrider object 00162 // and the complete object, so the "this" argument may sometimes point to 00163 // memory that has no particular type (e.g. past the complete object). 00164 // In this case, we just use a generic pointer type. 00165 // FIXME: might want to have a more precise type in the non-virtual 00166 // multiple inheritance case. 00167 if (ML.VBase || !ML.VFPtrOffset.isZero()) 00168 return nullptr; 00169 } 00170 return MD->getParent(); 00171 } 00172 00173 llvm::Value * 00174 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD, 00175 llvm::Value *This, 00176 bool VirtualCall) override; 00177 00178 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy, 00179 FunctionArgList &Params) override; 00180 00181 llvm::Value *adjustThisParameterInVirtualFunctionPrologue( 00182 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) override; 00183 00184 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override; 00185 00186 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF, 00187 const CXXConstructorDecl *D, 00188 CXXCtorType Type, bool ForVirtualBase, 00189 bool Delegating, 00190 CallArgList &Args) override; 00191 00192 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD, 00193 CXXDtorType Type, bool ForVirtualBase, 00194 bool Delegating, llvm::Value *This) override; 00195 00196 void emitVTableDefinitions(CodeGenVTables &CGVT, 00197 const CXXRecordDecl *RD) override; 00198 00199 llvm::Value *getVTableAddressPointInStructor( 00200 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, 00201 BaseSubobject Base, const CXXRecordDecl *NearestVBase, 00202 bool &NeedsVirtualOffset) override; 00203 00204 llvm::Constant * 00205 getVTableAddressPointForConstExpr(BaseSubobject Base, 00206 const CXXRecordDecl *VTableClass) override; 00207 00208 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD, 00209 CharUnits VPtrOffset) override; 00210 00211 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD, 00212 llvm::Value *This, 00213 llvm::Type *Ty) override; 00214 00215 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF, 00216 const CXXDestructorDecl *Dtor, 00217 CXXDtorType DtorType, 00218 llvm::Value *This, 00219 const CXXMemberCallExpr *CE) override; 00220 00221 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD, 00222 CallArgList &CallArgs) override { 00223 assert(GD.getDtorType() == Dtor_Deleting && 00224 "Only deleting destructor thunks are available in this ABI"); 00225 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)), 00226 CGM.getContext().IntTy); 00227 } 00228 00229 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override; 00230 00231 llvm::GlobalVariable * 00232 getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD, 00233 llvm::GlobalVariable::LinkageTypes Linkage); 00234 00235 void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD, 00236 llvm::GlobalVariable *GV) const; 00237 00238 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, 00239 GlobalDecl GD, bool ReturnAdjustment) override { 00240 // Never dllimport/dllexport thunks. 00241 Thunk->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 00242 00243 GVALinkage Linkage = 00244 getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl())); 00245 00246 if (Linkage == GVA_Internal) 00247 Thunk->setLinkage(llvm::GlobalValue::InternalLinkage); 00248 else if (ReturnAdjustment) 00249 Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage); 00250 else 00251 Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage); 00252 } 00253 00254 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This, 00255 const ThisAdjustment &TA) override; 00256 00257 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret, 00258 const ReturnAdjustment &RA) override; 00259 00260 void EmitThreadLocalInitFuncs( 00261 CodeGenModule &CGM, 00262 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>> 00263 CXXThreadLocals, 00264 ArrayRef<llvm::Function *> CXXThreadLocalInits, 00265 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) override; 00266 00267 bool usesThreadWrapperFunction() const override { return false; } 00268 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, 00269 QualType LValType) override; 00270 00271 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, 00272 llvm::GlobalVariable *DeclPtr, 00273 bool PerformInit) override; 00274 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D, 00275 llvm::Constant *Dtor, llvm::Constant *Addr) override; 00276 00277 // ==== Notes on array cookies ========= 00278 // 00279 // MSVC seems to only use cookies when the class has a destructor; a 00280 // two-argument usual array deallocation function isn't sufficient. 00281 // 00282 // For example, this code prints "100" and "1": 00283 // struct A { 00284 // char x; 00285 // void *operator new[](size_t sz) { 00286 // printf("%u\n", sz); 00287 // return malloc(sz); 00288 // } 00289 // void operator delete[](void *p, size_t sz) { 00290 // printf("%u\n", sz); 00291 // free(p); 00292 // } 00293 // }; 00294 // int main() { 00295 // A *p = new A[100]; 00296 // delete[] p; 00297 // } 00298 // Whereas it prints "104" and "104" if you give A a destructor. 00299 00300 bool requiresArrayCookie(const CXXDeleteExpr *expr, 00301 QualType elementType) override; 00302 bool requiresArrayCookie(const CXXNewExpr *expr) override; 00303 CharUnits getArrayCookieSizeImpl(QualType type) override; 00304 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF, 00305 llvm::Value *NewPtr, 00306 llvm::Value *NumElements, 00307 const CXXNewExpr *expr, 00308 QualType ElementType) override; 00309 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, 00310 llvm::Value *allocPtr, 00311 CharUnits cookieSize) override; 00312 00313 friend struct MSRTTIBuilder; 00314 00315 bool isImageRelative() const { 00316 return CGM.getTarget().getPointerWidth(/*AddressSpace=*/0) == 64; 00317 } 00318 00319 // 5 routines for constructing the llvm types for MS RTTI structs. 00320 llvm::StructType *getTypeDescriptorType(StringRef TypeInfoString) { 00321 llvm::SmallString<32> TDTypeName("rtti.TypeDescriptor"); 00322 TDTypeName += llvm::utostr(TypeInfoString.size()); 00323 llvm::StructType *&TypeDescriptorType = 00324 TypeDescriptorTypeMap[TypeInfoString.size()]; 00325 if (TypeDescriptorType) 00326 return TypeDescriptorType; 00327 llvm::Type *FieldTypes[] = { 00328 CGM.Int8PtrPtrTy, 00329 CGM.Int8PtrTy, 00330 llvm::ArrayType::get(CGM.Int8Ty, TypeInfoString.size() + 1)}; 00331 TypeDescriptorType = 00332 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, TDTypeName); 00333 return TypeDescriptorType; 00334 } 00335 00336 llvm::Type *getImageRelativeType(llvm::Type *PtrType) { 00337 if (!isImageRelative()) 00338 return PtrType; 00339 return CGM.IntTy; 00340 } 00341 00342 llvm::StructType *getBaseClassDescriptorType() { 00343 if (BaseClassDescriptorType) 00344 return BaseClassDescriptorType; 00345 llvm::Type *FieldTypes[] = { 00346 getImageRelativeType(CGM.Int8PtrTy), 00347 CGM.IntTy, 00348 CGM.IntTy, 00349 CGM.IntTy, 00350 CGM.IntTy, 00351 CGM.IntTy, 00352 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()), 00353 }; 00354 BaseClassDescriptorType = llvm::StructType::create( 00355 CGM.getLLVMContext(), FieldTypes, "rtti.BaseClassDescriptor"); 00356 return BaseClassDescriptorType; 00357 } 00358 00359 llvm::StructType *getClassHierarchyDescriptorType() { 00360 if (ClassHierarchyDescriptorType) 00361 return ClassHierarchyDescriptorType; 00362 // Forward-declare RTTIClassHierarchyDescriptor to break a cycle. 00363 ClassHierarchyDescriptorType = llvm::StructType::create( 00364 CGM.getLLVMContext(), "rtti.ClassHierarchyDescriptor"); 00365 llvm::Type *FieldTypes[] = { 00366 CGM.IntTy, 00367 CGM.IntTy, 00368 CGM.IntTy, 00369 getImageRelativeType( 00370 getBaseClassDescriptorType()->getPointerTo()->getPointerTo()), 00371 }; 00372 ClassHierarchyDescriptorType->setBody(FieldTypes); 00373 return ClassHierarchyDescriptorType; 00374 } 00375 00376 llvm::StructType *getCompleteObjectLocatorType() { 00377 if (CompleteObjectLocatorType) 00378 return CompleteObjectLocatorType; 00379 CompleteObjectLocatorType = llvm::StructType::create( 00380 CGM.getLLVMContext(), "rtti.CompleteObjectLocator"); 00381 llvm::Type *FieldTypes[] = { 00382 CGM.IntTy, 00383 CGM.IntTy, 00384 CGM.IntTy, 00385 getImageRelativeType(CGM.Int8PtrTy), 00386 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()), 00387 getImageRelativeType(CompleteObjectLocatorType), 00388 }; 00389 llvm::ArrayRef<llvm::Type *> FieldTypesRef(FieldTypes); 00390 if (!isImageRelative()) 00391 FieldTypesRef = FieldTypesRef.drop_back(); 00392 CompleteObjectLocatorType->setBody(FieldTypesRef); 00393 return CompleteObjectLocatorType; 00394 } 00395 00396 llvm::GlobalVariable *getImageBase() { 00397 StringRef Name = "__ImageBase"; 00398 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name)) 00399 return GV; 00400 00401 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, 00402 /*isConstant=*/true, 00403 llvm::GlobalValue::ExternalLinkage, 00404 /*Initializer=*/nullptr, Name); 00405 } 00406 00407 llvm::Constant *getImageRelativeConstant(llvm::Constant *PtrVal) { 00408 if (!isImageRelative()) 00409 return PtrVal; 00410 00411 llvm::Constant *ImageBaseAsInt = 00412 llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM.IntPtrTy); 00413 llvm::Constant *PtrValAsInt = 00414 llvm::ConstantExpr::getPtrToInt(PtrVal, CGM.IntPtrTy); 00415 llvm::Constant *Diff = 00416 llvm::ConstantExpr::getSub(PtrValAsInt, ImageBaseAsInt, 00417 /*HasNUW=*/true, /*HasNSW=*/true); 00418 return llvm::ConstantExpr::getTrunc(Diff, CGM.IntTy); 00419 } 00420 00421 private: 00422 MicrosoftMangleContext &getMangleContext() { 00423 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext()); 00424 } 00425 00426 llvm::Constant *getZeroInt() { 00427 return llvm::ConstantInt::get(CGM.IntTy, 0); 00428 } 00429 00430 llvm::Constant *getAllOnesInt() { 00431 return llvm::Constant::getAllOnesValue(CGM.IntTy); 00432 } 00433 00434 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) { 00435 return C ? C : getZeroInt(); 00436 } 00437 00438 llvm::Value *getValueOrZeroInt(llvm::Value *C) { 00439 return C ? C : getZeroInt(); 00440 } 00441 00442 CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD); 00443 00444 void 00445 GetNullMemberPointerFields(const MemberPointerType *MPT, 00446 llvm::SmallVectorImpl<llvm::Constant *> &fields); 00447 00448 /// \brief Shared code for virtual base adjustment. Returns the offset from 00449 /// the vbptr to the virtual base. Optionally returns the address of the 00450 /// vbptr itself. 00451 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF, 00452 llvm::Value *Base, 00453 llvm::Value *VBPtrOffset, 00454 llvm::Value *VBTableOffset, 00455 llvm::Value **VBPtr = nullptr); 00456 00457 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF, 00458 llvm::Value *Base, 00459 int32_t VBPtrOffset, 00460 int32_t VBTableOffset, 00461 llvm::Value **VBPtr = nullptr) { 00462 assert(VBTableOffset % 4 == 0 && "should be byte offset into table of i32s"); 00463 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), 00464 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset); 00465 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr); 00466 } 00467 00468 /// \brief Performs a full virtual base adjustment. Used to dereference 00469 /// pointers to members of virtual bases. 00470 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E, 00471 const CXXRecordDecl *RD, llvm::Value *Base, 00472 llvm::Value *VirtualBaseAdjustmentOffset, 00473 llvm::Value *VBPtrOffset /* optional */); 00474 00475 /// \brief Emits a full member pointer with the fields common to data and 00476 /// function member pointers. 00477 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField, 00478 bool IsMemberFunction, 00479 const CXXRecordDecl *RD, 00480 CharUnits NonVirtualBaseAdjustment); 00481 00482 llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD, 00483 const CXXMethodDecl *MD, 00484 CharUnits NonVirtualBaseAdjustment); 00485 00486 bool MemberPointerConstantIsNull(const MemberPointerType *MPT, 00487 llvm::Constant *MP); 00488 00489 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type. 00490 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD); 00491 00492 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables(). 00493 const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD); 00494 00495 /// \brief Generate a thunk for calling a virtual member function MD. 00496 llvm::Function *EmitVirtualMemPtrThunk( 00497 const CXXMethodDecl *MD, 00498 const MicrosoftVTableContext::MethodVFTableLocation &ML); 00499 00500 public: 00501 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override; 00502 00503 bool isZeroInitializable(const MemberPointerType *MPT) override; 00504 00505 bool isMemberPointerConvertible(const MemberPointerType *MPT) const override { 00506 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 00507 return RD->hasAttr<MSInheritanceAttr>(); 00508 } 00509 00510 bool isTypeInfoCalculable(QualType Ty) const override { 00511 if (!CGCXXABI::isTypeInfoCalculable(Ty)) 00512 return false; 00513 if (const auto *MPT = Ty->getAs<MemberPointerType>()) { 00514 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 00515 if (!RD->hasAttr<MSInheritanceAttr>()) 00516 return false; 00517 } 00518 return true; 00519 } 00520 00521 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override; 00522 00523 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT, 00524 CharUnits offset) override; 00525 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD) override; 00526 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override; 00527 00528 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF, 00529 llvm::Value *L, 00530 llvm::Value *R, 00531 const MemberPointerType *MPT, 00532 bool Inequality) override; 00533 00534 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 00535 llvm::Value *MemPtr, 00536 const MemberPointerType *MPT) override; 00537 00538 llvm::Value * 00539 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E, 00540 llvm::Value *Base, llvm::Value *MemPtr, 00541 const MemberPointerType *MPT) override; 00542 00543 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF, 00544 const CastExpr *E, 00545 llvm::Value *Src) override; 00546 00547 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E, 00548 llvm::Constant *Src) override; 00549 00550 llvm::Value * 00551 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E, 00552 llvm::Value *&This, llvm::Value *MemPtr, 00553 const MemberPointerType *MPT) override; 00554 00555 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override; 00556 00557 private: 00558 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy; 00559 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VTablesMapTy; 00560 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalValue *> VFTablesMapTy; 00561 /// \brief All the vftables that have been referenced. 00562 VFTablesMapTy VFTablesMap; 00563 VTablesMapTy VTablesMap; 00564 00565 /// \brief This set holds the record decls we've deferred vtable emission for. 00566 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables; 00567 00568 00569 /// \brief All the vbtables which have been referenced. 00570 llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap; 00571 00572 /// Info on the global variable used to guard initialization of static locals. 00573 /// The BitIndex field is only used for externally invisible declarations. 00574 struct GuardInfo { 00575 GuardInfo() : Guard(nullptr), BitIndex(0) {} 00576 llvm::GlobalVariable *Guard; 00577 unsigned BitIndex; 00578 }; 00579 00580 /// Map from DeclContext to the current guard variable. We assume that the 00581 /// AST is visited in source code order. 00582 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap; 00583 00584 llvm::DenseMap<size_t, llvm::StructType *> TypeDescriptorTypeMap; 00585 llvm::StructType *BaseClassDescriptorType; 00586 llvm::StructType *ClassHierarchyDescriptorType; 00587 llvm::StructType *CompleteObjectLocatorType; 00588 }; 00589 00590 } 00591 00592 CGCXXABI::RecordArgABI 00593 MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const { 00594 switch (CGM.getTarget().getTriple().getArch()) { 00595 default: 00596 // FIXME: Implement for other architectures. 00597 return RAA_Default; 00598 00599 case llvm::Triple::x86: 00600 // All record arguments are passed in memory on x86. Decide whether to 00601 // construct the object directly in argument memory, or to construct the 00602 // argument elsewhere and copy the bytes during the call. 00603 00604 // If C++ prohibits us from making a copy, construct the arguments directly 00605 // into argument memory. 00606 if (!canCopyArgument(RD)) 00607 return RAA_DirectInMemory; 00608 00609 // Otherwise, construct the argument into a temporary and copy the bytes 00610 // into the outgoing argument memory. 00611 return RAA_Default; 00612 00613 case llvm::Triple::x86_64: 00614 // Win64 passes objects with non-trivial copy ctors indirectly. 00615 if (RD->hasNonTrivialCopyConstructor()) 00616 return RAA_Indirect; 00617 00618 // If an object has a destructor, we'd really like to pass it indirectly 00619 // because it allows us to elide copies. Unfortunately, MSVC makes that 00620 // impossible for small types, which it will pass in a single register or 00621 // stack slot. Most objects with dtors are large-ish, so handle that early. 00622 // We can't call out all large objects as being indirect because there are 00623 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 00624 // how we pass large POD types. 00625 if (RD->hasNonTrivialDestructor() && 00626 getContext().getTypeSize(RD->getTypeForDecl()) > 64) 00627 return RAA_Indirect; 00628 00629 // We have a trivial copy constructor or no copy constructors, but we have 00630 // to make sure it isn't deleted. 00631 bool CopyDeleted = false; 00632 for (const CXXConstructorDecl *CD : RD->ctors()) { 00633 if (CD->isCopyConstructor()) { 00634 assert(CD->isTrivial()); 00635 // We had at least one undeleted trivial copy ctor. Return directly. 00636 if (!CD->isDeleted()) 00637 return RAA_Default; 00638 CopyDeleted = true; 00639 } 00640 } 00641 00642 // The trivial copy constructor was deleted. Return indirectly. 00643 if (CopyDeleted) 00644 return RAA_Indirect; 00645 00646 // There were no copy ctors. Return in RAX. 00647 return RAA_Default; 00648 } 00649 00650 llvm_unreachable("invalid enum"); 00651 } 00652 00653 void MicrosoftCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF, 00654 const CXXDeleteExpr *DE, 00655 llvm::Value *Ptr, 00656 QualType ElementType, 00657 const CXXDestructorDecl *Dtor) { 00658 // FIXME: Provide a source location here even though there's no 00659 // CXXMemberCallExpr for dtor call. 00660 bool UseGlobalDelete = DE->isGlobalDelete(); 00661 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting; 00662 llvm::Value *MDThis = 00663 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr); 00664 if (UseGlobalDelete) 00665 CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType); 00666 } 00667 00668 /// \brief Gets the offset to the virtual base that contains the vfptr for 00669 /// MS-ABI polymorphic types. 00670 static llvm::Value *getPolymorphicOffset(CodeGenFunction &CGF, 00671 const CXXRecordDecl *RD, 00672 llvm::Value *Value) { 00673 const ASTContext &Context = RD->getASTContext(); 00674 for (const CXXBaseSpecifier &Base : RD->vbases()) 00675 if (Context.getASTRecordLayout(Base.getType()->getAsCXXRecordDecl()) 00676 .hasExtendableVFPtr()) 00677 return CGF.CGM.getCXXABI().GetVirtualBaseClassOffset( 00678 CGF, Value, RD, Base.getType()->getAsCXXRecordDecl()); 00679 llvm_unreachable("One of our vbases should be polymorphic."); 00680 } 00681 00682 static std::pair<llvm::Value *, llvm::Value *> 00683 performBaseAdjustment(CodeGenFunction &CGF, llvm::Value *Value, 00684 QualType SrcRecordTy) { 00685 Value = CGF.Builder.CreateBitCast(Value, CGF.Int8PtrTy); 00686 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl(); 00687 00688 if (CGF.getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr()) 00689 return std::make_pair(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0)); 00690 00691 // Perform a base adjustment. 00692 llvm::Value *Offset = getPolymorphicOffset(CGF, SrcDecl, Value); 00693 Value = CGF.Builder.CreateInBoundsGEP(Value, Offset); 00694 Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty); 00695 return std::make_pair(Value, Offset); 00696 } 00697 00698 bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref, 00699 QualType SrcRecordTy) { 00700 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl(); 00701 return IsDeref && 00702 !CGM.getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr(); 00703 } 00704 00705 static llvm::CallSite emitRTtypeidCall(CodeGenFunction &CGF, 00706 llvm::Value *Argument) { 00707 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy}; 00708 llvm::FunctionType *FTy = 00709 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false); 00710 llvm::Value *Args[] = {Argument}; 00711 llvm::Constant *Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid"); 00712 return CGF.EmitRuntimeCallOrInvoke(Fn, Args); 00713 } 00714 00715 void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) { 00716 llvm::CallSite Call = 00717 emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy)); 00718 Call.setDoesNotReturn(); 00719 CGF.Builder.CreateUnreachable(); 00720 } 00721 00722 llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF, 00723 QualType SrcRecordTy, 00724 llvm::Value *ThisPtr, 00725 llvm::Type *StdTypeInfoPtrTy) { 00726 llvm::Value *Offset; 00727 std::tie(ThisPtr, Offset) = performBaseAdjustment(CGF, ThisPtr, SrcRecordTy); 00728 return CGF.Builder.CreateBitCast( 00729 emitRTtypeidCall(CGF, ThisPtr).getInstruction(), StdTypeInfoPtrTy); 00730 } 00731 00732 bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr, 00733 QualType SrcRecordTy) { 00734 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl(); 00735 return SrcIsPtr && 00736 !CGM.getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr(); 00737 } 00738 00739 llvm::Value *MicrosoftCXXABI::EmitDynamicCastCall( 00740 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy, 00741 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) { 00742 llvm::Type *DestLTy = CGF.ConvertType(DestTy); 00743 00744 llvm::Value *SrcRTTI = 00745 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType()); 00746 llvm::Value *DestRTTI = 00747 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType()); 00748 00749 llvm::Value *Offset; 00750 std::tie(Value, Offset) = performBaseAdjustment(CGF, Value, SrcRecordTy); 00751 00752 // PVOID __RTDynamicCast( 00753 // PVOID inptr, 00754 // LONG VfDelta, 00755 // PVOID SrcType, 00756 // PVOID TargetType, 00757 // BOOL isReference) 00758 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy, 00759 CGF.Int8PtrTy, CGF.Int32Ty}; 00760 llvm::Constant *Function = CGF.CGM.CreateRuntimeFunction( 00761 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false), 00762 "__RTDynamicCast"); 00763 llvm::Value *Args[] = { 00764 Value, Offset, SrcRTTI, DestRTTI, 00765 llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())}; 00766 Value = CGF.EmitRuntimeCallOrInvoke(Function, Args).getInstruction(); 00767 return CGF.Builder.CreateBitCast(Value, DestLTy); 00768 } 00769 00770 llvm::Value * 00771 MicrosoftCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value, 00772 QualType SrcRecordTy, 00773 QualType DestTy) { 00774 llvm::Value *Offset; 00775 std::tie(Value, Offset) = performBaseAdjustment(CGF, Value, SrcRecordTy); 00776 00777 // PVOID __RTCastToVoid( 00778 // PVOID inptr) 00779 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy}; 00780 llvm::Constant *Function = CGF.CGM.CreateRuntimeFunction( 00781 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false), 00782 "__RTCastToVoid"); 00783 llvm::Value *Args[] = {Value}; 00784 return CGF.EmitRuntimeCall(Function, Args); 00785 } 00786 00787 bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) { 00788 return false; 00789 } 00790 00791 llvm::Value *MicrosoftCXXABI::GetVirtualBaseClassOffset( 00792 CodeGenFunction &CGF, llvm::Value *This, const CXXRecordDecl *ClassDecl, 00793 const CXXRecordDecl *BaseClassDecl) { 00794 int64_t VBPtrChars = 00795 getContext().getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity(); 00796 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars); 00797 CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy); 00798 CharUnits VBTableChars = 00799 IntSize * 00800 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl); 00801 llvm::Value *VBTableOffset = 00802 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity()); 00803 00804 llvm::Value *VBPtrToNewBase = 00805 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset); 00806 VBPtrToNewBase = 00807 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy); 00808 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase); 00809 } 00810 00811 bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const { 00812 return isa<CXXConstructorDecl>(GD.getDecl()); 00813 } 00814 00815 static bool isDeletingDtor(GlobalDecl GD) { 00816 return isa<CXXDestructorDecl>(GD.getDecl()) && 00817 GD.getDtorType() == Dtor_Deleting; 00818 } 00819 00820 bool MicrosoftCXXABI::hasMostDerivedReturn(GlobalDecl GD) const { 00821 return isDeletingDtor(GD); 00822 } 00823 00824 bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const { 00825 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl(); 00826 if (!RD) 00827 return false; 00828 00829 if (FI.isInstanceMethod()) { 00830 // If it's an instance method, aggregates are always returned indirectly via 00831 // the second parameter. 00832 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false); 00833 FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod()); 00834 return true; 00835 } else if (!RD->isPOD()) { 00836 // If it's a free function, non-POD types are returned indirectly. 00837 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false); 00838 return true; 00839 } 00840 00841 // Otherwise, use the C ABI rules. 00842 return false; 00843 } 00844 00845 llvm::BasicBlock * 00846 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF, 00847 const CXXRecordDecl *RD) { 00848 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF); 00849 assert(IsMostDerivedClass && 00850 "ctor for a class with virtual bases must have an implicit parameter"); 00851 llvm::Value *IsCompleteObject = 00852 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object"); 00853 00854 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases"); 00855 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases"); 00856 CGF.Builder.CreateCondBr(IsCompleteObject, 00857 CallVbaseCtorsBB, SkipVbaseCtorsBB); 00858 00859 CGF.EmitBlock(CallVbaseCtorsBB); 00860 00861 // Fill in the vbtable pointers here. 00862 EmitVBPtrStores(CGF, RD); 00863 00864 // CGF will put the base ctor calls in this basic block for us later. 00865 00866 return SkipVbaseCtorsBB; 00867 } 00868 00869 void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers( 00870 CodeGenFunction &CGF, const CXXRecordDecl *RD) { 00871 // In most cases, an override for a vbase virtual method can adjust 00872 // the "this" parameter by applying a constant offset. 00873 // However, this is not enough while a constructor or a destructor of some 00874 // class X is being executed if all the following conditions are met: 00875 // - X has virtual bases, (1) 00876 // - X overrides a virtual method M of a vbase Y, (2) 00877 // - X itself is a vbase of the most derived class. 00878 // 00879 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X 00880 // which holds the extra amount of "this" adjustment we must do when we use 00881 // the X vftables (i.e. during X ctor or dtor). 00882 // Outside the ctors and dtors, the values of vtorDisps are zero. 00883 00884 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 00885 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets; 00886 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap(); 00887 CGBuilderTy &Builder = CGF.Builder; 00888 00889 unsigned AS = 00890 cast<llvm::PointerType>(getThisValue(CGF)->getType())->getAddressSpace(); 00891 llvm::Value *Int8This = nullptr; // Initialize lazily. 00892 00893 for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end(); 00894 I != E; ++I) { 00895 if (!I->second.hasVtorDisp()) 00896 continue; 00897 00898 llvm::Value *VBaseOffset = 00899 GetVirtualBaseClassOffset(CGF, getThisValue(CGF), RD, I->first); 00900 // FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset() 00901 // just to Trunc back immediately. 00902 VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty); 00903 uint64_t ConstantVBaseOffset = 00904 Layout.getVBaseClassOffset(I->first).getQuantity(); 00905 00906 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase). 00907 llvm::Value *VtorDispValue = Builder.CreateSub( 00908 VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset), 00909 "vtordisp.value"); 00910 00911 if (!Int8This) 00912 Int8This = Builder.CreateBitCast(getThisValue(CGF), 00913 CGF.Int8Ty->getPointerTo(AS)); 00914 llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset); 00915 // vtorDisp is always the 32-bits before the vbase in the class layout. 00916 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4); 00917 VtorDispPtr = Builder.CreateBitCast( 00918 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr"); 00919 00920 Builder.CreateStore(VtorDispValue, VtorDispPtr); 00921 } 00922 } 00923 00924 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) { 00925 // There's only one constructor type in this ABI. 00926 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete)); 00927 } 00928 00929 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF, 00930 const CXXRecordDecl *RD) { 00931 llvm::Value *ThisInt8Ptr = 00932 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8"); 00933 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); 00934 00935 const VBTableGlobals &VBGlobals = enumerateVBTables(RD); 00936 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) { 00937 const VPtrInfo *VBT = (*VBGlobals.VBTables)[I]; 00938 llvm::GlobalVariable *GV = VBGlobals.Globals[I]; 00939 const ASTRecordLayout &SubobjectLayout = 00940 CGM.getContext().getASTRecordLayout(VBT->BaseWithVPtr); 00941 CharUnits Offs = VBT->NonVirtualOffset; 00942 Offs += SubobjectLayout.getVBPtrOffset(); 00943 if (VBT->getVBaseWithVPtr()) 00944 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr()); 00945 llvm::Value *VBPtr = 00946 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs.getQuantity()); 00947 llvm::Value *GVPtr = CGF.Builder.CreateConstInBoundsGEP2_32(GV, 0, 0); 00948 VBPtr = CGF.Builder.CreateBitCast(VBPtr, GVPtr->getType()->getPointerTo(0), 00949 "vbptr." + VBT->ReusingBase->getName()); 00950 CGF.Builder.CreateStore(GVPtr, VBPtr); 00951 } 00952 } 00953 00954 void 00955 MicrosoftCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T, 00956 SmallVectorImpl<CanQualType> &ArgTys) { 00957 // TODO: 'for base' flag 00958 if (T == StructorType::Deleting) { 00959 // The scalar deleting destructor takes an implicit int parameter. 00960 ArgTys.push_back(CGM.getContext().IntTy); 00961 } 00962 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 00963 if (!CD) 00964 return; 00965 00966 // All parameters are already in place except is_most_derived, which goes 00967 // after 'this' if it's variadic and last if it's not. 00968 00969 const CXXRecordDecl *Class = CD->getParent(); 00970 const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>(); 00971 if (Class->getNumVBases()) { 00972 if (FPT->isVariadic()) 00973 ArgTys.insert(ArgTys.begin() + 1, CGM.getContext().IntTy); 00974 else 00975 ArgTys.push_back(CGM.getContext().IntTy); 00976 } 00977 } 00978 00979 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) { 00980 // The TU defining a dtor is only guaranteed to emit a base destructor. All 00981 // other destructor variants are delegating thunks. 00982 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base)); 00983 } 00984 00985 CharUnits 00986 MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) { 00987 GD = GD.getCanonicalDecl(); 00988 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 00989 00990 GlobalDecl LookupGD = GD; 00991 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) { 00992 // Complete destructors take a pointer to the complete object as a 00993 // parameter, thus don't need this adjustment. 00994 if (GD.getDtorType() == Dtor_Complete) 00995 return CharUnits(); 00996 00997 // There's no Dtor_Base in vftable but it shares the this adjustment with 00998 // the deleting one, so look it up instead. 00999 LookupGD = GlobalDecl(DD, Dtor_Deleting); 01000 } 01001 01002 MicrosoftVTableContext::MethodVFTableLocation ML = 01003 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD); 01004 CharUnits Adjustment = ML.VFPtrOffset; 01005 01006 // Normal virtual instance methods need to adjust from the vfptr that first 01007 // defined the virtual method to the virtual base subobject, but destructors 01008 // do not. The vector deleting destructor thunk applies this adjustment for 01009 // us if necessary. 01010 if (isa<CXXDestructorDecl>(MD)) 01011 Adjustment = CharUnits::Zero(); 01012 01013 if (ML.VBase) { 01014 const ASTRecordLayout &DerivedLayout = 01015 CGM.getContext().getASTRecordLayout(MD->getParent()); 01016 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase); 01017 } 01018 01019 return Adjustment; 01020 } 01021 01022 llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall( 01023 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This, bool VirtualCall) { 01024 if (!VirtualCall) { 01025 // If the call of a virtual function is not virtual, we just have to 01026 // compensate for the adjustment the virtual function does in its prologue. 01027 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD); 01028 if (Adjustment.isZero()) 01029 return This; 01030 01031 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace(); 01032 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS); 01033 This = CGF.Builder.CreateBitCast(This, charPtrTy); 01034 assert(Adjustment.isPositive()); 01035 return CGF.Builder.CreateConstGEP1_32(This, Adjustment.getQuantity()); 01036 } 01037 01038 GD = GD.getCanonicalDecl(); 01039 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 01040 01041 GlobalDecl LookupGD = GD; 01042 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) { 01043 // Complete dtors take a pointer to the complete object, 01044 // thus don't need adjustment. 01045 if (GD.getDtorType() == Dtor_Complete) 01046 return This; 01047 01048 // There's only Dtor_Deleting in vftable but it shares the this adjustment 01049 // with the base one, so look up the deleting one instead. 01050 LookupGD = GlobalDecl(DD, Dtor_Deleting); 01051 } 01052 MicrosoftVTableContext::MethodVFTableLocation ML = 01053 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD); 01054 01055 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace(); 01056 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS); 01057 CharUnits StaticOffset = ML.VFPtrOffset; 01058 01059 // Base destructors expect 'this' to point to the beginning of the base 01060 // subobject, not the first vfptr that happens to contain the virtual dtor. 01061 // However, we still need to apply the virtual base adjustment. 01062 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) 01063 StaticOffset = CharUnits::Zero(); 01064 01065 if (ML.VBase) { 01066 This = CGF.Builder.CreateBitCast(This, charPtrTy); 01067 llvm::Value *VBaseOffset = 01068 GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase); 01069 This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset); 01070 } 01071 if (!StaticOffset.isZero()) { 01072 assert(StaticOffset.isPositive()); 01073 This = CGF.Builder.CreateBitCast(This, charPtrTy); 01074 if (ML.VBase) { 01075 // Non-virtual adjustment might result in a pointer outside the allocated 01076 // object, e.g. if the final overrider class is laid out after the virtual 01077 // base that declares a method in the most derived class. 01078 // FIXME: Update the code that emits this adjustment in thunks prologues. 01079 This = CGF.Builder.CreateConstGEP1_32(This, StaticOffset.getQuantity()); 01080 } else { 01081 This = CGF.Builder.CreateConstInBoundsGEP1_32(This, 01082 StaticOffset.getQuantity()); 01083 } 01084 } 01085 return This; 01086 } 01087 01088 void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF, 01089 QualType &ResTy, 01090 FunctionArgList &Params) { 01091 ASTContext &Context = getContext(); 01092 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 01093 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)); 01094 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) { 01095 ImplicitParamDecl *IsMostDerived 01096 = ImplicitParamDecl::Create(Context, nullptr, 01097 CGF.CurGD.getDecl()->getLocation(), 01098 &Context.Idents.get("is_most_derived"), 01099 Context.IntTy); 01100 // The 'most_derived' parameter goes second if the ctor is variadic and last 01101 // if it's not. Dtors can't be variadic. 01102 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 01103 if (FPT->isVariadic()) 01104 Params.insert(Params.begin() + 1, IsMostDerived); 01105 else 01106 Params.push_back(IsMostDerived); 01107 getStructorImplicitParamDecl(CGF) = IsMostDerived; 01108 } else if (isDeletingDtor(CGF.CurGD)) { 01109 ImplicitParamDecl *ShouldDelete 01110 = ImplicitParamDecl::Create(Context, nullptr, 01111 CGF.CurGD.getDecl()->getLocation(), 01112 &Context.Idents.get("should_call_delete"), 01113 Context.IntTy); 01114 Params.push_back(ShouldDelete); 01115 getStructorImplicitParamDecl(CGF) = ShouldDelete; 01116 } 01117 } 01118 01119 llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue( 01120 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) { 01121 // In this ABI, every virtual function takes a pointer to one of the 01122 // subobjects that first defines it as the 'this' parameter, rather than a 01123 // pointer to the final overrider subobject. Thus, we need to adjust it back 01124 // to the final overrider subobject before use. 01125 // See comments in the MicrosoftVFTableContext implementation for the details. 01126 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD); 01127 if (Adjustment.isZero()) 01128 return This; 01129 01130 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace(); 01131 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS), 01132 *thisTy = This->getType(); 01133 01134 This = CGF.Builder.CreateBitCast(This, charPtrTy); 01135 assert(Adjustment.isPositive()); 01136 This = 01137 CGF.Builder.CreateConstInBoundsGEP1_32(This, -Adjustment.getQuantity()); 01138 return CGF.Builder.CreateBitCast(This, thisTy); 01139 } 01140 01141 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) { 01142 EmitThisParam(CGF); 01143 01144 /// If this is a function that the ABI specifies returns 'this', initialize 01145 /// the return slot to 'this' at the start of the function. 01146 /// 01147 /// Unlike the setting of return types, this is done within the ABI 01148 /// implementation instead of by clients of CGCXXABI because: 01149 /// 1) getThisValue is currently protected 01150 /// 2) in theory, an ABI could implement 'this' returns some other way; 01151 /// HasThisReturn only specifies a contract, not the implementation 01152 if (HasThisReturn(CGF.CurGD)) 01153 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue); 01154 else if (hasMostDerivedReturn(CGF.CurGD)) 01155 CGF.Builder.CreateStore(CGF.EmitCastToVoidPtr(getThisValue(CGF)), 01156 CGF.ReturnValue); 01157 01158 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 01159 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) { 01160 assert(getStructorImplicitParamDecl(CGF) && 01161 "no implicit parameter for a constructor with virtual bases?"); 01162 getStructorImplicitParamValue(CGF) 01163 = CGF.Builder.CreateLoad( 01164 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), 01165 "is_most_derived"); 01166 } 01167 01168 if (isDeletingDtor(CGF.CurGD)) { 01169 assert(getStructorImplicitParamDecl(CGF) && 01170 "no implicit parameter for a deleting destructor?"); 01171 getStructorImplicitParamValue(CGF) 01172 = CGF.Builder.CreateLoad( 01173 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), 01174 "should_call_delete"); 01175 } 01176 } 01177 01178 unsigned MicrosoftCXXABI::addImplicitConstructorArgs( 01179 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type, 01180 bool ForVirtualBase, bool Delegating, CallArgList &Args) { 01181 assert(Type == Ctor_Complete || Type == Ctor_Base); 01182 01183 // Check if we need a 'most_derived' parameter. 01184 if (!D->getParent()->getNumVBases()) 01185 return 0; 01186 01187 // Add the 'most_derived' argument second if we are variadic or last if not. 01188 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>(); 01189 llvm::Value *MostDerivedArg = 01190 llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete); 01191 RValue RV = RValue::get(MostDerivedArg); 01192 if (MostDerivedArg) { 01193 if (FPT->isVariadic()) 01194 Args.insert(Args.begin() + 1, 01195 CallArg(RV, getContext().IntTy, /*needscopy=*/false)); 01196 else 01197 Args.add(RV, getContext().IntTy); 01198 } 01199 01200 return 1; // Added one arg. 01201 } 01202 01203 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF, 01204 const CXXDestructorDecl *DD, 01205 CXXDtorType Type, bool ForVirtualBase, 01206 bool Delegating, llvm::Value *This) { 01207 llvm::Value *Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)); 01208 01209 if (DD->isVirtual()) { 01210 assert(Type != CXXDtorType::Dtor_Deleting && 01211 "The deleting destructor should only be called via a virtual call"); 01212 This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type), 01213 This, false); 01214 } 01215 01216 CGF.EmitCXXStructorCall(DD, Callee, ReturnValueSlot(), This, 01217 /*ImplicitParam=*/nullptr, 01218 /*ImplicitParamTy=*/QualType(), nullptr, 01219 getFromDtorType(Type)); 01220 } 01221 01222 void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT, 01223 const CXXRecordDecl *RD) { 01224 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext(); 01225 const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD); 01226 01227 for (VPtrInfo *Info : VFPtrs) { 01228 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC); 01229 if (VTable->hasInitializer()) 01230 continue; 01231 01232 llvm::Constant *RTTI = getContext().getLangOpts().RTTIData 01233 ? getMSCompleteObjectLocator(RD, Info) 01234 : nullptr; 01235 01236 const VTableLayout &VTLayout = 01237 VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC); 01238 llvm::Constant *Init = CGVT.CreateVTableInitializer( 01239 RD, VTLayout.vtable_component_begin(), 01240 VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(), 01241 VTLayout.getNumVTableThunks(), RTTI); 01242 01243 VTable->setInitializer(Init); 01244 } 01245 } 01246 01247 llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor( 01248 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base, 01249 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) { 01250 NeedsVirtualOffset = (NearestVBase != nullptr); 01251 01252 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset()); 01253 VFTableIdTy ID(VTableClass, Base.getBaseOffset()); 01254 llvm::GlobalValue *VTableAddressPoint = VFTablesMap[ID]; 01255 if (!VTableAddressPoint) { 01256 assert(Base.getBase()->getNumVBases() && 01257 !CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr()); 01258 } 01259 return VTableAddressPoint; 01260 } 01261 01262 static void mangleVFTableName(MicrosoftMangleContext &MangleContext, 01263 const CXXRecordDecl *RD, const VPtrInfo *VFPtr, 01264 SmallString<256> &Name) { 01265 llvm::raw_svector_ostream Out(Name); 01266 MangleContext.mangleCXXVFTable(RD, VFPtr->MangledPath, Out); 01267 } 01268 01269 llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr( 01270 BaseSubobject Base, const CXXRecordDecl *VTableClass) { 01271 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset()); 01272 VFTableIdTy ID(VTableClass, Base.getBaseOffset()); 01273 llvm::GlobalValue *VFTable = VFTablesMap[ID]; 01274 assert(VFTable && "Couldn't find a vftable for the given base?"); 01275 return VFTable; 01276 } 01277 01278 llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD, 01279 CharUnits VPtrOffset) { 01280 // getAddrOfVTable may return 0 if asked to get an address of a vtable which 01281 // shouldn't be used in the given record type. We want to cache this result in 01282 // VFTablesMap, thus a simple zero check is not sufficient. 01283 VFTableIdTy ID(RD, VPtrOffset); 01284 VTablesMapTy::iterator I; 01285 bool Inserted; 01286 std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr)); 01287 if (!Inserted) 01288 return I->second; 01289 01290 llvm::GlobalVariable *&VTable = I->second; 01291 01292 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext(); 01293 const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD); 01294 01295 if (DeferredVFTables.insert(RD)) { 01296 // We haven't processed this record type before. 01297 // Queue up this v-table for possible deferred emission. 01298 CGM.addDeferredVTable(RD); 01299 01300 #ifndef NDEBUG 01301 // Create all the vftables at once in order to make sure each vftable has 01302 // a unique mangled name. 01303 llvm::StringSet<> ObservedMangledNames; 01304 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) { 01305 SmallString<256> Name; 01306 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name); 01307 if (!ObservedMangledNames.insert(Name.str())) 01308 llvm_unreachable("Already saw this mangling before?"); 01309 } 01310 #endif 01311 } 01312 01313 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) { 01314 if (VFPtrs[J]->FullOffsetInMDC != VPtrOffset) 01315 continue; 01316 SmallString<256> VFTableName; 01317 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], VFTableName); 01318 StringRef VTableName = VFTableName; 01319 01320 uint64_t NumVTableSlots = 01321 VTContext.getVFTableLayout(RD, VFPtrs[J]->FullOffsetInMDC) 01322 .getNumVTableComponents(); 01323 llvm::GlobalValue::LinkageTypes VTableLinkage = 01324 llvm::GlobalValue::ExternalLinkage; 01325 llvm::ArrayType *VTableType = 01326 llvm::ArrayType::get(CGM.Int8PtrTy, NumVTableSlots); 01327 if (getContext().getLangOpts().RTTIData) { 01328 VTableLinkage = llvm::GlobalValue::PrivateLinkage; 01329 VTableName = ""; 01330 } 01331 01332 VTable = CGM.getModule().getNamedGlobal(VFTableName); 01333 if (!VTable) { 01334 // Create a backing variable for the contents of VTable. The VTable may 01335 // or may not include space for a pointer to RTTI data. 01336 llvm::GlobalValue *VFTable = VTable = new llvm::GlobalVariable( 01337 CGM.getModule(), VTableType, /*isConstant=*/true, VTableLinkage, 01338 /*Initializer=*/nullptr, VTableName); 01339 VTable->setUnnamedAddr(true); 01340 01341 // Only insert a pointer into the VFTable for RTTI data if we are not 01342 // importing it. We never reference the RTTI data directly so there is no 01343 // need to make room for it. 01344 if (getContext().getLangOpts().RTTIData && 01345 !RD->hasAttr<DLLImportAttr>()) { 01346 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0), 01347 llvm::ConstantInt::get(CGM.IntTy, 1)}; 01348 // Create a GEP which points just after the first entry in the VFTable, 01349 // this should be the location of the first virtual method. 01350 llvm::Constant *VTableGEP = 01351 llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, GEPIndices); 01352 // The symbol for the VFTable is an alias to the GEP. It is 01353 // transparent, to other modules, what the nature of this symbol is; all 01354 // that matters is that the alias be the address of the first virtual 01355 // method. 01356 VFTable = llvm::GlobalAlias::create( 01357 cast<llvm::SequentialType>(VTableGEP->getType())->getElementType(), 01358 /*AddressSpace=*/0, llvm::GlobalValue::ExternalLinkage, 01359 VFTableName.str(), VTableGEP, &CGM.getModule()); 01360 } else { 01361 // We don't need a GlobalAlias to be a symbol for the VTable if we won't 01362 // be referencing any RTTI data. The GlobalVariable will end up being 01363 // an appropriate definition of the VFTable. 01364 VTable->setName(VFTableName.str()); 01365 } 01366 01367 VFTable->setUnnamedAddr(true); 01368 if (RD->hasAttr<DLLImportAttr>()) 01369 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 01370 else if (RD->hasAttr<DLLExportAttr>()) 01371 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 01372 01373 llvm::GlobalValue::LinkageTypes VFTableLinkage = CGM.getVTableLinkage(RD); 01374 if (VFTable != VTable) { 01375 if (llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage)) { 01376 // AvailableExternally implies that we grabbed the data from another 01377 // executable. No need to stick the alias in a Comdat. 01378 } else if (llvm::GlobalValue::isInternalLinkage(VFTableLinkage) || 01379 llvm::GlobalValue::isWeakODRLinkage(VFTableLinkage) || 01380 llvm::GlobalValue::isLinkOnceODRLinkage(VFTableLinkage)) { 01381 // The alias is going to be dropped into a Comdat, no need to make it 01382 // weak. 01383 if (!llvm::GlobalValue::isInternalLinkage(VFTableLinkage)) 01384 VFTableLinkage = llvm::GlobalValue::ExternalLinkage; 01385 llvm::Comdat *C = 01386 CGM.getModule().getOrInsertComdat(VFTable->getName()); 01387 // We must indicate which VFTable is larger to support linking between 01388 // translation units which do and do not have RTTI data. The largest 01389 // VFTable contains the RTTI data; translation units which reference 01390 // the smaller VFTable always reference it relative to the first 01391 // virtual method. 01392 C->setSelectionKind(llvm::Comdat::Largest); 01393 VTable->setComdat(C); 01394 } else { 01395 llvm_unreachable("unexpected linkage for vftable!"); 01396 } 01397 } 01398 VFTable->setLinkage(VFTableLinkage); 01399 CGM.setGlobalVisibility(VFTable, RD); 01400 VFTablesMap[ID] = VFTable; 01401 } 01402 break; 01403 } 01404 01405 return VTable; 01406 } 01407 01408 llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF, 01409 GlobalDecl GD, 01410 llvm::Value *This, 01411 llvm::Type *Ty) { 01412 GD = GD.getCanonicalDecl(); 01413 CGBuilderTy &Builder = CGF.Builder; 01414 01415 Ty = Ty->getPointerTo()->getPointerTo(); 01416 llvm::Value *VPtr = 01417 adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true); 01418 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty); 01419 01420 MicrosoftVTableContext::MethodVFTableLocation ML = 01421 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD); 01422 llvm::Value *VFuncPtr = 01423 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn"); 01424 return Builder.CreateLoad(VFuncPtr); 01425 } 01426 01427 llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall( 01428 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType, 01429 llvm::Value *This, const CXXMemberCallExpr *CE) { 01430 assert(CE == nullptr || CE->arg_begin() == CE->arg_end()); 01431 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete); 01432 01433 // We have only one destructor in the vftable but can get both behaviors 01434 // by passing an implicit int parameter. 01435 GlobalDecl GD(Dtor, Dtor_Deleting); 01436 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration( 01437 Dtor, StructorType::Deleting); 01438 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo); 01439 llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty); 01440 01441 ASTContext &Context = CGF.getContext(); 01442 llvm::Value *ImplicitParam = 01443 llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()), 01444 DtorType == Dtor_Deleting); 01445 01446 This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true); 01447 RValue RV = CGF.EmitCXXStructorCall(Dtor, Callee, ReturnValueSlot(), This, 01448 ImplicitParam, Context.IntTy, CE, 01449 StructorType::Deleting); 01450 return RV.getScalarVal(); 01451 } 01452 01453 const VBTableGlobals & 01454 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) { 01455 // At this layer, we can key the cache off of a single class, which is much 01456 // easier than caching each vbtable individually. 01457 llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry; 01458 bool Added; 01459 std::tie(Entry, Added) = 01460 VBTablesMap.insert(std::make_pair(RD, VBTableGlobals())); 01461 VBTableGlobals &VBGlobals = Entry->second; 01462 if (!Added) 01463 return VBGlobals; 01464 01465 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext(); 01466 VBGlobals.VBTables = &Context.enumerateVBTables(RD); 01467 01468 // Cache the globals for all vbtables so we don't have to recompute the 01469 // mangled names. 01470 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD); 01471 for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(), 01472 E = VBGlobals.VBTables->end(); 01473 I != E; ++I) { 01474 VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage)); 01475 } 01476 01477 return VBGlobals; 01478 } 01479 01480 llvm::Function *MicrosoftCXXABI::EmitVirtualMemPtrThunk( 01481 const CXXMethodDecl *MD, 01482 const MicrosoftVTableContext::MethodVFTableLocation &ML) { 01483 assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) && 01484 "can't form pointers to ctors or virtual dtors"); 01485 01486 // Calculate the mangled name. 01487 SmallString<256> ThunkName; 01488 llvm::raw_svector_ostream Out(ThunkName); 01489 getMangleContext().mangleVirtualMemPtrThunk(MD, Out); 01490 Out.flush(); 01491 01492 // If the thunk has been generated previously, just return it. 01493 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName)) 01494 return cast<llvm::Function>(GV); 01495 01496 // Create the llvm::Function. 01497 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSMemberPointerThunk(MD); 01498 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo); 01499 llvm::Function *ThunkFn = 01500 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage, 01501 ThunkName.str(), &CGM.getModule()); 01502 assert(ThunkFn->getName() == ThunkName && "name was uniqued!"); 01503 01504 ThunkFn->setLinkage(MD->isExternallyVisible() 01505 ? llvm::GlobalValue::LinkOnceODRLinkage 01506 : llvm::GlobalValue::InternalLinkage); 01507 01508 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn); 01509 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn); 01510 01511 // These thunks can be compared, so they are not unnamed. 01512 ThunkFn->setUnnamedAddr(false); 01513 01514 // Start codegen. 01515 CodeGenFunction CGF(CGM); 01516 CGF.CurGD = GlobalDecl(MD); 01517 CGF.CurFuncIsThunk = true; 01518 01519 // Build FunctionArgs, but only include the implicit 'this' parameter 01520 // declaration. 01521 FunctionArgList FunctionArgs; 01522 buildThisParam(CGF, FunctionArgs); 01523 01524 // Start defining the function. 01525 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo, 01526 FunctionArgs, MD->getLocation(), SourceLocation()); 01527 EmitThisParam(CGF); 01528 01529 // Load the vfptr and then callee from the vftable. The callee should have 01530 // adjusted 'this' so that the vfptr is at offset zero. 01531 llvm::Value *VTable = CGF.GetVTablePtr( 01532 getThisValue(CGF), ThunkTy->getPointerTo()->getPointerTo()); 01533 llvm::Value *VFuncPtr = 01534 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn"); 01535 llvm::Value *Callee = CGF.Builder.CreateLoad(VFuncPtr); 01536 01537 CGF.EmitMustTailThunk(MD, getThisValue(CGF), Callee); 01538 01539 return ThunkFn; 01540 } 01541 01542 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) { 01543 const VBTableGlobals &VBGlobals = enumerateVBTables(RD); 01544 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) { 01545 const VPtrInfo *VBT = (*VBGlobals.VBTables)[I]; 01546 llvm::GlobalVariable *GV = VBGlobals.Globals[I]; 01547 emitVBTableDefinition(*VBT, RD, GV); 01548 } 01549 } 01550 01551 llvm::GlobalVariable * 01552 MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD, 01553 llvm::GlobalVariable::LinkageTypes Linkage) { 01554 SmallString<256> OutName; 01555 llvm::raw_svector_ostream Out(OutName); 01556 getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out); 01557 Out.flush(); 01558 StringRef Name = OutName.str(); 01559 01560 llvm::ArrayType *VBTableType = 01561 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ReusingBase->getNumVBases()); 01562 01563 assert(!CGM.getModule().getNamedGlobal(Name) && 01564 "vbtable with this name already exists: mangling bug?"); 01565 llvm::GlobalVariable *GV = 01566 CGM.CreateOrReplaceCXXRuntimeVariable(Name, VBTableType, Linkage); 01567 GV->setUnnamedAddr(true); 01568 01569 if (RD->hasAttr<DLLImportAttr>()) 01570 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 01571 else if (RD->hasAttr<DLLExportAttr>()) 01572 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 01573 01574 return GV; 01575 } 01576 01577 void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT, 01578 const CXXRecordDecl *RD, 01579 llvm::GlobalVariable *GV) const { 01580 const CXXRecordDecl *ReusingBase = VBT.ReusingBase; 01581 01582 assert(RD->getNumVBases() && ReusingBase->getNumVBases() && 01583 "should only emit vbtables for classes with vbtables"); 01584 01585 const ASTRecordLayout &BaseLayout = 01586 CGM.getContext().getASTRecordLayout(VBT.BaseWithVPtr); 01587 const ASTRecordLayout &DerivedLayout = 01588 CGM.getContext().getASTRecordLayout(RD); 01589 01590 SmallVector<llvm::Constant *, 4> Offsets(1 + ReusingBase->getNumVBases(), 01591 nullptr); 01592 01593 // The offset from ReusingBase's vbptr to itself always leads. 01594 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset(); 01595 Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity()); 01596 01597 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext(); 01598 for (const auto &I : ReusingBase->vbases()) { 01599 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl(); 01600 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase); 01601 assert(!Offset.isNegative()); 01602 01603 // Make it relative to the subobject vbptr. 01604 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset; 01605 if (VBT.getVBaseWithVPtr()) 01606 CompleteVBPtrOffset += 01607 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr()); 01608 Offset -= CompleteVBPtrOffset; 01609 01610 unsigned VBIndex = Context.getVBTableIndex(ReusingBase, VBase); 01611 assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?"); 01612 Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity()); 01613 } 01614 01615 assert(Offsets.size() == 01616 cast<llvm::ArrayType>(cast<llvm::PointerType>(GV->getType()) 01617 ->getElementType())->getNumElements()); 01618 llvm::ArrayType *VBTableType = 01619 llvm::ArrayType::get(CGM.IntTy, Offsets.size()); 01620 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets); 01621 GV->setInitializer(Init); 01622 01623 // Set the right visibility. 01624 CGM.setGlobalVisibility(GV, RD); 01625 } 01626 01627 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF, 01628 llvm::Value *This, 01629 const ThisAdjustment &TA) { 01630 if (TA.isEmpty()) 01631 return This; 01632 01633 llvm::Value *V = CGF.Builder.CreateBitCast(This, CGF.Int8PtrTy); 01634 01635 if (!TA.Virtual.isEmpty()) { 01636 assert(TA.Virtual.Microsoft.VtordispOffset < 0); 01637 // Adjust the this argument based on the vtordisp value. 01638 llvm::Value *VtorDispPtr = 01639 CGF.Builder.CreateConstGEP1_32(V, TA.Virtual.Microsoft.VtordispOffset); 01640 VtorDispPtr = 01641 CGF.Builder.CreateBitCast(VtorDispPtr, CGF.Int32Ty->getPointerTo()); 01642 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp"); 01643 V = CGF.Builder.CreateGEP(V, CGF.Builder.CreateNeg(VtorDisp)); 01644 01645 if (TA.Virtual.Microsoft.VBPtrOffset) { 01646 // If the final overrider is defined in a virtual base other than the one 01647 // that holds the vfptr, we have to use a vtordispex thunk which looks up 01648 // the vbtable of the derived class. 01649 assert(TA.Virtual.Microsoft.VBPtrOffset > 0); 01650 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0); 01651 llvm::Value *VBPtr; 01652 llvm::Value *VBaseOffset = 01653 GetVBaseOffsetFromVBPtr(CGF, V, -TA.Virtual.Microsoft.VBPtrOffset, 01654 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr); 01655 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset); 01656 } 01657 } 01658 01659 if (TA.NonVirtual) { 01660 // Non-virtual adjustment might result in a pointer outside the allocated 01661 // object, e.g. if the final overrider class is laid out after the virtual 01662 // base that declares a method in the most derived class. 01663 V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual); 01664 } 01665 01666 // Don't need to bitcast back, the call CodeGen will handle this. 01667 return V; 01668 } 01669 01670 llvm::Value * 01671 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret, 01672 const ReturnAdjustment &RA) { 01673 if (RA.isEmpty()) 01674 return Ret; 01675 01676 llvm::Value *V = CGF.Builder.CreateBitCast(Ret, CGF.Int8PtrTy); 01677 01678 if (RA.Virtual.Microsoft.VBIndex) { 01679 assert(RA.Virtual.Microsoft.VBIndex > 0); 01680 int32_t IntSize = 01681 getContext().getTypeSizeInChars(getContext().IntTy).getQuantity(); 01682 llvm::Value *VBPtr; 01683 llvm::Value *VBaseOffset = 01684 GetVBaseOffsetFromVBPtr(CGF, V, RA.Virtual.Microsoft.VBPtrOffset, 01685 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr); 01686 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset); 01687 } 01688 01689 if (RA.NonVirtual) 01690 V = CGF.Builder.CreateConstInBoundsGEP1_32(V, RA.NonVirtual); 01691 01692 // Cast back to the original type. 01693 return CGF.Builder.CreateBitCast(V, Ret->getType()); 01694 } 01695 01696 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr, 01697 QualType elementType) { 01698 // Microsoft seems to completely ignore the possibility of a 01699 // two-argument usual deallocation function. 01700 return elementType.isDestructedType(); 01701 } 01702 01703 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) { 01704 // Microsoft seems to completely ignore the possibility of a 01705 // two-argument usual deallocation function. 01706 return expr->getAllocatedType().isDestructedType(); 01707 } 01708 01709 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) { 01710 // The array cookie is always a size_t; we then pad that out to the 01711 // alignment of the element type. 01712 ASTContext &Ctx = getContext(); 01713 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()), 01714 Ctx.getTypeAlignInChars(type)); 01715 } 01716 01717 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, 01718 llvm::Value *allocPtr, 01719 CharUnits cookieSize) { 01720 unsigned AS = allocPtr->getType()->getPointerAddressSpace(); 01721 llvm::Value *numElementsPtr = 01722 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS)); 01723 return CGF.Builder.CreateLoad(numElementsPtr); 01724 } 01725 01726 llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 01727 llvm::Value *newPtr, 01728 llvm::Value *numElements, 01729 const CXXNewExpr *expr, 01730 QualType elementType) { 01731 assert(requiresArrayCookie(expr)); 01732 01733 // The size of the cookie. 01734 CharUnits cookieSize = getArrayCookieSizeImpl(elementType); 01735 01736 // Compute an offset to the cookie. 01737 llvm::Value *cookiePtr = newPtr; 01738 01739 // Write the number of elements into the appropriate slot. 01740 unsigned AS = newPtr->getType()->getPointerAddressSpace(); 01741 llvm::Value *numElementsPtr 01742 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS)); 01743 CGF.Builder.CreateStore(numElements, numElementsPtr); 01744 01745 // Finally, compute a pointer to the actual data buffer by skipping 01746 // over the cookie completely. 01747 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr, 01748 cookieSize.getQuantity()); 01749 } 01750 01751 static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD, 01752 llvm::Constant *Dtor, 01753 llvm::Constant *Addr) { 01754 // Create a function which calls the destructor. 01755 llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr); 01756 01757 // extern "C" int __tlregdtor(void (*f)(void)); 01758 llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get( 01759 CGF.IntTy, DtorStub->getType(), /*IsVarArg=*/false); 01760 01761 llvm::Constant *TLRegDtor = 01762 CGF.CGM.CreateRuntimeFunction(TLRegDtorTy, "__tlregdtor"); 01763 if (llvm::Function *TLRegDtorFn = dyn_cast<llvm::Function>(TLRegDtor)) 01764 TLRegDtorFn->setDoesNotThrow(); 01765 01766 CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub); 01767 } 01768 01769 void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D, 01770 llvm::Constant *Dtor, 01771 llvm::Constant *Addr) { 01772 if (D.getTLSKind()) 01773 return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr); 01774 01775 // The default behavior is to use atexit. 01776 CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr); 01777 } 01778 01779 void MicrosoftCXXABI::EmitThreadLocalInitFuncs( 01780 CodeGenModule &CGM, 01781 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>> 01782 CXXThreadLocals, 01783 ArrayRef<llvm::Function *> CXXThreadLocalInits, 01784 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) { 01785 // This will create a GV in the .CRT$XDU section. It will point to our 01786 // initialization function. The CRT will call all of these function 01787 // pointers at start-up time and, eventually, at thread-creation time. 01788 auto AddToXDU = [&CGM](llvm::Function *InitFunc) { 01789 llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable( 01790 CGM.getModule(), InitFunc->getType(), /*IsConstant=*/true, 01791 llvm::GlobalVariable::InternalLinkage, InitFunc, 01792 Twine(InitFunc->getName(), "$initializer$")); 01793 InitFuncPtr->setSection(".CRT$XDU"); 01794 // This variable has discardable linkage, we have to add it to @llvm.used to 01795 // ensure it won't get discarded. 01796 CGM.addUsedGlobal(InitFuncPtr); 01797 return InitFuncPtr; 01798 }; 01799 01800 std::vector<llvm::Function *> NonComdatInits; 01801 for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; ++I) { 01802 llvm::GlobalVariable *GV = CXXThreadLocalInitVars[I]; 01803 llvm::Function *F = CXXThreadLocalInits[I]; 01804 01805 // If the GV is already in a comdat group, then we have to join it. 01806 llvm::Comdat *C = GV->getComdat(); 01807 01808 // LinkOnce and Weak linkage are lowered down to a single-member comdat 01809 // group. 01810 // Make an explicit group so we can join it. 01811 if (!C && (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage())) { 01812 C = CGM.getModule().getOrInsertComdat(GV->getName()); 01813 GV->setComdat(C); 01814 AddToXDU(F)->setComdat(C); 01815 } else { 01816 NonComdatInits.push_back(F); 01817 } 01818 } 01819 01820 if (!NonComdatInits.empty()) { 01821 llvm::FunctionType *FTy = 01822 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false); 01823 llvm::Function *InitFunc = CGM.CreateGlobalInitOrDestructFunction( 01824 FTy, "__tls_init", SourceLocation(), 01825 /*TLS=*/true); 01826 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits); 01827 01828 AddToXDU(InitFunc); 01829 } 01830 } 01831 01832 LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, 01833 const VarDecl *VD, 01834 QualType LValType) { 01835 CGF.CGM.ErrorUnsupported(VD, "thread wrappers"); 01836 return LValue(); 01837 } 01838 01839 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, 01840 llvm::GlobalVariable *GV, 01841 bool PerformInit) { 01842 // MSVC only uses guards for static locals. 01843 if (!D.isStaticLocal()) { 01844 assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage()); 01845 // GlobalOpt is allowed to discard the initializer, so use linkonce_odr. 01846 CGF.CurFn->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage); 01847 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit); 01848 return; 01849 } 01850 01851 // MSVC always uses an i32 bitfield to guard initialization, which is *not* 01852 // threadsafe. Since the user may be linking in inline functions compiled by 01853 // cl.exe, there's no reason to provide a false sense of security by using 01854 // critical sections here. 01855 01856 if (D.getTLSKind()) 01857 CGM.ErrorUnsupported(&D, "dynamic TLS initialization"); 01858 01859 CGBuilderTy &Builder = CGF.Builder; 01860 llvm::IntegerType *GuardTy = CGF.Int32Ty; 01861 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0); 01862 01863 // Get the guard variable for this function if we have one already. 01864 GuardInfo *GI = &GuardVariableMap[D.getDeclContext()]; 01865 01866 unsigned BitIndex; 01867 if (D.isStaticLocal() && D.isExternallyVisible()) { 01868 // Externally visible variables have to be numbered in Sema to properly 01869 // handle unreachable VarDecls. 01870 BitIndex = getContext().getStaticLocalNumber(&D); 01871 assert(BitIndex > 0); 01872 BitIndex--; 01873 } else { 01874 // Non-externally visible variables are numbered here in CodeGen. 01875 BitIndex = GI->BitIndex++; 01876 } 01877 01878 if (BitIndex >= 32) { 01879 if (D.isExternallyVisible()) 01880 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations"); 01881 BitIndex %= 32; 01882 GI->Guard = nullptr; 01883 } 01884 01885 // Lazily create the i32 bitfield for this function. 01886 if (!GI->Guard) { 01887 // Mangle the name for the guard. 01888 SmallString<256> GuardName; 01889 { 01890 llvm::raw_svector_ostream Out(GuardName); 01891 getMangleContext().mangleStaticGuardVariable(&D, Out); 01892 Out.flush(); 01893 } 01894 01895 // Create the guard variable with a zero-initializer. Just absorb linkage, 01896 // visibility and dll storage class from the guarded variable. 01897 GI->Guard = 01898 new llvm::GlobalVariable(CGM.getModule(), GuardTy, false, 01899 GV->getLinkage(), Zero, GuardName.str()); 01900 GI->Guard->setVisibility(GV->getVisibility()); 01901 GI->Guard->setDLLStorageClass(GV->getDLLStorageClass()); 01902 } else { 01903 assert(GI->Guard->getLinkage() == GV->getLinkage() && 01904 "static local from the same function had different linkage"); 01905 } 01906 01907 // Pseudo code for the test: 01908 // if (!(GuardVar & MyGuardBit)) { 01909 // GuardVar |= MyGuardBit; 01910 // ... initialize the object ...; 01911 // } 01912 01913 // Test our bit from the guard variable. 01914 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex); 01915 llvm::LoadInst *LI = Builder.CreateLoad(GI->Guard); 01916 llvm::Value *IsInitialized = 01917 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero); 01918 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init"); 01919 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end"); 01920 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock); 01921 01922 // Set our bit in the guard variable and emit the initializer and add a global 01923 // destructor if appropriate. 01924 CGF.EmitBlock(InitBlock); 01925 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI->Guard); 01926 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit); 01927 Builder.CreateBr(EndBlock); 01928 01929 // Continue. 01930 CGF.EmitBlock(EndBlock); 01931 } 01932 01933 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) { 01934 // Null-ness for function memptrs only depends on the first field, which is 01935 // the function pointer. The rest don't matter, so we can zero initialize. 01936 if (MPT->isMemberFunctionPointer()) 01937 return true; 01938 01939 // The virtual base adjustment field is always -1 for null, so if we have one 01940 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a 01941 // valid field offset. 01942 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 01943 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 01944 return (!MSInheritanceAttr::hasVBTableOffsetField(Inheritance) && 01945 RD->nullFieldOffsetIsZero()); 01946 } 01947 01948 llvm::Type * 01949 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) { 01950 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 01951 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 01952 llvm::SmallVector<llvm::Type *, 4> fields; 01953 if (MPT->isMemberFunctionPointer()) 01954 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk 01955 else 01956 fields.push_back(CGM.IntTy); // FieldOffset 01957 01958 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(), 01959 Inheritance)) 01960 fields.push_back(CGM.IntTy); 01961 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) 01962 fields.push_back(CGM.IntTy); 01963 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 01964 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset 01965 01966 if (fields.size() == 1) 01967 return fields[0]; 01968 return llvm::StructType::get(CGM.getLLVMContext(), fields); 01969 } 01970 01971 void MicrosoftCXXABI:: 01972 GetNullMemberPointerFields(const MemberPointerType *MPT, 01973 llvm::SmallVectorImpl<llvm::Constant *> &fields) { 01974 assert(fields.empty()); 01975 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 01976 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 01977 if (MPT->isMemberFunctionPointer()) { 01978 // FunctionPointerOrVirtualThunk 01979 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy)); 01980 } else { 01981 if (RD->nullFieldOffsetIsZero()) 01982 fields.push_back(getZeroInt()); // FieldOffset 01983 else 01984 fields.push_back(getAllOnesInt()); // FieldOffset 01985 } 01986 01987 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(), 01988 Inheritance)) 01989 fields.push_back(getZeroInt()); 01990 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) 01991 fields.push_back(getZeroInt()); 01992 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 01993 fields.push_back(getAllOnesInt()); 01994 } 01995 01996 llvm::Constant * 01997 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) { 01998 llvm::SmallVector<llvm::Constant *, 4> fields; 01999 GetNullMemberPointerFields(MPT, fields); 02000 if (fields.size() == 1) 02001 return fields[0]; 02002 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields); 02003 assert(Res->getType() == ConvertMemberPointerType(MPT)); 02004 return Res; 02005 } 02006 02007 llvm::Constant * 02008 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField, 02009 bool IsMemberFunction, 02010 const CXXRecordDecl *RD, 02011 CharUnits NonVirtualBaseAdjustment) 02012 { 02013 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 02014 02015 // Single inheritance class member pointer are represented as scalars instead 02016 // of aggregates. 02017 if (MSInheritanceAttr::hasOnlyOneField(IsMemberFunction, Inheritance)) 02018 return FirstField; 02019 02020 llvm::SmallVector<llvm::Constant *, 4> fields; 02021 fields.push_back(FirstField); 02022 02023 if (MSInheritanceAttr::hasNVOffsetField(IsMemberFunction, Inheritance)) 02024 fields.push_back(llvm::ConstantInt::get( 02025 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity())); 02026 02027 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) { 02028 CharUnits Offs = CharUnits::Zero(); 02029 if (RD->getNumVBases()) 02030 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset(); 02031 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity())); 02032 } 02033 02034 // The rest of the fields are adjusted by conversions to a more derived class. 02035 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 02036 fields.push_back(getZeroInt()); 02037 02038 return llvm::ConstantStruct::getAnon(fields); 02039 } 02040 02041 llvm::Constant * 02042 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT, 02043 CharUnits offset) { 02044 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 02045 llvm::Constant *FirstField = 02046 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity()); 02047 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD, 02048 CharUnits::Zero()); 02049 } 02050 02051 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) { 02052 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero()); 02053 } 02054 02055 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP, 02056 QualType MPType) { 02057 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>(); 02058 const ValueDecl *MPD = MP.getMemberPointerDecl(); 02059 if (!MPD) 02060 return EmitNullMemberPointer(MPT); 02061 02062 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP); 02063 02064 // FIXME PR15713: Support virtual inheritance paths. 02065 02066 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) 02067 return BuildMemberPointer(MPT->getMostRecentCXXRecordDecl(), MD, 02068 ThisAdjustment); 02069 02070 CharUnits FieldOffset = 02071 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD)); 02072 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset); 02073 } 02074 02075 llvm::Constant * 02076 MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD, 02077 const CXXMethodDecl *MD, 02078 CharUnits NonVirtualBaseAdjustment) { 02079 assert(MD->isInstance() && "Member function must not be static!"); 02080 MD = MD->getCanonicalDecl(); 02081 RD = RD->getMostRecentDecl(); 02082 CodeGenTypes &Types = CGM.getTypes(); 02083 02084 llvm::Constant *FirstField; 02085 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 02086 if (!MD->isVirtual()) { 02087 llvm::Type *Ty; 02088 // Check whether the function has a computable LLVM signature. 02089 if (Types.isFuncTypeConvertible(FPT)) { 02090 // The function has a computable LLVM signature; use the correct type. 02091 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD)); 02092 } else { 02093 // Use an arbitrary non-function type to tell GetAddrOfFunction that the 02094 // function type is incomplete. 02095 Ty = CGM.PtrDiffTy; 02096 } 02097 FirstField = CGM.GetAddrOfFunction(MD, Ty); 02098 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy); 02099 } else { 02100 MicrosoftVTableContext::MethodVFTableLocation ML = 02101 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD); 02102 if (!CGM.getTypes().isFuncTypeConvertible( 02103 MD->getType()->castAs<FunctionType>())) { 02104 CGM.ErrorUnsupported(MD, "pointer to virtual member function with " 02105 "incomplete return or parameter type"); 02106 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy); 02107 } else if (FPT->getCallConv() == CC_X86FastCall) { 02108 CGM.ErrorUnsupported(MD, "pointer to fastcall virtual member function"); 02109 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy); 02110 } else if (ML.VBase) { 02111 CGM.ErrorUnsupported(MD, "pointer to virtual member function overriding " 02112 "member function in virtual base class"); 02113 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy); 02114 } else { 02115 llvm::Function *Thunk = EmitVirtualMemPtrThunk(MD, ML); 02116 FirstField = llvm::ConstantExpr::getBitCast(Thunk, CGM.VoidPtrTy); 02117 // Include the vfptr adjustment if the method is in a non-primary vftable. 02118 NonVirtualBaseAdjustment += ML.VFPtrOffset; 02119 } 02120 } 02121 02122 // The rest of the fields are common with data member pointers. 02123 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD, 02124 NonVirtualBaseAdjustment); 02125 } 02126 02127 /// Member pointers are the same if they're either bitwise identical *or* both 02128 /// null. Null-ness for function members is determined by the first field, 02129 /// while for data member pointers we must compare all fields. 02130 llvm::Value * 02131 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF, 02132 llvm::Value *L, 02133 llvm::Value *R, 02134 const MemberPointerType *MPT, 02135 bool Inequality) { 02136 CGBuilderTy &Builder = CGF.Builder; 02137 02138 // Handle != comparisons by switching the sense of all boolean operations. 02139 llvm::ICmpInst::Predicate Eq; 02140 llvm::Instruction::BinaryOps And, Or; 02141 if (Inequality) { 02142 Eq = llvm::ICmpInst::ICMP_NE; 02143 And = llvm::Instruction::Or; 02144 Or = llvm::Instruction::And; 02145 } else { 02146 Eq = llvm::ICmpInst::ICMP_EQ; 02147 And = llvm::Instruction::And; 02148 Or = llvm::Instruction::Or; 02149 } 02150 02151 // If this is a single field member pointer (single inheritance), this is a 02152 // single icmp. 02153 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 02154 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 02155 if (MSInheritanceAttr::hasOnlyOneField(MPT->isMemberFunctionPointer(), 02156 Inheritance)) 02157 return Builder.CreateICmp(Eq, L, R); 02158 02159 // Compare the first field. 02160 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0"); 02161 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0"); 02162 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first"); 02163 02164 // Compare everything other than the first field. 02165 llvm::Value *Res = nullptr; 02166 llvm::StructType *LType = cast<llvm::StructType>(L->getType()); 02167 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) { 02168 llvm::Value *LF = Builder.CreateExtractValue(L, I); 02169 llvm::Value *RF = Builder.CreateExtractValue(R, I); 02170 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest"); 02171 if (Res) 02172 Res = Builder.CreateBinOp(And, Res, Cmp); 02173 else 02174 Res = Cmp; 02175 } 02176 02177 // Check if the first field is 0 if this is a function pointer. 02178 if (MPT->isMemberFunctionPointer()) { 02179 // (l1 == r1 && ...) || l0 == 0 02180 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType()); 02181 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero"); 02182 Res = Builder.CreateBinOp(Or, Res, IsZero); 02183 } 02184 02185 // Combine the comparison of the first field, which must always be true for 02186 // this comparison to succeeed. 02187 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp"); 02188 } 02189 02190 llvm::Value * 02191 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 02192 llvm::Value *MemPtr, 02193 const MemberPointerType *MPT) { 02194 CGBuilderTy &Builder = CGF.Builder; 02195 llvm::SmallVector<llvm::Constant *, 4> fields; 02196 // We only need one field for member functions. 02197 if (MPT->isMemberFunctionPointer()) 02198 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy)); 02199 else 02200 GetNullMemberPointerFields(MPT, fields); 02201 assert(!fields.empty()); 02202 llvm::Value *FirstField = MemPtr; 02203 if (MemPtr->getType()->isStructTy()) 02204 FirstField = Builder.CreateExtractValue(MemPtr, 0); 02205 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0"); 02206 02207 // For function member pointers, we only need to test the function pointer 02208 // field. The other fields if any can be garbage. 02209 if (MPT->isMemberFunctionPointer()) 02210 return Res; 02211 02212 // Otherwise, emit a series of compares and combine the results. 02213 for (int I = 1, E = fields.size(); I < E; ++I) { 02214 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I); 02215 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp"); 02216 Res = Builder.CreateOr(Res, Next, "memptr.tobool"); 02217 } 02218 return Res; 02219 } 02220 02221 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT, 02222 llvm::Constant *Val) { 02223 // Function pointers are null if the pointer in the first field is null. 02224 if (MPT->isMemberFunctionPointer()) { 02225 llvm::Constant *FirstField = Val->getType()->isStructTy() ? 02226 Val->getAggregateElement(0U) : Val; 02227 return FirstField->isNullValue(); 02228 } 02229 02230 // If it's not a function pointer and it's zero initializable, we can easily 02231 // check zero. 02232 if (isZeroInitializable(MPT) && Val->isNullValue()) 02233 return true; 02234 02235 // Otherwise, break down all the fields for comparison. Hopefully these 02236 // little Constants are reused, while a big null struct might not be. 02237 llvm::SmallVector<llvm::Constant *, 4> Fields; 02238 GetNullMemberPointerFields(MPT, Fields); 02239 if (Fields.size() == 1) { 02240 assert(Val->getType()->isIntegerTy()); 02241 return Val == Fields[0]; 02242 } 02243 02244 unsigned I, E; 02245 for (I = 0, E = Fields.size(); I != E; ++I) { 02246 if (Val->getAggregateElement(I) != Fields[I]) 02247 break; 02248 } 02249 return I == E; 02250 } 02251 02252 llvm::Value * 02253 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF, 02254 llvm::Value *This, 02255 llvm::Value *VBPtrOffset, 02256 llvm::Value *VBTableOffset, 02257 llvm::Value **VBPtrOut) { 02258 CGBuilderTy &Builder = CGF.Builder; 02259 // Load the vbtable pointer from the vbptr in the instance. 02260 This = Builder.CreateBitCast(This, CGM.Int8PtrTy); 02261 llvm::Value *VBPtr = 02262 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr"); 02263 if (VBPtrOut) *VBPtrOut = VBPtr; 02264 VBPtr = Builder.CreateBitCast(VBPtr, 02265 CGM.Int32Ty->getPointerTo(0)->getPointerTo(0)); 02266 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable"); 02267 02268 // Translate from byte offset to table index. It improves analyzability. 02269 llvm::Value *VBTableIndex = Builder.CreateAShr( 02270 VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2), 02271 "vbtindex", /*isExact=*/true); 02272 02273 // Load an i32 offset from the vb-table. 02274 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableIndex); 02275 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0)); 02276 return Builder.CreateLoad(VBaseOffs, "vbase_offs"); 02277 } 02278 02279 // Returns an adjusted base cast to i8*, since we do more address arithmetic on 02280 // it. 02281 llvm::Value *MicrosoftCXXABI::AdjustVirtualBase( 02282 CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD, 02283 llvm::Value *Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) { 02284 CGBuilderTy &Builder = CGF.Builder; 02285 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy); 02286 llvm::BasicBlock *OriginalBB = nullptr; 02287 llvm::BasicBlock *SkipAdjustBB = nullptr; 02288 llvm::BasicBlock *VBaseAdjustBB = nullptr; 02289 02290 // In the unspecified inheritance model, there might not be a vbtable at all, 02291 // in which case we need to skip the virtual base lookup. If there is a 02292 // vbtable, the first entry is a no-op entry that gives back the original 02293 // base, so look for a virtual base adjustment offset of zero. 02294 if (VBPtrOffset) { 02295 OriginalBB = Builder.GetInsertBlock(); 02296 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust"); 02297 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust"); 02298 llvm::Value *IsVirtual = 02299 Builder.CreateICmpNE(VBTableOffset, getZeroInt(), 02300 "memptr.is_vbase"); 02301 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB); 02302 CGF.EmitBlock(VBaseAdjustBB); 02303 } 02304 02305 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll 02306 // know the vbptr offset. 02307 if (!VBPtrOffset) { 02308 CharUnits offs = CharUnits::Zero(); 02309 if (!RD->hasDefinition()) { 02310 DiagnosticsEngine &Diags = CGF.CGM.getDiags(); 02311 unsigned DiagID = Diags.getCustomDiagID( 02312 DiagnosticsEngine::Error, 02313 "member pointer representation requires a " 02314 "complete class type for %0 to perform this expression"); 02315 Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange(); 02316 } else if (RD->getNumVBases()) 02317 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset(); 02318 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity()); 02319 } 02320 llvm::Value *VBPtr = nullptr; 02321 llvm::Value *VBaseOffs = 02322 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr); 02323 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs); 02324 02325 // Merge control flow with the case where we didn't have to adjust. 02326 if (VBaseAdjustBB) { 02327 Builder.CreateBr(SkipAdjustBB); 02328 CGF.EmitBlock(SkipAdjustBB); 02329 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base"); 02330 Phi->addIncoming(Base, OriginalBB); 02331 Phi->addIncoming(AdjustedBase, VBaseAdjustBB); 02332 return Phi; 02333 } 02334 return AdjustedBase; 02335 } 02336 02337 llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress( 02338 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr, 02339 const MemberPointerType *MPT) { 02340 assert(MPT->isMemberDataPointer()); 02341 unsigned AS = Base->getType()->getPointerAddressSpace(); 02342 llvm::Type *PType = 02343 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS); 02344 CGBuilderTy &Builder = CGF.Builder; 02345 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 02346 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 02347 02348 // Extract the fields we need, regardless of model. We'll apply them if we 02349 // have them. 02350 llvm::Value *FieldOffset = MemPtr; 02351 llvm::Value *VirtualBaseAdjustmentOffset = nullptr; 02352 llvm::Value *VBPtrOffset = nullptr; 02353 if (MemPtr->getType()->isStructTy()) { 02354 // We need to extract values. 02355 unsigned I = 0; 02356 FieldOffset = Builder.CreateExtractValue(MemPtr, I++); 02357 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) 02358 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++); 02359 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 02360 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++); 02361 } 02362 02363 if (VirtualBaseAdjustmentOffset) { 02364 Base = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset, 02365 VBPtrOffset); 02366 } 02367 02368 // Cast to char*. 02369 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS)); 02370 02371 // Apply the offset, which we assume is non-null. 02372 llvm::Value *Addr = 02373 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset"); 02374 02375 // Cast the address to the appropriate pointer type, adopting the address 02376 // space of the base pointer. 02377 return Builder.CreateBitCast(Addr, PType); 02378 } 02379 02380 static MSInheritanceAttr::Spelling 02381 getInheritanceFromMemptr(const MemberPointerType *MPT) { 02382 return MPT->getMostRecentCXXRecordDecl()->getMSInheritanceModel(); 02383 } 02384 02385 llvm::Value * 02386 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF, 02387 const CastExpr *E, 02388 llvm::Value *Src) { 02389 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || 02390 E->getCastKind() == CK_BaseToDerivedMemberPointer || 02391 E->getCastKind() == CK_ReinterpretMemberPointer); 02392 02393 // Use constant emission if we can. 02394 if (isa<llvm::Constant>(Src)) 02395 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src)); 02396 02397 // We may be adding or dropping fields from the member pointer, so we need 02398 // both types and the inheritance models of both records. 02399 const MemberPointerType *SrcTy = 02400 E->getSubExpr()->getType()->castAs<MemberPointerType>(); 02401 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>(); 02402 bool IsFunc = SrcTy->isMemberFunctionPointer(); 02403 02404 // If the classes use the same null representation, reinterpret_cast is a nop. 02405 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer; 02406 if (IsReinterpret && IsFunc) 02407 return Src; 02408 02409 CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl(); 02410 CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl(); 02411 if (IsReinterpret && 02412 SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero()) 02413 return Src; 02414 02415 CGBuilderTy &Builder = CGF.Builder; 02416 02417 // Branch past the conversion if Src is null. 02418 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy); 02419 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy); 02420 02421 // C++ 5.2.10p9: The null member pointer value is converted to the null member 02422 // pointer value of the destination type. 02423 if (IsReinterpret) { 02424 // For reinterpret casts, sema ensures that src and dst are both functions 02425 // or data and have the same size, which means the LLVM types should match. 02426 assert(Src->getType() == DstNull->getType()); 02427 return Builder.CreateSelect(IsNotNull, Src, DstNull); 02428 } 02429 02430 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock(); 02431 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert"); 02432 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted"); 02433 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB); 02434 CGF.EmitBlock(ConvertBB); 02435 02436 // Decompose src. 02437 llvm::Value *FirstField = Src; 02438 llvm::Value *NonVirtualBaseAdjustment = nullptr; 02439 llvm::Value *VirtualBaseAdjustmentOffset = nullptr; 02440 llvm::Value *VBPtrOffset = nullptr; 02441 MSInheritanceAttr::Spelling SrcInheritance = SrcRD->getMSInheritanceModel(); 02442 if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) { 02443 // We need to extract values. 02444 unsigned I = 0; 02445 FirstField = Builder.CreateExtractValue(Src, I++); 02446 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance)) 02447 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++); 02448 if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance)) 02449 VBPtrOffset = Builder.CreateExtractValue(Src, I++); 02450 if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance)) 02451 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++); 02452 } 02453 02454 // For data pointers, we adjust the field offset directly. For functions, we 02455 // have a separate field. 02456 llvm::Constant *Adj = getMemberPointerAdjustment(E); 02457 if (Adj) { 02458 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy); 02459 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField; 02460 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); 02461 if (!NVAdjustField) // If this field didn't exist in src, it's zero. 02462 NVAdjustField = getZeroInt(); 02463 if (isDerivedToBase) 02464 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj"); 02465 else 02466 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj"); 02467 } 02468 02469 // FIXME PR15713: Support conversions through virtually derived classes. 02470 02471 // Recompose dst from the null struct and the adjusted fields from src. 02472 MSInheritanceAttr::Spelling DstInheritance = DstRD->getMSInheritanceModel(); 02473 llvm::Value *Dst; 02474 if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance)) { 02475 Dst = FirstField; 02476 } else { 02477 Dst = llvm::UndefValue::get(DstNull->getType()); 02478 unsigned Idx = 0; 02479 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++); 02480 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance)) 02481 Dst = Builder.CreateInsertValue( 02482 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++); 02483 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance)) 02484 Dst = Builder.CreateInsertValue( 02485 Dst, getValueOrZeroInt(VBPtrOffset), Idx++); 02486 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance)) 02487 Dst = Builder.CreateInsertValue( 02488 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++); 02489 } 02490 Builder.CreateBr(ContinueBB); 02491 02492 // In the continuation, choose between DstNull and Dst. 02493 CGF.EmitBlock(ContinueBB); 02494 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted"); 02495 Phi->addIncoming(DstNull, OriginalBB); 02496 Phi->addIncoming(Dst, ConvertBB); 02497 return Phi; 02498 } 02499 02500 llvm::Constant * 02501 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E, 02502 llvm::Constant *Src) { 02503 const MemberPointerType *SrcTy = 02504 E->getSubExpr()->getType()->castAs<MemberPointerType>(); 02505 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>(); 02506 02507 // If src is null, emit a new null for dst. We can't return src because dst 02508 // might have a new representation. 02509 if (MemberPointerConstantIsNull(SrcTy, Src)) 02510 return EmitNullMemberPointer(DstTy); 02511 02512 // We don't need to do anything for reinterpret_casts of non-null member 02513 // pointers. We should only get here when the two type representations have 02514 // the same size. 02515 if (E->getCastKind() == CK_ReinterpretMemberPointer) 02516 return Src; 02517 02518 MSInheritanceAttr::Spelling SrcInheritance = getInheritanceFromMemptr(SrcTy); 02519 MSInheritanceAttr::Spelling DstInheritance = getInheritanceFromMemptr(DstTy); 02520 02521 // Decompose src. 02522 llvm::Constant *FirstField = Src; 02523 llvm::Constant *NonVirtualBaseAdjustment = nullptr; 02524 llvm::Constant *VirtualBaseAdjustmentOffset = nullptr; 02525 llvm::Constant *VBPtrOffset = nullptr; 02526 bool IsFunc = SrcTy->isMemberFunctionPointer(); 02527 if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) { 02528 // We need to extract values. 02529 unsigned I = 0; 02530 FirstField = Src->getAggregateElement(I++); 02531 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance)) 02532 NonVirtualBaseAdjustment = Src->getAggregateElement(I++); 02533 if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance)) 02534 VBPtrOffset = Src->getAggregateElement(I++); 02535 if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance)) 02536 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++); 02537 } 02538 02539 // For data pointers, we adjust the field offset directly. For functions, we 02540 // have a separate field. 02541 llvm::Constant *Adj = getMemberPointerAdjustment(E); 02542 if (Adj) { 02543 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy); 02544 llvm::Constant *&NVAdjustField = 02545 IsFunc ? NonVirtualBaseAdjustment : FirstField; 02546 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); 02547 if (!NVAdjustField) // If this field didn't exist in src, it's zero. 02548 NVAdjustField = getZeroInt(); 02549 if (IsDerivedToBase) 02550 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj); 02551 else 02552 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj); 02553 } 02554 02555 // FIXME PR15713: Support conversions through virtually derived classes. 02556 02557 // Recompose dst from the null struct and the adjusted fields from src. 02558 if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance)) 02559 return FirstField; 02560 02561 llvm::SmallVector<llvm::Constant *, 4> Fields; 02562 Fields.push_back(FirstField); 02563 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance)) 02564 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment)); 02565 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance)) 02566 Fields.push_back(getConstantOrZeroInt(VBPtrOffset)); 02567 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance)) 02568 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset)); 02569 return llvm::ConstantStruct::getAnon(Fields); 02570 } 02571 02572 llvm::Value *MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer( 02573 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This, 02574 llvm::Value *MemPtr, const MemberPointerType *MPT) { 02575 assert(MPT->isMemberFunctionPointer()); 02576 const FunctionProtoType *FPT = 02577 MPT->getPointeeType()->castAs<FunctionProtoType>(); 02578 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 02579 llvm::FunctionType *FTy = 02580 CGM.getTypes().GetFunctionType( 02581 CGM.getTypes().arrangeCXXMethodType(RD, FPT)); 02582 CGBuilderTy &Builder = CGF.Builder; 02583 02584 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 02585 02586 // Extract the fields we need, regardless of model. We'll apply them if we 02587 // have them. 02588 llvm::Value *FunctionPointer = MemPtr; 02589 llvm::Value *NonVirtualBaseAdjustment = nullptr; 02590 llvm::Value *VirtualBaseAdjustmentOffset = nullptr; 02591 llvm::Value *VBPtrOffset = nullptr; 02592 if (MemPtr->getType()->isStructTy()) { 02593 // We need to extract values. 02594 unsigned I = 0; 02595 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++); 02596 if (MSInheritanceAttr::hasNVOffsetField(MPT, Inheritance)) 02597 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++); 02598 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) 02599 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++); 02600 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 02601 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++); 02602 } 02603 02604 if (VirtualBaseAdjustmentOffset) { 02605 This = AdjustVirtualBase(CGF, E, RD, This, VirtualBaseAdjustmentOffset, 02606 VBPtrOffset); 02607 } 02608 02609 if (NonVirtualBaseAdjustment) { 02610 // Apply the adjustment and cast back to the original struct type. 02611 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy()); 02612 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment); 02613 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted"); 02614 } 02615 02616 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo()); 02617 } 02618 02619 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) { 02620 return new MicrosoftCXXABI(CGM); 02621 } 02622 02623 // MS RTTI Overview: 02624 // The run time type information emitted by cl.exe contains 5 distinct types of 02625 // structures. Many of them reference each other. 02626 // 02627 // TypeInfo: Static classes that are returned by typeid. 02628 // 02629 // CompleteObjectLocator: Referenced by vftables. They contain information 02630 // required for dynamic casting, including OffsetFromTop. They also contain 02631 // a reference to the TypeInfo for the type and a reference to the 02632 // CompleteHierarchyDescriptor for the type. 02633 // 02634 // ClassHieararchyDescriptor: Contains information about a class hierarchy. 02635 // Used during dynamic_cast to walk a class hierarchy. References a base 02636 // class array and the size of said array. 02637 // 02638 // BaseClassArray: Contains a list of classes in a hierarchy. BaseClassArray is 02639 // somewhat of a misnomer because the most derived class is also in the list 02640 // as well as multiple copies of virtual bases (if they occur multiple times 02641 // in the hiearchy.) The BaseClassArray contains one BaseClassDescriptor for 02642 // every path in the hierarchy, in pre-order depth first order. Note, we do 02643 // not declare a specific llvm type for BaseClassArray, it's merely an array 02644 // of BaseClassDescriptor pointers. 02645 // 02646 // BaseClassDescriptor: Contains information about a class in a class hierarchy. 02647 // BaseClassDescriptor is also somewhat of a misnomer for the same reason that 02648 // BaseClassArray is. It contains information about a class within a 02649 // hierarchy such as: is this base is ambiguous and what is its offset in the 02650 // vbtable. The names of the BaseClassDescriptors have all of their fields 02651 // mangled into them so they can be aggressively deduplicated by the linker. 02652 02653 static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) { 02654 StringRef MangledName("\01??_7type_info@@6B@"); 02655 if (auto VTable = CGM.getModule().getNamedGlobal(MangledName)) 02656 return VTable; 02657 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy, 02658 /*Constant=*/true, 02659 llvm::GlobalVariable::ExternalLinkage, 02660 /*Initializer=*/nullptr, MangledName); 02661 } 02662 02663 namespace { 02664 02665 /// \brief A Helper struct that stores information about a class in a class 02666 /// hierarchy. The information stored in these structs struct is used during 02667 /// the generation of ClassHierarchyDescriptors and BaseClassDescriptors. 02668 // During RTTI creation, MSRTTIClasses are stored in a contiguous array with 02669 // implicit depth first pre-order tree connectivity. getFirstChild and 02670 // getNextSibling allow us to walk the tree efficiently. 02671 struct MSRTTIClass { 02672 enum { 02673 IsPrivateOnPath = 1 | 8, 02674 IsAmbiguous = 2, 02675 IsPrivate = 4, 02676 IsVirtual = 16, 02677 HasHierarchyDescriptor = 64 02678 }; 02679 MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {} 02680 uint32_t initialize(const MSRTTIClass *Parent, 02681 const CXXBaseSpecifier *Specifier); 02682 02683 MSRTTIClass *getFirstChild() { return this + 1; } 02684 static MSRTTIClass *getNextChild(MSRTTIClass *Child) { 02685 return Child + 1 + Child->NumBases; 02686 } 02687 02688 const CXXRecordDecl *RD, *VirtualRoot; 02689 uint32_t Flags, NumBases, OffsetInVBase; 02690 }; 02691 02692 /// \brief Recursively initialize the base class array. 02693 uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent, 02694 const CXXBaseSpecifier *Specifier) { 02695 Flags = HasHierarchyDescriptor; 02696 if (!Parent) { 02697 VirtualRoot = nullptr; 02698 OffsetInVBase = 0; 02699 } else { 02700 if (Specifier->getAccessSpecifier() != AS_public) 02701 Flags |= IsPrivate | IsPrivateOnPath; 02702 if (Specifier->isVirtual()) { 02703 Flags |= IsVirtual; 02704 VirtualRoot = RD; 02705 OffsetInVBase = 0; 02706 } else { 02707 if (Parent->Flags & IsPrivateOnPath) 02708 Flags |= IsPrivateOnPath; 02709 VirtualRoot = Parent->VirtualRoot; 02710 OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext() 02711 .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity(); 02712 } 02713 } 02714 NumBases = 0; 02715 MSRTTIClass *Child = getFirstChild(); 02716 for (const CXXBaseSpecifier &Base : RD->bases()) { 02717 NumBases += Child->initialize(this, &Base) + 1; 02718 Child = getNextChild(Child); 02719 } 02720 return NumBases; 02721 } 02722 02723 static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) { 02724 switch (Ty->getLinkage()) { 02725 case NoLinkage: 02726 case InternalLinkage: 02727 case UniqueExternalLinkage: 02728 return llvm::GlobalValue::InternalLinkage; 02729 02730 case VisibleNoLinkage: 02731 case ExternalLinkage: 02732 return llvm::GlobalValue::LinkOnceODRLinkage; 02733 } 02734 llvm_unreachable("Invalid linkage!"); 02735 } 02736 02737 /// \brief An ephemeral helper class for building MS RTTI types. It caches some 02738 /// calls to the module and information about the most derived class in a 02739 /// hierarchy. 02740 struct MSRTTIBuilder { 02741 enum { 02742 HasBranchingHierarchy = 1, 02743 HasVirtualBranchingHierarchy = 2, 02744 HasAmbiguousBases = 4 02745 }; 02746 02747 MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD) 02748 : CGM(ABI.CGM), Context(CGM.getContext()), 02749 VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD), 02750 Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))), 02751 ABI(ABI) {} 02752 02753 llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes); 02754 llvm::GlobalVariable * 02755 getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes); 02756 llvm::GlobalVariable *getClassHierarchyDescriptor(); 02757 llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo *Info); 02758 02759 CodeGenModule &CGM; 02760 ASTContext &Context; 02761 llvm::LLVMContext &VMContext; 02762 llvm::Module &Module; 02763 const CXXRecordDecl *RD; 02764 llvm::GlobalVariable::LinkageTypes Linkage; 02765 MicrosoftCXXABI &ABI; 02766 }; 02767 02768 } // namespace 02769 02770 /// \brief Recursively serializes a class hierarchy in pre-order depth first 02771 /// order. 02772 static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes, 02773 const CXXRecordDecl *RD) { 02774 Classes.push_back(MSRTTIClass(RD)); 02775 for (const CXXBaseSpecifier &Base : RD->bases()) 02776 serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl()); 02777 } 02778 02779 /// \brief Find ambiguity among base classes. 02780 static void 02781 detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) { 02782 llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases; 02783 llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases; 02784 llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases; 02785 for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) { 02786 if ((Class->Flags & MSRTTIClass::IsVirtual) && 02787 !VirtualBases.insert(Class->RD)) { 02788 Class = MSRTTIClass::getNextChild(Class); 02789 continue; 02790 } 02791 if (!UniqueBases.insert(Class->RD)) 02792 AmbiguousBases.insert(Class->RD); 02793 Class++; 02794 } 02795 if (AmbiguousBases.empty()) 02796 return; 02797 for (MSRTTIClass &Class : Classes) 02798 if (AmbiguousBases.count(Class.RD)) 02799 Class.Flags |= MSRTTIClass::IsAmbiguous; 02800 } 02801 02802 llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() { 02803 SmallString<256> MangledName; 02804 { 02805 llvm::raw_svector_ostream Out(MangledName); 02806 ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out); 02807 } 02808 02809 // Check to see if we've already declared this ClassHierarchyDescriptor. 02810 if (auto CHD = Module.getNamedGlobal(MangledName)) 02811 return CHD; 02812 02813 // Serialize the class hierarchy and initialize the CHD Fields. 02814 SmallVector<MSRTTIClass, 8> Classes; 02815 serializeClassHierarchy(Classes, RD); 02816 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr); 02817 detectAmbiguousBases(Classes); 02818 int Flags = 0; 02819 for (auto Class : Classes) { 02820 if (Class.RD->getNumBases() > 1) 02821 Flags |= HasBranchingHierarchy; 02822 // Note: cl.exe does not calculate "HasAmbiguousBases" correctly. We 02823 // believe the field isn't actually used. 02824 if (Class.Flags & MSRTTIClass::IsAmbiguous) 02825 Flags |= HasAmbiguousBases; 02826 } 02827 if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0) 02828 Flags |= HasVirtualBranchingHierarchy; 02829 // These gep indices are used to get the address of the first element of the 02830 // base class array. 02831 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0), 02832 llvm::ConstantInt::get(CGM.IntTy, 0)}; 02833 02834 // Forward-declare the class hierarchy descriptor 02835 auto Type = ABI.getClassHierarchyDescriptorType(); 02836 auto CHD = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage, 02837 /*Initializer=*/nullptr, 02838 MangledName.c_str()); 02839 02840 // Initialize the base class ClassHierarchyDescriptor. 02841 llvm::Constant *Fields[] = { 02842 llvm::ConstantInt::get(CGM.IntTy, 0), // Unknown 02843 llvm::ConstantInt::get(CGM.IntTy, Flags), 02844 llvm::ConstantInt::get(CGM.IntTy, Classes.size()), 02845 ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr( 02846 getBaseClassArray(Classes), 02847 llvm::ArrayRef<llvm::Value *>(GEPIndices))), 02848 }; 02849 CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields)); 02850 return CHD; 02851 } 02852 02853 llvm::GlobalVariable * 02854 MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) { 02855 SmallString<256> MangledName; 02856 { 02857 llvm::raw_svector_ostream Out(MangledName); 02858 ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out); 02859 } 02860 02861 // Forward-declare the base class array. 02862 // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit 02863 // mode) bytes of padding. We provide a pointer sized amount of padding by 02864 // adding +1 to Classes.size(). The sections have pointer alignment and are 02865 // marked pick-any so it shouldn't matter. 02866 llvm::Type *PtrType = ABI.getImageRelativeType( 02867 ABI.getBaseClassDescriptorType()->getPointerTo()); 02868 auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1); 02869 auto *BCA = new llvm::GlobalVariable( 02870 Module, ArrType, 02871 /*Constant=*/true, Linkage, /*Initializer=*/nullptr, MangledName.c_str()); 02872 02873 // Initialize the BaseClassArray. 02874 SmallVector<llvm::Constant *, 8> BaseClassArrayData; 02875 for (MSRTTIClass &Class : Classes) 02876 BaseClassArrayData.push_back( 02877 ABI.getImageRelativeConstant(getBaseClassDescriptor(Class))); 02878 BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType)); 02879 BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData)); 02880 return BCA; 02881 } 02882 02883 llvm::GlobalVariable * 02884 MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) { 02885 // Compute the fields for the BaseClassDescriptor. They are computed up front 02886 // because they are mangled into the name of the object. 02887 uint32_t OffsetInVBTable = 0; 02888 int32_t VBPtrOffset = -1; 02889 if (Class.VirtualRoot) { 02890 auto &VTableContext = CGM.getMicrosoftVTableContext(); 02891 OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4; 02892 VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity(); 02893 } 02894 02895 SmallString<256> MangledName; 02896 { 02897 llvm::raw_svector_ostream Out(MangledName); 02898 ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor( 02899 Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable, 02900 Class.Flags, Out); 02901 } 02902 02903 // Check to see if we've already declared this object. 02904 if (auto BCD = Module.getNamedGlobal(MangledName)) 02905 return BCD; 02906 02907 // Forward-declare the base class descriptor. 02908 auto Type = ABI.getBaseClassDescriptorType(); 02909 auto BCD = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage, 02910 /*Initializer=*/nullptr, 02911 MangledName.c_str()); 02912 02913 // Initialize the BaseClassDescriptor. 02914 llvm::Constant *Fields[] = { 02915 ABI.getImageRelativeConstant( 02916 ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))), 02917 llvm::ConstantInt::get(CGM.IntTy, Class.NumBases), 02918 llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase), 02919 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), 02920 llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable), 02921 llvm::ConstantInt::get(CGM.IntTy, Class.Flags), 02922 ABI.getImageRelativeConstant( 02923 MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()), 02924 }; 02925 BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields)); 02926 return BCD; 02927 } 02928 02929 llvm::GlobalVariable * 02930 MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo *Info) { 02931 SmallString<256> MangledName; 02932 { 02933 llvm::raw_svector_ostream Out(MangledName); 02934 ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info->MangledPath, Out); 02935 } 02936 02937 // Check to see if we've already computed this complete object locator. 02938 if (auto COL = Module.getNamedGlobal(MangledName)) 02939 return COL; 02940 02941 // Compute the fields of the complete object locator. 02942 int OffsetToTop = Info->FullOffsetInMDC.getQuantity(); 02943 int VFPtrOffset = 0; 02944 // The offset includes the vtordisp if one exists. 02945 if (const CXXRecordDecl *VBase = Info->getVBaseWithVPtr()) 02946 if (Context.getASTRecordLayout(RD) 02947 .getVBaseOffsetsMap() 02948 .find(VBase) 02949 ->second.hasVtorDisp()) 02950 VFPtrOffset = Info->NonVirtualOffset.getQuantity() + 4; 02951 02952 // Forward-declare the complete object locator. 02953 llvm::StructType *Type = ABI.getCompleteObjectLocatorType(); 02954 auto COL = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage, 02955 /*Initializer=*/nullptr, MangledName.c_str()); 02956 02957 // Initialize the CompleteObjectLocator. 02958 llvm::Constant *Fields[] = { 02959 llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()), 02960 llvm::ConstantInt::get(CGM.IntTy, OffsetToTop), 02961 llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset), 02962 ABI.getImageRelativeConstant( 02963 CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))), 02964 ABI.getImageRelativeConstant(getClassHierarchyDescriptor()), 02965 ABI.getImageRelativeConstant(COL), 02966 }; 02967 llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields); 02968 if (!ABI.isImageRelative()) 02969 FieldsRef = FieldsRef.drop_back(); 02970 COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef)); 02971 return COL; 02972 } 02973 02974 /// \brief Gets a TypeDescriptor. Returns a llvm::Constant * rather than a 02975 /// llvm::GlobalVariable * because different type descriptors have different 02976 /// types, and need to be abstracted. They are abstracting by casting the 02977 /// address to an Int8PtrTy. 02978 llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) { 02979 SmallString<256> MangledName, TypeInfoString; 02980 { 02981 llvm::raw_svector_ostream Out(MangledName); 02982 getMangleContext().mangleCXXRTTI(Type, Out); 02983 } 02984 02985 // Check to see if we've already declared this TypeDescriptor. 02986 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName)) 02987 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy); 02988 02989 // Compute the fields for the TypeDescriptor. 02990 { 02991 llvm::raw_svector_ostream Out(TypeInfoString); 02992 getMangleContext().mangleCXXRTTIName(Type, Out); 02993 } 02994 02995 // Declare and initialize the TypeDescriptor. 02996 llvm::Constant *Fields[] = { 02997 getTypeInfoVTable(CGM), // VFPtr 02998 llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data 02999 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)}; 03000 llvm::StructType *TypeDescriptorType = 03001 getTypeDescriptorType(TypeInfoString); 03002 return llvm::ConstantExpr::getBitCast( 03003 new llvm::GlobalVariable( 03004 CGM.getModule(), TypeDescriptorType, /*Constant=*/false, 03005 getLinkageForRTTI(Type), 03006 llvm::ConstantStruct::get(TypeDescriptorType, Fields), 03007 MangledName.c_str()), 03008 CGM.Int8PtrTy); 03009 } 03010 03011 /// \brief Gets or a creates a Microsoft CompleteObjectLocator. 03012 llvm::GlobalVariable * 03013 MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD, 03014 const VPtrInfo *Info) { 03015 return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info); 03016 } 03017 03018 static void emitCXXConstructor(CodeGenModule &CGM, 03019 const CXXConstructorDecl *ctor, 03020 StructorType ctorType) { 03021 // There are no constructor variants, always emit the complete destructor. 03022 CGM.codegenCXXStructor(ctor, StructorType::Complete); 03023 } 03024 03025 static void emitCXXDestructor(CodeGenModule &CGM, const CXXDestructorDecl *dtor, 03026 StructorType dtorType) { 03027 // The complete destructor is equivalent to the base destructor for 03028 // classes with no virtual bases, so try to emit it as an alias. 03029 if (!dtor->getParent()->getNumVBases() && 03030 (dtorType == StructorType::Complete || dtorType == StructorType::Base)) { 03031 bool ProducedAlias = !CGM.TryEmitDefinitionAsAlias( 03032 GlobalDecl(dtor, Dtor_Complete), GlobalDecl(dtor, Dtor_Base), true); 03033 if (ProducedAlias) { 03034 if (dtorType == StructorType::Complete) 03035 return; 03036 if (dtor->isVirtual()) 03037 CGM.getVTables().EmitThunks(GlobalDecl(dtor, Dtor_Complete)); 03038 } 03039 } 03040 03041 // The base destructor is equivalent to the base destructor of its 03042 // base class if there is exactly one non-virtual base class with a 03043 // non-trivial destructor, there are no fields with a non-trivial 03044 // destructor, and the body of the destructor is trivial. 03045 if (dtorType == StructorType::Base && !CGM.TryEmitBaseDestructorAsAlias(dtor)) 03046 return; 03047 03048 CGM.codegenCXXStructor(dtor, dtorType); 03049 } 03050 03051 void MicrosoftCXXABI::emitCXXStructor(const CXXMethodDecl *MD, 03052 StructorType Type) { 03053 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) { 03054 emitCXXConstructor(CGM, CD, Type); 03055 return; 03056 } 03057 emitCXXDestructor(CGM, cast<CXXDestructorDecl>(MD), Type); 03058 }